code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
/*
* You may not change or alter any portion of this comment or credits
* of supporting developers from this source code or any supporting source code
* which is considered copyrighted (c) material of the original comment or credit authors.
*
* 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.
*/
/**
* @copyright XOOPS Project https://xoops.org/
* @license GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
* @package
* @since
* @author XOOPS Development Team, Kazumi Ono (AKA onokazu)
*/
/**
* !
* Example
*
* require_once __DIR__ . '/uploader.php';
* $allowed_mimetypes = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/x-png');
* $maxfilesize = 50000;
* $maxfilewidth = 120;
* $maxfileheight = 120;
* $uploader = new \XoopsMediaUploader('/home/xoops/uploads', $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
* if ($uploader->fetchMedia($_POST['uploade_file_name'])) {
* if (!$uploader->upload()) {
* echo $uploader->getErrors();
* } else {
* echo '<h4>File uploaded successfully!</h4>'
* echo 'Saved as: ' . $uploader->getSavedFileName() . '<br>';
* echo 'Full path: ' . $uploader->getSavedDestination();
* }
* } else {
* echo $uploader->getErrors();
* }
*/
/**
* Upload Media files
*
* Example of usage:
* <code>
* require_once __DIR__ . '/uploader.php';
* $allowed_mimetypes = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/x-png');
* $maxfilesize = 50000;
* $maxfilewidth = 120;
* $maxfileheight = 120;
* $uploader = new \XoopsMediaUploader('/home/xoops/uploads', $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
* if ($uploader->fetchMedia($_POST['uploade_file_name'])) {
* if (!$uploader->upload()) {
* echo $uploader->getErrors();
* } else {
* echo '<h4>File uploaded successfully!</h4>'
* echo 'Saved as: ' . $uploader->getSavedFileName() . '<br>';
* echo 'Full path: ' . $uploader->getSavedDestination();
* }
* } else {
* echo $uploader->getErrors();
* }
* </code>
*
* @package kernel
* @subpackage core
* @author Kazumi Ono <onokazu@xoops.org>
* @copyright (c) 2000-2003 XOOPS Project (https://xoops.org)
*/
mt_srand((double)microtime() * 1000000);
/**
* Class XoopsMediaUploader
*/
class XoopsMediaUploader
{
public $mediaName;
public $mediaType;
public $mediaSize;
public $mediaTmpName;
public $mediaError;
public $uploadDir = '';
public $allowedMimeTypes = [];
public $maxFileSize = 0;
public $maxWidth;
public $maxHeight;
public $targetFileName;
public $prefix;
public $ext;
public $dimension;
public $errors = [];
public $savedDestination;
public $savedFileName;
/**
* No admin check for uploads
*/
public $noadmin_sizecheck;
/**
* Constructor
*
* @param string $uploadDir
* @param array|int $allowedMimeTypes
* @param int $maxFileSize
* @param int $maxWidth
* @param int $maxHeight
* @internal param int $cmodvalue
*/
public function __construct($uploadDir, $allowedMimeTypes = 0, $maxFileSize, $maxWidth = 0, $maxHeight = 0)
{
if (is_array($allowedMimeTypes)) {
$this->allowedMimeTypes =& $allowedMimeTypes;
}
$this->uploadDir = $uploadDir;
$this->maxFileSize = (int)$maxFileSize;
if (isset($maxWidth)) {
$this->maxWidth = (int)$maxWidth;
}
if (isset($maxHeight)) {
$this->maxHeight = (int)$maxHeight;
}
}
/**
* @param $value
*/
public function noAdminSizeCheck($value)
{
$this->noadmin_sizecheck = $value;
}
/**
* Fetch the uploaded file
*
* @param string $media_name Name of the file field
* @param int $index Index of the file (if more than one uploaded under that name)
* @global $HTTP_POST_FILES
* @return bool
*/
public function fetchMedia($media_name, $index = null)
{
global $_FILES;
if (!isset($_FILES[$media_name])) {
$this->setErrors('You either did not choose a file to upload or the server has insufficient read/writes to upload this file.!');
return false;
} elseif (is_array($_FILES[$media_name]['name']) && isset($index)) {
$index = (int)$index;
// $this->mediaName = get_magic_quotes_gpc() ? stripslashes($_FILES[$media_name]['name'][$index]): $_FILES[$media_name]['name'][$index];
$this->mediaName = $_FILES[$media_name]['name'][$index];
$this->mediaType = $_FILES[$media_name]['type'][$index];
$this->mediaSize = $_FILES[$media_name]['size'][$index];
$this->mediaTmpName = $_FILES[$media_name]['tmp_name'][$index];
$this->mediaError = !empty($_FILES[$media_name]['error'][$index]) ? $_FILES[$media_name]['errir'][$index] : 0;
} else {
$media_name = @$_FILES[$media_name];
// $this->mediaName = get_magic_quotes_gpc() ? stripslashes($media_name['name']): $media_name['name'];
$this->mediaName = $media_name['name'];
$this->mediaType = $media_name['type'];
$this->mediaSize = $media_name['size'];
$this->mediaTmpName = $media_name['tmp_name'];
$this->mediaError = !empty($media_name['error']) ? $media_name['error'] : 0;
}
$this->dimension = getimagesize($this->mediaTmpName);
$this->errors = [];
if ((int)$this->mediaSize < 0) {
$this->setErrors('Invalid File Size');
return false;
}
if ('' === $this->mediaName) {
$this->setErrors('Filename Is Empty');
return false;
}
if ('none' === $this->mediaTmpName) {
$this->setErrors('No file uploaded, this is a error');
return false;
}
if (!$this->checkMaxFileSize()) {
$this->setErrors(sprintf('File Size: %u. Maximum Size Allowed: %u', $this->mediaSize, $this->maxFileSize));
}
if (is_array($this->dimension)) {
if (!$this->checkMaxWidth($this->dimension[0])) {
$this->setErrors(sprintf('File width: %u. Maximum width allowed: %u', $this->dimension[0], $this->maxWidth));
}
if (!$this->checkMaxHeight($this->dimension[1])) {
$this->setErrors(sprintf('File height: %u. Maximum height allowed: %u', $this->dimension[1], $this->maxHeight));
}
}
if (count($this->errors) > 0) {
return false;
}
if (!$this->checkMimeType()) {
$this->setErrors('MIME type not allowed: ' . $this->mediaType);
}
if (!is_uploaded_file($this->mediaTmpName)) {
switch ($this->mediaError) {
case 0: // no error; possible file attack!
$this->setErrors('There was a problem with your upload. Error: 0');
break;
case 1: // uploaded file exceeds the upload_max_filesize directive in php.ini
//if ($this->noAdminSizeCheck)
//{
// return true;
//}
$this->setErrors('The file you are trying to upload is too big. Error: 1');
break;
case 2: // uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
$this->setErrors('The file you are trying to upload is too big. Error: 2');
break;
case 3: // uploaded file was only partially uploaded
$this->setErrors('The file you are trying upload was only partially uploaded. Error: 3');
break;
case 4: // no file was uploaded
$this->setErrors('No file selected for upload. Error: 4');
break;
default: // a default error, just in case! :)
$this->setErrors('No file selected for upload. Error: 5');
break;
}
return false;
}
return true;
}
/**
* Set the target filename
*
* @param string $value
*/
public function setTargetFileName($value)
{
$this->targetFileName = trim($value);
}
/**
* Set the prefix
*
* @param string $value
*/
public function setPrefix($value)
{
$this->prefix = trim($value);
}
/**
* Get the uploaded filename
*
* @return string
*/
public function getMediaName()
{
return $this->mediaName;
}
/**
* Get the type of the uploaded file
*
* @return string
*/
public function getMediaType()
{
return $this->mediaType;
}
/**
* Get the size of the uploaded file
*
* @return int
*/
public function getMediaSize()
{
return $this->mediaSize;
}
/**
* Get the temporary name that the uploaded file was stored under
*
* @return string
*/
public function getMediaTmpName()
{
return $this->mediaTmpName;
}
/**
* Get the saved filename
*
* @return string
*/
public function getSavedFileName()
{
return $this->savedFileName;
}
/**
* Get the destination the file is saved to
*
* @return string
*/
public function getSavedDestination()
{
return $this->savedDestination;
}
/**
* Check the file and copy it to the destination
*
* @param int $chmod
* @return bool
*/
public function upload($chmod = 0644)
{
if ('' == $this->uploadDir) {
$this->setErrors('Upload directory not set');
return false;
}
if (!is_dir($this->uploadDir)) {
$this->setErrors('Failed opening directory: ' . $this->uploadDir);
}
if (!is_writable($this->uploadDir)) {
$this->setErrors('Failed opening directory with write permission: ' . $this->uploadDir);
}
if (!$this->checkMaxFileSize()) {
$this->setErrors(sprintf('File Size: %u. Maximum Size Allowed: %u', $this->mediaSize, $this->maxFileSize));
}
if (is_array($this->dimension)) {
if (!$this->checkMaxWidth($this->dimension[0])) {
$this->setErrors(sprintf('File width: %u. Maximum width allowed: %u', $this->dimension[0], $this->maxWidth));
}
if (!$this->checkMaxHeight($this->dimension[1])) {
$this->setErrors(sprintf('File height: %u. Maximum height allowed: %u', $this->dimension[1], $this->maxHeight));
}
}
if (!$this->checkMimeType()) {
$this->setErrors('MIME type not allowed: ' . $this->mediaType);
}
if (!$this->_copyFile($chmod)) {
$this->setErrors('Failed uploading file: ' . $this->mediaName);
}
if (count($this->errors) > 0) {
return false;
}
return true;
}
/**
* Copy the file to its destination
*
* @param $chmod
* @return bool
*/
public function _copyFile($chmod)
{
$matched = [];
if (!preg_match("/\.([a-zA-Z0-9]+)$/", $this->mediaName, $matched)) {
return false;
}
if (isset($this->targetFileName)) {
$this->savedFileName = $this->targetFileName;
} elseif (isset($this->prefix)) {
$this->savedFileName = uniqid($this->prefix, true) . '.' . strtolower($matched[1]);
} else {
$this->savedFileName = strtolower($this->mediaName);
}
$this->savedFileName = preg_replace('!\s+!', '_', $this->savedFileName);
$this->savedDestination = $this->uploadDir . $this->savedFileName;
if (is_file($this->savedDestination) && !!is_dir($this->savedDestination)) {
$this->setErrors('File ' . $this->mediaName . ' already exists on the server. Please rename this file and try again.<br>');
return false;
}
if (!move_uploaded_file($this->mediaTmpName, $this->savedDestination)) {
return false;
}
@chmod($this->savedDestination, $chmod);
return true;
}
/**
* Is the file the right size?
*
* @return bool
*/
public function checkMaxFileSize()
{
if ($this->noadmin_sizecheck) {
return true;
}
if ($this->mediaSize > $this->maxFileSize) {
return false;
}
return true;
}
/**
* Is the picture the right width?
*
* @param $dimension
* @return bool
*/
public function checkMaxWidth($dimension)
{
if (!isset($this->maxWidth)) {
return true;
}
if ($dimension > $this->maxWidth) {
return false;
}
return true;
}
/**
* Is the picture the right height?
*
* @param $dimension
* @return bool
*/
public function checkMaxHeight($dimension)
{
if (!isset($this->maxHeight)) {
return true;
}
if ($dimension > $this->maxWidth) {
return false;
}
return true;
}
/**
* Is the file the right Mime type
*
* (is there a right type of mime? ;-)
*
* @return bool
*/
public function checkMimeType()
{
if (count($this->allowedMimeTypes) > 0 && !in_array($this->mediaType, $this->allowedMimeTypes)) {
return false;
} else {
return true;
}
}
/**
* Add an error
*
* @param string $error
*/
public function setErrors($error)
{
$this->errors[] = trim($error);
}
/**
* Get generated errors
*
* @param bool $ashtml Format using HTML?
* @return array |string Array of array messages OR HTML string
*/
public function &getErrors($ashtml = true)
{
if (!$ashtml) {
return $this->errors;
} else {
$ret = '';
if (count($this->errors) > 0) {
$ret = '<h4>Errors Returned While Uploading</h4>';
foreach ($this->errors as $error) {
$ret .= $error . '<br>';
}
}
return $ret;
}
}
}
| mambax7/257 | htdocs/modules/smartpartner/class/uploader.php | PHP | gpl-2.0 | 14,883 |
/**
* Attr: cmTooltip and cmTooltipContent
*/
myApp.directive('cmTooltip', function() {
return function (scope, iElement, iAttrs) {
console.log("appling cm tooltip");
var currentValue = "";
iAttrs.$observe('cmTooltipContent', function(value) {
if(value != currentValue && value != "") {
iElement.tooltip({
"animation": true,
"placement": "top",
"title": value
});
currentValue = value;
}
});
}
}); | Bio-LarK/skeletome-knowledge | sites/all/modules/custom/skeletome_angular/js/directives/cm_tooltip.js | JavaScript | gpl-2.0 | 573 |
// requestAnim shim layer by Paul Irish
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
// example code from mr doob : http://mrdoob.com/lab/javascript/requestanimationframe/
//var canvas = document.getElementById("myCanvas");
//var context = canvas.getContext("2d");
var canvas, context, toggle;
var y= 220;
var x= 284;
var y2=-10;
var x2= 10;
var y3=-10;
var x3= 400;
var mid = 128;
var dirX = 1;
var dirY = 1;
var destX ;
var destY ;
var i;
var state ;
var inbounds='true';
var status = -1; // -1: stopped , 0 In play
var imageObj = new Image();
var imageObj2 = new Image();
var imageObj3 = new Image();
var background_obj= new Image();
background_obj.src = "deep-space.jpg";
imageObj.src = "spshipsprite.png";
imageObj2.src = "spacestation.png";
imageObj3.src = "blueship4.png";
var jump = 'rest';
var backg_x = 0;
var backg_y = 0;
var floating =false;
var degrees = 0;
var str;
var name;
//init();
var dir = 1;
var monster = {};
var origin = {};
// Bullet image
var bulletReady = false;
var bulletImage = new Image();
bulletImage.onload = function () {
//bulletReady = true;
};
bulletImage.src = "images/bullet.png";
var bullet = {
speed: 256 // movement in pixels per second
};
//function init() {
canvas = document.createElement( 'canvas' );
canvas.width = 568;
canvas.height = 400;
context = canvas.getContext( '2d' );
//context.font = "40pt Calibri";
//context.fillStyle = "white";
// align text horizontally center
context.textAlign = "center";
// align text vertically center
context.textBaseline = "middle";
//context.font = "12pt Calibri";
//canvas.width = 8248;
context.drawImage(background_obj, backg_x, backg_y);
//imageData = context.getImageData(0,0,8248,400); //fnord
//var x = document;
// canvas.width = 568;
$( "#container" ).append( canvas );
//}
animate();
// shoot addition
var shoot = function(modifier){
if (dir==1){
bullet.y -= bullet.speed * modifier * 4;
}
if (dir==2){
bullet.y += bullet.speed * modifier * 4;
}
if (dir==3){
bullet.x -= bullet.speed * modifier * 4;
}
if (dir==4){
bullet.x += bullet.speed * modifier * 4;
}
// Are they touching2?
if (
bullet.x <= (monster.x + 32)
&& monster.x <= (bullet.x + 32)
&& hero.y <= (bullet.y + 32)
&& monster.y <= (bullet.y + 32)
) {
++monstersShot;
reset();
}
//distance = square root sqrt of ( (x2-x1)^2 + (y2-y1)^2)
var distance = Math.sqrt( Math.pow(bullet.x-origin.x, 2) + Math.pow(bullet.y - origin.y,2) );
if (distance > 200)
{
bulletReady = false;
first = true
}
}
if (bulletReady) {
context.drawImage(bulletImage, bullet.x, bullet.y);
}
// shoot addition
function shoot()
{
if (dir==1){
bullet.y -= bullet.speed * 4;
}
if (dir==2){
bullet.y += bullet.speed * 4;
}
if (dir==3){
bullet.x -= bullet.speed * 4;
}
if (dir==4){
bullet.x += bullet.speed * 4;
}
//distance = square root sqrt of ( (x2-x1)^2 + (y2-y1)^2)
var distance = Math.sqrt( Math.pow(bullet.x - x, 2) + Math.pow(bullet.y - y,2) );
if (distance > 200)
{
bulletReady = false;
first = true
}
}
function animate() {
update();
requestAnimFrame( animate );
shoot();
draw();
}
function update() {
y2++;
x2++;
y3++;
x3--;
if (y2==400)
{
y2=0;
}
if (x2==598)
{
x2=0;
}
if (y3==400)
{
y3=0;
}
if (x3==0)
{
x3=598;
}
}
function draw() {
context.fillText( state + ":" , canvas.width / 2 , canvas.height / 2 );
$(document).keyup(function(e)
{
if (e.keyCode == 37)
{
state= "stop";
dirX=1;
dir=3;
}
if (e.keyCode == 39)
{
state= "stop";
dirX=1;
dir=4;
}
if (e.keyCode == 38)
{
jump = 'descend';
}
});
$(document).keydown(function(e) {
//alert (e.keyCode);
//if space start/stop gameloop
//var time = new Date().getTime() * 0.002;
if(e.keyCode == 32)
{
status = 0 - status;
bulletReady = true;
bullet.x = x;
bullet.y = y;
}
// if (jump != 'descend')
// {
if (e.keyCode == 38 )
{
jump = 'ascend';
}
// }
if (e.keyCode == 40){
// down
}
if (e.keyCode == 37){
state = 'left';
}
if (e.keyCode == 39){
state = 'right';
}
});
///////////////////////////////////////////////////////////////////////////////
if (state == 'left')
{
//x = x-(1 * dirX);
// backg_x = backg_x + 1 ;
degrees = degrees - 1;
// context.setTransform(1,0.5,-0.5,10,10);
}
if (state == 'right')
{
//x = x + (1 * dirX);
// backg_x = backg_x - 1 ;
degrees = degrees +1 ;
// context.setTransform(1,0.5,-0.5,1,10,10);
}
if (jump == 'ascend')
{
}
if (jump == 'descend')
{
y = y - 1;
if (y == 0)
{
jump = 'rest';
}
}
if (jump == 'rest')
{
y = 0;
dirY = -1;
}
if (inbounds=='true')
{
// destX = (canvas.width / 2 ) + x;
// destY = canvas.height - 30 - y ;// 60 pixels offset from centre
}//end if inbounds
if (destX > canvas.width || destX < 0)
{
// dirX =-dirX;
}
if (destY > canvas.width || destY < 0)
{
// dirY =-dirY;
}
//canvas.width = 8248;
context.clearRect(0,0 , canvas.width, canvas.height);
context.drawImage(background_obj, backg_x, backg_y);
context.save();
context.beginPath();
context.translate( 290,210 );
// rotate the rect
context.rotate(degrees*Math.PI/180);
context.drawImage(imageObj, -37, -50);
context.restore();
context.drawImage(imageObj2, x2, y2);
context.drawImage(imageObj3, x3, y3);
str = "width=" + imageData.width + " height=" + imageData.height
+ " red :" + red + " green :" + green + " blue :" + blue
+ " destX :" + parseInt(0-backg_x) + " destY :" +destY
+ " inbounds:" + inbounds
+ " float: " + floating + " jump : " + jump;
context.fillText(str, 20, 14);
str2 = "x: " + x + "y :" + y;
context.fillText(str2, 20, 34);
context.fillStyle = 'white';
}
| Techbot/Techbot.github.io | template013/script.js | JavaScript | gpl-2.0 | 6,656 |
/*
* Copyright 1999-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.management;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
/**
* <p>Provides general information for an MBean descriptor object.
* The feature described can be an attribute, an operation, a
* parameter, or a notification. Instances of this class are
* immutable. Subclasses may be mutable but this is not
* recommended.</p>
*
* @since 1.5
*/
public class MBeanFeatureInfo implements Serializable, DescriptorRead {
/* Serial version */
static final long serialVersionUID = 3952882688968447265L;
/**
* The name of the feature. It is recommended that subclasses call
* {@link #getName} rather than reading this field, and that they
* not change it.
*
* @serial The name of the feature.
*/
protected String name;
/**
* The human-readable description of the feature. It is
* recommended that subclasses call {@link #getDescription} rather
* than reading this field, and that they not change it.
*
* @serial The human-readable description of the feature.
*/
protected String description;
/**
* @serial The Descriptor for this MBeanFeatureInfo. This field
* can be null, which is equivalent to an empty Descriptor.
*/
private transient Descriptor descriptor;
/**
* Constructs an <CODE>MBeanFeatureInfo</CODE> object. This
* constructor is equivalent to {@code MBeanFeatureInfo(name,
* description, (Descriptor) null}.
*
* @param name The name of the feature.
* @param description A human readable description of the feature.
*/
public MBeanFeatureInfo(String name, String description) {
this(name, description, null);
}
/**
* Constructs an <CODE>MBeanFeatureInfo</CODE> object.
*
* @param name The name of the feature.
* @param description A human readable description of the feature.
* @param descriptor The descriptor for the feature. This may be null
* which is equivalent to an empty descriptor.
*
* @since 1.6
*/
public MBeanFeatureInfo(String name, String description,
Descriptor descriptor) {
this.name = name;
this.description = description;
this.descriptor = descriptor;
}
/**
* Returns the name of the feature.
*
* @return the name of the feature.
*/
public String getName() {
return name;
}
/**
* Returns the human-readable description of the feature.
*
* @return the human-readable description of the feature.
*/
public String getDescription() {
return description;
}
/**
* Returns the descriptor for the feature. Changing the returned value
* will have no affect on the original descriptor.
*
* @return a descriptor that is either immutable or a copy of the original.
*
* @since 1.6
*/
public Descriptor getDescriptor() {
return (Descriptor) ImmutableDescriptor.nonNullDescriptor(descriptor).clone();
}
/**
* Compare this MBeanFeatureInfo to another.
*
* @param o the object to compare to.
*
* @return true if and only if <code>o</code> is an MBeanFeatureInfo such
* that its {@link #getName()}, {@link #getDescription()}, and
* {@link #getDescriptor()}
* values are equal (not necessarily identical) to those of this
* MBeanFeatureInfo.
*/
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof MBeanFeatureInfo))
return false;
MBeanFeatureInfo p = (MBeanFeatureInfo) o;
return (p.getName().equals(getName()) &&
p.getDescription().equals(getDescription()) &&
p.getDescriptor().equals(getDescriptor()));
}
public int hashCode() {
return getName().hashCode() ^ getDescription().hashCode() ^
getDescriptor().hashCode();
}
/**
* Serializes an {@link MBeanFeatureInfo} to an {@link ObjectOutputStream}.
* @serialData
* For compatibility reasons, an object of this class is serialized as follows.
* <ul>
* The method {@link ObjectOutputStream#defaultWriteObject defaultWriteObject()}
* is called first to serialize the object except the field {@code descriptor}
* which is declared as transient. The field {@code descriptor} is serialized
* as follows:
* <ul>
* <li>If {@code descriptor} is an instance of the class
* {@link ImmutableDescriptor}, the method {@link ObjectOutputStream#write
* write(int val)} is called to write a byte with the value {@code 1},
* then the method {@link ObjectOutputStream#writeObject writeObject(Object obj)}
* is called twice to serialize the field names and the field values of the
* {@code descriptor}, respectively as a {@code String[]} and an
* {@code Object[]};</li>
* <li>Otherwise, the method {@link ObjectOutputStream#write write(int val)}
* is called to write a byte with the value {@code 0}, then the method
* {@link ObjectOutputStream#writeObject writeObject(Object obj)} is called
* to serialize directly the field {@code descriptor}.
* </ul>
* </ul>
* @since 1.6
*/
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (descriptor != null &&
descriptor.getClass() == ImmutableDescriptor.class) {
out.write(1);
final String[] names = descriptor.getFieldNames();
out.writeObject(names);
out.writeObject(descriptor.getFieldValues(names));
} else {
out.write(0);
out.writeObject(descriptor);
}
}
/**
* Deserializes an {@link MBeanFeatureInfo} from an {@link ObjectInputStream}.
* @serialData
* For compatibility reasons, an object of this class is deserialized as follows.
* <ul>
* The method {@link ObjectInputStream#defaultReadObject defaultReadObject()}
* is called first to deserialize the object except the field
* {@code descriptor}, which is not serialized in the default way. Then the method
* {@link ObjectInputStream#read read()} is called to read a byte, the field
* {@code descriptor} is deserialized according to the value of the byte value:
* <ul>
* <li>1. The method {@link ObjectInputStream#readObject readObject()}
* is called twice to obtain the field names (a {@code String[]}) and
* the field values (a {@code Object[]}) of the {@code descriptor}.
* The two obtained values then are used to construct
* an {@link ImmutableDescriptor} instance for the field
* {@code descriptor};</li>
* <li>0. The value for the field {@code descriptor} is obtained directly
* by calling the method {@link ObjectInputStream#readObject readObject()}.
* If the obtained value is null, the field {@code descriptor} is set to
* {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR};</li>
* <li>-1. This means that there is no byte to read and that the object is from
* an earlier version of the JMX API. The field {@code descriptor} is set
* to {@link ImmutableDescriptor#EMPTY_DESCRIPTOR EMPTY_DESCRIPTOR}</li>
* <li>Any other value. A {@link StreamCorruptedException} is thrown.</li>
* </ul>
* </ul>
* @since 1.6
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
switch (in.read()) {
case 1:
final String[] names = (String[])in.readObject();
if (names.length == 0) {
descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;
} else {
final Object[] values = (Object[])in.readObject();
descriptor = new ImmutableDescriptor(names, values);
}
break;
case 0:
descriptor = (Descriptor)in.readObject();
if (descriptor == null) {
descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;
}
break;
case -1: // from an earlier version of the JMX API
descriptor = ImmutableDescriptor.EMPTY_DESCRIPTOR;
break;
default:
throw new StreamCorruptedException("Got unexpected byte.");
}
}
}
| TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/javax/management/MBeanFeatureInfo.java | Java | gpl-2.0 | 9,932 |
/*
* Copyright (C) 2010-2011 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Common.h"
#include "Player.h"
#include "GridNotifiers.h"
#include "Log.h"
#include "GridStates.h"
#include "CellImpl.h"
#include "Map.h"
#include "MapManager.h"
#include "MapInstanced.h"
#include "InstanceSaveMgr.h"
#include "Timer.h"
#include "GridNotifiersImpl.h"
#include "Config.h"
#include "Transport.h"
#include "ObjectMgr.h"
#include "World.h"
#include "Group.h"
#include "InstanceScript.h"
uint16 InstanceSaveManager::ResetTimeDelay[] = {3600, 900, 300, 60};
InstanceSaveManager::~InstanceSaveManager()
{
// it is undefined whether this or objectmgr will be unloaded first
// so we must be prepared for both cases
lock_instLists = true;
for (InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr)
{
InstanceSave* save = itr->second;
for (InstanceSave::PlayerListType::iterator itr2 = save->m_playerList.begin(), next = itr2; itr2 != save->m_playerList.end(); itr2 = next)
{
++next;
(*itr2)->UnbindInstance(save->GetMapId(), save->GetDifficulty(), true);
}
save->m_playerList.clear();
for (InstanceSave::GroupListType::iterator itr2 = save->m_groupList.begin(), next = itr2; itr2 != save->m_groupList.end(); itr2 = next)
{
++next;
(*itr2)->UnbindInstance(save->GetMapId(), save->GetDifficulty(), true);
}
save->m_groupList.clear();
delete save;
}
}
/*
- adding instance into manager
- called from InstanceMap::Add, _LoadBoundInstances, LoadGroups
*/
InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instanceId, Difficulty difficulty, time_t resetTime, bool canReset, bool load)
{
if (InstanceSave* old_save = GetInstanceSave(instanceId))
return old_save;
const MapEntry* entry = sMapStore.LookupEntry(mapId);
if (!entry)
{
sLog->outError("InstanceSaveManager::AddInstanceSave: wrong mapid = %d, instanceid = %d!", mapId, instanceId);
return NULL;
}
if (instanceId == 0)
{
sLog->outError("InstanceSaveManager::AddInstanceSave: mapid = %d, wrong instanceid = %d!", mapId, instanceId);
return NULL;
}
if (difficulty >= (entry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY))
{
sLog->outError("InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d, wrong dificalty %u!", mapId, instanceId, difficulty);
return NULL;
}
if (!resetTime)
{
// initialize reset time
// for normal instances if no creatures are killed the instance will reset in two hours
if (entry->map_type == MAP_RAID || difficulty > DUNGEON_DIFFICULTY_NORMAL)
resetTime = GetResetTimeFor(mapId, difficulty);
else
{
resetTime = time(NULL) + 2 * HOUR;
// normally this will be removed soon after in InstanceMap::Add, prevent error
ScheduleReset(true, resetTime, InstResetEvent(0, mapId, difficulty, instanceId));
}
}
sLog->outDebug(LOG_FILTER_MAPS, "InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d", mapId, instanceId);
InstanceSave* save = new InstanceSave(mapId, instanceId, difficulty, resetTime, canReset);
if (!load)
save->SaveToDB();
m_instanceSaveById[instanceId] = save;
return save;
}
InstanceSave* InstanceSaveManager::GetInstanceSave(uint32 InstanceId)
{
InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(InstanceId);
return itr != m_instanceSaveById.end() ? itr->second : NULL;
}
void InstanceSaveManager::DeleteInstanceFromDB(uint32 instanceid)
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
trans->PAppend("DELETE FROM instance WHERE id = '%u'", instanceid);
trans->PAppend("DELETE FROM character_instance WHERE instance = '%u'", instanceid);
trans->PAppend("DELETE FROM group_instance WHERE instance = '%u'", instanceid);
CharacterDatabase.CommitTransaction(trans);
// respawn times should be deleted only when the map gets unloaded
// Delete completed encounters cache when deleting instance from db
sInstanceSaveMgr->DeleteCompletedEncounters(instanceid);
}
void InstanceSaveManager::RemoveInstanceSave(uint32 InstanceId)
{
InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(InstanceId);
if (itr != m_instanceSaveById.end())
{
// save the resettime for normal instances only when they get unloaded
if (time_t resettime = itr->second->GetResetTimeForDB())
CharacterDatabase.PExecute("UPDATE instance SET resettime = '"UI64FMTD"' WHERE id = '%u'", (uint64)resettime, InstanceId);
delete itr->second;
m_instanceSaveById.erase(itr);
}
}
InstanceSave::InstanceSave(uint16 MapId, uint32 InstanceId, Difficulty difficulty, time_t resetTime, bool canReset)
: m_resetTime(resetTime), m_instanceid(InstanceId), m_mapid(MapId),
m_difficulty(difficulty), m_canReset(canReset)
{
}
InstanceSave::~InstanceSave()
{
// the players and groups must be unbound before deleting the save
ASSERT(m_playerList.empty() && m_groupList.empty());
}
/*
Called from AddInstanceSave
*/
void InstanceSave::SaveToDB()
{
// save instance data too
std::string data;
uint32 completedEncounters = 0;
Map* map = sMapMgr->FindMap(GetMapId(), m_instanceid);
if (map)
{
ASSERT(map->IsDungeon());
if (InstanceScript* instanceScript = ((InstanceMap*)map)->GetInstanceScript())
{
data = instanceScript->GetSaveData();
completedEncounters = instanceScript->GetCompletedEncounterMask();
}
}
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_INSTANCE_SAVE);
stmt->setUInt32(0, m_instanceid);
stmt->setUInt16(1, GetMapId());
stmt->setUInt32(2, uint32(GetResetTimeForDB()));
stmt->setUInt8(3, uint8(GetDifficulty()));
stmt->setUInt32(4, completedEncounters);
stmt->setString(5, data);
CharacterDatabase.Execute(stmt);
// Update completed encounters cache when adding InstanceSave
sInstanceSaveMgr->SetCompletedEncounters(m_instanceid, GetMapId(), GetDifficulty(), completedEncounters);
}
time_t InstanceSave::GetResetTimeForDB()
{
// only save the reset time for normal instances
const MapEntry* entry = sMapStore.LookupEntry(GetMapId());
if (!entry || entry->map_type == MAP_RAID || GetDifficulty() == DUNGEON_DIFFICULTY_HEROIC)
return 0;
else
return GetResetTime();
}
// to cache or not to cache, that is the question
InstanceTemplate const* InstanceSave::GetTemplate()
{
return sObjectMgr->GetInstanceTemplate(m_mapid);
}
MapEntry const* InstanceSave::GetMapEntry()
{
return sMapStore.LookupEntry(m_mapid);
}
void InstanceSave::DeleteFromDB()
{
InstanceSaveManager::DeleteInstanceFromDB(GetInstanceId());
}
/* true if the instance save is still valid */
bool InstanceSave::UnloadIfEmpty()
{
if (m_playerList.empty() && m_groupList.empty())
{
if (!sInstanceSaveMgr->lock_instLists)
sInstanceSaveMgr->RemoveInstanceSave(GetInstanceId());
return false;
}
else
return true;
}
void InstanceSaveManager::LoadInstances()
{
uint32 oldMSTime = getMSTime();
// Delete expired instances (Instance related spawns are removed in the following cleanup queries)
CharacterDatabase.DirectExecute("DELETE i FROM instance i LEFT JOIN instance_reset ir ON mapid = map AND i.difficulty = ir.difficulty "
"WHERE (i.resettime > 0 AND i.resettime < UNIX_TIMESTAMP()) OR (ir.resettime IS NOT NULL AND ir.resettime < UNIX_TIMESTAMP())");
// Delete invalid character_instance and group_instance references
CharacterDatabase.DirectExecute("DELETE ci.* FROM character_instance AS ci LEFT JOIN characters AS c ON ci.guid = c.guid WHERE c.guid IS NULL");
CharacterDatabase.DirectExecute("DELETE gi.* FROM group_instance AS gi LEFT JOIN groups AS g ON gi.guid = g.guid WHERE g.guid IS NULL");
// Delete invalid instance references
CharacterDatabase.DirectExecute("DELETE i.* FROM instance AS i LEFT JOIN character_instance AS ci ON i.id = ci.instance LEFT JOIN group_instance AS gi ON i.id = gi.instance WHERE ci.guid IS NULL AND gi.guid IS NULL");
// Delete invalid references to instance
CharacterDatabase.DirectExecute(CharacterDatabase.GetPreparedStatement(CHAR_DEL_NONEXISTENT_INSTANCE_CREATURE_RESPAWNS));
CharacterDatabase.DirectExecute(CharacterDatabase.GetPreparedStatement(CHAR_DEL_NONEXISTENT_INSTANCE_GO_RESPAWNS));
CharacterDatabase.DirectExecute("DELETE tmp.* FROM character_instance AS tmp LEFT JOIN instance ON tmp.instance = instance.id WHERE tmp.instance > 0 AND instance.id IS NULL");
CharacterDatabase.DirectExecute("DELETE tmp.* FROM group_instance AS tmp LEFT JOIN instance ON tmp.instance = instance.id WHERE tmp.instance > 0 AND instance.id IS NULL");
// Clean invalid references to instance
CharacterDatabase.DirectExecute(CharacterDatabase.GetPreparedStatement(CHAR_RESET_NONEXISTENT_INSTANCE_FOR_CORPSES));
CharacterDatabase.DirectExecute("UPDATE characters AS tmp LEFT JOIN instance ON tmp.instance_id = instance.id SET tmp.instance_id = 0 WHERE tmp.instance_id > 0 AND instance.id IS NULL");
// Initialize instance id storage (Needs to be done after the trash has been clean out)
sMapMgr->InitInstanceIds();
// Load reset times and clean expired instances
sInstanceSaveMgr->LoadResetTimes();
sLog->outString(">> Loaded instances in %u ms", GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
oldMSTime = getMSTime();
sInstanceSaveMgr->LoadCompletedEncounters();
sLog->outString(">> Loaded instance completed encounters in %u ms", GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void InstanceSaveManager::LoadResetTimes()
{
time_t now = time(NULL);
time_t today = (now / DAY) * DAY;
// NOTE: Use DirectPExecute for tables that will be queried later
// get the current reset times for normal instances (these may need to be updated)
// these are only kept in memory for InstanceSaves that are loaded later
// resettime = 0 in the DB for raid/heroic instances so those are skipped
typedef std::pair<uint32 /*PAIR32(map, difficulty)*/, time_t> ResetTimeMapDiffType;
typedef std::map<uint32, ResetTimeMapDiffType> InstResetTimeMapDiffType;
InstResetTimeMapDiffType instResetTime;
// index instance ids by map/difficulty pairs for fast reset warning send
typedef std::multimap<uint32 /*PAIR32(map, difficulty)*/, uint32 /*instanceid*/ > ResetTimeMapDiffInstances;
ResetTimeMapDiffInstances mapDiffResetInstances;
QueryResult result = CharacterDatabase.Query("SELECT id, map, difficulty, resettime FROM instance ORDER BY id ASC");
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 instanceId = fields[0].GetUInt32();
// Instances are pulled in ascending order from db and nextInstanceId is initialized with 1,
// so if the instance id is used, increment until we find the first unused one for a potential new instance
if (sMapMgr->GetNextInstanceId() == instanceId)
sMapMgr->SetNextInstanceId(instanceId + 1);
// Mark instance id as being used
sMapMgr->RegisterInstanceId(instanceId);
if (time_t resettime = time_t(fields[3].GetUInt32()))
{
uint32 mapid = fields[1].GetUInt16();
uint32 difficulty = fields[2].GetUInt8();
instResetTime[instanceId] = ResetTimeMapDiffType(MAKE_PAIR32(mapid, difficulty), resettime);
mapDiffResetInstances.insert(ResetTimeMapDiffInstances::value_type(MAKE_PAIR32(mapid, difficulty), instanceId));
}
}
while (result->NextRow());
// update reset time for normal instances with the max creature respawn time + X hours
if (PreparedQueryResult result2 = CharacterDatabase.Query(CharacterDatabase.GetPreparedStatement(CHAR_GET_MAX_CREATURE_RESPAWNS)))
{
do
{
Field* fields = result2->Fetch();
uint32 instance = fields[1].GetUInt32();
time_t resettime = time_t(fields[0].GetUInt32() + 2 * HOUR);
InstResetTimeMapDiffType::iterator itr = instResetTime.find(instance);
if (itr != instResetTime.end() && itr->second.second != resettime)
{
CharacterDatabase.DirectPExecute("UPDATE instance SET resettime = '"UI64FMTD"' WHERE id = '%u'", uint64(resettime), instance);
itr->second.second = resettime;
}
}
while (result->NextRow());
}
// schedule the reset times
for (InstResetTimeMapDiffType::iterator itr = instResetTime.begin(); itr != instResetTime.end(); ++itr)
if (itr->second.second > now)
ScheduleReset(true, itr->second.second, InstResetEvent(0, PAIR32_LOPART(itr->second.first), Difficulty(PAIR32_HIPART(itr->second.first)), itr->first));
}
// load the global respawn times for raid/heroic instances
uint32 diff = sWorld->getIntConfig(CONFIG_INSTANCE_RESET_TIME_HOUR) * HOUR;
result = CharacterDatabase.Query("SELECT mapid, difficulty, resettime FROM instance_reset");
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 mapid = fields[0].GetUInt16();
Difficulty difficulty = Difficulty(fields[1].GetUInt32());
uint64 oldresettime = fields[2].GetUInt32();
MapDifficulty const* mapDiff = GetMapDifficultyData(mapid, difficulty);
if (!mapDiff)
{
sLog->outError("InstanceSaveManager::LoadResetTimes: invalid mapid(%u)/difficulty(%u) pair in instance_reset!", mapid, difficulty);
CharacterDatabase.DirectPExecute("DELETE FROM instance_reset WHERE mapid = '%u' AND difficulty = '%u'", mapid, difficulty);
continue;
}
// update the reset time if the hour in the configs changes
uint64 newresettime = (oldresettime / DAY) * DAY + diff;
if (oldresettime != newresettime)
CharacterDatabase.DirectPExecute("UPDATE instance_reset SET resettime = '%u' WHERE mapid = '%u' AND difficulty = '%u'", uint32(newresettime), mapid, difficulty);
SetResetTimeFor(mapid, difficulty, newresettime);
} while (result->NextRow());
}
ResetTimeMapDiffInstances::const_iterator in_itr;
// calculate new global reset times for expired instances and those that have never been reset yet
// add the global reset times to the priority queue
for (MapDifficultyMap::const_iterator itr = sMapDifficultyMap.begin(); itr != sMapDifficultyMap.end(); ++itr)
{
uint32 map_diff_pair = itr->first;
uint32 mapid = PAIR32_LOPART(map_diff_pair);
Difficulty difficulty = Difficulty(PAIR32_HIPART(map_diff_pair));
MapDifficulty const* mapDiff = &itr->second;
if (!mapDiff->resetTime)
continue;
// the reset_delay must be at least one day
uint32 period = uint32(((mapDiff->resetTime * sWorld->getRate(RATE_INSTANCE_RESET_TIME))/DAY) * DAY);
if (period < DAY)
period = DAY;
time_t t = GetResetTimeFor(mapid, difficulty);
if (!t)
{
// initialize the reset time
t = today + period + diff;
CharacterDatabase.DirectPExecute("INSERT INTO instance_reset VALUES ('%u', '%u', '%u')", mapid, difficulty, (uint32)t);
}
if (t < now)
{
// assume that expired instances have already been cleaned
// calculate the next reset time
t = (t / DAY) * DAY;
t += ((today - t) / period + 1) * period + diff;
CharacterDatabase.DirectPExecute("UPDATE instance_reset SET resettime = '"UI64FMTD"' WHERE mapid = '%u' AND difficulty= '%u'", (uint64)t, mapid, difficulty);
}
SetResetTimeFor(mapid, difficulty, t);
// schedule the global reset/warning
uint8 type;
for (type = 1; type < 4; ++type)
if (t - ResetTimeDelay[type-1] > now)
break;
ScheduleReset(true, t - ResetTimeDelay[type-1], InstResetEvent(type, mapid, difficulty, 0));
for (in_itr = mapDiffResetInstances.lower_bound(map_diff_pair); in_itr != mapDiffResetInstances.upper_bound(map_diff_pair); ++in_itr)
ScheduleReset(true, t - ResetTimeDelay[type-1], InstResetEvent(type, mapid, difficulty, in_itr->second));
}
}
// TODO: this function should be merged into LoadResetTimes and rename to LoadInstances
void InstanceSaveManager::LoadCompletedEncounters()
{
m_completedEncounters.clear();
QueryResult result = CharacterDatabase.Query("SELECT id, map, difficulty, completedEncounters FROM instance");
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 instanceId = fields[0].GetUInt32();
uint32 mapid = fields[1].GetUInt16();
uint32 difficulty = fields[2].GetUInt8();
uint32 completedEncounters = fields[3].GetUInt32();
InstanceEncounter encounter(mapid, Difficulty(difficulty), completedEncounters);
m_completedEncounters.insert(InstanceCompletedEncounters::value_type(instanceId, encounter));
}
while (result->NextRow());
}
}
void InstanceSaveManager::ScheduleReset(bool add, time_t time, InstResetEvent event)
{
if (!add)
{
// find the event in the queue and remove it
ResetTimeQueue::iterator itr;
std::pair<ResetTimeQueue::iterator, ResetTimeQueue::iterator> range;
range = m_resetTimeQueue.equal_range(time);
for (itr = range.first; itr != range.second; ++itr)
{
if (itr->second == event)
{
m_resetTimeQueue.erase(itr);
return;
}
}
// in case the reset time changed (should happen very rarely), we search the whole queue
if (itr == range.second)
{
for (itr = m_resetTimeQueue.begin(); itr != m_resetTimeQueue.end(); ++itr)
{
if (itr->second == event)
{
m_resetTimeQueue.erase(itr);
return;
}
}
if (itr == m_resetTimeQueue.end())
sLog->outError("InstanceSaveManager::ScheduleReset: cannot cancel the reset, the event(%d, %d, %d) was not found!", event.type, event.mapid, event.instanceId);
}
}
else
m_resetTimeQueue.insert(std::pair<time_t, InstResetEvent>(time, event));
}
void InstanceSaveManager::Update()
{
time_t now = time(NULL);
time_t t;
while (!m_resetTimeQueue.empty())
{
t = m_resetTimeQueue.begin()->first;
if (t >= now)
break;
InstResetEvent &event = m_resetTimeQueue.begin()->second;
if (event.type == 0)
{
// for individual normal instances, max creature respawn + X hours
_ResetInstance(event.mapid, event.instanceId);
m_resetTimeQueue.erase(m_resetTimeQueue.begin());
}
else
{
// global reset/warning for a certain map
time_t resetTime = GetResetTimeFor(event.mapid, event.difficulty);
_ResetOrWarnAll(event.mapid, event.difficulty, event.type != 4, resetTime);
if (event.type != 4)
{
// schedule the next warning/reset
++event.type;
ScheduleReset(true, resetTime - ResetTimeDelay[event.type-1], event);
}
m_resetTimeQueue.erase(m_resetTimeQueue.begin());
}
}
}
void InstanceSaveManager::_ResetSave(InstanceSaveHashMap::iterator &itr)
{
// unbind all players bound to the instance
// do not allow UnbindInstance to automatically unload the InstanceSaves
lock_instLists = true;
InstanceSave::PlayerListType &pList = itr->second->m_playerList;
while (!pList.empty())
{
Player* player = *(pList.begin());
player->UnbindInstance(itr->second->GetMapId(), itr->second->GetDifficulty(), true);
}
InstanceSave::GroupListType &gList = itr->second->m_groupList;
while (!gList.empty())
{
Group* group = *(gList.begin());
group->UnbindInstance(itr->second->GetMapId(), itr->second->GetDifficulty(), true);
}
delete itr->second;
m_instanceSaveById.erase(itr++);
lock_instLists = false;
}
void InstanceSaveManager::_ResetInstance(uint32 mapid, uint32 instanceId)
{
sLog->outDebug(LOG_FILTER_MAPS, "InstanceSaveMgr::_ResetInstance %u, %u", mapid, instanceId);
Map const* map = sMapMgr->CreateBaseMap(mapid);
if (!map->Instanceable())
return;
InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(instanceId);
if (itr != m_instanceSaveById.end())
_ResetSave(itr);
DeleteInstanceFromDB(instanceId); // even if save not loaded
Map* iMap = ((MapInstanced*)map)->FindInstanceMap(instanceId);
if (iMap && iMap->IsDungeon())
((InstanceMap*)iMap)->Reset(INSTANCE_RESET_RESPAWN_DELAY);
else
sObjectMgr->DeleteRespawnTimeForInstance(instanceId); // even if map is not loaded
// Free up the instance id and allow it to be reused
sMapMgr->FreeInstanceId(instanceId);
}
void InstanceSaveManager::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, bool warn, time_t resetTime)
{
// global reset for all instances of the given map
MapEntry const* mapEntry = sMapStore.LookupEntry(mapid);
if (!mapEntry->Instanceable())
return;
time_t now = time(NULL);
if (!warn)
{
MapDifficulty const* mapDiff = GetMapDifficultyData(mapid, difficulty);
if (!mapDiff || !mapDiff->resetTime)
{
sLog->outError("InstanceSaveManager::ResetOrWarnAll: not valid difficulty or no reset delay for map %d", mapid);
return;
}
// remove all binds to instances of the given map
for (InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end();)
{
if (itr->second->GetMapId() == mapid && itr->second->GetDifficulty() == difficulty)
_ResetSave(itr);
else
++itr;
}
// delete them from the DB, even if not loaded
SQLTransaction trans = CharacterDatabase.BeginTransaction();
trans->PAppend("DELETE FROM character_instance USING character_instance LEFT JOIN instance ON character_instance.instance = id WHERE map = '%u' and difficulty='%u'", mapid, difficulty);
trans->PAppend("DELETE FROM group_instance USING group_instance LEFT JOIN instance ON group_instance.instance = id WHERE map = '%u' and difficulty='%u'", mapid, difficulty);
trans->PAppend("DELETE FROM instance WHERE map = '%u' and difficulty='%u'", mapid, difficulty);
CharacterDatabase.CommitTransaction(trans);
// calculate the next reset time
uint32 diff = sWorld->getIntConfig(CONFIG_INSTANCE_RESET_TIME_HOUR) * HOUR;
uint32 period = uint32(((mapDiff->resetTime * sWorld->getRate(RATE_INSTANCE_RESET_TIME))/DAY) * DAY);
if (period < DAY)
period = DAY;
uint64 next_reset = ((resetTime + MINUTE) / DAY * DAY) + period + diff;
SetResetTimeFor(mapid, difficulty, next_reset);
ScheduleReset(true, time_t(next_reset-3600), InstResetEvent(1, mapid, difficulty, 0));
// update it in the DB
CharacterDatabase.PExecute("UPDATE instance_reset SET resettime = '%u' WHERE mapid = '%d' AND difficulty = '%d'", uint32(next_reset), mapid, difficulty);
}
// note: this isn't fast but it's meant to be executed very rarely
Map const* map = sMapMgr->CreateBaseMap(mapid); // _not_ include difficulty
MapInstanced::InstancedMaps &instMaps = ((MapInstanced*)map)->GetInstancedMaps();
MapInstanced::InstancedMaps::iterator mitr;
uint32 timeLeft;
for (mitr = instMaps.begin(); mitr != instMaps.end(); ++mitr)
{
Map* map2 = mitr->second;
if (!map2->IsDungeon())
continue;
if (warn)
{
if (now <= resetTime)
timeLeft = 0;
else
timeLeft = uint32(now - resetTime);
((InstanceMap*)map2)->SendResetWarnings(timeLeft);
}
else
((InstanceMap*)map2)->Reset(INSTANCE_RESET_GLOBAL);
}
// TODO: delete creature/gameobject respawn times even if the maps are not loaded
}
uint32 InstanceSaveManager::GetNumBoundPlayersTotal()
{
uint32 ret = 0;
for (InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr)
ret += itr->second->GetPlayerCount();
return ret;
}
uint32 InstanceSaveManager::GetNumBoundGroupsTotal()
{
uint32 ret = 0;
for (InstanceSaveHashMap::iterator itr = m_instanceSaveById.begin(); itr != m_instanceSaveById.end(); ++itr)
ret += itr->second->GetGroupCount();
return ret;
}
| sourceleaker/gaycore | src/server/game/Instances/InstanceSaveMgr.cpp | C++ | gpl-2.0 | 26,391 |
<?php
/**
* @package Mambo
* @subpackage Menus
* @author Mambo Foundation Inc see README.php
* @copyright Mambo Foundation Inc.
* See COPYRIGHT.php for copyright notices and details.
* @license GNU/GPL Version 2, see LICENSE.php
* Mambo 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.
*/
/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
mosAdminMenus::menuItem( $type );
switch ($task) {
case 'content_blog_category':
// this is the new item, ie, the same name as the menu `type`
content_blog_category::edit( 0, $menutype, $option );
break;
case 'edit':
content_blog_category::edit( $cid[0], $menutype, $option );
break;
case 'save':
case 'apply':
content_blog_category::saveMenu( $option, $task );
break;
}
?>
| chanhong/mambo | administrator/components/com_menus/content_blog_category/content_blog_category.menu.php | PHP | gpl-2.0 | 965 |
/**
Copyright (C) 2008-2013 Stefan Kolb.
This file is part of the program pso (particle swarm optimization).
The program pso is free software: you can redistribute it
and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation, either
version 2 of the License, or (at your option) any later version.
The program pso 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 pso. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "swarmcontrolwidget.h"
#include "functionoptionswidget.h"
#include "variationcontrolwidget.h"
#include "particleviewwidget.h"
#include "graphwidget.h"
MainWindow::MainWindow( QWidget *parent, Qt::WindowFlags flags )
: QMainWindow( parent, flags )
{
variation_max_iterations = 10000;
swarm.setDimension( 2 );
setWindowTitle( "Particle Swarm Optimization" );
setDockOptions( QMainWindow::ForceTabbedDocks | QMainWindow::AllowTabbedDocks | QMainWindow::AnimatedDocks | QMainWindow::AllowTabbedDocks );
{
QWidget *widget = new QWidget( this );
QBoxLayout *layout = new QBoxLayout( QBoxLayout::TopToBottom, widget );
ui_functionviewer = new FunctionViewer( this );
ui_functionviewer->setSwarm( &swarm );
connect( ui_functionviewer, SIGNAL( particleNumberChanged() ), this, SLOT( particleNumberChanged() ) );
layout->addWidget( ui_functionviewer );
variation_graph = new QwtPlot( QwtText( "Variation" ), this );
variation_graph->setAxisTitle( QwtPlot::xBottom, "particles" );
variation_graph->setAxisTitle( QwtPlot::yLeft, "iterations" );
variation_graph->enableAxis( QwtPlot::yRight );
variation_graph->setAxisTitle( QwtPlot::yRight, "fitness" );
variation_graph->insertLegend( new QwtLegend() );
variation_graph->setHidden( true );
layout->addWidget( variation_graph );
variation_variable_curve = new QwtPlotCurve( "iterations" );
variation_variable_curve->setPen( QPen( QColor( 255, 0, 0 ) ) );
variation_variable_curve->attach( variation_graph );
variation_fitness_curve = new QwtPlotCurve( "fitness" );
variation_fitness_curve->setPen( QPen( QColor( 0, 0, 255 ) ) );
variation_fitness_curve->attach( variation_graph );
variation_fitness_curve->setYAxis( QwtPlot::yRight );
widget->setLayout( layout );
setCentralWidget( widget );
}
timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), this, SLOT( timerTimeOut() ) );
QMenu *mode = menuBar()->addMenu( tr( "&Mode" ) );
QActionGroup *actiongroup = new QActionGroup( this );
connect( actiongroup, SIGNAL( triggered( QAction * ) ), this, SLOT( changeApplicationMode( QAction * ) ) );
menu_actions_container["mode:3d"] = actiongroup->addAction( "&3D" );
menu_actions_container["mode:3d"]->setCheckable( true );
menu_actions_container["mode:3d"]->setChecked( true );
mode->addAction( menu_actions_container["mode:3d"] );
menu_actions_container["mode:variation"] = actiongroup->addAction( "&Variation" );
menu_actions_container["mode:variation"]->setCheckable( true );
mode->addAction( menu_actions_container["mode:variation"] );
mode->addSeparator();
menu_actions_container["mode:exit"] = mode->addAction( "&Exit", this, SLOT( close() ) );
QMenu *options = menuBar()->addMenu( tr( "&Options" ) );
menu_actions_container["options:default view"] = options->addAction( "&Default View", ui_functionviewer, SLOT( setDefaultView() ) );
menu_actions_container["options:min function color"] = options->addAction( "&Min Function Color", ui_functionviewer, SLOT( changeFunctionMinColor() ) );
menu_actions_container["options:max function color"] = options->addAction( "&Max Function Color", ui_functionviewer, SLOT( changeFunctionMaxColor() ) );
menu_actions_container["options:point size"] = options->addAction( "&Point Size", ui_functionviewer, SLOT( changePointSize() ) );
menu_actions_container["options:point color"] = options->addAction( "&Point Color", ui_functionviewer, SLOT( changePointColor() ) );
menu_actions_container["options:mini map"] = options->addAction( "&Mini Map" );
menu_actions_container["options:mini map"]->setCheckable( true );
menu_actions_container["options:mini map"]->setChecked( true );
connect( menu_actions_container["options:mini map"], SIGNAL( toggled( bool ) ), ui_functionviewer, SLOT( showMiniMap( bool ) ) );
menu_actions_container["options:mini map mark best"] = options->addAction( "&Mini Map Mark Best" );
menu_actions_container["options:mini map mark best"]->setCheckable( true );
menu_actions_container["options:mini map mark best"]->setChecked( true );
ui_functionviewer->showMiniMapGlobalBest( true );
connect( menu_actions_container["options:mini map mark best"], SIGNAL( toggled( bool ) ), ui_functionviewer, SLOT( showMiniMapGlobalBest( bool ) ) );
menu_actions_container["options:mark best"] = options->addAction( "&Mark Best" );
menu_actions_container["options:mark best"]->setCheckable( true );
menu_actions_container["options:mark best"]->setChecked( true );
ui_functionviewer->showGlobalBest3D( true );
connect( menu_actions_container["options:mark best"], SIGNAL( toggled( bool ) ), ui_functionviewer, SLOT( showGlobalBest3D( bool ) ) );
#ifdef USE_FTGL
menu_actions_container["options:show axis"] = options->addAction( "&Show Axis" );
menu_actions_container["options:show axis"]->setCheckable( true );
menu_actions_container["options:show axis"]->setChecked( true );
connect( menu_actions_container["options:show axis"], SIGNAL( toggled( bool ) ), ui_functionviewer, SLOT( showAxis( bool ) ) );
if( !ui_functionviewer->isFTGLFontLoaded() )
{
menu_actions_container["options:show axis"]->setEnabled( false );
menu_actions_container["options:show axis"]->setChecked( false );
}
#endif
menu_actions_container["options:trace particles"] = options->addAction( "&Trace Particles" );
menu_actions_container["options:trace particles"]->setCheckable( true );
menu_actions_container["options:trace particles"]->setChecked( false );
ui_functionviewer->showTraceParticles( false );
connect( menu_actions_container["options:trace particles"], SIGNAL( toggled( bool ) ), ui_functionviewer, SLOT( showTraceParticles( bool ) ) );
menu_actions_container["options:gl background color"] = options->addAction( "&GL Background Color", ui_functionviewer, SLOT( changeBackgroundColor() ) );
menu_actions_container["options:wireframe"] = options->addAction( "&Wireframe" );
menu_actions_container["options:wireframe"]->setCheckable( true );
connect( menu_actions_container["options:wireframe"], SIGNAL( toggled( bool ) ), this, SLOT( changeGLWireframe( bool ) ) );
menu_actions_container["options:points"] = options->addAction( "&Points" );
menu_actions_container["options:points"]->setCheckable( true );
connect( menu_actions_container["options:points"], SIGNAL( toggled( bool ) ), this, SLOT( changeGLPoint( bool ) ) );
options->addSeparator();
menu_actions_container["options:variation max iterations"] = options->addAction( "&Variation Max Iterations", this, SLOT( changeVariationMaxIterations() ) );
menu_actions_container["options:variation max iterations"]->setEnabled( false );
QMenu *dock_menu = new QMenu( tr( "Dock" ) );
ui_dockmanager = new DockManager( this, dock_menu );
menuBar()->addMenu( dock_menu );
setDockOptions( QMainWindow::VerticalTabs );
ui_dockwidgets["swarm control"] = new DockWidget( tr( "Swarm Control" ) );
ui_dockmanager->addDock( Qt::LeftDockWidgetArea, ui_dockwidgets["swarm control"] );
ui_swarm_control = new SwarmControlWidget( this, this );
ui_dockwidgets["swarm control"]->setWidget( ui_swarm_control );
ui_dockwidgets["function options"] = new DockWidget( tr( "Function Options" ) );
ui_dockmanager->addDock( Qt::LeftDockWidgetArea, ui_dockwidgets["function options"] );
ui_function_options = new FunctionOptionsWidget( this, this );
ui_dockwidgets["function options"]->setWidget( ui_function_options );
ui_dockwidgets["variation control"] = new DockWidget( tr( "Variation Coltrol" ) );
ui_dockmanager->addDock( Qt::LeftDockWidgetArea, ui_dockwidgets["variation control"] );
ui_variation_control = new VariationControlWidget( this, this );
ui_dockwidgets["variation control"]->setWidget( ui_variation_control );
ui_dockwidgets["particle view"] = new DockWidget( tr( "Particle View" ) );
ui_dockmanager->addDock( Qt::RightDockWidgetArea, ui_dockwidgets["particle view"] );
ui_particle_view = new ParticleViewWidget( this, this );
ui_dockwidgets["particle view"]->setWidget( ui_particle_view );
ui_dockwidgets["particle view"]->close();
ui_dockwidgets["graph"] = new DockWidget( tr( "Graph" ) );
ui_dockmanager->addDock( Qt::RightDockWidgetArea, ui_dockwidgets["graph"] );
ui_graph_widget = new GraphWidget( this, this );
ui_dockwidgets["graph"]->setWidget( ui_graph_widget );
ui_dockwidgets["graph"]->close();
setApplicationMode( PSOMode3DView );
ui_function_options->setFunction();
}
void MainWindow::changeGLWireframe( bool w )
{
if( menu_actions_container["options:points"]->isChecked() && w )
{
menu_actions_container["options:points"]->setChecked( false );
}
ui_functionviewer->setViewModeWireframe( w );
}
void MainWindow::changeGLPoint( bool w )
{
if( menu_actions_container["options:wireframe"]->isChecked() && w )
{
menu_actions_container["options:wireframe"]->setChecked( false );
}
ui_functionviewer->setViewModePoint( w );
}
/**
Handles the timer timeout callback!
In both application modes the optimization is performed in this function.
This includes all user interface element updates.
*/
void MainWindow::timerTimeOut()
{
switch( application_mode )
{
case PSOMode3DView:
try
{
bool check = false;
if( swarm.m_swarm.empty() )
{
ui_swarm_control->disableTimer();
}
if( swarm.getCheckAbortCriterion() )
{
check = !swarm.checkAbortCriterion();
}
else
{
swarm.checkAbortCriterion(); //needed for auto velocity see: void Swarm::calculateMaxVelocity()
check = true;
}
if( check )
{
if( !ui_dockwidgets["particle view"]->isHidden() )
{
ui_particle_view->updateView();
}
if( !ui_dockwidgets["graph"]->isHidden() )
{
ui_graph_widget->updateGraph();
}
computeNextStep();
ui_swarm_control->showUsedIterations( swarm.getIterationStep() );
if( swarm.getBestParticle() )
{
ui_swarm_control->showBestPartileFitness( swarm.getBestParticle()->getBestValue() );
ui_swarm_control->showCurrentBestFoundPosition( swarm.getBestParticle()->getBestPosition()[0], swarm.getBestParticle()->getBestPosition()[1] );
}
if( ui_swarm_control->isAutoVelocityUsed() )
{
ui_swarm_control->showCurrentMaxVelocity( swarm.getMaxVelocity() );
}
ui_functionviewer->updateGL();
}
else
{
ui_swarm_control->disableTimer();
}
}
catch( RuntimeError &err )
{
ui_swarm_control->disableTimer();
showError( err );
}
break;
case PSOModeVariation:
if( ui_variation_control->getToValue() <= ui_variation_control->getFromValue() )
{
ui_variation_control->disableTimer();
}
else
{
try
{
size_t average_number = ui_variation_control->getAverageNumber();
QString variable = ui_variation_control->getCurrentlyUsedVariable();
double average = 0.0;
double average_fitness = 0.0;
bool random = true;
if( ui_swarm_control->isCreationModeRandom() )
{
random = true;
}
else
{
random = false;
}
for( size_t i = 0; i < average_number; i++ )
{
ui_swarm_control->setMaxVelocity();
unsigned int particle_number = ui_swarm_control->getParticleNumber();
if( variable == ui_variation_control->getVariationVariableNames()["particle"] )
{
particle_number = ui_variation_control->getFromValue();
}
{
VectorN<double> range_min( 1 ), range_max( 1 );
ui_function_options->getFunctionRange( range_min, range_max );
getSwarm()->createSwarm( particle_number, range_min, range_max, random );
}
if( variable == ui_variation_control->getVariationVariableNames()["c1"] )
{
getSwarm()->setParameterC1( ui_variation_control->getFromValue() );
}
else if( variable == ui_variation_control->getVariationVariableNames()["c2"] )
{
getSwarm()->setParameterC2( ui_variation_control->getFromValue() );
}
else if( variable == ui_variation_control->getVariationVariableNames()["c3"] )
{
getSwarm()->setParameterC3( ui_variation_control->getFromValue() );
}
else if( variable == ui_variation_control->getVariationVariableNames()["w"] )
{
getSwarm()->setParameterW( ui_variation_control->getFromValue() );
}
else if( variable == ui_variation_control->getVariationVariableNames()["radius"] )
{
getSwarm()->setNeighbourRadius( ui_variation_control->getFromValue() );
}
else if( variable == ui_variation_control->getVariationVariableNames()["max velocity"] )
{
getSwarm()->setMaxVelocity( ui_variation_control->getFromValue() );
}
average += getSwarm()->optimize( variation_max_iterations );
average_fitness += getSwarm()->getBestFitness();
}
variation_variables_data.push_back( ui_variation_control->getFromValue() );
variation_iterations_data.push_back( average / static_cast<double>( average_number ) );
variation_fitness_data.push_back( average_fitness / static_cast<double>( average_number ) );
variation_variable_curve->setSamples( &*variation_variables_data.begin(), &*variation_iterations_data.begin(), variation_variables_data.size() );
variation_fitness_curve->setSamples( &*variation_variables_data.begin(), &*variation_fitness_data.begin(), variation_variables_data.size() );
variation_graph->replot();
ui_variation_control->setFromValue( ui_variation_control->getFromValue() + ui_variation_control->getStepValue() );
}
catch( RuntimeError &err )
{
ui_variation_control->disableTimer();
showError( err );
}
}
break;
}
}
void MainWindow::showError( const RuntimeError &err )
{
QString line;
line.setNum( err.getLine() );
QMessageBox::warning( this, QString( "Error" ), QString::fromStdString( err.getFile() ) + QString( ":" ) + line + QString( "\n" ) + QString::fromStdString( err.getMessage() ) );
}
void MainWindow::particleNumberChanged()
{
ui_swarm_control->setParticleNumber( swarm.m_swarm.size() );
}
Swarm< Function > *MainWindow::getSwarm()
{
return &swarm;
}
FunctionViewer *MainWindow::getGLWidget()
{
return ui_functionviewer;
}
FunctionOptionsWidget *MainWindow::getFunctionOptionsWidget()
{
return ui_function_options;
}
SwarmControlWidget *MainWindow::getSwarmControlWidget()
{
return ui_swarm_control;
}
QwtPlot *MainWindow::getVariationPlotWidget()
{
return variation_graph;
}
VariationControlWidget *MainWindow::getStatisticControlWidget()
{
return ui_variation_control;
}
QTimer *MainWindow::getTimer()
{
return timer;
}
ParticleViewWidget *MainWindow::getParticleViewWidget()
{
return ui_particle_view;
}
GraphWidget *MainWindow::getGraphWidget()
{
return ui_graph_widget;
}
/**
Sets the maximum number of allowed iterations in the application mode variations.
*/
void MainWindow::changeVariationMaxIterations()
{
size_t iterations;
bool ok;
iterations = QInputDialog::getInteger( this, "Max Iterations", "max iterations:", variation_max_iterations, 1, 10000000, 1, &ok );
if( ok )
{
variation_max_iterations = iterations;
}
}
void MainWindow::changeApplicationMode( QAction *action )
{
if( action->text() == "&3D" )
{
setApplicationMode( PSOMode3DView );
}
else if( action->text() == "&Variation" )
{
setApplicationMode( PSOModeVariation );
}
else
{
setApplicationMode( PSOMode3DView );
}
}
/**
This function enables and disables a couple of user interface
elements dependent on \a mode.
\param[in] mode
*/
void MainWindow::setApplicationMode( PSOMode mode )
{
application_mode = mode;
ui_swarm_control->changeApplicationMode( mode );
ui_function_options->changeApplicationMode( mode );
switch( mode )
{
case PSOMode3DView:
getTimer()->setInterval( ui_swarm_control->getCurrentTimerTimeout() );
getSwarm()->clear();
getSwarm()->setDimension( 2 );
variation_graph->setHidden( true );
ui_functionviewer->setVisible( true );
ui_dockwidgets["particle view"]->setEnabled( true );
ui_dockwidgets["particle view"]->close();
ui_dockwidgets["graph"]->setEnabled( true );
ui_dockwidgets["graph"]->close();
ui_dockwidgets["variation control"]->setEnabled( false );
ui_dockwidgets["variation control"]->close();
for( QMap<QString, QAction *>::iterator it = menu_actions_container.begin(); it != menu_actions_container.end(); it++ )
{
if( it.key().contains( "options:" ) )
{
it.value()->setEnabled( true );
}
}
menu_actions_container["options:variation max iterations"]->setEnabled( false );
if( !ui_functionviewer->isFTGLFontLoaded() )
{
menu_actions_container["options:show axis"]->setEnabled( false );
}
ui_dockmanager->updateDockMenu();
break;
case PSOModeVariation:
getTimer()->stop();
ui_functionviewer->setHidden( true );
variation_graph->setVisible( true );
ui_dockwidgets["particle view"]->setEnabled( false );
ui_dockwidgets["particle view"]->close();
ui_dockwidgets["graph"]->setEnabled( false );
ui_dockwidgets["graph"]->close();
ui_dockwidgets["variation control"]->show();
addDockWidget( Qt::LeftDockWidgetArea, ui_dockwidgets["variation control"] );
for( QMap<QString, QAction *>::iterator it = menu_actions_container.begin(); it != menu_actions_container.end(); it++ )
{
if( it.key().contains( "options:" ) )
{
it.value()->setEnabled( false );
}
}
menu_actions_container["options:variation max iterations"]->setEnabled( true );
ui_dockmanager->updateDockMenu();
ui_function_options->setFunction();
break;
}
}
void MainWindow::clearVariationGraphData()
{
variation_variables_data.clear();
variation_iterations_data.clear();
variation_fitness_data.clear();
}
PSOMode MainWindow::getCurrentApplicationMode() const
{
return application_mode;
}
/**
The computation of the next time step is performed in this function. Additionally
the array to display the particle trace is updated in this function. If particle
tracing is enabled.
*/
void MainWindow::computeNextStep()
{
bool trace_particles = ui_functionviewer->isParticleTracingEnabled();
std::vector<std::vector<Vector<double> > > &trace_particle_container = ui_functionviewer->getTraceParticleContainer();
if( swarm.getIterationStep() == 0 )
{
trace_particle_container.clear();
if( trace_particles )
{
if( trace_particle_container.size() != swarm.m_swarm.size() )
{
trace_particle_container.clear();
trace_particle_container.resize( swarm.m_swarm.size() );
}
unsigned int i = 0;
Swarm<Function>::particle_container::iterator begin = swarm.m_swarm.begin(), end = swarm.m_swarm.end();
for( Swarm<Function>::particle_container::iterator it( begin ); it != end; it++, i++ )
{
trace_particle_container[i].push_back( Vector<double>( ( *it )->getPosition()[0], ( *it )->getPosition()[1], ( *it )->getCurrentValue() + 0.2 ) );
}
}
}
swarm.computeNextStep();
if( trace_particles )
{
if( trace_particle_container.size() != swarm.m_swarm.size() )
{
trace_particle_container.clear();
trace_particle_container.resize( swarm.m_swarm.size() );
}
unsigned int i = 0;
Swarm<Function>::particle_container::iterator begin = swarm.m_swarm.begin(), end = swarm.m_swarm.end();
for( Swarm<Function>::particle_container::iterator it( begin ); it != end; it++, i++ )
{
trace_particle_container[i].push_back( Vector<double>( ( *it )->getPosition()[0], ( *it )->getPosition()[1], ( *it )->getCurrentValue() + 0.2 ) );
}
}
}
| kolb-stefan/particle_swarm_optimization | mainwindow.cpp | C++ | gpl-2.0 | 23,482 |
<?php // $Id$
require_once("../../config.php");
require_once("lib.php");
$id = required_param('id', PARAM_INT); // Course Module ID
if (!$course = $DB->get_record('course', array('id'=>$id))) {
print_error('invalidcourseid');
}
require_course_login($course);
add_to_log($course->id, "survey", "view all", "index.php?id=$course->id", "");
$strsurveys = get_string("modulenameplural", "survey");
$strweek = get_string("week");
$strtopic = get_string("topic");
$strname = get_string("name");
$strstatus = get_string("status");
$strdone = get_string("done", "survey");
$strnotdone = get_string("notdone", "survey");
$navlinks = array();
$navlinks[] = array('name' => $strsurveys, 'link' => '', 'type' => 'activity');
$navigation = build_navigation($navlinks);
print_header_simple("$strsurveys", "", $navigation,
"", "", true, "", navmenu($course));
if (! $surveys = get_all_instances_in_course("survey", $course)) {
notice(get_string('thereareno', 'moodle', $strsurveys), "../../course/view.php?id=$course->id");
}
if ($course->format == "weeks") {
$table->head = array ($strweek, $strname, $strstatus);
$table->align = array ("CENTER", "LEFT", "LEFT");
} else if ($course->format == "topics") {
$table->head = array ($strtopic, $strname, $strstatus);
$table->align = array ("CENTER", "LEFT", "LEFT");
} else {
$table->head = array ($strname, $strstatus);
$table->align = array ("LEFT", "LEFT");
}
$currentsection = '';
foreach ($surveys as $survey) {
if (!empty($USER->id) and survey_already_done($survey->id, $USER->id)) {
$ss = $strdone;
} else {
$ss = $strnotdone;
}
$printsection = "";
if ($survey->section !== $currentsection) {
if ($survey->section) {
$printsection = $survey->section;
}
if ($currentsection !== "") {
$table->data[] = 'hr';
}
$currentsection = $survey->section;
}
//Calculate the href
if (!$survey->visible) {
//Show dimmed if the mod is hidden
$tt_href = "<a class=\"dimmed\" href=\"view.php?id=$survey->coursemodule\">".format_string($survey->name,true)."</a>";
} else {
//Show normal if the mod is visible
$tt_href = "<a href=\"view.php?id=$survey->coursemodule\">".format_string($survey->name,true)."</a>";
}
if ($course->format == "weeks" or $course->format == "topics") {
$table->data[] = array ($printsection, $tt_href, "<a href=\"view.php?id=$survey->coursemodule\">$ss</a>");
} else {
$table->data[] = array ($tt_href, "<a href=\"view.php?id=$survey->coursemodule\">$ss</a>");
}
}
echo "<br />";
print_table($table);
print_footer($course);
?>
| cwaclawik/moodle | mod/survey/index.php | PHP | gpl-2.0 | 2,988 |
/*
* Copyright (C) 2007-2009 Gabest
* http://www.gabest.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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "stdafx.h"
#include "GSdx.h"
#include "GSUtil.h"
#include "GSRendererSW.h"
#include "GSRendererNull.h"
#include "GSDeviceNull.h"
#include "GSDeviceOGL.h"
#include "GSRendererOGL.h"
#ifdef _WINDOWS
#include "GSRendererDX9.h"
#include "GSRendererDX11.h"
#include "GSDevice9.h"
#include "GSDevice11.h"
#include "GSWndDX.h"
#include "GSWndWGL.h"
#include "GSRendererCS.h"
#include "GSSettingsDlg.h"
static HRESULT s_hr = E_FAIL;
#else
#include "GSWndOGL.h"
#include "GSWndEGL.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
extern bool RunLinuxDialog();
#endif
#define PS2E_LT_GS 0x01
#define PS2E_GS_VERSION 0x0006
#define PS2E_X86 0x01 // 32 bit
#define PS2E_X86_64 0x02 // 64 bit
static GSRenderer* s_gs = NULL;
static void (*s_irq)() = NULL;
static uint8* s_basemem = NULL;
static int s_renderer = -1;
static bool s_framelimit = true;
static bool s_vsync = false;
static bool s_exclusive = true;
#ifdef _WINDOWS
static bool s_isgsopen2 = false; // boolean to remove some stuff from the config panel in new PCSX2's/
#endif
bool gsopen_done = false; // crash guard for GSgetTitleInfo2
EXPORT_C_(uint32) PS2EgetLibType()
{
return PS2E_LT_GS;
}
EXPORT_C_(const char*) PS2EgetLibName()
{
return GSUtil::GetLibName();
}
EXPORT_C_(uint32) PS2EgetLibVersion2(uint32 type)
{
const uint32 revision = 0;
const uint32 build = 1;
return (build << 0) | (revision << 8) | (PS2E_GS_VERSION << 16) | (PLUGIN_VERSION << 24);
}
#ifdef _WINDOWS
EXPORT_C_(void) PS2EsetEmuVersion(const char* emuId, uint32 version)
{
s_isgsopen2 = true;
}
#endif
EXPORT_C_(uint32) PS2EgetCpuPlatform()
{
#ifdef _M_AMD64
return PS2E_X86_64;
#else
return PS2E_X86;
#endif
}
EXPORT_C GSsetBaseMem(uint8* mem)
{
s_basemem = mem;
if(s_gs)
{
s_gs->SetRegsMem(s_basemem);
}
}
EXPORT_C GSsetSettingsDir(const char* dir)
{
theApp.SetConfigDir(dir);
}
EXPORT_C_(int) GSinit()
{
if(!GSUtil::CheckSSE())
{
return -1;
}
#ifdef _WINDOWS
s_hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
if(!GSUtil::CheckDirectX())
{
return -1;
}
#endif
return 0;
}
EXPORT_C GSshutdown()
{
gsopen_done = false;
delete s_gs;
s_gs = NULL;
s_renderer = -1;
#ifdef _WINDOWS
if(SUCCEEDED(s_hr))
{
::CoUninitialize();
s_hr = E_FAIL;
}
#endif
}
EXPORT_C GSclose()
{
gsopen_done = false;
if(s_gs == NULL) return;
s_gs->ResetDevice();
// Opengl requirement: It must be done before the Detach() of
// the context
delete s_gs->m_dev;
s_gs->m_dev = NULL;
if (s_gs->m_wnd)
{
s_gs->m_wnd->Detach();
}
}
static int _GSopen(void** dsp, char* title, int renderer, int threads = -1)
{
GSDevice* dev = NULL;
if(renderer == -1)
{
renderer = theApp.GetConfig("renderer", 0);
}
if(threads == -1)
{
threads = theApp.GetConfig("extrathreads", 0);
}
GSWnd* wnd[2];
try
{
if(s_renderer != renderer)
{
// Emulator has made a render change request, which requires a completely
// new s_gs -- if the emu doesn't save/restore the GS state across this
// GSopen call then they'll get corrupted graphics, but that's not my problem.
delete s_gs;
s_gs = NULL;
}
if(renderer == 15)
{
#ifdef _WINDOWS
dev = new GSDevice11();
if(dev == NULL)
{
return -1;
}
delete s_gs;
s_gs = new GSRendererCS();
s_renderer = renderer;
#endif
}
else
{
switch(renderer / 3)
{
default:
#ifdef _WINDOWS
case 0: dev = new GSDevice9(); break;
case 1: dev = new GSDevice11(); break;
#endif
case 3: dev = new GSDeviceNull(); break;
case 4: dev = new GSDeviceOGL(); break;
}
if(dev == NULL)
{
return -1;
}
if(s_gs == NULL)
{
switch(renderer % 3)
{
default:
case 0:
switch(renderer)
{
default:
#ifdef _WINDOWS
case 0: s_gs = (GSRenderer*)new GSRendererDX9(); break;
case 3: s_gs = (GSRenderer*)new GSRendererDX11(); break;
#endif
case 12: s_gs = (GSRenderer*)new GSRendererOGL(); break;
}
break;
case 1:
s_gs = new GSRendererSW(threads);
break;
case 2:
s_gs = new GSRendererNull();
break;
}
s_renderer = renderer;
}
}
if (s_gs->m_wnd == NULL)
{
#ifdef _WINDOWS
if (renderer / 3 == 4)
s_gs->m_wnd = new GSWndWGL();
else
s_gs->m_wnd = new GSWndDX();
#else
#ifdef ENABLE_GLES
wnd[0] = NULL;
#else
wnd[0] = new GSWndOGL();
#endif
wnd[1] = new GSWndEGL();
#endif
}
}
catch(std::exception& ex)
{
// Allowing std exceptions to escape the scope of the plugin callstack could
// be problematic, because of differing typeids between DLL and EXE compilations.
// ('new' could throw std::alloc)
printf("GSdx error: Exception caught in GSopen: %s", ex.what());
return -1;
}
s_gs->SetRegsMem(s_basemem);
s_gs->SetIrqCallback(s_irq);
s_gs->SetVSync(s_vsync);
s_gs->SetFrameLimit(s_framelimit);
if(*dsp == NULL)
{
// old-style API expects us to create and manage our own window:
int w = theApp.GetConfig("ModeWidth", 0);
int h = theApp.GetConfig("ModeHeight", 0);
#ifdef _LINUX
for(uint32 i = 0; i < 2; i++) {
try
{
if (wnd[i] == NULL) continue;
wnd[i]->Create(title, w, h);
s_gs->m_wnd = wnd[i];
if (i == 0) delete wnd[1];
break;
}
catch (GSDXRecoverableError)
{
wnd[i]->Detach();
delete wnd[i];
}
}
if (s_gs->m_wnd == NULL)
{
GSclose();
return -1;
}
#endif
#ifdef _WINDOWS
if(!s_gs->CreateWnd(title, w, h))
{
GSclose();
return -1;
}
#endif
s_gs->m_wnd->Show();
*dsp = s_gs->m_wnd->GetDisplay();
}
else
{
s_gs->SetMultithreaded(true);
#ifdef _LINUX
if (s_gs->m_wnd) {
// A window was already attached to s_gs so we also
// need to restore the window state (Attach)
s_gs->m_wnd->Attach((void*)((uint32*)(dsp)+1), false);
} else {
// No window found, try to attach a GLX win and retry
// with EGL win if failed.
for(uint32 i = 0; i < 2; i++) {
try
{
if (wnd[i] == NULL) continue;
wnd[i]->Attach((void*)((uint32*)(dsp)+1), false);
s_gs->m_wnd = wnd[i];
if (i == 0) delete wnd[1];
break;
}
catch (GSDXRecoverableError)
{
wnd[i]->Detach();
delete wnd[i];
}
}
}
if (s_gs->m_wnd == NULL)
{
return -1;
}
#endif
#ifdef _WINDOWS
s_gs->m_wnd->Attach(*dsp, false);
#endif
}
if(!s_gs->CreateDevice(dev))
{
// This probably means the user has DX11 configured with a video card that is only DX9
// compliant. Cound mean drivr issues of some sort also, but to be sure, that's the most
// common cause of device creation errors. :) --air
GSclose();
return -1;
}
return 0;
}
EXPORT_C_(int) GSopen2(void** dsp, uint32 flags)
{
#ifdef _LINUX
// Use ogl renderer as default otherwise it crash at startup
// GSRenderOGL only GSDeviceOGL (not GSDeviceNULL)
int renderer = theApp.GetConfig("renderer", 12);
#else
int renderer = theApp.GetConfig("renderer", 0);
#endif
if(flags & 4)
{
#ifdef _WINDOWS
int best_sw_renderer = GSUtil::CheckDirect3D11Level() >= D3D_FEATURE_LEVEL_10_0 ? 4 : 1; // dx11 / dx9 sw
switch(renderer){
// Use alternative renderer (SW if currently using HW renderer, and vice versa, keeping the same DX level)
case 1: renderer = 0; break; // DX9: SW to HW
case 0: renderer = 1; break; // DX9: HW to SW
case 4: renderer = 3; break; // DX11: SW to HW
case 3: renderer = 4; break; // DX11: HW to SW
case 13: renderer = 12; break; // OGL: SW to HW
case 12: renderer = 13; break; // OGL: HW to SW
default: renderer = best_sw_renderer; // If wasn't using DX (e.g. SDL), use best SW renderer.
}
#endif
#ifdef _LINUX
switch(renderer) {
case 13: renderer = 12; break; // OGL: SW to HW
case 12: renderer = 13; break; // OGL: HW to SW
}
#endif
}
int retval = _GSopen(dsp, NULL, renderer);
if (s_gs != NULL)
s_gs->SetAspectRatio(0); // PCSX2 manages the aspect ratios
gsopen_done = true;
return retval;
}
EXPORT_C_(int) GSopen(void** dsp, char* title, int mt)
{
/*
if(!XInitThreads()) return -1;
Display* display = XOpenDisplay(0);
XCloseDisplay(display);
*/
int renderer = 0;
// Legacy GUI expects to acquire vsync from the configuration files.
s_vsync = !!theApp.GetConfig("vsync", 0);
if(mt == 2)
{
// pcsx2 sent a switch renderer request
#ifdef _WINDOWS
renderer = GSUtil::CheckDirect3D11Level() >= D3D_FEATURE_LEVEL_10_0 ? 4 : 1; // dx11 / dx9 sw
#endif
mt = 1;
}
else
{
// normal init
renderer = theApp.GetConfig("renderer", 0);
}
*dsp = NULL;
int retval = _GSopen(dsp, title, renderer);
if(retval == 0 && s_gs)
{
s_gs->SetMultithreaded(!!mt);
}
gsopen_done = true;
return retval;
}
EXPORT_C GSreset()
{
try
{
s_gs->Reset();
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSgifSoftReset(uint32 mask)
{
try
{
s_gs->SoftReset(mask);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSwriteCSR(uint32 csr)
{
try
{
s_gs->WriteCSR(csr);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSinitReadFIFO(uint8* mem)
{
try
{
s_gs->InitReadFIFO(mem, 1);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSreadFIFO(uint8* mem)
{
try
{
s_gs->ReadFIFO(mem, 1);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSinitReadFIFO2(uint8* mem, uint32 size)
{
try
{
s_gs->InitReadFIFO(mem, size);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSreadFIFO2(uint8* mem, uint32 size)
{
try
{
s_gs->ReadFIFO(mem, size);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSgifTransfer(const uint8* mem, uint32 size)
{
try
{
s_gs->Transfer<3>(mem, size);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSgifTransfer1(uint8* mem, uint32 addr)
{
try
{
s_gs->Transfer<0>(const_cast<uint8*>(mem) + addr, (0x4000 - addr) / 16);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSgifTransfer2(uint8* mem, uint32 size)
{
try
{
s_gs->Transfer<1>(const_cast<uint8*>(mem), size);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSgifTransfer3(uint8* mem, uint32 size)
{
try
{
s_gs->Transfer<2>(const_cast<uint8*>(mem), size);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C GSvsync(int field)
{
try
{
#ifdef _WINDOWS
if(s_gs->m_wnd->IsManaged())
{
MSG msg;
memset(&msg, 0, sizeof(msg));
while(msg.message != WM_QUIT && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
#endif
s_gs->VSync(field);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C_(uint32) GSmakeSnapshot(char* path)
{
try
{
string s(path);
if(!s.empty() && s[s.length() - 1] != DIRECTORY_SEPARATOR)
{
s = s + DIRECTORY_SEPARATOR;
}
return s_gs->MakeSnapshot(s + "gsdx");
}
catch (GSDXRecoverableError)
{
return false;
}
}
EXPORT_C GSkeyEvent(GSKeyEventData* e)
{
try
{
if (gsopen_done)
s_gs->KeyEvent(e);
}
catch (GSDXRecoverableError)
{
}
}
EXPORT_C_(int) GSfreeze(int mode, GSFreezeData* data)
{
try
{
if(mode == FREEZE_SAVE)
{
return s_gs->Freeze(data, false);
}
else if(mode == FREEZE_SIZE)
{
return s_gs->Freeze(data, true);
}
else if(mode == FREEZE_LOAD)
{
return s_gs->Defrost(data);
}
}
catch (GSDXRecoverableError)
{
}
return 0;
}
EXPORT_C GSconfigure()
{
try
{
if(!GSUtil::CheckSSE()) return;
#ifdef _WINDOWS
if(GSSettingsDlg(s_isgsopen2).DoModal() == IDOK)
{
if(s_gs != NULL && s_gs->m_wnd->IsManaged())
{
// Legacy apps like gsdxgui expect this...
GSshutdown();
}
}
#else
if (RunLinuxDialog()) {
theApp.ReloadConfig();
}
#endif
} catch (GSDXRecoverableError)
{
}
}
EXPORT_C_(int) GStest()
{
if(!GSUtil::CheckSSE())
{
return -1;
}
#ifdef _WINDOWS
s_hr = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
if(!GSUtil::CheckDirectX())
{
if(SUCCEEDED(s_hr))
{
::CoUninitialize();
}
s_hr = E_FAIL;
return -1;
}
if(SUCCEEDED(s_hr))
{
::CoUninitialize();
}
s_hr = E_FAIL;
#endif
return 0;
}
EXPORT_C GSabout()
{
}
EXPORT_C GSirqCallback(void (*irq)())
{
s_irq = irq;
if(s_gs)
{
s_gs->SetIrqCallback(s_irq);
}
}
void pt(const char* str){
struct tm *current;
time_t now;
time(&now);
current = localtime(&now);
printf("%02i:%02i:%02i%s", current->tm_hour, current->tm_min, current->tm_sec, str);
}
EXPORT_C_(int) GSsetupRecording(int start, void* data)
{
if (s_gs == NULL) {
printf("GSdx: no s_gs for recording\n");
return 0;
}
if(start & 1)
{
printf("GSdx: Recording start command\n");
if( s_gs->BeginCapture() )
pt(" - Capture started\n");
}
else
{
printf("GSdx: Recording end command\n");
s_gs->EndCapture();
pt(" - Capture ended\n");
}
return 1;
}
EXPORT_C GSsetGameCRC(uint32 crc, int options)
{
s_gs->SetGameCRC(crc, options);
}
EXPORT_C GSgetLastTag(uint32* tag)
{
s_gs->GetLastTag(tag);
}
EXPORT_C GSgetTitleInfo2(char* dest, size_t length)
{
if (gsopen_done == false) {
//printf("GSdx: GSgetTitleInfo but GSOpen not yet done. Ignoring\n");
return;
}
string s = "GSdx";
// TODO: this gets called from a different thread concurrently with GSOpen (on linux)
if(s_gs == NULL) return;
if(s_gs->m_GStitleInfoBuffer[0])
{
GSAutoLock lock(&s_gs->m_pGSsetTitle_Crit);
s = format("GSdx | %s", s_gs->m_GStitleInfoBuffer);
if(s.size() > length - 1)
{
s = s.substr(0, length - 1);
}
}
strcpy(dest, s.c_str());
}
EXPORT_C GSsetFrameSkip(int frameskip)
{
s_gs->SetFrameSkip(frameskip);
}
EXPORT_C GSsetVsync(int enabled)
{
s_vsync = !!enabled;
if(s_gs)
{
s_gs->SetVSync(s_vsync);
}
}
EXPORT_C GSsetExclusive(int enabled)
{
s_exclusive = !!enabled;
if(s_gs)
{
s_gs->SetVSync(s_vsync);
}
}
EXPORT_C GSsetFrameLimit(int limit)
{
s_framelimit = !!limit;
if(s_gs)
{
s_gs->SetFrameLimit(s_framelimit);
}
}
#ifdef _WINDOWS
#include <io.h>
#include <fcntl.h>
class Console
{
HANDLE m_console;
string m_title;
public:
Console::Console(LPCSTR title, bool open)
: m_console(NULL)
, m_title(title)
{
if(open) Open();
}
Console::~Console()
{
Close();
}
void Console::Open()
{
if(m_console == NULL)
{
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
AllocConsole();
SetConsoleTitle(m_title.c_str());
m_console = GetStdHandle(STD_OUTPUT_HANDLE);
COORD size;
size.X = 100;
size.Y = 300;
SetConsoleScreenBufferSize(m_console, size);
GetConsoleScreenBufferInfo(m_console, &csbiInfo);
SMALL_RECT rect;
rect = csbiInfo.srWindow;
rect.Right = rect.Left + 99;
rect.Bottom = rect.Top + 64;
SetConsoleWindowInfo(m_console, TRUE, &rect);
*stdout = *_fdopen(_open_osfhandle((long)m_console, _O_TEXT), "w");
setvbuf(stdout, NULL, _IONBF, 0);
}
}
void Console::Close()
{
if(m_console != NULL)
{
FreeConsole();
m_console = NULL;
}
}
};
// lpszCmdLine:
// First parameter is the renderer.
// Second parameter is the gs file to load and run.
EXPORT_C GSReplay(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow)
{
int renderer = -1;
{
char* start = lpszCmdLine;
char* end = NULL;
long n = strtol(lpszCmdLine, &end, 10);
if(end > start) {renderer = n; lpszCmdLine = end;}
}
while(*lpszCmdLine == ' ') lpszCmdLine++;
::SetPriorityClass(::GetCurrentProcess(), HIGH_PRIORITY_CLASS);
if(FILE* fp = fopen(lpszCmdLine, "rb"))
{
Console console("GSdx", true);
GSinit();
uint8 regs[0x2000];
GSsetBaseMem(regs);
s_vsync = !!theApp.GetConfig("vsync", 0);
HWND hWnd = NULL;
_GSopen((void**)&hWnd, "", renderer);
uint32 crc;
fread(&crc, 4, 1, fp);
GSsetGameCRC(crc, 0);
GSFreezeData fd;
fread(&fd.size, 4, 1, fp);
fd.data = new uint8[fd.size];
fread(fd.data, fd.size, 1, fp);
GSfreeze(FREEZE_LOAD, &fd);
delete [] fd.data;
fread(regs, 0x2000, 1, fp);
long start = ftell(fp);
GSvsync(1);
struct Packet {uint8 type, param; uint32 size, addr; vector<uint8> buff;};
list<Packet*> packets;
vector<uint8> buff;
int type;
while((type = fgetc(fp)) != EOF)
{
Packet* p = new Packet();
p->type = (uint8)type;
switch(type)
{
case 0:
p->param = (uint8)fgetc(fp);
fread(&p->size, 4, 1, fp);
switch(p->param)
{
case 0:
p->buff.resize(0x4000);
p->addr = 0x4000 - p->size;
fread(&p->buff[p->addr], p->size, 1, fp);
break;
case 1:
case 2:
case 3:
p->buff.resize(p->size);
fread(&p->buff[0], p->size, 1, fp);
break;
}
break;
case 1:
p->param = (uint8)fgetc(fp);
break;
case 2:
fread(&p->size, 4, 1, fp);
break;
case 3:
p->buff.resize(0x2000);
fread(&p->buff[0], 0x2000, 1, fp);
break;
}
packets.push_back(p);
}
Sleep(100);
while(IsWindowVisible(hWnd))
{
for(list<Packet*>::iterator i = packets.begin(); i != packets.end(); i++)
{
Packet* p = *i;
switch(p->type)
{
case 0:
switch(p->param)
{
case 0: GSgifTransfer1(&p->buff[0], p->addr); break;
case 1: GSgifTransfer2(&p->buff[0], p->size / 16); break;
case 2: GSgifTransfer3(&p->buff[0], p->size / 16); break;
case 3: GSgifTransfer(&p->buff[0], p->size / 16); break;
}
break;
case 1:
GSvsync(p->param);
break;
case 2:
if(buff.size() < p->size) buff.resize(p->size);
GSreadFIFO2(&buff[0], p->size / 16);
break;
case 3:
memcpy(regs, &p->buff[0], 0x2000);
break;
}
}
}
for(list<Packet*>::iterator i = packets.begin(); i != packets.end(); i++)
{
delete *i;
}
packets.clear();
Sleep(100);
/*
vector<uint8> buff;
bool exit = false;
int round = 0;
while(!exit)
{
uint32 index;
uint32 size;
uint32 addr;
int pos;
switch(fgetc(fp))
{
case EOF:
fseek(fp, start, 0);
exit = !IsWindowVisible(hWnd);
//exit = ++round == 60;
break;
case 0:
index = fgetc(fp);
fread(&size, 4, 1, fp);
switch(index)
{
case 0:
if(buff.size() < 0x4000) buff.resize(0x4000);
addr = 0x4000 - size;
fread(&buff[addr], size, 1, fp);
GSgifTransfer1(&buff[0], addr);
break;
case 1:
if(buff.size() < size) buff.resize(size);
fread(&buff[0], size, 1, fp);
GSgifTransfer2(&buff[0], size / 16);
break;
case 2:
if(buff.size() < size) buff.resize(size);
fread(&buff[0], size, 1, fp);
GSgifTransfer3(&buff[0], size / 16);
break;
case 3:
if(buff.size() < size) buff.resize(size);
fread(&buff[0], size, 1, fp);
GSgifTransfer(&buff[0], size / 16);
break;
}
break;
case 1:
GSvsync(fgetc(fp));
exit = !IsWindowVisible(hWnd);
break;
case 2:
fread(&size, 4, 1, fp);
if(buff.size() < size) buff.resize(size);
GSreadFIFO2(&buff[0], size / 16);
break;
case 3:
fread(regs, 0x2000, 1, fp);
break;
}
}
*/
GSclose();
GSshutdown();
fclose(fp);
}
}
EXPORT_C GSBenchmark(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow)
{
::SetPriorityClass(::GetCurrentProcess(), HIGH_PRIORITY_CLASS);
FILE* file = fopen("c:\\temp1\\log.txt", "a");
fprintf(file, "-------------------------\n\n");
if(1)
{
GSLocalMemory * pMem = new GSLocalMemory();
GSLocalMemory& mem(*pMem);
static struct {int psm; const char* name;} s_format[] =
{
{PSM_PSMCT32, "32"},
{PSM_PSMCT24, "24"},
{PSM_PSMCT16, "16"},
{PSM_PSMCT16S, "16S"},
{PSM_PSMT8, "8"},
{PSM_PSMT4, "4"},
{PSM_PSMT8H, "8H"},
{PSM_PSMT4HL, "4HL"},
{PSM_PSMT4HH, "4HH"},
{PSM_PSMZ32, "32Z"},
{PSM_PSMZ24, "24Z"},
{PSM_PSMZ16, "16Z"},
{PSM_PSMZ16S, "16ZS"},
};
uint8* ptr = (uint8*)_aligned_malloc(1024 * 1024 * 4, 32);
for(int i = 0; i < 1024 * 1024 * 4; i++) ptr[i] = (uint8)i;
//
for(int tbw = 5; tbw <= 10; tbw++)
{
int n = 256 << ((10 - tbw) * 2);
int w = 1 << tbw;
int h = 1 << tbw;
fprintf(file, "%d x %d\n\n", w, h);
for(size_t i = 0; i < countof(s_format); i++)
{
const GSLocalMemory::psm_t& psm = GSLocalMemory::m_psm[s_format[i].psm];
GSLocalMemory::writeImage wi = psm.wi;
GSLocalMemory::readImage ri = psm.ri;
GSLocalMemory::readTexture rtx = psm.rtx;
GSLocalMemory::readTexture rtxP = psm.rtxP;
GIFRegBITBLTBUF BITBLTBUF;
BITBLTBUF.SBP = 0;
BITBLTBUF.SBW = w / 64;
BITBLTBUF.SPSM = s_format[i].psm;
BITBLTBUF.DBP = 0;
BITBLTBUF.DBW = w / 64;
BITBLTBUF.DPSM = s_format[i].psm;
GIFRegTRXPOS TRXPOS;
TRXPOS.SSAX = 0;
TRXPOS.SSAY = 0;
TRXPOS.DSAX = 0;
TRXPOS.DSAY = 0;
GIFRegTRXREG TRXREG;
TRXREG.RRW = w;
TRXREG.RRH = h;
GSVector4i r(0, 0, w, h);
GIFRegTEX0 TEX0;
TEX0.TBP0 = 0;
TEX0.TBW = w / 64;
GIFRegTEXA TEXA;
TEXA.TA0 = 0;
TEXA.TA1 = 0x80;
TEXA.AEM = 0;
int trlen = w * h * psm.trbpp / 8;
int len = w * h * psm.bpp / 8;
clock_t start, end;
_ftprintf(file, _T("[%4s] "), s_format[i].name);
start = clock();
for(int j = 0; j < n; j++)
{
int x = 0;
int y = 0;
(mem.*wi)(x, y, ptr, trlen, BITBLTBUF, TRXPOS, TRXREG);
}
end = clock();
fprintf(file, "%6d %6d | ", (int)((float)trlen * n / (end - start) / 1000), (int)((float)(w * h) * n / (end - start) / 1000));
start = clock();
for(int j = 0; j < n; j++)
{
int x = 0;
int y = 0;
(mem.*ri)(x, y, ptr, trlen, BITBLTBUF, TRXPOS, TRXREG);
}
end = clock();
fprintf(file, "%6d %6d | ", (int)((float)trlen * n / (end - start) / 1000), (int)((float)(w * h) * n / (end - start) / 1000));
const GSOffset* o = mem.GetOffset(TEX0.TBP0, TEX0.TBW, TEX0.PSM);
start = clock();
for(int j = 0; j < n; j++)
{
(mem.*rtx)(o, r, ptr, w * 4, TEXA);
}
end = clock();
fprintf(file, "%6d %6d ", (int)((float)len * n / (end - start) / 1000), (int)((float)(w * h) * n / (end - start) / 1000));
if(psm.pal > 0)
{
start = clock();
for(int j = 0; j < n; j++)
{
(mem.*rtxP)(o, r, ptr, w, TEXA);
}
end = clock();
fprintf(file, "| %6d %6d ", (int)((float)len * n / (end - start) / 1000), (int)((float)(w * h) * n / (end - start) / 1000));
}
fprintf(file, "\n");
fflush(file);
}
fprintf(file, "\n");
}
_aligned_free(ptr);
delete pMem;
}
//
if(0)
{
GSLocalMemory * pMem2 = new GSLocalMemory();
GSLocalMemory& mem2(*pMem2);
uint8* ptr = (uint8*)_aligned_malloc(1024 * 1024 * 4, 32);
for(int i = 0; i < 1024 * 1024 * 4; i++) ptr[i] = (uint8)i;
const GSLocalMemory::psm_t& psm = GSLocalMemory::m_psm[PSM_PSMCT32];
GSLocalMemory::writeImage wi = psm.wi;
GIFRegBITBLTBUF BITBLTBUF;
BITBLTBUF.DBP = 0;
BITBLTBUF.DBW = 32;
BITBLTBUF.DPSM = PSM_PSMCT32;
GIFRegTRXPOS TRXPOS;
TRXPOS.DSAX = 0;
TRXPOS.DSAY = 1;
GIFRegTRXREG TRXREG;
TRXREG.RRW = 256;
TRXREG.RRH = 256;
int trlen = 256 * 256 * psm.trbpp / 8;
int x = 0;
int y = 0;
(mem2.*wi)(x, y, ptr, trlen, BITBLTBUF, TRXPOS, TRXREG);
delete pMem2;
}
//
fclose(file);
PostQuitMessage(0);
}
#endif
#ifdef _LINUX
#include <sys/time.h>
#include <sys/timeb.h> // ftime(), struct timeb
inline unsigned long timeGetTime()
{
timeb t;
ftime(&t);
return (unsigned long)(t.time*1000 + t.millitm);
}
void _fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
static uint32 read_cnt = 0;
read_cnt++;
size_t result = fread(ptr, size, nmemb, stream);
if (result != nmemb) {
fprintf(stderr, "Read error\n");
exit(read_cnt);
}
}
// Note
EXPORT_C GSReplay(char* lpszCmdLine, int renderer)
{
GLLoader::in_replayer = true;
// lpszCmdLine:
// First parameter is the renderer.
// Second parameter is the gs file to load and run.
//EXPORT_C GSReplay(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow)
#if 0
int renderer = -1;
{
char* start = lpszCmdLine;
char* end = NULL;
long n = strtol(lpszCmdLine, &end, 10);
if(end > start) {renderer = n; lpszCmdLine = end;}
}
while(*lpszCmdLine == ' ') lpszCmdLine++;
::SetPriorityClass(::GetCurrentProcess(), HIGH_PRIORITY_CLASS);
#endif
// Allow to easyly switch between SW/HW renderer
renderer = theApp.GetConfig("renderer", 12);
if (renderer != 12 && renderer != 13)
{
fprintf(stderr, "wrong renderer selected %d\n", renderer);
return;
}
vector<float> stats;
stats.clear();
if(FILE* fp = fopen(lpszCmdLine, "rb"))
{
//Console console("GSdx", true);
GSinit();
uint8 regs[0x2000];
GSsetBaseMem(regs);
s_vsync = !!theApp.GetConfig("vsync", 0);
void* hWnd = NULL;
int err = _GSopen((void**)&hWnd, "", renderer);
if (err != 0) {
fprintf(stderr, "Error failed to GSopen\n");
return;
}
if (s_gs->m_wnd == NULL) return;
uint32 crc;
_fread(&crc, 4, 1, fp);
GSsetGameCRC(crc, 0);
GSFreezeData fd;
_fread(&fd.size, 4, 1, fp);
fd.data = new uint8[fd.size];
_fread(fd.data, fd.size, 1, fp);
GSfreeze(FREEZE_LOAD, &fd);
delete [] fd.data;
_fread(regs, 0x2000, 1, fp);
GSvsync(1);
struct Packet {uint8 type, param; uint32 size, addr; vector<uint8> buff;};
list<Packet*> packets;
vector<uint8> buff;
int type;
while((type = fgetc(fp)) != EOF)
{
Packet* p = new Packet();
p->type = (uint8)type;
switch(type)
{
case 0:
p->param = (uint8)fgetc(fp);
_fread(&p->size, 4, 1, fp);
switch(p->param)
{
case 0:
p->buff.resize(0x4000);
p->addr = 0x4000 - p->size;
_fread(&p->buff[p->addr], p->size, 1, fp);
break;
case 1:
case 2:
case 3:
p->buff.resize(p->size);
_fread(&p->buff[0], p->size, 1, fp);
break;
}
break;
case 1:
p->param = (uint8)fgetc(fp);
break;
case 2:
_fread(&p->size, 4, 1, fp);
break;
case 3:
p->buff.resize(0x2000);
_fread(&p->buff[0], 0x2000, 1, fp);
break;
}
packets.push_back(p);
}
sleep(1);
//while(IsWindowVisible(hWnd))
//FIXME map?
int finished = theApp.GetConfig("linux_replay", 1);
unsigned long frame_number = 0;
while(finished > 0)
{
frame_number = 0;
unsigned long start = timeGetTime();
for(auto i = packets.begin(); i != packets.end(); i++)
{
Packet* p = *i;
switch(p->type)
{
case 0:
switch(p->param)
{
case 0: GSgifTransfer1(&p->buff[0], p->addr); break;
case 1: GSgifTransfer2(&p->buff[0], p->size / 16); break;
case 2: GSgifTransfer3(&p->buff[0], p->size / 16); break;
case 3: GSgifTransfer(&p->buff[0], p->size / 16); break;
}
break;
case 1:
GSvsync(p->param);
frame_number++;
break;
case 2:
if(buff.size() < p->size) buff.resize(p->size);
GSreadFIFO2(&buff[0], p->size / 16);
break;
case 3:
memcpy(regs, &p->buff[0], 0x2000);
break;
}
}
unsigned long end = timeGetTime();
fprintf(stderr, "The %ld frames of the scene was render on %ldms\n", frame_number, end - start);
fprintf(stderr, "A means of %fms by frame\n", (float)(end - start)/(float)frame_number);
stats.push_back((float)(end - start));
sleep(1);
finished--;
}
if (theApp.GetConfig("linux_replay", 1) > 1) {
// Print some nice stats
// Skip first frame (shader compilation populate the result)
// it divides by 10 the standard deviation...
float n = (float)theApp.GetConfig("linux_replay", 1) - 1.0f;
float mean = 0;
float sd = 0;
for (auto i = stats.begin()+1; i != stats.end(); i++) {
mean += *i;
}
mean = mean/n;
for (auto i = stats.begin()+1; i != stats.end(); i++) {
sd += pow((*i)-mean, 2);
}
sd = sqrt(sd/n);
fprintf(stderr, "\n\nMean: %fms\n", mean);
fprintf(stderr, "Standard deviation: %fms\n", sd);
fprintf(stderr, "Mean by frame: %fms (%ffps)\n", mean/(float)frame_number, 1000.0f*frame_number/mean);
fprintf(stderr, "Standard deviatin by frame: %fms\n", sd/(float)frame_number);
}
#ifdef ENABLE_OGL_DEBUG_MEM_BW
fprintf(stderr, "memory bandwith. T: %f. V: %f\n", (float)g_texture_upload_byte/(float)frame_number/1024, (float)g_vertex_upload_byte/(float)frame_number/1024);
#endif
for(auto i = packets.begin(); i != packets.end(); i++)
{
delete *i;
}
packets.clear();
sleep(1);
GSclose();
GSshutdown();
fclose(fp);
} else {
fprintf(stderr, "failed to open %s\n", lpszCmdLine);
}
}
#endif
| aktau/pcsx2 | plugins/GSdx/GS.cpp | C++ | gpl-2.0 | 29,172 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest14967")
public class BenchmarkTest14967 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getHeader("foo");
String bar = doSomething(param);
Object[] obj = { "a", "b" };
response.getWriter().format(java.util.Locale.US,bar,obj);
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
String bar = "safe!";
java.util.HashMap<String,Object> map83646 = new java.util.HashMap<String,Object>();
map83646.put("keyA-83646", "a Value"); // put some stuff in the collection
map83646.put("keyB-83646", param.toString()); // put it in a collection
map83646.put("keyC", "another Value"); // put some stuff in the collection
bar = (String)map83646.get("keyB-83646"); // get it back out
return bar;
}
}
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest14967.java | Java | gpl-2.0 | 2,214 |
<?php
/*
* File contains csutom defined shortcuts
*/
function oxy_load_child_scripts() {
wp_enqueue_style('child-style', get_stylesheet_directory_uri() . '/style.css', array('style'), false, 'all');
}
add_action('wp_enqueue_scripts', 'oxy_load_child_scripts');
//validation for custom taxonomy
//add_action('save_post', 'completion_validator', 10, 2);
function completion_validator($pid, $post) {
// don't do on autosave or when new posts are first created
if (( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) || $post->post_status == 'auto-draft')
return $pid;
// abort if not my custom type
if ($post->post_type != 'oxy_content')
return $pid;
// init completion marker (add more as needed)
$category_missing = false;
$more_then_one_assigned = false;
$summary_missing = false;
// retrieve meta to be validated
$assignedCategory = wp_get_post_terms($pid, 'oxy_content_category', array("fields" => "all"));
// just checking it's not empty
if (empty($assignedCategory)) {
$category_missing = true;
}
if (!$category_missing && count($assignedCategory) > 1) {
$more_then_one_assigned = true;
}
//get value of summary
$summary = get_field('summary', $post->ID);
if (empty($summary)) {
$summary_missing = true;
}
// on attempting to publish - check for completion and intervene if necessary
if (( isset($_POST['publish']) || isset($_POST['save']) ) && $_POST['post_status'] == 'publish') {
// don't allow publishing while any of these are incomplete
if ($category_missing || $more_then_one_assigned || $summary_missing) {
global $wpdb;
$wpdb->update($wpdb->posts, array('post_status' => 'pending'), array('ID' => $pid));
// filter the query URL to change the published message
if ($category_missing) {
$message_number = $summary_missing ? 100 : 99;
$filter_name = $summary_missing ? 'redirect_no_one_assigned_and_no_summary' : 'redirect_no_one_assigned';
} else if ($more_then_one_assigned) {
$message_number = $summary_missing ? 97 : 98;
$filter_name = $summary_missing ? 'redirect_more_then_one_assigned_and_no_summary' : 'redirect_more_then_one_assigned';
} else if ($summary_missing) {
$message_number = 101;
$filter_name = 'redirect_no_summary_assigned';
}
add_filter('redirect_post_location', $filter_name, $message_number);
}
}
}
function redirect_no_summary_assigned($location) {
remove_filter('redirect_post_location', __FUNCTION__, 101);
$location = add_query_arg('message', 101, $location);
return $location;
}
function redirect_no_one_assigned_and_no_summary($location) {
remove_filter('redirect_post_location', __FUNCTION__, 100);
$location = add_query_arg('message', 100, $location);
return $location;
}
function redirect_no_one_assigned($location) {
remove_filter('redirect_post_location', __FUNCTION__, 99);
$location = add_query_arg('message', 99, $location);
return $location;
}
function redirect_more_then_one_assigned($location) {
remove_filter('redirect_post_location', __FUNCTION__, 98);
$location = add_query_arg('message', 98, $location);
return $location;
}
function redirect_more_then_one_assigned_and_no_summary($location) {
remove_filter('redirect_post_location', __FUNCTION__, 97);
$location = add_query_arg('message', 97, $location);
return $location;
}
add_filter('post_updated_messages', 'my_post_updated_messages_filter');
function my_post_updated_messages_filter($messages) {
$messages['post'][97] = __('Publish not allowed, more then one category assigned. Please select exact one category. And fill the summary.', THEME_FRONT_TD);
$messages['post'][98] = __('Publish not allowed, more then one category assigned. Please select exact one category', THEME_FRONT_TD);
$messages['post'][99] = __('Publish not allowed, please select one category', THEME_FRONT_TD);
$messages['post'][100] = __('Publish not allowed, please select one category. And fill the summary.', THEME_FRONT_TD);
$messages['post'][101] = __('Publish not allowed, please fill the summary.', THEME_FRONT_TD);
return $messages;
}
Class Recent_Bloggers extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'wpb_widget',
// Widget name will appear in UI
__('Recent Bloggers', 'wpb_widget_domain'),
// Widget description
array('description' => __('Самые крутые блоггеры', 'wpb_widget_domain'),)
);
}
function widget($args, $instance) {
extract($args);
$title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Bloggers', THEME_FRONT_TD) : $instance['title'], $instance, $this->id_base);
if (empty($instance['number']) || !$number = absint($instance['number']))
$number = 5;
$user_query = new WP_User_Query(array('orderby' => 'post_count', 'order' => 'DESC')); //new WP_Query( apply_filters( 'widget_posts_args', array( 'posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true ) ) );
// User Loop
if (!empty($user_query->results)) {
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title;
?>
<ul>
<?php
$counter = 0;
foreach ($user_query->results as $user) {
++$counter;
if ( count_user_posts( $user->id ) == 0 ) continue;
?>
<div class="row-fluid">
<div class="span3">
<div class="round-box box-mini box-colored">
<?php echo get_avatar($user->ID, 300); ?>
</div>
</div>
<div class="span9">
<h4>
<?php echo $user->display_name; ?>
</h4>
</div>
</div>
<?php if($counter == $number) break;} ?>
</ul>
<?php
echo $after_widget;
wp_reset_postdata();
} else {
echo 'No users found.';
}
}
function form( $instance ) {
$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
$number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
?>
<p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /></p>
<p><label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts to show:' ); ?></label>
<input id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="text" value="<?php echo $number; ?>" size="3" /></p>
<?php
}
}
// replace default widgets
register_widget('Recent_Bloggers');
Class Taxonomy_Topics extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'wpb_widget_taxonomy_topics',
// Widget name will appear in UI
__('Taxonomy Topics', 'wpb_widget_taxonomy_topics'),
// Widget description
array('description' => __('Taxonomy topics for archive', 'wpb_widget_taxonomy_topics'),)
);
}
function widget($args, $instance) {
extract($args);
$title = apply_filters('widget_title', empty($instance['title']) ? __('Taxonomy Topics', THEME_FRONT_TD) : $instance['title'], $instance, $this->id_base);
$post_type = isset( $instance['post_type'] ) ? esc_attr( $instance['post_type'] ) : 'oxy_content';
echo $before_widget;
echo hb_ui_taxonomy_terms_cloud($post_type, $title);
echo $after_widget;
}
function form( $instance ) {
$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
$post_type = isset( $instance['post_type'] ) ? esc_attr( $instance['post_type'] ) : 'oxy_content';
?>
<p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /></p>
<p><label for="<?php echo $this->get_field_id( 'post_type' ); ?>"><?php _e( 'Type of posts to show:' ); ?></label>
<input id="<?php echo $this->get_field_id( 'post_type' ); ?>" name="<?php echo $this->get_field_name( 'post_type' ); ?>" type="text" value="<?php echo $post_type; ?>"/></p>
<?php
}
}
// replace default widgets
register_widget('Taxonomy_Topics');
Class Custom_Search extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'wpb_widget_custom_search',
// Widget name will appear in UI
__('Custom Search', 'wpb_widget_custom_search'),
// Widget description
array('description' => __('Search for custom post types', 'wpb_widget_custom_search'),)
);
}
function widget($args, $instance) {
extract($args);
$title = apply_filters('widget_title', empty($instance['title']) ? __('Taxonomy Topics', THEME_FRONT_TD) : $instance['title'], $instance, $this->id_base);
$post_type = isset( $instance['post_type'] ) ? esc_attr( $instance['post_type'] ) : 'oxy_content';
if(empty($title))
$title = __('Search', THEME_FRONT_TD);
echo $before_widget;
if($post_type === 'oxy_video')
include( CUSTOM_THEME_DIR . 'searchform_sidebar_videos.php');
elseif ($post_type === 'oxy_content')
include( CUSTOM_THEME_DIR . 'searchform_sidebar_texts.php');
echo $after_widget;
}
function form( $instance ) {
$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
$post_type = isset( $instance['post_type'] ) ? esc_attr( $instance['post_type'] ) : 'oxy_content';
?>
<p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /></p>
<p><label for="<?php echo $this->get_field_id( 'post_type' ); ?>"><?php _e( 'Type of posts to show:' ); ?></label>
<input id="<?php echo $this->get_field_id( 'post_type' ); ?>" name="<?php echo $this->get_field_name( 'post_type' ); ?>" type="text" value="<?php echo $post_type; ?>"/></p>
<?php
}
}
// replace default widgets
register_widget('Custom_Search');
Class Archive_Custom_Types extends WP_Widget {
function __construct() {
parent::__construct(
// Base ID of your widget
'wp_widget_archive_custom_types',
// Widget name will appear in UI
__('Archive Custom Types', 'wp_widget_archive_custom_types'),
// Widget description
array('description' => __('Archive for custom post types', 'wp_widget_archive_custom_types'),)
);
}
function widget($args, $instance) {
extract($args);
$title = apply_filters('widget_title', empty($instance['title']) ? __('Archive', THEME_FRONT_TD) : $instance['title'], $instance, $this->id_base);
$post_type = isset( $instance['post_type'] ) ? esc_attr( $instance['post_type'] ) : 'oxy_content';
$args = array('post_type' => $post_type, 'show_post_count' => true,'echo' => 0, 'before' => '<h4>',
'after' => '</h4>', 'format' => 'custom');
$output = '<div >';
$output .= ' <h3 class="sidebar-header">'.$title.'</h3>';
$output .= '<ul>';
$output .= wp_get_archives_cpt( $args );
$output .= '</ul>';
$output .= '</div></hr>';
echo $before_widget;
echo $output;
echo $after_widget;
}
function form( $instance ) {
$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
$post_type = isset( $instance['post_type'] ) ? esc_attr( $instance['post_type'] ) : 'oxy_content';
?>
<p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /></p>
<p><label for="<?php echo $this->get_field_id( 'post_type' ); ?>"><?php _e( 'Type of posts to show:' ); ?></label>
<input id="<?php echo $this->get_field_id( 'post_type' ); ?>" name="<?php echo $this->get_field_name( 'post_type' ); ?>" type="text" value="<?php echo $post_type; ?>"/></p>
<?php
}
}
// replace default widgets
register_widget('Archive_Custom_Types');
function template_chooser($template) {
global $wp_query;
$post_type = get_query_var('post_type');
if(($wp_query->is_search or $wp_query->is_archive) && $post_type == 'oxy_video' ){
return locate_template('page-videoarchive.php'); // redirect to page-videos.php
}elseif(($wp_query->is_search or $wp_query->is_archive) && $post_type == 'oxy_content' ){
return locate_template('page-archive.php'); // redirect to page-texts.php
}
return $template;
}
add_filter('template_include', 'template_chooser');
?> | andriysobol/holybunch_preprod | wp-content/themes/smartbox-theme-custom/inc/hb_functions.php | PHP | gpl-2.0 | 13,674 |
<?php
class jaw_message {
private $_data = array();
private $_tmpl;
public function __construct($tmpl = null) {
$this->class_name = get_class();
if (isset($tmpl)) {
$this->_tmpl = $tmpl;
} else {
$this->_tmpl = substr($this->class_name, 4);
}
add_shortcode($this->class_name, array($this, $this->class_name . '_shortcode'));
}
public function jaw_message_shortcode($atts, $content = null, $code = null) {
jaw_template_set_data($this->model((array) $atts, $content));
return jaw_get_template_part($this->_tmpl, 'simple-shortcodes');
}
private function model($atts, $content = '') {
extract(shortcode_atts(array(
'message_style' => 'success',
'message_text' => ''
), $atts));
$atts['message_style'] = $message_style;
if ($message_text != '') {
$atts['message_text'] = $message_text;
} else {
$atts['message_text'] = $content;
}
if (isset($atts['box_size'])) {
$atts['box_size'] = $atts['box_size'];
} else {
$atts['box_size'] = 'max';
}
return $atts;
}
}
| thanhtrantv/car-wp | wp-content/plugins/jaw-shortcodes/shortcodes/jaw_message.php | PHP | gpl-2.0 | 1,243 |
#line 3 "<stdout>"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define yy_create_buffer defargsYY_create_buffer
#define yy_delete_buffer defargsYY_delete_buffer
#define yy_flex_debug defargsYY_flex_debug
#define yy_init_buffer defargsYY_init_buffer
#define yy_flush_buffer defargsYY_flush_buffer
#define yy_load_buffer_state defargsYY_load_buffer_state
#define yy_switch_to_buffer defargsYY_switch_to_buffer
#define yyin defargsYYin
#define yyleng defargsYYleng
#define yylex defargsYYlex
#define yylineno defargsYYlineno
#define yyout defargsYYout
#define yyrestart defargsYYrestart
#define yytext defargsYYtext
#define yywrap defargsYYwrap
#define yyalloc defargsYYalloc
#define yyrealloc defargsYYrealloc
#define yyfree defargsYYfree
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 35
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
#endif /* ! C99 */
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE defargsYYrestart(defargsYYin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 262144
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
extern int defargsYYleng;
extern FILE *defargsYYin, *defargsYYout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
#define YY_LESS_LINENO(n)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up defargsYYtext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up defargsYYtext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via defargsYYrestart()), so that the user can continue scanning by
* just pointing defargsYYin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when defargsYYtext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
int defargsYYleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow defargsYYwrap()'s to do buffer switches
* instead of setting up a fresh defargsYYin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void defargsYYrestart (FILE *input_file );
void defargsYY_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE defargsYY_create_buffer (FILE *file,int size );
void defargsYY_delete_buffer (YY_BUFFER_STATE b );
void defargsYY_flush_buffer (YY_BUFFER_STATE b );
void defargsYYpush_buffer_state (YY_BUFFER_STATE new_buffer );
void defargsYYpop_buffer_state (void );
static void defargsYYensure_buffer_stack (void );
static void defargsYY_load_buffer_state (void );
static void defargsYY_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER defargsYY_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE defargsYY_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE defargsYY_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE defargsYY_scan_bytes (yyconst char *bytes,int len );
void *defargsYYalloc (yy_size_t );
void *defargsYYrealloc (void *,yy_size_t );
void defargsYYfree (void * );
#define yy_new_buffer defargsYY_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
defargsYYensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
defargsYY_create_buffer(defargsYYin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
defargsYYensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
defargsYY_create_buffer(defargsYYin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define defargsYYwrap(n) 1
#define YY_SKIP_YYWRAP
typedef unsigned char YY_CHAR;
FILE *defargsYYin = (FILE *) 0, *defargsYYout = (FILE *) 0;
typedef int yy_state_type;
extern int defargsYYlineno;
int defargsYYlineno = 1;
extern char *defargsYYtext;
#define yytext_ptr defargsYYtext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up defargsYYtext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
defargsYYleng = (size_t) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 56
#define YY_END_OF_BUFFER 57
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_acclist[291] =
{ 0,
2, 2, 57, 55, 56, 54, 56, 55, 56, 1,
55, 56, 36, 55, 56, 29, 36, 55, 56, 36,
55, 56, 36, 55, 56, 36, 55, 56, 36, 55,
56, 36, 55, 56, 36, 55, 56, 38, 55, 56,
16, 38, 55, 56, 17, 18, 38, 55, 56, 38,
55, 56, 37, 38, 55, 56, 17, 38, 55, 56,
23, 38, 55, 56, 24, 38, 55, 56, 21, 38,
55, 56, 22, 38, 55, 56, 25, 38, 55, 56,
26, 38, 55, 56, 34, 55, 56, 2, 34, 55,
56, 34, 55, 56, 15, 34, 55, 56, 32, 34,
55, 56, 34, 55, 56, 34, 55, 56, 15, 34,
55, 56, 30, 34, 55, 56, 32, 34, 55, 56,
33, 34, 55, 56, 34, 55, 56, 15, 34, 55,
56, 8, 36, 55, 56, 36, 55, 56, 15, 36,
55, 56, 32, 36, 55, 56, 15, 36, 55, 56,
32, 36, 55, 56, 36, 55, 56, 36, 55, 56,
36, 55, 56, 13, 34, 55, 56, 10, 33, 34,
55, 56, 55, 56, 55, 56, 55, 56, 55, 56,
55, 56, 47, 52, 55, 56, 51, 54, 56, 52,
55, 56, 47, 52, 55, 56, 48, 55, 56, 50,
54, 56, 48, 55, 56, 44, 55, 56, 44, 55,
56, 45, 54, 56, 44, 55, 56, 44, 55, 56,
35, 27, 28, 18, 17, 37, 19, 20, 2, 33,
16393, 14, 33, 3, 11, 12, 10, 33, 42, 41,
47, 49, 47, 48, 48, 48, 53, 28, 17, 17,
16393, 8201, 6, 6, 7, 46, 47, 53, 48, 53,
53, 28, 8201, 5, 4, 5, 47, 53, 48, 53,
28, 31, 4, 39, 28, 43, 28, 43, 28, 40,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28
} ;
static yyconst flex_int16_t yy_accept[244] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 2, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 4, 6, 8, 10, 13, 16, 20, 23, 26,
29, 32, 35, 38, 41, 45, 50, 53, 57, 61,
65, 69, 73, 77, 81, 85, 88, 92, 95, 99,
103, 106, 109, 113, 117, 121, 125, 128, 132, 136,
139, 143, 147, 151, 155, 158, 161, 164, 168, 173,
175, 177, 179, 181, 183, 187, 190, 193, 197, 200,
203, 206, 209, 212, 215, 218, 221, 221, 221, 222,
223, 223, 224, 225, 226, 227, 227, 228, 229, 230,
231, 231, 231, 232, 232, 232, 233, 234, 234, 235,
235, 235, 235, 235, 235, 235, 236, 237, 239, 239,
239, 240, 240, 241, 241, 241, 242, 243, 244, 245,
246, 247, 247, 247, 248, 248, 249, 250, 251, 251,
251, 251, 252, 253, 253, 253, 254, 254, 255, 255,
255, 256, 256, 257, 257, 257, 259, 261, 261, 261,
262, 262, 263, 263, 264, 264, 265, 267, 267, 267,
267, 267, 269, 271, 271, 271, 271, 272, 273, 274,
274, 274, 275, 275, 275, 275, 275, 276, 276, 276,
277, 277, 277, 278, 278, 278, 279, 279, 279, 280,
280, 281, 281, 281, 282, 282, 282, 283, 283, 283,
284, 284, 284, 285, 285, 285, 286, 286, 286, 287,
287, 287, 288, 288, 288, 289, 289, 289, 290, 290,
291, 291, 291
} ;
static yyconst flex_int32_t yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 4, 5, 1, 6, 1, 7, 8, 9,
10, 11, 1, 12, 13, 1, 14, 15, 16, 16,
16, 16, 16, 16, 16, 17, 18, 19, 1, 20,
21, 22, 1, 1, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 24, 23, 23, 23, 23,
23, 25, 23, 23, 26, 23, 23, 23, 23, 23,
27, 28, 29, 7, 23, 1, 30, 23, 31, 32,
33, 34, 23, 23, 35, 23, 23, 36, 23, 37,
38, 23, 23, 39, 40, 41, 42, 43, 23, 23,
23, 23, 44, 1, 45, 1, 1, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23
} ;
static yyconst flex_int32_t yy_meta[46] =
{ 0,
1, 2, 3, 1, 1, 1, 1, 1, 4, 5,
6, 1, 1, 1, 7, 7, 7, 7, 8, 1,
1, 1, 9, 9, 9, 9, 1, 10, 1, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 1, 1
} ;
static yyconst flex_int16_t yy_base[294] =
{ 0,
0, 1, 2, 3, 21, 47, 15, 17, 75, 0,
796, 790, 35, 44, 27, 29, 120, 0, 163, 0,
207, 0, 250, 291, 37, 167, 5, 7, 44, 177,
799, 877, 877, 19, 877, 877, 877, 775, 45, 42,
171, 0, 786, 877, 877, 786, 183, 0, 780, 877,
877, 761, 757, 877, 877, 877, 771, 0, 188, 172,
748, 189, 181, 877, 252, 0, 735, 877, 877, 735,
877, 182, 235, 255, 736, 750, 242, 256, 0, 5,
730, 167, 708, 707, 0, 877, 729, 261, 0, 877,
268, 877, 246, 877, 274, 276, 257, 282, 877, 877,
732, 729, 726, 293, 0, 725, 877, 877, 723, 0,
268, 295, 333, 301, 278, 877, 0, 690, 877, 708,
305, 705, 700, 682, 298, 877, 877, 0, 296, 672,
877, 314, 877, 661, 656, 0, 877, 313, 0, 315,
314, 656, 646, 663, 675, 669, 330, 0, 322, 654,
331, 2, 376, 326, 335, 877, 663, 657, 345, 653,
877, 627, 877, 615, 623, 627, 624, 601, 604, 877,
630, 624, 420, 0, 606, 877, 877, 417, 611, 578,
576, 0, 0, 571, 559, 584, 580, 877, 877, 575,
573, 877, 546, 544, 535, 568, 566, 553, 519, 550,
513, 534, 520, 512, 485, 510, 477, 503, 502, 497,
877, 472, 499, 493, 488, 490, 481, 421, 424, 423,
417, 419, 418, 377, 357, 350, 345, 346, 338, 327,
326, 294, 281, 257, 201, 195, 162, 65, 59, 877,
33, 877, 433, 443, 453, 463, 473, 483, 493, 501,
504, 19, 513, 517, 526, 536, 540, 549, 559, 569,
577, 586, 596, 605, 615, 624, 633, 642, 651, 660,
669, 678, 687, 696, 705, 714, 723, 732, 741, 750,
759, 768, 777, 786, 795, 804, 813, 822, 831, 840,
849, 858, 867
} ;
static yyconst flex_int16_t yy_def[294] =
{ 0,
243, 243, 243, 243, 244, 244, 244, 244, 242, 9,
9, 9, 9, 9, 9, 9, 242, 17, 244, 19,
242, 21, 243, 243, 245, 245, 246, 246, 247, 247,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 248, 249, 242, 242, 250, 242, 251, 250, 242,
242, 242, 242, 242, 242, 242, 242, 252, 253, 242,
242, 242, 242, 242, 242, 254, 255, 242, 242, 256,
242, 242, 242, 242, 242, 242, 242, 242, 257, 242,
242, 242, 242, 242, 258, 242, 242, 258, 259, 242,
259, 242, 242, 242, 242, 242, 242, 242, 242, 242,
260, 260, 250, 261, 251, 250, 242, 242, 242, 254,
253, 253, 253, 242, 242, 242, 254, 255, 242, 242,
262, 242, 263, 242, 242, 242, 242, 257, 242, 264,
242, 242, 242, 242, 242, 258, 242, 258, 259, 259,
259, 242, 242, 242, 265, 265, 261, 147, 253, 242,
253, 113, 242, 242, 242, 242, 242, 242, 242, 266,
242, 264, 242, 242, 242, 258, 259, 242, 242, 242,
267, 267, 253, 153, 242, 242, 242, 242, 268, 242,
242, 258, 259, 242, 242, 269, 269, 242, 242, 242,
270, 242, 242, 242, 242, 271, 271, 272, 242, 242,
242, 273, 273, 274, 242, 242, 242, 275, 275, 276,
242, 242, 277, 277, 278, 279, 279, 280, 281, 281,
282, 283, 283, 284, 285, 285, 286, 287, 287, 288,
289, 289, 290, 291, 291, 292, 242, 242, 293, 242,
242, 0, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242
} ;
static yyconst flex_int16_t yy_nxt[923] =
{ 0,
242, 242, 33, 33, 33, 33, 129, 90, 111, 90,
35, 35, 111, 34, 34, 34, 34, 33, 91, 33,
91, 35, 35, 33, 43, 37, 43, 110, 39, 97,
39, 130, 98, 38, 39, 44, 44, 44, 44, 86,
40, 161, 41, 50, 51, 93, 94, 87, 42, 33,
88, 37, 50, 51, 52, 97, 53, 95, 98, 38,
39, 99, 99, 52, 96, 53, 40, 161, 41, 240,
54, 55, 54, 55, 42, 44, 44, 33, 44, 44,
44, 44, 44, 45, 46, 44, 44, 44, 47, 44,
44, 44, 44, 44, 44, 44, 44, 48, 48, 48,
48, 44, 44, 44, 48, 48, 48, 48, 48, 48,
48, 48, 48, 48, 48, 48, 48, 48, 44, 44,
56, 57, 33, 56, 56, 58, 56, 56, 59, 60,
56, 60, 61, 62, 56, 56, 56, 56, 56, 63,
64, 65, 66, 66, 66, 66, 67, 56, 56, 66,
66, 66, 66, 66, 66, 66, 66, 66, 66, 66,
66, 66, 66, 68, 56, 33, 240, 69, 132, 86,
70, 71, 72, 114, 72, 38, 39, 87, 93, 94,
88, 133, 73, 114, 74, 115, 75, 76, 75, 112,
95, 99, 99, 97, 113, 115, 98, 96, 113, 97,
116, 116, 98, 161, 77, 238, 71, 56, 56, 33,
56, 56, 58, 56, 56, 56, 78, 56, 56, 56,
62, 56, 56, 56, 56, 56, 56, 56, 56, 79,
79, 79, 79, 56, 56, 56, 79, 79, 79, 79,
79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
56, 56, 33, 114, 99, 99, 114, 125, 124, 80,
144, 238, 81, 34, 126, 115, 122, 144, 115, 149,
82, 97, 116, 116, 138, 99, 99, 132, 140, 142,
83, 141, 127, 143, 97, 144, 150, 98, 154, 161,
133, 155, 84, 33, 106, 144, 151, 129, 235, 125,
80, 113, 114, 81, 34, 113, 126, 147, 147, 147,
147, 82, 158, 150, 115, 132, 166, 167, 167, 159,
159, 83, 130, 149, 127, 167, 166, 167, 133, 175,
235, 106, 151, 84, 152, 161, 175, 113, 175, 113,
150, 113, 232, 113, 147, 147, 147, 147, 175, 150,
232, 150, 177, 161, 229, 153, 153, 153, 153, 178,
178, 229, 153, 153, 153, 153, 153, 153, 153, 153,
153, 153, 153, 153, 153, 153, 111, 149, 111, 111,
111, 111, 111, 111, 111, 161, 111, 111, 111, 111,
174, 174, 174, 174, 150, 111, 111, 111, 174, 174,
174, 174, 111, 111, 111, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 111,
111, 112, 226, 226, 189, 161, 113, 223, 223, 161,
113, 190, 190, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 85, 85, 85, 85, 85, 85, 85,
85, 85, 85, 89, 89, 89, 89, 89, 89, 89,
89, 89, 89, 92, 92, 92, 92, 92, 92, 92,
92, 92, 92, 100, 100, 220, 100, 100, 100, 100,
100, 100, 100, 101, 220, 101, 161, 217, 101, 101,
101, 101, 104, 217, 200, 161, 214, 214, 212, 104,
105, 206, 105, 111, 111, 111, 111, 211, 111, 111,
161, 111, 111, 117, 209, 117, 118, 118, 118, 118,
118, 118, 118, 118, 118, 118, 120, 120, 209, 120,
120, 120, 120, 120, 120, 120, 128, 207, 128, 136,
136, 206, 136, 136, 205, 136, 136, 136, 136, 139,
139, 161, 139, 139, 139, 139, 139, 139, 139, 145,
203, 145, 203, 201, 145, 145, 145, 145, 148, 200,
199, 161, 189, 148, 197, 148, 157, 157, 197, 157,
157, 157, 157, 157, 157, 157, 160, 195, 160, 160,
194, 160, 160, 160, 160, 162, 162, 162, 162, 162,
162, 162, 162, 162, 162, 171, 193, 171, 192, 161,
171, 171, 171, 171, 179, 188, 179, 179, 187, 179,
179, 179, 179, 186, 187, 186, 185, 184, 186, 186,
186, 186, 191, 183, 191, 191, 182, 191, 191, 191,
191, 196, 181, 196, 180, 163, 196, 196, 196, 196,
198, 161, 198, 198, 176, 198, 198, 198, 198, 202,
176, 202, 173, 172, 202, 202, 202, 202, 204, 172,
204, 204, 170, 204, 204, 204, 204, 208, 169, 208,
168, 165, 208, 208, 208, 208, 210, 164, 210, 210,
163, 210, 210, 210, 210, 213, 122, 213, 161, 123,
213, 213, 213, 213, 215, 156, 215, 215, 119, 215,
215, 215, 215, 216, 109, 216, 106, 103, 216, 216,
216, 216, 218, 146, 218, 218, 146, 218, 218, 218,
218, 219, 137, 219, 135, 134, 219, 219, 219, 219,
221, 131, 221, 221, 123, 221, 221, 221, 221, 222,
122, 222, 121, 119, 222, 222, 222, 222, 224, 116,
224, 224, 109, 224, 224, 224, 224, 225, 108, 225,
107, 106, 225, 225, 225, 225, 227, 103, 227, 227,
102, 227, 227, 227, 227, 228, 99, 228, 242, 49,
228, 228, 228, 228, 230, 49, 230, 230, 242, 230,
230, 230, 230, 231, 242, 231, 242, 242, 231, 231,
231, 231, 233, 242, 233, 233, 242, 233, 233, 233,
233, 234, 242, 234, 242, 242, 234, 234, 234, 234,
236, 242, 236, 236, 242, 236, 236, 236, 236, 237,
242, 237, 242, 242, 237, 237, 237, 237, 239, 242,
239, 239, 242, 239, 239, 239, 239, 241, 242, 241,
241, 242, 241, 241, 241, 241, 31, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242
} ;
static yyconst flex_int16_t yy_chk[923] =
{ 0,
0, 0, 1, 2, 3, 4, 80, 27, 152, 28,
3, 4, 152, 1, 2, 3, 4, 7, 27, 8,
28, 3, 4, 5, 7, 5, 8, 252, 7, 34,
8, 80, 34, 5, 5, 15, 15, 16, 16, 25,
5, 241, 5, 13, 13, 29, 29, 25, 5, 6,
25, 6, 14, 14, 13, 39, 13, 29, 39, 6,
6, 40, 40, 14, 29, 14, 6, 239, 6, 238,
15, 15, 16, 16, 6, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 19, 237, 19, 82, 26,
19, 19, 19, 60, 19, 19, 19, 26, 30, 30,
26, 82, 19, 72, 19, 60, 19, 19, 19, 59,
30, 41, 41, 47, 59, 72, 47, 30, 59, 62,
63, 63, 62, 236, 19, 235, 19, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
21, 21, 23, 65, 73, 73, 74, 78, 77, 23,
97, 234, 23, 23, 78, 65, 77, 97, 74, 111,
23, 88, 65, 65, 88, 74, 74, 96, 91, 93,
23, 91, 78, 93, 95, 98, 111, 95, 115, 233,
96, 115, 23, 24, 104, 98, 112, 129, 232, 125,
24, 112, 114, 24, 24, 112, 125, 104, 104, 104,
104, 24, 121, 112, 114, 132, 138, 141, 140, 121,
121, 24, 129, 149, 125, 140, 138, 141, 132, 154,
231, 147, 151, 24, 113, 230, 154, 151, 155, 113,
149, 151, 229, 113, 147, 147, 147, 147, 155, 151,
228, 113, 159, 227, 226, 113, 113, 113, 113, 159,
159, 225, 113, 113, 113, 113, 113, 113, 113, 113,
113, 113, 113, 113, 113, 113, 153, 153, 153, 153,
153, 153, 153, 153, 153, 224, 153, 153, 153, 153,
153, 153, 153, 153, 153, 153, 153, 153, 153, 153,
153, 153, 153, 153, 153, 153, 153, 153, 153, 153,
153, 153, 153, 153, 153, 153, 153, 153, 153, 153,
153, 173, 223, 222, 178, 221, 173, 220, 219, 218,
173, 178, 178, 243, 243, 243, 243, 243, 243, 243,
243, 243, 243, 244, 244, 244, 244, 244, 244, 244,
244, 244, 244, 245, 245, 245, 245, 245, 245, 245,
245, 245, 245, 246, 246, 246, 246, 246, 246, 246,
246, 246, 246, 247, 247, 247, 247, 247, 247, 247,
247, 247, 247, 248, 248, 217, 248, 248, 248, 248,
248, 248, 248, 249, 216, 249, 215, 214, 249, 249,
249, 249, 250, 213, 212, 210, 209, 208, 207, 250,
251, 206, 251, 253, 253, 253, 253, 205, 253, 253,
204, 253, 253, 254, 203, 254, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 256, 256, 202, 256,
256, 256, 256, 256, 256, 256, 257, 201, 257, 258,
258, 200, 258, 258, 199, 258, 258, 258, 258, 259,
259, 198, 259, 259, 259, 259, 259, 259, 259, 260,
197, 260, 196, 195, 260, 260, 260, 260, 261, 194,
193, 191, 190, 261, 187, 261, 262, 262, 186, 262,
262, 262, 262, 262, 262, 262, 263, 185, 263, 263,
184, 263, 263, 263, 263, 264, 264, 264, 264, 264,
264, 264, 264, 264, 264, 265, 181, 265, 180, 179,
265, 265, 265, 265, 266, 175, 266, 266, 172, 266,
266, 266, 266, 267, 171, 267, 169, 168, 267, 267,
267, 267, 268, 167, 268, 268, 166, 268, 268, 268,
268, 269, 165, 269, 164, 162, 269, 269, 269, 269,
270, 160, 270, 270, 158, 270, 270, 270, 270, 271,
157, 271, 150, 146, 271, 271, 271, 271, 272, 145,
272, 272, 144, 272, 272, 272, 272, 273, 143, 273,
142, 135, 273, 273, 273, 273, 274, 134, 274, 274,
130, 274, 274, 274, 274, 275, 124, 275, 123, 122,
275, 275, 275, 275, 276, 120, 276, 276, 118, 276,
276, 276, 276, 277, 109, 277, 106, 103, 277, 277,
277, 277, 278, 102, 278, 278, 101, 278, 278, 278,
278, 279, 87, 279, 84, 83, 279, 279, 279, 279,
280, 81, 280, 280, 76, 280, 280, 280, 280, 281,
75, 281, 70, 67, 281, 281, 281, 281, 282, 61,
282, 282, 57, 282, 282, 282, 282, 283, 53, 283,
52, 49, 283, 283, 283, 283, 284, 46, 284, 284,
43, 284, 284, 284, 284, 285, 38, 285, 31, 12,
285, 285, 285, 285, 286, 11, 286, 286, 0, 286,
286, 286, 286, 287, 0, 287, 0, 0, 287, 287,
287, 287, 288, 0, 288, 288, 0, 288, 288, 288,
288, 289, 0, 289, 0, 0, 289, 289, 289, 289,
290, 0, 290, 290, 0, 290, 290, 290, 290, 291,
0, 291, 0, 0, 291, 291, 291, 291, 292, 0,
292, 292, 0, 292, 292, 292, 292, 293, 0, 293,
293, 0, 293, 293, 293, 293, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242, 242, 242, 242, 242, 242, 242, 242, 242,
242, 242
} ;
extern int defargsYY_flex_debug;
int defargsYY_flex_debug = 0;
static yy_state_type *yy_state_buf=0, *yy_state_ptr=0;
static char *yy_full_match;
static int yy_lp;
static int yy_looking_for_trail_begin = 0;
static int yy_full_lp;
static int *yy_full_state;
#define YY_TRAILING_MASK 0x2000
#define YY_TRAILING_HEAD_MASK 0x4000
#define REJECT \
{ \
*yy_cp = (yy_hold_char); /* undo effects of setting up defargsYYtext */ \
yy_cp = (yy_full_match); /* restore poss. backed-over text */ \
(yy_lp) = (yy_full_lp); /* restore orig. accepting pos. */ \
(yy_state_ptr) = (yy_full_state); /* restore orig. state */ \
yy_current_state = *(yy_state_ptr); /* restore curr. state */ \
++(yy_lp); \
goto find_rule; \
}
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *defargsYYtext;
#line 1 "defargs.l"
/******************************************************************************
*
*
*
* Copyright (C) 1997-2014 by Dimitri van Heesch.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation under the terms of the GNU General Public License is hereby
* granted. No representations are made about the suitability of this software
* for any purpose. It is provided "as is" without express or implied warranty.
* See the GNU General Public License for more details.
*
* Documents produced by Doxygen are derivative works derived from the
* input used in their production; they are not affected by this license.
*
*/
/*! \file
* This scanner is used to convert a string into a list of function or
* template arguments. Each parsed argument results in a Argument struct,
* that is put into an ArgumentList in declaration order.
* Comment blocks for arguments can also be included in the string.
* The argument string does not contain new-lines (except inside any
* comment blocks).
* An Argument consists of the string fields:
* type,name,default value, and documentation
* The Argument list as a whole can be pure, constant or volatile.
*
* Examples of input strings are:
* \code
* "(int a,int b) const"
* "(const char *s="hello world",int=5) = 0"
* "<class T,class N>"
* "(char c,const char)"
* \endcode
*
* Note: It is not always possible to distinguish between the name and
* type of an argument. In case of doubt the name is added to the
* type, and the matchArgumentList in util.cpp is be used to
* further determine the correct separation.
*/
#line 44 "defargs.l"
/*
* includes
*/
#include <stdio.h>
//#include <iostream.h>
#include <assert.h>
#include <ctype.h>
#include <qregexp.h>
#include "defargs.h"
#include "entry.h"
#include "util.h"
#include "arguments.h"
#include "message.h"
#define YY_NEVER_INTERACTIVE 1
#define YY_NO_INPUT 1
/* -----------------------------------------------------------------
* state variables
*/
static const char *g_inputString;
static int g_inputPosition;
static ArgumentList *g_argList;
static QCString *g_copyArgValue;
static QCString g_curArgTypeName;
static QCString g_curArgDefValue;
static QCString g_curArgName;
static QCString g_curArgDocs;
static QCString g_curArgAttrib;
static QCString g_curArgArray;
static QCString g_extraTypeChars;
static int g_argRoundCount;
static int g_argSharpCount;
static int g_argCurlyCount;
static int g_readArgContext;
static int g_lastDocContext;
static int g_lastDocChar;
static QCString g_delimiter;
/* -----------------------------------------------------------------
*/
#undef YY_INPUT
#define YY_INPUT(buf,result,max_size) result=yyread(buf,max_size);
static int yyread(char *buf,int max_size)
{
int c=0;
while( c < max_size && g_inputString[g_inputPosition] )
{
*buf = g_inputString[g_inputPosition++] ;
c++; buf++;
}
return c;
}
#line 926 "<stdout>"
#define INITIAL 0
#define Start 1
#define CopyArgString 2
#define CopyRawString 3
#define CopyArgRound 4
#define CopyArgRound2 5
#define CopyArgSharp 6
#define CopyArgCurly 7
#define ReadFuncArgType 8
#define ReadFuncArgDef 9
#define ReadFuncArgPtr 10
#define FuncQual 11
#define ReadDocBlock 12
#define ReadDocLine 13
#define TrailingReturn 14
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int defargsYYlex_destroy (void );
int defargsYYget_debug (void );
void defargsYYset_debug (int debug_flag );
YY_EXTRA_TYPE defargsYYget_extra (void );
void defargsYYset_extra (YY_EXTRA_TYPE user_defined );
FILE *defargsYYget_in (void );
void defargsYYset_in (FILE * in_str );
FILE *defargsYYget_out (void );
void defargsYYset_out (FILE * out_str );
int defargsYYget_leng (void );
char *defargsYYget_text (void );
int defargsYYget_lineno (void );
void defargsYYset_lineno (int line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int defargsYYwrap (void );
#else
extern int defargsYYwrap (void );
#endif
#endif
static void yyunput (int c,char *buf_ptr );
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 262144
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( defargsYYtext, defargsYYleng, 1, defargsYYout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
unsigned n; \
for ( n = 0; n < max_size && \
(c = getc( defargsYYin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( defargsYYin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, defargsYYin))==0 && ferror(defargsYYin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(defargsYYin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int defargsYYlex (void);
#define YY_DECL int defargsYYlex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after defargsYYtext and defargsYYleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
register yy_state_type yy_current_state;
register char *yy_cp, *yy_bp;
register int yy_act;
#line 126 "defargs.l"
#line 1125 "<stdout>"
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
/* Create the reject buffer large enough to save one state per allowed character. */
if ( ! (yy_state_buf) )
(yy_state_buf) = (yy_state_type *)defargsYYalloc(YY_STATE_BUF_SIZE );
if ( ! (yy_state_buf) )
YY_FATAL_ERROR( "out of dynamic memory in defargsYYlex()" );
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! defargsYYin )
defargsYYin = stdin;
if ( ! defargsYYout )
defargsYYout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
defargsYYensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
defargsYY_create_buffer(defargsYYin,YY_BUF_SIZE );
}
defargsYY_load_buffer_state( );
}
while ( 1 ) /* loops until end-of-file is reached */
{
yy_cp = (yy_c_buf_p);
/* Support of defargsYYtext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
(yy_state_ptr) = (yy_state_buf);
*(yy_state_ptr)++ = yy_current_state;
yy_match:
do
{
register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 243 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
*(yy_state_ptr)++ = yy_current_state;
++yy_cp;
}
while ( yy_base[yy_current_state] != 877 );
yy_find_action:
yy_current_state = *--(yy_state_ptr);
(yy_lp) = yy_accept[yy_current_state];
find_rule: /* we branch to this label when backing up */
for ( ; ; ) /* until we find what rule we matched */
{
if ( (yy_lp) && (yy_lp) < yy_accept[yy_current_state + 1] )
{
yy_act = yy_acclist[(yy_lp)];
if ( yy_act & YY_TRAILING_HEAD_MASK ||
(yy_looking_for_trail_begin) )
{
if ( yy_act == (yy_looking_for_trail_begin) )
{
(yy_looking_for_trail_begin) = 0;
yy_act &= ~YY_TRAILING_HEAD_MASK;
break;
}
}
else if ( yy_act & YY_TRAILING_MASK )
{
(yy_looking_for_trail_begin) = yy_act & ~YY_TRAILING_MASK;
(yy_looking_for_trail_begin) |= YY_TRAILING_HEAD_MASK;
(yy_full_match) = yy_cp;
(yy_full_state) = (yy_state_ptr);
(yy_full_lp) = (yy_lp);
}
else
{
(yy_full_match) = yy_cp;
(yy_full_state) = (yy_state_ptr);
(yy_full_lp) = (yy_lp);
break;
}
++(yy_lp);
goto find_rule;
}
--yy_cp;
yy_current_state = *--(yy_state_ptr);
(yy_lp) = yy_accept[yy_current_state];
}
YY_DO_BEFORE_ACTION;
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 1:
YY_RULE_SETUP
#line 128 "defargs.l"
{ BEGIN(ReadFuncArgType); }
YY_BREAK
case 2:
YY_RULE_SETUP
#line 130 "defargs.l"
{
g_curArgTypeName+=" ";
}
YY_BREAK
case 3:
/* rule 3 can match eol */
YY_RULE_SETUP
#line 133 "defargs.l"
{
if (g_curArgTypeName.stripWhiteSpace().isEmpty())
{
g_curArgAttrib=defargsYYtext; // for M$-IDL
}
else // array type
{
g_curArgArray+=defargsYYtext;
}
}
YY_BREAK
case 4:
YY_RULE_SETUP
#line 143 "defargs.l"
{ g_curArgDefValue+=defargsYYtext; }
YY_BREAK
case 5:
YY_RULE_SETUP
#line 144 "defargs.l"
{ g_curArgDefValue+=defargsYYtext; }
YY_BREAK
case 6:
YY_RULE_SETUP
#line 145 "defargs.l"
{ g_curArgDefValue+=defargsYYtext; }
YY_BREAK
case 7:
/* rule 7 can match eol */
YY_RULE_SETUP
#line 146 "defargs.l"
{ g_curArgDefValue+=defargsYYtext;
QCString text=defargsYYtext;
int i=text.find('"');
g_delimiter = defargsYYtext+i+1;
g_delimiter=g_delimiter.left(g_delimiter.length()-1);
BEGIN( CopyRawString );
}
YY_BREAK
case 8:
YY_RULE_SETUP
#line 153 "defargs.l"
{
g_curArgDefValue+=*defargsYYtext;
BEGIN( CopyArgString );
}
YY_BREAK
case 9:
/* rule 9 can match eol */
YY_RULE_SETUP
#line 157 "defargs.l"
{
// function pointer as argument
g_curArgTypeName+=defargsYYtext;
//g_curArgTypeName=g_curArgTypeName.simplifyWhiteSpace();
BEGIN( ReadFuncArgPtr );
}
YY_BREAK
case 10:
YY_RULE_SETUP
#line 163 "defargs.l"
{
g_curArgName=defargsYYtext;
}
YY_BREAK
case 11:
YY_RULE_SETUP
#line 166 "defargs.l"
{ // function pointer
g_curArgTypeName+=defargsYYtext;
//g_curArgTypeName=g_curArgTypeName.simplifyWhiteSpace();
g_readArgContext = ReadFuncArgType;
g_copyArgValue=&g_curArgTypeName;
g_argRoundCount=0;
BEGIN( CopyArgRound2 );
}
YY_BREAK
case 12:
*yy_cp = (yy_hold_char); /* undo effects of setting up defargsYYtext */
(yy_c_buf_p) = yy_cp = yy_bp + 1;
YY_DO_BEFORE_ACTION; /* set up defargsYYtext again */
YY_RULE_SETUP
#line 174 "defargs.l"
{ // pointer to fixed size array
g_curArgTypeName+=defargsYYtext;
g_curArgTypeName+=g_curArgName;
//g_curArgTypeName=g_curArgTypeName.simplifyWhiteSpace();
BEGIN( ReadFuncArgType );
}
YY_BREAK
case 13:
YY_RULE_SETUP
#line 180 "defargs.l"
{ // redundant braces detected / remove them
int i=g_curArgTypeName.findRev('('),l=g_curArgTypeName.length();
if (i!=-1)
g_curArgTypeName=g_curArgTypeName.left(i)+
g_curArgTypeName.right(l-i-1);
g_curArgTypeName+=g_curArgName;
BEGIN( ReadFuncArgType );
}
YY_BREAK
case 14:
YY_RULE_SETUP
#line 188 "defargs.l"
{ // handle operators in defargs
g_curArgTypeName+=defargsYYtext;
}
YY_BREAK
case 15:
YY_RULE_SETUP
#line 191 "defargs.l"
{
if (YY_START==ReadFuncArgType)
{
g_curArgTypeName+=*defargsYYtext;
g_copyArgValue=&g_curArgTypeName;
}
else // YY_START==ReadFuncArgDef
{
g_curArgDefValue+=*defargsYYtext;
g_copyArgValue=&g_curArgDefValue;
}
g_readArgContext = YY_START;
if (*defargsYYtext=='(')
{
g_argRoundCount=0;
BEGIN( CopyArgRound );
}
else if (*defargsYYtext=='{')
{
g_argCurlyCount=0;
BEGIN( CopyArgCurly );
}
else // defargsYYtext=='<'
{
g_argSharpCount=0;
g_argRoundCount=0;
BEGIN( CopyArgSharp );
}
}
YY_BREAK
case 16:
YY_RULE_SETUP
#line 220 "defargs.l"
{
g_argRoundCount++;
*g_copyArgValue += *defargsYYtext;
}
YY_BREAK
case 17:
YY_RULE_SETUP
#line 224 "defargs.l"
{
*g_copyArgValue += defargsYYtext;
if (g_argRoundCount>0)
{
g_argRoundCount--;
}
else
{
if (YY_START==CopyArgRound2)
{
*g_copyArgValue+=" "+g_curArgName;
}
BEGIN( g_readArgContext );
}
}
YY_BREAK
case 18:
*yy_cp = (yy_hold_char); /* undo effects of setting up defargsYYtext */
(yy_c_buf_p) = yy_cp = yy_bp + 1;
YY_DO_BEFORE_ACTION; /* set up defargsYYtext again */
YY_RULE_SETUP
#line 239 "defargs.l"
{
*g_copyArgValue += *defargsYYtext;
if (g_argRoundCount>0) g_argRoundCount--;
else BEGIN( g_readArgContext );
}
YY_BREAK
case 19:
YY_RULE_SETUP
#line 244 "defargs.l"
{
if (g_argRoundCount>0)
{
*g_copyArgValue += defargsYYtext;
}
else
{
REJECT;
}
}
YY_BREAK
case 20:
YY_RULE_SETUP
#line 254 "defargs.l"
{
if (g_argRoundCount>0)
{
*g_copyArgValue += defargsYYtext;
}
else
{
REJECT;
}
}
YY_BREAK
case 21:
YY_RULE_SETUP
#line 264 "defargs.l"
{
g_argSharpCount++;
*g_copyArgValue += *defargsYYtext;
}
YY_BREAK
case 22:
YY_RULE_SETUP
#line 268 "defargs.l"
{
*g_copyArgValue += *defargsYYtext;
if (g_argSharpCount>0) g_argSharpCount--;
else BEGIN( g_readArgContext );
}
YY_BREAK
case 23:
YY_RULE_SETUP
#line 273 "defargs.l"
{
g_argRoundCount++;
*g_copyArgValue += *defargsYYtext;
}
YY_BREAK
case 24:
YY_RULE_SETUP
#line 277 "defargs.l"
{
g_argRoundCount--;
*g_copyArgValue += *defargsYYtext;
}
YY_BREAK
case 25:
YY_RULE_SETUP
#line 281 "defargs.l"
{
g_argCurlyCount++;
*g_copyArgValue += *defargsYYtext;
}
YY_BREAK
case 26:
YY_RULE_SETUP
#line 285 "defargs.l"
{
*g_copyArgValue += *defargsYYtext;
if (g_argCurlyCount>0) g_argCurlyCount--;
else BEGIN( g_readArgContext );
}
YY_BREAK
case 27:
YY_RULE_SETUP
#line 290 "defargs.l"
{
g_curArgDefValue+=defargsYYtext;
}
YY_BREAK
case 28:
/* rule 28 can match eol */
YY_RULE_SETUP
#line 293 "defargs.l"
{
g_curArgDefValue+=defargsYYtext;
QCString delimiter = defargsYYtext+1;
delimiter=delimiter.left(delimiter.length()-1);
if (delimiter==g_delimiter)
{
BEGIN( ReadFuncArgDef );
}
}
YY_BREAK
case 29:
YY_RULE_SETUP
#line 302 "defargs.l"
{
g_curArgDefValue+=*defargsYYtext;
BEGIN( ReadFuncArgDef );
}
YY_BREAK
case 30:
YY_RULE_SETUP
#line 306 "defargs.l"
{
BEGIN( ReadFuncArgDef );
}
YY_BREAK
case 31:
YY_RULE_SETUP
#line 309 "defargs.l"
{
g_lastDocContext=YY_START;
g_lastDocChar=*defargsYYtext;
QCString text=defargsYYtext;
if (text.find("//")!=-1)
BEGIN( ReadDocLine );
else
BEGIN( ReadDocBlock );
}
YY_BREAK
case 32:
YY_RULE_SETUP
#line 318 "defargs.l"
{
if (*defargsYYtext==')' && g_curArgTypeName.stripWhiteSpace().isEmpty())
{
g_curArgTypeName+=*defargsYYtext;
BEGIN(FuncQual);
}
else
{
g_curArgTypeName=removeRedundantWhiteSpace(g_curArgTypeName);
g_curArgDefValue=g_curArgDefValue.stripWhiteSpace();
//printf("curArgType=`%s' curArgDefVal=`%s'\n",g_curArgTypeName.data(),g_curArgDefValue.data());
int l=g_curArgTypeName.length();
if (l>0)
{
int i=l-1;
while (i>=0 && (isspace((uchar)g_curArgTypeName.at(i)) || g_curArgTypeName.at(i)=='.')) i--;
while (i>=0 && (isId(g_curArgTypeName.at(i)) || g_curArgTypeName.at(i)=='$')) i--;
Argument *a = new Argument;
a->attrib = g_curArgAttrib.copy();
//printf("a->type=%s a->name=%s i=%d l=%d\n",
// a->type.data(),a->name.data(),i,l);
a->array.resize(0);
if (i==l-1 && g_curArgTypeName.at(i)==')') // function argument
{
int bi=g_curArgTypeName.find('(');
int fi=bi-1;
//printf("func arg fi=%d\n",fi);
while (fi>=0 && isId(g_curArgTypeName.at(fi))) fi--;
if (fi>=0)
{
a->type = g_curArgTypeName.left(fi+1);
a->name = g_curArgTypeName.mid(fi+1,bi-fi-1).stripWhiteSpace();
a->array = g_curArgTypeName.right(l-bi);
}
else
{
a->type = g_curArgTypeName;
}
}
else if (i>=0 && g_curArgTypeName.at(i)!=':')
{ // type contains a name
a->type = removeRedundantWhiteSpace(g_curArgTypeName.left(i+1)).stripWhiteSpace();
a->name = g_curArgTypeName.right(l-i-1).stripWhiteSpace();
// if the type becomes a type specifier only then we make a mistake
// and need to correct it to avoid seeing a nameless parameter
// "struct A" as a parameter with type "struct" and name "A".
int sv=0;
if (a->type.left(6)=="const ") sv=6;
else if (a->type.left(9)=="volatile ") sv=9;
if (a->type.mid(sv)=="struct" ||
a->type.mid(sv)=="union" ||
a->type.mid(sv)=="class" ||
a->type.mid(sv)=="typename" ||
a->type=="const" ||
a->type=="volatile"
)
{
a->type = a->type + " " + a->name;
a->name.resize(0);
}
//printf(" --> a->type='%s'\n",a->type.data());
}
else // assume only the type was specified, try to determine name later
{
a->type = removeRedundantWhiteSpace(g_curArgTypeName);
}
if (!a->type.isEmpty() && a->type.at(0)=='$') // typeless PHP name?
{
a->name = a->type;
a->type = "";
}
a->array += removeRedundantWhiteSpace(g_curArgArray);
//printf("array=%s\n",a->array.data());
int alen = a->array.length();
if (alen>2 && a->array.at(0)=='(' &&
a->array.at(alen-1)==')') // fix-up for int *(a[10])
{
int i=a->array.find('[')-1;
a->array = a->array.mid(1,alen-2);
if (i>0 && a->name.isEmpty())
{
a->name = a->array.left(i).stripWhiteSpace();
a->array = a->array.mid(i);
}
}
a->defval = g_curArgDefValue.copy();
//printf("a->type=%s a->name=%s a->defval=\"%s\"\n",a->type.data(),a->name.data(),a->defval.data());
a->docs = g_curArgDocs.stripWhiteSpace();
//printf("Argument `%s' `%s' adding docs=`%s'\n",a->type.data(),a->name.data(),a->docs.data());
g_argList->append(a);
}
g_curArgAttrib.resize(0);
g_curArgTypeName.resize(0);
g_curArgDefValue.resize(0);
g_curArgArray.resize(0);
g_curArgDocs.resize(0);
if (*defargsYYtext==')')
{
BEGIN(FuncQual);
//printf(">>> end of argument list\n");
}
else
{
BEGIN( ReadFuncArgType );
}
}
}
YY_BREAK
case 33:
YY_RULE_SETUP
#line 427 "defargs.l"
{
QCString name=defargsYYtext; //resolveDefines(defargsYYtext);
if (YY_START==ReadFuncArgType && g_curArgArray=="[]") // Java style array
{
g_curArgTypeName+=" []";
g_curArgArray.resize(0);
}
//printf("resolveName `%s'->`%s'\n",defargsYYtext,name.data());
g_curArgTypeName+=name;
}
YY_BREAK
case 34:
YY_RULE_SETUP
#line 437 "defargs.l"
{
g_curArgTypeName+=*defargsYYtext;
}
YY_BREAK
case 35:
YY_RULE_SETUP
#line 441 "defargs.l"
{
g_curArgDefValue+=defargsYYtext;
}
YY_BREAK
case 36:
YY_RULE_SETUP
#line 444 "defargs.l"
{
g_curArgDefValue+=*defargsYYtext;
}
YY_BREAK
case 37:
YY_RULE_SETUP
#line 447 "defargs.l"
{
QCString name=defargsYYtext; //resolveDefines(defargsYYtext);
*g_copyArgValue+=name;
}
YY_BREAK
case 38:
YY_RULE_SETUP
#line 451 "defargs.l"
{
*g_copyArgValue += *defargsYYtext;
}
YY_BREAK
case 39:
YY_RULE_SETUP
#line 454 "defargs.l"
{
g_argList->constSpecifier=TRUE;
}
YY_BREAK
case 40:
YY_RULE_SETUP
#line 457 "defargs.l"
{
g_argList->volatileSpecifier=TRUE;
}
YY_BREAK
case 41:
YY_RULE_SETUP
#line 460 "defargs.l"
{
g_argList->pureSpecifier=TRUE;
BEGIN(FuncQual);
}
YY_BREAK
case 42:
YY_RULE_SETUP
#line 464 "defargs.l"
{ // C++11 trailing return type
g_argList->trailingReturnType=" -> ";
BEGIN(TrailingReturn);
}
YY_BREAK
case 43:
*yy_cp = (yy_hold_char); /* undo effects of setting up defargsYYtext */
(yy_c_buf_p) = yy_cp = yy_bp + 1;
YY_DO_BEFORE_ACTION; /* set up defargsYYtext again */
YY_RULE_SETUP
#line 468 "defargs.l"
{
unput(*defargsYYtext);
BEGIN(FuncQual);
}
YY_BREAK
case 44:
YY_RULE_SETUP
#line 472 "defargs.l"
{
g_argList->trailingReturnType+=defargsYYtext;
}
YY_BREAK
case 45:
/* rule 45 can match eol */
YY_RULE_SETUP
#line 475 "defargs.l"
{
g_argList->trailingReturnType+=defargsYYtext;
}
YY_BREAK
case 46:
/* rule 46 can match eol */
YY_RULE_SETUP
#line 478 "defargs.l"
{ // for functions returning a pointer to an array,
// i.e. ")[]" in "int (*f(int))[4]" with argsString="(int))[4]"
g_extraTypeChars=defargsYYtext;
}
YY_BREAK
case 47:
YY_RULE_SETUP
#line 482 "defargs.l"
{
g_curArgDocs+=defargsYYtext;
}
YY_BREAK
case 48:
YY_RULE_SETUP
#line 485 "defargs.l"
{
g_curArgDocs+=defargsYYtext;
}
YY_BREAK
case 49:
YY_RULE_SETUP
#line 488 "defargs.l"
{
if (g_lastDocChar!=0)
unput(g_lastDocChar);
BEGIN(g_lastDocContext);
}
YY_BREAK
case 50:
/* rule 50 can match eol */
YY_RULE_SETUP
#line 493 "defargs.l"
{
if (g_lastDocChar!=0)
unput(g_lastDocChar);
BEGIN(g_lastDocContext);
}
YY_BREAK
case 51:
/* rule 51 can match eol */
YY_RULE_SETUP
#line 498 "defargs.l"
{
g_curArgDocs+=*defargsYYtext;
}
YY_BREAK
case 52:
YY_RULE_SETUP
#line 501 "defargs.l"
{
g_curArgDocs+=*defargsYYtext;
}
YY_BREAK
case 53:
YY_RULE_SETUP
#line 504 "defargs.l"
{
g_lastDocContext=YY_START;
g_lastDocChar=0;
if (defargsYYtext[1]=='/')
BEGIN( ReadDocLine );
else
BEGIN( ReadDocBlock );
}
YY_BREAK
case 54:
/* rule 54 can match eol */
YY_RULE_SETUP
#line 512 "defargs.l"
YY_BREAK
case 55:
YY_RULE_SETUP
#line 513 "defargs.l"
YY_BREAK
case 56:
YY_RULE_SETUP
#line 515 "defargs.l"
ECHO;
YY_BREAK
#line 1867 "<stdout>"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(Start):
case YY_STATE_EOF(CopyArgString):
case YY_STATE_EOF(CopyRawString):
case YY_STATE_EOF(CopyArgRound):
case YY_STATE_EOF(CopyArgRound2):
case YY_STATE_EOF(CopyArgSharp):
case YY_STATE_EOF(CopyArgCurly):
case YY_STATE_EOF(ReadFuncArgType):
case YY_STATE_EOF(ReadFuncArgDef):
case YY_STATE_EOF(ReadFuncArgPtr):
case YY_STATE_EOF(FuncQual):
case YY_STATE_EOF(ReadDocBlock):
case YY_STATE_EOF(ReadDocLine):
case YY_STATE_EOF(TrailingReturn):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed defargsYYin at a new source and called
* defargsYYlex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = defargsYYin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_c_buf_p);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( defargsYYwrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* defargsYYtext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of defargsYYlex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
register char *source = (yytext_ptr);
register int number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
int num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
YY_FATAL_ERROR(
"input buffer overflow, can't enlarge buffer because scanner uses REJECT" );
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), (size_t) num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
defargsYYrestart(defargsYYin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) defargsYYrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
register yy_state_type yy_current_state;
register char *yy_cp;
yy_current_state = (yy_start);
(yy_state_ptr) = (yy_state_buf);
*(yy_state_ptr)++ = yy_current_state;
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 243 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
*(yy_state_ptr)++ = yy_current_state;
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
register int yy_is_jam;
register YY_CHAR yy_c = 1;
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 243 )
yy_c = yy_meta[(unsigned int) yy_c];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 242);
if ( ! yy_is_jam )
*(yy_state_ptr)++ = yy_current_state;
return yy_is_jam ? 0 : yy_current_state;
}
static void yyunput (int c, register char * yy_bp )
{
register char *yy_cp;
yy_cp = (yy_c_buf_p);
/* undo effects of setting up defargsYYtext */
*yy_cp = (yy_hold_char);
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
{ /* need to shift things up to make room */
/* +2 for EOB chars. */
register int number_to_move = (yy_n_chars) + 2;
register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
register char *source =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
*--dest = *--source;
yy_cp += (int) (dest - source);
yy_bp += (int) (dest - source);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
YY_FATAL_ERROR( "flex scanner push-back overflow" );
}
*--yy_cp = (char) c;
(yytext_ptr) = yy_bp;
(yy_hold_char) = *yy_cp;
(yy_c_buf_p) = yy_cp;
}
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
int offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
defargsYYrestart(defargsYYin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( defargsYYwrap( ) )
return EOF;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve defargsYYtext */
(yy_hold_char) = *++(yy_c_buf_p);
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void defargsYYrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
defargsYYensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
defargsYY_create_buffer(defargsYYin,YY_BUF_SIZE );
}
defargsYY_init_buffer(YY_CURRENT_BUFFER,input_file );
defargsYY_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void defargsYY_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* defargsYYpop_buffer_state();
* defargsYYpush_buffer_state(new_buffer);
*/
defargsYYensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
defargsYY_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (defargsYYwrap()) processing, but the only time this flag
* is looked at is after defargsYYwrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void defargsYY_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
defargsYYin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE defargsYY_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) defargsYYalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in defargsYY_create_buffer()" );
b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) defargsYYalloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in defargsYY_create_buffer()" );
b->yy_is_our_buffer = 1;
defargsYY_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with defargsYY_create_buffer()
*
*/
void defargsYY_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
defargsYYfree((void *) b->yy_ch_buf );
defargsYYfree((void *) b );
}
#ifndef __cplusplus
extern int isatty (int );
#endif /* __cplusplus */
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a defargsYYrestart() or at EOF.
*/
static void defargsYY_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
defargsYY_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then defargsYY_init_buffer was _probably_
* called from defargsYYrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void defargsYY_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
defargsYY_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void defargsYYpush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
defargsYYensure_buffer_stack();
/* This block is copied from defargsYY_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from defargsYY_switch_to_buffer. */
defargsYY_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void defargsYYpop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
defargsYY_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
defargsYY_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void defargsYYensure_buffer_stack (void)
{
int num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1;
(yy_buffer_stack) = (struct yy_buffer_state**)defargsYYalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in defargsYYensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
int grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)defargsYYrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in defargsYYensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE defargsYY_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) defargsYYalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in defargsYY_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
defargsYY_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to defargsYYlex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* defargsYY_scan_bytes() instead.
*/
YY_BUFFER_STATE defargsYY_scan_string (yyconst char * yystr )
{
return defargsYY_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to defargsYYlex() will
* scan from a @e copy of @a bytes.
* @param bytes the byte buffer to scan
* @param len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE defargsYY_scan_bytes (yyconst char * yybytes, int _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
int i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) defargsYYalloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in defargsYY_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = defargsYY_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in defargsYY_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up defargsYYtext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
defargsYYtext[defargsYYleng] = (yy_hold_char); \
(yy_c_buf_p) = defargsYYtext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
defargsYYleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int defargsYYget_lineno (void)
{
return defargsYYlineno;
}
/** Get the input stream.
*
*/
FILE *defargsYYget_in (void)
{
return defargsYYin;
}
/** Get the output stream.
*
*/
FILE *defargsYYget_out (void)
{
return defargsYYout;
}
/** Get the length of the current token.
*
*/
int defargsYYget_leng (void)
{
return defargsYYleng;
}
/** Get the current token.
*
*/
char *defargsYYget_text (void)
{
return defargsYYtext;
}
/** Set the current line number.
* @param line_number
*
*/
void defargsYYset_lineno (int line_number )
{
defargsYYlineno = line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param in_str A readable stream.
*
* @see defargsYY_switch_to_buffer
*/
void defargsYYset_in (FILE * in_str )
{
defargsYYin = in_str ;
}
void defargsYYset_out (FILE * out_str )
{
defargsYYout = out_str ;
}
int defargsYYget_debug (void)
{
return defargsYY_flex_debug;
}
void defargsYYset_debug (int bdebug )
{
defargsYY_flex_debug = bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from defargsYYlex_destroy(), so don't allocate here.
*/
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
(yy_state_buf) = 0;
(yy_state_ptr) = 0;
(yy_full_match) = 0;
(yy_lp) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
defargsYYin = stdin;
defargsYYout = stdout;
#else
defargsYYin = (FILE *) 0;
defargsYYout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* defargsYYlex_init()
*/
return 0;
}
/* defargsYYlex_destroy is for both reentrant and non-reentrant scanners. */
int defargsYYlex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
defargsYY_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
defargsYYpop_buffer_state();
}
/* Destroy the stack itself. */
defargsYYfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
defargsYYfree ( (yy_state_buf) );
(yy_state_buf) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* defargsYYlex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
register int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
register int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *defargsYYalloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *defargsYYrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void defargsYYfree (void * ptr )
{
free( (char *) ptr ); /* see defargsYYrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 515 "defargs.l"
/* ----------------------------------------------------------------------------
*/
/*! Converts an argument string into an ArgumentList.
* \param[in] argsString the list of Arguments.
* \param[out] al a reference to resulting argument list pointer.
* \param[out] extraTypeChars point to string to which trailing characters
* for complex types are written to
*/
void stringToArgumentList(const char *argsString,ArgumentList* al,QCString *extraTypeChars)
{
if (al==0) return;
if (argsString==0) return;
printlex(defargsYY_flex_debug, TRUE, __FILE__, NULL);
g_copyArgValue=0;
g_curArgDocs.resize(0);
g_curArgAttrib.resize(0);
g_curArgArray.resize(0);
g_extraTypeChars.resize(0);
g_argRoundCount = 0;
g_argSharpCount = 0;
g_argCurlyCount = 0;
g_lastDocChar = 0;
g_inputString = argsString;
g_inputPosition = 0;
g_curArgTypeName.resize(0);
g_curArgDefValue.resize(0);
g_curArgName.resize(0);
g_argList = al;
defargsYYrestart( defargsYYin );
BEGIN( Start );
defargsYYlex();
if (extraTypeChars) *extraTypeChars=g_extraTypeChars;
//printf("stringToArgumentList(%s) result=%s\n",argsString,argListToString(al).data());
printlex(defargsYY_flex_debug, FALSE, __FILE__, NULL);
}
#if !defined(YY_FLEX_SUBMINOR_VERSION)
extern "C" { // some bogus code to keep the compiler happy
void defargsYYdummy() { yy_flex_realloc(0,0); }
}
#endif
| shiqianmiao/mydoxygen_source | generated_src/doxygen/defargs.cpp | C++ | gpl-2.0 | 87,344 |
package com.yh.hr.component.im.check.service.impl;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import com.yh.hr.component.im.check.service.CollItemCheckService;
import com.yh.hr.component.im.dto.CheckColumnDTO;
import com.yh.hr.component.im.dto.CheckResultDTO;
import com.yh.hr.res.dictionary.DicConstants;
import com.yh.hr.res.im.dto.ImCollectTemplateDTO;
import com.yh.platform.core.exception.ServiceException;
/**
* 数据项长度检查实现类
* @author wangx
* @date 2017-07-11
* @version 1.0
*/
public class DataLengthCheckServiceImpl implements CollItemCheckService {
/**
* 数据项长度检查
* @param column
* @param collList 已映射的采集项模板
* @throws ServiceException
*/
public CheckResultDTO check(CheckColumnDTO column,List<ImCollectTemplateDTO> collList) throws ServiceException {
String importCollName = column.getImportCollName();
if(importCollName==null) {
throw new ServiceException(null, "导入采集项名称不能为空!");
}
ImCollectTemplateDTO imCollectTemplateDTO=null;
if(CollectionUtils.isNotEmpty(collList)) {
for(ImCollectTemplateDTO collDTO:collList) {
if(DicConstants.YHRS0003_1.equals(collDTO.getEffectiveFlag())&&importCollName.equals(collDTO.getImportCollName())) {
imCollectTemplateDTO = collDTO;
}
}
}
String importCollValue = column.getImportCollValue();
if(importCollValue!=null&&!"".equals(importCollValue)) {
if(imCollectTemplateDTO!=null) {
Integer importCollMaxlength = imCollectTemplateDTO.getImportCollMaxlength();
Integer valueLength = importCollValue.length();
if(valueLength>importCollMaxlength) {
CheckResultDTO result = new CheckResultDTO();
result.setDatabaseColumnCode(imCollectTemplateDTO.getDatabaseColumnCode());
result.setImportCollValue(importCollValue);
result.setCheckType(column.getCheckType());
result.setCheckStatus(DicConstants.YHRS0003_0);
result.setCheckMessage("“"+imCollectTemplateDTO.getTemplateCollName()+"”长度超长");
return result;
}
}
}
return null;
}
}
| meijmOrg/Repo-test | freelance-hr-component/src/java/com/yh/hr/component/im/check/service/impl/DataLengthCheckServiceImpl.java | Java | gpl-2.0 | 2,107 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\Tests\Apcu;
use PHPUnit\Framework\TestCase;
/**
* @requires extension apc
*/
class ApcuTest extends TestCase
{
public function testApcu()
{
$key = __CLASS__;
apcu_delete($key);
$this->assertFalse(apcu_exists($key));
$this->assertTrue(apcu_add($key, 123));
$this->assertTrue(apcu_exists($key));
$this->assertSame(array($key => -1), apcu_add(array($key => 123)));
$this->assertSame(123, apcu_fetch($key));
$this->assertTrue(apcu_store($key, 124));
$this->assertSame(124, apcu_fetch($key));
$this->assertSame(125, apcu_inc($key));
$this->assertSame(124, apcu_dec($key));
$this->assertTrue(apcu_cas($key, 124, 123));
$this->assertFalse(apcu_cas($key, 124, 123));
$this->assertTrue(apcu_delete($key));
$this->assertFalse(apcu_delete($key));
$this->assertArrayHasKey('cache_list', apcu_cache_info());
}
public function testArrayCompatibility()
{
$data = array (
'key1' => 'value1',
'key2' => 'value2',
);
apcu_delete(array_keys($data));
apcu_add($data);
foreach ($data as $key => $value) {
$this->assertEquals($value, apcu_fetch($key));
}
$data = array (
'key1' => 'value2',
'key2' => 'value3',
);
apcu_store($data);
$this->assertEquals($data, apcu_fetch(array_keys($data)));
$this->assertSame(array('key1' => true, 'key2' => true), apcu_exists(array('key1', 'key2', 'key3')));
apcu_delete(array_keys($data));
$this->assertSame(array(), apcu_exists(array_keys($data)));
}
public function testAPCUIterator()
{
$key = __CLASS__;
$this->assertTrue(apcu_store($key, 456));
$entries = iterator_to_array(new \APCUIterator('/^'.preg_quote($key, '/').'$/', APC_ITER_KEY | APC_ITER_VALUE));
$this->assertSame(array($key), array_keys($entries));
$this->assertSame($key, $entries[$key]['key']);
$this->assertSame(456, $entries[$key]['value']);
}
}
| lazyphp/PESCMS-TEAM | vendor/symfony/polyfill/tests/Apcu/ApcuTest.php | PHP | gpl-2.0 | 2,386 |
class CountUniqueIntegers {
private Set<Integer> set;
public CountIntegers( Set<Integer> set ) {
this.set = set;
}
public int getCount( int[] array ) {
int length = array.length;
for( int i = 0; i < length; i ++ )
this.set.push( array[i] );
return this.set.size();
}
}
| supalogix/java-liskov-example | src/CountIntegers.java | Java | gpl-2.0 | 293 |
<?php
// +----------------------------------------------------------------------+
// | BoletoPhp - Versão Beta |
// +----------------------------------------------------------------------+
// | Este arquivo está disponível sob a Licença GPL disponível pela Web |
// | em http://pt.wikipedia.org/wiki/GNU_General_Public_License |
// | Você deve ter recebido uma cópia da GNU Public License junto com |
// | esse pacote; se não, escreva para: |
// | |
// | Free Software Foundation, Inc. |
// | 59 Temple Place - Suite 330 |
// | Boston, MA 02111-1307, USA. |
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Originado do Projeto BBBoletoFree que tiveram colaborações de Daniel |
// | William Schultz e Leandro Maniezo que por sua vez foi derivado do |
// | PHPBoleto de João Prado Maia e Pablo Martins F. Costa |
// | |
// | Se vc quer colaborar, nos ajude a desenvolver p/ os demais bancos :-)|
// | Acesse o site do Projeto BoletoPhp: www.boletophp.com.br |
// +----------------------------------------------------------------------+
// +--------------------------------------------------------------------------------------------------------+
// | Equipe Coordenação Projeto BoletoPhp: <boletophp@boletophp.com.br> |
// | Desenvolvimento Boleto Banco do Brasil: Daniel William Schultz / Leandro Maniezo / Rogério Dias Pereira|
// +--------------------------------------------------------------------------------------------------------+
// ------------------------- DADOS DINÂMICOS DO SEU CLIENTE PARA A GERAÇÃO DO BOLETO (FIXO OU VIA GET) -------------------- //
// Os valores abaixo podem ser colocados manualmente ou ajustados p/ formulário c/ POST, GET ou de BD (MySql,Postgre,etc) //
// DADOS DO BOLETO PARA O SEU CLIENTE
require_once("../../conexao.php");
$valor_do_boleto_passado=$_POST['valor_boleto'];
$id_participante=$_POST['id_participante'];
$id_evento=$_POST['id_evento'];
if(empty($valor_do_boleto_passado) || empty($id_participante) || empty($id_evento)) exit("Os dados do boleto não estão corretos.");
$dias_de_prazo_para_pagamento = 7;
$taxa_boleto = 4.50;
$data_venc = date("d/m/Y", time() + ($dias_de_prazo_para_pagamento * 86400)); // Prazo de X dias OU informe data: "13/04/2006";
//$valor_cobrado = "2950,00"; // Valor - REGRA: Sem pontos na milhar e tanto faz com "." ou "," ou com 1 ou 2 ou sem casa decimal
$valor_cobrado=$valor_do_boleto_passado;
$valor_cobrado = str_replace(",", ".",$valor_cobrado);
$valor_boleto=number_format($valor_cobrado+$taxa_boleto, 2, ',', '');
$sql_participante = "SELECT id, nome FROM ev_participante WHERE id='".$id_participante."'";
$qr_participante = mysql_query($sql_participante, $conexao) or die(mysql_error());
$p=mysql_fetch_assoc($qr_participante);
$sql_pag = "SELECT id FROM ev_pagamento WHERE id_participante='".$id_participante."'";
$qr_pag = mysql_query($sql_pag, $conexao) or die(mysql_error());
$ja_tem_pagamento=mysql_num_rows($qr_pag);
$valor_tabela_pagamento = ($valor_cobrado+$taxa_boleto);
if ($ja_tem_pagamento>0){ // ja solicitou boleto antes - atualiza
$sql_update = "UPDATE ev_pagamento SET
valor = '$valor_tabela_pagamento',
pago = 'nao'
WHERE id_participante='$id_participante'";
mysql_query($sql_update, $conexao);
}else{ //primeira vez - insere
$sql_insert_pagamento = "insert into ev_pagamento(id_participante,valor,pago)
values('$id_participante','$valor_tabela_pagamento','nao');";
mysql_query($sql_insert_pagamento, $conexao);
}
$dadosboleto["nosso_numero"] = $p['id'];
$dadosboleto["numero_documento"] = $p['id']; // Num do pedido ou do documento
$dadosboleto["data_vencimento"] = $data_venc; // Data de Vencimento do Boleto - REGRA: Formato DD/MM/AAAA
$dadosboleto["data_documento"] = date("d/m/Y"); // Data de emissão do Boleto
$dadosboleto["data_processamento"] = date("d/m/Y"); // Data de processamento do boleto (opcional)
$dadosboleto["valor_boleto"] = $valor_boleto; // Valor do Boleto - REGRA: Com vírgula e sempre com duas casas depois da virgula
// DADOS DO SEU CLIENTE
$dadosboleto["sacado"] = $p['nome'];
//$dadosboleto["endereco1"] = $p['endereco'];
//$dadosboleto["endereco2"] = $p['cep'];
// INFORMACOES PARA O CLIENTE
$dadosboleto["demonstrativo1"] = "";
$dadosboleto["demonstrativo2"] = "Mensalidade referente a pagamento de evento<br>Taxa bancária - R$ ".number_format($taxa_boleto, 2, ',', '');
$dadosboleto["demonstrativo3"] = "www.alab.org.br";
// INSTRUÇÕES PARA O CAIXA
$dadosboleto["instrucoes1"] = "- Sr. Caixa, cobrar multa de 2% após o vencimento";
$dadosboleto["instrucoes2"] = "";//- Receber até 10 dias após o vencimento";
$dadosboleto["instrucoes3"] = "- Em caso de dúvidas entre em contato conosco: alab@alab.org.br";
$dadosboleto["instrucoes4"] = " Emitido por - www.alab.org.br";
// DADOS OPCIONAIS DE ACORDO COM O BANCO OU CLIENTE
$dadosboleto["quantidade"] = "1";
//$dadosboleto["valor_unitario"] = "10";
$dadosboleto["aceite"] = "N";
$dadosboleto["especie"] = "R$";
$dadosboleto["especie_doc"] = "DM";
// ---------------------- DADOS FIXOS DE CONFIGURAÇÃO DO SEU BOLETO --------------- //
// DADOS DA SUA CONTA - BANCO DO BRASIL
//3603-X
$dadosboleto["agencia"] = "3603"; // Num da agencia, sem digito
$dadosboleto["conta"] = "30184"; // Num da conta, sem digito
//30184-1
// DADOS PERSONALIZADOS - BANCO DO BRASIL
$dadosboleto["convenio"] = "2100971"; // Num do convênio - REGRA: 6 ou 7 ou 8 dígitos
//$dadosboleto["contrato"] = "999999"; // Num do seu contrato
$dadosboleto["carteira"] = "18";
//17
$dadosboleto["variacao_carteira"] = "-019"; // Variação da Carteira, com traço (opcional)
// TIPO DO BOLETO
$dadosboleto["formatacao_convenio"] = "7"; // REGRA: 8 p/ Convênio c/ 8 dígitos, 7 p/ Convênio c/ 7 dígitos, ou 6 se Convênio c/ 6 dígitos
$dadosboleto["formatacao_nosso_numero"] = "2"; // REGRA: Usado apenas p/ Convênio c/ 6 dígitos: informe 1 se for NossoNúmero de até 5 dígitos ou 2 para opção de até 17 dígitos
/*
#################################################
DESENVOLVIDO PARA CARTEIRA 18
- Carteira 18 com Convenio de 8 digitos
Nosso número: pode ser até 9 dígitos
- Carteira 18 com Convenio de 7 digitos
Nosso número: pode ser até 10 dígitos
- Carteira 18 com Convenio de 6 digitos
Nosso número:
de 1 a 99999 para opção de até 5 dígitos
de 1 a 99999999999999999 para opção de até 17 dígitos
#################################################
*/
// SEUS DADOS
$dadosboleto["identificacao"] = "ALAB - Associação de Linguística Aplicada do Brasil";
$dadosboleto["cpf_cnpj"] = "";
$dadosboleto["endereco"] = "Av. Horácio Macedo 2151 sala F-317 Cidade Universitária - CEP 21.941-917";
$dadosboleto["cidade_uf"] = "Rio de Janeiro / RJ";
$dadosboleto["cedente"] = "ALAB - Associação de Linguística Aplicada do Brasil";
// NÃO ALTERAR!
include("include/funcoes_bb.php");
include("include/layout_bb.php");
?> | viollarr/alab | eventosalab/queering/boleto/boleto_bb.php | PHP | gpl-2.0 | 7,541 |
package com.geminno.calculatorapplication;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener
{
//ÉùÃ÷һЩ¿Ø¼þ
Button btn0=null;
Button btn1=null;
Button btn2=null;
Button btn3=null;
Button btn4=null;
Button btn5=null;
Button btn6=null;
Button btn7=null;
Button btn8=null;
Button btn9=null;
Button btnBackspace=null;
Button btnCE=null;
Button btnC=null;
Button btnAdd=null;
Button btnSub=null;
Button btnMul=null;
Button btnDiv=null;
Button btnEqu=null;
TextView tvResult=null;
//ÉùÃ÷Á½¸ö²ÎÊý¡£½ÓÊÕtvResultǰºóµÄÖµ
double num1=0,num2=0;
double Result=0;//¼ÆËã½á¹û
int op=0;//ÅжϲÙ×÷Êý£¬
boolean isClickEqu=false;//ÅжÏÊÇ·ñ°´ÁË¡°=¡±°´Å¥
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//´Ó²¼¾ÖÎļþÖлñÈ¡¿Ø¼þ£¬
btn0=(Button)findViewById(R.id.btn0);
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn3=(Button)findViewById(R.id.btn3);
btn4=(Button)findViewById(R.id.btn4);
btn5=(Button)findViewById(R.id.btn5);
btn6=(Button)findViewById(R.id.btn6);
btn7=(Button)findViewById(R.id.btn7);
btn8=(Button)findViewById(R.id.btn8);
btn9=(Button)findViewById(R.id.btn9);
btnBackspace=(Button)findViewById(R.id.btnBackspace);
btnCE=(Button)findViewById(R.id.btnCE);
btnC=(Button)findViewById(R.id.btnC);
btnEqu=(Button)findViewById(R.id.btnEqu);
btnAdd=(Button)findViewById(R.id.btnAdd);
btnSub=(Button)findViewById(R.id.btnSub);
btnMul=(Button)findViewById(R.id.btnMul);
btnDiv=(Button)findViewById(R.id.btnDiv);
tvResult=(TextView)findViewById(R.id.tvResult);
//Ìí¼Ó¼àÌý\
btnBackspace.setOnClickListener(this);
btnCE.setOnClickListener(this);
btn0.setOnClickListener(this);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btnAdd.setOnClickListener(this);
btnSub.setOnClickListener(this);
btnMul.setOnClickListener(this);
btnDiv.setOnClickListener(this);
btnEqu.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
//btnBackspaceºÍCE--------------------
case R.id.btnBackspace:
String myStr=tvResult.getText().toString();
try {
tvResult.setText(myStr.substring(0, myStr.length()-1));
} catch (Exception e) {
tvResult.setText("");
}
break;
case R.id.btnCE:
tvResult.setText(null);
break;
//btn0--9---------------------------
case R.id.btn0:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString=tvResult.getText().toString();
myString+="0";
tvResult.setText(myString);
break;
case R.id.btn1:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString1=tvResult.getText().toString();
myString1+="1";
tvResult.setText(myString1);
break;
case R.id.btn2:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString2=tvResult.getText().toString();
myString2+="2";
tvResult.setText(myString2);
break;
case R.id.btn3:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString3=tvResult.getText().toString();
myString3+="3";
tvResult.setText(myString3);
break;
case R.id.btn4:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString4=tvResult.getText().toString();
myString4+="4";
tvResult.setText(myString4);
break;
case R.id.btn5:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString5=tvResult.getText().toString();
myString5+="5";
tvResult.setText(myString5);
break;
case R.id.btn6:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString6=tvResult.getText().toString();
myString6+="6";
tvResult.setText(myString6);
break;
case R.id.btn7:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString7=tvResult.getText().toString();
myString7+="7";
tvResult.setText(myString7);
break;
case R.id.btn8:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString8=tvResult.getText().toString();
myString8+="8";
tvResult.setText(myString8);
break;
case R.id.btn9:
if(isClickEqu)
{
tvResult.setText(null);
isClickEqu=false;
}
String myString9=tvResult.getText().toString();
myString9+="9";
tvResult.setText(myString9);
break;
//btn+-*/=--------------------------------
case R.id.btnAdd:
String myStringAdd=tvResult.getText().toString();
if(myStringAdd.equals(null))
{
return;
}
num1=Double.valueOf(myStringAdd);
tvResult.setText(null);
op=1;
isClickEqu=false;
break;
// case R.id.btnSub:
case R.id.btnSub:
String myStringSub=tvResult.getText().toString();
if(myStringSub.equals(null))
{
return;
}
num1=Double.valueOf(myStringSub);
tvResult.setText(null);
op=2;
isClickEqu=false;
break;
case R.id.btnMul:
String myStringMul=tvResult.getText().toString();
if(myStringMul.equals(null))
{
return;
}
num1=Double.valueOf(myStringMul);
tvResult.setText(null);
op=3;
isClickEqu=false;
break;
case R.id.btnDiv:
String myStringDiv=tvResult.getText().toString();
if(myStringDiv.equals(null))
{
return;
}
num1=Double.valueOf(myStringDiv);
tvResult.setText(null);
op=4;
isClickEqu=false;
break;
case R.id.btnEqu:
String myStringEqu=tvResult.getText().toString();
if(myStringEqu.equals(null))
{
return;
}
num2=Double.valueOf(myStringEqu);
tvResult.setText(null);
switch (op) {
case 0:
Result=num2;
break;
case 1:
Result=num1+num2;
break;
case 2:
Result=num1-num2;
break;
case 3:
Result=num1*num2;
break;
case 4:
Result=num1/num2;
break;
default:
Result=0;
break;
}
tvResult.setText(String.valueOf(Result));
isClickEqu=true;
break;
default:
break;
}
}
}
| A203/LuWeidan | CalculatorApplication/app/src/main/java/com/geminno/calculatorapplication/MainActivity.java | Java | gpl-2.0 | 9,472 |
#!/usr/bin/env python
import re
import sys
from urllib import urlopen
def isup(domain):
resp = urlopen("http://www.isup.me/%s" % domain).read()
return "%s" % ("UP" if re.search("It's just you.", resp,
re.DOTALL) else "DOWN")
if __name__ == '__main__':
if len(sys.argv) > 1:
print "\n".join(isup(d) for d in sys.argv[1:])
else:
print "usage: %s domain1 [domain2 .. domainN]" % sys.argv[0]
| BogdanWDK/ajaxbot | src/files/isup.py | Python | gpl-2.0 | 433 |
<?php
/**
* Fabrik From Controller
*
* @package Joomla
* @subpackage Fabrik
* @copyright Copyright (C) 2005-2013 fabrikar.com - All rights reserved.
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
*/
// No direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
/**
* Fabrik From Controller
*
* @static
* @package Joomla
* @subpackage Fabrik
* @since 1.5
*/
class FabrikControllerForm extends JController
{
/**
* Is the view rendered from the J content plugin
*
* @var bool
*/
public $isMambot = false;
/**
* Id used from content plugin when caching turned on to ensure correct element rendered
*
* @var int
*/
public $cacheId = 0;
/**
* Magic method to convert the object to a string gracefully.
*
* $$$ hugh - added 08/05/2012. No idea what's going on, but I had to add this to stop
* the classname 'FabrikControllerForm' being output at the bottom of the form, when rendered
* through a Fabrik form module. See:
*
* https://github.com/Fabrik/fabrik/issues/398
*
* @return string empty string.
*/
public function __toString()
{
return '';
}
/**
* Inline edit control
*
* @since 3.0b
*
* @return null
*/
public function inlineedit()
{
$document = JFactory::getDocument();
$app = JFactory::getApplication();
$input = $app->input;
$model = JModel::getInstance('Form', 'FabrikFEModel');
$viewType = $document->getType();
$viewLayout = $input->get('layout', 'default');
$view = $this->getView('form', $viewType, '');
$view->setModel($model, true);
// Set the layout
$view->setLayout($viewLayout);
// @TODO check for cached version
$view->inlineEdit();
}
/**
* Display the view
*
* @param boolean $cachable If true, the view output will be cached
* @param array $urlparams An array of safe url parameters and their variable types, for valid values see {@link JFilterInput::clean()}.
*
* @return JController A JController object to support chaining.
*/
public function display($cachable = false, $urlparams = false)
{
$app = JFactory::getApplication();
$input = $app->input;
$package = $app->getUserState('com_fabrik.package', 'fabrik');
$session = JFactory::getSession();
$document = JFactory::getDocument();
$viewName = $input->get('view', 'form');
$modelName = $viewName;
if ($viewName == 'emailform')
{
$modelName = 'form';
}
$viewType = $document->getType();
// Set the default view name from the Request
$view = $this->getView($viewName, $viewType);
// Push a model into the view (may have been set in content plugin already
$model = !isset($this->_model) ? $this->getModel($modelName, 'FabrikFEModel') : $this->_model;
$model->isMambot = $this->isMambot;
$model->packageId = $app->input->getInt('packageId');
// Test for failed validation then page refresh
$model->getErrors();
if (!JError::isError($model) && is_object($model))
{
$view->setModel($model, true);
}
$view->isMambot = $this->isMambot;
// Get data as it will be needed for ACL when testing if current row is editable.
$model->getData();
// If we can't edit the record redirect to details view
if ($model->checkAccessFromListSettings() <= 1)
{
$app = JFactory::getApplication();
$input = $app->input;
if ($app->isAdmin())
{
$url = 'index.php?option=com_fabrik&task=details.view&formid=' . $input->getInt('formid') . '&rowid=' . $input->get('rowid', '', 'string');
}
else
{
$url = 'index.php?option=com_' . $package . '&view=details&formid=' . $input->getInt('formid') . '&rowid=' . $input->get('rowid', '', 'string');
}
$msg = $model->aclMessage();
$this->setRedirect(JRoute::_($url), $msg, 'notice');
return;
}
// Display the view
$view->error = $this->getError();
// $$$ hugh - added disable caching option, and no caching if not logged in (unless we can come up with a unique cacheid for guests)
// NOTE - can't use IP of client, as could be two users behind same NAT'ing proxy / firewall.
$listModel = $model->getListModel();
$listParams = $listModel->getParams();
$user = JFactory::getUser();
if ($user->get('id') == 0
|| $listParams->get('list_disable_caching', '0') === '1'
|| in_array($input->get('format'), array('raw', 'csv', 'pdf')))
{
$view->display();
}
else
{
$uri = JFactory::getURI();
$uri = $uri->toString(array('path', 'query'));
$cacheid = serialize(array($uri, $input->post, $user->get('id'), get_class($view), 'display', $this->cacheId));
$cache = JFactory::getCache('com_' . $package, 'view');
ob_start();
$cache->get($view, 'display', $cacheid);
$contents = ob_get_contents();
ob_end_clean();
// Workaround for token caching
$token = JSession::getFormToken();
$search = '#<input type="hidden" name="[0-9a-f]{32}" value="1" />#';
$replacement = '<input type="hidden" name="' . $token . '" value="1" />';
echo preg_replace($search, $replacement, $contents);
}
return $this;
}
/**
* Process the form
*
* @return null
*/
public function process()
{
$app = JFactory::getApplication();
$package = $app->getUserState('com_fabrik.package', 'fabrik');
$input = $app->input;
if ($input->get('format', '') == 'raw')
{
error_reporting(error_reporting() ^ (E_WARNING | E_NOTICE));
}
$model = $this->getModel('form', 'FabrikFEModel');
$viewName = $input->get('view', 'form');
$view = $this->getView($viewName, JFactory::getDocument()->getType());
if (!JError::isError($model))
{
$view->setModel($model, true);
}
$model->setId($input->getInt('formid', 0));
$model->packageId = $input->getInt('packageId');
$this->isMambot = $input->get('isMambot', 0);
$form = $model->getForm();
$model->_rowId = $input->get('rowid', '', 'string');
/**
* $$$ hugh - need this in plugin manager to be able to treat a "Copy" form submission
* as 'new' for purposes of running plugins. Rob's comment in model process() seems to
* indicate that origRowId was for this purposes, but it doesn't work, 'cos always has a value.
*/
if ($input->get('Copy', '') != '')
{
$model->copyingRow(true);
}
// Check for request forgeries
if ($model->spoofCheck())
{
JSession::checkToken() or die('Invalid Token');
}
$validated = $model->validate();
if (!$validated)
{
// If its in a module with ajax or in a package or inline edit
if ($input->get('fabrik_ajax'))
{
if ($input->getInt('elid', 0) !== 0)
{
// Inline edit
$eMsgs = array();
$errs = $model->getErrors();
// Only raise errors for fields that are present in the inline edit plugin
$toValidate = array_keys($input->get('toValidate', array(), 'array'));
foreach ($errs as $errorKey => $e)
{
if (in_array($errorKey, $toValidate) && count($e[0]) > 0)
{
array_walk_recursive($e, array('FabrikString', 'forHtml'));
$eMsgs[] = count($e[0]) === 1 ? '<li>' . $e[0][0] . '</li>' : '<ul><li>' . implode('</li><li>', $e[0]) . '</ul>';
}
}
if (!empty($eMsgs))
{
$eMsgs = '<ul>' . implode('</li><li>', $eMsgs) . '</ul>';
header('HTTP/1.1 500 ' . JText::_('COM_FABRIK_FAILED_VALIDATION') . $eMsgs);
jexit();
}
else
{
$validated = true;
}
}
else
{
// Package / model
echo $model->getJsonErrors();
}
if (!$validated)
{
return;
}
}
if (!$validated)
{
$this->savepage();
if ($this->isMambot)
{
$this->setRedirect($this->getRedirectURL($model, false));
}
else
{
/**
* $$$ rob - http://fabrikar.com/forums/showthread.php?t=17962
* couldn't determine the exact set up that triggered this, but we need to reset the rowid to -1
* if reshowing the form, otherwise it may not be editable, but rather show as a detailed view
*/
if ($input->get('usekey', '') !== '')
{
$input->set('rowid', -1);
}
// Meant that the form's data was in different format - so redirect to ensure that its showing the same data.
$input->set('task', '');
$view->display();
}
return;
}
}
// Reset errors as validate() now returns ok validations as empty arrays
$model->clearErrors();
try
{
$model->process();
}
catch (Exception $e)
{
$model->_arErrors['process_error'] = true;
JError::raiseWarning(500, $e->getMessage());
}
if ($input->getInt('elid', 0) !== 0)
{
// Inline edit show the edited element - ignores validations for now
echo $model->inLineEditResult();
return;
}
// Check if any plugin has created a new validation error
if ($model->hasErrors())
{
FabrikWorker::getPluginManager()->runPlugins('onError', $model);
$view->display();
return;
}
$listModel = $model->getListModel();
$listModel->set('_table', null);
$url = $this->getRedirectURL($model);
$msg = $this->getRedirectMessage($model);
// @todo -should get handed off to the json view to do this
if ($input->getInt('fabrik_ajax') == 1)
{
// $$$ hugh - adding some options for what to do with redirect when in content plugin
// Should probably do this elsewhere, but for now ...
$redirect_opts = array('msg' => $msg, 'url' => $url, 'baseRedirect' => $this->baseRedirect, 'rowid' => $input->get('rowid', '', 'string'));
if (!$this->baseRedirect && $this->isMambot)
{
$session = JFactory::getSession();
$context = $model->getRedirectContext();
$redirect_opts['redirect_how'] = $session->get($context . 'redirect_content_how', 'popup');
$redirect_opts['width'] = (int) $session->get($context . 'redirect_content_popup_width', '300');
$redirect_opts['height'] = (int) $session->get($context . 'redirect_content_popup_height', '300');
$redirect_opts['x_offset'] = (int) $session->get($context . 'redirect_content_popup_x_offset', '0');
$redirect_opts['y_offset'] = (int) $session->get($context . 'redirect_content_popup_y_offset', '0');
$redirect_opts['title'] = $session->get($context . 'redirect_content_popup_title', '');
$redirect_opts['reset_form'] = $session->get($context . 'redirect_content_reset_form', '1') == '1';
}
elseif ($this->isMambot)
{
// $$$ hugh - special case to allow custom code to specify that
// the form should not be cleared after a failed AJAX submit
$session = JFactory::getSession();
$context = 'com_fabrik.form.' . $model->get('id') . '.redirect.';
$redirect_opts['reset_form'] = $session->get($context . 'redirect_content_reset_form', '1') == '1';
}
// Let form.js handle the redirect logic (will also send out a
echo json_encode($redirect_opts);
return;
}
if ($input->get('format') == 'raw')
{
JRequest::setVar('view', 'list');
$this->display();
return;
}
else
{
$this->setRedirect($url, $msg);
}
}
/**
* Get redirect message
*
* @param object $model form model
*
* @since 3.0
*
* @deprecated - use form model getRedirectMessage instead
*
* @return string redirect message
*/
protected function getRedirectMessage($model)
{
return $model->getRedirectMessage();
}
/**
* Get redirect URL
*
* @param object $model form model
* @param bool $incSession set url in session?
*
* @since 3.0
*
* @deprecated - use form model getRedirectUrl() instead
*
* @return string redirect url
*/
protected function getRedirectURL($model, $incSession = true)
{
$res = $model->getRedirectURL($incSession, $this->isMambot);
$this->baseRedirect = $res['baseRedirect'];
return $res['url'];
}
/**
* Validate via ajax
*
* @return null
*/
public function ajax_validate()
{
$app = JFactory::getApplication();
$input = $app->input;
$model = $this->getModel('form', 'FabrikFEModel');
$model->setId($input->getInt('formid', 0));
$model->getForm();
$model->setRowId($input->get('rowid', '', 'string'));
$model->validate();
$data = array('modified' => $model->modifiedValidationData);
// Validating entire group when navigating form pages
$data['errors'] = $model->_arErrors;
echo json_encode($data);
}
/**
* Save a form's page to the session table
*
* @return null
*/
public function savepage()
{
$app = JFactory::getApplication();
$input = $app->input;
$model = $this->getModel('Formsession', 'FabrikFEModel');
$formModel = $this->getModel('Form', 'FabrikFEModel');
$formModel->setId($input->getInt('formid'));
$model->savePage($formModel);
}
/**
* Clear down any temp db records or cookies
* containing partially filled in form data
*
* @return null
*/
public function removeSession()
{
$app = JFactory::getApplication();
$input = $app->input;
$sessionModel = $this->getModel('formsession', 'FabrikFEModel');
$sessionModel->setFormId($input->getInt('formid', 0));
$sessionModel->setRowId($input->get('rowid', '', 'string'));
$sessionModel->remove();
$this->display();
}
/**
* Called via ajax to page through form records
*
* @return null
*/
public function paginate()
{
$app = JFactory::getApplication();
$input = $app->input;
$model = $this->getModel('Form', 'FabrikFEModel');
$model->setId($input->getInt('formid'));
$model->paginateRowId($input->get('dir'));
$this->display();
}
/**
* Delete a record from a form
*
* @return null
*/
public function delete()
{
// Check for request forgeries
JSession::checkToken() or die('Invalid Token');
$app = JFactory::getApplication();
$input = $app->input;
$package = $app->getUserState('com_fabrik.package', 'fabrik');
$model = $this->getModel('list', 'FabrikFEModel');
$ids = array($input->get('rowid', 0));
$listid = $input->getInt('listid');
$limitstart = $input->getInt('limitstart' . $listid);
$length = $input->getInt('limit' . $listid);
$oldtotal = $model->getTotalRecords();
$model->setId($listid);
$ok = $model->deleteRows($ids);
$total = $oldtotal - count($ids);
$ref = $input->get('fabrik_referrer', 'index.php?option=com_' . $package . '&view=list&listid=' . $listid, 'string');
if ($total >= $limitstart)
{
$newlimitstart = $limitstart - $length;
if ($newlimitstart < 0)
{
$newlimitstart = 0;
}
$ref = str_replace("limitstart$listid=$limitstart", "limitstart$listid=$newlimitstart", $ref);
$app = JFactory::getApplication();
$context = 'com_' . $package . '.list.' . $model->getRenderContext() . '.';
$app->setUserState($context . 'limitstart', $newlimitstart);
}
if ($input->get('format') == 'raw')
{
JRequest::setVar('view', 'list');
$this->display();
}
else
{
$msg = $ok ? count($ids) . ' ' . JText::_('COM_FABRIK_RECORDS_DELETED') : '';
$app->redirect($ref, $msg);
}
}
}
| emundus/v5 | components/com_fabrik/controllers/form.php | PHP | gpl-2.0 | 14,887 |
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2008 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/documents/epl-v10.php
See the LICENSE file in the project's top-level directory for details.
Authors:
* Sebastian Werner (wpbasti)
* Andreas Ecker (ecker)
************************************************************************ */
/**
* @appearance toolbar-button
*/
qx.Class.define("qx.legacy.ui.toolbar.Button",
{
extend : qx.legacy.ui.form.Button,
/*
*****************************************************************************
PROPERTIES
*****************************************************************************
*/
properties :
{
// Omit focus
tabIndex :
{
refine : true,
init : -1
},
appearance :
{
refine : true,
init : "toolbar-button"
},
show :
{
refine : true,
init : "inherit"
},
height :
{
refine : true,
init : null
},
allowStretchY :
{
refine : true,
init : true
}
},
/*
*****************************************************************************
MEMBERS
*****************************************************************************
*/
members :
{
/*
---------------------------------------------------------------------------
EVENT HANDLER
---------------------------------------------------------------------------
*/
/**
* @signature function()
*/
_onkeydown : qx.lang.Function.returnTrue,
/**
* @signature function()
*/
_onkeyup : qx.lang.Function.returnTrue
}
});
| omid/webian | usr/qx/sdk/framework/source/class/qx/legacy/ui/toolbar/Button.js | JavaScript | gpl-2.0 | 1,870 |
<?php
class WCML_Emails{
private $order_id = false;
private $locale = false;
function __construct(){
add_action('init', array($this, 'init'));
}
function init(){
//wrappers for email's header
if(is_admin() && !defined( 'DOING_AJAX' )){
add_action('woocommerce_order_status_completed_notification', array($this, 'email_heading_completed'),9);
add_action('woocommerce_order_status_changed', array($this, 'comments_language'),10);
}
add_action('woocommerce_new_customer_note_notification', array($this, 'email_heading_note'),9);
add_action('wp_ajax_woocommerce_mark_order_complete',array($this,'email_refresh_in_ajax'),9);
add_action( 'woocommerce_order_status_pending_to_processing_notification', array( $this, 'email_heading_processing' ) );
add_action( 'woocommerce_order_status_pending_to_on-hold_notification', array( $this, 'email_heading_processing' ) );
//wrappers for email's body
add_action('woocommerce_before_resend_order_emails', array($this, 'email_header'));
add_action('woocommerce_after_resend_order_email', array($this, 'email_footer'));
add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 9, 3 );
//WPML job link
add_filter('icl_job_edit_url',array($this,'icl_job_edit_url'),10 ,2);
//filter string language before for emails
add_filter('icl_current_string_language',array($this,'icl_current_string_language'),10 ,2);
//change order status
add_action('woocommerce_order_status_completed',array($this,'refresh_email_lang_complete'),9);
add_action('woocommerce_order_status_pending_to_processing_notification',array($this,'refresh_email_lang'),9);
add_action('woocommerce_order_status_pending_to_on-hold_notification',array($this,'refresh_email_lang'),9);
add_action('woocommerce_new_customer_note',array($this,'refresh_email_lang'),9);
//admin emails
add_action( 'woocommerce_order_status_pending_to_processing_notification', array( $this, 'admin_email' ), 9 );
add_action( 'woocommerce_order_status_pending_to_completed_notification', array( $this, 'admin_email' ), 9 );
add_action( 'woocommerce_order_status_pending_to_on-hold_notification', array( $this, 'admin_email' ), 9 );
add_action( 'woocommerce_order_status_failed_to_processing_notification', array( $this, 'admin_email' ), 9 );
add_action( 'woocommerce_order_status_failed_to_completed_notification', array( $this, 'admin_email' ), 9 );
add_action( 'woocommerce_order_status_failed_to_on-hold_notification', array( $this, 'admin_email' ), 9 );
add_filter( 'icl_st_admin_string_return_cached', array( $this, 'admin_string_return_cached' ), 10, 2 );
add_filter( 'plugin_locale', array( $this, 'set_locale_for_emails' ), 10, 2 );
}
function email_refresh_in_ajax(){
if(isset($_GET['order_id'])){
$this->refresh_email_lang($_GET['order_id']);
$this->email_heading_completed($_GET['order_id'],true);
}
}
function refresh_email_lang_complete( $order_id ){
$this->order_id = $order_id;
$this->refresh_email_lang($order_id);
$this->email_heading_completed($order_id,true);
}
/**
* Translate WooCommerce emails.
*
* @global type $sitepress
* @global type $order_id
* @return type
*/
function email_header($order) {
if (is_array($order)) {
$order = $order['order_id'];
} elseif (is_object($order)) {
$order = $order->id;
}
$this->refresh_email_lang($order);
}
function refresh_email_lang($order_id){
if(is_array($order_id)){
if(isset($order_id['order_id'])){
$order_id = $order_id['order_id'];
}else{
return;
}
}
$lang = get_post_meta($order_id, 'wpml_language', TRUE);
if(!empty($lang)){
$this->change_email_language($lang);
}
}
/**
* After email translation switch language to default.
*
* @global type $sitepress
* @return type
*/
function email_footer() {
global $sitepress;
$sitepress->switch_lang($sitepress->get_default_language());
}
function comments_language(){
global $sitepress_settings;
if ( WPML_SUPPORT_STRINGS_IN_DIFF_LANG ) {
$context_ob = icl_st_get_context( 'woocommerce' );
if($context_ob){
$this->change_email_language($context_ob->language);
}
}else{
$this->change_email_language($sitepress_settings['st']['strings_language']);
}
}
function email_heading_completed( $order_id, $no_checking = false ){
global $woocommerce;
if(class_exists('WC_Email_Customer_Completed_Order') || $no_checking){
$heading = $this->wcml_get_email_string_info( '[woocommerce_customer_completed_order_settings]heading' );
if($heading)
$woocommerce->mailer()->emails['WC_Email_Customer_Completed_Order']->heading = icl_t($heading[0]->context,'[woocommerce_customer_completed_order_settings]heading',$heading[0]->value);
$subject = $this->wcml_get_email_string_info( '[woocommerce_customer_completed_order_settings]subject' );
if($subject)
$woocommerce->mailer()->emails['WC_Email_Customer_Completed_Order']->subject = icl_t($subject[0]->context,'[woocommerce_customer_completed_order_settings]subject',$subject[0]->value);
$heading_downloadable = $this->wcml_get_email_string_info( '[woocommerce_customer_completed_order_settings]heading_downloadable' );
if($heading_downloadable)
$woocommerce->mailer()->emails['WC_Email_Customer_Completed_Order']->heading_downloadable = icl_t($heading_downloadable[0]->context,'[woocommerce_customer_completed_order_settings]heading_downloadable',$heading_downloadable[0]->value);
$subject_downloadable = $this->wcml_get_email_string_info( '[woocommerce_customer_completed_order_settings]subject_downloadable' );
if($subject_downloadable)
$woocommerce->mailer()->emails['WC_Email_Customer_Completed_Order']->subject_downloadable = icl_t($subject_downloadable[0]->context,'[woocommerce_customer_completed_order_settings]subject_downloadable',$subject_downloadable[0]->value);
$enabled = $woocommerce->mailer()->emails['WC_Email_Customer_Completed_Order']->enabled;
$woocommerce->mailer()->emails['WC_Email_Customer_Completed_Order']->enabled = false;
$woocommerce->mailer()->emails['WC_Email_Customer_Completed_Order']->trigger($order_id);
$woocommerce->mailer()->emails['WC_Email_Customer_Completed_Order']->enabled = $enabled;
}
}
function email_heading_processing($order_id){
global $woocommerce;
if(class_exists('WC_Email_Customer_Processing_Order')){
$heading = $this->wcml_get_email_string_info( '[woocommerce_customer_processing_order_settings]heading' );
if($heading)
$woocommerce->mailer()->emails['WC_Email_Customer_Processing_Order']->heading = icl_t($heading[0]->context,'[woocommerce_customer_processing_order_settings]heading',$heading[0]->value);
$subject = $this->wcml_get_email_string_info( '[woocommerce_customer_processing_order_settings]subject' );
if($subject)
$woocommerce->mailer()->emails['WC_Email_Customer_Processing_Order']->subject = icl_t($subject[0]->context,'[woocommerce_customer_processing_order_settings]subject',$subject[0]->value);
$enabled = $woocommerce->mailer()->emails['WC_Email_Customer_Processing_Order']->enabled;
$woocommerce->mailer()->emails['WC_Email_Customer_Processing_Order']->enabled = false;
$woocommerce->mailer()->emails['WC_Email_Customer_Processing_Order']->trigger($order_id);
$woocommerce->mailer()->emails['WC_Email_Customer_Processing_Order']->enabled = $enabled;
}
}
function email_heading_note($args){
global $woocommerce,$sitepress;
if(class_exists('WC_Email_Customer_Note')){
$heading = $this->wcml_get_email_string_info( '[woocommerce_customer_note_settings]heading' );
if($heading)
$woocommerce->mailer()->emails['WC_Email_Customer_Note']->heading = icl_t($heading[0]->context,'[woocommerce_customer_note_settings]heading',$heading[0]->value);
$subject = $this->wcml_get_email_string_info( '[woocommerce_customer_note_settings]subject' );
if($subject)
$woocommerce->mailer()->emails['WC_Email_Customer_Note']->subject = icl_t($subject[0]->context,'[woocommerce_customer_note_settings]subject',$subject[0]->value);
$enabled = $woocommerce->mailer()->emails['WC_Email_Customer_Note']->enabled;
$woocommerce->mailer()->emails['WC_Email_Customer_Note']->enabled = false;
$woocommerce->mailer()->emails['WC_Email_Customer_Note']->trigger($args);
$woocommerce->mailer()->emails['WC_Email_Customer_Note']->enabled = $enabled;
}
}
function admin_email($order_id){
global $woocommerce,$sitepress;
if(class_exists('WC_Email_New_Order')){
$recipients = explode(',',$woocommerce->mailer()->emails['WC_Email_New_Order']->get_recipient());
foreach($recipients as $recipient){
$user = get_user_by('email',$recipient);
if($user){
$user_lang = $sitepress->get_user_admin_language($user->ID);
}else{
$user_lang = get_post_meta($order_id, 'wpml_language', TRUE);
}
$this->change_email_language($user_lang);
$heading = $this->wcml_get_email_string_info( '[woocommerce_new_order_settings]heading' );
if($heading)
$woocommerce->mailer()->emails['WC_Email_New_Order']->heading = icl_t($heading[0]->context,'[woocommerce_new_order_settings]heading',$heading[0]->value);
$subject = $this->wcml_get_email_string_info( '[woocommerce_new_order_settings]subject' );
if($subject)
$woocommerce->mailer()->emails['WC_Email_New_Order']->subject = icl_t($subject[0]->context,'[woocommerce_new_order_settings]subject',$subject[0]->value);
$woocommerce->mailer()->emails['WC_Email_New_Order']->recipient = $recipient;
$woocommerce->mailer()->emails['WC_Email_New_Order']->trigger($order_id);
}
$woocommerce->mailer()->emails['WC_Email_New_Order']->enabled = false;
$this->refresh_email_lang($order_id);
}
}
function change_email_language($lang){
global $sitepress,$woocommerce;
$sitepress->switch_lang($lang,true);
$this->locale = $sitepress->get_locale( $lang );
unload_textdomain('woocommerce');
unload_textdomain('default');
$woocommerce->load_plugin_textdomain();
load_default_textdomain();
global $wp_locale;
$wp_locale = new WP_Locale();
}
function icl_job_edit_url($link,$job_id){
global $wpdb,$sitepress;
$trid = $wpdb->get_var($wpdb->prepare("
SELECT t.trid
FROM {$wpdb->prefix}icl_translate_job j
JOIN {$wpdb->prefix}icl_translation_status s ON j.rid = s.rid
JOIN {$wpdb->prefix}icl_translations t ON s.translation_id = t.translation_id
WHERE j.job_id = %d
", $job_id));
if($trid){
$original_product_id = $wpdb->get_var($wpdb->prepare("
SELECT element_id
FROM {$wpdb->prefix}icl_translations
WHERE trid = %d AND element_type = 'post_product' AND source_language_code IS NULL
", $trid ));
if($original_product_id){
$link = admin_url('admin.php?page=wpml-wcml&tab=products&prid='.$original_product_id);
}
}
return $link;
}
function email_instructions($order, $sent_to_admin, $plain_text = false){
global $woocommerce_wpml;
$woocommerce_wpml->strings->translate_payment_instructions($order->payment_method);
}
function admin_string_return_cached( $value, $option ){
if( in_array( $option, array ( 'woocommerce_email_from_address', 'woocommerce_email_from_name' ) ) )
return false;
return $value;
}
function wcml_get_email_string_info( $name ){
global $wpdb;
if ( WPML_SUPPORT_STRINGS_IN_DIFF_LANG ) {
$result = $wpdb->get_results( $wpdb->prepare( "SELECT st.value,cn.context FROM {$wpdb->prefix}icl_strings as st LEFT JOIN {$wpdb->prefix}icl_string_contexts as cn ON st.context_id = cn.id WHERE st.name = %s ", $name ) );
}else{
global $sitepress_settings;
$language = $sitepress_settings['st']['strings_language'];
$result = $wpdb->get_results( $wpdb->prepare( "SELECT value,context FROM {$wpdb->prefix}icl_strings WHERE language = %s AND name = %s ", $language, $name ) );
}
return $result;
}
function icl_current_string_language( $current_language, $name ){
$order_id = false;
if( isset($_POST['action']) && $_POST['action'] == 'editpost' && isset($_POST['post_type']) && $_POST['post_type'] == 'shop_order' ){
$order_id = filter_input( INPUT_POST, 'post_ID', FILTER_SANITIZE_NUMBER_INT );
}elseif( isset($_POST['action']) && $_POST['action'] == 'woocommerce_add_order_note' && isset($_POST['note_type']) && $_POST['note_type'] == 'customer' ) {
$order_id = filter_input( INPUT_POST, 'post_id', FILTER_SANITIZE_NUMBER_INT );
}elseif( isset($_GET['action']) && isset($_GET['order_id']) && ( $_GET['action'] == 'woocommerce_mark_order_complete' || $_GET['action'] == 'woocommerce_mark_order_status') ){
$order_id = filter_input( INPUT_GET, 'order_id', FILTER_SANITIZE_NUMBER_INT );
}elseif(isset($_GET['action']) && $_GET['action'] == 'mark_completed' && $this->order_id){
$order_id = $this->order_id;
}
if( $order_id ){
$order_language = get_post_meta( $order_id, 'wpml_language', true );
if( $order_language ){
return $order_language;
}else{
global $sitepress;
return $sitepress->get_current_language();
}
}
return $current_language;
}
// set correct locale code for emails
function set_locale_for_emails( $locale, $domain ){
if( $domain == 'woocommerce' && $this->locale ){
$locale = $this->locale;
}
return $locale;
}
} | wangejay/asiagolfshop_ej | wp-content/plugins/woocommerce-multilingual/inc/emails.class.php | PHP | gpl-2.0 | 15,179 |
<?php
/**
* The template for displaying all pages
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages and that other
* 'pages' on your WordPress site will use a different template.
*
* @package WordPress
* @subpackage Twenty_Thirteen
* @since Twenty Thirteen 1.0
*/
get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php?>
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="entry-content">
<?php the_content(); ?>
</div>
<footer class="entry-meta">
<?php edit_post_link( __( 'Edit', 'twentythirteen' ), '<span class="edit-link">', '</span>' ); ?>
</footer>
</article>
<?php endwhile; ?>
</div>
</div>
<?php get_footer(); ?> | afroldann/ManaWynwood-Redesign | wp-content/themes/manawynwood/page.php | PHP | gpl-2.0 | 891 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
namespace kontroll
{
class Rocket : Projectile
{
public enum Type { Homing, Straight, Slowing}
private float decay;
private Type type;
private Vector2 target;
public Rocket(Vector2 position, float angle, float speed, float decay, Type type, Vector2 target, bool enemy)
: base(position, angle, speed, enemy)
{
this.decay = decay;
SpriteCoords = new Point(Frame(1, 32), 10);
SpriteSize = new Point(8, 8);
this.type = type;
this.Rotation = angle;
this.target = target;
}
public override void Update()
{
if (type == Type.Homing)
{
Angle = (float)Math.Atan2(Position.Y - target.Y, Position.X - target.X);
}
else if (type == Type.Slowing)
{
Speed = (Speed >= decay) ? Speed - decay : Speed;
}
base.Update();
}
}
}
| Easy-Group-Teknik/TeknikShmup2015 | kontroll/kontroll/kontroll/Rocket.cs | C# | gpl-2.0 | 1,129 |
<?php
/*
Plugin Name: Memphis Custom Login
Plugin URI: http://www.kingofnothing.net
Description: A simple way to control your WordPress Login Page, features include Password Protected Blog, Custom Redirect after login, Changing the look of the Login Screen.
Author: Ian Howatson
Version: 3.2.3
Author URI: http://www.kingofnothing.net/
Date: 05/03/2016
Copyright 2016 Ian Howatson (email : ian@howatson.net)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
include 'localization.php';
include 'mwpl-dashboard.php';
include 'mwpl-dashboard-custom-login.php';
include 'mwpl-init.php';
include 'mwpl-functions.php';
include 'mwpl-upgrade.php';
include 'mwpl-inline-style.php';
add_action('login_enqueue_scripts', 'mwpl_custom_login_init');
add_action( 'admin_enqueue_scripts', 'mwpl_dashboard_init' );
add_action('admin_menu', 'mwpl_dashboard_menu');
// REDIRECT AFTER LOGIN TO DIFFERENT PAGE
function mwpl_change_login_redirect() {
global $redirect_to;
$site_url = site_url();
$redirect = get_option('mwpl_redirect_login');
$custom_page = get_option('mwpl_custom_redirect_page');
//echo $custom_page;
switch($redirect) {
case 'dashboard':
break;
case 'home':
//if(!FORCE_SSL_LOGIN || FORCE_SSL_LOGIN == null) $site_url = preg_replace('/https/','http',MWPL_HOME_PAGE);
//else $site_url = MWPL_HOME_PAGE;
if ($redirect_to == $site_url.'/wp-admin/') { $redirect_to = $site_url; }
break;
case 'profile':
if ($redirect_to == $site_url.'/wp-admin/') { $redirect_to = MWPL_PROFILE_PAGE; }
break;
//case 'buddypress-profile':
//if ($redirect_to == $site_url.'/wp-admin/') { $redirect_to = bp_loggedin_user_domain($user->ID); }
//break;
case 'custom':
//if(!FORCE_SSL_LOGIN && !preg_match('/wp-admin/',$custom_page)) $site_url = preg_replace('/https/','http',$site_url);
//if(!FORCE_SSL_ADMIN) $site_url = preg_replace('/https/','http',$site_url);
if ($custom_page != '') { $redirect_to = ($site_url.'/'.$custom_page); }
break;
default:
break;
}
}
add_action('login_form','mwpl_change_login_redirect');
//////////
//PASSWORD PROTECT SITE//
function mwpl_password_protected() {
//Password Protected Blog
$mwpl_password_protected = get_option('mwpl_password_protected',null);
if(is_ssl()) $site_url = preg_replace('/http/','https',get_option('siteurl'));
else $site_url == get_option('siteurl');
if($mwpl_password_protected) {
if (!is_user_logged_in() && $_SERVER['REQUEST_URI'] != "/") {
wp_safe_redirect(get_bloginfo('wpurl').'/wp-login.php?redirect_to='.urlencode($_SERVER['REQUEST_URI']));
} else if (!is_user_logged_in()) {
wp_safe_redirect($site_url .'/wp-login.php');
}
}
}
function mwpl_bp_password_protected() {
global $bp, $bp_unfiltered_uri;
if(defined('BP_MEMBERS_SLUG') && defined('BP_GROUPS_SLUG')) {
if (!is_user_logged_in() && (BP_MEMBERS_SLUG == $bp_unfiltered_uri[0] || BP_GROUPS_SLUG == $bp->current_component )) {
bp_core_redirect(get_bloginfo('wpurl') . '/wp-login.php');
}
}
}
add_action('login_head', 'rsd_link');
add_action('login_head', 'wlwmanifest_link');
add_action('template_redirect', 'mwpl_password_protected');
add_action('do_feed', 'mwpl_password_protected');
add_action( 'wp', 'mwpl_bp_password_protected', 3 );
///////// ADD GOOGLE ANALYTICS ///////
$google_reg = get_option('mwpl_google_analytics');
if($google_reg['enable_pages']) add_action('wp_head', 'mwpl_init_google_analytics');
if($google_reg['enable_login']) add_action('login_head', 'mwpl_init_google_analytics');
if($google_reg['enable_admin']) add_action('admin_head', 'mwpl_init_google_analytics');
////////////////////////////////////////
////////////////////////////////////////
///////// ADD CUSTOM DASHBOARD MESSAGE ///////
function my_admin_notice(){
?>
<div class="updated">
<p><?php _e('<b>Important!!!</b><br/> Memphis Custom Wordpress Login Version 2.0 has been complete overhaul, you will need to redo your custom login screen. This change was made to better match Wordpress functionality and style for easy of customization and easier updating in the future.'); ?></p>
</div>
<?php
}
//update_option('mwpl_admin_notice_00000001', false);
if(get_option('mwpl_admin_notice_00000001') != true) {
add_action('admin_notices', 'my_admin_notice');
update_option('mwpl_admin_notice_00000001', true);
}
////////////////////////////////////////
?> | ifrm/invatacel | wp-content/plugins/memphis-wordpress-custom-login/memphis-wp-login.php | PHP | gpl-2.0 | 4,906 |
/*
* _ __ _
* | |/ /__ __ __ _ _ __ | |_ _ _ _ __ ___
* | ' / \ \ / // _` || '_ \ | __|| | | || '_ ` _ \
* | . \ \ V /| (_| || | | || |_ | |_| || | | | | |
* |_|\_\ \_/ \__,_||_| |_| \__| \__,_||_| |_| |_|
*
* Copyright (C) 2019 Alexander Söderberg
*
* 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 xyz.kvantum.server.api.views;
import xyz.kvantum.files.Path;
import xyz.kvantum.server.api.util.MapBuilder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* Can be used to detect file structures that could be served by the standard library of {@link View views}
*/
@SuppressWarnings("unused") public final class ViewDetector {
private final String basePath;
private final Collection<String> ignore;
private final Path basePathObject;
private final Set<Path> paths = new HashSet<>();
private final Map<String, Map<String, Object>> viewEntries = new HashMap<>();
public ViewDetector(final String basePath, final Path basePathObject,
final Collection<String> ignore) {
this.basePath = basePath;
this.ignore = ignore;
this.basePathObject = basePathObject;
}
public int loadPaths() {
this.paths.add(this.basePathObject);
this.addSubPaths(this.basePathObject);
return this.paths.size();
}
public Collection<Path> getPaths() {
return new ArrayList<>(this.paths);
}
public Map<String, Map<String, Object>> getViewEntries() {
return new HashMap<>(this.viewEntries);
}
public void generateViewEntries() {
this.paths.forEach(p -> loadSubPath(viewEntries, basePath, basePathObject.toString(), p));
}
private void loadSubPath(final Map<String, Map<String, Object>> viewEntries,
final String basePath, final String toRemove, final Path path) {
String extension = null;
boolean moreThanOneType = false;
boolean hasIndex = false;
String indexExtension = "";
for (final Path subPath : path.getSubPaths(false)) {
if (extension == null) {
extension = subPath.getExtension();
} else if (!extension.equalsIgnoreCase(subPath.getExtension())) {
moreThanOneType = true;
}
if (!hasIndex) {
hasIndex = subPath.getEntityName().equals("index");
indexExtension = subPath.getExtension();
}
}
if (extension == null) {
return;
}
final String type;
if (moreThanOneType) {
type = "std";
} else {
switch (extension) {
case "html":
type = "html";
break;
case "js":
type = "javascript";
break;
case "css":
type = "css";
break;
case "png":
case "jpg":
case "jpeg":
case "ico":
type = "img";
break;
case "zip":
case "txt":
case "pdf":
type = "download";
break;
default:
type = "std";
break;
}
}
final String folder = "./" + path.toString();
final String viewPattern;
if (moreThanOneType) {
if (hasIndex) {
viewPattern =
(path.toString().replace(toRemove, basePath)) + "[file=index].[extension="
+ indexExtension + "]";
} else {
viewPattern = (path.toString().replace(toRemove, basePath)) + "<file>.<extension>";
}
} else {
if (hasIndex) {
viewPattern =
(path.toString().replace(toRemove, basePath)) + "[file=index].[extension="
+ indexExtension + "]";
} else {
viewPattern = (path.toString().replace(toRemove, basePath)) + "<file>." + extension;
}
}
final Map<String, Object> info =
MapBuilder.<String, Object>newHashMap().put("filter", viewPattern)
.put("options", MapBuilder.newHashMap().put("folder", folder).get())
.put("type", type).get();
viewEntries.put(UUID.randomUUID().toString(), info);
}
private void addSubPaths(final Path path) {
for (final Path subPath : path.getSubPaths()) {
if (!subPath.isFolder() || ignore.contains(subPath.getEntityName())) {
continue;
}
paths.add(subPath);
addSubPaths(subPath);
}
}
}
| IntellectualSites/IntellectualServer | ServerAPI/src/main/java/xyz/kvantum/server/api/views/ViewDetector.java | Java | gpl-2.0 | 5,465 |
package org.albianj.persistence.impl.db;
import java.util.Map;
import org.albianj.persistence.object.IAlbianObject;
import org.albianj.persistence.object.IAlbianObjectAttribute;
import org.albianj.persistence.object.IRoutingAttribute;
import org.albianj.persistence.object.IRoutingsAttribute;
public interface IUpdateCommand
{
public ICommand builder(IAlbianObject object,
IRoutingsAttribute routings, IAlbianObjectAttribute albianObject,
Map<String, Object> mapValue, IRoutingAttribute routing);
}
| xvhfeng/albianj | Albianj.Persistence.Impl/src/main/java/org/albianj/persistence/impl/db/IUpdateCommand.java | Java | gpl-2.0 | 524 |
/***************************************************************/
/** **/
/** Leonardo Haddad nº 7295361 **/
/** Desafios de Programação - Round 3 Professora Cris **/
/** Problema 2 - Divide an Island! Curso: BCC **/
/** **/
/***************************************************************/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define MAX_DIST 6000
#define debug_off 1
#define error 1e-9
using namespace std;
int xA, yA, xB, yB, xC, yC;
int xAtoB, yAtoB, xBtoC, yBtoC, xCtoA, yCtoA;
double abLength, bcLength, caLength, fullLength, abPercentage, bcPercentage, caPercentage;
double totalArea;
#ifdef debug_on
/* print arguments */
void printArgs () {
printf("Arguments:\n");
printf(" A = %d %d;\n",xA,yA);
printf(" B = %d %d;\n",xB,yB);
printf(" C = %d %d;\n",xC,yC);
}
#endif
double normalizedToX (double normalizedValue)
{
if (normalizedValue < abPercentage)
{
return xA + xAtoB * (normalizedValue / abPercentage);
}
else if (normalizedValue < abPercentage + bcPercentage)
{
return xB + xBtoC * ((normalizedValue - abPercentage) / bcPercentage);
}
else
{
return xC + xCtoA * ((normalizedValue - abPercentage - bcPercentage) / caPercentage);
}
}
double normalizedToY (double normalizedValue)
{
if (normalizedValue < abPercentage)
{
return yA + yAtoB * (normalizedValue / abPercentage);
}
else if (normalizedValue < abPercentage + bcPercentage)
{
return yB + yBtoC * ((normalizedValue - abPercentage) / bcPercentage);
}
else
{
return yC + yCtoA * ((normalizedValue - abPercentage - bcPercentage) / caPercentage);
}
}
double areaFromPointsViaHeronFormula (double pxA, double pyA, double pxB, double pyB, double pxC, double pyC)
{
double abL = sqrt((pxB-pxA)*(pxB-pxA)+(pyB-pyA)*(pyB-pyA));
double bcL = sqrt((pxC-pxB)*(pxC-pxB)+(pyC-pyB)*(pyC-pyB));
double caL = sqrt((pxA-pxC)*(pxA-pxC)+(pyA-pyC)*(pyA-pyC));
double semiPer = (abL + bcL + caL) / 2;
return sqrt(semiPer * (semiPer - abL) * (semiPer - bcL) * (semiPer - caL));
}
double areaFromPointsViaCrossProduct (double pxA, double pyA, double pxB, double pyB, double pxC, double pyC)
{
double abL = sqrt((pxB-pxA)*(pxB-pxA)+(pyB-pyA)*(pyB-pyA));
double bcL = sqrt((pxC-pxB)*(pxC-pxB)+(pyC-pyB)*(pyC-pyB));
double caL = sqrt((pxA-pxC)*(pxA-pxC)+(pyA-pyC)*(pyA-pyC));
double angle = acos((abL*abL+caL*caL-bcL*bcL) / (2*abL*caL));
return (0.5 * abL * caL * sin(angle));
}
double areaFromPoints (double pxA, double pyA, double pxB, double pyB, double pxC, double pyC)
{
//return areaFromPointsViaHeronFormula(pxA,pyA,pxB,pyB,pxC,pyC);
return areaFromPointsViaCrossProduct(pxA,pyA,pxB,pyB,pxC,pyC);
}
double normalizedToArea (double normalizedValue)
{
double otherEdge = normalizedValue + 0.5;
if (otherEdge > 1.0)
otherEdge = otherEdge - 1.0;
if (normalizedValue == 0)
{
return areaFromPoints(xB,yB,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else if (normalizedValue < abPercentage)
{
if (otherEdge < abPercentage+bcPercentage)
{
return areaFromPoints(xB,yB,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else
if (otherEdge <= abPercentage+bcPercentage+caPercentage)
{
return areaFromPoints(xA,yA,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else
printf("error (if1)!\n");
}
else if (normalizedValue == abPercentage)
{
return areaFromPoints(xC,yC,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else if (normalizedValue < abPercentage+bcPercentage)
{
if (otherEdge < abPercentage)
{
return areaFromPoints(xB,yB,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else
if (otherEdge <= abPercentage+bcPercentage+caPercentage)
{
return areaFromPoints(xC,yC,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else
printf("error (if2)!\n");
}
else if (normalizedValue == abPercentage+bcPercentage)
{
return areaFromPoints(xA,yA,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else if (normalizedValue < abPercentage+bcPercentage+caPercentage)
{
if (otherEdge < abPercentage)
{
return areaFromPoints(xA,yA,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else
if (otherEdge < abPercentage+bcPercentage)
{
return areaFromPoints(xC,yC,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else
printf("error (if3)!\n");
}
else if (normalizedValue == abPercentage+bcPercentage+caPercentage)
{
return areaFromPoints(xB,yB,normalizedToX(normalizedValue),normalizedToY(normalizedValue),normalizedToX(otherEdge),normalizedToY(otherEdge));
}
else
printf("error (final)!\n");
return -1;
}
void bruteForceSolution () {
int precision;
double attempt, dist, from, to, area, normalizedValueA, normalizedValueB;
totalArea = areaFromPoints(xA,yA,xB,yB,xC,yC);
#ifdef debug_on
printf(" totalArea: %.15f\n",totalArea);
#endif
dist = MAX_DIST;
normalizedValueA = -1;
precision = 4;
from = 0;
to = 0.5;
while (precision < 15)
{
attempt = from;
while (attempt < to)
{
area = normalizedToArea(attempt);
if (abs(area - totalArea/2) < dist)
{
dist = abs(area - totalArea/2);
normalizedValueA = attempt;
}
#ifdef debug_on
printf(" %.15f: (%.2f %.2f) ; area = %.15f\n",attempt,normalizedToX(attempt),normalizedToY(attempt),area);
#endif
attempt = attempt + pow(10,-precision);
}
from = normalizedValueA - pow(10,-precision);
to = normalizedValueA + pow(10,-precision);
if (from < 0)
from = 0;
if (to > 0.5)
to = 0.5;
precision++;
}
normalizedValueB = normalizedValueA + 0.5;
if (normalizedValueB >= 1.0)
normalizedValueB = normalizedValueB - 1.0;
if (dist < error)
printf("YES\n%.15f %.15f\n%.15f %.15f\n", normalizedToX(normalizedValueA), normalizedToY(normalizedValueA), normalizedToX(normalizedValueB), normalizedToY(normalizedValueB));
else
printf("NO\n");
}
int main () {
double semiPerimeter, linearFactorA, linearFactorB, ansXa, ansYa, ansXb, ansYb;
bool finished;
#ifdef debug_on
printf("\n| P2 - Divide an Island! |\n");
#endif
/* read program arguments */
scanf("%d %d %d %d %d %d", &xA, &yA, &xB, &yB, &xC, &yC);
#ifdef debug_on
printArgs();
printf("\nProblem Solution:\n");
#endif
/* solution */
xAtoB = xB - xA;
yAtoB = yB - yA;
xBtoC = xC - xB;
yBtoC = yC - yB;
xCtoA = xA - xC;
yCtoA = yA - yC;
abLength = sqrt(xAtoB*xAtoB + yAtoB*yAtoB);
bcLength = sqrt(xBtoC*xBtoC + yBtoC*yBtoC);
caLength = sqrt(xCtoA*xCtoA + yCtoA*yCtoA);
fullLength = abLength + bcLength + caLength;
semiPerimeter = fullLength / 2;
abPercentage = abLength / fullLength;
bcPercentage = bcLength / fullLength;
caPercentage = caLength / fullLength;
//bruteForceSolution();
finished = false;
linearFactorA = (semiPerimeter - sqrt(semiPerimeter * semiPerimeter - 2 * abLength * bcLength)) / 2;
linearFactorB = (semiPerimeter + sqrt(semiPerimeter * semiPerimeter - 2 * abLength * bcLength)) / 2;
if(linearFactorA <= abLength + error && linearFactorB <= bcLength + error) {
ansXa = xB - xAtoB * (linearFactorA / abLength);
ansYa = yB - yAtoB * (linearFactorA / abLength);
ansXb = xB + xBtoC * (linearFactorB / bcLength);
ansYb = yB + yBtoC * (linearFactorB / bcLength);
printf("YES\n%.15f %.15f\n%.15f %.15f\n", ansXa, ansYa, ansXb, ansYb);
finished = true;
}
if(!finished && linearFactorB <= abLength + error && linearFactorA <= bcLength + error) {
ansXa = xB - xAtoB * (linearFactorB / abLength);
ansYa = yB - yAtoB * (linearFactorB / abLength);
ansXb = xB + xBtoC * (linearFactorA / bcLength);
ansYb = yB + yBtoC * (linearFactorA / bcLength);
printf("YES\n%.15f %.15f\n%.15f %.15f\n", ansXa, ansYa, ansXb, ansYb);
finished = true;
}
linearFactorA = (semiPerimeter - sqrt(semiPerimeter * semiPerimeter - 2 * bcLength * caLength)) / 2;
linearFactorB = (semiPerimeter + sqrt(semiPerimeter * semiPerimeter - 2 * bcLength * caLength)) / 2;
if(!finished && linearFactorA <= bcLength + error && linearFactorB <= caLength + error) {
ansXa = xC - xBtoC * (linearFactorA / bcLength);
ansYa = yC - yBtoC * (linearFactorA / bcLength);
ansXb = xC + xCtoA * (linearFactorB / caLength);
ansYb = yC + yCtoA * (linearFactorB / caLength);
printf("YES\n%.15f %.15f\n%.15f %.15f\n", ansXa, ansYa, ansXb, ansYb);
finished = true;
}
if(!finished && linearFactorB <= bcLength + error && linearFactorA <= caLength + error) {
ansXa = xC - xBtoC * (linearFactorB / bcLength);
ansYa = yC - yBtoC * (linearFactorB / bcLength);
ansXb = xC + xCtoA * (linearFactorA / caLength);
ansYb = yC + yCtoA * (linearFactorA / caLength);
printf("YES\n%.15f %.15f\n%.15f %.15f\n", ansXa, ansYa, ansXb, ansYb);
finished = true;
}
linearFactorA = (semiPerimeter - sqrt(semiPerimeter * semiPerimeter - 2 * caLength * abLength)) / 2;
linearFactorB = (semiPerimeter + sqrt(semiPerimeter * semiPerimeter - 2 * caLength * abLength)) / 2;
if(!finished && linearFactorA <= caLength + error && linearFactorB <= abLength + error) {
ansXa = xA - xCtoA * (linearFactorA / caLength);
ansYa = yA - yCtoA * (linearFactorA / caLength);
ansXb = xA + xAtoB * (linearFactorB / abLength);
ansYb = yA + yAtoB * (linearFactorB / abLength);
printf("YES\n%.15f %.15f\n%.15f %.15f\n", ansXa, ansYa, ansXb, ansYb);
finished = true;
}
if(!finished && linearFactorB <= caLength + error && linearFactorA <= abLength + error) {
ansXa = xA - xCtoA * (linearFactorB / caLength);
ansYa = yA - yCtoA * (linearFactorB / caLength);
ansXb = xA + xAtoB * (linearFactorA / abLength);
ansYb = yA + yAtoB * (linearFactorA / abLength);
printf("YES\n%.15f %.15f\n%.15f %.15f\n", ansXa, ansYa, ansXb, ansYb);
finished = true;
}
if (!finished)
{
printf("NO\n");
}
#ifdef debug_on
printf("\n--------------------\n");
#endif
return 0;
}
/*
1647. Divide an Island!
Time limit: 1.0 second
Memory limit: 64 MB
Url: http://acm.timus.ru/problem.aspx?space=1&num=1647
A desert island Robinson Crusoe and his companion Friday live on has a shape of a non-degenerate triangle which vertices are points (x1, y1), (x2, y2), (x3, y3). Once Robinson and Friday fell aboard and decided to divide the island into two equal parts by choosing two points on the island coast and connecting them with a line segment. These parts were to have the same area and shore length. Robinson failed to choose these points. Can you do it for him?
Input:
The only line of the input contains space-separated integers x1, y1, x2, y2, x3, y3, not exceeding 2000 in absolute value.
Output:
If there is a line segment ST, which divides the island into two parts of the same area and shore length, output “YES” on the first line of the output, S coordinates on the second line, and T coordinates of the third line. S and T should be located on the island shore. Coordinates should be accurate within 10−9. If there is no such line segment, output “NO” on a single line.
Samples:
Input:
0 0 10 0 0 10
Output:
YES
0 0
5 5
Input:
0 3 4 0 3 4
Output:
YES
1.741248277008306 3.580416092336102
3.445803840397070 0.415647119702198
*/
| leeohaddad/bccimeusp-desafios | r3-p2-divide-an-island.cpp | C++ | gpl-2.0 | 11,839 |
<?php
/*
* @package MijoShop
* @copyright 2009-2013 Miwisoft LLC, miwisoft.com
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
* @license GNU/GPL based on AceShop www.joomace.net
*/
// No Permission
defined('_JEXEC') or die('Restricted access');
// Heading
$_['heading_title'] = 'SagePay';
// Text
$_['text_payment'] = 'Payment';
$_['text_success'] = 'Success: You have modified SagePay account details!';
$_['text_sagepay'] = '<a href="https://support.sagepay.com/apply/default.aspx?PartnerID=E511AF91-E4A0-42DE-80B0-09C981A3FB61" target="_blank"><img src="view/image/payment/sagepay.png" alt="SagePay" title="SagePay" style="border: 1px solid #EEEEEE;" /></a>';
$_['text_sim'] = 'Simulator';
$_['text_test'] = 'Test';
$_['text_live'] = 'Live';
$_['text_defered'] = 'Defered';
$_['text_authenticate'] = 'Authenticate';
// Entry
$_['entry_vendor'] = 'Vendor:';
$_['entry_password'] = 'Password:';
$_['entry_test'] = 'Test Mode:';
$_['entry_transaction'] = 'Transaction Method:';
$_['entry_total'] = 'Total:<br /><span class="help">The checkout total the order must reach before this payment method becomes active.</span>';
$_['entry_order_status'] = 'Order Status:';
$_['entry_geo_zone'] = 'Geo Zone:';
$_['entry_status'] = 'Status:';
$_['entry_sort_order'] = 'Sort Order:';
// Error
$_['error_permission'] = 'Warning: You do not have permission to modify payment SagePay!';
$_['error_vendor'] = 'Vendor ID Required!';
$_['error_password'] = 'Password Required!';
?> | eugeneuskov/modna | components/com_mijoshop/opencart/admin/language/english/payment/sagepay.php | PHP | gpl-2.0 | 1,592 |
<?php // $Id$
/// Overview report: displays a big table of all the attempts
class hotpot_report extends hotpot_default_report {
function display(&$hotpot, &$cm, &$course, &$users, &$attempts, &$questions, &$options) {
global $CFG;
// create the table
$tables = array();
$this->create_scores_table($hotpot, $course, $users, $attempts, $questions, $options, $tables);
$this->print_report($course, $hotpot, $tables, $options);
return true;
}
function create_scores_table(&$hotpot, &$course, &$users, &$attempts, &$questions, &$options, &$tables) {
global $CFG;
$download = ($options['reportformat']=='htm') ? false : true;
$is_html = ($options['reportformat']=='htm');
$blank = ($download ? '' : ' ');
$no_value = ($download ? '' : '-');
$allow_review = true;
// start the table
unset($table);
$table->border = 1;
$table->head = array();
$table->align = array();
$table->size = array();
// picture column, if required
if ($is_html) {
$table->head[] = ' ';
$table->align[] = 'center';
$table->size[] = 10;
}
// name, grade and attempt number
array_push($table->head,
get_string("name"),
hotpot_grade_heading($hotpot, $options),
get_string("attempt", "quiz")
);
array_push($table->align, "left", "center", "center");
array_push($table->size, '', '', '');
// question headings
$this->add_question_headings($questions, $table);
// penalties and raw score
array_push($table->head,
get_string('penalties', 'hotpot'),
get_string('score', 'quiz')
);
array_push($table->align, "center", "center");
array_push($table->size, '', '');
$table->data = array();
$q = array(
'grade' => array('count'=>0, 'total'=>0),
'penalties' => array('count'=>0, 'total'=>0),
'score' => array('count'=>0, 'total'=>0),
);
foreach ($users as $user) {
// shortcut to user info held in first attempt record
$u = &$user->attempts[0];
$picture = '';
$name = fullname($u);
if ($is_html) {
$picture = print_user_picture($u->userid, $course->id, $u->picture, false, true);
$name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$u->userid.'&course='.$course->id.'">'.$name.'</a>';
}
if (isset($user->grade)) {
$grade = $user->grade;
$q['grade']['count'] ++;
if (is_numeric($grade)) {
$q['grade']['total'] += $grade;
}
} else {
$grade = $no_value;
}
$attemptcount = count($user->attempts);
if ($attemptcount>1) {
$text = $name;
$name = NULL;
$name->text = $text;
$name->rowspan = $attemptcount;
$text = $grade;
$grade = NULL;
$grade->text = $text;
$grade->rowspan = $attemptcount;
}
$data = array();
if ($is_html) {
if ($attemptcount>1) {
$text = $picture;
$picture = NULL;
$picture->text = $text;
$picture->rowspan = $attemptcount;
}
$data[] = $picture;
}
array_push($data, $name, $grade);
foreach ($user->attempts as $attempt) {
// set flag if this is best grade
$is_best_grade = ($is_html && $attempt->score==$user->grade);
// get attempt number
$attemptnumber= $attempt->attempt;
if ($is_html && $allow_review) {
$attemptnumber = '<a href="review.php?hp='.$hotpot->id.'&attempt='.$attempt->id.'">'.$attemptnumber.'</a>';
}
if ($is_best_grade) {
$score = '<span class="highlight">'.$attemptnumber.'</span>';
}
$data[] = $attemptnumber;
// get responses to questions in this attempt by this user
foreach ($questions as $id=>$question) {
if (!isset($q[$id])) {
$q[$id] = array('count'=>0, 'total'=>0);
}
if (isset($attempt->responses[$id])) {
$score = $attempt->responses[$id]->score;
if (is_numeric($score)) {
$q[$id]['count'] ++;
$q[$id]['total'] += $score;
if ($is_best_grade) {
$score = '<span class="highlight">'.$score.'</span>';
}
} else if (empty($score)) {
$score = $no_value;
}
} else {
$score = $no_value;
}
$data[] = $score;
} // foreach $questions
if (isset($attempt->penalties)) {
$penalties = $attempt->penalties;
if (is_numeric($penalties)) {
$q['penalties']['count'] ++;
$q['penalties']['total'] += $penalties;
}
if ($is_best_grade) {
$penalties = '<span class="highlight">'.$penalties.'</span>';
}
} else {
$penalties = $no_value;
}
$data[] = $penalties;
if (isset($attempt->score)) {
$score = $attempt->score;
if (is_numeric($score)) {
$q['score']['total'] += $score;
$q['score']['count'] ++;
}
if ($is_best_grade) {
$score = '<span class="highlight">'.$score.'</span>';
}
} else {
$score = $no_value;
}
$data[] = $score;
// append data for this attempt
$table->data[] = $data;
// reset data array for next attempt, if any
$data = array();
} // end foreach $attempt
$table->data[] = 'hr';
} // end foreach $user
// remove final 'hr' from data rows
array_pop($table->data);
// add averages to foot of table
$averages = array();
if ($is_html) {
$averages[] = $blank;
}
array_push($averages, get_string('average', 'hotpot'));
$col = count($averages);
if (empty($q['grade']['count'])) {
// remove score $col from $table
$this->remove_column($table, $col);
} else {
$precision = ($hotpot->grademethod==HOTPOT_GRADEMETHOD_AVERAGE || $hotpot->grade<100) ? 1 : 0;
$averages[] = round($q['grade']['total'] / $q['grade']['count'], $precision);
$col++;
}
// skip the attempt number column
$averages[$col++] = $blank;
foreach ($questions as $id=>$question) {
if (empty($q[$id]['count'])) {
// remove this question $col from $table
$this->remove_column($table, $col);
} else {
$averages[$col++] = round($q[$id]['total'] / $q[$id]['count']);
}
}
if (empty($q['penalties']['count'])) {
// remove penalties $col from $table
$this->remove_column($table, $col);
} else {
$averages[$col++] = round($q['penalties']['total'] / $q['penalties']['count']);
}
if (empty($q['score']['count'])) {
// remove score $col from $table
$this->remove_column($table, $col);
} else {
$averages[$col++] = round($q['score']['total'] / $q['score']['count']);
}
$table->foot = array($averages);
$tables[] = &$table;
}
} // end class
?>
| cwaclawik/moodle | mod/hotpot/report/simplestat/report.php | PHP | gpl-2.0 | 6,386 |
/* Copyright (c) 2010 by CodeSourcery. All rights reserved. */
#ifndef vsip_core_dda_hpp_
#define vsip_core_dda_hpp_
#include <vsip/core/static_assert.hpp>
#include <vsip/core/block_traits.hpp>
#include <vsip/core/metaprogramming.hpp>
#include <vsip/core/storage.hpp>
#include <vsip/core/domain_utils.hpp>
#include <vsip/core/block_copy.hpp>
#include <vsip/core/us_block.hpp>
#include <vsip/core/view_traits.hpp>
#include <vsip/core/assign_local.hpp>
#include <vsip/core/adjust_layout.hpp>
#include <vsip/dda.hpp>
namespace vsip
{
namespace dda
{
namespace impl
{
using namespace vsip::impl;
/// @group Data Access Tags {
/// Direct_access_tag -- use direct access to block data
/// (data, stride member functions).
struct Direct_access_tag {};
/// Reorder_access_tag -- use direct access to block data, but reorder data
/// to match requested dimension-order.
struct Reorder_access_tag {};
/// Copy_access_tag -- copy block data (either using direct access if
/// available, or just get/put).
struct Copy_access_tag {};
/// Flexible_access_tag -- determine whether to use direct or copy access
/// at runtime.
struct Flexible_access_tag {};
/// }
#if VSIP_IMPL_REF_IMPL
template <typename Block, typename L>
struct Choose_access
{
typedef typename vsip::impl::remove_const<Block>::type block_type;
typedef typename get_block_layout<block_type>::type block_layout_type;
typedef typename
conditional<supports_dda<block_type>::value &&
is_same<block_layout_type, L>::value,
Direct_access_tag, Copy_access_tag>::type
type;
};
#endif
struct direct; // Use dda::Data directly on block.
struct local; // Use dda::Data on get_local_block of block
struct remap; // Use dda::Data on reorganized block.
template <typename Block, typename L>
struct Choose_impl_tag
{
static dimension_type const dim = L::dim;
typedef typename vsip::impl::remove_const<Block>::type block_type;
typedef typename block_type::value_type value_type;
typedef typename block_type::map_type map_type;
typedef typename get_block_layout<block_type>::type block_layout_type;
static bool const local_equiv =
is_layout_compatible<value_type, L, block_layout_type>::value &&
is_same<Replicated_map<dim>, map_type>::value;
static bool const equiv = local_equiv &&
adjust_type<Local_map, map_type>::equiv;
static bool const is_local = is_same<Local_map, map_type>::value;
typedef typename
conditional<is_local, direct,
typename conditional<local_equiv, local,
remap>::type>::type
type;
};
/// Low-level data access class.
///
/// Template parameters:
///
/// :Block: is a block that supports the data access interface indicated
/// by `AT`.
/// :LP: is a layout policy compatible with access tag `AT` and block
/// `Block`.
/// :AT: is a valid data access tag,
///
/// (Each specializtion may provide additional requirements).
///
/// Member Functions:
/// ...
///
/// Notes:
/// Accessor does not hold a block reference/pointer, it
/// is provided to each member function by the caller. This allows
/// the caller to make policy decisions, such as reference counting.
template <typename Block,
typename LP,
typename AT,
typename Impl = typename Choose_impl_tag<Block, LP>::type>
class Accessor;
/// Specialization for low-level direct data access.
///
/// Template parameters:
/// BLOCK to be a block that supports direct access via member
/// functions ptr() and stride().
/// LP is a layout policy describing the desired layout. It is should
/// match the inherent layout of the block. Specifying a layout
/// not directly supported by the block is an error and results in
/// undefined behavior.
template <typename Block,
typename LP>
class Accessor<Block, LP, Direct_access_tag, direct>
{
// Compile time typedefs.
public:
static dimension_type const dim = LP::dim;
typedef typename Block::value_type value_type;
typedef typename LP::order_type order_type;
static pack_type const packing = LP::packing;
static storage_format_type const storage_format = LP::storage_format;
typedef Storage<storage_format, value_type> storage_type;
typedef typename storage_type::type non_const_ptr_type;
typedef typename storage_type::const_type const_ptr_type;
typedef typename
vsip::impl::conditional<vsip::impl::is_modifiable_block<Block>::value,
non_const_ptr_type,
const_ptr_type>::type ptr_type;
static int const CT_Cost = 0;
static bool const CT_Mem_not_req = true;
static bool const CT_Xfer_not_req = true;
static int cost (Block const& /*block*/, LP const& /*layout*/)
{ return CT_Cost; }
static size_t mem_required (Block const& /*block*/, LP const& /*layout*/)
{ return 0; }
static size_t xfer_required(Block const& /*block*/, LP const& /*layout*/)
{ return !CT_Xfer_not_req; }
// Constructor and destructor.
public:
Accessor(Block&, non_const_ptr_type = non_const_ptr_type()) {}
~Accessor() {}
void begin(Block*, bool) {}
void end(Block*, bool) {}
int cost() const { return CT_Cost; }
// Direct data acessors.
public:
ptr_type ptr(Block * blk) const { return blk->ptr();}
stride_type stride(Block* blk, dimension_type d) const { return blk->stride(dim, d);}
length_type size (Block* blk, dimension_type d) const { return blk->size(dim, d);}
length_type size (Block* blk) const { return blk->size();}
};
/// Specialization for distributed blocks with matching layout.
/// Use get_local_block().
template <typename Block,
typename LP>
class Accessor<Block, LP, Direct_access_tag, local>
{
typedef typename remove_const<Block>::type non_const_block_type;
typedef typename add_const<Block>::type const_block_type;
typedef typename conditional<is_const<Block>::value,
typename Distributed_local_block<non_const_block_type>::type const,
typename Distributed_local_block<non_const_block_type>::type>::type
local_block_type;
public:
static dimension_type const dim = LP::dim;
typedef typename Block::value_type value_type;
typedef typename LP::order_type order_type;
static pack_type const packing = LP::packing;
static storage_format_type const storage_format = LP::storage_format;
typedef Storage<storage_format, value_type> storage_type;
typedef typename storage_type::type non_const_ptr_type;
typedef typename storage_type::const_type const_ptr_type;
typedef typename
vsip::impl::conditional<vsip::impl::is_modifiable_block<Block>::value,
non_const_ptr_type,
const_ptr_type>::type ptr_type;
static int const CT_Cost = 0;
static bool const CT_Mem_not_req = true;
static bool const CT_Xfer_not_req = true;
static int cost(Block const&, LP const&) { return CT_Cost;}
static size_t mem_required (Block const&, LP const&) { return 0;}
static size_t xfer_required(Block const&, LP const&) { return !CT_Xfer_not_req;}
Accessor(Block &b, non_const_ptr_type = non_const_ptr_type())
: block_(get_local_block(const_cast<non_const_block_type &>(b))) {}
~Accessor() {}
void begin(Block*, bool) {}
void end(Block*, bool) {}
int cost() const { return CT_Cost;}
ptr_type ptr(Block *) const { return block_.ptr();}
stride_type stride(Block *, dimension_type d) const { return block_.stride(dim, d);}
length_type size(Block *, dimension_type d) const { return block_.size(dim, d);}
length_type size(Block *) const { return block_.size();}
private:
local_block_type &block_;
};
/// Specialization for copied direct data access.
///
/// Template parameters:
/// :Block: to be a block.
/// :LP: is a layout policy describing the desired layout.
/// The desired layout can be different from the block's layout.
///
/// Notes:
/// When the desired layout packing format is either packing::unit_stride or
/// packing::unknown, the packing format used will be packing::dense.
template <typename Block,
typename LP>
class Accessor<Block, LP, Copy_access_tag, direct>
{
// Compile time typedefs.
public:
static dimension_type const dim = LP::dim;
typedef typename Block::value_type value_type;
typedef typename LP::order_type order_type;
static pack_type const packing =
LP::packing == unit_stride || LP::packing == any_packing
? dense : LP::packing;
static storage_format_type const storage_format = LP::storage_format;
typedef Layout<dim, order_type, packing, storage_format> actual_layout_type;
typedef Allocated_storage<storage_format, value_type> storage_type;
typedef typename storage_type::type non_const_ptr_type;
typedef typename storage_type::const_type const_ptr_type;
typedef typename
vsip::impl::conditional<vsip::impl::is_modifiable_block<Block>::value,
non_const_ptr_type,
const_ptr_type>::type ptr_type;
static int const CT_Cost = 2;
static bool const CT_Mem_not_req = false;
static bool const CT_Xfer_not_req = false;
static int cost(Block const&, LP const&)
{ return CT_Cost; }
static size_t mem_required (Block const& block, LP const&)
{ return sizeof(typename Block::value_type) * block.size(); }
static size_t xfer_required(Block const&, LP const&)
{ return !CT_Xfer_not_req; }
// Constructor and destructor.
public:
Accessor(Block & blk, non_const_ptr_type buffer = non_const_ptr_type())
: layout_ (extent<dim>(blk)),
storage_ (layout_.total_size(), buffer)
{}
~Accessor()
{ storage_.deallocate(layout_.total_size());}
void begin(Block* blk, bool sync)
{
if (sync)
Block_copy_to_ptr<LP::dim, Block, order_type, packing, storage_format>::
copy(blk, layout_, storage_.ptr());
}
void end(Block* blk, bool sync)
{
if (sync)
Block_copy_from_ptr<LP::dim, Block, order_type, packing, storage_format>::
copy(blk, layout_, storage_.ptr());
}
int cost() const { return CT_Cost; }
ptr_type ptr(Block*) { return storage_.ptr();}
const_ptr_type ptr(Block*) const { return storage_.ptr();}
stride_type stride(Block*, dimension_type d) const { return layout_.stride(d);}
length_type size(Block* blk, dimension_type d) const { return blk->size(Block::dim, d);}
length_type size(Block* blk) const { return blk->size();}
private:
Applied_layout<actual_layout_type> layout_;
storage_type storage_;
};
template <typename B, typename L, typename A>
class Accessor<B, L, A, remap>
{
public:
typedef typename B::value_type value_type;
typedef typename view_of<B>::type dist_view_type;
typedef Allocated_storage<L::storage_format, value_type> storage_type;
typedef typename storage_type::type non_const_ptr_type;
typedef typename storage_type::const_type const_ptr_type;
typedef typename
vsip::impl::conditional<vsip::impl::is_modifiable_block<B>::value,
non_const_ptr_type,
const_ptr_type>::type ptr_type;
typedef Us_block<B::dim, value_type, L, Local_map> block_type;
typedef typename view_of<block_type>::type local_view_type;
typedef Accessor<block_type, L, A> data_access_type;
public:
static int const CT_Cost = 2;
static bool const CT_Mem_not_req = false;
static bool const CT_Xfer_not_req = false;
static int cost(B const&, L const&)
{ return CT_Cost;}
static size_t mem_required (B const & block, L const&)
{ return sizeof(typename B::value_type) * block.size();}
static size_t xfer_required(B const &, L const &)
{ return !CT_Xfer_not_req;}
Accessor(B &b, non_const_ptr_type buffer = non_const_ptr_type())
: storage_(b.size(), buffer),
block_(block_domain<B::dim>(b), storage_.ptr()),
ext_(block_)
{}
~Accessor()
{ storage_.deallocate(block_.size());}
void begin(B *b, bool sync)
{
if (sync) assign_local(block_, *b);
ext_.begin(&block_, sync);
}
void end(B *b, bool sync)
{
ext_.end(&block_, sync);
if (sync) assign_local_if<is_modifiable_block<B>::value>(*b, block_);
}
int cost() const { return CT_Cost;}
ptr_type ptr(B*) { return ext_.ptr(&block_);}
const_ptr_type ptr(B*) const { return ext_.ptr(&block_);}
stride_type stride(B*, dimension_type d) const { return ext_.stride(&block_, d);}
length_type size(B *b, dimension_type d) const { return ext_.size(&block_, d);}
length_type size(B *b) const { return ext_.size(&block_);}
private:
storage_type storage_;
mutable block_type block_;
data_access_type ext_;
};
template <typename AT> struct Cost { static int const value = 10; };
template <> struct Cost<Direct_access_tag> { static int const value = 0; };
template <> struct Cost<Copy_access_tag> { static int const value = 2; };
} // namespace vsip::dda::impl
} // namespace vsip::dda
} // namespace vsip
#endif
| maxywb/vsipl | sourceryvsipl++-x86-3.1/src/vsipl++/src/vsip/core/dda.hpp | C++ | gpl-2.0 | 12,830 |
//=============================================================================
//
// akaze_features.cpp
// Authors: Pablo F. Alcantarilla (1), Jesus Nuevo (2)
// Institutions: Georgia Institute of Technology (1)
// TrueVision Solutions (2)
// Date: 16/09/2013
// Email: pablofdezalc@gmail.com
//
// AKAZE Features Copyright 2013, Pablo F. Alcantarilla, Jesus Nuevo
// All Rights Reserved
// See LICENSE for the license information
//=============================================================================
/**
* @file akaze_features.cpp
* @brief Main program for detecting and computing binary descriptors in an
* accelerated nonlinear scale space
* @date Sep 16, 2013
* @author Pablo F. Alcantarilla, Jesus Nuevo
*/
#include "AKAZE.h"
using namespace std;
/* ************************************************************************* */
/**
* @brief This function parses the command line arguments for setting A-KAZE parameters
* @param options Structure that contains A-KAZE settings
* @param img_path Path for the input image
* @param kpts_path Path for the file where the keypoints where be stored
*/
int parse_input_options(AKAZEOptions& options, std::string& img_path,
std::string& kpts_path, int argc, char *argv[]);
/* ************************************************************************* */
int main(int argc, char *argv[]) {
// Variables
AKAZEOptions options;
string img_path, kpts_path;
// Variable for computation times.
double t1 = 0.0, t2 = 0.0, tdet = 0.0, tdesc = 0.0;
// Parse the input command line options
if (parse_input_options(options,img_path,kpts_path,argc,argv)) {
return -1;
}
if (options.verbosity) {
cout << "Check AKAZE options:" << endl;
cout << options << endl;
}
// Try to read the image and if necessary convert to grayscale.
cv::Mat img = cv::imread(img_path,0);
if (img.data == NULL) {
cerr << "Error: cannot load image from file:" << endl << img_path << endl;
return -1;
}
// Convert the image to float to extract features.
cv::Mat img_32;
img.convertTo(img_32, CV_32F, 1.0/255.0,0);
// Don't forget to specify image dimensions in AKAZE's options.
options.img_width = img.cols;
options.img_height = img.rows;
// Extract features.
vector<cv::KeyPoint> kpts;
t1 = cv::getTickCount();
AKAZE evolution(options);
evolution.Create_Nonlinear_Scale_Space(img_32);
evolution.Feature_Detection(kpts);
t2 = cv::getTickCount();
tdet = 1000.0*(t2-t1) / cv::getTickFrequency();
// Compute descriptors.
cv::Mat desc;
t1 = cv::getTickCount();
evolution.Compute_Descriptors(kpts,desc);
t2 = cv::getTickCount();
tdesc = 1000.0*(t2-t1) / cv::getTickFrequency();
// Summarize the computation times.
evolution.Show_Computation_Times();
evolution.Save_Scale_Space();
cout << "Number of points: " << kpts.size() << endl;
cout << "Time Detector: " << tdet << " ms" << endl;
cout << "Time Descriptor: " << tdesc << " ms" << endl;
// Save keypoints in ASCII format.
if (!kpts_path.empty())
save_keypoints(kpts_path,kpts,desc,true);
// Check out the result visually.
cv::Mat img_rgb = cv::Mat(cv::Size(img.cols, img.rows), CV_8UC3);
cvtColor(img,img_rgb,CV_GRAY2BGR);
draw_keypoints(img_rgb,kpts);
cv::imshow(img_path,img_rgb);
cv::waitKey(0);
}
/* ************************************************************************* */
int parse_input_options(AKAZEOptions& options, std::string& img_path,
std::string& kpts_path, int argc, char *argv[]) {
// If there is only one argument return
if (argc == 1) {
show_input_options_help(0);
return -1;
}
// Set the options from the command line
else if (argc >= 2) {
options = AKAZEOptions();
kpts_path = "./keypoints.txt";
if (!strcmp(argv[1],"--help")) {
show_input_options_help(0);
return -1;
}
img_path = argv[1];
for (int i = 2; i < argc; i++) {
if (!strcmp(argv[i],"--soffset")) {
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else {
options.soffset = atof(argv[i]);
}
}
else if (!strcmp(argv[i],"--omax")) {
i = i+1;
if ( i >= argc ) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else {
options.omax = atof(argv[i]);
}
}
else if (!strcmp(argv[i],"--dthreshold")) {
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else {
options.dthreshold = atof(argv[i]);
}
}
else if (!strcmp(argv[i],"--sderivatives")) {
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else {
options.sderivatives = atof(argv[i]);
}
}
else if (!strcmp(argv[i],"--nsublevels")) {
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else
options.nsublevels = atoi(argv[i]);
}
else if (!strcmp(argv[i],"--diffusivity")) {
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else
options.diffusivity = DIFFUSIVITY_TYPE(atoi(argv[i]));
}
else if (!strcmp(argv[i],"--descriptor")) {
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else {
options.descriptor = DESCRIPTOR_TYPE(atoi(argv[i]));
if (options.descriptor < 0 || options.descriptor > MLDB) {
options.descriptor = MLDB;
}
}
}
else if (!strcmp(argv[i],"--descriptor_channels")) {
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else {
options.descriptor_channels = atoi(argv[i]);
if (options.descriptor_channels <= 0 || options.descriptor_channels > 3) {
options.descriptor_channels = 3;
}
}
}
else if (!strcmp(argv[i],"--descriptor_size")) {
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else {
options.descriptor_size = atoi(argv[i]);
if (options.descriptor_size < 0) {
options.descriptor_size = 0;
}
}
}
else if (!strcmp(argv[i],"--save_scale_space")) {
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else {
options.save_scale_space = (bool)atoi(argv[i]);
}
}
else if (!strcmp(argv[i],"--verbose")) {
options.verbosity = true;
}
else if (!strcmp(argv[i],"--output")) {
options.save_keypoints = true;
i = i+1;
if (i >= argc) {
cerr << "Error introducing input options!!" << endl;
return -1;
}
else
kpts_path = argv[i];
}
}
}
return 0;
}
| ducha-aiki/mods | akaze/src/akaze_features.cpp | C++ | gpl-2.0 | 7,420 |
var Traverse = require('.');
var assert = require('assert');
exports['negative update test'] = function () {
var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
var fixed = Traverse.map(obj, function (x) {
if (x < 0) this.update(x + 128);
});
assert.deepEqual(fixed,
[ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ],
'Negative values += 128'
);
assert.deepEqual(obj,
[ 5, 6, -3, [ 7, 8, -2, 1 ], { f: 10, g: -13 } ],
'Original references not modified'
);
}
| daslicht/TimberExperiments | mat/timber-starter-theme_/node_modules/grunt-contrib-nodeunit/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/negative.js | JavaScript | gpl-2.0 | 549 |
<<<<<<< HEAD
<?php
session_start();
/**
* Manejar la informacion correspondiente a las Sedes y ubicaciones Fisicas de los diferentes cuartos tecnicos
*
*/
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../includes/jquery/themes/bootstrap/easyui.css">
<link rel="stylesheet" type="text/css" href="../includes/jquery/themes/icon.css">
<link rel="stylesheet" type="text/css" href="../includes/jquery/demo/demo.css">
<script type="text/javascript" src="../includes/jquery/jquery.easyui.min.js"></script>
<script>
=======
<?php
session_start ();
/**
* Manejar la informacion correspondiente a las Sedes y ubicaciones Fisicas de los diferentes cuartos tecnicos
*/
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css"
href="../includes/jquery/themes/bootstrap/easyui.css">
<link rel="stylesheet" type="text/css"
href="../includes/jquery/themes/icon.css">
<link rel="stylesheet" type="text/css"
href="../includes/jquery/demo/demo.css">
<script type="text/javascript"
src="../includes/jquery/jquery.easyui.min.js"></script>
<script>
>>>>>>> 20c1718748b0b8a6644a5e204b65226df9a3b684
function cargarDistribucion(data){
$('#idflia').val(data);
$("#dg_dataServer").html('');
$("#ft").show();
$("#dg_dataServer").datagrid({
conCls: 'icon-edit',
singleSelect: true,
method:'get',
toolbar:'#ft',
fitColumns:'true',
pagination:'true',
//$idubicacion, $servf, $tiposerv
url:'./Manager/Servidor/actionServidor.php?accion=buscaServers&tiposerv=1&idubicacion='+data,
columns:[[
{field:'id',width:10, hidden:'true', title:'IDServer'},
{field:'placa',width:20, title:'N. Placa'},
{field:'descripcion',width:120, title:'Nombre'},
{field:'dirip',width:80, title:'IP'},
{field:'responsable',width:70, title:'Reponsable'},
{field:'responsable2',width:70, title:'Reponsable 2'},
{field:'uso',width:70, title:'Uso'}
]] ,
onClickRow:function(rowIndex, rowData){
editarUbicacion(rowData);
}
});
}
function editarUbicacion(data){
idserver = data.id;
descripcion = data.descripcion;
dirip = data.dirip;
responsable = data.responsable;
responsable2 = data.responsable2;
idubicacion = $("#idflia").val();
uso = data.uso;
placa = data.placa;
$("#windis").load('../UI/Manager/Servidor/editarServidor.php',
{accion:'EditarServer',idserver:idserver,descripcion:descripcion,dirip:dirip,responsable:responsable,responsable2:responsable2,tipo:1,idubicacion:idubicacion,uso:uso,placa:placa} );
}
function adicionarUbicacion(){
idubicacion =$("#idflia").val();
$("#windis").load('../UI/Manager/Servidor/editarServidor.php',{accion:'AddServerF',idubicacion:idubicacion,tipo:1});
}
$(document).ready(function(){
$("#dataso").hide();
$("#ft").hide();
})
<<<<<<< HEAD
</script>
</head>
<body>
<div class="easyui-panel" title="Registro de Servidores Fisicos" style="width:980px">
<!--div style="padding:10px 60px 20px 60px"></div-->
<div style="margin-bottom:20px"></div>
<table align = "center">
<tr>
<td> <label>Ubicaciones</label></td>
<td>
<input class="easyui-combobox" name="opt_flia"
=======
</script>
</head>
<body>
<div class="easyui-panel" title="Registro datos"
style="width: 980px">
<!--div style="padding:10px 60px 20px 60px"></div-->
<div style="margin-bottom: 20px"></div>
<table align="center">
<tr>
<td><label>Ubicaciones</label></td>
<td><input class="easyui-combobox" name="opt_flia"
>>>>>>> 20c1718748b0b8a6644a5e204b65226df9a3b684
data-options="url:' ./Manager/Servidor/actionServidor.php?accion=Ubicacion',
valueField:'id',
textField:'desclasf',
panelHeight: 'auto',
onSelect: function (rec){
$('#seleco').textbox('setValue',rec.desclasf);
cargarDistribucion(rec.id);
<<<<<<< HEAD
}"
style="width: 420px" />
<input class="easyui-textbox" id="seleco" data-options="editable:false, width:'420px'" />
</td>
</tr>
</table>
<div id="dg_dataServer"></div>
</div>
<div id="ft" style="padding:2px 5px;">
<a href="#" class="easyui-linkbutton" onclick="adicionarUbicacion();" iconCls="icon-add" plain="true"></a>
</div>
<div id= "dataso">
idfliaso<input id="idflia" />
</div>
<div id="windis" name="windis"></div>
</body>
</html>
=======
}"
style="width: 420px" /> <input class="easyui-textbox" id="seleco"
data-options="editable:false, width:'420px'" /></td>
</tr>
</table>
<div id="dg_dataServer"></div>
</div>
<div id="ft" style="padding: 2px 5px;">
<a href="#" class="easyui-linkbutton" onclick="adicionarUbicacion();"
iconCls="icon-add" plain="true"></a>
</div>
<div id="dataso">
idfliaso<input id="idflia" />
</div>
<div id="windis" name="windis"></div>
</body>
</html>
>>>>>>> 20c1718748b0b8a6644a5e204b65226df9a3b684
| isolarte/platafromas | UI/Manager/Servidor/FormServidor.php | PHP | gpl-2.0 | 5,077 |
/**
This package is part of the application VIF.
Copyright (C) 2008-2015, Benno Luthiger
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.hip.vif.member.ldap;
import java.sql.SQLException;
import java.util.Map;
import org.hip.kernel.bom.GettingException;
import org.hip.kernel.exc.VException;
import org.hip.vif.core.bom.Member;
import org.hip.vif.core.bom.MemberHome;
import org.hip.vif.core.member.AbstractMemberInformation;
import org.hip.vif.core.member.IMemberInformation;
/** @author Luthiger Created: 07.01.2008 */
public class LDAPMemberInformation extends AbstractMemberInformation implements IMemberInformation {
private final static Object[][] MEMBER_PROPERTIES = { { MemberHome.KEY_USER_ID, "" },
{ MemberHome.KEY_NAME, "" },
{ MemberHome.KEY_FIRSTNAME, "" },
{ MemberHome.KEY_MAIL, "" },
{ MemberHome.KEY_SEX, Integer.valueOf(-1) },
{ MemberHome.KEY_CITY, "" },
{ MemberHome.KEY_STREET, "" },
{ MemberHome.KEY_ZIP, "" },
{ MemberHome.KEY_PHONE, "" },
{ MemberHome.KEY_FAX, "" } };
private transient String userID = ""; // NOPMD by lbenno
/** LDAPMemberInformation constructor.
*
* @param inSource {@link Member} the member instance backing this information
* @throws VException */
public LDAPMemberInformation(final Member inSource) throws VException {
super();
userID = loadValues(inSource);
}
@Override
public void update(final Member inMember) throws SQLException, VException { // NOPMD by lbenno
setAllTo(inMember);
inMember.update(true);
}
@Override
public Long insert(final Member inMember) throws SQLException, VException { // NOPMD by lbenno
setAllTo(inMember);
return inMember.insert(true);
}
private String loadValues(final Member inSource) throws VException {
for (int i = 0; i < MEMBER_PROPERTIES.length; i++) {
final String lKey = MEMBER_PROPERTIES[i][0].toString();
Object lValue = null;
try {
lValue = inSource.get(lKey);
} catch (final GettingException exc) {
lValue = MEMBER_PROPERTIES[i][1];
}
put(lKey, lValue);
}
return inSource.get(MemberHome.KEY_USER_ID).toString();
}
private void setAllTo(final Member inMember) throws VException {
for (final Map.Entry<String, Object> lEntry : entries()) {
inMember.set(lEntry.getKey(), lEntry.getValue());
}
}
@Override
public String getUserID() { // NOPMD by lbenno
return userID;
}
}
| aktion-hip/vif | org.hip.vif.member.ldap/src/org/hip/vif/member/ldap/LDAPMemberInformation.java | Java | gpl-2.0 | 3,356 |
#include <iostream>
using namespace std;
struct Node
{
int inf;
Node *next;
}*start,*newptr,*save,*ptr,*rear;
Node* Create_New_Node(int n)
{
newptr=new Node;
newptr->inf=n;
newptr->next=NULL;
return newptr;
}
void Insert_End(Node *np)
{
if(start==NULL)
start=rear=np;
else
{
rear->next=np;
rear=np;
}
}
void display(Node *np)
{
while(np!=NULL)
{
cout<<np->inf<<"->";
np=np->next;
}
cout<<"!!!";
}
void pop()
{
if(start==NULL)
{
cout<<"Underflow!!";
return;
}
ptr=start;
start=start->next;
delete ptr;
}
int main()
{
start=NULL;
int n;
char ch='y';
while(ch=='y'||ch=='Y')
{
cout<<"Enter information for new node: ";
cin>>n;
ptr=Create_New_Node(n);
Insert_End(ptr);
display(start);
cout<<"\nWant to enter more (y/n) : ";
cin>>ch;
}
ch='y';
while(ch=='y'||ch=='Y')
{
cout<<"The list now is: ";
display(start);
cout<<"Want to delete element (y/n): ";
cin>>ch;
if(ch=='y'||ch=='Y')
pop();
}
return 0;
}
| Kingpin007/School-Cpp-Programs | Arrays/Deletion in a Linked List/main.cpp | C++ | gpl-2.0 | 1,188 |
/*
* Copyright 2013-2014 Odysseus Software GmbH
*
* 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.giffftalk.messenger.audioinfo.m4a;
import org.giffftalk.messenger.audioinfo.util.PositionInputStream;
import org.giffftalk.messenger.audioinfo.util.RangeInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
public class MP4Box<I extends PositionInputStream> {
protected static final String ASCII = "ISO8859_1";
private final I input;
private final MP4Box<?> parent;
private final String type;
protected final DataInput data;
private MP4Atom child;
public MP4Box(I input, MP4Box<?> parent, String type) {
this.input = input;
this.parent = parent;
this.type = type;
this.data = new DataInputStream(input);
}
public String getType() {
return type;
}
public MP4Box<?> getParent() {
return parent;
}
public long getPosition() {
return input.getPosition();
}
public I getInput() {
return input;
}
protected MP4Atom getChild() {
return child;
}
public MP4Atom nextChild() throws IOException {
if (child != null) {
child.skip();
}
int atomLength = data.readInt();
byte[] typeBytes = new byte[4];
data.readFully(typeBytes);
String atomType = new String(typeBytes, ASCII);
RangeInputStream atomInput;
if (atomLength == 1) { // extended length
atomInput = new RangeInputStream(input, 16, data.readLong() - 16);
} else {
atomInput = new RangeInputStream(input, 8, atomLength - 8);
}
return child = new MP4Atom(atomInput, this, atomType);
}
public MP4Atom nextChild(String expectedTypeExpression) throws IOException {
MP4Atom atom = nextChild();
if (atom.getType().matches(expectedTypeExpression)) {
return atom;
}
throw new IOException("atom type mismatch, expected " + expectedTypeExpression + ", got " + atom.getType());
}
}
| digantDj/Gifff-Talk | TMessagesProj/src/main/java/org/giffftalk/messenger/audioinfo/m4a/MP4Box.java | Java | gpl-2.0 | 2,379 |
<?php
/**
* This software is intended for use with Oxwall Free Community Software http://www.oxwall.org/ and is
* licensed under The BSD license.
* ---
* Copyright (c) 2011, Oxwall Foundation
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and
* the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Oxwall Foundation nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Data Access Object for `groups_group_user` table.
*
* @author Sergey Kambalin <greyexpert@gmail.com>
* @package ow_plugins.groups.bol
* @since 1.0
*/
class GROUPS_BOL_GroupUserDao extends OW_BaseDao
{
/**
* Singleton instance.
*
* @var GROUPS_BOL_GroupUserDao
*/
private static $classInstance;
/**
* Returns an instance of class (singleton pattern implementation).
*
* @return GROUPS_BOL_GroupUserDao
*/
public static function getInstance()
{
if ( self::$classInstance === null )
{
self::$classInstance = new self();
}
return self::$classInstance;
}
/**
* @see OW_BaseDao::getDtoClassName()
*
*/
public function getDtoClassName()
{
return 'GROUPS_BOL_GroupUser';
}
/**
* @see OW_BaseDao::getTableName()
*
*/
public function getTableName()
{
return OW_DB_PREFIX . 'groups_group_user';
}
public function findListByGroupId( $groupId, $first, $count )
{
$queryParts = BOL_UserDao::getInstance()->getUserQueryFilter("u", "userId", array(
"method" => "GROUPS_BOL_GroupUserDao::findListByGroupId"
));
$query = "SELECT u.* FROM " . $this->getTableName() . " u " . $queryParts["join"]
. " WHERE " . $queryParts["where"] . " AND u.groupId=:g AND u.privacy=:p LIMIT :lf, :lc";
return $this->dbo->queryForObjectList($query, $this->getDtoClassName(), array(
"g" => $groupId,
"p" => GROUPS_BOL_Service::PRIVACY_EVERYBODY,
"lf" => $first,
"lc" => $count
));
}
public function findByGroupId( $groupId, $privacy = null )
{
$example = new OW_Example();
$example->andFieldEqual('groupId', $groupId);
if ( $privacy !== null )
{
$example->andFieldEqual('privacy', $privacy);
}
return $this->findListByExample($example);
}
public function findCountByGroupId( $groupId )
{
$queryParts = BOL_UserDao::getInstance()->getUserQueryFilter("u", "userId", array(
"method" => "GROUPS_BOL_GroupUserDao::findCountByGroupId"
));
$query = "SELECT COUNT(DISTINCT u.id) FROM " . $this->getTableName() . " u " . $queryParts["join"]
. " WHERE " . $queryParts["where"] . " AND u.groupId=:g";
return $this->dbo->queryForColumn($query, array(
"g" => $groupId
));
}
public function findCountByGroupIdList( $groupIdList )
{
if ( empty($groupIdList) )
{
return array();
}
$queryParts = BOL_UserDao::getInstance()->getUserQueryFilter("u", "userId", array(
"method" => "GROUPS_BOL_GroupUserDao::findCountByGroupIdList"
));
$query = 'SELECT u.groupId, COUNT(*) count FROM ' . $this->getTableName() . ' u '
. $queryParts["join"]
. ' WHERE ' . $queryParts["where"] . ' AND u.groupId IN (' . implode(',', $groupIdList) . ') GROUP BY u.groupId';
$list = $this->dbo->queryForList($query, null
, GROUPS_BOL_GroupDao::LIST_CACHE_LIFETIME, array(GROUPS_BOL_GroupDao::LIST_CACHE_TAG));
$resultList = array();
foreach ( $list as $item )
{
$resultList[$item['groupId']] = $item['count'];
}
foreach ( $groupIdList as $groupId )
{
$resultList[$groupId] = empty($resultList[$groupId]) ? 0 : $resultList[$groupId];
}
return $resultList;
}
/**
*
* @param int $groupId
* @param int $userId
* @return GROUPS_BOL_GroupUser
*/
public function findGroupUser( $groupId, $userId )
{
$example = new OW_Example();
$example->andFieldEqual('groupId', $groupId);
$example->andFieldEqual('userId', $userId);
return $this->findObjectByExample($example);
}
public function deleteByGroupId( $groupId )
{
$example = new OW_Example();
$example->andFieldEqual('groupId', $groupId);
return $this->deleteByExample($example);
}
public function deleteByUserId( $userId )
{
$example = new OW_Example();
$example->andFieldEqual('userId', $userId);
return $this->deleteByExample($example);
}
public function deleteByGroupAndUserId( $groupId, $userId )
{
$example = new OW_Example();
$example->andFieldEqual('groupId', $groupId);
$example->andFieldEqual('userId', $userId);
return $this->deleteByExample($example);
}
public function setPrivacy( $userId, $privacy )
{
$query = 'UPDATE ' . $this->getTableName() . ' SET privacy=:p WHERE userId=:u';
$this->dbo->query($query, array(
'p' => $privacy,
'u' => $userId
));
}
} | locthdev/shopthoitrang-oxwall | ow_plugins/groups/bol/group_user_dao.php | PHP | gpl-2.0 | 6,663 |
/**
* rigid_constraintType.java
*
* This file was generated by XMLSpy 2007sp2 Enterprise Edition.
*
* YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE
* OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION.
*
* Refer to the XMLSpy Documentation for further details.
* http://www.altova.com/xmlspy
*/
package com.jmex.model.collada.schema;
import com.jmex.xml.types.SchemaNCName;
public class rigid_constraintType extends com.jmex.xml.xml.Node {
public rigid_constraintType(rigid_constraintType node) {
super(node);
}
public rigid_constraintType(org.w3c.dom.Node node) {
super(node);
}
public rigid_constraintType(org.w3c.dom.Document doc) {
super(doc);
}
public rigid_constraintType(com.jmex.xml.xml.Document doc, String namespaceURI, String prefix, String name) {
super(doc, namespaceURI, prefix, name);
}
public void adjustPrefix() {
for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "sid" );
tmpNode != null;
tmpNode = getDomNextChild( Attribute, null, "sid", tmpNode )
) {
internalAdjustPrefix(tmpNode, false);
}
for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "name" );
tmpNode != null;
tmpNode = getDomNextChild( Attribute, null, "name", tmpNode )
) {
internalAdjustPrefix(tmpNode, false);
}
for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment" );
tmpNode != null;
tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", tmpNode )
) {
internalAdjustPrefix(tmpNode, true);
new ref_attachmentType(tmpNode).adjustPrefix();
}
for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment" );
tmpNode != null;
tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment", tmpNode )
) {
internalAdjustPrefix(tmpNode, true);
new attachmentType(tmpNode).adjustPrefix();
}
for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common" );
tmpNode != null;
tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common", tmpNode )
) {
internalAdjustPrefix(tmpNode, true);
new technique_commonType8(tmpNode).adjustPrefix();
}
for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique" );
tmpNode != null;
tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique", tmpNode )
) {
internalAdjustPrefix(tmpNode, true);
new techniqueType5(tmpNode).adjustPrefix();
}
for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "extra" );
tmpNode != null;
tmpNode = getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "extra", tmpNode )
) {
internalAdjustPrefix(tmpNode, true);
new extraType(tmpNode).adjustPrefix();
}
}
public void setXsiType() {
org.w3c.dom.Element el = (org.w3c.dom.Element) domNode;
el.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:type", "rigid_constraint");
}
public static int getsidMinCount() {
return 1;
}
public static int getsidMaxCount() {
return 1;
}
public int getsidCount() {
return getDomChildCount(Attribute, null, "sid");
}
public boolean hassid() {
return hasDomChild(Attribute, null, "sid");
}
public SchemaNCName newsid() {
return new SchemaNCName();
}
public SchemaNCName getsidAt(int index) throws Exception {
return new SchemaNCName(getDomNodeValue(getDomChildAt(Attribute, null, "sid", index)));
}
public org.w3c.dom.Node getStartingsidCursor() throws Exception {
return getDomFirstChild(Attribute, null, "sid" );
}
public org.w3c.dom.Node getAdvancedsidCursor( org.w3c.dom.Node curNode ) throws Exception {
return getDomNextChild( Attribute, null, "sid", curNode );
}
public SchemaNCName getsidValueAtCursor( org.w3c.dom.Node curNode ) throws Exception {
if( curNode == null )
throw new com.jmex.xml.xml.XmlException("Out of range");
else
return new SchemaNCName(getDomNodeValue(curNode));
}
public SchemaNCName getsid() throws Exception
{
return getsidAt(0);
}
public void removesidAt(int index) {
removeDomChildAt(Attribute, null, "sid", index);
}
public void removesid() {
removesidAt(0);
}
public org.w3c.dom.Node addsid(SchemaNCName value) {
if( value.isNull() )
return null;
return appendDomChild(Attribute, null, "sid", value.toString());
}
public org.w3c.dom.Node addsid(String value) throws Exception {
return addsid(new SchemaNCName(value));
}
public void insertsidAt(SchemaNCName value, int index) {
insertDomChildAt(Attribute, null, "sid", index, value.toString());
}
public void insertsidAt(String value, int index) throws Exception {
insertsidAt(new SchemaNCName(value), index);
}
public void replacesidAt(SchemaNCName value, int index) {
replaceDomChildAt(Attribute, null, "sid", index, value.toString());
}
public void replacesidAt(String value, int index) throws Exception {
replacesidAt(new SchemaNCName(value), index);
}
public static int getnameMinCount() {
return 0;
}
public static int getnameMaxCount() {
return 1;
}
public int getnameCount() {
return getDomChildCount(Attribute, null, "name");
}
public boolean hasname() {
return hasDomChild(Attribute, null, "name");
}
public SchemaNCName newname() {
return new SchemaNCName();
}
public SchemaNCName getnameAt(int index) throws Exception {
return new SchemaNCName(getDomNodeValue(getDomChildAt(Attribute, null, "name", index)));
}
public org.w3c.dom.Node getStartingnameCursor() throws Exception {
return getDomFirstChild(Attribute, null, "name" );
}
public org.w3c.dom.Node getAdvancednameCursor( org.w3c.dom.Node curNode ) throws Exception {
return getDomNextChild( Attribute, null, "name", curNode );
}
public SchemaNCName getnameValueAtCursor( org.w3c.dom.Node curNode ) throws Exception {
if( curNode == null )
throw new com.jmex.xml.xml.XmlException("Out of range");
else
return new SchemaNCName(getDomNodeValue(curNode));
}
public SchemaNCName getname() throws Exception
{
return getnameAt(0);
}
public void removenameAt(int index) {
removeDomChildAt(Attribute, null, "name", index);
}
public void removename() {
removenameAt(0);
}
public org.w3c.dom.Node addname(SchemaNCName value) {
if( value.isNull() )
return null;
return appendDomChild(Attribute, null, "name", value.toString());
}
public org.w3c.dom.Node addname(String value) throws Exception {
return addname(new SchemaNCName(value));
}
public void insertnameAt(SchemaNCName value, int index) {
insertDomChildAt(Attribute, null, "name", index, value.toString());
}
public void insertnameAt(String value, int index) throws Exception {
insertnameAt(new SchemaNCName(value), index);
}
public void replacenameAt(SchemaNCName value, int index) {
replaceDomChildAt(Attribute, null, "name", index, value.toString());
}
public void replacenameAt(String value, int index) throws Exception {
replacenameAt(new SchemaNCName(value), index);
}
public static int getref_attachmentMinCount() {
return 1;
}
public static int getref_attachmentMaxCount() {
return 1;
}
public int getref_attachmentCount() {
return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment");
}
public boolean hasref_attachment() {
return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment");
}
public ref_attachmentType newref_attachment() {
return new ref_attachmentType(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "ref_attachment"));
}
public ref_attachmentType getref_attachmentAt(int index) throws Exception {
return new ref_attachmentType(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", index));
}
public org.w3c.dom.Node getStartingref_attachmentCursor() throws Exception {
return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment" );
}
public org.w3c.dom.Node getAdvancedref_attachmentCursor( org.w3c.dom.Node curNode ) throws Exception {
return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", curNode );
}
public ref_attachmentType getref_attachmentValueAtCursor( org.w3c.dom.Node curNode ) throws Exception {
if( curNode == null )
throw new com.jmex.xml.xml.XmlException("Out of range");
else
return new ref_attachmentType(curNode);
}
public ref_attachmentType getref_attachment() throws Exception
{
return getref_attachmentAt(0);
}
public void removeref_attachmentAt(int index) {
removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", index);
}
public void removeref_attachment() {
removeref_attachmentAt(0);
}
public org.w3c.dom.Node addref_attachment(ref_attachmentType value) {
return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", value);
}
public void insertref_attachmentAt(ref_attachmentType value, int index) {
insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", index, value);
}
public void replaceref_attachmentAt(ref_attachmentType value, int index) {
replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "ref_attachment", index, value);
}
public static int getattachmentMinCount() {
return 1;
}
public static int getattachmentMaxCount() {
return 1;
}
public int getattachmentCount() {
return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment");
}
public boolean hasattachment() {
return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment");
}
public attachmentType newattachment() {
return new attachmentType(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "attachment"));
}
public attachmentType getattachmentAt(int index) throws Exception {
return new attachmentType(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment", index));
}
public org.w3c.dom.Node getStartingattachmentCursor() throws Exception {
return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment" );
}
public org.w3c.dom.Node getAdvancedattachmentCursor( org.w3c.dom.Node curNode ) throws Exception {
return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment", curNode );
}
public attachmentType getattachmentValueAtCursor( org.w3c.dom.Node curNode ) throws Exception {
if( curNode == null )
throw new com.jmex.xml.xml.XmlException("Out of range");
else
return new attachmentType(curNode);
}
public attachmentType getattachment() throws Exception
{
return getattachmentAt(0);
}
public void removeattachmentAt(int index) {
removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "attachment", index);
}
public void removeattachment() {
removeattachmentAt(0);
}
public org.w3c.dom.Node addattachment(attachmentType value) {
return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "attachment", value);
}
public void insertattachmentAt(attachmentType value, int index) {
insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "attachment", index, value);
}
public void replaceattachmentAt(attachmentType value, int index) {
replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "attachment", index, value);
}
public static int gettechnique_commonMinCount() {
return 1;
}
public static int gettechnique_commonMaxCount() {
return 1;
}
public int gettechnique_commonCount() {
return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common");
}
public boolean hastechnique_common() {
return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common");
}
public technique_commonType8 newtechnique_common() {
return new technique_commonType8(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "technique_common"));
}
public technique_commonType8 gettechnique_commonAt(int index) throws Exception {
return new technique_commonType8(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common", index));
}
public org.w3c.dom.Node getStartingtechnique_commonCursor() throws Exception {
return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common" );
}
public org.w3c.dom.Node getAdvancedtechnique_commonCursor( org.w3c.dom.Node curNode ) throws Exception {
return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common", curNode );
}
public technique_commonType8 gettechnique_commonValueAtCursor( org.w3c.dom.Node curNode ) throws Exception {
if( curNode == null )
throw new com.jmex.xml.xml.XmlException("Out of range");
else
return new technique_commonType8(curNode);
}
public technique_commonType8 gettechnique_common() throws Exception
{
return gettechnique_commonAt(0);
}
public void removetechnique_commonAt(int index) {
removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique_common", index);
}
public void removetechnique_common() {
removetechnique_commonAt(0);
}
public org.w3c.dom.Node addtechnique_common(technique_commonType8 value) {
return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "technique_common", value);
}
public void inserttechnique_commonAt(technique_commonType8 value, int index) {
insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "technique_common", index, value);
}
public void replacetechnique_commonAt(technique_commonType8 value, int index) {
replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "technique_common", index, value);
}
public static int gettechniqueMinCount() {
return 0;
}
public static int gettechniqueMaxCount() {
return Integer.MAX_VALUE;
}
public int gettechniqueCount() {
return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique");
}
public boolean hastechnique() {
return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique");
}
public techniqueType5 newtechnique() {
return new techniqueType5(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "technique"));
}
public techniqueType5 gettechniqueAt(int index) throws Exception {
return new techniqueType5(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique", index));
}
public org.w3c.dom.Node getStartingtechniqueCursor() throws Exception {
return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique" );
}
public org.w3c.dom.Node getAdvancedtechniqueCursor( org.w3c.dom.Node curNode ) throws Exception {
return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "technique", curNode );
}
public techniqueType5 gettechniqueValueAtCursor( org.w3c.dom.Node curNode ) throws Exception {
if( curNode == null )
throw new com.jmex.xml.xml.XmlException("Out of range");
else
return new techniqueType5(curNode);
}
public techniqueType5 gettechnique() throws Exception
{
return gettechniqueAt(0);
}
public void removetechniqueAt(int index) {
removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "technique", index);
}
public void removetechnique() {
while (hastechnique())
removetechniqueAt(0);
}
public org.w3c.dom.Node addtechnique(techniqueType5 value) {
return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "technique", value);
}
public void inserttechniqueAt(techniqueType5 value, int index) {
insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "technique", index, value);
}
public void replacetechniqueAt(techniqueType5 value, int index) {
replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "technique", index, value);
}
public static int getextraMinCount() {
return 0;
}
public static int getextraMaxCount() {
return Integer.MAX_VALUE;
}
public int getextraCount() {
return getDomChildCount(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra");
}
public boolean hasextra() {
return hasDomChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra");
}
public extraType newextra() {
return new extraType(domNode.getOwnerDocument().createElementNS("http://www.collada.org/2005/11/COLLADASchema", "extra"));
}
public extraType getextraAt(int index) throws Exception {
return new extraType(getDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra", index));
}
public org.w3c.dom.Node getStartingextraCursor() throws Exception {
return getDomFirstChild(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra" );
}
public org.w3c.dom.Node getAdvancedextraCursor( org.w3c.dom.Node curNode ) throws Exception {
return getDomNextChild( Element, "http://www.collada.org/2005/11/COLLADASchema", "extra", curNode );
}
public extraType getextraValueAtCursor( org.w3c.dom.Node curNode ) throws Exception {
if( curNode == null )
throw new com.jmex.xml.xml.XmlException("Out of range");
else
return new extraType(curNode);
}
public extraType getextra() throws Exception
{
return getextraAt(0);
}
public void removeextraAt(int index) {
removeDomChildAt(Element, "http://www.collada.org/2005/11/COLLADASchema", "extra", index);
}
public void removeextra() {
while (hasextra())
removeextraAt(0);
}
public org.w3c.dom.Node addextra(extraType value) {
return appendDomElement("http://www.collada.org/2005/11/COLLADASchema", "extra", value);
}
public void insertextraAt(extraType value, int index) {
insertDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "extra", index, value);
}
public void replaceextraAt(extraType value, int index) {
replaceDomElementAt("http://www.collada.org/2005/11/COLLADASchema", "extra", index, value);
}
}
| tectronics/xenogeddon | src/com/jmex/model/collada/schema/rigid_constraintType.java | Java | gpl-2.0 | 19,115 |
package com.lami.tuomatuo.core.dao.impl;
import com.lami.tuomatuo.core.base.MySqlBaseDao;
import com.lami.tuomatuo.core.dao.QQAccountDaoInterface;
import com.lami.tuomatuo.core.model.QQAccount;
import org.springframework.stereotype.Repository;
/**
* Created by xjk on 2016/1/18.
*/
@Repository("qqAccountDaoInterface")
public class QQAccountDaoImpl extends MySqlBaseDao<QQAccount, Long> implements QQAccountDaoInterface {
public QQAccountDaoImpl(){
super(QQAccount.class);
}
} | jackkiexu/tuomatuo | tuomatuo-core/src/main/java/com/lami/tuomatuo/core/dao/impl/QQAccountDaoImpl.java | Java | gpl-2.0 | 496 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OddAndEvenProduct")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OddAndEvenProduct")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("74f941fd-8ffb-4084-8256-ab3f2934c8b9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| iDonev/CSharp-Fundamentals | 09-Loops/OddAndEvenProduct/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,410 |
package kurtis.rx.androidexamples;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ExampleListActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example_list);
setupActionBar();
setupExampleList();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.example_list_title);
}
}
private void setupExampleList() {
RecyclerView exampleList = (RecyclerView) findViewById(R.id.example_list);
exampleList.setHasFixedSize(true);
exampleList.setLayoutManager(new LinearLayoutManager(this));
exampleList.setAdapter(new ExampleAdapter(this, getExamples()));
}
private static List<ExampleActivityAndName> getExamples() {
List<ExampleActivityAndName> exampleActivityAndNames = new ArrayList<>();
exampleActivityAndNames.add(new ExampleActivityAndName(
Example1Activity.class,
"Example 1: Simple Color List"));
exampleActivityAndNames.add(new ExampleActivityAndName(
Example2Activity.class,
"Example 2: Favorite Tv Shows"));
exampleActivityAndNames.add(new ExampleActivityAndName(
Example3Activity.class,
"Example 3: Improved Favorite Tv Shows"));
exampleActivityAndNames.add(new ExampleActivityAndName(
Example4Activity.class,
"Example 4: Button Counter"));
exampleActivityAndNames.add(new ExampleActivityAndName(
Example5Activity.class,
"Example 5: Value Display"));
exampleActivityAndNames.add(new ExampleActivityAndName(
Example6Activity.class,
"Example 6: City Search"));
return exampleActivityAndNames;
}
}
| klnusbaum/rxandroidexamples | app/src/main/java/kurtis/rx/androidexamples/ExampleListActivity.java | Java | gpl-2.0 | 2,227 |
<?php
/**
* Custom template tags for this theme.
*
* Eventually, some of the functionality here could be replaced by core features
*
* @package SKT IT Consultant
*/
if ( ! function_exists( 'skt_itconsultant_content_nav' ) ) :
/**
* Display navigation to next/previous pages when applicable
*/
function skt_itconsultant_content_nav( $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() ) ? 'post-navigation' : 'paging-navigation';
?>
<div role="navigation" id="<?php echo esc_attr( $nav_id ); ?>" class="<?php echo $nav_class; ?>">
<h1 class="screen-reader-text"><?php _e( 'Post navigation', 'itconsultant' ); ?></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', 'itconsultant' ) . '</span> %title' ); ?>
<?php next_post_link( '<div class="nav-next">%link</div>', '%title <span class="meta-nav">' . _x( '→', 'Next post link', 'itconsultant' ) . '</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', 'itconsultant' ) ); ?></div>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>', 'itconsultant' ) ); ?></div>
<?php endif; ?>
<?php endif; ?>
<div class="clear"></div>
</div><!-- #<?php echo esc_html( $nav_id ); ?> -->
<?php
}
endif; // skt_itconsultant_content_nav
if ( ! function_exists( 'skt_itconsultant_comment' ) ) :
/**
* Template for comments and pingbacks.
*
* Used as a callback by wp_list_comments() for displaying the comments.
*/
function skt_itconsultant_comment( $comment, $args, $depth ) {
$GLOBALS['comment'] = $comment;
if ( 'pingback' == $comment->comment_type || 'trackback' == $comment->comment_type ) : ?>
<li id="comment-<?php comment_ID(); ?>" <?php comment_class(); ?>>
<div class="comment-body">
<?php _e( 'Pingback:', 'itconsultant' ); ?> <?php comment_author_link(); ?> <?php edit_comment_link( __( 'Edit', 'itconsultant' ), '<span class="edit-link">', '</span>' ); ?>
</div>
<?php else : ?>
<li id="comment-<?php comment_ID(); ?>" <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?>>
<article id="div-comment-<?php comment_ID(); ?>" class="comment-body">
<footer class="comment-meta">
<div class="comment-author vcard">
<?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, 34 ); ?>
</div><!-- .comment-author -->
<div class="comment-metadata">
<?php printf( __( sprintf( '<cite class="fn">%s</cite> on', get_comment_author_link() ) ) ); ?>
<a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
<time datetime="<?php comment_time( 'c' ); ?>">
<?php printf( _x( '%1$s', '1: date', 'itconsultant' ), get_comment_date(), get_comment_time() ); ?>
</time>
</a>
<?php edit_comment_link( __( 'Edit', 'itconsultant' ), '<span class="edit-link">', '</span>' ); ?>
</div><!-- .comment-metadata -->
<?php if ( '0' == $comment->comment_approved ) : ?>
<p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'itconsultant' ); ?></p>
<?php endif; ?>
</footer><!-- .comment-meta -->
<div class="comment-content">
<?php comment_text(); ?>
</div><!-- .comment-content -->
<?php
comment_reply_link( array_merge( $args, array(
'add_below' => 'div-comment',
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<div class="reply">',
'after' => '</div>',
) ) );
?>
</article><!-- .comment-body -->
<?php
endif;
}
endif; // ends check for skt_itconsultant_comment()
if ( ! function_exists( 'skt_itconsultant_the_attached_image' ) ) :
/**
* Prints the attached image with a link to the next attached image.
*/
function skt_itconsultant_the_attached_image() {
$post = get_post();
$attachment_size = apply_filters( 'skt_itconsultant_attachment_size', array( 1200, 1200 ) );
$next_attachment_url = wp_get_attachment_url();
/**
* Grab the IDs of all the image attachments in a gallery so we can get the
* URL of the next adjacent image in a gallery, or the first image (if
* we're looking at the last image in a gallery), or, in a gallery of one,
* just the link to that image file.
*/
$attachment_ids = get_posts( array(
'post_parent' => $post->post_parent,
'fields' => 'ids',
'numberposts' => -1,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID'
) );
// If there is more than 1 attachment in a gallery...
if ( count( $attachment_ids ) > 1 ) {
foreach ( $attachment_ids as $attachment_id ) {
if ( $attachment_id == $post->ID ) {
$next_id = current( $attachment_ids );
break;
}
}
// get the URL of the next image attachment...
if ( $next_id )
$next_attachment_url = get_attachment_link( $next_id );
// or get the URL of the first image attachment.
else
$next_attachment_url = get_attachment_link( array_shift( $attachment_ids ) );
}
printf( '<a href="%1$s" rel="attachment">%2$s</a>',
esc_url( $next_attachment_url ),
wp_get_attachment_image( $post->ID, $attachment_size )
);
}
endif;
if ( ! function_exists( 'skt_itconsultant_posted_on' ) ) :
/**
* Prints HTML with meta information for the current post-date/time and author.
*/
function skt_itconsultant_posted_on() {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) )
$time_string .= '<time class="updated" datetime="%3$s">%4$s</time>';
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
printf( __( '<span class="posted-on">Published %1$s</span><span class="byline"> by %2$s</span>', 'itconsultant' ),
sprintf( '<a href="%1$s" rel="bookmark">%2$s</a>',
esc_url( get_permalink() ),
$time_string
),
sprintf( '<span class="author vcard"><a class="url fn n" href="%1$s">%2$s</a></span>',
esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
esc_html( get_the_author() )
)
);
}
endif;
/**
* Returns true if a blog has more than 1 category
*/
function skt_itconsultant_categorized_blog() {
if ( false === ( $all_the_cool_cats = get_transient( 'all_the_cool_cats' ) ) ) {
// Create an array of all the categories that are attached to posts
$all_the_cool_cats = get_categories( array(
'hide_empty' => 1,
) );
// Count the number of categories that are attached to the posts
$all_the_cool_cats = count( $all_the_cool_cats );
set_transient( 'all_the_cool_cats', $all_the_cool_cats );
}
if ( '1' != $all_the_cool_cats ) {
// This blog has more than 1 category so skt_itconsultant_categorized_blog should return true
return true;
} else {
// This blog has only 1 category so skt_itconsultant_categorized_blog should return false
return false;
}
}
/**
* Flush out the transients used in skt_itconsultant_categorized_blog
*/
function skt_itconsultant_category_transient_flusher() {
// Like, beat it. Dig?
delete_transient( 'all_the_cool_cats' );
}
add_action( 'edit_category', 'skt_itconsultant_category_transient_flusher' );
add_action( 'save_post', 'skt_itconsultant_category_transient_flusher' );
| Tamiiy/spartan-english | wp-content/themes/skt-it-consultant/inc/template-tags.php | PHP | gpl-2.0 | 8,307 |
/**
* @package JCE
* @copyright Copyright (c) 2009-2015 Ryan Demmer. All rights reserved.
* @license GNU/GPL 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* JCE is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
(function(){
tinymce.create('tinymce.plugins.Browser', {
init: function(ed, url){
this.ed = ed;
},
browse: function(name, url, type, win){
var ed = this.ed;
ed.windowManager.open({
file: ed.getParam('site_url') + 'index.php?option=com_jce&view=editor&layout=plugin&plugin=browser&type=' + type,
width : 780 + ed.getLang('browser.delta_width', 0),
height : 480 + ed.getLang('browser.delta_height', 0),
resizable: "yes",
inline: "yes",
close_previous: "no",
popup_css : false
}, {
window: win,
input: name,
url: url,
type: type
});
return false;
},
getInfo: function(){
return {
longname: 'Browser',
author: 'Ryan Demmer',
authorurl: 'http://www.joomlacontenteditor.net',
infourl: 'http://www.joomlacontenteditor.net/index.php?option=com_content&view=article&task=findkey&tmpl=component&lang=en&keyref=browser.about',
version: '@@version@@'
};
}
});
// Register plugin
tinymce.PluginManager.add('browser', tinymce.plugins.Browser);
})(); | widgetfactory/jce-editor | editor/tiny_mce/plugins/browser/editor_plugin.js | JavaScript | gpl-2.0 | 1,889 |
/*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
*/
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import sun.nio.cs.Surrogate;
/**
* An abstract base class for subclasses which encodes
* IBM double byte host encodings such as ibm code
* pages 942,943,948, etc.
*
*/
public abstract class DBCS_IBM_EBCDIC_Encoder extends CharsetEncoder
{
protected static final char REPLACE_CHAR='\uFFFD';
private byte b1;
private byte b2;
protected short index1[];
protected String index2;
protected String index2a;
protected int mask1;
protected int mask2;
protected int shift;
private static final int SBCS = 0;
private static final int DBCS = 1;
private static final byte SO = 0x0e;
private static final byte SI = 0x0f;
private int currentState;
private final Surrogate.Parser sgp = new Surrogate.Parser();
protected DBCS_IBM_EBCDIC_Encoder(Charset cs) {
super(cs, 4.0f, 5.0f, new byte[] {(byte)0x6f});
}
protected void implReset() {
currentState = SBCS;
}
protected CoderResult implFlush(ByteBuffer out) {
if (currentState == DBCS) {
if (out.remaining() < 1)
return CoderResult.OVERFLOW;
out.put(SI);
}
implReset();
return CoderResult.UNDERFLOW;
}
/**
* Returns true if the given character can be converted to the
* target character encoding.
*/
public boolean canEncode(char ch) {
int index;
int theBytes;
index = index1[((ch & mask1) >> shift)] + (ch & mask2);
if (index < 15000)
theBytes = (int)(index2.charAt(index));
else
theBytes = (int)(index2a.charAt(index-15000));
if (theBytes != 0)
return (true);
// only return true if input char was unicode null - all others are
// undefined
return( ch == '\u0000');
}
private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) {
char[] sa = src.array();
int sp = src.arrayOffset() + src.position();
int sl = src.arrayOffset() + src.limit();
byte[] da = dst.array();
int dp = dst.arrayOffset() + dst.position();
int dl = dst.arrayOffset() + dst.limit();
int outputSize = 0; // size of output
int spaceNeeded;
try {
while (sp < sl) {
int index;
int theBytes;
char c = sa[sp];
if (Surrogate.is(c)) {
if (sgp.parse(c, sa, sp, sl) < 0)
return sgp.error();
return sgp.unmappableResult();
}
if (c >= '\uFFFE')
return CoderResult.unmappableForLength(1);
index = index1[((c & mask1) >> shift)]
+ (c & mask2);
if (index < 15000)
theBytes = (int)(index2.charAt(index));
else
theBytes = (int)(index2a.charAt(index-15000));
b1= (byte)((theBytes & 0x0000ff00)>>8);
b2 = (byte)(theBytes & 0x000000ff);
if (b1 == 0x00 && b2 == 0x00
&& c != '\u0000') {
return CoderResult.unmappableForLength(1);
}
if (currentState == DBCS && b1 == 0x00) {
if (dl - dp < 1)
return CoderResult.OVERFLOW;
currentState = SBCS;
da[dp++] = SI;
} else if (currentState == SBCS && b1 != 0x00) {
if (dl - dp < 1)
return CoderResult.OVERFLOW;
currentState = DBCS;
da[dp++] = SO;
}
if (currentState == DBCS)
spaceNeeded = 2;
else
spaceNeeded = 1;
if (dl - dp < spaceNeeded)
return CoderResult.OVERFLOW;
if (currentState == SBCS)
da[dp++] = b2;
else {
da[dp++] = b1;
da[dp++] = b2;
}
sp++;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(sp - src.arrayOffset());
dst.position(dp - dst.arrayOffset());
}
}
private CoderResult encodeBufferLoop(CharBuffer src, ByteBuffer dst) {
int mark = src.position();
int outputSize = 0; // size of output
int spaceNeeded;
try {
while (src.hasRemaining()) {
int index;
int theBytes;
char c = src.get();
if (Surrogate.is(c)) {
if (sgp.parse(c, src) < 0)
return sgp.error();
return sgp.unmappableResult();
}
if (c >= '\uFFFE')
return CoderResult.unmappableForLength(1);
index = index1[((c & mask1) >> shift)]
+ (c & mask2);
if (index < 15000)
theBytes = (int)(index2.charAt(index));
else
theBytes = (int)(index2a.charAt(index-15000));
b1 = (byte)((theBytes & 0x0000ff00)>>8);
b2 = (byte)(theBytes & 0x000000ff);
if (b1== 0x00 && b2 == 0x00
&& c != '\u0000') {
return CoderResult.unmappableForLength(1);
}
if (currentState == DBCS && b1 == 0x00) {
if (dst.remaining() < 1)
return CoderResult.OVERFLOW;
currentState = SBCS;
dst.put(SI);
} else if (currentState == SBCS && b1 != 0x00) {
if (dst.remaining() < 1)
return CoderResult.OVERFLOW;
currentState = DBCS;
dst.put(SO);
}
if (currentState == DBCS)
spaceNeeded = 2;
else
spaceNeeded = 1;
if (dst.remaining() < spaceNeeded)
return CoderResult.OVERFLOW;
if (currentState == SBCS)
dst.put(b2);
else {
dst.put(b1);
dst.put(b2);
}
mark++;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(mark);
}
}
protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
if (true && src.hasArray() && dst.hasArray())
return encodeArrayLoop(src, dst);
else
return encodeBufferLoop(src, dst);
}
}
| TheTypoMaster/Scaper | openjdk/jdk/test/sun/nio/cs/OLD/DBCS_IBM_EBCDIC_Encoder.java | Java | gpl-2.0 | 8,255 |
<?php
/*
* This file is part of Double Choco Latte.
* Copyright (C) 1999-2014 Free Software Foundation
*
* Double Choco Latte 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.
*
* Double Choco Latte 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.
*
* Select License Info from the Help menu to view the terms and conditions of this license.
*/
function smarty_block_dcl_form_control($params, $content, $template, &$repeat)
{
$inputGroup = isset($params['inputGroup']) && $params['inputGroup'] == true;
if (is_null($content) && $repeat) {
$required = isset($params['required']) && $params['required'] == true;
$labelUsed = isset($params['label']) && $params['label'] != '';
$controlSizeUsed = isset($params['controlsize']) && $params['controlsize'] != '';
?> <div class="form-group<?php if ($required) {?> required<?php } ?>"<?php if ($required) {?> data-required="required"<?php } ?>>
<?php if ($labelUsed) {?><label for="<?php echo $params['id']; ?>" class="col-sm-2 control-label"><?php echo htmlspecialchars($params['label'], ENT_QUOTES, 'UTF-8'); ?></label><?php } ?>
<div<?php if ($controlSizeUsed || $inputGroup) { ?> class="<?php if ($controlSizeUsed) { ?>col-sm-<?php echo $params['controlsize']; ?><?php } ?><?php if ($inputGroup) { ?> inputGroupContainer<?php } ?>"<?php } ?>>
<?php if ($inputGroup) { ?><div class="input-group"><?php }
return;
}
else if (!$repeat)
{
$help = '';
if (isset($params['help']))
$help = '<div class="col-sm-offset-2 col-sm-10"><span class="help-block">' . htmlspecialchars($params['help'], ENT_QUOTES, 'UTF-8') . '</span></div>';
$closeInputGroup = $inputGroup ? '</div>' : '';
echo $content, '</div>', $closeInputGroup, $help, '</div>';
}
} | gnuedcl/dcl | dcl/inc/plugins/block.dcl_form_control.php | PHP | gpl-2.0 | 2,310 |
from django import forms
from django.forms import ModelForm
from models import *
from django.forms import Textarea
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import Group
class OgretimElemaniFormu(ModelForm):
parolasi=forms.CharField(label="Parolasi",
help_text='Parola yazilmazsa onceki parola gecerlidir',
required=False)
class Meta:
model = OgretimElemani
fields = ('unvani','first_name','last_name',
'username','parolasi','email','telefonu')
def save(self,commit=True):
instance = super(OgretimElemaniFormu,self).save(commit=False)
if self.cleaned_data.get('parolasi'):
instance.password=make_password(self.cleaned_data['parolasi'])
if commit:
instance.save()
if instance.group.filter(name='ogretimelemanlari'):
grp = Group.objects.get(name='ogretimelemanlari')
instance.group.add(grp)
return instance
class DersFormu(ModelForm):
class Meta:
model = Ders
widgets = {
'tanimi':Textarea(attrs={'cols':35, 'rows':5}),
}
#class OgretimElemaniAltFormu(ModelForm):
# class Meta:
# model = OgretimElemani
# fields = ('username','parolasi','email')
#exclude=('unvani','telefonu') bu da ayni gorevi gorur
# fields kullanarak hangi sirada gozukmesini istiyorsak ayarlayabiliriz
# yada exclude diyerek istemedigimiz alanlari formdan cikartabiliriz
class AramaFormu(forms.Form):
aranacak_kelime = forms.CharField()
def clean_aranacak_kelime(self):
kelime=self.cleaned_data['aranacak_kelime']
if len(kelime) < 3:
raise forms.ValidationError('Aranacak kelime 3 harften az olamaz')
return kelime | dogancankilment/Django-obs | yonetim/forms.py | Python | gpl-2.0 | 1,672 |
<div class="container">
<h1 class="page-header">Log masuk sistem</h1>
<?php
/*
switch($strLoginState) {
case 1:
$strLoginMsg="Anda telah dilog keluar. Log masuk sekali lagi untuk meneruskan.";
$alertType="alert-success";
break;
case 2:
$strLoginMsg="Sesi anda telah ditamatkan. Log masuk sekali lagi untuk meneruskan.";
$alertType="alert-warning";
break;
case 3:
$strLoginMsg="Nama pengguna atau kata laluan anda salah. Cuba lagi.";
$alertType="alert-danger";
break;
case 4:
$strLoginMsg="Kata laluan anda telah berjaya diubah. Sila log masuk untuk meneruskan.";
$alertType="alert-info";
break;
default:
*/
$strLoginMsg="Sila log masuk untuk meneruskan.";
$alertType="alert-info";
/*
break;
}
*/
?>
<div class="alert alert-dismissable <?php echo $alertType; ?>">
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo $strLoginMsg; ?>
</div>
<div class="well">
<form id="login" method="post" action="<?php echo URL; ?>login/index">
<div class="form-group">
<label class="control-label">ID Login</label>
<div class="controls">
<input type="text" class="form-control" name="userlogin" />
</div>
<label class="control-label">Kata Laluan</label>
<div class="controls">
<input type="password" class="form-control col-xs-5" name="userpassword" />
</div>
<label class="control-label"> </label>
<div class="controls">
<button class="btn pull-right btn-primary" name="submit_login" type="submit">Log Masuk</button>
</div>
</div>
</form>
</div><!-- .well --> | webgrrrl/tugu-scoring-php-mvc-mysql | application/views/home/index.php | PHP | gpl-2.0 | 1,767 |
<?php
/* meta_gallery_link.html.twig */
class __TwigTemplate_0a35e86033eea29b6e7022dea59ab96e extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 7
echo "
<p id=\"image_link_desc\">
";
// line 9
echo $this->env->getExtension('translate')->transFilter("By default, the <code>[ + ]</code> icon will be linked to a page containing more details about the background image displayed.");
echo "
";
// line 10
echo $this->env->getExtension('translate')->transFilter("Specifying a URL here allows you to override that link to, for example, a gallery. For your convenience, shortcodes (i.e., <code>[gallery_url 1]</code>) are accepted.");
echo "
</p>
<label>
";
// line 13
echo twig_escape_filter($this->env, $this->env->getExtension('translate')->transFilter("Background Image Link"), "html", null, true);
echo "
<input type=\"text\" id=\"image_link\" name=\"image_link\" style=\"width:100%\" value=\"";
// line 14
if (isset($context["image_link"])) { $_image_link_ = $context["image_link"]; } else { $_image_link_ = null; }
echo twig_escape_filter($this->env, $_image_link_, "html", null, true);
echo "\" tabindex=\"3\" />
</label>
";
}
public function getTemplateName()
{
return "meta_gallery_link.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 37 => 14, 33 => 13, 27 => 10, 23 => 9, 19 => 7,);
}
}
| zakfaithfull/wordpress_sit | wp-content/plugins/background-manager/store/cache/views/0a/35/e86033eea29b6e7022dea59ab96e.php | PHP | gpl-2.0 | 1,805 |
<?php
/**
* Theme options / General / General Settings
*
* @package wpv
* @subpackage honeymoon
*/
return array(
array(
'name' => __('General Settings', 'honeymoon'),
'type' => 'start'
),
array(
'name' => __('Header Logo Type', 'honeymoon'),
'id' => 'header-logo-type',
'type' => 'select',
'options' => array(
'image' => __( 'Image', 'honeymoon' ),
'names' => __( 'Names', 'honeymoon' ),
'site-title' => __( 'Site Title', 'honeymoon' ),
),
'static' => true,
'field_filter' => 'fblogo',
),
array(
'name' => __('Custom Logo Picture', 'honeymoon'),
'desc' => __('Please Put a logo which exactly twice the width and height of the space that you want the logo to occupy. The real image size is used for retina displays.', 'honeymoon'),
'id' => 'custom-header-logo',
'type' => 'upload',
'static' => true,
'class' => 'fblogo fblogo-image',
),
array(
'name' => __('First Left Name', 'honeymoon'),
'id' => 'header-name-left-top',
'type' => 'text',
'static' => true,
'class' => 'fblogo fblogo-names',
),
array(
'name' => __('Last Left Name', 'honeymoon'),
'id' => 'header-name-left-bottom',
'type' => 'text',
'static' => true,
'class' => 'fblogo fblogo-names',
),
array(
'name' => __('First Right Name', 'honeymoon'),
'id' => 'header-name-right-top',
'type' => 'text',
'static' => true,
'class' => 'fblogo fblogo-names',
),
array(
'name' => __('Last Right Name', 'honeymoon'),
'id' => 'header-name-right-bottom',
'type' => 'text',
'static' => true,
'class' => 'fblogo fblogo-names',
),
array(
'name' => __('Splash Screen Logo', 'honeymoon'),
'id' => 'splash-screen-logo',
'type' => 'upload',
'static' => true,
),
array(
'name' => __('Favicon', 'honeymoon'),
'desc' => __('Upload your custom "favicon" which is visible in browser favourites and tabs. (Must be .png or .ico file - preferably 16px by 16px ). Leave blank if none required.', 'honeymoon'),
'id' => 'favicon_url',
'type' => 'upload',
'static' => true,
),
array(
'name' => __('Google Maps API Key', 'honeymoon'),
'desc' => __("Only required if you have more than 2500 map loads per day. Paste your Google Maps API Key here. If you don't have one, please sign up for a <a href='https://developers.google.com/maps/documentation/javascript/tutorial#api_key'>Google Maps API key</a>.", 'honeymoon'),
'id' => 'gmap_api_key',
'type' => 'text',
'static' => true,
'class' => 'hidden',
),
array(
'name' => __('Google Analytics Key', 'honeymoon'),
'desc' => __("Paste your key here. It should be something like UA-XXXXX-X. We're using the faster asynchronous loader, so you don't need to worry about speed.", 'honeymoon'),
'id' => 'analytics_key',
'type' => 'text',
'static' => true,
),
array(
'name' => __('"Scroll to Top" Button', 'honeymoon'),
'desc' => __('It is found in the bottom right side. It is sole purpose is help the user scroll a long page quickly to the top.', 'honeymoon'),
'id' => 'show_scroll_to_top',
'type' => 'toggle',
),
array(
'name' => __('Feedback Button', 'honeymoon'),
'desc' => __('It is found on the right hand side of your website. You can chose from a "link" or a slide out form(widget area).The slide out form is configured as a standard widget. You can use the same form you are using for your "contact us" page.', 'honeymoon'),
'id' => 'feedback-type',
'type' => 'select',
'options' => array(
'none' => __('None', 'honeymoon'),
'link' => __('Link', 'honeymoon'),
'sidebar' => __('Slide out widget area', 'honeymoon'),
),
),
array(
'name' => __('Feedback Button Link', 'honeymoon'),
'desc' => __('If you have chosen a "link" in the option above, place the link of the button here, usually to your contact us page.', 'honeymoon'),
'id' => 'feedback-link',
'type' => 'text',
),
array(
'name' => __('Share Icons', 'honeymoon'),
'desc' => __('Select the social media you want enabled and for which parts of the website', 'honeymoon'),
'type' => 'social',
'static' => true,
),
array(
'name' => __('Custom JavaScript', 'honeymoon'),
'desc' => __('If the hundreds of options in the Theme Options Panel are not enough and you need customisation that is outside of the scope of the Theme Option Panel please place your javascript in this field. The contents of this field are placed near the <strong></body></strong> tag, which improves the load times of the page.', 'honeymoon'),
'id' => 'custom_js',
'type' => 'textarea',
'rows' => 15,
'static' => true,
),
array(
'name' => __('Custom CSS', 'honeymoon'),
'desc' => __('If the hundreds of options in the Theme Options Panel are not enough and you need customisation that is outside of the scope of the Theme Options Panel please place your CSS in this field.', 'honeymoon'),
'id' => 'custom_css',
'type' => 'textarea',
'rows' => 15,
'class' => 'top-desc',
),
array(
'type' => 'end'
)
); | basilmon92/wordpress_4_1_1 | wp-content/themes/honeymoon/wpv_theme/options/general/general.php | PHP | gpl-2.0 | 4,983 |
/********************************
* 프로젝트 : gargoyle-jython
* 패키지 : com.kyj.fx.nashorn
* 작성일 : 2019. 10. 4.
* 작성자 : KYJ (callakrsos@naver.com)
*******************************/
package com.kyj.fx.nashorn;
import java.io.File;
import java.io.IOException;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.junit.Test;
import com.kyj.fx.jython.DefaultScriptEngine;
/**
* @author KYJ (callakrsos@naver.com)
*
*/
public class DefaultScriptEngineTest {
// static {
// System.setProperty("python.console.encoding", "UTF-8");
// }
@Test
public void test() throws ScriptException {
DefaultScriptEngine z = new DefaultScriptEngine();
ScriptEngine engine = z.createEngine();
// Using the eval() method on the engine causes a direct
// interpretataion and execution of the code string passed into it
engine.eval("import sys");
engine.eval("print sys");
// Using the put() method allows one to place values into
// specified variables within the engine
engine.put("a", "42");
// As you can see, once the variable has been set with
// a value by using the put() method, we an issue eval statements
// to use it.
engine.eval("print a");
engine.eval("x = 2 + 2");
// Using the get() method allows one to obtain the value
// of a specified variable from the engine instance
Object x = engine.get("x");
System.out.println("x: " + x);
// engine.eval(" print(\"한글\") ");
}
/**
* Hangul Print Test <br/>
* @throws ScriptException
* @throws IOException
*
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2019. 10. 7.
*/
@Test
public void test4() throws IOException, ScriptException {
// System.setProperty("python.console.encoding", "EUC-KR");
DefaultScriptEngine engine = new DefaultScriptEngine();
StringBuffer sb = new StringBuffer();
sb.append("import java.lang.String\n");
sb.append("def Hangul(str, encoding='utf-8'):\n");
sb.append(" return java.lang.String(str,encoding)\n");
sb.append("x = '한글 깨짐' \n" );
sb.append("print(x)\n");
sb.append("x = u'한글 안깨짐' \n" );
sb.append("print(x)\n");
sb.append("print(java.lang.String('한글 안깨짐', 'utf-8'))\n");
sb.append("print(Hangul('한글 안깨짐', 'utf-8'))\n");
sb.append("\n");
//// sb.append("import sys");
// sb.append("sys.stdout.write(u\"한글\")");
// sb.toString();
engine.execute(sb.toString());
}
/**
* read from file. <br/>
* @throws ScriptException
* @throws IOException
* @작성자 : KYJ (callakrsos@naver.com)
* @작성일 : 2019. 10. 7.
*/
@Test
public void test3() throws IOException, ScriptException {
DefaultScriptEngine engine = new DefaultScriptEngine();
engine.execute(new File("script", "Test.py"));
}
@Test
public void test2() throws IOException, ScriptException {
StringBuffer sb = new StringBuffer();
sb.append("x = 100\n");
sb.append("if x > 0:\n");
sb.append(" print('wow this is elegant')\n");
sb.append("else:\n");
sb.append(" print('Oranization is the key.')\n");
sb.append("\n");
sb.append("\n");
sb.append("print('hello ' + ' ' + 'world')\n");
sb.append("\n");
sb.append("\n");
sb.append("def my_function(a='zz'):\n");
sb.append(" print(a)\n");
sb.append("\n");
sb.append("my_function()\n");
sb.append("\n");
sb.append("\n");
sb.append("class my_class:\n");
sb.append(" def __init__(self, x, y ):\n");
sb.append(" self.x = x\n");
sb.append(" self.y = y\n");
sb.append(" print('초기화 함수 ')\n");
sb.append("\n");
sb.append(" def mul(self):\n");
sb.append(" print(self.x * self.y)\n");
sb.append("\n");
sb.append(" def add(self):\n");
sb.append(" print(self.x + self.y)\n");
sb.append("\n");
sb.append("\n");
sb.append("ob1 = my_class(7,8)\n");
sb.append("ob1.mul()\n");
sb.append("\n");
sb.append("ob1.add()\n");
sb.append("\n");
sb.append("decimalValue = 10\n");
sb.append("stringValue = \"10\"\n");
sb.append("floatValue = 10.0\n");
sb.append("\n");
sb.append("print ('String of text goes here %d %s %f' % (decimalValue, stringValue, floatValue))\n");
sb.append("\n");
sb.append("\n");
sb.append("x = 3\n");
sb.append("y = 0\n");
sb.append("try:\n");
sb.append(" print('로켓의 궤도 : %f' % (x/y))\n");
sb.append("except Exception as ex:\n");
sb.append(" print(ex.__str__() )\n");
sb.append("\n");
sb.append("\n");
sb.append("\n");
sb.append("print(range(1,5))\n");
sb.append("\n");
sb.append("\n");
sb.append("items = [1,2,3,4,5, 10]\n");
sb.append("for item in items:\n");
sb.append(" print(item)\n");
sb.append("items.append(11)\n");
sb.append("\n");
sb.append("print(items)\n");
sb.append("\n");
sb.append("items = [ y**2 for y in range(1,10)]\n");
sb.append("print(items)\n");
sb.append("\n");
sb.append("pairs = []\n");
sb.append("A = ['blue', 'yellow', 'red']\n");
sb.append("B = ['red', 'green', 'blue']\n");
sb.append("\n");
sb.append("for a in A:\n");
sb.append(" for b in B:\n");
sb.append(" if a != b:\n");
sb.append(" pairs.append((a,b))\n");
sb.append("print (pairs)\n");
sb.append("\n");
sb.append("\n");
sb.append("pairs = []\n");
sb.append("pairs = [(a,b) for a in A for b in B if a!=b]\n");
sb.append("print(pairs)\n");
sb.append("\n");
sb.append("\n");
sb.append("a = {x for x in 'abracatabra' if x not in 'abc'}\n");
sb.append("print(a)\n");
sb.append("\n");
sb.append("print(\"###############################################\")\n");
sb.append("alpa = 2\n");
sb.append("\n");
sb.append("for a in range(1,10):\n");
sb.append(" print(\"%d x %d = %d\" % (alpa , a , (alpa*a)) )\n");
sb.append("\n");
sb.append("\n");
sb.append("print('###############################################')\n");
sb.append("print('abcdefg'.upper())\n");
sb.append("print(\"%s %s %s\" % (ord('a'), ord('b'), ord('c')))\n");
sb.append("\n");
sb.append("\n");
sb.append("print(\"########################################\")\n");
sb.append("str = \"abcde\"\n");
sb.append("newStr = \"\"\n");
sb.append("for a in range(len(str) - 1, -1 , -1):\n");
sb.append(" newStr += str[a]\n");
sb.append("print(\"print newStr : %s \" % (newStr))\n");
sb.append("\n");
sb.append("\n");
sb.append("books = [ {\n");
sb.append(" \"제목\":\"개발자의 코드\",\n");
sb.append(" \"출판연도\": \"2013.02.28\",\n");
sb.append(" \"출판사\":\"A\",\n");
sb.append(" \"쪽수\":200,\n");
sb.append(" \"추천유무\":False\n");
sb.append("}, {\n");
sb.append(" \"제목\":\"클린코드\",\n");
sb.append(" \"출판연도\": \"2010.03.04\",\n");
sb.append(" \"출판사\":\"B\",\n");
sb.append(" \"쪽수\":584,\n");
sb.append(" \"추천유무\":True\n");
sb.append("}, {\n");
sb.append(" \"제목\":\"빅데이터 마케팅\",\n");
sb.append(" \"출판연도\": \"2014.07.10\",\n");
sb.append(" \"출판사\":\"A\",\n");
sb.append(" \"쪽수\":296,\n");
sb.append(" \"추천유무\":True\n");
sb.append("},\n");
sb.append("]\n");
sb.append("\n");
sb.append("print(\"############################################\")\n");
sb.append("many_page = []\n");
sb.append("my_recommand = []\n");
sb.append("for book in books:\n");
sb.append(" if book[\"쪽수\"] > 250:\n");
sb.append(" many_page.append(book)\n");
sb.append("\n");
sb.append(" if book[\"추천유무\"]:\n");
sb.append(" my_recommand.append(book)\n");
sb.append("\n");
sb.append("print(many_page)\n");
sb.append("print(my_recommand)\n");
DefaultScriptEngine engine = new DefaultScriptEngine();
engine.execute(sb.toString());
}
}
| callakrsos/Gargoyle | gargoyle-jython/src/test/java/com/kyj/fx/nashorn/DefaultScriptEngineTest.java | Java | gpl-2.0 | 8,095 |
<?php
/**
* @package JobBoard
* @copyright Copyright (c)2010-2012 Tandolin <http://www.tandolin.com>
* @license : GNU General Public License v2 or later
* ----------------------------------------------------------------------- */
// Protect from unauthorized access
defined('_JEXEC') or die('Restricted Access');
//JTable::addIncludePath(JPATH_COMPONENT.DS.'tables');
jimport('joomla.application.component.controller');
class JobboardControllerCareerlevels extends JController {
var $view;
function add() {
JToolBarHelper::title(JText::_('COM_JOBBOARD_NEW_CAREER_LEVEL'));
JToolBarHelper::save();
JToolBarHelper::cancel();
JRequest::setVar('view', 'careerleveledit');
$this->displaySingle('old');
}
function edit() {
JToolBarHelper::title(JText::_('COM_JOBBOARD_EDIT_CAREER_LEVEL'));
JToolBarHelper::save();
JToolBarHelper::cancel();
JobBoardToolbarHelper::setToolbarLinks('careerlevels');
JRequest::setVar('view', 'careerleveledit');
$this->displaySingle('old');
}
function remove() {
$cid = JRequest::getVar('cid', array(), '', 'array');
JArrayHelper::toInteger($cid);
$doc = JFactory::getDocument();
$style = " .icon-48-job_posts {background-image:url(components/com_jobboard/images/job_posts.png); no-repeat; }";
$doc->addStyleDeclaration($style);
$this->setToolbar();
if (count($cid)) {
$cids = implode(',', $cid);
$jobs_model = $this->getModel('Careerlevels');
$delete_result = $jobs_model->deleteCareers($cids);
if ($delete_result <> true) {
//echo "<script> alert('".$db->getErrorMsg(true)."'); window.history.go(-1); </script>\n";
$this->setRedirect('index.php?option=com_jobboard&view=careerlevels', $delete_result);
} else {
$success_msg = (count($cid) == 1) ? JText::_('COM_JOBBOARD_CAREER_LEVEL_DELETED') : JText::_('COM_JOBBOARD_CAREERS_DELETED');
$this->setRedirect('index.php?option=com_jobboard&view=careerlevels', $success_msg);
}
}
}
function setToolbar() {
JToolBarHelper::title(JText::_('COM_JOBBOARD_CAREER_LEVELS'), 'job_posts.png');
JToolBarHelper::deleteList();
JToolBarHelper::addNewX();
JToolBarHelper::editList();
JToolBarHelper::back();
//$selected = ($view == 'item6');
// prepare links
}
function display() //display list of all users
{
$doc = JFactory::getDocument();
$style = " .icon-48-job_posts {background-image:url(components/com_jobboard/images/job_posts.png); no-repeat; }";
$doc->addStyleDeclaration($style);
JToolBarHelper::title(JText::_('COM_JOBBOARD_CAREER_LEVELS'), 'job_posts.png');
JToolBarHelper::deleteList();
JToolBarHelper::addNewX();
JToolBarHelper::editList();
JToolBarHelper::back();
$view = JRequest::getVar('view');
if (!$view) {
JRequest::setVar('view', 'careerlevel');
}
JobBoardToolbarHelper::setToolbarLinks('careerlevels');
parent::display();
}
function displaySingle($type) //display a single User that can be edited
{
JRequest::setVar('view', 'careerleveledit');
if ($type = 'new') JRequest::setVar('task', 'add');
parent::display();
}
function cancel() {
//reset the parameters
JRequest::setVar('task', '');
JRequest::setVar('view', 'dashboard');
//call up the dashboard screen controller
require_once(JPATH_COMPONENT_ADMINISTRATOR . DS . 'controllers' . DS . 'dashboard.php');
}
}
$controller = new JobboardControllerCareerlevels();
if (!isset($task)) $task = "display"; //cancel button doesn't pass task so may gen php warning on execute below
$controller->execute($task);
$controller->redirect();
?> | pdxfixit/pkg_jobboard | admin/controllers/careerlevels.php | PHP | gpl-2.0 | 3,986 |
<?php
namespace mapaxe\core;
if( !defined('ENTRYPOINT') ) die('Restricted Access');
use \mapaxe\libs\Log;
use \mapaxe\core\Marco;
/**
* Handler.php is the core object to manage the error and exceptions throws by the program;
* entry.php is the entry point to get easy and offer function tools for the core functionality
* @package mapaxe.core
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License version 2 or later; see LICENSE.txt. Moreover it intends to be a collaborative class multiple developers among several PHP developers.
* @author Marco Mapaxe
*/
class Handler{
/**
* Constant necesary to control the type of message what log
*/
const ERROR='error';
/**
* Constant necesary to control the type of message what log
*/
const EXCEPTION='exception';
/**
* Constant necesary to control the type of message what log
*/
const WARNING='warn';
/**
* Constant necesary to control the type of message what log
*/
const INFO='info';
/**
*
* @param string $typeMsg it will be one of the control constant of this class, to know what king of error we are dealing with
* @param string $message the content of the error/exception
* @param string $rawdata the raw content of the error/exception
* @return string the the complete message logged
* @throws \InvalidArgumentException if bad paremeters were passed (string in $typeMsg, string in $message, string in $rawdata)
*/
static function log( $typeMsg, $message , $rawdata= '' ){
if( !is_string($typeMsg) || !is_string($message) || !is_string($rawdata) )
throw new \InvalidArgumentException( "Handler::log EXCEPTION, bad parameter on core handler" );
if($typeMsg!=self::ERROR && $typeMsg!=self::EXCEPTION && $typeMsg!=self::WARNING && $typeMsg!=self::INFO)
$typeMsg=self::INFO;
$message = strtoupper($typeMsg). ': ' .$message;
$info='. You can find more details on the log file.';
$config=Marco::$config;
$log=new Log( $config->getLog('directory') , $config->getLog('timezone') );
$log->write( $message.( $rawdata ? ' and raw data: '.$rawdata : '' ) );
return $message.$info;
}
/**
* Ideal manager for the set_exception_handler function although it can be called from external
*
* @param \Exception $e the original exception info
* @return void
*/
static function exception_handler(\Exception $e){
$context=array( $e->getPrevious(), $e->getTraceAsString() );
self::error_handler( $e->getCode(),$e->getMessage(),$e->getFile(),$e->getLine(), $context );
}
/**
* Ideal manager for the set_error_handler function although it can be called from external
*
* @param string $errno error code
* @param string $errstr error message
* @param string $errfile absolute filename where error became
* @param string $errline number of line in the file where script stopped
* @param array $errcontext it can be info about the trace or the previous error
* @return boolean for a complete or not bypass of PHP engine errors
*
*/
static function error_handler($errno ,$errstr , $errfile , $errline , array $errcontext ){
$code=$errno;
$typeMsg=self::ERROR;
$errcontext=json_encode($errcontext);
switch($errno){
case E_ALL: $errno='E_ALL - All errors and warnings (includes E_STRICT as of PHP 6.0.0)';break;
case E_ERROR: $errno='E_ERROR - fatal run-time errors';break;
case E_RECOVERABLE_ERROR: $errno='E_RECOVERABLE_ERROR - almost fatal run-time errors';break;
case E_WARNING: $errno='E_WARNING - run-time warnings (non-fatal errors)';break;
case E_PARSE: $errno='E_PARSE - compile-time parse errors';break;
case E_NOTICE: $errno='E_NOTICE run-time notices (these are warnings which often result from a bug in your code, but it\'s possible that it was intentional (e.g., using an uninitialized variable and relying on the fact it\'s automatically initialized to an empty string)';break;
case E_STRICT: $errno='E_STRICT run-time notices, enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code';break;
case E_CORE_ERROR: $errno='E_CORE_ERROR - fatal errors that occur during PHP\'s initial startup';break;
case E_CORE_WARNING: $errno='E_CORE_WARNING - warnings (non-fatal errors) that occur during PHP\'s initial startup';break;
case E_COMPILE_ERROR: $errno='E_COMPILE_ERROR - fatal compile-time errors';break;
case E_COMPILE_WARNING: $errno='E_COMPILE_WARNING - compile-time warnings (non-fatal errors)';break;
case E_USER_ERROR: $errno='E_USER_ERROR - user-generated error message';break;
case E_USER_WARNING: $errno='E_USER_WARNING - user-generated warning message';break;
case E_USER_NOTICE: $errno='E_USER_NOTICE - user-generated notice message';break;
case E_DEPRECATED: $errno='E_DEPRECATED - warn about code that will not work in future versions of PHP';break;
default:
$errno='EXCEPTION - if no codified by PHP Error level constants, it is an Exception by the php script.';
$typeMsg=self::EXCEPTION;
break;
}
$rawdata='TYPE OF ERROR: '.$errno.'(code '.$code.'); FILE: '.$errfile.'; LINE: '.$errline.'; CONTEXT VARS: '.$errcontext;
self::log($typeMsg,$errstr,$rawdata);
return TRUE;
}
}
| proyectomarcomapaxe/mapaxe | core/Handler.php | PHP | gpl-2.0 | 5,978 |
using System;
using System.Collections.Generic;
using System.Text;
namespace ICaiBan.ModelBL.FieldEnums
{
[Serializable]
public enum FETabPlatMessage
{
/// <summary>
/// 流水号
/// </summary>
Seq_No = 0,
/// <summary>
/// 接收用户ID
/// </summary>
Rec_User_Id = 1,
/// <summary>
/// 接收用户类型(0:会员;1:商户;2:平台)
/// </summary>
Rec_User_Type = 2,
/// <summary>
/// 信息类型ID(101:提醒消费;102:系统通知;103:提现/充值;201:发布商品审核;202:会员条件审核;203:会员等级审核;204:特殊顾客审核;205:储值条件审核;206:商户认证;207:商户签约;208:商户冻结;209:商户解冻;210:认证签约处理意见;211:商户资料审核;212:结算费用调整;213:申请会员储值)
/// </summary>
Msg_Type_Id = 3,
/// <summary>
/// 信息标题
/// </summary>
Msg_Title = 4,
/// <summary>
/// 信息内容
/// </summary>
Msg_Context = 5,
/// <summary>
/// 发件用户ID
/// </summary>
Send_User_Id = 6,
/// <summary>
/// 发件用户类型(0:会员;1:商户;2:平台)
/// </summary>
Send_User_Type = 7,
/// <summary>
/// 发送时间
/// </summary>
Send_Time = 8,
/// <summary>
/// 阅读标志(0:未读;1:已读)
/// </summary>
Read_Flag = 9,
/// <summary>
/// 阅读时间
/// </summary>
Read_Time = 10,
/// <summary>
/// 接收删除标志(0:未删除;1:已删除)
/// </summary>
Rec_Delete_Flag = 11,
/// <summary>
/// 发送删除标志(0:未删除;1:已删除)
/// </summary>
Send_Delete_Flag = 12,
/// <summary>
/// 业务流水号(订单号/产品ID)(无的情况下写入0)
/// </summary>
Business_Seq_No = 13,
/// <summary>
/// 事件链接地址
/// </summary>
Event_Link_Address = 14,
}
} | zhangbojr/ICB | DAL/ICaiBan.ModelBL/FieldEnums/FETabPlatMessage.cs | C# | gpl-2.0 | 2,346 |
// URI - 1195
// Implementar um TAD ABB (Arvore Binaria de Busca) com as funcoes de insercao e liberacao
#include <iostream>
#include <cstdio>
using namespace std;
// Estrutura da ABB
struct Arv
{
int valor;
Arv *esq;
Arv *dir;
}typedef Arv;
// Funcoes da ABB
Arv* init ();
Arv* busca (Arv *r, int v);
Arv* insere (Arv *r, int v);
bool vazia (Arv *r);
Arv* libera (Arv *r);
void imprimePos (Arv *r);
void imprimeIn (Arv *r);
void imprimePre (Arv *r);
// Inicializa a ABB
Arv* init ()
{
return NULL;
}
Arv* insere (Arv *r, int valor)
{
// ABB esta vazia
if (r == NULL)
{
r = new Arv();
r->valor = valor;
r->esq = NULL;
r->dir = NULL;
}
// ABB ja possui elementos
// Valor eh menor que o da raiz, procurar na sub.arvore esquerda
else if (valor < r->valor)
r->esq = insere(r->esq,valor);
// Valor eh maior que o da raiz, procurar na sub.arvore direita
else
r->dir = insere(r->dir,valor);
return r;
}
// Imprime em Pre-Ordem
void imprimePre (Arv *r)
{
if (r != NULL)
{
printf(" %d",r->valor);
imprimePre(r->esq);
imprimePre(r->dir);
}
}
// Imprime em In-Ordem
void imprimeIn (Arv *r)
{
if (r != NULL)
{
imprimeIn(r->esq);
printf(" %d",r->valor);
imprimeIn(r->dir);
}
}
// Imprime em Pos-Ordem
void imprimePos (Arv *r)
{
if (r != NULL)
{
imprimePos(r->esq);
imprimePos(r->dir);
printf(" %d",r->valor);
}
}
bool vazia (Arv *r)
{
if (r == NULL) return true;
else return false;
}
Arv* libera (Arv *r)
{
if (!vazia(r))
{
r->esq = libera(r->esq);
r->dir = libera(r->dir);
delete r;
}
return NULL;
}
int main ()
{
int K, N;
int valor;
scanf("%d",&K);
for (int k = 0; k < K; k++)
{
// Montar a arvore
Arv *arv = init();
scanf("%d",&N);
for (int i = 0; i < N; i++)
{
scanf("%d",&valor);
arv = insere(arv,valor);
}
// Imprime a arvore de acordo com a saida
printf("Case %d:\n",k+1);
printf("Pre.:"); imprimePre(arv); printf("\n");
printf("In..:"); imprimeIn(arv); printf("\n");
printf("Post:"); imprimePos(arv); printf("\n");
// Libera arvore para a proxima entrada
libera(arv);
printf("\n");
}
}
| bergolho1337/URI-Online-Judge | Grafos/1195/main.cpp | C++ | gpl-2.0 | 2,415 |
<?php
/**
* Auto Amazon Links
*
* https://en.michaeluno.jp/amazon-auto-links/
* Copyright (c) 2013-2021 Michael Uno
*
*/
/**
* The U.S. locale class.
*
* @since 4.3.4
*/
class AmazonAutoLinks_Locale_US extends AmazonAutoLinks_Locale_NorthAmerica {
/**
* The locale code.
* @var string
*/
public $sSlug = 'US';
/**
* Two digits locale number.
* @var string
*/
public $sLocaleNumber = '01';
/**
* @var string
*/
public $sDomain = 'www.amazon.com';
/**
* @var string
*/
public $sAssociatesURL = 'https://affiliate-program.amazon.com/';
/**
* @var string
*/
public $sFlagImg = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAWCAYAAAChWZ5EAAABSklEQVRIS2PMFlaJ3SwbPO8dqwgLAwgwM4Ephr//IDQRfCYONobqI7kQ9cSDl///M6QyyhmU/37LKAixnEzAyM7KUHummBzdLxl5TLv////zl2HnvBQGRkYGhpiGC2CDFtcbEM1nZmNhODXXgiQHTJm3FKwe7oBd84EOAApEQx2wpAHoACL5zKxAB8wj1wEWvf////zNICZvQrLPYV5m5WZn2HYqkqQQWHv/CTQE0BxAis9hNrIBHbCVbAeMpoHRNDCaBtDSAEmZGaqYonKAz2Hy/38/fjFIyBkzMPxnYGBiYwaXgH9//yWaz87LwbB+byBJbocXRE0T5/5nZ2djSI0OJckAShXD64IBd0AnCyjgGRiCFWUo9RRJ+uFRMOAOGPAoGHAHAKPgBTDyxEmKQOopfsbYwczgC2yKzQGaKUY9c4ky6RmwUZoBAO2BIfPVOVScAAAAAElFTkSuQmCC';
/**
* @return string The country name.
* @since 4.5.0
*/
public function getName() {
return __( 'United States', 'amazon-auto-links' );
}
/**
* @return string
*/
public function getLabel() {
return $this->sSlug . ' - ' . __( 'United States', 'amazon-auto-links' );
}
/**
* @remark The supported locales: US, CA, FR, DE, UK, JP.
* @see https://www.assoc-amazon.com/s/impression-counter-common.js
* @return string
*/
protected function _getImpressionCounterScript() {
return <<<SCRIPT
var amazon_impression_url = "www.assoc-amazon.com";
var amazon_impression_campaign = '211189';
var amazon_impression_ccmids = {
'as2' : '374929',
'-as2' : '9325',
'am2' : '374925',
'-am2' : '9325',
'ur2' : '9325'
};
document.write("<scr"+"ipt src='https://"
+ amazon_impression_url
+ "/s/impression-counter-common.js' type='text/javascript'></scr"+"ipt>");
SCRIPT;
}
} | michaeluno/amazon-auto-links | include/core/_common/utility/locale/AmazonAutoLinks_Locale_US.php | PHP | gpl-2.0 | 2,256 |
var FileChooser = function(config)
{
// Setup a variable for the current directory
this.current_directory;
/* ---- Begin side_navbar tree --- */
this.tree = new Ext.tree.TreePanel(
{
region: 'west',
width: 150,
minSize: 150,
maxSize: 250,
animate: true,
loader: new Ext.tree.TreeLoader({dataUrl: 'tree_data.json.php' }),
enableDD: true,
containerScroll: true,
rootVisible:true,
root: new Ext.tree.AsyncTreeNode(
{
text: 'Files',
draggable: false,
id: 'source',
expanded: true
}),
listeners:
{
scope: this,
'click': function(node, e)
{
current_directory = node.attributes.url;
this.ds.load({ params: {directory: node.attributes.url}});
}
}
});
// Add a tree sorter in folder mode
new Ext.tree.TreeSorter(this.tree, {folderSort: true});
/* ---- End side_navbar tree --- */
/* ---- Begin grid --- */
this.ds = new Ext.data.GroupingStore(
{
url: 'js/grid_data.json.php',
method: 'POST',
autoLoad: true,
sortInfo: {field: 'name', direction: 'ASC'},
reader: new Ext.data.JsonReader(
{
root: 'data',
totalProperty: 'count'
},
[
{name: 'name'},
{name: 'size', type: 'float'},
{name: 'type'},
{name: 'relative_path'},
{name: 'full_path'},
{name: 'web_path'}
])
});
this.cm = new Ext.grid.ColumnModel(
[
{header: 'Name', dataIndex: 'name', sortable: true},
{header: 'Size', dataIndex: 'size', sortable: true, renderer: Ext.util.Format.fileSize},
{header: 'Type', dataIndex: 'type', sortable: true},
{header: 'Relative Path', dataIndex: 'relative_path', sortable: true, hidden: true},
{header: 'Full Path', dataIndex: 'full_path', sortable: true, hidden: true},
{header: 'Web Path', dataIndex: 'web_path', sortable: true, hidden: true}
]);
this.grid = new Ext.grid.GridPanel(
{
region: 'center',
border: false,
view: new Ext.grid.GroupingView(
{
emptyText: 'This folder contains no files.',
forceFit: true,
showGroupName: false,
enableNoGroups: true
}),
ds: this.ds,
cm: this.cm,
listeners:
{
scope: this,
'rowdblclick': this.doCallback
}
});
/* ---- End grid --- */
/* ---- Begin window --- */
this.popup = new Ext.Window(
{
id: 'FileChooser',
title: 'Choose A File',
width: config.width,
height: config.height,
minWidth: config.width,
minHeight: config.height,
layout: 'border',
items: [ this.tree, this.grid ],
buttons: [
{
text: 'Ok',
scope: this,
handler: this.doCallback
},
{
text: 'Cancel',
scope: this,
handler: function()
{
this.popup.hide();
}
}]
});
/* ---- End window --- */
};
FileChooser.prototype =
{
show : function(el, callback)
{
if (Ext.type(el) == 'object')
this.showEl = el.getEl();
else
this.showEl = el;
this.el = el;
this.popup.show(this.showEl);
this.callback = callback;
},
doCallback : function()
{
var row = this.grid.getSelectionModel().getSelected();
var callback = this.callback;
var el = this.el;
this.popup.close();
if (row && callback)
{
var data = row.data.web_path;
callback(el, data);
}
}
};
function FileBrowser(fieldName, url, win)
{
var chooser = new FileChooser({width: 500, height:400});
chooser.show(fieldName, function(el, data)
{
win.document.getElementById(el).value = data;
});
} | vyos/vyatta-webgui | src/client/Vyatta/utils/vyatta-filechooser.js | JavaScript | gpl-2.0 | 4,309 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenCLNet;
using System.IO;
namespace OpenCLDSP
{
public unsafe class BufferedFIRSolver
{
private Platform Platform { get; set; }
private Context OpenCLContext { get; set; }
private CommandQueue OpenCLCommandQueue { get; set; }
public IList<Device> OpenCLDevices { get; set; }
private Program DiffEqnProgram { get; set; }
private Kernel initWorkBufferKernel { get; set; }
private Kernel filterKernel { get; set; }
private Kernel bufferedFilterKernel { get; set; }
private Mem Table { get; set; }
private Mem WorkBuffer { get; set; }
private Mem OutputBuffer { get; set; }
private Mem InputBuffer { get; set; }
private Mem LockBuffer { get; set; }
public int FilterOrder { get; private set; }
public int CurrentPos { get; private set; }
public int FilterCount { get; private set; }
private int BufferLength { get; set; }
private int BufferPos { get; set; }
public BufferedFIRSolver(Platform platform, IList<FIRFilter> filters, int bufferLength)
{
BufferLength = bufferLength;
FilterCount = filters.Count;
var order = filters[0].B.Count;
FilterOrder = order;
foreach (var x in filters)
if (order != x.B.Count)
throw new InvalidOperationException("The filters should have the same order");
var table = new float[filters.Count * order];
var f = 0;
foreach (var x in filters)
{
for (int i = 0; i < order; i++)
table[f*order + i] = x.B[i];
f++;
}
Platform = platform;
OpenCLContext = Platform.CreateDefaultContext();
OpenCLDevices = Platform.QueryDevices(DeviceType.ALL);
OpenCLCommandQueue = OpenCLContext.CreateCommandQueue(OpenCLDevices[0]);
DiffEqnProgram = OpenCLContext.CreateProgramWithSource(File.OpenText("opencl/BufferedFIRFilter.cl").ReadToEnd());
DiffEqnProgram.Build();
initWorkBufferKernel = DiffEqnProgram.CreateKernel("initWorkBuffer");
filterKernel = DiffEqnProgram.CreateKernel("filter");
Table = OpenCLContext.CreateBuffer(MemFlags.READ_ONLY, table.Length * 4);
WorkBuffer = OpenCLContext.CreateBuffer(MemFlags.WRITE_ONLY, table.Length * 4);
OutputBuffer = OpenCLContext.CreateBuffer(MemFlags.WRITE_ONLY, bufferLength*filters.Count * 4);
InputBuffer = OpenCLContext.CreateBuffer(MemFlags.WRITE_ONLY, bufferLength * filters.Count * 4);
LockBuffer = OpenCLContext.CreateBuffer(MemFlags.READ_ONLY, FilterCount * 4);
fixed (float* array = table)
{
OpenCLCommandQueue.EnqueueWriteBuffer(Table, false, 0, table.Length * 4, new IntPtr((void*)array));
}
initWorkBufferKernel.SetArg(0, WorkBuffer);
OpenCLCommandQueue.EnqueueNDRangeKernel(initWorkBufferKernel, 1, null, new int[] { table.Length }, null, 0, null, out LastStep);
filterKernel.SetArg(0, InputBuffer);
filterKernel.SetArg(2, FilterOrder);
filterKernel.SetArg(3, Table);
filterKernel.SetArg(4, WorkBuffer);
filterKernel.SetArg(5, OutputBuffer);
filterKernel.SetArg(6, BufferLength);
filterKernel.SetArg(7, LockBuffer);
filterKernelGlobalWorkSize = new int[] { table.Length };
mapToOutputKernelGlobalWorkSize = new int[] { filters.Count };
filterKernelLocalWorkSize = getLocalSize(filterKernelGlobalWorkSize[0]);
mapToOutputLocalWorkSize = getLocalSize(mapToOutputKernelGlobalWorkSize[0]);
}
private Event LastStep;
private int[] filterKernelGlobalWorkSize { get; set; }
private int[] mapToOutputKernelGlobalWorkSize { get; set; }
private int[] filterKernelLocalWorkSize { get; set; }
private int[] mapToOutputLocalWorkSize { get; set; }
private int[] getLocalSize(int sz)
{
//return null;
var val = 256;
for (; val > 0; val--)
{
if (sz % val == 0)
break;
}
return new int[] { val };
}
public void Perform(float[] input)
{
if (input.Length != BufferLength)
throw new InvalidOperationException("Invalid Input Length");
Event writeBufferevn;
fixed (float* array = input)
{
OpenCLCommandQueue.EnqueueWriteBuffer(InputBuffer, false, 0, input.Length * 4, new IntPtr((void*)array), 1, new Event[] { LastStep }, out writeBufferevn);
}
Event e1;
filterKernel.SetArg(1, CurrentPos);
OpenCLCommandQueue.EnqueueNDRangeKernel(filterKernel, 1, null, filterKernelGlobalWorkSize, filterKernelLocalWorkSize, 1, new Event[] { writeBufferevn }, out e1);
//mapToOutputKernel.SetArg(0, CurrentPos);
//OpenCLCommandQueue.EnqueueNDRangeKernel(mapToOutputKernel, 1, null, mapToOutputKernelGlobalWorkSize, mapToOutputLocalWorkSize, 1, new Event[] { e1 }, out LastStep);
CurrentPos = (CurrentPos + BufferLength) % FilterOrder;
LastStep = e1;
}
public float[] ReadOutputBuffer()
{
var output = new float[FilterCount * BufferLength];
fixed (float* array = output)
{
OpenCLCommandQueue.EnqueueReadBuffer(OutputBuffer, true, 0, output.Length * 4, new IntPtr((void*)array), 1, new Event[] { LastStep });
}
return output;
}
public void Finish()
{
OpenCLCommandQueue.Finish();
}
}
}
| bngreen/OpenCL-Equalizer | OpenCLDSP/BufferedFIRSolver.cs | C# | gpl-2.0 | 5,990 |
// ---------------------------------------------------------------------- //
// //
// Copyright (c) 2007-2014 //
// Digital Beacon, LLC //
// //
// ---------------------------------------------------------------------- //
using System;
namespace DigitalBeacon.Util
{
public static class DateExtensions
{
/// <summary>
/// Converts the given date to the corresponding JSON date string
/// </summary>
/// <param name="dt">The date.</param>
/// <returns></returns>
public static string ToJson(this DateTime dt)
{
return "/Date({0})/".FormatWith(dt.ToJavaScriptMilliseconds());
}
/// <summary>
/// Converts the given date to the corresponding milliseconds representation
/// that can be used in the JavaScript date constructor
/// http://forums.asp.net/t/1044408.aspx
/// </summary>
/// <param name="dt">The date.</param>
/// <returns></returns>
public static long ToJavaScriptMilliseconds(this DateTime dt)
{
return (long)new TimeSpan(dt.ToUniversalTime().Ticks - new DateTime(1970, 1, 1).Ticks).TotalMilliseconds;
}
/// <summary>
/// Returns the age for the given date of birth
/// </summary>
/// <param name="dateOfBirth">The date of birth.</param>
/// <returns></returns>
public static int Age(this DateTime dateOfBirth)
{
return Age(dateOfBirth, DateTime.Today);
}
/// <summary>
/// Returns the age for the given date of birth on the specified date
/// </summary>
/// <param name="dateOfBirth">The date of birth.</param>
/// <param name="date">The date.</param>
/// <returns></returns>
public static int Age(this DateTime dateOfBirth, DateTime date)
{
int age = date.Year - dateOfBirth.Year;
if (dateOfBirth > date.AddYears(-age))
{
age--;
}
return age;
}
/// <summary>
/// Returns the first day of the week based on the specified date
/// </summary>
/// <param name="dt">The dt.</param>
/// <param name="startOfWeek">The start of week.</param>
/// <returns></returns>
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = dt.DayOfWeek - startOfWeek;
if (diff < 0)
{
diff += 7;
}
return dt.AddDays(-1 * diff).Date;
}
}
}
| digitalbeacon/sitebase | Util/DateExtensions.cs | C# | gpl-2.0 | 2,522 |
package net.xngo.tutorial.java.xxhash;
import net.jpountz.xxhash.XXHashFactory;
import net.jpountz.xxhash.StreamingXXHash32;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
/**
* Basic example showing how to get the hash value of string using XXHash.
* @author Xuan Ngo
*
*/
public class XxhashString
{
public static void main(String[] args)
{
XXHashFactory factory = XXHashFactory.fastestInstance();
try
{
byte[] data = "12345345234572".getBytes("UTF-8");
ByteArrayInputStream in = new ByteArrayInputStream(data);
int seed = 0x9747b28c; // Used to initialize the hash value, use whatever
// value you want, but always the same.
StreamingXXHash32 hash32 = factory.newStreamingHash32(seed);
byte[] buf = new byte[8]; // For real-world usage, use a larger buffer, like 8192 bytes
for (;;)
{
int read = in.read(buf);
if (read == -1)
{
break;
}
hash32.update(buf, 0, read);
}
int hash = hash32.getValue();
System.out.println(hash);
}
catch(UnsupportedEncodingException ex)
{
System.out.println(ex);
}
catch(IOException ex)
{
System.out.println(ex);
}
}
}
| limelime/Tutorial | src/net/xngo/tutorial/java/xxhash/XxhashString.java | Java | gpl-2.0 | 1,394 |
/*
* Copyright (C) 2005-2015 Team Kodi
* http://kodi.tv
*
* 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 Kodi; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "system.h"
#include "VideoPlayerRadioRDS.h"
#include "VideoPlayer.h"
#include "DVDInputStreams/DVDInputStream.h"
#include "DVDInputStreams/DVDFactoryInputStream.h"
#include "DVDInputStreams/DVDInputStreamNavigator.h"
#include "DVDInputStreams/DVDInputStreamPVRManager.h"
#include "DVDDemuxers/DVDDemux.h"
#include "DVDDemuxers/DVDDemuxUtils.h"
#include "DVDDemuxers/DVDDemuxVobsub.h"
#include "DVDDemuxers/DVDFactoryDemuxer.h"
#include "DVDDemuxers/DVDDemuxFFmpeg.h"
#include "DVDFileInfo.h"
#include "utils/LangCodeExpander.h"
#include "input/Key.h"
#include "guilib/LocalizeStrings.h"
#include "utils/URIUtils.h"
#include "GUIInfoManager.h"
#include "cores/DataCacheCore.h"
#include "guilib/GUIWindowManager.h"
#include "guilib/StereoscopicsManager.h"
#include "Application.h"
#include "messaging/ApplicationMessenger.h"
#include "DVDDemuxers/DVDDemuxCC.h"
#include "cores/VideoPlayer/VideoRenderers/RenderManager.h"
#include "cores/VideoPlayer/VideoRenderers/RenderFlags.h"
#ifdef HAS_PERFORMANCE_SAMPLE
#include "xbmc/utils/PerformanceSample.h"
#else
#define MEASURE_FUNCTION
#endif
#include "settings/AdvancedSettings.h"
#include "FileItem.h"
#include "GUIUserMessages.h"
#include "settings/Settings.h"
#include "settings/MediaSettings.h"
#include "utils/log.h"
#include "utils/StreamDetails.h"
#include "pvr/PVRManager.h"
#include "utils/StreamUtils.h"
#include "utils/Variant.h"
#include "storage/MediaManager.h"
#include "dialogs/GUIDialogBusy.h"
#include "dialogs/GUIDialogKaiToast.h"
#include "utils/StringUtils.h"
#include "Util.h"
#include "LangInfo.h"
#include "URL.h"
#include "video/VideoReferenceClock.h"
#ifdef HAS_OMXPLAYER
#include "cores/omxplayer/OMXPlayerAudio.h"
#include "cores/omxplayer/OMXPlayerVideo.h"
#include "cores/omxplayer/OMXHelper.h"
#endif
#include "VideoPlayerAudio.h"
#include "windowing/WindowingFactory.h"
#include "DVDCodecs/DVDCodecUtils.h"
using namespace PVR;
using namespace KODI::MESSAGING;
void CSelectionStreams::Clear(StreamType type, StreamSource source)
{
CSingleLock lock(m_section);
for(int i=m_Streams.size()-1;i>=0;i--)
{
if(type && m_Streams[i].type != type)
continue;
if(source && m_Streams[i].source != source)
continue;
m_Streams.erase(m_Streams.begin() + i);
}
}
SelectionStream& CSelectionStreams::Get(StreamType type, int index)
{
CSingleLock lock(m_section);
int count = -1;
for(size_t i=0;i<m_Streams.size();i++)
{
if(m_Streams[i].type != type)
continue;
count++;
if(count == index)
return m_Streams[i];
}
return m_invalid;
}
std::vector<SelectionStream> CSelectionStreams::Get(StreamType type)
{
std::vector<SelectionStream> streams;
int count = Count(type);
for(int index = 0; index < count; ++index){
streams.push_back(Get(type, index));
}
return streams;
}
#define PREDICATE_RETURN(lh, rh) \
do { \
if((lh) != (rh)) \
return (lh) > (rh); \
} while(0)
class PredicateSubtitleFilter
{
private:
std::string audiolang;
bool original;
bool nosub;
bool onlyforced;
public:
/** \brief The class' operator() decides if the given (subtitle) SelectionStream is relevant wrt.
* preferred subtitle language and audio language. If the subtitle is relevant <B>false</B> false is returned.
*
* A subtitle is relevant if
* - it was previously selected, or
* - it's an external sub, or
* - it's a forced sub and "original stream's language" was selected, or
* - it's a forced sub and its language matches the audio's language, or
* - it's a default sub, or
* - its language matches the preferred subtitle's language (unequal to "original stream's language")
*/
PredicateSubtitleFilter(std::string& lang)
: audiolang(lang),
original(StringUtils::EqualsNoCase(CSettings::GetInstance().GetString(CSettings::SETTING_LOCALE_SUBTITLELANGUAGE), "original")),
nosub(StringUtils::EqualsNoCase(CSettings::GetInstance().GetString(CSettings::SETTING_LOCALE_SUBTITLELANGUAGE), "none")),
onlyforced(StringUtils::EqualsNoCase(CSettings::GetInstance().GetString(CSettings::SETTING_LOCALE_SUBTITLELANGUAGE), "forced_only"))
{
};
bool operator()(const SelectionStream& ss) const
{
if (ss.type_index == CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleStream)
return false;
if (nosub)
return true;
if (onlyforced)
{
if ((ss.flags & CDemuxStream::FLAG_FORCED) && g_LangCodeExpander.CompareISO639Codes(ss.language, audiolang))
return false;
else
return true;
}
if(STREAM_SOURCE_MASK(ss.source) == STREAM_SOURCE_DEMUX_SUB || STREAM_SOURCE_MASK(ss.source) == STREAM_SOURCE_TEXT)
return false;
if ((ss.flags & CDemuxStream::FLAG_FORCED) && (original || g_LangCodeExpander.CompareISO639Codes(ss.language, audiolang)))
return false;
if ((ss.flags & CDemuxStream::FLAG_DEFAULT))
return false;
if(!original)
{
std::string subtitle_language = g_langInfo.GetSubtitleLanguage();
if (g_LangCodeExpander.CompareISO639Codes(subtitle_language, ss.language))
return false;
}
return true;
}
};
static bool PredicateAudioPriority(const SelectionStream& lh, const SelectionStream& rh)
{
PREDICATE_RETURN(lh.type_index == CMediaSettings::GetInstance().GetCurrentVideoSettings().m_AudioStream
, rh.type_index == CMediaSettings::GetInstance().GetCurrentVideoSettings().m_AudioStream);
if(!StringUtils::EqualsNoCase(CSettings::GetInstance().GetString(CSettings::SETTING_LOCALE_AUDIOLANGUAGE), "original"))
{
std::string audio_language = g_langInfo.GetAudioLanguage();
PREDICATE_RETURN(g_LangCodeExpander.CompareISO639Codes(audio_language, lh.language)
, g_LangCodeExpander.CompareISO639Codes(audio_language, rh.language));
bool hearingimp = CSettings::GetInstance().GetBool(CSettings::SETTING_ACCESSIBILITY_AUDIOHEARING);
PREDICATE_RETURN(!hearingimp ? !(lh.flags & CDemuxStream::FLAG_HEARING_IMPAIRED) : lh.flags & CDemuxStream::FLAG_HEARING_IMPAIRED
, !hearingimp ? !(rh.flags & CDemuxStream::FLAG_HEARING_IMPAIRED) : rh.flags & CDemuxStream::FLAG_HEARING_IMPAIRED);
bool visualimp = CSettings::GetInstance().GetBool(CSettings::SETTING_ACCESSIBILITY_AUDIOVISUAL);
PREDICATE_RETURN(!visualimp ? !(lh.flags & CDemuxStream::FLAG_VISUAL_IMPAIRED) : lh.flags & CDemuxStream::FLAG_VISUAL_IMPAIRED
, !visualimp ? !(rh.flags & CDemuxStream::FLAG_VISUAL_IMPAIRED) : rh.flags & CDemuxStream::FLAG_VISUAL_IMPAIRED);
}
if (CSettings::GetInstance().GetBool(CSettings::SETTING_VIDEOPLAYER_PREFERDEFAULTFLAG))
{
PREDICATE_RETURN(lh.flags & CDemuxStream::FLAG_DEFAULT
, rh.flags & CDemuxStream::FLAG_DEFAULT);
}
PREDICATE_RETURN(lh.channels
, rh.channels);
PREDICATE_RETURN(StreamUtils::GetCodecPriority(lh.codec)
, StreamUtils::GetCodecPriority(rh.codec));
PREDICATE_RETURN(lh.flags & CDemuxStream::FLAG_DEFAULT
, rh.flags & CDemuxStream::FLAG_DEFAULT);
return false;
}
/** \brief The class' operator() decides if the given (subtitle) SelectionStream lh is 'better than' the given (subtitle) SelectionStream rh.
* If lh is 'better than' rh the return value is true, false otherwise.
*
* A subtitle lh is 'better than' a subtitle rh (in evaluation order) if
* - lh was previously selected, or
* - lh is an external sub and rh not, or
* - lh is a forced sub and ("original stream's language" was selected or subtitles are off) and rh not, or
* - lh is an external sub and its language matches the preferred subtitle's language (unequal to "original stream's language") and rh not, or
* - lh is language matches the preferred subtitle's language (unequal to "original stream's language") and rh not, or
* - lh is a default sub and rh not
*/
class PredicateSubtitlePriority
{
private:
std::string audiolang;
bool original;
bool subson;
PredicateSubtitleFilter filter;
public:
PredicateSubtitlePriority(std::string& lang)
: audiolang(lang),
original(StringUtils::EqualsNoCase(CSettings::GetInstance().GetString(CSettings::SETTING_LOCALE_SUBTITLELANGUAGE), "original")),
subson(CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleOn),
filter(lang)
{
};
bool relevant(const SelectionStream& ss) const
{
return !filter(ss);
}
bool operator()(const SelectionStream& lh, const SelectionStream& rh) const
{
PREDICATE_RETURN(relevant(lh)
, relevant(rh));
PREDICATE_RETURN(lh.type_index == CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleStream
, rh.type_index == CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleStream);
// prefer external subs
PREDICATE_RETURN(STREAM_SOURCE_MASK(lh.source) == STREAM_SOURCE_DEMUX_SUB || STREAM_SOURCE_MASK(lh.source) == STREAM_SOURCE_TEXT
, STREAM_SOURCE_MASK(rh.source) == STREAM_SOURCE_DEMUX_SUB || STREAM_SOURCE_MASK(rh.source) == STREAM_SOURCE_TEXT);
if(!subson || original)
{
PREDICATE_RETURN(lh.flags & CDemuxStream::FLAG_FORCED && g_LangCodeExpander.CompareISO639Codes(lh.language, audiolang)
, rh.flags & CDemuxStream::FLAG_FORCED && g_LangCodeExpander.CompareISO639Codes(rh.language, audiolang));
PREDICATE_RETURN(lh.flags & CDemuxStream::FLAG_FORCED
, rh.flags & CDemuxStream::FLAG_FORCED);
}
std::string subtitle_language = g_langInfo.GetSubtitleLanguage();
if(!original)
{
PREDICATE_RETURN((STREAM_SOURCE_MASK(lh.source) == STREAM_SOURCE_DEMUX_SUB || STREAM_SOURCE_MASK(lh.source) == STREAM_SOURCE_TEXT) && g_LangCodeExpander.CompareISO639Codes(subtitle_language, lh.language)
, (STREAM_SOURCE_MASK(rh.source) == STREAM_SOURCE_DEMUX_SUB || STREAM_SOURCE_MASK(rh.source) == STREAM_SOURCE_TEXT) && g_LangCodeExpander.CompareISO639Codes(subtitle_language, rh.language));
}
if(!original)
{
PREDICATE_RETURN(g_LangCodeExpander.CompareISO639Codes(subtitle_language, lh.language)
, g_LangCodeExpander.CompareISO639Codes(subtitle_language, rh.language));
bool hearingimp = CSettings::GetInstance().GetBool(CSettings::SETTING_ACCESSIBILITY_SUBHEARING);
PREDICATE_RETURN(!hearingimp ? !(lh.flags & CDemuxStream::FLAG_HEARING_IMPAIRED) : lh.flags & CDemuxStream::FLAG_HEARING_IMPAIRED
, !hearingimp ? !(rh.flags & CDemuxStream::FLAG_HEARING_IMPAIRED) : rh.flags & CDemuxStream::FLAG_HEARING_IMPAIRED);
}
PREDICATE_RETURN(lh.flags & CDemuxStream::FLAG_DEFAULT
, rh.flags & CDemuxStream::FLAG_DEFAULT);
return false;
}
};
static bool PredicateVideoPriority(const SelectionStream& lh, const SelectionStream& rh)
{
PREDICATE_RETURN(lh.type_index == CMediaSettings::GetInstance().GetCurrentVideoSettings().m_VideoStream
, rh.type_index == CMediaSettings::GetInstance().GetCurrentVideoSettings().m_VideoStream);
PREDICATE_RETURN(lh.flags & CDemuxStream::FLAG_DEFAULT
, rh.flags & CDemuxStream::FLAG_DEFAULT);
return false;
}
bool CSelectionStreams::Get(StreamType type, CDemuxStream::EFlags flag, SelectionStream& out)
{
CSingleLock lock(m_section);
for(size_t i=0;i<m_Streams.size();i++)
{
if(m_Streams[i].type != type)
continue;
if((m_Streams[i].flags & flag) != flag)
continue;
out = m_Streams[i];
return true;
}
return false;
}
int CSelectionStreams::IndexOf(StreamType type, int source, int id) const
{
CSingleLock lock(m_section);
int count = -1;
for(size_t i=0;i<m_Streams.size();i++)
{
if(type && m_Streams[i].type != type)
continue;
count++;
if(source && m_Streams[i].source != source)
continue;
if(id < 0)
continue;
if(m_Streams[i].id == id)
return count;
}
if(id < 0)
return count;
else
return -1;
}
int CSelectionStreams::IndexOf(StreamType type, const CVideoPlayer& p) const
{
if (p.m_pInputStream && p.m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
{
int id = -1;
if(type == STREAM_AUDIO)
id = ((CDVDInputStreamNavigator*)p.m_pInputStream)->GetActiveAudioStream();
else if (type == STREAM_VIDEO)
id = ((CDVDInputStreamNavigator*)p.m_pInputStream)->GetActiveAngle();
else if(type == STREAM_SUBTITLE)
id = ((CDVDInputStreamNavigator*)p.m_pInputStream)->GetActiveSubtitleStream();
return IndexOf(type, STREAM_SOURCE_NAV, id);
}
if(type == STREAM_AUDIO)
return IndexOf(type, p.m_CurrentAudio.source, p.m_CurrentAudio.id);
else if(type == STREAM_VIDEO)
return IndexOf(type, p.m_CurrentVideo.source, p.m_CurrentVideo.id);
else if(type == STREAM_SUBTITLE)
return IndexOf(type, p.m_CurrentSubtitle.source, p.m_CurrentSubtitle.id);
else if(type == STREAM_TELETEXT)
return IndexOf(type, p.m_CurrentTeletext.source, p.m_CurrentTeletext.id);
else if(type == STREAM_RADIO_RDS)
return IndexOf(type, p.m_CurrentRadioRDS.source, p.m_CurrentRadioRDS.id);
return -1;
}
int CSelectionStreams::Source(StreamSource source, std::string filename)
{
CSingleLock lock(m_section);
int index = source - 1;
for(size_t i=0;i<m_Streams.size();i++)
{
SelectionStream &s = m_Streams[i];
if(STREAM_SOURCE_MASK(s.source) != source)
continue;
// if it already exists, return same
if(s.filename == filename)
return s.source;
if(index < s.source)
index = s.source;
}
// return next index
return index + 1;
}
void CSelectionStreams::Update(SelectionStream& s)
{
CSingleLock lock(m_section);
int index = IndexOf(s.type, s.source, s.id);
if(index >= 0)
{
SelectionStream& o = Get(s.type, index);
s.type_index = o.type_index;
o = s;
}
else
{
s.type_index = Count(s.type);
m_Streams.push_back(s);
}
}
void CSelectionStreams::Update(CDVDInputStream* input, CDVDDemux* demuxer, std::string filename2)
{
if(input && input->IsStreamType(DVDSTREAM_TYPE_DVD))
{
CDVDInputStreamNavigator* nav = (CDVDInputStreamNavigator*)input;
std::string filename = nav->GetFileName();
int source = Source(STREAM_SOURCE_NAV, filename);
int count;
count = nav->GetAudioStreamCount();
for(int i=0;i<count;i++)
{
SelectionStream s;
s.source = source;
s.type = STREAM_AUDIO;
s.id = i;
s.flags = CDemuxStream::FLAG_NONE;
s.filename = filename;
DVDNavAudioStreamInfo info = nav->GetAudioStreamInfo(i);
s.name = info.name;
s.language = g_LangCodeExpander.ConvertToISO6392T(info.language);
s.channels = info.channels;
Update(s);
}
count = nav->GetSubTitleStreamCount();
for(int i=0;i<count;i++)
{
SelectionStream s;
s.source = source;
s.type = STREAM_SUBTITLE;
s.id = i;
s.filename = filename;
s.channels = 0;
DVDNavSubtitleStreamInfo info = nav->GetSubtitleStreamInfo(i);
s.name = info.name;
s.flags = info.flags;
s.language = g_LangCodeExpander.ConvertToISO6392T(info.language);
Update(s);
}
DVDNavVideoStreamInfo info = nav->GetVideoStreamInfo();
for (int i = 1; i <= info.angles; i++)
{
SelectionStream s;
s.source = source;
s.type = STREAM_VIDEO;
s.id = i;
s.flags = CDemuxStream::FLAG_NONE;
s.filename = filename;
s.channels = 0;
s.aspect_ratio = info.aspectRatio;
s.width = (int)info.width;
s.height = (int)info.height;
s.codec = info.codec;
s.name = StringUtils::Format("%s %i", g_localizeStrings.Get(38032).c_str(), i);
Update(s);
}
}
else if(demuxer)
{
std::string filename = demuxer->GetFileName();
int count = demuxer->GetNrOfStreams();
int source;
if(input) /* hack to know this is sub decoder */
source = Source(STREAM_SOURCE_DEMUX, filename);
else if (!filename2.empty())
source = Source(STREAM_SOURCE_DEMUX_SUB, filename);
else
source = Source(STREAM_SOURCE_VIDEOMUX, filename);
for(int i=0;i<count;i++)
{
CDemuxStream* stream = demuxer->GetStream(i);
/* skip streams with no type */
if (stream->type == STREAM_NONE)
continue;
/* make sure stream is marked with right source */
stream->source = source;
SelectionStream s;
s.source = source;
s.type = stream->type;
s.id = stream->iId;
s.language = g_LangCodeExpander.ConvertToISO6392T(stream->language);
s.flags = stream->flags;
s.filename = demuxer->GetFileName();
s.filename2 = filename2;
s.name = stream->GetStreamName();
s.codec = demuxer->GetStreamCodecName(stream->iId);
s.channels = 0; // Default to 0. Overwrite if STREAM_AUDIO below.
if(stream->type == STREAM_VIDEO)
{
s.width = ((CDemuxStreamVideo*)stream)->iWidth;
s.height = ((CDemuxStreamVideo*)stream)->iHeight;
}
if(stream->type == STREAM_AUDIO)
{
std::string type;
type = ((CDemuxStreamAudio*)stream)->GetStreamType();
if(type.length() > 0)
{
if(s.name.length() > 0)
s.name += " - ";
s.name += type;
}
s.channels = ((CDemuxStreamAudio*)stream)->iChannels;
}
Update(s);
}
}
g_dataCacheCore.SignalAudioInfoChange();
g_dataCacheCore.SignalVideoInfoChange();
}
int CSelectionStreams::CountSource(StreamType type, StreamSource source) const
{
CSingleLock lock(m_section);
int count = 0;
for(size_t i=0;i<m_Streams.size();i++)
{
if(type && m_Streams[i].type != type)
continue;
if (source && m_Streams[i].source != source)
continue;
count++;
continue;
}
return count;
}
void CVideoPlayer::CreatePlayers()
{
#ifdef HAS_OMXPLAYER
bool omx_suitable = !OMXPlayerUnsuitable(m_HasVideo, m_HasAudio, m_pDemuxer, m_pInputStream, m_SelectionStreams);
if (m_omxplayer_mode != omx_suitable)
{
DestroyPlayers();
m_omxplayer_mode = omx_suitable;
}
#endif
if (m_players_created)
return;
if (m_omxplayer_mode)
{
#ifdef HAS_OMXPLAYER
m_VideoPlayerVideo = new OMXPlayerVideo(&m_OmxPlayerState.av_clock, &m_overlayContainer, m_messenger, m_renderManager);
m_VideoPlayerAudio = new OMXPlayerAudio(&m_OmxPlayerState.av_clock, m_messenger);
#endif
}
else
{
m_VideoPlayerVideo = new CVideoPlayerVideo(&m_clock, &m_overlayContainer, m_messenger, m_renderManager);
m_VideoPlayerAudio = new CVideoPlayerAudio(&m_clock, m_messenger);
}
m_VideoPlayerSubtitle = new CVideoPlayerSubtitle(&m_overlayContainer);
m_VideoPlayerTeletext = new CDVDTeletextData();
m_VideoPlayerRadioRDS = new CDVDRadioRDSData();
m_players_created = true;
}
void CVideoPlayer::DestroyPlayers()
{
if (!m_players_created)
return;
delete m_VideoPlayerVideo;
delete m_VideoPlayerAudio;
delete m_VideoPlayerSubtitle;
delete m_VideoPlayerTeletext;
delete m_VideoPlayerRadioRDS;
m_players_created = false;
}
CVideoPlayer::CVideoPlayer(IPlayerCallback& callback)
: IPlayer(callback),
CThread("VideoPlayer"),
m_CurrentAudio(STREAM_AUDIO, VideoPlayer_AUDIO),
m_CurrentVideo(STREAM_VIDEO, VideoPlayer_VIDEO),
m_CurrentSubtitle(STREAM_SUBTITLE, VideoPlayer_SUBTITLE),
m_CurrentTeletext(STREAM_TELETEXT, VideoPlayer_TELETEXT),
m_CurrentRadioRDS(STREAM_RADIO_RDS, VideoPlayer_RDS),
m_messenger("player"),
m_renderManager(m_clock, this),
m_ready(true)
{
m_players_created = false;
m_pDemuxer = NULL;
m_pSubtitleDemuxer = NULL;
m_pCCDemuxer = NULL;
m_pInputStream = NULL;
m_dvd.Clear();
m_State.Clear();
m_EdlAutoSkipMarkers.Clear();
m_UpdateApplication = 0;
m_bAbortRequest = false;
m_errorCount = 0;
m_offset_pts = 0.0;
m_playSpeed = DVD_PLAYSPEED_NORMAL;
m_streamPlayerSpeed = DVD_PLAYSPEED_NORMAL;
m_caching = CACHESTATE_DONE;
m_HasVideo = false;
m_HasAudio = false;
memset(&m_SpeedState, 0, sizeof(m_SpeedState));
// omxplayer variables
m_OmxPlayerState.last_check_time = 0.0;
m_OmxPlayerState.stamp = 0.0;
m_OmxPlayerState.bOmxWaitVideo = false;
m_OmxPlayerState.bOmxWaitAudio = false;
m_OmxPlayerState.bOmxSentEOFs = false;
m_OmxPlayerState.threshold = 0.2f;
m_OmxPlayerState.current_deinterlace = CMediaSettings::GetInstance().GetCurrentVideoSettings().m_DeinterlaceMode;
m_OmxPlayerState.interlace_method = VS_INTERLACEMETHOD_MAX;
#ifdef HAS_OMXPLAYER
m_omxplayer_mode = CSettings::GetInstance().GetBool(CSettings::SETTING_VIDEOPLAYER_USEOMXPLAYER);
#else
m_omxplayer_mode = false;
#endif
CreatePlayers();
m_displayLost = false;
g_Windowing.Register(this);
}
CVideoPlayer::~CVideoPlayer()
{
g_Windowing.Unregister(this);
CloseFile();
DestroyPlayers();
}
bool CVideoPlayer::OpenFile(const CFileItem& file, const CPlayerOptions &options)
{
CLog::Log(LOGNOTICE, "VideoPlayer: Opening: %s", CURL::GetRedacted(file.GetPath()).c_str());
// if playing a file close it first
// this has to be changed so we won't have to close it.
if(IsRunning())
CloseFile();
m_bAbortRequest = false;
SetPlaySpeed(DVD_PLAYSPEED_NORMAL);
m_State.Clear();
memset(&m_SpeedState, 0, sizeof(m_SpeedState));
m_UpdateApplication = 0;
m_offset_pts = 0;
m_CurrentAudio.lastdts = DVD_NOPTS_VALUE;
m_CurrentVideo.lastdts = DVD_NOPTS_VALUE;
m_PlayerOptions = options;
m_item = file;
m_ready.Reset();
m_renderManager.PreInit();
Create();
// wait for the ready event
CGUIDialogBusy::WaitOnEvent(m_ready, g_advancedSettings.m_videoBusyDialogDelay_ms, false);
// Playback might have been stopped due to some error
if (m_bStop || m_bAbortRequest)
return false;
return true;
}
bool CVideoPlayer::CloseFile(bool reopen)
{
CLog::Log(LOGNOTICE, "CVideoPlayer::CloseFile()");
// set the abort request so that other threads can finish up
m_bAbortRequest = true;
// tell demuxer to abort
if(m_pDemuxer)
m_pDemuxer->Abort();
if(m_pSubtitleDemuxer)
m_pSubtitleDemuxer->Abort();
if(m_pInputStream)
m_pInputStream->Abort();
CLog::Log(LOGNOTICE, "VideoPlayer: waiting for threads to exit");
// wait for the main thread to finish up
// since this main thread cleans up all other resources and threads
// we are done after the StopThread call
StopThread();
m_Edl.Clear();
m_EdlAutoSkipMarkers.Clear();
m_HasVideo = false;
m_HasAudio = false;
CLog::Log(LOGNOTICE, "VideoPlayer: finished waiting");
m_renderManager.UnInit();
return true;
}
bool CVideoPlayer::IsPlaying() const
{
return !m_bStop;
}
void CVideoPlayer::OnStartup()
{
m_CurrentVideo.Clear();
m_CurrentAudio.Clear();
m_CurrentSubtitle.Clear();
m_CurrentTeletext.Clear();
m_CurrentRadioRDS.Clear();
m_messenger.Init();
CUtil::ClearTempFonts();
}
bool CVideoPlayer::OpenInputStream()
{
if(m_pInputStream)
SAFE_DELETE(m_pInputStream);
CLog::Log(LOGNOTICE, "Creating InputStream");
// correct the filename if needed
std::string filename(m_item.GetPath());
if (URIUtils::IsProtocol(filename, "dvd") ||
StringUtils::EqualsNoCase(filename, "iso9660://video_ts/video_ts.ifo"))
{
m_item.SetPath(g_mediaManager.TranslateDevicePath(""));
}
m_pInputStream = CDVDFactoryInputStream::CreateInputStream(this, m_item);
if(m_pInputStream == NULL)
{
CLog::Log(LOGERROR, "CVideoPlayer::OpenInputStream - unable to create input stream for [%s]", m_item.GetPath().c_str());
return false;
}
if (!m_pInputStream->Open())
{
CLog::Log(LOGERROR, "CVideoPlayer::OpenInputStream - error opening [%s]", m_item.GetPath().c_str());
return false;
}
// find any available external subtitles for non dvd files
if (!m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD)
&& !m_pInputStream->IsStreamType(DVDSTREAM_TYPE_PVRMANAGER)
&& !m_pInputStream->IsStreamType(DVDSTREAM_TYPE_TV))
{
// find any available external subtitles
std::vector<std::string> filenames;
CUtil::ScanForExternalSubtitles(m_item.GetPath(), filenames);
// load any subtitles from file item
std::string key("subtitle:1");
for(unsigned s = 1; m_item.HasProperty(key); key = StringUtils::Format("subtitle:%u", ++s))
filenames.push_back(m_item.GetProperty(key).asString());
for(unsigned int i=0;i<filenames.size();i++)
{
// if vobsub subtitle:
if (URIUtils::HasExtension(filenames[i], ".idx"))
{
std::string strSubFile;
if ( CUtil::FindVobSubPair( filenames, filenames[i], strSubFile ) )
AddSubtitleFile(filenames[i], strSubFile);
}
else
{
if ( !CUtil::IsVobSub(filenames, filenames[i] ) )
{
AddSubtitleFile(filenames[i]);
}
}
} // end loop over all subtitle files
CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleCached = true;
}
SetAVDelay(CMediaSettings::GetInstance().GetCurrentVideoSettings().m_AudioDelay);
SetSubTitleDelay(CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleDelay);
m_clock.Reset();
m_dvd.Clear();
m_errorCount = 0;
m_ChannelEntryTimeOut.SetInfinite();
return true;
}
bool CVideoPlayer::OpenDemuxStream()
{
if(m_pDemuxer)
SAFE_DELETE(m_pDemuxer);
CLog::Log(LOGNOTICE, "Creating Demuxer");
int attempts = 10;
while(!m_bStop && attempts-- > 0)
{
m_pDemuxer = CDVDFactoryDemuxer::CreateDemuxer(m_pInputStream);
if(!m_pDemuxer && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_PVRMANAGER))
{
continue;
}
else if(!m_pDemuxer && m_pInputStream->NextStream() != CDVDInputStream::NEXTSTREAM_NONE)
{
CLog::Log(LOGDEBUG, "%s - New stream available from input, retry open", __FUNCTION__);
continue;
}
break;
}
if(!m_pDemuxer)
{
CLog::Log(LOGERROR, "%s - Error creating demuxer", __FUNCTION__);
return false;
}
m_SelectionStreams.Clear(STREAM_NONE, STREAM_SOURCE_DEMUX);
m_SelectionStreams.Clear(STREAM_NONE, STREAM_SOURCE_NAV);
m_SelectionStreams.Update(m_pInputStream, m_pDemuxer);
int64_t len = m_pInputStream->GetLength();
int64_t tim = m_pDemuxer->GetStreamLength();
if(len > 0 && tim > 0)
m_pInputStream->SetReadRate((unsigned int) (len * 1000 / tim));
m_offset_pts = 0;
return true;
}
void CVideoPlayer::OpenDefaultStreams(bool reset)
{
// if input stream dictate, we will open later
if(m_dvd.iSelectedAudioStream >= 0
|| m_dvd.iSelectedSPUStream >= 0)
return;
SelectionStreams streams;
bool valid;
// open video stream
streams = m_SelectionStreams.Get(STREAM_VIDEO, PredicateVideoPriority);
valid = false;
for(SelectionStreams::iterator it = streams.begin(); it != streams.end() && !valid; ++it)
{
if(OpenStream(m_CurrentVideo, it->id, it->source, reset))
valid = true;
}
if(!valid)
CloseStream(m_CurrentVideo, true);
// open audio stream
if(m_PlayerOptions.video_only)
streams.clear();
else
streams = m_SelectionStreams.Get(STREAM_AUDIO, PredicateAudioPriority);
valid = false;
for(SelectionStreams::iterator it = streams.begin(); it != streams.end() && !valid; ++it)
{
if(OpenStream(m_CurrentAudio, it->id, it->source, reset))
valid = true;
}
if(!valid)
CloseStream(m_CurrentAudio, true);
// enable or disable subtitles
bool visible = CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleOn;
// open subtitle stream
SelectionStream as = m_SelectionStreams.Get(STREAM_AUDIO, GetAudioStream());
PredicateSubtitlePriority psp(as.language);
streams = m_SelectionStreams.Get(STREAM_SUBTITLE, psp);
valid = false;
CloseStream(m_CurrentSubtitle, false);
for(SelectionStreams::iterator it = streams.begin(); it != streams.end() && !valid; ++it)
{
if(OpenStream(m_CurrentSubtitle, it->id, it->source))
{
valid = true;
if(!psp.relevant(*it))
visible = false;
else if(it->flags & CDemuxStream::FLAG_FORCED)
visible = true;
}
}
if(!valid)
CloseStream(m_CurrentSubtitle, false);
if (!dynamic_cast<CDVDInputStreamNavigator*>(m_pInputStream) || m_PlayerOptions.state.empty())
SetSubtitleVisibleInternal(visible); // only set subtitle visibility if state not stored by dvd navigator, because navigator will restore it (if visible)
// open teletext stream
streams = m_SelectionStreams.Get(STREAM_TELETEXT);
valid = false;
for(SelectionStreams::iterator it = streams.begin(); it != streams.end() && !valid; ++it)
{
if(OpenStream(m_CurrentTeletext, it->id, it->source))
valid = true;
}
if(!valid)
CloseStream(m_CurrentTeletext, false);
// open RDS stream
streams = m_SelectionStreams.Get(STREAM_RADIO_RDS);
valid = false;
for(SelectionStreams::iterator it = streams.begin(); it != streams.end() && !valid; ++it)
{
if(OpenStream(m_CurrentRadioRDS, it->id, it->source))
valid = true;
}
if(!valid)
CloseStream(m_CurrentRadioRDS, false);
}
bool CVideoPlayer::ReadPacket(DemuxPacket*& packet, CDemuxStream*& stream)
{
// check if we should read from subtitle demuxer
if( m_pSubtitleDemuxer && m_VideoPlayerSubtitle->AcceptsData() )
{
packet = m_pSubtitleDemuxer->Read();
if(packet)
{
UpdateCorrection(packet, m_offset_pts);
if(packet->iStreamId < 0)
return true;
stream = m_pSubtitleDemuxer->GetStream(packet->iStreamId);
if (!stream)
{
CLog::Log(LOGERROR, "%s - Error demux packet doesn't belong to a valid stream", __FUNCTION__);
return false;
}
if(stream->source == STREAM_SOURCE_NONE)
{
m_SelectionStreams.Clear(STREAM_NONE, STREAM_SOURCE_DEMUX_SUB);
m_SelectionStreams.Update(NULL, m_pSubtitleDemuxer);
}
return true;
}
}
if (m_omxplayer_mode)
{
// reset eos state when we get a packet (e.g. for case of seek after eos)
if (packet && stream)
{
m_OmxPlayerState.bOmxWaitVideo = false;
m_OmxPlayerState.bOmxWaitAudio = false;
m_OmxPlayerState.bOmxSentEOFs = false;
}
}
// read a data frame from stream.
if(m_pDemuxer)
packet = m_pDemuxer->Read();
if(packet)
{
// stream changed, update and open defaults
if(packet->iStreamId == DMX_SPECIALID_STREAMCHANGE)
{
m_SelectionStreams.Clear(STREAM_NONE, STREAM_SOURCE_DEMUX);
m_SelectionStreams.Update(m_pInputStream, m_pDemuxer);
OpenDefaultStreams(false);
// reevaluate HasVideo/Audio, we may have switched from/to a radio channel
if(m_CurrentVideo.id < 0)
m_HasVideo = false;
if(m_CurrentAudio.id < 0)
m_HasAudio = false;
return true;
}
UpdateCorrection(packet, m_offset_pts);
if(packet->iStreamId < 0)
return true;
if(m_pDemuxer)
{
stream = m_pDemuxer->GetStream(packet->iStreamId);
if (!stream)
{
CLog::Log(LOGERROR, "%s - Error demux packet doesn't belong to a valid stream", __FUNCTION__);
return false;
}
if(stream->source == STREAM_SOURCE_NONE)
{
m_SelectionStreams.Clear(STREAM_NONE, STREAM_SOURCE_DEMUX);
m_SelectionStreams.Update(m_pInputStream, m_pDemuxer);
}
}
return true;
}
return false;
}
bool CVideoPlayer::IsValidStream(CCurrentStream& stream)
{
if(stream.id<0)
return true; // we consider non selected as valid
int source = STREAM_SOURCE_MASK(stream.source);
if(source == STREAM_SOURCE_TEXT)
return true;
if(source == STREAM_SOURCE_DEMUX_SUB)
{
CDemuxStream* st = m_pSubtitleDemuxer->GetStream(stream.id);
if(st == NULL || st->disabled)
return false;
if(st->type != stream.type)
return false;
return true;
}
if(source == STREAM_SOURCE_DEMUX)
{
CDemuxStream* st = m_pDemuxer->GetStream(stream.id);
if(st == NULL || st->disabled)
return false;
if(st->type != stream.type)
return false;
if (m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
{
if(stream.type == STREAM_AUDIO && st->iPhysicalId != m_dvd.iSelectedAudioStream)
return false;
if(stream.type == STREAM_SUBTITLE && st->iPhysicalId != m_dvd.iSelectedSPUStream)
return false;
}
return true;
}
if (source == STREAM_SOURCE_VIDEOMUX)
{
CDemuxStream* st = m_pCCDemuxer->GetStream(stream.id);
if (st == NULL || st->disabled)
return false;
if (st->type != stream.type)
return false;
return true;
}
return false;
}
bool CVideoPlayer::IsBetterStream(CCurrentStream& current, CDemuxStream* stream)
{
// Do not reopen non-video streams if we're in video-only mode
if(m_PlayerOptions.video_only && current.type != STREAM_VIDEO)
return false;
if(stream->disabled)
return false;
if (m_pInputStream && ( m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD)
|| m_pInputStream->IsStreamType(DVDSTREAM_TYPE_BLURAY) ) )
{
int source_type;
source_type = STREAM_SOURCE_MASK(current.source);
if(source_type != STREAM_SOURCE_DEMUX
&& source_type != STREAM_SOURCE_NONE)
return false;
source_type = STREAM_SOURCE_MASK(stream->source);
if(source_type != STREAM_SOURCE_DEMUX
|| stream->type != current.type
|| stream->iId == current.id)
return false;
if(current.type == STREAM_AUDIO && stream->iPhysicalId == m_dvd.iSelectedAudioStream)
return true;
if(current.type == STREAM_SUBTITLE && stream->iPhysicalId == m_dvd.iSelectedSPUStream)
return true;
if(current.type == STREAM_VIDEO && current.id < 0)
return true;
}
else
{
if(stream->source == current.source
&& stream->iId == current.id)
return false;
if(stream->type != current.type)
return false;
if(current.type == STREAM_SUBTITLE)
return false;
if(current.id < 0)
return true;
}
return false;
}
void CVideoPlayer::CheckBetterStream(CCurrentStream& current, CDemuxStream* stream)
{
IDVDStreamPlayer* player = GetStreamPlayer(current.player);
if (!IsValidStream(current) && (player == NULL || player->IsStalled()))
CloseStream(current, true);
if (IsBetterStream(current, stream))
OpenStream(current, stream->iId, stream->source);
}
void CVideoPlayer::Process()
{
if (!OpenInputStream())
{
m_bAbortRequest = true;
return;
}
if (CDVDInputStream::IMenus* ptr = dynamic_cast<CDVDInputStream::IMenus*>(m_pInputStream))
{
CLog::Log(LOGNOTICE, "VideoPlayer: playing a file with menu's");
if(dynamic_cast<CDVDInputStreamNavigator*>(m_pInputStream))
m_PlayerOptions.starttime = 0;
if(!m_PlayerOptions.state.empty())
ptr->SetState(m_PlayerOptions.state);
else if(CDVDInputStreamNavigator* nav = dynamic_cast<CDVDInputStreamNavigator*>(m_pInputStream))
nav->EnableSubtitleStream(CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleOn);
CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleCached = true;
}
if(!OpenDemuxStream())
{
m_bAbortRequest = true;
return;
}
// give players a chance to reconsider now codecs are known
CreatePlayers();
// allow renderer to switch to fullscreen if requested
m_VideoPlayerVideo->EnableFullscreen(m_PlayerOptions.fullscreen);
if (m_omxplayer_mode)
{
if (!m_OmxPlayerState.av_clock.OMXInitialize(&m_clock))
m_bAbortRequest = true;
if (CSettings::GetInstance().GetInt(CSettings::SETTING_VIDEOPLAYER_ADJUSTREFRESHRATE) != ADJUST_REFRESHRATE_OFF)
m_OmxPlayerState.av_clock.HDMIClockSync();
m_OmxPlayerState.av_clock.OMXStateIdle();
m_OmxPlayerState.av_clock.OMXStateExecute();
m_OmxPlayerState.av_clock.OMXStop();
m_OmxPlayerState.av_clock.OMXPause();
}
OpenDefaultStreams();
// look for any EDL files
m_Edl.Clear();
m_EdlAutoSkipMarkers.Clear();
if (m_CurrentVideo.id >= 0 && m_CurrentVideo.hint.fpsrate > 0 && m_CurrentVideo.hint.fpsscale > 0)
{
float fFramesPerSecond = (float)m_CurrentVideo.hint.fpsrate / (float)m_CurrentVideo.hint.fpsscale;
m_Edl.ReadEditDecisionLists(m_item.GetPath(), fFramesPerSecond, m_CurrentVideo.hint.height);
}
/*
* Check to see if the demuxer should start at something other than time 0. This will be the case
* if there was a start time specified as part of the "Start from where last stopped" (aka
* auto-resume) feature or if there is an EDL cut or commercial break that starts at time 0.
*/
CEdl::Cut cut;
int starttime = 0;
if(m_PlayerOptions.starttime > 0 || m_PlayerOptions.startpercent > 0)
{
if (m_PlayerOptions.startpercent > 0 && m_pDemuxer)
{
int playerStartTime = (int)( ( (float) m_pDemuxer->GetStreamLength() ) * ( m_PlayerOptions.startpercent/(float)100 ) );
starttime = m_Edl.RestoreCutTime(playerStartTime);
}
else
{
starttime = m_Edl.RestoreCutTime(m_PlayerOptions.starttime * 1000); // s to ms
}
CLog::Log(LOGDEBUG, "%s - Start position set to last stopped position: %d", __FUNCTION__, starttime);
}
else if(m_Edl.InCut(0, &cut)
&& (cut.action == CEdl::CUT || cut.action == CEdl::COMM_BREAK))
{
starttime = cut.end;
CLog::Log(LOGDEBUG, "%s - Start position set to end of first cut or commercial break: %d", __FUNCTION__, starttime);
if(cut.action == CEdl::COMM_BREAK)
{
/*
* Setup auto skip markers as if the commercial break had been skipped using standard
* detection.
*/
m_EdlAutoSkipMarkers.commbreak_start = cut.start;
m_EdlAutoSkipMarkers.commbreak_end = cut.end;
m_EdlAutoSkipMarkers.seek_to_start = true;
}
}
if(starttime > 0)
{
double startpts = DVD_NOPTS_VALUE;
if(m_pDemuxer)
{
if (m_pDemuxer->SeekTime(starttime, false, &startpts))
CLog::Log(LOGDEBUG, "%s - starting demuxer from: %d", __FUNCTION__, starttime);
else
CLog::Log(LOGDEBUG, "%s - failed to start demuxing from: %d", __FUNCTION__, starttime);
}
if(m_pSubtitleDemuxer)
{
if(m_pSubtitleDemuxer->SeekTime(starttime, false, &startpts))
CLog::Log(LOGDEBUG, "%s - starting subtitle demuxer from: %d", __FUNCTION__, starttime);
else
CLog::Log(LOGDEBUG, "%s - failed to start subtitle demuxing from: %d", __FUNCTION__, starttime);
}
}
// make sure application know our info
UpdateApplication(0);
UpdatePlayState(0);
if(m_PlayerOptions.identify == false)
m_callback.OnPlayBackStarted();
// we are done initializing now, set the readyevent
m_ready.Set();
SetCaching(CACHESTATE_FLUSH);
while (!m_bAbortRequest)
{
#ifdef HAS_OMXPLAYER
if (m_omxplayer_mode && OMXDoProcessing(m_OmxPlayerState, m_playSpeed, m_VideoPlayerVideo, m_VideoPlayerAudio, m_CurrentAudio, m_CurrentVideo, m_HasVideo, m_HasAudio, m_renderManager))
{
CloseStream(m_CurrentVideo, false);
OpenStream(m_CurrentVideo, m_CurrentVideo.id, m_CurrentVideo.source);
if (m_State.canseek)
m_messenger.Put(new CDVDMsgPlayerSeek(GetTime(), true, true, true, true, true));
}
#endif
// check display lost
if (m_displayLost)
{
Sleep(50);
continue;
}
// handle messages send to this thread, like seek or demuxer reset requests
HandleMessages();
if(m_bAbortRequest)
break;
// should we open a new input stream?
if(!m_pInputStream)
{
if (OpenInputStream() == false)
{
m_bAbortRequest = true;
break;
}
}
// should we open a new demuxer?
if(!m_pDemuxer)
{
if (m_pInputStream->NextStream() == CDVDInputStream::NEXTSTREAM_NONE)
break;
if (m_pInputStream->IsEOF())
break;
if (OpenDemuxStream() == false)
{
m_bAbortRequest = true;
break;
}
// on channel switch we don't want to close stream players at this
// time. we'll get the stream change event later
if (!m_pInputStream->IsStreamType(DVDSTREAM_TYPE_PVRMANAGER) ||
!m_SelectionStreams.m_Streams.empty())
OpenDefaultStreams();
// never allow first frames after open to be skipped
if( m_VideoPlayerVideo->IsInited() )
m_VideoPlayerVideo->SendMessage(new CDVDMsg(CDVDMsg::VIDEO_NOSKIP));
UpdateApplication(0);
UpdatePlayState(0);
}
// handle eventual seeks due to playspeed
HandlePlaySpeed();
// update player state
UpdatePlayState(200);
// update application with our state
UpdateApplication(1000);
// make sure we run subtitle process here
m_VideoPlayerSubtitle->Process(m_clock.GetClock() + m_State.time_offset - m_VideoPlayerVideo->GetSubtitleDelay(), m_State.time_offset);
if (CheckDelayedChannelEntry())
continue;
// if the queues are full, no need to read more
if ((!m_VideoPlayerAudio->AcceptsData() && m_CurrentAudio.id >= 0) ||
(!m_VideoPlayerVideo->AcceptsData() && m_CurrentVideo.id >= 0))
{
if (m_pDemuxer && m_playSpeed == DVD_PLAYSPEED_PAUSE)
{
m_pDemuxer->SetSpeed(DVD_PLAYSPEED_PAUSE);
}
Sleep(10);
continue;
}
else if (m_pDemuxer)
{
m_pDemuxer->SetSpeed(m_playSpeed);
}
// always yield to players if they have data levels > 50 percent
if((m_VideoPlayerAudio->GetLevel() > 50 || m_CurrentAudio.id < 0)
&& (m_VideoPlayerVideo->GetLevel() > 50 || m_CurrentVideo.id < 0))
Sleep(0);
DemuxPacket* pPacket = NULL;
CDemuxStream *pStream = NULL;
ReadPacket(pPacket, pStream);
if (pPacket && !pStream)
{
/* probably a empty packet, just free it and move on */
CDVDDemuxUtils::FreeDemuxPacket(pPacket);
continue;
}
if (!pPacket)
{
// when paused, demuxer could be be returning empty
if (m_playSpeed == DVD_PLAYSPEED_PAUSE)
continue;
// check for a still frame state
if (CDVDInputStream::IMenus* pStream = dynamic_cast<CDVDInputStream::IMenus*>(m_pInputStream))
{
// stills will be skipped
if(m_dvd.state == DVDSTATE_STILL)
{
if (m_dvd.iDVDStillTime > 0)
{
if ((XbmcThreads::SystemClockMillis() - m_dvd.iDVDStillStartTime) >= m_dvd.iDVDStillTime)
{
m_dvd.iDVDStillTime = 0;
m_dvd.iDVDStillStartTime = 0;
m_dvd.state = DVDSTATE_NORMAL;
pStream->SkipStill();
continue;
}
}
}
}
// if there is another stream available, reopen demuxer
CDVDInputStream::ENextStream next = m_pInputStream->NextStream();
if(next == CDVDInputStream::NEXTSTREAM_OPEN)
{
SAFE_DELETE(m_pDemuxer);
SetCaching(CACHESTATE_DONE);
CLog::Log(LOGNOTICE, "VideoPlayer: next stream, wait for old streams to be finished");
CloseStream(m_CurrentAudio, true);
CloseStream(m_CurrentVideo, true);
m_CurrentAudio.Clear();
m_CurrentVideo.Clear();
m_CurrentSubtitle.Clear();
continue;
}
// input stream asked us to just retry
if(next == CDVDInputStream::NEXTSTREAM_RETRY)
{
Sleep(100);
continue;
}
// make sure we tell all players to finish it's data
if (m_omxplayer_mode && !m_OmxPlayerState.bOmxSentEOFs)
{
if(m_CurrentAudio.inited)
m_OmxPlayerState.bOmxWaitAudio = true;
if(m_CurrentVideo.inited)
m_OmxPlayerState.bOmxWaitVideo = true;
m_OmxPlayerState.bOmxSentEOFs = true;
}
if(m_CurrentAudio.inited)
m_VideoPlayerAudio->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_EOF));
if(m_CurrentVideo.inited)
m_VideoPlayerVideo->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_EOF));
if(m_CurrentSubtitle.inited)
m_VideoPlayerSubtitle->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_EOF));
if(m_CurrentTeletext.inited)
m_VideoPlayerTeletext->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_EOF));
if(m_CurrentRadioRDS.inited)
m_VideoPlayerRadioRDS->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_EOF));
m_CurrentAudio.inited = false;
m_CurrentVideo.inited = false;
m_CurrentSubtitle.inited = false;
m_CurrentTeletext.inited = false;
m_CurrentRadioRDS.inited = false;
// if we are caching, start playing it again
SetCaching(CACHESTATE_DONE);
// while players are still playing, keep going to allow seekbacks
if(m_VideoPlayerAudio->HasData()
|| m_VideoPlayerVideo->HasData())
{
Sleep(100);
continue;
}
#ifdef HAS_OMXPLAYER
if (m_omxplayer_mode && OMXStillPlaying(m_OmxPlayerState.bOmxWaitVideo, m_OmxPlayerState.bOmxWaitAudio, m_VideoPlayerVideo->IsEOS(), m_VideoPlayerAudio->IsEOS()))
{
Sleep(100);
continue;
}
#endif
if (!m_pInputStream->IsEOF())
CLog::Log(LOGINFO, "%s - eof reading from demuxer", __FUNCTION__);
break;
}
// it's a valid data packet, reset error counter
m_errorCount = 0;
// see if we can find something better to play
CheckBetterStream(m_CurrentAudio, pStream);
CheckBetterStream(m_CurrentVideo, pStream);
CheckBetterStream(m_CurrentSubtitle, pStream);
CheckBetterStream(m_CurrentTeletext, pStream);
CheckBetterStream(m_CurrentRadioRDS, pStream);
// demux video stream
if (CSettings::GetInstance().GetBool(CSettings::SETTING_SUBTITLES_PARSECAPTIONS) && CheckIsCurrent(m_CurrentVideo, pStream, pPacket))
{
if (m_pCCDemuxer)
{
bool first = true;
while(!m_bAbortRequest)
{
DemuxPacket *pkt = m_pCCDemuxer->Read(first ? pPacket : NULL);
if (!pkt)
break;
first = false;
if (m_pCCDemuxer->GetNrOfStreams() != m_SelectionStreams.CountSource(STREAM_SUBTITLE, STREAM_SOURCE_VIDEOMUX))
{
m_SelectionStreams.Clear(STREAM_SUBTITLE, STREAM_SOURCE_VIDEOMUX);
m_SelectionStreams.Update(NULL, m_pCCDemuxer, "");
OpenDefaultStreams(false);
}
CDemuxStream *pSubStream = m_pCCDemuxer->GetStream(pkt->iStreamId);
if (pSubStream && m_CurrentSubtitle.id == pkt->iStreamId && m_CurrentSubtitle.source == STREAM_SOURCE_VIDEOMUX)
ProcessSubData(pSubStream, pkt);
else
CDVDDemuxUtils::FreeDemuxPacket(pkt);
}
}
}
if (IsInMenuInternal())
{
if (CDVDInputStream::IMenus* menu = dynamic_cast<CDVDInputStream::IMenus*>(m_pInputStream))
{
double correction = menu->GetTimeStampCorrection();
if (pPacket->dts > correction)
pPacket->dts -= correction;
if (pPacket->pts > correction)
pPacket->pts -= correction;
}
if (m_dvd.syncClock)
{
m_clock.Discontinuity(pPacket->dts);
m_dvd.syncClock = false;
}
}
// process the packet
ProcessPacket(pStream, pPacket);
// check if in a cut or commercial break that should be automatically skipped
CheckAutoSceneSkip();
// update the player info for streams
if (m_player_status_timer.IsTimePast())
{
m_player_status_timer.Set(500);
UpdateStreamInfos();
}
}
}
bool CVideoPlayer::CheckDelayedChannelEntry(void)
{
bool bReturn(false);
if (m_ChannelEntryTimeOut.IsTimePast())
{
CFileItem currentFile(g_application.CurrentFileItem());
CPVRChannelPtr currentChannel(currentFile.GetPVRChannelInfoTag());
if (currentChannel)
{
SwitchChannel(currentChannel);
bReturn = true;
}
m_ChannelEntryTimeOut.SetInfinite();
}
return bReturn;
}
bool CVideoPlayer::CheckIsCurrent(CCurrentStream& current, CDemuxStream* stream, DemuxPacket* pkg)
{
if(current.id == pkg->iStreamId
&& current.source == stream->source
&& current.type == stream->type)
return true;
else
return false;
}
void CVideoPlayer::ProcessPacket(CDemuxStream* pStream, DemuxPacket* pPacket)
{
// process packet if it belongs to selected stream.
// for dvd's don't allow automatic opening of streams*/
if (CheckIsCurrent(m_CurrentAudio, pStream, pPacket))
ProcessAudioData(pStream, pPacket);
else if (CheckIsCurrent(m_CurrentVideo, pStream, pPacket))
ProcessVideoData(pStream, pPacket);
else if (CheckIsCurrent(m_CurrentSubtitle, pStream, pPacket))
ProcessSubData(pStream, pPacket);
else if (CheckIsCurrent(m_CurrentTeletext, pStream, pPacket))
ProcessTeletextData(pStream, pPacket);
else if (CheckIsCurrent(m_CurrentRadioRDS, pStream, pPacket))
ProcessRadioRDSData(pStream, pPacket);
else
{
pStream->SetDiscard(AVDISCARD_ALL);
CDVDDemuxUtils::FreeDemuxPacket(pPacket); // free it since we won't do anything with it
}
}
void CVideoPlayer::CheckStreamChanges(CCurrentStream& current, CDemuxStream* stream)
{
if (current.stream != (void*)stream
|| current.changes != stream->changes)
{
/* check so that dmuxer hints or extra data hasn't changed */
/* if they have, reopen stream */
if (current.hint != CDVDStreamInfo(*stream, true))
OpenStream(current, stream->iId, stream->source );
current.stream = (void*)stream;
current.changes = stream->changes;
}
}
void CVideoPlayer::ProcessAudioData(CDemuxStream* pStream, DemuxPacket* pPacket)
{
CheckStreamChanges(m_CurrentAudio, pStream);
bool checkcont = CheckContinuity(m_CurrentAudio, pPacket);
UpdateTimestamps(m_CurrentAudio, pPacket);
if (checkcont && (m_CurrentAudio.avsync == CCurrentStream::AV_SYNC_CHECK))
m_CurrentAudio.avsync = CCurrentStream::AV_SYNC_NONE;
bool drop = false;
if (CheckPlayerInit(m_CurrentAudio))
drop = true;
/*
* If CheckSceneSkip() returns true then demux point is inside an EDL cut and the packets are dropped.
* If not inside a hard cut, but the demux point has reached an EDL mute section then trigger the
* AUDIO_SILENCE state. The AUDIO_SILENCE state is reverted as soon as the demux point is outside
* of any EDL section while EDL mute is still active.
*/
CEdl::Cut cut;
if (CheckSceneSkip(m_CurrentAudio))
drop = true;
else if (m_Edl.InCut(DVD_TIME_TO_MSEC(m_CurrentAudio.dts + m_offset_pts), &cut) && cut.action == CEdl::MUTE // Inside EDL mute
&& !m_EdlAutoSkipMarkers.mute) // Mute not already triggered
{
m_VideoPlayerAudio->SendMessage(new CDVDMsgBool(CDVDMsg::AUDIO_SILENCE, true));
m_EdlAutoSkipMarkers.mute = true;
}
else if (!m_Edl.InCut(DVD_TIME_TO_MSEC(m_CurrentAudio.dts + m_offset_pts), &cut) // Outside of any EDL
&& m_EdlAutoSkipMarkers.mute) // But the mute hasn't been removed yet
{
m_VideoPlayerAudio->SendMessage(new CDVDMsgBool(CDVDMsg::AUDIO_SILENCE, false));
m_EdlAutoSkipMarkers.mute = false;
}
m_VideoPlayerAudio->SendMessage(new CDVDMsgDemuxerPacket(pPacket, drop));
m_CurrentAudio.packets++;
}
void CVideoPlayer::ProcessVideoData(CDemuxStream* pStream, DemuxPacket* pPacket)
{
CheckStreamChanges(m_CurrentVideo, pStream);
bool checkcont = false;
if( pPacket->iSize != 4) //don't check the EOF_SEQUENCE of stillframes
{
checkcont = CheckContinuity(m_CurrentVideo, pPacket);
UpdateTimestamps(m_CurrentVideo, pPacket);
}
if (checkcont && (m_CurrentVideo.avsync == CCurrentStream::AV_SYNC_CHECK))
m_CurrentVideo.avsync = CCurrentStream::AV_SYNC_NONE;
bool drop = false;
if (CheckPlayerInit(m_CurrentVideo))
drop = true;
if (CheckSceneSkip(m_CurrentVideo))
drop = true;
m_VideoPlayerVideo->SendMessage(new CDVDMsgDemuxerPacket(pPacket, drop));
m_CurrentVideo.packets++;
}
void CVideoPlayer::ProcessSubData(CDemuxStream* pStream, DemuxPacket* pPacket)
{
CheckStreamChanges(m_CurrentSubtitle, pStream);
UpdateTimestamps(m_CurrentSubtitle, pPacket);
bool drop = false;
if (CheckPlayerInit(m_CurrentSubtitle))
drop = true;
if (CheckSceneSkip(m_CurrentSubtitle))
drop = true;
m_VideoPlayerSubtitle->SendMessage(new CDVDMsgDemuxerPacket(pPacket, drop));
if(m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
m_VideoPlayerSubtitle->UpdateOverlayInfo((CDVDInputStreamNavigator*)m_pInputStream, LIBDVDNAV_BUTTON_NORMAL);
}
void CVideoPlayer::ProcessTeletextData(CDemuxStream* pStream, DemuxPacket* pPacket)
{
CheckStreamChanges(m_CurrentTeletext, pStream);
UpdateTimestamps(m_CurrentTeletext, pPacket);
bool drop = false;
if (CheckPlayerInit(m_CurrentTeletext))
drop = true;
if (CheckSceneSkip(m_CurrentTeletext))
drop = true;
m_VideoPlayerTeletext->SendMessage(new CDVDMsgDemuxerPacket(pPacket, drop));
}
void CVideoPlayer::ProcessRadioRDSData(CDemuxStream* pStream, DemuxPacket* pPacket)
{
CheckStreamChanges(m_CurrentRadioRDS, pStream);
UpdateTimestamps(m_CurrentRadioRDS, pPacket);
bool drop = false;
if (CheckPlayerInit(m_CurrentRadioRDS))
drop = true;
if (CheckSceneSkip(m_CurrentRadioRDS))
drop = true;
m_VideoPlayerRadioRDS->SendMessage(new CDVDMsgDemuxerPacket(pPacket, drop));
}
bool CVideoPlayer::GetCachingTimes(double& level, double& delay, double& offset)
{
if(!m_pInputStream || !m_pDemuxer)
return false;
XFILE::SCacheStatus status;
if (!m_pInputStream->GetCacheStatus(&status))
return false;
int64_t cached = status.forward;
unsigned currate = status.currate;
unsigned maxrate = status.maxrate;
bool full = status.full;
int64_t length = m_pInputStream->GetLength();
int64_t remain = length - m_pInputStream->Seek(0, SEEK_CUR);
if(cached < 0 || length <= 0 || remain < 0)
return false;
double play_sbp = DVD_MSEC_TO_TIME(m_pDemuxer->GetStreamLength()) / length;
double queued = 1000.0 * GetQueueTime() / play_sbp;
delay = 0.0;
level = 0.0;
offset = (double)(cached + queued) / length;
if (currate == 0)
return true;
double cache_sbp = 1.1 * (double)DVD_TIME_BASE / currate; /* underestimate by 10 % */
double play_left = play_sbp * (remain + queued); /* time to play out all remaining bytes */
double cache_left = cache_sbp * (remain - cached); /* time to cache the remaining bytes */
double cache_need = std::max(0.0, remain - play_left / cache_sbp); /* bytes needed until play_left == cache_left */
delay = cache_left - play_left;
if (full && (currate < maxrate) )
{
CLog::Log(LOGDEBUG, "Readrate %u is too low with %u required", currate, maxrate);
level = -1.0; /* buffer is full & our read rate is too low */
}
else
level = (cached + queued) / (cache_need + queued);
return true;
}
void CVideoPlayer::HandlePlaySpeed()
{
bool isInMenu = IsInMenuInternal();
if (isInMenu && m_caching != CACHESTATE_DONE)
SetCaching(CACHESTATE_DONE);
if (m_caching == CACHESTATE_FULL)
{
double level, delay, offset;
if (GetCachingTimes(level, delay, offset))
{
if (level < 0.0)
{
CGUIDialogKaiToast::QueueNotification(g_localizeStrings.Get(21454), g_localizeStrings.Get(21455));
SetCaching(CACHESTATE_INIT);
}
if (level >= 1.0)
SetCaching(CACHESTATE_INIT);
}
else
{
if ((!m_VideoPlayerAudio->AcceptsData() && m_CurrentAudio.id >= 0) ||
(!m_VideoPlayerVideo->AcceptsData() && m_CurrentVideo.id >= 0))
SetCaching(CACHESTATE_INIT);
}
}
if (m_caching == CACHESTATE_INIT)
{
// if all enabled streams have been inited we are done
if ((m_CurrentVideo.id >= 0 || m_CurrentAudio.id >= 0) &&
(m_CurrentVideo.id < 0 || m_CurrentVideo.syncState != IDVDStreamPlayer::SYNC_STARTING) &&
(m_CurrentAudio.id < 0 || m_CurrentAudio.syncState != IDVDStreamPlayer::SYNC_STARTING))
SetCaching(CACHESTATE_PLAY);
// handle exceptions
if (m_CurrentAudio.id >= 0 && m_CurrentVideo.id >= 0)
{
if ((!m_VideoPlayerAudio->AcceptsData() || !m_VideoPlayerVideo->AcceptsData()) &&
m_cachingTimer.IsTimePast())
{
SetCaching(CACHESTATE_DONE);
}
}
}
if (m_caching == CACHESTATE_PLAY)
{
// if all enabled streams have started playing we are done
if ((m_CurrentVideo.id < 0 || !m_VideoPlayerVideo->IsStalled()) &&
(m_CurrentAudio.id < 0 || !m_VideoPlayerAudio->IsStalled()))
SetCaching(CACHESTATE_DONE);
}
if (m_caching == CACHESTATE_DONE)
{
if (m_playSpeed == DVD_PLAYSPEED_NORMAL && !isInMenu)
{
// take action is audio or video stream is stalled
if (((m_VideoPlayerAudio->IsStalled() && m_CurrentAudio.inited) ||
(m_VideoPlayerVideo->IsStalled() && m_CurrentVideo.inited)) &&
m_syncTimer.IsTimePast())
{
if (m_pInputStream->IsRealtime())
{
if ((m_CurrentAudio.id >= 0 && m_CurrentAudio.syncState == IDVDStreamPlayer::SYNC_INSYNC && m_VideoPlayerAudio->IsStalled()) ||
(m_CurrentVideo.id >= 0 && m_CurrentVideo.syncState == IDVDStreamPlayer::SYNC_INSYNC && m_VideoPlayerVideo->GetLevel() == 0))
{
CLog::Log(LOGDEBUG, "Stream stalled, start buffering. Audio: %d - Video: %d",
m_VideoPlayerAudio->GetLevel(),m_VideoPlayerVideo->GetLevel());
FlushBuffers(false);
}
}
else
{
// start caching if audio and video have run dry
if (m_VideoPlayerAudio->GetLevel() <= 50 &&
m_VideoPlayerVideo->GetLevel() <= 50)
{
SetCaching(CACHESTATE_FULL);
}
else if (m_CurrentAudio.id >= 0 && m_CurrentAudio.inited &&
m_CurrentAudio.syncState == IDVDStreamPlayer::SYNC_INSYNC &&
m_VideoPlayerAudio->GetLevel() == 0)
{
CLog::Log(LOGDEBUG,"CVideoPlayer::HandlePlaySpeed - audio stream stalled, triggering re-sync");
FlushBuffers(false);
m_messenger.Put(new CDVDMsgPlayerSeek((int) GetTime(), false, true, true, true, true));
}
}
}
// care for live streams
else if (m_pInputStream->IsRealtime())
{
if (m_CurrentAudio.id >= 0)
{
double adjust = -1.0; // a unique value
if (m_clock.GetSpeedAdjust() >= 0 && m_VideoPlayerAudio->GetLevel() < 5)
adjust = -0.01;
if (m_clock.GetSpeedAdjust() < 0 && m_VideoPlayerAudio->GetLevel() > 10)
adjust = 0.0;
if (adjust != -1.0)
{
m_clock.SetSpeedAdjust(adjust);
if (m_omxplayer_mode)
m_OmxPlayerState.av_clock.OMXSetSpeedAdjust(adjust);
CLog::Log(LOGDEBUG, "CVideoPlayer::HandlePlaySpeed set clock adjust: %f", adjust);
}
}
}
}
}
// sync streams to clock
if ((m_CurrentVideo.syncState == IDVDStreamPlayer::SYNC_WAITSYNC) ||
(m_CurrentAudio.syncState == IDVDStreamPlayer::SYNC_WAITSYNC))
{
unsigned int threshold = 20;
if (m_pInputStream->IsRealtime())
threshold = 40;
bool video = m_CurrentVideo.id < 0 || (m_CurrentVideo.syncState == IDVDStreamPlayer::SYNC_WAITSYNC) ||
(m_CurrentVideo.packets == 0 && m_CurrentAudio.packets > threshold);
bool audio = m_CurrentAudio.id < 0 || (m_CurrentAudio.syncState == IDVDStreamPlayer::SYNC_WAITSYNC) ||
(m_CurrentAudio.packets == 0 && m_CurrentVideo.packets > threshold);
if (m_CurrentAudio.syncState == IDVDStreamPlayer::SYNC_WAITSYNC &&
m_CurrentAudio.avsync == CCurrentStream::AV_SYNC_CONT)
{
m_CurrentAudio.syncState = IDVDStreamPlayer::SYNC_INSYNC;
m_CurrentAudio.avsync = CCurrentStream::AV_SYNC_NONE;
m_VideoPlayerAudio->SendMessage(new CDVDMsgDouble(CDVDMsg::GENERAL_RESYNC, m_clock.GetClock()), 1);
}
else if (m_CurrentVideo.syncState == IDVDStreamPlayer::SYNC_WAITSYNC &&
m_CurrentVideo.avsync == CCurrentStream::AV_SYNC_CONT)
{
m_CurrentVideo.syncState = IDVDStreamPlayer::SYNC_INSYNC;
m_CurrentVideo.avsync = CCurrentStream::AV_SYNC_NONE;
m_VideoPlayerVideo->SendMessage(new CDVDMsgDouble(CDVDMsg::GENERAL_RESYNC, m_clock.GetClock()), 1);
}
else if (video && audio)
{
double clock = 0;
if (m_CurrentAudio.syncState == IDVDStreamPlayer::SYNC_WAITSYNC)
CLog::Log(LOGDEBUG, "VideoPlayer::Sync - Audio - pts: %f, cache: %f, totalcache: %f",
m_CurrentAudio.starttime, m_CurrentAudio.cachetime, m_CurrentAudio.cachetotal);
if (m_CurrentVideo.syncState == IDVDStreamPlayer::SYNC_WAITSYNC)
CLog::Log(LOGDEBUG, "VideoPlayer::Sync - Video - pts: %f, cache: %f, totalcache: %f",
m_CurrentVideo.starttime, m_CurrentVideo.cachetime, m_CurrentVideo.cachetotal);
if (m_CurrentAudio.starttime != DVD_NOPTS_VALUE && m_CurrentAudio.packets > 0)
{
if (m_pInputStream->IsRealtime())
clock = m_CurrentAudio.starttime - m_CurrentAudio.cachetotal - DVD_MSEC_TO_TIME(400);
else
clock = m_CurrentAudio.starttime - m_CurrentAudio.cachetime;
if (m_CurrentVideo.starttime != DVD_NOPTS_VALUE &&
(m_CurrentVideo.packets > 0) &&
m_CurrentVideo.starttime - m_CurrentVideo.cachetotal < clock)
{
clock = m_CurrentVideo.starttime - m_CurrentVideo.cachetotal;
}
}
else if (m_CurrentVideo.starttime != DVD_NOPTS_VALUE && m_CurrentVideo.packets > 0)
{
clock = m_CurrentVideo.starttime - m_CurrentVideo.cachetotal;
}
if (m_omxplayer_mode)
{
CLog::Log(LOGDEBUG, "%s::%s player started RESET", "CVideoPlayer", __FUNCTION__);
m_OmxPlayerState.av_clock.OMXReset(m_CurrentVideo.id >= 0, m_playSpeed != DVD_PLAYSPEED_NORMAL && m_playSpeed != DVD_PLAYSPEED_PAUSE ? false: (m_CurrentAudio.id >= 0));
}
m_clock.Discontinuity(clock);
m_CurrentAudio.syncState = IDVDStreamPlayer::SYNC_INSYNC;
m_CurrentAudio.avsync = CCurrentStream::AV_SYNC_NONE;
m_CurrentVideo.syncState = IDVDStreamPlayer::SYNC_INSYNC;
m_CurrentVideo.avsync = CCurrentStream::AV_SYNC_NONE;
m_VideoPlayerAudio->SendMessage(new CDVDMsgDouble(CDVDMsg::GENERAL_RESYNC, clock), 1);
m_VideoPlayerVideo->SendMessage(new CDVDMsgDouble(CDVDMsg::GENERAL_RESYNC, clock), 1);
SetCaching(CACHESTATE_DONE);
m_syncTimer.Set(3000);
}
}
// handle ff/rw
if(m_playSpeed != DVD_PLAYSPEED_NORMAL && m_playSpeed != DVD_PLAYSPEED_PAUSE)
{
if (isInMenu)
{
// this can't be done in menu
SetPlaySpeed(DVD_PLAYSPEED_NORMAL);
}
else
{
bool check = true;
// only check if we have video
if (m_CurrentVideo.id < 0 || m_CurrentVideo.syncState != IDVDStreamPlayer::SYNC_INSYNC)
check = false;
// video message queue either initiated or already seen eof
else if (m_CurrentVideo.inited == false && m_playSpeed >= 0)
check = false;
// don't check if time has not advanced since last check
else if (m_SpeedState.lasttime == GetTime())
check = false;
// skip if frame at screen has no valid timestamp
else if (m_VideoPlayerVideo->GetCurrentPts() == DVD_NOPTS_VALUE)
check = false;
// skip if frame on screen has not changed
else if (m_SpeedState.lastpts == m_VideoPlayerVideo->GetCurrentPts() &&
(m_SpeedState.lastpts > m_State.dts || m_playSpeed > 0))
check = false;
if (check)
{
m_SpeedState.lastpts = m_VideoPlayerVideo->GetCurrentPts();
m_SpeedState.lasttime = GetTime();
m_SpeedState.lastabstime = CDVDClock::GetAbsoluteClock();
// check how much off clock video is when ff/rw:ing
// a problem here is that seeking isn't very accurate
// and since the clock will be resynced after seek
// we might actually not really be playing at the wanted
// speed. we'd need to have some way to not resync the clock
// after a seek to remember timing. still need to handle
// discontinuities somehow
double error;
error = m_clock.GetClock() - m_SpeedState.lastpts;
error *= m_playSpeed / abs(m_playSpeed);
// allow a bigger error when going ff, the faster we go
// the the bigger is the error we allow
if (m_playSpeed > DVD_PLAYSPEED_NORMAL)
{
int errorwin = m_playSpeed / DVD_PLAYSPEED_NORMAL;
if (errorwin > 8)
errorwin = 8;
error /= errorwin;
}
if(error > DVD_MSEC_TO_TIME(1000))
{
error = (int)DVD_TIME_TO_MSEC(m_clock.GetClock()) - m_SpeedState.lastseekpts;
if(std::abs(error) > 1000)
{
CLog::Log(LOGDEBUG, "CVideoPlayer::Process - Seeking to catch up");
m_SpeedState.lastseekpts = (int)DVD_TIME_TO_MSEC(m_clock.GetClock());
int direction = (m_playSpeed > 0) ? 1 : -1;
int iTime = DVD_TIME_TO_MSEC(m_clock.GetClock() + m_State.time_offset + 1000000.0 * direction);
m_messenger.Put(new CDVDMsgPlayerSeek(iTime, (GetPlaySpeed() < 0), true, false, false, true, false));
}
}
}
}
}
}
bool CVideoPlayer::CheckPlayerInit(CCurrentStream& current)
{
if (current.inited)
return false;
if (current.startpts != DVD_NOPTS_VALUE)
{
if(current.dts == DVD_NOPTS_VALUE)
{
CLog::Log(LOGDEBUG, "%s - dropping packet type:%d dts:%f to get to start point at %f", __FUNCTION__, current.player, current.dts, current.startpts);
return true;
}
if ((current.startpts - current.dts) > DVD_SEC_TO_TIME(20))
{
CLog::Log(LOGDEBUG, "%s - too far to decode before finishing seek", __FUNCTION__);
if(m_CurrentAudio.startpts != DVD_NOPTS_VALUE)
m_CurrentAudio.startpts = current.dts;
if(m_CurrentVideo.startpts != DVD_NOPTS_VALUE)
m_CurrentVideo.startpts = current.dts;
if(m_CurrentSubtitle.startpts != DVD_NOPTS_VALUE)
m_CurrentSubtitle.startpts = current.dts;
if(m_CurrentTeletext.startpts != DVD_NOPTS_VALUE)
m_CurrentTeletext.startpts = current.dts;
if(m_CurrentRadioRDS.startpts != DVD_NOPTS_VALUE)
m_CurrentRadioRDS.startpts = current.dts;
}
if(current.dts < current.startpts)
{
CLog::Log(LOGDEBUG, "%s - dropping packet type:%d dts:%f to get to start point at %f", __FUNCTION__, current.player, current.dts, current.startpts);
return true;
}
}
if (current.dts != DVD_NOPTS_VALUE)
{
current.inited = true;
current.startpts = current.dts;
}
return false;
}
void CVideoPlayer::UpdateCorrection(DemuxPacket* pkt, double correction)
{
if(pkt->dts != DVD_NOPTS_VALUE)
pkt->dts -= correction;
if(pkt->pts != DVD_NOPTS_VALUE)
pkt->pts -= correction;
}
void CVideoPlayer::UpdateTimestamps(CCurrentStream& current, DemuxPacket* pPacket)
{
double dts = current.dts;
/* update stored values */
if(pPacket->dts != DVD_NOPTS_VALUE)
dts = pPacket->dts;
else if(pPacket->pts != DVD_NOPTS_VALUE)
dts = pPacket->pts;
/* calculate some average duration */
if(pPacket->duration != DVD_NOPTS_VALUE)
current.dur = pPacket->duration;
else if(dts != DVD_NOPTS_VALUE && current.dts != DVD_NOPTS_VALUE)
current.dur = 0.1 * (current.dur * 9 + (dts - current.dts));
current.dts = dts;
}
static void UpdateLimits(double& minimum, double& maximum, double dts)
{
if(dts == DVD_NOPTS_VALUE)
return;
if(minimum == DVD_NOPTS_VALUE || minimum > dts) minimum = dts;
if(maximum == DVD_NOPTS_VALUE || maximum < dts) maximum = dts;
}
bool CVideoPlayer::CheckContinuity(CCurrentStream& current, DemuxPacket* pPacket)
{
if (m_playSpeed < DVD_PLAYSPEED_PAUSE)
return false;
if( pPacket->dts == DVD_NOPTS_VALUE || current.dts == DVD_NOPTS_VALUE)
return false;
double mindts = DVD_NOPTS_VALUE, maxdts = DVD_NOPTS_VALUE;
UpdateLimits(mindts, maxdts, m_CurrentAudio.dts);
UpdateLimits(mindts, maxdts, m_CurrentVideo.dts);
UpdateLimits(mindts, maxdts, m_CurrentAudio.dts_end());
UpdateLimits(mindts, maxdts, m_CurrentVideo.dts_end());
/* if we don't have max and min, we can't do anything more */
if( mindts == DVD_NOPTS_VALUE || maxdts == DVD_NOPTS_VALUE )
return false;
double correction = 0.0;
if( pPacket->dts > maxdts + DVD_MSEC_TO_TIME(1000))
{
CLog::Log(LOGDEBUG, "CVideoPlayer::CheckContinuity - resync forward :%d, prev:%f, curr:%f, diff:%f"
, current.type, current.dts, pPacket->dts, pPacket->dts - maxdts);
correction = pPacket->dts - maxdts;
}
/* if it's large scale jump, correct for it after having confirmed the jump */
if(pPacket->dts + DVD_MSEC_TO_TIME(500) < current.dts_end())
{
CLog::Log(LOGDEBUG, "CVideoPlayer::CheckContinuity - resync backward :%d, prev:%f, curr:%f, diff:%f"
, current.type, current.dts, pPacket->dts, pPacket->dts - current.dts);
correction = pPacket->dts - current.dts_end();
}
else if(pPacket->dts < current.dts)
{
CLog::Log(LOGDEBUG, "CVideoPlayer::CheckContinuity - wrapback :%d, prev:%f, curr:%f, diff:%f"
, current.type, current.dts, pPacket->dts, pPacket->dts - current.dts);
}
double lastdts = pPacket->dts;
if(correction != 0.0)
{
// we want the dts values of two streams to close, or for one to be invalid (e.g. from a missing audio stream)
double this_dts = pPacket->dts;
double that_dts = current.type == STREAM_AUDIO ? m_CurrentVideo.lastdts : m_CurrentAudio.lastdts;
if (m_CurrentAudio.id == -1 || m_CurrentVideo.id == -1 ||
current.lastdts == DVD_NOPTS_VALUE ||
fabs(this_dts - that_dts) < DVD_MSEC_TO_TIME(1000))
{
m_offset_pts += correction;
UpdateCorrection(pPacket, correction);
lastdts = pPacket->dts;
CLog::Log(LOGDEBUG, "CVideoPlayer::CheckContinuity - update correction: %f", correction);
}
else
{
// not sure yet - flags the packets as unknown until we get confirmation on another audio/video packet
pPacket->dts = DVD_NOPTS_VALUE;
pPacket->pts = DVD_NOPTS_VALUE;
}
}
else
{
if (current.avsync == CCurrentStream::AV_SYNC_CHECK)
current.avsync = CCurrentStream::AV_SYNC_CONT;
}
current.lastdts = lastdts;
return true;
}
bool CVideoPlayer::CheckSceneSkip(CCurrentStream& current)
{
if(!m_Edl.HasCut())
return false;
if(current.dts == DVD_NOPTS_VALUE)
return false;
if(current.inited == false)
return false;
CEdl::Cut cut;
return m_Edl.InCut(DVD_TIME_TO_MSEC(current.dts + m_offset_pts), &cut) && cut.action == CEdl::CUT;
}
void CVideoPlayer::CheckAutoSceneSkip()
{
if(!m_Edl.HasCut())
return;
/*
* Check that there is an audio and video stream.
*/
if(m_CurrentAudio.id < 0
|| m_CurrentVideo.id < 0)
return;
/*
* If there is a startpts defined for either the audio or video stream then VideoPlayer is still
* still decoding frames to get to the previously requested seek point.
*/
if(m_CurrentAudio.inited == false
|| m_CurrentVideo.inited == false)
return;
if(m_CurrentAudio.dts == DVD_NOPTS_VALUE
|| m_CurrentVideo.dts == DVD_NOPTS_VALUE)
return;
const int64_t clock = m_omxplayer_mode ? GetTime() : DVD_TIME_TO_MSEC(std::min(m_CurrentAudio.dts, m_CurrentVideo.dts) + m_offset_pts);
CEdl::Cut cut;
if(!m_Edl.InCut(clock, &cut))
return;
if(cut.action == CEdl::CUT
&& !(cut.end == m_EdlAutoSkipMarkers.cut || cut.start == m_EdlAutoSkipMarkers.cut)) // To prevent looping if same cut again
{
CLog::Log(LOGDEBUG, "%s - Clock in EDL cut [%s - %s]: %s. Automatically skipping over.",
__FUNCTION__, CEdl::MillisecondsToTimeString(cut.start).c_str(),
CEdl::MillisecondsToTimeString(cut.end).c_str(), CEdl::MillisecondsToTimeString(clock).c_str());
/*
* Seeking either goes to the start or the end of the cut depending on the play direction.
*/
int seek = GetPlaySpeed() >= 0 ? cut.end : cut.start;
/*
* Seeking is NOT flushed so any content up to the demux point is retained when playing forwards.
*/
m_messenger.Put(new CDVDMsgPlayerSeek(seek, true, false, m_omxplayer_mode, true, false, true));
/*
* Seek doesn't always work reliably. Last physical seek time is recorded to prevent looping
* if there was an error with seeking and it landed somewhere unexpected, perhaps back in the
* cut. The cut automatic skip marker is reset every 500ms allowing another attempt at the seek.
*/
m_EdlAutoSkipMarkers.cut = GetPlaySpeed() >= 0 ? cut.end : cut.start;
}
else if(cut.action == CEdl::COMM_BREAK
&& GetPlaySpeed() >= 0
&& cut.start > m_EdlAutoSkipMarkers.commbreak_end)
{
CLog::Log(LOGDEBUG, "%s - Clock in commercial break [%s - %s]: %s. Automatically skipping to end of commercial break (only done once per break)",
__FUNCTION__, CEdl::MillisecondsToTimeString(cut.start).c_str(), CEdl::MillisecondsToTimeString(cut.end).c_str(),
CEdl::MillisecondsToTimeString(clock).c_str());
/*
* Seeking is NOT flushed so any content up to the demux point is retained when playing forwards.
*/
m_messenger.Put(new CDVDMsgPlayerSeek(cut.end + 1, true, false, m_omxplayer_mode, true, false, true));
/*
* Each commercial break is only skipped once so poorly detected commercial breaks can be
* manually re-entered. Start and end are recorded to prevent looping and to allow seeking back
* to the start of the commercial break if incorrectly flagged.
*/
m_EdlAutoSkipMarkers.commbreak_start = cut.start;
m_EdlAutoSkipMarkers.commbreak_end = cut.end;
m_EdlAutoSkipMarkers.seek_to_start = true; // Allow backwards Seek() to go directly to the start
}
}
void CVideoPlayer::SynchronizeDemuxer(unsigned int timeout)
{
if(IsCurrentThread())
return;
if(!m_messenger.IsInited())
return;
CDVDMsgGeneralSynchronize* message = new CDVDMsgGeneralSynchronize(timeout, 0);
m_messenger.Put(message->Acquire());
message->Wait(&m_bStop, 0);
message->Release();
}
void CVideoPlayer::SynchronizePlayers(unsigned int sources)
{
/* we need a big timeout as audio queue is about 8seconds for 2ch ac3 */
const int timeout = 10*1000; // in milliseconds
CDVDMsgGeneralSynchronize* message = new CDVDMsgGeneralSynchronize(timeout, sources);
if (m_CurrentAudio.id >= 0)
m_VideoPlayerAudio->SendMessage(message->Acquire());
if (m_CurrentVideo.id >= 0)
m_VideoPlayerVideo->SendMessage(message->Acquire());
/* TODO - we have to rewrite the sync class, to not require
all other players waiting for subtitle, should only
be the oposite way
if (m_CurrentSubtitle.id >= 0)
m_VideoPlayerSubtitle->SendMessage(message->Acquire());
*/
message->Release();
}
IDVDStreamPlayer* CVideoPlayer::GetStreamPlayer(unsigned int target)
{
if(target == VideoPlayer_AUDIO)
return m_VideoPlayerAudio;
if(target == VideoPlayer_VIDEO)
return m_VideoPlayerVideo;
if(target == VideoPlayer_SUBTITLE)
return m_VideoPlayerSubtitle;
if(target == VideoPlayer_TELETEXT)
return m_VideoPlayerTeletext;
if(target == VideoPlayer_RDS)
return m_VideoPlayerRadioRDS;
return NULL;
}
void CVideoPlayer::SendPlayerMessage(CDVDMsg* pMsg, unsigned int target)
{
IDVDStreamPlayer* player = GetStreamPlayer(target);
if(player)
player->SendMessage(pMsg, 0);
}
void CVideoPlayer::OnExit()
{
CLog::Log(LOGNOTICE, "CVideoPlayer::OnExit()");
// set event to inform openfile something went wrong in case openfile is still waiting for this event
SetCaching(CACHESTATE_DONE);
// close each stream
if (!m_bAbortRequest) CLog::Log(LOGNOTICE, "VideoPlayer: eof, waiting for queues to empty");
CloseStream(m_CurrentAudio, !m_bAbortRequest);
CloseStream(m_CurrentVideo, !m_bAbortRequest);
// the generalization principle was abused for subtitle player. actually it is not a stream player like
// video and audio. subtitle player does not run on its own thread, hence waitForBuffers makes
// no sense here. waitForBuffers is abused to clear overlay container (false clears container)
// subtitles are added from video player. after video player has finished, overlays have to be cleared.
CloseStream(m_CurrentSubtitle, false); // clear overlay container
CloseStream(m_CurrentTeletext, !m_bAbortRequest);
CloseStream(m_CurrentRadioRDS, !m_bAbortRequest);
// destroy objects
SAFE_DELETE(m_pDemuxer);
SAFE_DELETE(m_pSubtitleDemuxer);
SAFE_DELETE(m_pCCDemuxer);
SAFE_DELETE(m_pInputStream);
// clean up all selection streams
m_SelectionStreams.Clear(STREAM_NONE, STREAM_SOURCE_NONE);
m_messenger.End();
if (m_omxplayer_mode)
{
m_OmxPlayerState.av_clock.OMXStop();
m_OmxPlayerState.av_clock.OMXStateIdle();
m_OmxPlayerState.av_clock.OMXDeinitialize();
}
m_bStop = true;
// if we didn't stop playing, advance to the next item in xbmc's playlist
if(m_PlayerOptions.identify == false)
{
if (m_bAbortRequest)
m_callback.OnPlayBackStopped();
else
m_callback.OnPlayBackEnded();
}
// set event to inform openfile something went wrong in case openfile is still waiting for this event
m_ready.Set();
}
void CVideoPlayer::HandleMessages()
{
CDVDMsg* pMsg;
while (m_messenger.Get(&pMsg, 0) == MSGQ_OK)
{
if (pMsg->IsType(CDVDMsg::PLAYER_SEEK) && m_messenger.GetPacketCount(CDVDMsg::PLAYER_SEEK) == 0
&& m_messenger.GetPacketCount(CDVDMsg::PLAYER_SEEK_CHAPTER) == 0)
{
CDVDMsgPlayerSeek &msg(*((CDVDMsgPlayerSeek*)pMsg));
if (!m_State.canseek)
{
pMsg->Release();
continue;
}
if(!msg.GetTrickPlay())
{
g_infoManager.SetDisplayAfterSeek(100000);
if(msg.GetFlush())
SetCaching(CACHESTATE_FLUSH);
}
double start = DVD_NOPTS_VALUE;
int time = msg.GetRestore() ? m_Edl.RestoreCutTime(msg.GetTime()) : msg.GetTime();
// if input stream doesn't support ISeekTime, convert back to pts
// TODO:
// After demuxer we add an offset to input pts so that displayed time and clock are
// increasing steadily. For seeking we need to determine the boundaries and offset
// of the desired segment. With the current approach calculated time may point
// to nirvana
if (m_pInputStream->GetIPosTime() == nullptr)
time += DVD_TIME_TO_MSEC(m_offset_pts - m_State.time_offset);
CLog::Log(LOGDEBUG, "demuxer seek to: %d", time);
if (m_pDemuxer && m_pDemuxer->SeekTime(time, msg.GetBackward(), &start))
{
CLog::Log(LOGDEBUG, "demuxer seek to: %d, success", time);
if(m_pSubtitleDemuxer)
{
if(!m_pSubtitleDemuxer->SeekTime(time, msg.GetBackward()))
CLog::Log(LOGDEBUG, "failed to seek subtitle demuxer: %d, success", time);
}
// dts after successful seek
if (start == DVD_NOPTS_VALUE)
m_State.dts = DVD_MSEC_TO_TIME(time) - m_State.time_offset;
else
{
start -= m_offset_pts;
m_State.dts = start;
}
FlushBuffers(!msg.GetFlush(), start, msg.GetAccurate(), msg.GetSync());
}
else
CLog::Log(LOGWARNING, "error while seeking");
// set flag to indicate we have finished a seeking request
if(!msg.GetTrickPlay())
g_infoManager.SetDisplayAfterSeek();
// dvd's will issue a HOP_CHANNEL that we need to skip
if(m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
m_dvd.state = DVDSTATE_SEEK;
}
else if (pMsg->IsType(CDVDMsg::PLAYER_SEEK_CHAPTER) && m_messenger.GetPacketCount(CDVDMsg::PLAYER_SEEK) == 0
&& m_messenger.GetPacketCount(CDVDMsg::PLAYER_SEEK_CHAPTER) == 0)
{
g_infoManager.SetDisplayAfterSeek(100000);
SetCaching(CACHESTATE_FLUSH);
CDVDMsgPlayerSeekChapter &msg(*((CDVDMsgPlayerSeekChapter*)pMsg));
double start = DVD_NOPTS_VALUE;
double offset = 0;
int64_t beforeSeek = GetTime();
// This should always be the case.
if(m_pDemuxer && m_pDemuxer->SeekChapter(msg.GetChapter(), &start))
{
if (start != DVD_NOPTS_VALUE)
start -= m_offset_pts;
FlushBuffers(false, start, true);
offset = DVD_TIME_TO_MSEC(start) - beforeSeek;
m_callback.OnPlayBackSeekChapter(msg.GetChapter());
}
g_infoManager.SetDisplayAfterSeek(2500, offset);
}
else if (pMsg->IsType(CDVDMsg::DEMUXER_RESET))
{
m_CurrentAudio.stream = NULL;
m_CurrentVideo.stream = NULL;
m_CurrentSubtitle.stream = NULL;
// we need to reset the demuxer, probably because the streams have changed
if(m_pDemuxer)
m_pDemuxer->Reset();
if(m_pSubtitleDemuxer)
m_pSubtitleDemuxer->Reset();
}
else if (pMsg->IsType(CDVDMsg::PLAYER_SET_AUDIOSTREAM))
{
CDVDMsgPlayerSetAudioStream* pMsg2 = (CDVDMsgPlayerSetAudioStream*)pMsg;
SelectionStream& st = m_SelectionStreams.Get(STREAM_AUDIO, pMsg2->GetStreamId());
if(st.source != STREAM_SOURCE_NONE)
{
if(st.source == STREAM_SOURCE_NAV && m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
{
CDVDInputStreamNavigator* pStream = (CDVDInputStreamNavigator*)m_pInputStream;
if(pStream->SetActiveAudioStream(st.id))
{
m_dvd.iSelectedAudioStream = -1;
CloseStream(m_CurrentAudio, false);
m_messenger.Put(new CDVDMsgPlayerSeek((int) GetTime(), true, true, true, true, true));
}
}
else
{
CloseStream(m_CurrentAudio, false);
OpenStream(m_CurrentAudio, st.id, st.source);
AdaptForcedSubtitles();
m_messenger.Put(new CDVDMsgPlayerSeek((int) GetTime(), true, true, true, true, true));
}
}
}
else if (pMsg->IsType(CDVDMsg::PLAYER_SET_VIDEOSTREAM))
{
CDVDMsgPlayerSetVideoStream* pMsg2 = (CDVDMsgPlayerSetVideoStream*)pMsg;
SelectionStream& st = m_SelectionStreams.Get(STREAM_VIDEO, pMsg2->GetStreamId());
if (st.source != STREAM_SOURCE_NONE)
{
if (st.source == STREAM_SOURCE_NAV && m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
{
CDVDInputStreamNavigator* pStream = (CDVDInputStreamNavigator*)m_pInputStream;
if (pStream->SetAngle(st.id))
{
m_dvd.iSelectedVideoStream = st.id;
m_messenger.Put(new CDVDMsgPlayerSeek((int)GetTime(), true, true, true, true, true));
}
}
else
{
CloseStream(m_CurrentVideo, false);
OpenStream(m_CurrentVideo, st.id, st.source);
m_messenger.Put(new CDVDMsgPlayerSeek((int)GetTime(), true, true, true, true, true));
}
}
}
else if (pMsg->IsType(CDVDMsg::PLAYER_SET_SUBTITLESTREAM))
{
CDVDMsgPlayerSetSubtitleStream* pMsg2 = (CDVDMsgPlayerSetSubtitleStream*)pMsg;
SelectionStream& st = m_SelectionStreams.Get(STREAM_SUBTITLE, pMsg2->GetStreamId());
if(st.source != STREAM_SOURCE_NONE)
{
if(st.source == STREAM_SOURCE_NAV && m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
{
CDVDInputStreamNavigator* pStream = (CDVDInputStreamNavigator*)m_pInputStream;
if(pStream->SetActiveSubtitleStream(st.id))
{
m_dvd.iSelectedSPUStream = -1;
CloseStream(m_CurrentSubtitle, false);
}
}
else
{
CloseStream(m_CurrentSubtitle, false);
OpenStream(m_CurrentSubtitle, st.id, st.source);
}
}
}
else if (pMsg->IsType(CDVDMsg::PLAYER_SET_SUBTITLESTREAM_VISIBLE))
{
CDVDMsgBool* pValue = (CDVDMsgBool*)pMsg;
SetSubtitleVisibleInternal(pValue->m_value);
}
else if (pMsg->IsType(CDVDMsg::PLAYER_SET_STATE))
{
g_infoManager.SetDisplayAfterSeek(100000);
SetCaching(CACHESTATE_FLUSH);
CDVDMsgPlayerSetState* pMsgPlayerSetState = (CDVDMsgPlayerSetState*)pMsg;
if (CDVDInputStream::IMenus* ptr = dynamic_cast<CDVDInputStream::IMenus*>(m_pInputStream))
{
if(ptr->SetState(pMsgPlayerSetState->GetState()))
{
m_dvd.state = DVDSTATE_NORMAL;
m_dvd.iDVDStillStartTime = 0;
m_dvd.iDVDStillTime = 0;
}
}
g_infoManager.SetDisplayAfterSeek();
}
else if (pMsg->IsType(CDVDMsg::PLAYER_SET_RECORD))
{
CDVDInputStreamPVRManager* input = dynamic_cast<CDVDInputStreamPVRManager*>(m_pInputStream);
if(input)
input->Record(*(CDVDMsgBool*)pMsg);
}
else if (pMsg->IsType(CDVDMsg::GENERAL_FLUSH))
{
FlushBuffers(false);
}
else if (pMsg->IsType(CDVDMsg::PLAYER_SETSPEED))
{
int speed = static_cast<CDVDMsgInt*>(pMsg)->m_value;
// correct our current clock, as it would start going wrong otherwise
if(m_State.timestamp > 0)
{
double offset;
offset = CDVDClock::GetAbsoluteClock() - m_State.timestamp;
offset *= m_playSpeed / DVD_PLAYSPEED_NORMAL;
offset = DVD_TIME_TO_MSEC(offset);
if(offset > 1000) offset = 1000;
if(offset < -1000) offset = -1000;
m_State.time += offset;
m_State.timestamp = CDVDClock::GetAbsoluteClock();
}
if (speed != DVD_PLAYSPEED_PAUSE && m_playSpeed != DVD_PLAYSPEED_PAUSE && speed != m_playSpeed)
m_callback.OnPlayBackSpeedChanged(speed / DVD_PLAYSPEED_NORMAL);
if (m_pInputStream->IsStreamType(DVDSTREAM_TYPE_PVRMANAGER) && speed != m_playSpeed)
{
CDVDInputStreamPVRManager* pvrinputstream = static_cast<CDVDInputStreamPVRManager*>(m_pInputStream);
pvrinputstream->Pause( speed == 0 );
}
// do a seek after rewind, clock is not in sync with current pts
if (m_omxplayer_mode)
{
// when switching from trickplay to normal, we may not have a full set of reference frames
// in decoder and we may get corrupt frames out. Seeking to current time will avoid this.
if ( (speed != DVD_PLAYSPEED_PAUSE && speed != DVD_PLAYSPEED_NORMAL) ||
(m_playSpeed != DVD_PLAYSPEED_PAUSE && m_playSpeed != DVD_PLAYSPEED_NORMAL) )
{
m_messenger.Put(new CDVDMsgPlayerSeek(GetTime(), (speed < 0), true, true, false, true));
}
else
{
m_OmxPlayerState.av_clock.OMXPause();
}
m_OmxPlayerState.av_clock.OMXSetSpeed(speed);
CLog::Log(LOGDEBUG, "%s::%s CDVDMsg::PLAYER_SETSPEED speed : %d (%d)", "CVideoPlayer", __FUNCTION__, speed, m_playSpeed);
}
else if ((speed == DVD_PLAYSPEED_NORMAL) &&
(m_playSpeed != DVD_PLAYSPEED_NORMAL) &&
(m_playSpeed != DVD_PLAYSPEED_PAUSE))
{
int64_t iTime = (int64_t)DVD_TIME_TO_MSEC(m_clock.GetClock() + m_State.time_offset);
if (m_State.time != DVD_NOPTS_VALUE)
iTime = m_State.time;
m_messenger.Put(new CDVDMsgPlayerSeek(iTime, m_playSpeed < 0, true, false, false, true));
}
// if playspeed is different then DVD_PLAYSPEED_NORMAL or DVD_PLAYSPEED_PAUSE
// audioplayer, stops outputing audio to audiorendere, but still tries to
// sleep an correct amount for each packet
// videoplayer just plays faster after the clock speed has been increased
// 1. disable audio
// 2. skip frames and adjust their pts or the clock
m_playSpeed = speed;
m_caching = CACHESTATE_DONE;
m_clock.SetSpeed(speed);
m_VideoPlayerAudio->SetSpeed(speed);
m_VideoPlayerVideo->SetSpeed(speed);
m_streamPlayerSpeed = speed;
}
else if (pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_SELECT_NUMBER) && m_messenger.GetPacketCount(CDVDMsg::PLAYER_CHANNEL_SELECT_NUMBER) == 0)
{
FlushBuffers(false);
CDVDInputStreamPVRManager* input = dynamic_cast<CDVDInputStreamPVRManager*>(m_pInputStream);
// TODO find a better solution for the "otherStreaHack"
// a stream is not sopposed to be terminated before demuxer
if (input && input->IsOtherStreamHack())
{
SAFE_DELETE(m_pDemuxer);
}
if(input && input->SelectChannelByNumber(static_cast<CDVDMsgInt*>(pMsg)->m_value))
{
SAFE_DELETE(m_pDemuxer);
m_playSpeed = DVD_PLAYSPEED_NORMAL;
// when using fast channel switching some shortcuts are taken which
// means we'll have to update the view mode manually
m_renderManager.SetViewMode(CMediaSettings::GetInstance().GetCurrentVideoSettings().m_ViewMode);
}else
{
CLog::Log(LOGWARNING, "%s - failed to switch channel. playback stopped", __FUNCTION__);
CApplicationMessenger::GetInstance().PostMsg(TMSG_MEDIA_STOP);
}
}
else if (pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_SELECT) && m_messenger.GetPacketCount(CDVDMsg::PLAYER_CHANNEL_SELECT) == 0)
{
FlushBuffers(false);
CDVDInputStreamPVRManager* input = dynamic_cast<CDVDInputStreamPVRManager*>(m_pInputStream);
if (input && input->IsOtherStreamHack())
{
SAFE_DELETE(m_pDemuxer);
}
if(input && input->SelectChannel(static_cast<CDVDMsgType <CPVRChannelPtr> *>(pMsg)->m_value))
{
SAFE_DELETE(m_pDemuxer);
m_playSpeed = DVD_PLAYSPEED_NORMAL;
}
else
{
CLog::Log(LOGWARNING, "%s - failed to switch channel. playback stopped", __FUNCTION__);
CApplicationMessenger::GetInstance().PostMsg(TMSG_MEDIA_STOP);
}
}
else if (pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_NEXT) || pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_PREV) ||
pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_PREVIEW_NEXT) || pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_PREVIEW_PREV))
{
CDVDInputStreamPVRManager* input = dynamic_cast<CDVDInputStreamPVRManager*>(m_pInputStream);
if (input)
{
bool bSwitchSuccessful(false);
bool bShowPreview(pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_PREVIEW_NEXT) ||
pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_PREVIEW_PREV) ||
CSettings::GetInstance().GetInt(CSettings::SETTING_PVRPLAYBACK_CHANNELENTRYTIMEOUT) > 0);
if (!bShowPreview)
{
g_infoManager.SetDisplayAfterSeek(100000);
FlushBuffers(false);
if (input->IsOtherStreamHack())
{
SAFE_DELETE(m_pDemuxer);
}
}
if (pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_NEXT) || pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_PREVIEW_NEXT))
bSwitchSuccessful = input->NextChannel(bShowPreview);
else
bSwitchSuccessful = input->PrevChannel(bShowPreview);
if (bSwitchSuccessful)
{
if (bShowPreview)
{
UpdateApplication(0);
if (pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_PREVIEW_NEXT) || pMsg->IsType(CDVDMsg::PLAYER_CHANNEL_PREVIEW_PREV))
m_ChannelEntryTimeOut.SetInfinite();
else
m_ChannelEntryTimeOut.Set(CSettings::GetInstance().GetInt(CSettings::SETTING_PVRPLAYBACK_CHANNELENTRYTIMEOUT));
}
else
{
m_ChannelEntryTimeOut.SetInfinite();
SAFE_DELETE(m_pDemuxer);
m_playSpeed = DVD_PLAYSPEED_NORMAL;
g_infoManager.SetDisplayAfterSeek();
// when using fast channel switching some shortcuts are taken which
// means we'll have to update the view mode manually
m_renderManager.SetViewMode(CMediaSettings::GetInstance().GetCurrentVideoSettings().m_ViewMode);
}
}
else
{
CLog::Log(LOGWARNING, "%s - failed to switch channel. playback stopped", __FUNCTION__);
CApplicationMessenger::GetInstance().PostMsg(TMSG_MEDIA_STOP);
}
}
}
else if (pMsg->IsType(CDVDMsg::GENERAL_GUI_ACTION))
OnAction(((CDVDMsgType<CAction>*)pMsg)->m_value);
else if (pMsg->IsType(CDVDMsg::PLAYER_STARTED))
{
SStartMsg& msg = ((CDVDMsgType<SStartMsg>*)pMsg)->m_value;
if (msg.player == VideoPlayer_AUDIO)
{
m_CurrentAudio.syncState = IDVDStreamPlayer::SYNC_WAITSYNC;
m_CurrentAudio.cachetime = msg.cachetime;
m_CurrentAudio.cachetotal = msg.cachetotal;
m_CurrentAudio.starttime = msg.timestamp;
}
if (msg.player == VideoPlayer_VIDEO)
{
m_CurrentVideo.syncState = IDVDStreamPlayer::SYNC_WAITSYNC;
m_CurrentVideo.cachetime = msg.cachetime;
m_CurrentVideo.cachetotal = msg.cachetotal;
m_CurrentVideo.starttime = msg.timestamp;
}
CLog::Log(LOGDEBUG, "CVideoPlayer::HandleMessages - player started %d", msg.player);
}
else if (pMsg->IsType(CDVDMsg::SUBTITLE_ADDFILE))
{
int id = AddSubtitleFile(((CDVDMsgType<std::string>*) pMsg)->m_value);
if (id >= 0)
{
SetSubtitle(id);
SetSubtitleVisibleInternal(true);
}
}
else if (pMsg->IsType(CDVDMsg::GENERAL_SYNCHRONIZE))
{
if (((CDVDMsgGeneralSynchronize*)pMsg)->Wait(100, SYNCSOURCE_OWNER))
CLog::Log(LOGDEBUG, "CVideoPlayer - CDVDMsg::GENERAL_SYNCHRONIZE");
}
else if (pMsg->IsType(CDVDMsg::PLAYER_AVCHANGE))
{
UpdateStreamInfos();
g_dataCacheCore.SignalAudioInfoChange();
g_dataCacheCore.SignalVideoInfoChange();
}
pMsg->Release();
}
}
void CVideoPlayer::SetCaching(ECacheState state)
{
if(state == CACHESTATE_FLUSH)
{
double level, delay, offset;
if(GetCachingTimes(level, delay, offset))
state = CACHESTATE_FULL;
else
state = CACHESTATE_INIT;
}
if(m_caching == state)
return;
CLog::Log(LOGDEBUG, "CVideoPlayer::SetCaching - caching state %d", state);
if (state == CACHESTATE_FULL ||
state == CACHESTATE_INIT)
{
m_clock.SetSpeed(DVD_PLAYSPEED_PAUSE);
if (m_omxplayer_mode)
m_OmxPlayerState.av_clock.OMXPause();
m_VideoPlayerAudio->SetSpeed(DVD_PLAYSPEED_PAUSE);
m_VideoPlayerVideo->SetSpeed(DVD_PLAYSPEED_PAUSE);
m_streamPlayerSpeed = DVD_PLAYSPEED_PAUSE;
m_pInputStream->ResetScanTimeout((unsigned int) CSettings::GetInstance().GetInt(CSettings::SETTING_PVRPLAYBACK_SCANTIME) * 1000);
m_cachingTimer.Set(5000);
}
if (state == CACHESTATE_PLAY ||
(state == CACHESTATE_DONE && m_caching != CACHESTATE_PLAY))
{
m_clock.SetSpeed(m_playSpeed);
m_VideoPlayerAudio->SetSpeed(m_playSpeed);
m_VideoPlayerVideo->SetSpeed(m_playSpeed);
m_streamPlayerSpeed = m_playSpeed;
m_pInputStream->ResetScanTimeout(0);
}
m_caching = state;
m_clock.SetSpeedAdjust(0);
if (m_omxplayer_mode)
m_OmxPlayerState.av_clock.OMXSetSpeedAdjust(0);
}
void CVideoPlayer::SetPlaySpeed(int speed)
{
if (IsPlaying())
m_messenger.Put(new CDVDMsgInt(CDVDMsg::PLAYER_SETSPEED, speed));
else
{
m_playSpeed = speed;
m_streamPlayerSpeed = speed;
}
}
bool CVideoPlayer::CanPause()
{
CSingleLock lock(m_StateSection);
return m_State.canpause;
}
void CVideoPlayer::Pause()
{
CSingleLock lock(m_StateSection);
if (!m_State.canpause)
return;
lock.Leave();
if(m_playSpeed != DVD_PLAYSPEED_PAUSE && IsCaching())
{
SetCaching(CACHESTATE_DONE);
return;
}
// return to normal speed if it was paused before, pause otherwise
if (m_playSpeed == DVD_PLAYSPEED_PAUSE)
{
SetPlaySpeed(DVD_PLAYSPEED_NORMAL);
m_callback.OnPlayBackResumed();
}
else
{
SetPlaySpeed(DVD_PLAYSPEED_PAUSE);
m_callback.OnPlayBackPaused();
}
}
bool CVideoPlayer::IsPaused() const
{
return m_playSpeed == DVD_PLAYSPEED_PAUSE || IsCaching();
}
bool CVideoPlayer::HasVideo() const
{
return m_HasVideo;
}
bool CVideoPlayer::HasAudio() const
{
return m_HasAudio;
}
bool CVideoPlayer::HasRDS() const
{
return m_CurrentRadioRDS.id >= 0;
}
bool CVideoPlayer::IsPassthrough() const
{
return m_VideoPlayerAudio->IsPassthrough();
}
bool CVideoPlayer::CanSeek()
{
CSingleLock lock(m_StateSection);
return m_State.canseek;
}
void CVideoPlayer::Seek(bool bPlus, bool bLargeStep, bool bChapterOverride)
{
if( m_playSpeed == DVD_PLAYSPEED_PAUSE && bPlus && !bLargeStep)
{
if (m_VideoPlayerVideo->StepFrame())
return;
}
if (!m_State.canseek)
return;
if (bLargeStep && bChapterOverride && GetChapter() > 0)
{
if (!bPlus)
{
SeekChapter(GetChapter() - 1);
return;
}
else if (GetChapter() < GetChapterCount())
{
SeekChapter(GetChapter() + 1);
return;
}
}
int64_t seek;
if (g_advancedSettings.m_videoUseTimeSeeking && GetTotalTime() > 2000*g_advancedSettings.m_videoTimeSeekForwardBig)
{
if (bLargeStep)
seek = bPlus ? g_advancedSettings.m_videoTimeSeekForwardBig : g_advancedSettings.m_videoTimeSeekBackwardBig;
else
seek = bPlus ? g_advancedSettings.m_videoTimeSeekForward : g_advancedSettings.m_videoTimeSeekBackward;
seek *= 1000;
seek += GetTime();
}
else
{
int percent;
if (bLargeStep)
percent = bPlus ? g_advancedSettings.m_videoPercentSeekForwardBig : g_advancedSettings.m_videoPercentSeekBackwardBig;
else
percent = bPlus ? g_advancedSettings.m_videoPercentSeekForward : g_advancedSettings.m_videoPercentSeekBackward;
seek = (int64_t)(GetTotalTimeInMsec()*(GetPercentage()+percent)/100);
}
bool restore = true;
if (m_Edl.HasCut())
{
/*
* Alter the standard seek position based on whether any commercial breaks have been
* automatically skipped.
*/
const int clock = DVD_TIME_TO_MSEC(m_clock.GetClock());
/*
* If a large backwards seek occurs within 10 seconds of the end of the last automated
* commercial skip, then seek back to the start of the commercial break under the assumption
* it was flagged incorrectly. 10 seconds grace period is allowed in case the watcher has to
* fumble around finding the remote. Only happens once per commercial break.
*
* Small skip does not trigger this in case the start of the commercial break was in fact fine
* but it skipped too far into the program. In that case small skip backwards behaves as normal.
*/
if (!bPlus && bLargeStep
&& m_EdlAutoSkipMarkers.seek_to_start
&& clock >= m_EdlAutoSkipMarkers.commbreak_end
&& clock <= m_EdlAutoSkipMarkers.commbreak_end + 10*1000) // Only if within 10 seconds of the end (in msec)
{
CLog::Log(LOGDEBUG, "%s - Seeking back to start of commercial break [%s - %s] as large backwards skip activated within 10 seconds of the automatic commercial skip (only done once per break).",
__FUNCTION__, CEdl::MillisecondsToTimeString(m_EdlAutoSkipMarkers.commbreak_start).c_str(),
CEdl::MillisecondsToTimeString(m_EdlAutoSkipMarkers.commbreak_end).c_str());
seek = m_EdlAutoSkipMarkers.commbreak_start;
restore = false;
m_EdlAutoSkipMarkers.seek_to_start = false; // So this will only happen within the 10 second grace period once.
}
/*
* If big skip forward within the last "reverted" commercial break, seek to the end of the
* commercial break under the assumption that the break was incorrectly flagged and playback has
* now reached the actual start of the commercial break. Assume that the end is flagged more
* correctly than the landing point for a standard big skip (ends seem to be flagged more
* accurately than the start).
*/
else if (bPlus && bLargeStep
&& clock >= m_EdlAutoSkipMarkers.commbreak_start
&& clock <= m_EdlAutoSkipMarkers.commbreak_end)
{
CLog::Log(LOGDEBUG, "%s - Seeking to end of previously skipped commercial break [%s - %s] as big forwards skip activated within the break.",
__FUNCTION__, CEdl::MillisecondsToTimeString(m_EdlAutoSkipMarkers.commbreak_start).c_str(),
CEdl::MillisecondsToTimeString(m_EdlAutoSkipMarkers.commbreak_end).c_str());
seek = m_EdlAutoSkipMarkers.commbreak_end;
restore = false;
}
}
int64_t time = GetTime();
if(g_application.CurrentFileItem().IsStack()
&& (seek > GetTotalTimeInMsec() || seek < 0))
{
g_application.SeekTime((seek - time) * 0.001 + g_application.GetTime());
// warning, don't access any VideoPlayer variables here as
// the VideoPlayer object may have been destroyed
return;
}
m_messenger.Put(new CDVDMsgPlayerSeek((int)seek, !bPlus, true, false, restore));
SynchronizeDemuxer(100);
if (seek < 0) seek = 0;
m_callback.OnPlayBackSeek((int)seek, (int)(seek - time));
}
bool CVideoPlayer::SeekScene(bool bPlus)
{
if (!m_Edl.HasSceneMarker())
return false;
/*
* There is a 5 second grace period applied when seeking for scenes backwards. If there is no
* grace period applied it is impossible to go backwards past a scene marker.
*/
int64_t clock = GetTime();
if (!bPlus && clock > 5 * 1000) // 5 seconds
clock -= 5 * 1000;
int iScenemarker;
if (m_Edl.GetNextSceneMarker(bPlus, clock, &iScenemarker))
{
/*
* Seeking is flushed and inaccurate, just like Seek()
*/
m_messenger.Put(new CDVDMsgPlayerSeek(iScenemarker, !bPlus, true, false, false));
SynchronizeDemuxer(100);
return true;
}
return false;
}
void CVideoPlayer::GetAudioInfo(std::string& strAudioInfo)
{
{ CSingleLock lock(m_StateSection);
strAudioInfo = StringUtils::Format("D(%s)", m_State.demux_audio.c_str());
}
strAudioInfo += StringUtils::Format("\nP(%s)", m_VideoPlayerAudio->GetPlayerInfo().c_str());
}
void CVideoPlayer::GetVideoInfo(std::string& strVideoInfo)
{
{ CSingleLock lock(m_StateSection);
strVideoInfo = StringUtils::Format("D(%s)", m_State.demux_video.c_str());
}
strVideoInfo += StringUtils::Format("\nP(%s)", m_VideoPlayerVideo->GetPlayerInfo().c_str());
}
void CVideoPlayer::GetGeneralInfo(std::string& strGeneralInfo)
{
if (!m_bStop)
{
if (m_omxplayer_mode)
{
double apts = m_VideoPlayerAudio->GetCurrentPts();
double vpts = m_VideoPlayerVideo->GetCurrentPts();
double dDiff = 0;
if( apts != DVD_NOPTS_VALUE && vpts != DVD_NOPTS_VALUE )
dDiff = (apts - vpts) / DVD_TIME_BASE;
std::string strEDL;
strEDL += StringUtils::Format(", edl:%s", m_Edl.GetInfo().c_str());
std::string strBuf;
CSingleLock lock(m_StateSection);
if(m_State.cache_bytes >= 0)
{
strBuf += StringUtils::Format(" forward:%s %2.0f%%"
, StringUtils::SizeToString(m_State.cache_bytes).c_str()
, m_State.cache_level * 100);
if(m_playSpeed == 0 || m_caching == CACHESTATE_FULL)
strBuf += StringUtils::Format(" %d sec", DVD_TIME_TO_SEC(m_State.cache_delay));
}
strGeneralInfo = StringUtils::Format("C( a/v:% 6.3f%s, dcpu:%2i%% acpu:%2i%% vcpu:%2i%%%s amp:% 5.2f )"
, dDiff
, strEDL.c_str()
, (int)(CThread::GetRelativeUsage()*100)
, (int)(m_VideoPlayerAudio->GetRelativeUsage()*100)
, (int)(m_VideoPlayerVideo->GetRelativeUsage()*100)
, strBuf.c_str()
, m_VideoPlayerAudio->GetDynamicRangeAmplification());
}
else
{
double dDelay = m_VideoPlayerVideo->GetDelay() / DVD_TIME_BASE - m_renderManager.GetDisplayLatency();
double apts = m_VideoPlayerAudio->GetCurrentPts();
double vpts = m_VideoPlayerVideo->GetCurrentPts();
double dDiff = 0;
if( apts != DVD_NOPTS_VALUE && vpts != DVD_NOPTS_VALUE )
dDiff = (apts - vpts) / DVD_TIME_BASE;
std::string strEDL = StringUtils::Format(", edl:%s", m_Edl.GetInfo().c_str());
std::string strBuf;
CSingleLock lock(m_StateSection);
if(m_State.cache_bytes >= 0)
{
strBuf += StringUtils::Format(" forward:%s %2.0f%%"
, StringUtils::SizeToString(m_State.cache_bytes).c_str()
, m_State.cache_level * 100);
if(m_playSpeed == 0 || m_caching == CACHESTATE_FULL)
strBuf += StringUtils::Format(" %d sec", DVD_TIME_TO_SEC(m_State.cache_delay));
}
strGeneralInfo = StringUtils::Format("C( ad:% 6.3f, a/v:% 6.3f%s, dcpu:%2i%% acpu:%2i%% vcpu:%2i%%%s )"
, dDelay
, dDiff
, strEDL.c_str()
, (int)(CThread::GetRelativeUsage()*100)
, (int)(m_VideoPlayerAudio->GetRelativeUsage()*100)
, (int)(m_VideoPlayerVideo->GetRelativeUsage()*100)
, strBuf.c_str());
}
}
}
void CVideoPlayer::SeekPercentage(float iPercent)
{
int64_t iTotalTime = GetTotalTimeInMsec();
if (!iTotalTime)
return;
SeekTime((int64_t)(iTotalTime * iPercent / 100));
}
float CVideoPlayer::GetPercentage()
{
int64_t iTotalTime = GetTotalTimeInMsec();
if (!iTotalTime)
return 0.0f;
return GetTime() * 100 / (float)iTotalTime;
}
float CVideoPlayer::GetCachePercentage()
{
CSingleLock lock(m_StateSection);
return (float) (m_State.cache_offset * 100); // NOTE: Percentage returned is relative
}
void CVideoPlayer::SetAVDelay(float fValue)
{
m_VideoPlayerVideo->SetDelay( (fValue * DVD_TIME_BASE) ) ;
}
float CVideoPlayer::GetAVDelay()
{
return (float) m_VideoPlayerVideo->GetDelay() / (float)DVD_TIME_BASE;
}
void CVideoPlayer::SetSubTitleDelay(float fValue)
{
m_VideoPlayerVideo->SetSubtitleDelay(-fValue * DVD_TIME_BASE);
}
float CVideoPlayer::GetSubTitleDelay()
{
return (float) -m_VideoPlayerVideo->GetSubtitleDelay() / DVD_TIME_BASE;
}
// priority: 1: libdvdnav, 2: external subtitles, 3: muxed subtitles
int CVideoPlayer::GetSubtitleCount()
{
return m_SelectionStreams.Count(STREAM_SUBTITLE);
}
int CVideoPlayer::GetSubtitle()
{
return m_SelectionStreams.IndexOf(STREAM_SUBTITLE, *this);
}
void CVideoPlayer::UpdateStreamInfos()
{
if (!m_pDemuxer)
return;
CSingleLock lock(m_SelectionStreams.m_section);
int streamId;
std::string retVal;
// video
streamId = GetVideoStream();
if (streamId >= 0 && streamId < GetVideoStreamCount())
{
SelectionStream& s = m_SelectionStreams.Get(STREAM_VIDEO, streamId);
s.bitrate = m_VideoPlayerVideo->GetVideoBitrate();
s.aspect_ratio = m_renderManager.GetAspectRatio();
CRect viewRect;
m_renderManager.GetVideoRect(s.SrcRect, s.DestRect, viewRect);
s.stereo_mode = m_VideoPlayerVideo->GetStereoMode();
if (s.stereo_mode == "mono")
s.stereo_mode = "";
CDemuxStream* stream = m_pDemuxer->GetStream(m_CurrentVideo.id);
if (stream && stream->type == STREAM_VIDEO)
{
s.width = ((CDemuxStreamVideo*)stream)->iWidth;
s.height = ((CDemuxStreamVideo*)stream)->iHeight;
}
}
// audio
streamId = GetAudioStream();
if (streamId >= 0 && streamId < GetAudioStreamCount())
{
SelectionStream& s = m_SelectionStreams.Get(STREAM_AUDIO, streamId);
s.bitrate = m_VideoPlayerAudio->GetAudioBitrate();
s.channels = m_VideoPlayerAudio->GetAudioChannels();
CDemuxStream* stream = m_pDemuxer->GetStream(m_CurrentAudio.id);
if (stream && stream->type == STREAM_AUDIO)
{
s.codec = m_pDemuxer->GetStreamCodecName(stream->iId);
}
}
}
void CVideoPlayer::GetSubtitleStreamInfo(int index, SPlayerSubtitleStreamInfo &info)
{
CSingleLock lock(m_SelectionStreams.m_section);
if (index < 0 || index > (int) GetSubtitleCount() - 1)
return;
SelectionStream& s = m_SelectionStreams.Get(STREAM_SUBTITLE, index);
if(s.name.length() > 0)
info.name = s.name;
if(s.type == STREAM_NONE)
info.name += "(Invalid)";
info.language = s.language;
}
void CVideoPlayer::SetSubtitle(int iStream)
{
m_messenger.Put(new CDVDMsgPlayerSetSubtitleStream(iStream));
}
bool CVideoPlayer::GetSubtitleVisible()
{
if (m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
{
CDVDInputStreamNavigator* pStream = (CDVDInputStreamNavigator*)m_pInputStream;
return pStream->IsSubtitleStreamEnabled();
}
return m_VideoPlayerVideo->IsSubtitleEnabled();
}
void CVideoPlayer::SetSubtitleVisible(bool bVisible)
{
m_messenger.Put(new CDVDMsgBool(CDVDMsg::PLAYER_SET_SUBTITLESTREAM_VISIBLE, bVisible));
}
void CVideoPlayer::SetSubtitleVisibleInternal(bool bVisible)
{
m_VideoPlayerVideo->EnableSubtitle(bVisible);
if (m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
static_cast<CDVDInputStreamNavigator*>(m_pInputStream)->EnableSubtitleStream(bVisible);
}
int CVideoPlayer::GetAudioStreamCount()
{
return m_SelectionStreams.Count(STREAM_AUDIO);
}
int CVideoPlayer::GetAudioStream()
{
return m_SelectionStreams.IndexOf(STREAM_AUDIO, *this);
}
void CVideoPlayer::SetAudioStream(int iStream)
{
m_messenger.Put(new CDVDMsgPlayerSetAudioStream(iStream));
SynchronizeDemuxer(100);
}
int CVideoPlayer::GetVideoStreamCount() const
{
return m_SelectionStreams.Count(STREAM_VIDEO);
}
int CVideoPlayer::GetVideoStream() const
{
return m_SelectionStreams.IndexOf(STREAM_VIDEO, *this);
}
void CVideoPlayer::SetVideoStream(int iStream)
{
m_messenger.Put(new CDVDMsgPlayerSetVideoStream(iStream));
SynchronizeDemuxer(100);
}
TextCacheStruct_t* CVideoPlayer::GetTeletextCache()
{
if (m_CurrentTeletext.id < 0)
return 0;
return m_VideoPlayerTeletext->GetTeletextCache();
}
void CVideoPlayer::LoadPage(int p, int sp, unsigned char* buffer)
{
if (m_CurrentTeletext.id < 0)
return;
return m_VideoPlayerTeletext->LoadPage(p, sp, buffer);
}
std::string CVideoPlayer::GetRadioText(unsigned int line)
{
if (m_CurrentRadioRDS.id < 0)
return "";
return m_VideoPlayerRadioRDS->GetRadioText(line);
}
void CVideoPlayer::SeekTime(int64_t iTime)
{
int seekOffset = (int)(iTime - GetTime());
m_messenger.Put(new CDVDMsgPlayerSeek((int)iTime, true, true, true));
SynchronizeDemuxer(100);
m_callback.OnPlayBackSeek((int)iTime, seekOffset);
}
bool CVideoPlayer::SeekTimeRelative(int64_t iTime)
{
int64_t abstime = GetTime() + iTime;
m_messenger.Put(new CDVDMsgPlayerSeek((int)abstime, (iTime < 0) ? true : false, true, false));
SynchronizeDemuxer(100);
m_callback.OnPlayBackSeek((int)abstime, iTime);
return true;
}
// return the time in milliseconds
int64_t CVideoPlayer::GetTime()
{
CSingleLock lock(m_StateSection);
double offset = 0;
const double limit = DVD_MSEC_TO_TIME(500);
if (m_State.timestamp > 0)
{
offset = CDVDClock::GetAbsoluteClock() - m_State.timestamp;
offset *= m_playSpeed / DVD_PLAYSPEED_NORMAL;
if (offset > limit)
offset = limit;
if (offset < -limit)
offset = -limit;
}
return llrint(m_State.time + DVD_TIME_TO_MSEC(offset));
}
// return length in msec
int64_t CVideoPlayer::GetTotalTimeInMsec()
{
CSingleLock lock(m_StateSection);
return llrint(m_State.time_total);
}
// return length in seconds.. this should be changed to return in milleseconds throughout xbmc
int64_t CVideoPlayer::GetTotalTime()
{
return GetTotalTimeInMsec();
}
void CVideoPlayer::ToFFRW(int iSpeed)
{
// can't rewind in menu as seeking isn't possible
// forward is fine
if (iSpeed < 0 && IsInMenu()) return;
SetPlaySpeed(iSpeed * DVD_PLAYSPEED_NORMAL);
}
bool CVideoPlayer::OpenStream(CCurrentStream& current, int iStream, int source, bool reset)
{
CDemuxStream* stream = NULL;
CDVDStreamInfo hint;
CLog::Log(LOGNOTICE, "Opening stream: %i source: %i", iStream, source);
if(STREAM_SOURCE_MASK(source) == STREAM_SOURCE_DEMUX_SUB)
{
int index = m_SelectionStreams.IndexOf(current.type, source, iStream);
if(index < 0)
return false;
SelectionStream st = m_SelectionStreams.Get(current.type, index);
if(!m_pSubtitleDemuxer || m_pSubtitleDemuxer->GetFileName() != st.filename)
{
CLog::Log(LOGNOTICE, "Opening Subtitle file: %s", st.filename.c_str());
std::unique_ptr<CDVDDemuxVobsub> demux(new CDVDDemuxVobsub());
if(!demux->Open(st.filename, source, st.filename2))
return false;
m_pSubtitleDemuxer = demux.release();
}
double pts = m_VideoPlayerVideo->GetCurrentPts();
if(pts == DVD_NOPTS_VALUE)
pts = m_CurrentVideo.dts;
if(pts == DVD_NOPTS_VALUE)
pts = 0;
pts += m_offset_pts;
if (!m_pSubtitleDemuxer->SeekTime((int)(1000.0 * pts / (double)DVD_TIME_BASE)))
CLog::Log(LOGDEBUG, "%s - failed to start subtitle demuxing from: %f", __FUNCTION__, pts);
stream = m_pSubtitleDemuxer->GetStream(iStream);
if(!stream || stream->disabled)
return false;
stream->SetDiscard(AVDISCARD_NONE);
hint.Assign(*stream, true);
}
else if(STREAM_SOURCE_MASK(source) == STREAM_SOURCE_TEXT)
{
int index = m_SelectionStreams.IndexOf(current.type, source, iStream);
if(index < 0)
return false;
hint.Clear();
hint.filename = m_SelectionStreams.Get(current.type, index).filename;
hint.fpsscale = m_CurrentVideo.hint.fpsscale;
hint.fpsrate = m_CurrentVideo.hint.fpsrate;
}
else if(STREAM_SOURCE_MASK(source) == STREAM_SOURCE_DEMUX)
{
if(!m_pDemuxer)
return false;
stream = m_pDemuxer->GetStream(iStream);
if(!stream || stream->disabled)
return false;
stream->SetDiscard(AVDISCARD_NONE);
hint.Assign(*stream, true);
if(m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
hint.filename = "dvd";
}
else if(STREAM_SOURCE_MASK(source) == STREAM_SOURCE_VIDEOMUX)
{
if(!m_pCCDemuxer)
return false;
stream = m_pCCDemuxer->GetStream(iStream);
if(!stream || stream->disabled)
return false;
hint.Assign(*stream, false);
}
bool res;
switch(current.type)
{
case STREAM_AUDIO:
res = OpenAudioStream(hint, reset);
break;
case STREAM_VIDEO:
res = OpenVideoStream(hint, reset);
break;
case STREAM_SUBTITLE:
res = OpenSubtitleStream(hint);
break;
case STREAM_TELETEXT:
res = OpenTeletextStream(hint);
break;
case STREAM_RADIO_RDS:
res = OpenRadioRDSStream(hint);
break;
default:
res = false;
break;
}
if (res)
{
current.id = iStream;
current.source = source;
current.hint = hint;
current.stream = (void*)stream;
current.lastdts = DVD_NOPTS_VALUE;
if (current.avsync != CCurrentStream::AV_SYNC_FORCE)
current.avsync = CCurrentStream::AV_SYNC_CHECK;
if(stream)
current.changes = stream->changes;
}
else
{
if(stream)
{
/* mark stream as disabled, to disallaw further attempts*/
CLog::Log(LOGWARNING, "%s - Unsupported stream %d. Stream disabled.", __FUNCTION__, stream->iId);
stream->disabled = true;
stream->SetDiscard(AVDISCARD_ALL);
}
}
g_dataCacheCore.SignalAudioInfoChange();
g_dataCacheCore.SignalVideoInfoChange();
return res;
}
bool CVideoPlayer::OpenAudioStream(CDVDStreamInfo& hint, bool reset)
{
IDVDStreamPlayer* player = GetStreamPlayer(m_CurrentAudio.player);
if(player == nullptr)
return false;
if(m_CurrentAudio.id < 0 ||
m_CurrentAudio.hint != hint)
{
if (!player->OpenStream(hint))
return false;
static_cast<IDVDStreamPlayerAudio*>(player)->SetSpeed(m_streamPlayerSpeed);
m_CurrentAudio.syncState = IDVDStreamPlayer::SYNC_STARTING;
m_CurrentAudio.packets = 0;
}
else if (reset)
player->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_RESET), 0);
m_HasAudio = true;
return true;
}
bool CVideoPlayer::OpenVideoStream(CDVDStreamInfo& hint, bool reset)
{
if (m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
{
/* set aspect ratio as requested by navigator for dvd's */
float aspect = static_cast<CDVDInputStreamNavigator*>(m_pInputStream)->GetVideoAspectRatio();
if (aspect != 0.0)
{
hint.aspect = aspect;
hint.forced_aspect = true;
}
hint.dvd = true;
}
else if (m_pInputStream && m_pInputStream->IsStreamType(DVDSTREAM_TYPE_PVRMANAGER))
{
// set framerate if not set by demuxer
if (hint.fpsrate == 0 || hint.fpsscale == 0)
{
int fpsidx = CSettings::GetInstance().GetInt(CSettings::SETTING_PVRPLAYBACK_FPS);
if (fpsidx == 1)
{
hint.fpsscale = 1000;
hint.fpsrate = 50000;
}
else if (fpsidx == 2)
{
hint.fpsscale = 1001;
hint.fpsrate = 60000;
}
}
}
CDVDInputStream::IMenus* pMenus = dynamic_cast<CDVDInputStream::IMenus*>(m_pInputStream);
if(pMenus && pMenus->IsInMenu())
hint.stills = true;
if (hint.stereo_mode.empty())
hint.stereo_mode = CStereoscopicsManager::GetInstance().DetectStereoModeByString(m_item.GetPath());
SelectionStream& s = m_SelectionStreams.Get(STREAM_VIDEO, 0);
if(hint.flags & AV_DISPOSITION_ATTACHED_PIC)
return false;
// set desired refresh rate
if (m_PlayerOptions.fullscreen && g_graphicsContext.IsFullScreenRoot() &&
hint.fpsrate != 0 && hint.fpsscale != 0)
{
if (CSettings::GetInstance().GetInt(CSettings::SETTING_VIDEOPLAYER_ADJUSTREFRESHRATE) != ADJUST_REFRESHRATE_OFF)
{
float framerate = DVD_TIME_BASE / CDVDCodecUtils::NormalizeFrameduration((double)DVD_TIME_BASE * hint.fpsscale / hint.fpsrate);
m_renderManager.TriggerUpdateResolution(framerate, hint.width, RenderManager::GetStereoModeFlags(hint.stereo_mode));
}
}
IDVDStreamPlayer* player = GetStreamPlayer(m_CurrentVideo.player);
if(player == nullptr)
return false;
if(m_CurrentVideo.id < 0 ||
m_CurrentVideo.hint != hint)
{
if (hint.codec == AV_CODEC_ID_MPEG2VIDEO || hint.codec == AV_CODEC_ID_H264)
SAFE_DELETE(m_pCCDemuxer);
if (!player->OpenStream(hint))
return false;
s.stereo_mode = static_cast<IDVDStreamPlayerVideo*>(player)->GetStereoMode();
if (s.stereo_mode == "mono")
s.stereo_mode = "";
static_cast<IDVDStreamPlayerVideo*>(player)->SetSpeed(m_streamPlayerSpeed);
m_CurrentVideo.syncState = IDVDStreamPlayer::SYNC_STARTING;
m_CurrentVideo.packets = 0;
}
else if (reset)
player->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_RESET), 0);
m_HasVideo = true;
// open CC demuxer if video is mpeg2
if ((hint.codec == AV_CODEC_ID_MPEG2VIDEO || hint.codec == AV_CODEC_ID_H264) && !m_pCCDemuxer)
{
m_pCCDemuxer = new CDVDDemuxCC(hint.codec);
m_SelectionStreams.Clear(STREAM_NONE, STREAM_SOURCE_VIDEOMUX);
}
return true;
}
bool CVideoPlayer::OpenSubtitleStream(CDVDStreamInfo& hint)
{
IDVDStreamPlayer* player = GetStreamPlayer(m_CurrentSubtitle.player);
if(player == nullptr)
return false;
if(m_CurrentSubtitle.id < 0 ||
m_CurrentSubtitle.hint != hint)
{
if (!player->OpenStream(hint))
return false;
}
return true;
}
bool CVideoPlayer::AdaptForcedSubtitles()
{
bool valid = false;
SelectionStream ss = m_SelectionStreams.Get(STREAM_SUBTITLE, GetSubtitle());
if (ss.flags & CDemuxStream::FLAG_FORCED || !GetSubtitleVisible())
{
SelectionStream as = m_SelectionStreams.Get(STREAM_AUDIO, GetAudioStream());
SelectionStreams streams = m_SelectionStreams.Get(STREAM_SUBTITLE);
for(SelectionStreams::iterator it = streams.begin(); it != streams.end() && !valid; ++it)
{
if (it->flags & CDemuxStream::FLAG_FORCED && g_LangCodeExpander.CompareISO639Codes(it->language, as.language))
{
if(OpenStream(m_CurrentSubtitle, it->id, it->source))
{
valid = true;
SetSubtitleVisibleInternal(true);
}
}
}
if(!valid)
{
CloseStream(m_CurrentSubtitle, true);
SetSubtitleVisibleInternal(false);
}
}
return valid;
}
bool CVideoPlayer::OpenTeletextStream(CDVDStreamInfo& hint)
{
if (!m_VideoPlayerTeletext->CheckStream(hint))
return false;
IDVDStreamPlayer* player = GetStreamPlayer(m_CurrentTeletext.player);
if(player == nullptr)
return false;
if(m_CurrentTeletext.id < 0 ||
m_CurrentTeletext.hint != hint)
{
if (!player->OpenStream(hint))
return false;
}
return true;
}
bool CVideoPlayer::OpenRadioRDSStream(CDVDStreamInfo& hint)
{
if (!m_VideoPlayerRadioRDS->CheckStream(hint))
return false;
IDVDStreamPlayer* player = GetStreamPlayer(m_CurrentRadioRDS.player);
if(player == nullptr)
return false;
if(m_CurrentRadioRDS.id < 0 ||
m_CurrentRadioRDS.hint != hint)
{
if (!player->OpenStream(hint))
return false;
}
return true;
}
bool CVideoPlayer::CloseStream(CCurrentStream& current, bool bWaitForBuffers)
{
if (current.id < 0)
return false;
CLog::Log(LOGNOTICE, "Closing stream player %d", current.player);
if(bWaitForBuffers)
SetCaching(CACHESTATE_DONE);
IDVDStreamPlayer* player = GetStreamPlayer(current.player);
if(player)
{
if ((current.type == STREAM_AUDIO && current.syncState != IDVDStreamPlayer::SYNC_INSYNC) ||
(current.type == STREAM_VIDEO && current.syncState != IDVDStreamPlayer::SYNC_INSYNC))
bWaitForBuffers = false;
player->CloseStream(bWaitForBuffers);
}
current.Clear();
return true;
}
void CVideoPlayer::FlushBuffers(bool queued, double pts, bool accurate, bool sync)
{
CLog::Log(LOGDEBUG, "CVideoPlayer::FlushBuffers - flushing buffers");
double startpts;
if (accurate && !m_omxplayer_mode)
startpts = pts;
else
startpts = DVD_NOPTS_VALUE;
if (sync)
{
m_CurrentAudio.inited = false;
m_CurrentAudio.avsync = CCurrentStream::AV_SYNC_FORCE;
m_CurrentVideo.inited = false;
m_CurrentVideo.avsync = CCurrentStream::AV_SYNC_FORCE;
m_CurrentSubtitle.inited = false;
m_CurrentTeletext.inited = false;
m_CurrentRadioRDS.inited = false;
}
m_CurrentAudio.dts = DVD_NOPTS_VALUE;
m_CurrentAudio.startpts = startpts;
m_CurrentAudio.packets = 0;
m_CurrentVideo.dts = DVD_NOPTS_VALUE;
m_CurrentVideo.startpts = startpts;
m_CurrentVideo.packets = 0;
m_CurrentSubtitle.dts = DVD_NOPTS_VALUE;
m_CurrentSubtitle.startpts = startpts;
m_CurrentSubtitle.packets = 0;
m_CurrentTeletext.dts = DVD_NOPTS_VALUE;
m_CurrentTeletext.startpts = startpts;
m_CurrentTeletext.packets = 0;
m_CurrentRadioRDS.dts = DVD_NOPTS_VALUE;
m_CurrentRadioRDS.startpts = startpts;
m_CurrentRadioRDS.packets = 0;
if (queued)
{
m_VideoPlayerAudio->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_RESET));
m_VideoPlayerVideo->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_RESET));
m_VideoPlayerVideo->SendMessage(new CDVDMsg(CDVDMsg::VIDEO_NOSKIP));
m_VideoPlayerSubtitle->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_RESET));
m_VideoPlayerTeletext->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_RESET));
m_VideoPlayerRadioRDS->SendMessage(new CDVDMsg(CDVDMsg::GENERAL_RESET));
SynchronizePlayers(SYNCSOURCE_ALL);
}
else
{
m_VideoPlayerAudio->Flush(sync);
m_VideoPlayerVideo->Flush(sync);
m_VideoPlayerSubtitle->Flush();
m_VideoPlayerTeletext->Flush();
m_VideoPlayerRadioRDS->Flush();
// clear subtitle and menu overlays
m_overlayContainer.Clear();
if(m_playSpeed == DVD_PLAYSPEED_NORMAL
|| m_playSpeed == DVD_PLAYSPEED_PAUSE)
{
// make sure players are properly flushed, should put them in stalled state
CDVDMsgGeneralSynchronize* msg = new CDVDMsgGeneralSynchronize(1000, 0);
m_VideoPlayerAudio->SendMessage(msg->Acquire(), 1);
m_VideoPlayerVideo->SendMessage(msg->Acquire(), 1);
msg->Wait(&m_bStop, 0);
msg->Release();
// purge any pending PLAYER_STARTED messages
m_messenger.Flush(CDVDMsg::PLAYER_STARTED);
// we should now wait for init cache
SetCaching(CACHESTATE_FLUSH);
if (sync)
{
m_CurrentAudio.syncState = IDVDStreamPlayer::SYNC_STARTING;
m_CurrentVideo.syncState = IDVDStreamPlayer::SYNC_STARTING;
}
}
if(pts != DVD_NOPTS_VALUE && sync)
m_clock.Discontinuity(pts);
UpdatePlayState(0);
// update state, buffers are flushed and it may take some time until
// we get an update from players
CSingleLock lock(m_StateSection);
m_State = m_State;
}
if (m_omxplayer_mode)
{
m_OmxPlayerState.av_clock.OMXFlush();
if (!queued)
m_OmxPlayerState.av_clock.OMXStop();
m_OmxPlayerState.av_clock.OMXPause();
m_OmxPlayerState.av_clock.OMXMediaTime(0.0);
}
}
// since we call ffmpeg functions to decode, this is being called in the same thread as ::Process() is
int CVideoPlayer::OnDVDNavResult(void* pData, int iMessage)
{
if (m_pInputStream->IsStreamType(DVDSTREAM_TYPE_BLURAY))
{
if(iMessage == 0)
m_overlayContainer.Add((CDVDOverlay*)pData);
else if(iMessage == 1)
m_messenger.Put(new CDVDMsg(CDVDMsg::GENERAL_FLUSH));
else if(iMessage == 2)
m_dvd.iSelectedAudioStream = *(int*)pData;
else if(iMessage == 3)
m_dvd.iSelectedSPUStream = *(int*)pData;
else if(iMessage == 4)
m_VideoPlayerVideo->EnableSubtitle(*(int*)pData ? true: false);
else if(iMessage == 5)
{
if (m_dvd.state != DVDSTATE_STILL)
{
// else notify the player we have received a still frame
m_dvd.iDVDStillTime = *(int*)pData;
m_dvd.iDVDStillStartTime = XbmcThreads::SystemClockMillis();
/* adjust for the output delay in the video queue */
unsigned int time = 0;
if( m_CurrentVideo.stream && m_dvd.iDVDStillTime > 0 )
{
time = (unsigned int)(m_VideoPlayerVideo->GetOutputDelay() / ( DVD_TIME_BASE / 1000 ));
if( time < 10000 && time > 0 )
m_dvd.iDVDStillTime += time;
}
m_dvd.state = DVDSTATE_STILL;
CLog::Log(LOGDEBUG,
"DVDNAV_STILL_FRAME - waiting %i sec, with delay of %d sec",
m_dvd.iDVDStillTime, time / 1000);
}
}
else if (iMessage == 6)
{
m_dvd.state = DVDSTATE_NORMAL;
CLog::Log(LOGDEBUG, "CVideoPlayer::OnDVDNavResult - libbluray read error (DVDSTATE_NORMAL)");
CGUIDialogKaiToast::QueueNotification(g_localizeStrings.Get(25008), g_localizeStrings.Get(25009));
}
return 0;
}
if (m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
{
CDVDInputStreamNavigator* pStream = (CDVDInputStreamNavigator*)m_pInputStream;
switch (iMessage)
{
case DVDNAV_STILL_FRAME:
{
//CLog::Log(LOGDEBUG, "DVDNAV_STILL_FRAME");
dvdnav_still_event_t *still_event = (dvdnav_still_event_t *)pData;
// should wait the specified time here while we let the player running
// after that call dvdnav_still_skip(m_dvdnav);
if (m_dvd.state != DVDSTATE_STILL)
{
// else notify the player we have received a still frame
if(still_event->length < 0xff)
m_dvd.iDVDStillTime = still_event->length * 1000;
else
m_dvd.iDVDStillTime = 0;
m_dvd.iDVDStillStartTime = XbmcThreads::SystemClockMillis();
/* adjust for the output delay in the video queue */
unsigned int time = 0;
if( m_CurrentVideo.stream && m_dvd.iDVDStillTime > 0 )
{
time = (unsigned int)(m_VideoPlayerVideo->GetOutputDelay() / ( DVD_TIME_BASE / 1000 ));
if( time < 10000 && time > 0 )
m_dvd.iDVDStillTime += time;
}
m_dvd.state = DVDSTATE_STILL;
CLog::Log(LOGDEBUG,
"DVDNAV_STILL_FRAME - waiting %i sec, with delay of %d sec",
still_event->length, time / 1000);
}
return NAVRESULT_HOLD;
}
break;
case DVDNAV_SPU_CLUT_CHANGE:
{
m_VideoPlayerSubtitle->SendMessage(new CDVDMsgSubtitleClutChange((uint8_t*)pData));
}
break;
case DVDNAV_SPU_STREAM_CHANGE:
{
dvdnav_spu_stream_change_event_t* event = (dvdnav_spu_stream_change_event_t*)pData;
int iStream = event->physical_wide;
bool visible = !(iStream & 0x80);
SetSubtitleVisibleInternal(visible);
if (iStream >= 0)
m_dvd.iSelectedSPUStream = (iStream & ~0x80);
else
m_dvd.iSelectedSPUStream = -1;
m_CurrentSubtitle.stream = NULL;
}
break;
case DVDNAV_AUDIO_STREAM_CHANGE:
{
// This should be the correct way i think, however we don't have any streams right now
// since the demuxer hasn't started so it doesn't change. not sure how to do this.
dvdnav_audio_stream_change_event_t* event = (dvdnav_audio_stream_change_event_t*)pData;
// Tell system what audiostream should be opened by default
if (event->logical >= 0)
m_dvd.iSelectedAudioStream = event->physical;
else
m_dvd.iSelectedAudioStream = -1;
m_CurrentAudio.stream = NULL;
}
break;
case DVDNAV_HIGHLIGHT:
{
//dvdnav_highlight_event_t* pInfo = (dvdnav_highlight_event_t*)pData;
int iButton = pStream->GetCurrentButton();
CLog::Log(LOGDEBUG, "DVDNAV_HIGHLIGHT: Highlight button %d\n", iButton);
m_VideoPlayerSubtitle->UpdateOverlayInfo((CDVDInputStreamNavigator*)m_pInputStream, LIBDVDNAV_BUTTON_NORMAL);
}
break;
case DVDNAV_VTS_CHANGE:
{
//dvdnav_vts_change_event_t* vts_change_event = (dvdnav_vts_change_event_t*)pData;
CLog::Log(LOGDEBUG, "DVDNAV_VTS_CHANGE");
//Make sure we clear all the old overlays here, or else old forced items are left.
m_overlayContainer.Clear();
//Force an aspect ratio that is set in the dvdheaders if available
m_CurrentVideo.hint.aspect = pStream->GetVideoAspectRatio();
if( m_VideoPlayerVideo->IsInited() )
m_VideoPlayerVideo->SendMessage(new CDVDMsgDouble(CDVDMsg::VIDEO_SET_ASPECT, m_CurrentVideo.hint.aspect));
m_SelectionStreams.Clear(STREAM_NONE, STREAM_SOURCE_NAV);
m_SelectionStreams.Update(m_pInputStream, m_pDemuxer);
return NAVRESULT_HOLD;
}
break;
case DVDNAV_CELL_CHANGE:
{
//dvdnav_cell_change_event_t* cell_change_event = (dvdnav_cell_change_event_t*)pData;
CLog::Log(LOGDEBUG, "DVDNAV_CELL_CHANGE");
if (m_dvd.state != DVDSTATE_STILL)
m_dvd.state = DVDSTATE_NORMAL;
}
break;
case DVDNAV_NAV_PACKET:
{
//pci_t* pci = (pci_t*)pData;
// this should be possible to use to make sure we get
// seamless transitions over these boundaries
// if we remember the old vobunits boundaries
// when a packet comes out of demuxer that has
// pts values outside that boundary, it belongs
// to the new vobunit, wich has new timestamps
UpdatePlayState(0);
}
break;
case DVDNAV_HOP_CHANNEL:
{
// This event is issued whenever a non-seamless operation has been executed.
// Applications with fifos should drop the fifos content to speed up responsiveness.
CLog::Log(LOGDEBUG, "DVDNAV_HOP_CHANNEL");
if(m_dvd.state == DVDSTATE_SEEK)
m_dvd.state = DVDSTATE_NORMAL;
else
{
bool sync = !IsInMenuInternal();
FlushBuffers(false, DVD_NOPTS_VALUE, false, sync);
m_dvd.syncClock = true;
m_dvd.state = DVDSTATE_NORMAL;
if (m_pDemuxer)
m_pDemuxer->Flush();
}
return NAVRESULT_ERROR;
}
break;
case DVDNAV_STOP:
{
CLog::Log(LOGDEBUG, "DVDNAV_STOP");
m_dvd.state = DVDSTATE_NORMAL;
CGUIDialogKaiToast::QueueNotification(g_localizeStrings.Get(16026), g_localizeStrings.Get(16029));
}
break;
default:
{}
break;
}
}
return NAVRESULT_NOP;
}
bool CVideoPlayer::ShowPVRChannelInfo(void)
{
bool bReturn(false);
if (CSettings::GetInstance().GetInt(CSettings::SETTING_PVRMENU_DISPLAYCHANNELINFO) > 0)
{
g_PVRManager.ShowPlayerInfo(CSettings::GetInstance().GetInt(CSettings::SETTING_PVRMENU_DISPLAYCHANNELINFO));
bReturn = true;
}
return bReturn;
}
bool CVideoPlayer::OnAction(const CAction &action)
{
#define THREAD_ACTION(action) \
do { \
if (!IsCurrentThread()) { \
m_messenger.Put(new CDVDMsgType<CAction>(CDVDMsg::GENERAL_GUI_ACTION, action)); \
return true; \
} \
} while(false)
CDVDInputStream::IMenus* pMenus = dynamic_cast<CDVDInputStream::IMenus*>(m_pInputStream);
if (pMenus)
{
if (m_dvd.state == DVDSTATE_STILL && m_dvd.iDVDStillTime != 0 && pMenus->GetTotalButtons() == 0)
{
switch(action.GetID())
{
case ACTION_NEXT_ITEM:
case ACTION_MOVE_RIGHT:
case ACTION_MOVE_UP:
case ACTION_SELECT_ITEM:
{
THREAD_ACTION(action);
/* this will force us out of the stillframe */
CLog::Log(LOGDEBUG, "%s - User asked to exit stillframe", __FUNCTION__);
m_dvd.iDVDStillStartTime = 0;
m_dvd.iDVDStillTime = 1;
}
return true;
}
}
switch (action.GetID())
{
/* this code is disabled to allow switching playlist items (dvdimage "stacks") */
#if 0
case ACTION_PREV_ITEM: // SKIP-:
{
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - pushed prev");
pMenus->OnPrevious();
g_infoManager.SetDisplayAfterSeek();
return true;
}
break;
case ACTION_NEXT_ITEM: // SKIP+:
{
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - pushed next");
pMenus->OnNext();
g_infoManager.SetDisplayAfterSeek();
return true;
}
break;
#endif
case ACTION_SHOW_VIDEOMENU: // start button
{
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - go to menu");
pMenus->OnMenu();
if (m_playSpeed == DVD_PLAYSPEED_PAUSE)
{
SetPlaySpeed(DVD_PLAYSPEED_NORMAL);
m_callback.OnPlayBackResumed();
}
// send a message to everyone that we've gone to the menu
CGUIMessage msg(GUI_MSG_VIDEO_MENU_STARTED, 0, 0);
g_windowManager.SendThreadMessage(msg);
return true;
}
break;
}
if (pMenus->IsInMenu())
{
switch (action.GetID())
{
case ACTION_NEXT_ITEM:
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - pushed next in menu, stream will decide");
pMenus->OnNext();
g_infoManager.SetDisplayAfterSeek();
return true;
case ACTION_PREV_ITEM:
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - pushed prev in menu, stream will decide");
pMenus->OnPrevious();
g_infoManager.SetDisplayAfterSeek();
return true;
case ACTION_PREVIOUS_MENU:
case ACTION_NAV_BACK:
{
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - menu back");
pMenus->OnBack();
}
break;
case ACTION_MOVE_LEFT:
{
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - move left");
pMenus->OnLeft();
}
break;
case ACTION_MOVE_RIGHT:
{
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - move right");
pMenus->OnRight();
}
break;
case ACTION_MOVE_UP:
{
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - move up");
pMenus->OnUp();
}
break;
case ACTION_MOVE_DOWN:
{
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - move down");
pMenus->OnDown();
}
break;
case ACTION_MOUSE_MOVE:
case ACTION_MOUSE_LEFT_CLICK:
{
CRect rs, rd, rv;
m_renderManager.GetVideoRect(rs, rd, rv);
CPoint pt(action.GetAmount(), action.GetAmount(1));
if (!rd.PtInRect(pt))
return false; // out of bounds
THREAD_ACTION(action);
// convert to video coords...
pt -= CPoint(rd.x1, rd.y1);
pt.x *= rs.Width() / rd.Width();
pt.y *= rs.Height() / rd.Height();
pt += CPoint(rs.x1, rs.y1);
if (action.GetID() == ACTION_MOUSE_LEFT_CLICK)
{
if (pMenus->OnMouseClick(pt))
return true;
else
{
CApplicationMessenger::GetInstance().PostMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1, static_cast<void*>(new CAction(ACTION_TRIGGER_OSD)));
return false;
}
}
return pMenus->OnMouseMove(pt);
}
break;
case ACTION_SELECT_ITEM:
{
THREAD_ACTION(action);
CLog::Log(LOGDEBUG, " - button select");
// show button pushed overlay
if(m_pInputStream->IsStreamType(DVDSTREAM_TYPE_DVD))
m_VideoPlayerSubtitle->UpdateOverlayInfo((CDVDInputStreamNavigator*)m_pInputStream, LIBDVDNAV_BUTTON_CLICKED);
pMenus->ActivateButton();
}
break;
case REMOTE_0:
case REMOTE_1:
case REMOTE_2:
case REMOTE_3:
case REMOTE_4:
case REMOTE_5:
case REMOTE_6:
case REMOTE_7:
case REMOTE_8:
case REMOTE_9:
{
THREAD_ACTION(action);
// Offset from key codes back to button number
int button = action.GetID() - REMOTE_0;
CLog::Log(LOGDEBUG, " - button pressed %d", button);
pMenus->SelectButton(button);
}
break;
default:
return false;
break;
}
return true; // message is handled
}
}
if (dynamic_cast<CDVDInputStreamPVRManager*>(m_pInputStream))
{
switch (action.GetID())
{
case ACTION_MOVE_UP:
case ACTION_NEXT_ITEM:
case ACTION_CHANNEL_UP:
{
bool bPreview(action.GetID() == ACTION_MOVE_UP && // only up/down shows a preview, all others do switch
CSettings::GetInstance().GetBool(CSettings::SETTING_PVRPLAYBACK_CONFIRMCHANNELSWITCH));
if (bPreview)
m_messenger.Put(new CDVDMsg(CDVDMsg::PLAYER_CHANNEL_PREVIEW_NEXT));
else
{
m_messenger.Put(new CDVDMsg(CDVDMsg::PLAYER_CHANNEL_NEXT));
if (CSettings::GetInstance().GetInt(CSettings::SETTING_PVRPLAYBACK_CHANNELENTRYTIMEOUT) == 0)
g_infoManager.SetDisplayAfterSeek();
}
ShowPVRChannelInfo();
return true;
}
case ACTION_MOVE_DOWN:
case ACTION_PREV_ITEM:
case ACTION_CHANNEL_DOWN:
{
bool bPreview(action.GetID() == ACTION_MOVE_DOWN && // only up/down shows a preview, all others do switch
CSettings::GetInstance().GetBool(CSettings::SETTING_PVRPLAYBACK_CONFIRMCHANNELSWITCH));
if (bPreview)
m_messenger.Put(new CDVDMsg(CDVDMsg::PLAYER_CHANNEL_PREVIEW_PREV));
else
{
m_messenger.Put(new CDVDMsg(CDVDMsg::PLAYER_CHANNEL_PREV));
if (CSettings::GetInstance().GetInt(CSettings::SETTING_PVRPLAYBACK_CHANNELENTRYTIMEOUT) == 0)
g_infoManager.SetDisplayAfterSeek();
}
ShowPVRChannelInfo();
return true;
}
case ACTION_CHANNEL_SWITCH:
{
// Offset from key codes back to button number
int channel = (int) action.GetAmount();
m_messenger.Put(new CDVDMsgInt(CDVDMsg::PLAYER_CHANNEL_SELECT_NUMBER, channel));
g_infoManager.SetDisplayAfterSeek();
ShowPVRChannelInfo();
return true;
}
break;
}
}
switch (action.GetID())
{
case ACTION_NEXT_ITEM:
if (GetChapter() > 0 && GetChapter() < GetChapterCount())
{
m_messenger.Put(new CDVDMsgPlayerSeekChapter(GetChapter() + 1));
g_infoManager.SetDisplayAfterSeek();
return true;
}
else
break;
case ACTION_PREV_ITEM:
if (GetChapter() > 0)
{
m_messenger.Put(new CDVDMsgPlayerSeekChapter(GetChapter() - 1));
g_infoManager.SetDisplayAfterSeek();
return true;
}
else
break;
}
// return false to inform the caller we didn't handle the message
return false;
}
bool CVideoPlayer::IsInMenuInternal() const
{
CDVDInputStream::IMenus* pStream = dynamic_cast<CDVDInputStream::IMenus*>(m_pInputStream);
if (pStream)
{
if (m_dvd.state == DVDSTATE_STILL)
return true;
else
return pStream->IsInMenu();
}
return false;
}
bool CVideoPlayer::IsInMenu() const
{
CSingleLock lock(m_StateSection);
return m_State.isInMenu;
}
bool CVideoPlayer::HasMenu() const
{
CSingleLock lock(m_StateSection);
return m_State.hasMenu;
}
std::string CVideoPlayer::GetPlayerState()
{
CSingleLock lock(m_StateSection);
return m_State.player_state;
}
bool CVideoPlayer::SetPlayerState(const std::string& state)
{
m_messenger.Put(new CDVDMsgPlayerSetState(state));
return true;
}
int CVideoPlayer::GetChapterCount()
{
CSingleLock lock(m_StateSection);
return m_State.chapters.size();
}
int CVideoPlayer::GetChapter()
{
CSingleLock lock(m_StateSection);
return m_State.chapter;
}
void CVideoPlayer::GetChapterName(std::string& strChapterName, int chapterIdx)
{
CSingleLock lock(m_StateSection);
if (chapterIdx == -1 && m_State.chapter > 0 && m_State.chapter <= (int) m_State.chapters.size())
strChapterName = m_State.chapters[m_State.chapter - 1].first;
else if (chapterIdx > 0 && chapterIdx <= (int) m_State.chapters.size())
strChapterName = m_State.chapters[chapterIdx - 1].first;
}
int CVideoPlayer::SeekChapter(int iChapter)
{
if (GetChapter() > 0)
{
if (iChapter < 0)
iChapter = 0;
if (iChapter > GetChapterCount())
return 0;
// Seek to the chapter.
m_messenger.Put(new CDVDMsgPlayerSeekChapter(iChapter));
SynchronizeDemuxer(100);
}
return 0;
}
int64_t CVideoPlayer::GetChapterPos(int chapterIdx)
{
CSingleLock lock(m_StateSection);
if (chapterIdx > 0 && chapterIdx <= (int) m_State.chapters.size())
return m_State.chapters[chapterIdx - 1].second;
return -1;
}
void CVideoPlayer::AddSubtitle(const std::string& strSubPath)
{
m_messenger.Put(new CDVDMsgType<std::string>(CDVDMsg::SUBTITLE_ADDFILE, strSubPath));
}
int CVideoPlayer::GetCacheLevel() const
{
CSingleLock lock(m_StateSection);
return (int)(m_State.cache_level * 100);
}
double CVideoPlayer::GetQueueTime()
{
int a = m_VideoPlayerAudio->GetLevel();
int v = m_VideoPlayerVideo->GetLevel();
return std::max(a, v) * 8000.0 / 100;
}
void CVideoPlayer::GetVideoStreamInfo(int streamId, SPlayerVideoStreamInfo &info)
{
CSingleLock lock(m_SelectionStreams.m_section);
if (streamId == CURRENT_STREAM)
streamId = GetVideoStream();
if (streamId < 0 || streamId > GetVideoStreamCount() - 1)
return;
SelectionStream& s = m_SelectionStreams.Get(STREAM_VIDEO, streamId);
if (s.language.length() > 0)
info.language = s.language;
if (s.name.length() > 0)
info.name = s.name;
info.bitrate = s.bitrate;
info.width = s.width;
info.height = s.height;
info.SrcRect = s.SrcRect;
info.DestRect = s.DestRect;
info.videoCodecName = s.codec;
info.videoAspectRatio = s.aspect_ratio;
info.stereoMode = s.stereo_mode;
}
int CVideoPlayer::GetSourceBitrate()
{
if (m_pInputStream)
return (int)m_pInputStream->GetBitstreamStats().GetBitrate();
return 0;
}
void CVideoPlayer::GetAudioStreamInfo(int index, SPlayerAudioStreamInfo &info)
{
CSingleLock lock(m_SelectionStreams.m_section);
if (index == CURRENT_STREAM)
index = GetAudioStream();
if (index < 0 || index > GetAudioStreamCount() - 1 )
return;
SelectionStream& s = m_SelectionStreams.Get(STREAM_AUDIO, index);
if(s.language.length() > 0)
info.language = s.language;
if(s.name.length() > 0)
info.name = s.name;
if(s.type == STREAM_NONE)
info.name += " (Invalid)";
info.bitrate = s.bitrate;
info.channels = s.channels;
info.audioCodecName = s.codec;
}
int CVideoPlayer::AddSubtitleFile(const std::string& filename, const std::string& subfilename)
{
std::string ext = URIUtils::GetExtension(filename);
std::string vobsubfile = subfilename;
if (ext == ".idx")
{
if (vobsubfile.empty()) {
// find corresponding .sub (e.g. in case of manually selected .idx sub)
vobsubfile = CUtil::GetVobSubSubFromIdx(filename);
if (vobsubfile.empty())
return -1;
}
CDVDDemuxVobsub v;
if (!v.Open(filename, STREAM_SOURCE_NONE, vobsubfile))
return -1;
m_SelectionStreams.Update(NULL, &v, vobsubfile);
ExternalStreamInfo info;
CUtil::GetExternalStreamDetailsFromFilename(m_item.GetPath(), vobsubfile, info);
for (int i = 0; i < v.GetNrOfSubtitleStreams(); ++i)
{
int index = m_SelectionStreams.IndexOf(STREAM_SUBTITLE, m_SelectionStreams.Source(STREAM_SOURCE_DEMUX_SUB, filename), i);
SelectionStream& stream = m_SelectionStreams.Get(STREAM_SUBTITLE, index);
if (stream.name.empty())
stream.name = info.name;
if (stream.language.empty())
stream.language = info.language;
if (static_cast<CDemuxStream::EFlags>(info.flag) != CDemuxStream::FLAG_NONE)
stream.flags = static_cast<CDemuxStream::EFlags>(info.flag);
}
return m_SelectionStreams.IndexOf(STREAM_SUBTITLE, m_SelectionStreams.Source(STREAM_SOURCE_DEMUX_SUB, filename), 0);
}
if(ext == ".sub")
{
// if this looks like vobsub file (i.e. .idx found), add it as such
std::string vobsubidx = CUtil::GetVobSubIdxFromSub(filename);
if (!vobsubidx.empty())
return AddSubtitleFile(vobsubidx, filename);
}
SelectionStream s;
s.source = m_SelectionStreams.Source(STREAM_SOURCE_TEXT, filename);
s.type = STREAM_SUBTITLE;
s.id = 0;
s.filename = filename;
ExternalStreamInfo info;
CUtil::GetExternalStreamDetailsFromFilename(m_item.GetPath(), filename, info);
s.name = info.name;
s.language = info.language;
if (static_cast<CDemuxStream::EFlags>(info.flag) != CDemuxStream::FLAG_NONE)
s.flags = static_cast<CDemuxStream::EFlags>(info.flag);
m_SelectionStreams.Update(s);
return m_SelectionStreams.IndexOf(STREAM_SUBTITLE, s.source, s.id);
}
void CVideoPlayer::UpdatePlayState(double timeout)
{
if(m_State.timestamp != 0
&& m_State.timestamp + DVD_MSEC_TO_TIME(timeout) > CDVDClock::GetAbsoluteClock())
return;
SPlayerState state(m_State);
if (m_CurrentVideo.dts != DVD_NOPTS_VALUE)
state.dts = m_CurrentVideo.dts;
else if (m_CurrentAudio.dts != DVD_NOPTS_VALUE)
state.dts = m_CurrentAudio.dts;
else if (m_CurrentVideo.startpts != DVD_NOPTS_VALUE)
state.dts = m_CurrentVideo.startpts;
else if (m_CurrentAudio.startpts != DVD_NOPTS_VALUE)
state.dts = m_CurrentAudio.startpts;
if (m_pDemuxer)
{
if (IsInMenuInternal())
state.chapter = 0;
else
state.chapter = m_pDemuxer->GetChapter();
state.chapters.clear();
if (m_pDemuxer->GetChapterCount() > 0)
{
for (int i = 0; i < m_pDemuxer->GetChapterCount(); ++i)
{
std::string name;
m_pDemuxer->GetChapterName(name, i + 1);
state.chapters.push_back(make_pair(name, m_pDemuxer->GetChapterPos(i + 1)));
}
}
// time = dts - m_offset_pts
state.time = DVD_TIME_TO_MSEC(m_clock.GetClock(false));
state.time_offset = 0;
state.time_total = m_pDemuxer->GetStreamLength();
}
state.canpause = true;
state.canseek = true;
state.isInMenu = false;
state.hasMenu = false;
if (m_pInputStream)
{
// override from input stream if needed
CDVDInputStreamPVRManager* pvrStream = dynamic_cast<CDVDInputStreamPVRManager*>(m_pInputStream);
if (pvrStream)
{
state.canrecord = pvrStream->CanRecord();
state.recording = pvrStream->IsRecording();
}
CDVDInputStream::IDisplayTime* pDisplayTime = m_pInputStream->GetIDisplayTime();
if (pDisplayTime && pDisplayTime->GetTotalTime() > 0)
{
if (state.dts != DVD_NOPTS_VALUE)
{
// dts is correct by offset_pts, so we need to revert this correction here
// the results is: time = pDisplayTime->GetTime()
state.time_offset += DVD_MSEC_TO_TIME(pDisplayTime->GetTime()) - state.dts + m_offset_pts;
state.time += DVD_TIME_TO_MSEC(state.time_offset);
}
state.time_total = pDisplayTime->GetTotalTime();
}
if (CDVDInputStream::IMenus* ptr = dynamic_cast<CDVDInputStream::IMenus*>(m_pInputStream))
{
if (!ptr->GetState(state.player_state))
state.player_state = "";
if (m_dvd.state == DVDSTATE_STILL)
{
state.time = XbmcThreads::SystemClockMillis() - m_dvd.iDVDStillStartTime;
state.time_total = m_dvd.iDVDStillTime;
state.isInMenu = true;
}
else if (IsInMenuInternal())
{
state.time = pDisplayTime->GetTime();
state.time_offset = 0;
state.isInMenu = true;
}
state.hasMenu = true;
}
state.canpause = m_pInputStream->CanPause();
state.canseek = m_pInputStream->CanSeek();
}
if (m_Edl.HasCut())
{
state.time = (double) m_Edl.RemoveCutTime(llrint(state.time));
state.time_total = (double) m_Edl.RemoveCutTime(llrint(state.time_total));
}
if(state.time_total <= 0)
state.canseek = false;
if (m_CurrentAudio.id >= 0 && m_pDemuxer)
{
CDemuxStream* pStream = m_pDemuxer->GetStream(m_CurrentAudio.id);
if (pStream && pStream->type == STREAM_AUDIO)
state.demux_audio = ((CDemuxStreamAudio*)pStream)->GetStreamInfo();
}
else
state.demux_audio = "";
if (m_CurrentVideo.id >= 0 && m_pDemuxer)
{
CDemuxStream* pStream = m_pDemuxer->GetStream(m_CurrentVideo.id);
if (pStream && pStream->type == STREAM_VIDEO)
state.demux_video = ((CDemuxStreamVideo*)pStream)->GetStreamInfo();
}
else
state.demux_video = "";
double level, delay, offset;
if(GetCachingTimes(level, delay, offset))
{
state.cache_delay = std::max(0.0, delay);
state.cache_level = std::max(0.0, std::min(1.0, level));
state.cache_offset = offset;
}
else
{
state.cache_delay = 0.0;
state.cache_level = std::min(1.0, GetQueueTime() / 8000.0);
state.cache_offset = GetQueueTime() / state.time_total;
}
XFILE::SCacheStatus status;
if(m_pInputStream && m_pInputStream->GetCacheStatus(&status))
{
state.cache_bytes = status.forward;
if(state.time_total)
state.cache_bytes += m_pInputStream->GetLength() * (int64_t) (GetQueueTime() / state.time_total);
}
else
state.cache_bytes = 0;
state.timestamp = CDVDClock::GetAbsoluteClock();
CSingleLock lock(m_StateSection);
m_State = state;
}
void CVideoPlayer::UpdateApplication(double timeout)
{
if(m_UpdateApplication != 0
&& m_UpdateApplication + DVD_MSEC_TO_TIME(timeout) > CDVDClock::GetAbsoluteClock())
return;
CDVDInputStreamPVRManager* pStream = dynamic_cast<CDVDInputStreamPVRManager*>(m_pInputStream);
if(pStream)
{
CFileItem item(g_application.CurrentFileItem());
if(pStream->UpdateItem(item))
{
g_application.CurrentFileItem() = item;
CApplicationMessenger::GetInstance().PostMsg(TMSG_UPDATE_CURRENT_ITEM, 0, -1, static_cast<void*>(new CFileItem(item)));
}
}
m_UpdateApplication = CDVDClock::GetAbsoluteClock();
}
bool CVideoPlayer::CanRecord()
{
CSingleLock lock(m_StateSection);
return m_State.canrecord;
}
bool CVideoPlayer::IsRecording()
{
CSingleLock lock(m_StateSection);
return m_State.recording;
}
bool CVideoPlayer::Record(bool bOnOff)
{
if (m_pInputStream && (m_pInputStream->IsStreamType(DVDSTREAM_TYPE_TV) ||
m_pInputStream->IsStreamType(DVDSTREAM_TYPE_PVRMANAGER)) )
{
m_messenger.Put(new CDVDMsgBool(CDVDMsg::PLAYER_SET_RECORD, bOnOff));
return true;
}
return false;
}
bool CVideoPlayer::GetStreamDetails(CStreamDetails &details)
{
if (m_pDemuxer)
{
std::vector<SelectionStream> subs = m_SelectionStreams.Get(STREAM_SUBTITLE);
std::vector<CStreamDetailSubtitle> extSubDetails;
for (unsigned int i = 0; i < subs.size(); i++)
{
if (subs[i].filename == m_item.GetPath())
continue;
CStreamDetailSubtitle p;
p.m_strLanguage = subs[i].language;
extSubDetails.push_back(p);
}
bool result = CDVDFileInfo::DemuxerToStreamDetails(m_pInputStream, m_pDemuxer, extSubDetails, details);
if (result && details.GetStreamCount(CStreamDetail::VIDEO) > 0) // this is more correct (dvds in particular)
{
/*
* We can only obtain the aspect & duration from VideoPlayer when the Process() thread is running
* and UpdatePlayState() has been called at least once. In this case VideoPlayer duration/AR will
* return 0 and we'll have to fallback to the (less accurate) info from the demuxer.
*/
float aspect = m_renderManager.GetAspectRatio();
if (aspect > 0.0f)
((CStreamDetailVideo*)details.GetNthStream(CStreamDetail::VIDEO,0))->m_fAspect = aspect;
int64_t duration = GetTotalTime() / 1000;
if (duration > 0)
((CStreamDetailVideo*)details.GetNthStream(CStreamDetail::VIDEO,0))->m_iDuration = (int) duration;
}
return result;
}
else
return false;
}
std::string CVideoPlayer::GetPlayingTitle()
{
/* Currently we support only Title Name from Teletext line 30 */
TextCacheStruct_t* ttcache = m_VideoPlayerTeletext->GetTeletextCache();
if (ttcache && !ttcache->line30.empty())
return ttcache->line30;
return "";
}
bool CVideoPlayer::SwitchChannel(const CPVRChannelPtr &channel)
{
if (g_PVRManager.IsPlayingChannel(channel))
return false; // desired channel already active, nothing to do.
if (!g_PVRManager.CheckParentalLock(channel))
return false;
/* set GUI info */
if (!g_PVRManager.PerformChannelSwitch(channel, true))
return false;
UpdateApplication(0);
UpdatePlayState(0);
/* select the new channel */
m_messenger.Put(new CDVDMsgType<CPVRChannelPtr>(CDVDMsg::PLAYER_CHANNEL_SELECT, channel));
return true;
}
void CVideoPlayer::FrameMove()
{
m_renderManager.FrameMove();
}
void CVideoPlayer::FrameWait(int ms)
{
m_renderManager.FrameWait(ms);
}
bool CVideoPlayer::HasFrame()
{
return m_renderManager.HasFrame();
}
void CVideoPlayer::Render(bool clear, uint32_t alpha, bool gui)
{
m_renderManager.Render(clear, 0, alpha, gui);
}
void CVideoPlayer::AfterRender()
{
m_renderManager.FrameFinish();
}
void CVideoPlayer::FlushRenderer()
{
m_renderManager.Flush();
}
void CVideoPlayer::SetRenderViewMode(int mode)
{
m_renderManager.SetViewMode(mode);
}
float CVideoPlayer::GetRenderAspectRatio()
{
return m_renderManager.GetAspectRatio();
}
RESOLUTION CVideoPlayer::GetRenderResolution()
{
return g_graphicsContext.GetVideoResolution();
}
void CVideoPlayer::TriggerUpdateResolution()
{
m_renderManager.TriggerUpdateResolution(0, 0, 0);
}
bool CVideoPlayer::IsRenderingVideo()
{
return m_renderManager.IsConfigured();
}
bool CVideoPlayer::IsRenderingGuiLayer()
{
return m_renderManager.IsGuiLayer();
}
bool CVideoPlayer::IsRenderingVideoLayer()
{
return m_renderManager.IsVideoLayer();
}
bool CVideoPlayer::Supports(EDEINTERLACEMODE mode)
{
return m_renderManager.Supports(mode);
}
bool CVideoPlayer::Supports(EINTERLACEMETHOD method)
{
return m_renderManager.Supports(method);
}
bool CVideoPlayer::Supports(ESCALINGMETHOD method)
{
return m_renderManager.Supports(method);
}
bool CVideoPlayer::Supports(ERENDERFEATURE feature)
{
return m_renderManager.Supports(feature);
}
unsigned int CVideoPlayer::RenderCaptureAlloc()
{
return m_renderManager.AllocRenderCapture();
}
void CVideoPlayer::RenderCapture(unsigned int captureId, unsigned int width, unsigned int height, int flags)
{
m_renderManager.StartRenderCapture(captureId, width, height, flags);
}
void CVideoPlayer::RenderCaptureRelease(unsigned int captureId)
{
m_renderManager.ReleaseRenderCapture(captureId);
}
bool CVideoPlayer::RenderCaptureGetPixels(unsigned int captureId, unsigned int millis, uint8_t *buffer, unsigned int size)
{
return m_renderManager.RenderCaptureGetPixels(captureId, millis, buffer, size);
}
std::string CVideoPlayer::GetRenderVSyncState()
{
return m_renderManager.GetVSyncState();
}
void CVideoPlayer::VideoParamsChange()
{
m_messenger.Put(new CDVDMsg(CDVDMsg::PLAYER_AVCHANGE));
}
// IDispResource interface
void CVideoPlayer::OnLostDisplay()
{
CLog::Log(LOGNOTICE, "VideoPlayer: OnLostDisplay received");
m_displayLost = true;
}
void CVideoPlayer::OnResetDisplay()
{
CLog::Log(LOGNOTICE, "VideoPlayer: OnResetDisplay received");
m_displayLost = false;
}
| pbureau/xbmc | xbmc/cores/VideoPlayer/VideoPlayer.cpp | C++ | gpl-2.0 | 159,051 |
<?php
/**
* Odin_Theme_Options class.
*
* Built settings page.
*
* @package Odin
* @category Options
* @author WPBrasil
* @version 2.1.4
*/
class Brasa_Request_A_Quote_Options {
/**
* Settings tabs.
*
* @var array
*/
protected $tabs = array();
/**
* Settings fields.
*
* @var array
*/
protected $fields = array();
/**
* Settings construct.
*
* @param string $id Page id.
* @param string $title Page title.
* @param string $capability User capability.
*/
public function __construct( $id, $title, $capability = 'manage_options' ) {
$this->id = $id;
$this->title = $title;
$this->capability = $capability;
// Actions.
add_action( 'admin_menu', array( &$this, 'add_page' ) );
add_action( 'admin_init', array( &$this, 'create_settings' ) );
add_action( 'admin_enqueue_scripts', array( &$this, 'scripts' ) );
}
/**
* Add Settings Theme page.
*/
public function add_page() {
add_submenu_page(
'woocommerce',
$this->title,
$this->title,
$this->capability,
$this->id,
array( &$this, 'settings_page' )
);
}
/**
* Load options scripts.
*/
function scripts() {
// Checks if is the settings page.
if ( isset( $_GET['page'] ) && $this->id == $_GET['page'] ) {
// Color Picker.
wp_enqueue_style( 'wp-color-picker' );
wp_enqueue_script( 'wp-color-picker' );
// Media Upload.
wp_enqueue_media();
// jQuery UI.
wp_enqueue_script( 'jquery-ui-sortable' );
}
}
/**
* Set settings tabs.
*
* @param array $tabs Settings tabs.
*/
public function set_tabs( $tabs ) {
$this->tabs = $tabs;
}
/**
* Set settings fields
*
* @param array $fields Settings fields.
*/
public function set_fields( $fields ) {
$this->fields = $fields;
}
/**
* Get current tab.
*
* @return string Current tab ID.
*/
protected function get_current_tab() {
if ( isset( $_GET['tab'] ) ) {
$current_tab = $_GET['tab'];
} else {
$current_tab = $this->tabs[0]['id'];
}
return $current_tab;
}
/**
* Get the menu current URL.
*
* @return string Current URL.
*/
private function get_current_url() {
$url = 'http';
if ( isset( $_SERVER['HTTPS'] ) && 'on' == $_SERVER['HTTPS'] ) {
$url .= 's';
}
$url .= '://';
if ( '80' != $_SERVER['SERVER_PORT'] ) {
$url .= $_SERVER['SERVER_NAME'] . ' : ' . $_SERVER['SERVER_PORT'] . $_SERVER['PHP_SELF'];
} else {
$url .= $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
}
return esc_url( $url );
}
/**
* Get tab navigation.
*
* @param string $current_tab Current tab ID.
*
* @return string Tab Navigation.
*/
protected function get_navigation( $current_tab ) {
$html = '<h2 class="nav-tab-wrapper">';
foreach ( $this->tabs as $tab ) {
$current = ( $current_tab == $tab['id'] ) ? ' nav-tab-active' : '';
$html .= sprintf( '<a href="?page=%s&tab=%s" class="nav-tab%s">%s</a>', $this->id, $tab['id'], $current, $tab['title'] );
}
$html .= '</h2>';
echo $html;
}
/**
* Built settings page.
*/
public function settings_page() {
// Get current tag.
$current_tab = $this->get_current_tab();
// Opens the wrap.
echo '<div class="wrap">';
// Display the navigation menu.
$this->get_navigation( $current_tab );
// Display erros.
settings_errors();
// Creates the option form.
echo '<form method="post" action="options.php">';
foreach ( $this->tabs as $tabs ) {
if ( $current_tab == $tabs['id'] ) {
// Prints nonce, action and options_page fields.
settings_fields( $tabs['id'] );
// Prints settings sections and settings fields.
do_settings_sections( $tabs['id'] );
break;
}
}
// Display submit button.
submit_button();
// Closes the form.
echo '</form>';
// Closes the wrap.
echo '</div>';
}
/**
* Create settings.
*/
public function create_settings() {
// Register settings fields.
foreach ( $this->fields as $section => $items ) {
// Register settings sections.
add_settings_section(
$section,
$items['title'],
'__return_false',
$items['tab']
);
foreach ( $items['fields'] as $option ) {
$type = isset( $option['type'] ) ? $option['type'] : 'text';
$args = array(
'id' => $option['id'],
'tab' => $items['tab'],
'section' => $section,
'options' => isset( $option['options'] ) ? $option['options'] : '',
'default' => isset( $option['default'] ) ? $option['default'] : '',
'attributes' => isset( $option['attributes'] ) ? $option['attributes'] : array(),
'description' => isset( $option['description'] ) ? $option['description'] : ''
);
add_settings_field(
$option['id'],
$option['label'],
array( &$this, 'callback_' . $type ),
$items['tab'],
$section,
$args
);
}
}
// Register settings.
foreach ( $this->tabs as $tabs ) {
register_setting( $tabs['id'], $tabs['id'], array( &$this, 'validate_input' ) );
}
}
/**
* Get Option.
*
* @param string $tab Tab that the option belongs
* @param string $id Option ID.
* @param string $default Default option.
*
* @return array Item options.
*/
protected function get_option( $tab, $id, $default = '' ) {
$options = get_option( $tab );
if ( isset( $options[ $id ] ) ) {
$default = $options[ $id ];
}
return $default;
}
/**
* Build field attributes.
*
* @param array $attrs Attributes as array.
*
* @return string Attributes as string.
*/
protected function build_field_attributes( $attrs ) {
$attributes = '';
if ( ! empty( $attrs ) ) {
foreach ( $attrs as $key => $attr ) {
$attributes .= ' ' . $key . '="' . $attr . '"';
}
}
return $attributes;
}
/**
* Input field callback.
*
* @param array $args Arguments from the option.
*
* @return string Input field HTML.
*/
public function callback_input( $args ) {
$tab = $args['tab'];
$id = $args['id'];
$attrs = $args['attributes'];
// Sets default type.
if ( ! isset( $attrs['type'] ) ) {
$attrs['type'] = 'text';
}
// Sets current option.
$current = esc_html( $this->get_option( $tab, $id, $args['default'] ) );
$html = sprintf( '<input id="%1$s" name="%2$s[%1$s]" value="%3$s"%4$s />', $id, $tab, $current, $this->build_field_attributes( $attrs ) );
// Displays the description.
if ( $args['description'] ) {
$html .= sprintf( '<p class="description">%s</p>', $args['description'] );
}
echo $html;
}
/**
* Text field callback.
*
* @param array $args Arguments from the option.
*
* @return string Text field HTML.
*/
public function callback_text( $args ) {
// Sets regular text class.
$args['attributes']['class'] = 'regular-text';
$this->callback_input( $args );
}
/**
* Textarea field callback.
*
* @param array $args Arguments from the option.
*
* @return string Textarea field HTML.
*/
public function callback_textarea( $args ) {
$tab = $args['tab'];
$id = $args['id'];
$attrs = $args['attributes'];
if ( ! isset( $attrs['cols'] ) ) {
$attrs['cols'] = '60';
}
if ( ! isset( $attrs['rows'] ) ) {
$attrs['rows'] = '5';
}
// Sets current option.
$current = esc_textarea( $this->get_option( $tab, $id, $args['default'] ) );
$html = sprintf( '<textarea id="%1$s" name="%2$s[%1$s]"%4$s>%3$s</textarea>', $id, $tab, $current, $this->build_field_attributes( $attrs ) );
// Displays the description.
if ( $args['description'] ) {
$html .= sprintf( '<p class="description">%s</p>', $args['description'] );
}
echo $html;
}
/**
* Editor field callback.
*
* @param array $args Arguments from the option.
*
* @return string Editor field HTML.
*/
public function callback_editor( $args ) {
$tab = $args['tab'];
$id = $args['id'];
$options = $args['options'];
// Sets current option.
$current = wpautop( $this->get_option( $tab, $id, $args['default'] ) );
// Set default options.
if ( empty( $options ) ) {
$options = array( 'textarea_rows' => 10 );
}
$options[ 'textarea_name' ] = $tab . '[' . $id . ']';
echo '<div style="width: 600px;">';
wp_editor( $current, $id, $options );
echo '</div>';
// Displays the description.
if ( $args['description'] ) {
echo sprintf( '<p class="description">%s</p>', $args['description'] );
}
}
/**
* Checkbox field callback.
*
* @param array $args Arguments from the option.
*
* @return string Checkbox field HTML.
*/
public function callback_checkbox( $args ) {
$tab = $args['tab'];
$id = $args['id'];
$attrs = $args['attributes'];
// Sets current option.
$current = $this->get_option( $tab, $id, $args['default'] );
$html = sprintf( '<input type="checkbox" id="%1$s" name="%2$s[%1$s]" value="1"%3$s%4$s />', $id, $tab, checked( 1, $current, false ), $this->build_field_attributes( $attrs ) );
// Displays the description.
if ( $args['description'] ) {
$html .= sprintf( '<label for="%s"> %s</label>', $id, $args['description'] );
}
echo $html;
}
/**
* Radio field callback.
*
* @param array $args Arguments from the option.
*
* @return string Radio field HTML.
*/
public function callback_radio( $args ) {
$tab = $args['tab'];
$id = $args['id'];
$attrs = $args['attributes'];
// Sets current option.
$current = $this->get_option( $tab, $id, $args['default'] );
$html = '';
foreach( $args['options'] as $key => $label ) {
$item_id = $id . '_' . $key;
$key = sanitize_title( $key );
$html .= sprintf( '<input type="radio" id="%1$s_%3$s" name="%2$s[%1$s]" value="%3$s"%4$s%5$s />', $id, $tab, $key, checked( $current, $key, false ), $this->build_field_attributes( $attrs ) );
$html .= sprintf( '<label for="%s"> %s</label><br />', $item_id, $label );
}
// Displays the description.
if ( $args['description'] ) {
$html .= sprintf( '<p class="description">%s</p>', $args['description'] );
}
echo $html;
}
/**
* Select field callback.
*
* @param array $args Arguments from the option.
*
* @return string Select field HTML.
*/
public function callback_select( $args ) {
$tab = $args['tab'];
$id = $args['id'];
$attrs = $args['attributes'];
// Sets current option.
$current = $this->get_option( $tab, $id, $args['default'] );
// If multiple add a array in the option.
$multiple = ( in_array( 'multiple', $attrs ) ) ? '[]' : '';
$html = sprintf( '<select id="%1$s" name="%2$s[%1$s]%3$s"%4$s>', $id, $tab, $multiple, $this->build_field_attributes( $attrs ) );
foreach( $args['options'] as $key => $label ) {
$key = sanitize_title( $key );
$html .= sprintf( '<option value="%s"%s>%s</option>', $key, selected( $current, $key, false ), $label );
}
$html .= '</select>';
// Displays the description.
if ( $args['description'] ) {
$html .= sprintf( '<p class="description">%s</p>', $args['description'] );
}
echo $html;
}
/**
* Color field callback.
*
* @param array $args Arguments from the option.
*
* @return string Color field HTML.
*/
public function callback_color( $args ) {
// Sets color class.
$args['attributes']['class'] = 'odin-color-field';
$this->callback_input( $args );
}
/**
* Upload field callback.
*
* @param array $args Arguments from the option.
*
* @return string Upload field HTML.
*/
public function callback_upload( $args ) {
$tab = $args['tab'];
$id = $args['id'];
$attrs = $args['attributes'];
// Sets current option.
$current = esc_url( $this->get_option( $tab, $id, $args['default'] ) );
$html = sprintf( '<input type="text" id="%1$s" name="%2$s[%1$s]" value="%3$s" class="regular-text"%5$s /> <input class="button odin-upload-button" id="%1$s-button" type="button" value="%4$s" />', $id, $tab, $current, __( 'Select file', 'odin' ), $this->build_field_attributes( $attrs ) );
// Displays the description.
if ( $args['description'] ) {
$html .= sprintf( '<p class="description">%s</p>', $args['description'] );
}
echo $html;
}
/**
* Image field callback.
*
* @param array $args Arguments from the option.
*
* @return string Image field HTML.
*/
public function callback_image( $args ) {
$tab = $args['tab'];
$id = $args['id'];
// Sets current option.
$current = $this->get_option( $tab, $id, $args['default'] );
// Gets placeholder image.
$image = get_template_directory_uri() . '/core/assets/images/placeholder.png';
$html = '<div class="odin-upload-image">';
$html .= '<span class="default-image">' . $image . '</span>';
if ( ! empty( $current ) ) {
$image = wp_get_attachment_image_src( $current, 'thumbnail' );
$image = $image[0];
}
$html .= sprintf( '<input id="%1$s" name="%2$s[%1$s]" type="hidden" class="image" value="%3$s" /><img src="%4$s" class="preview" style="height: 150px; width: 150px;" alt="" /><input id="%1$s-button" class="button" type="button" value="%5$s" /><ul class="actions"><li><a href="#" class="delete" title="%6$s"><span class="dashicons dashicons-no"></span></a></li></ul>', $id, $tab, $current, $image, __( 'Select image', 'odin' ), __( 'Remove image', 'odin' ) );
$html .= '<br class="clear" />';
$html .= '</div>';
// Displays the description.
if ( $args['description'] ) {
$html .= sprintf( '<p class="description">%s</p>', $args['description'] );
}
echo $html;
}
/**
* Image Plupload field callback.
*
* @param array $args Arguments from the option.
*
* @return string Image Plupload field HTML.
*/
public function callback_image_plupload( $args ) {
$tab = $args['tab'];
$id = $args['id'];
// Sets current option.
$current = $this->get_option( $tab, $id, $args['default'] );
$html = '<div class="odin-gallery-container">';
$html .= '<ul class="odin-gallery-images">';
if ( ! empty( $current ) ) {
// Gets the current images.
$attachments = array_filter( explode( ',', $current ) );
if ( $attachments ) {
foreach ( $attachments as $attachment_id ) {
$html .= sprintf( '<li class="image" data-attachment_id="%1$s">%2$s<ul class="actions"><li><a href="#" class="delete" title="%3$s"><span class="dashicons dashicons-no"></span></a></li></ul></li>',
$attachment_id,
wp_get_attachment_image( $attachment_id, 'thumbnail' ),
__( 'Remove image', 'odin' )
);
}
}
}
$html .= '</ul><div class="clear"></div>';
// Adds the hidden input.
$html .= sprintf( '<input type="hidden" id="%1$s" name="%2$s[%1$s]" value="%3$s" class="odin-gallery-field" />', $id, $tab, $current );
// Adds "adds images in gallery" url.
$html .= sprintf( '<p class="odin-gallery-add hide-if-no-js"><a href="#">%s</a></p>', __( 'Add images in gallery', 'odin' ) );
$html .= '</div>';
// Displays the description.
if ( $args['description'] ) {
$html .= sprintf( '<p class="description">%s</p>', $args['description'] );
}
echo $html;
}
/**
* HTML callback.
*
* @param array $args Arguments from the option.
*
* @return string HTML.
*/
public function callback_html( $args ) {
echo $args['description'];
}
/**
* Sanitization fields callback.
*
* @param string $input The unsanitized collection of options.
*
* @return string The collection of sanitized values.
*/
public function validate_input( $input ) {
// Create our array for storing the validated options.
$output = array();
// Loop through each of the incoming options.
foreach ( $input as $key => $value ) {
// Check to see if the current option has a value. If so, process it.
if ( isset( $input[ $key ] ) ) {
$output[ $key ] = apply_filters( 'odin_theme_options_validate_' . $this->id, $value, $key );
}
}
return $output;
}
}
| brasadesign/brasa-request-a-quote | inc/settings-class.php | PHP | gpl-2.0 | 15,917 |
;(function ($, window) {
var intervals = {};
var removeListener = function(selector) {
if (intervals[selector]) {
window.clearInterval(intervals[selector]);
intervals[selector] = null;
}
};
var found = 'waitUntilExists.found';
/**
* @function
* @property {object} jQuery plugin which runs handler function once specified
* element is inserted into the DOM
* @param {function|string} handler
* A function to execute at the time when the element is inserted or
* string "remove" to remove the listener from the given selector
* @param {bool} shouldRunHandlerOnce
* Optional: if true, handler is unbound after its first invocation
* @example jQuery(selector).waitUntilExists(function);
*/
$.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {
var selector = this.selector;
var $this = $(selector);
var $elements = $this.not(function() { return $(this).data(found); });
if (handler === 'remove') {
// Hijack and remove interval immediately if the code requests
removeListener(selector);
}
else {
// Run the handler on all found elements and mark as found
$elements.each(handler).data(found, true);
if (shouldRunHandlerOnce && $this.length) {
// Element was found, implying the handler already ran for all
// matched elements
removeListener(selector);
}
else if (!isChild) {
// If this is a recurring search or if the target has not yet been
// found, create an interval to continue searching for the target
intervals[selector] = window.setInterval(function () {
$this.waitUntilExists(handler, shouldRunHandlerOnce, true);
}, 500);
}
}
return $this;
};
}(jQuery, window)); | chikato/TND | wp-content/plugins/smart-social-media-widget/js/jquery.waituntilexists.js | JavaScript | gpl-2.0 | 1,735 |
/*! lightgallery - v1.2.15 - 2016-03-10
* http://sachinchoolur.github.io/lightGallery/
* Copyright (c) 2016 Sachin N; Licensed Apache 2.0 */
(function($, window, document, undefined) {
'use strict';
var defaults = {
thumbnail: true,
animateThumb: true,
currentPagerPosition: 'middle',
thumbWidth: 100,
thumbContHeight: 100,
thumbMargin: 5,
exThumbImage: false,
showThumbByDefault: true,
toogleThumb: true,
pullCaptionUp: true,
enableThumbDrag: true,
enableThumbSwipe: true,
swipeThreshold: 50,
loadYoutubeThumbnail: true,
youtubeThumbSize: 1,
loadVimeoThumbnail: true,
vimeoThumbSize: 'thumbnail_small',
loadDailymotionThumbnail: true
};
var Thumbnail = function(element) {
// get lightGallery core plugin data
this.core = $(element).data('lightGallery');
// extend module default settings with lightGallery core settings
this.core.s = $.extend({}, defaults, this.core.s);
this.$el = $(element);
this.$thumbOuter = null;
this.thumbOuterWidth = 0;
this.thumbTotalWidth = (this.core.$items.length * (this.core.s.thumbWidth + this.core.s.thumbMargin));
this.thumbIndex = this.core.index;
// Thumbnail animation value
this.left = 0;
this.init();
return this;
};
Thumbnail.prototype.init = function() {
var _this = this;
if (this.core.s.thumbnail && this.core.$items.length > 1) {
if (this.core.s.showThumbByDefault) {
setTimeout(function(){
_this.core.$outer.addClass('lg-thumb-open');
}, 700);
}
if (this.core.s.pullCaptionUp) {
this.core.$outer.addClass('lg-pull-caption-up');
}
this.build();
if (this.core.s.animateThumb) {
if (this.core.s.enableThumbDrag && !this.core.isTouch && this.core.doCss()) {
this.enableThumbDrag();
}
if (this.core.s.enableThumbSwipe && this.core.isTouch && this.core.doCss()) {
this.enableThumbSwipe();
}
this.thumbClickable = false;
} else {
this.thumbClickable = true;
}
this.toogle();
this.thumbkeyPress();
}
};
Thumbnail.prototype.build = function() {
var _this = this;
var thumbList = '';
var vimeoErrorThumbSize = '';
var $thumb;
var html = '<div class="lg-thumb-outer">' +
'<div class="lg-thumb group">' +
'</div>' +
'</div>';
switch (this.core.s.vimeoThumbSize) {
case 'thumbnail_large':
vimeoErrorThumbSize = '640';
break;
case 'thumbnail_medium':
vimeoErrorThumbSize = '200x150';
break;
case 'thumbnail_small':
vimeoErrorThumbSize = '100x75';
}
_this.core.$outer.addClass('lg-has-thumb');
_this.core.$outer.find('.lg').append(html);
_this.$thumbOuter = _this.core.$outer.find('.lg-thumb-outer');
_this.thumbOuterWidth = _this.$thumbOuter.width();
if (_this.core.s.animateThumb) {
_this.core.$outer.find('.lg-thumb').css({
width: _this.thumbTotalWidth + 'px',
position: 'relative'
});
}
if (this.core.s.animateThumb) {
_this.$thumbOuter.css('height', _this.core.s.thumbContHeight + 'px');
}
function getThumb(src, thumb, index) {
var isVideo = _this.core.isVideo(src, index) || {};
var thumbImg;
var vimeoId = '';
if (isVideo.youtube || isVideo.vimeo || isVideo.dailymotion) {
if (isVideo.youtube) {
if (_this.core.s.loadYoutubeThumbnail) {
thumbImg = '//img.youtube.com/vi/' + isVideo.youtube[1] + '/' + _this.core.s.youtubeThumbSize + '.jpg';
} else {
thumbImg = thumb;
}
} else if (isVideo.vimeo) {
if (_this.core.s.loadVimeoThumbnail) {
thumbImg = '//i.vimeocdn.com/video/error_' + vimeoErrorThumbSize + '.jpg';
vimeoId = isVideo.vimeo[1];
} else {
thumbImg = thumb;
}
} else if (isVideo.dailymotion) {
if (_this.core.s.loadDailymotionThumbnail) {
thumbImg = '//www.dailymotion.com/thumbnail/video/' + isVideo.dailymotion[1];
} else {
thumbImg = thumb;
}
}
} else {
thumbImg = thumb;
}
thumbList += '<div data-vimeo-id="' + vimeoId + '" class="lg-thumb-item" style="width:' + _this.core.s.thumbWidth + 'px; margin-right: ' + _this.core.s.thumbMargin + 'px"><img src="' + thumbImg + '" /></div>';
vimeoId = '';
}
if (_this.core.s.dynamic) {
for (var i = 0; i < _this.core.s.dynamicEl.length; i++) {
getThumb(_this.core.s.dynamicEl[i].src, _this.core.s.dynamicEl[i].thumb, i);
}
} else {
_this.core.$items.each(function(i) {
if (!_this.core.s.exThumbImage) {
getThumb($(this).attr('href') || $(this).attr('data-src'), $(this).find('img').attr('src'), i);
} else {
getThumb($(this).attr('href') || $(this).attr('data-src'), $(this).attr(_this.core.s.exThumbImage), i);
}
});
}
_this.core.$outer.find('.lg-thumb').html(thumbList);
$thumb = _this.core.$outer.find('.lg-thumb-item');
// Load vimeo thumbnails
$thumb.each(function() {
var $this = $(this);
var vimeoVideoId = $this.attr('data-vimeo-id');
if (vimeoVideoId) {
$.getJSON('//www.vimeo.com/api/v2/video/' + vimeoVideoId + '.json?callback=?', {
format: 'json'
}, function(data) {
$this.find('img').attr('src', data[0][_this.core.s.vimeoThumbSize]);
});
}
});
// manage active class for thumbnail
$thumb.eq(_this.core.index).addClass('active');
_this.core.$el.on('onBeforeSlide.lg.tm', function() {
$thumb.removeClass('active');
$thumb.eq(_this.core.index).addClass('active');
});
$thumb.on('click.lg touchend.lg', function() {
var _$this = $(this);
setTimeout(function() {
// In IE9 and bellow touch does not support
// Go to slide if browser does not support css transitions
if ((_this.thumbClickable && !_this.core.lgBusy) || !_this.core.doCss()) {
_this.core.index = _$this.index();
_this.core.slide(_this.core.index, false, true);
}
}, 50);
});
_this.core.$el.on('onBeforeSlide.lg.tm', function() {
_this.animateThumb(_this.core.index);
});
$(window).on('resize.lg.thumb orientationchange.lg.thumb', function() {
setTimeout(function() {
_this.animateThumb(_this.core.index);
_this.thumbOuterWidth = _this.$thumbOuter.width();
}, 200);
});
};
Thumbnail.prototype.setTranslate = function(value) {
// jQuery supports Automatic CSS prefixing since jQuery 1.8.0
this.core.$outer.find('.lg-thumb').css({
transform: 'translate3d(-' + (value) + 'px, 0px, 0px)'
});
};
Thumbnail.prototype.animateThumb = function(index) {
var $thumb = this.core.$outer.find('.lg-thumb');
if (this.core.s.animateThumb) {
var position;
switch (this.core.s.currentPagerPosition) {
case 'left':
position = 0;
break;
case 'middle':
position = (this.thumbOuterWidth / 2) - (this.core.s.thumbWidth / 2);
break;
case 'right':
position = this.thumbOuterWidth - this.core.s.thumbWidth;
}
this.left = ((this.core.s.thumbWidth + this.core.s.thumbMargin) * index - 1) - position;
if (this.left > (this.thumbTotalWidth - this.thumbOuterWidth)) {
this.left = this.thumbTotalWidth - this.thumbOuterWidth;
}
if (this.left < 0) {
this.left = 0;
}
if (this.core.lGalleryOn) {
if (!$thumb.hasClass('on')) {
this.core.$outer.find('.lg-thumb').css('transition-duration', this.core.s.speed + 'ms');
}
if (!this.core.doCss()) {
$thumb.animate({
left: -this.left + 'px'
}, this.core.s.speed);
}
} else {
if (!this.core.doCss()) {
$thumb.css('left', -this.left + 'px');
}
}
this.setTranslate(this.left);
}
};
// Enable thumbnail dragging and swiping
Thumbnail.prototype.enableThumbDrag = function() {
var _this = this;
var startCoords = 0;
var endCoords = 0;
var isDraging = false;
var isMoved = false;
var tempLeft = 0;
_this.$thumbOuter.addClass('lg-grab');
_this.core.$outer.find('.lg-thumb').on('mousedown.lg.thumb', function(e) {
if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
// execute only on .lg-object
e.preventDefault();
startCoords = e.pageX;
isDraging = true;
// ** Fix for webkit cursor issue https://code.google.com/p/chromium/issues/detail?id=26723
_this.core.$outer.scrollLeft += 1;
_this.core.$outer.scrollLeft -= 1;
// *
_this.thumbClickable = false;
_this.$thumbOuter.removeClass('lg-grab').addClass('lg-grabbing');
}
});
$(window).on('mousemove.lg.thumb', function(e) {
if (isDraging) {
tempLeft = _this.left;
isMoved = true;
endCoords = e.pageX;
_this.$thumbOuter.addClass('lg-dragging');
tempLeft = tempLeft - (endCoords - startCoords);
if (tempLeft > (_this.thumbTotalWidth - _this.thumbOuterWidth)) {
tempLeft = _this.thumbTotalWidth - _this.thumbOuterWidth;
}
if (tempLeft < 0) {
tempLeft = 0;
}
// move current slide
_this.setTranslate(tempLeft);
}
});
$(window).on('mouseup.lg.thumb', function() {
if (isMoved) {
isMoved = false;
_this.$thumbOuter.removeClass('lg-dragging');
_this.left = tempLeft;
if (Math.abs(endCoords - startCoords) < _this.core.s.swipeThreshold) {
_this.thumbClickable = true;
}
} else {
_this.thumbClickable = true;
}
if (isDraging) {
isDraging = false;
_this.$thumbOuter.removeClass('lg-grabbing').addClass('lg-grab');
}
});
};
Thumbnail.prototype.enableThumbSwipe = function() {
var _this = this;
var startCoords = 0;
var endCoords = 0;
var isMoved = false;
var tempLeft = 0;
_this.core.$outer.find('.lg-thumb').on('touchstart.lg', function(e) {
if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
e.preventDefault();
startCoords = e.originalEvent.targetTouches[0].pageX;
_this.thumbClickable = false;
}
});
_this.core.$outer.find('.lg-thumb').on('touchmove.lg', function(e) {
if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
e.preventDefault();
endCoords = e.originalEvent.targetTouches[0].pageX;
isMoved = true;
_this.$thumbOuter.addClass('lg-dragging');
tempLeft = _this.left;
tempLeft = tempLeft - (endCoords - startCoords);
if (tempLeft > (_this.thumbTotalWidth - _this.thumbOuterWidth)) {
tempLeft = _this.thumbTotalWidth - _this.thumbOuterWidth;
}
if (tempLeft < 0) {
tempLeft = 0;
}
// move current slide
_this.setTranslate(tempLeft);
}
});
_this.core.$outer.find('.lg-thumb').on('touchend.lg', function() {
if (_this.thumbTotalWidth > _this.thumbOuterWidth) {
if (isMoved) {
isMoved = false;
_this.$thumbOuter.removeClass('lg-dragging');
if (Math.abs(endCoords - startCoords) < _this.core.s.swipeThreshold) {
_this.thumbClickable = true;
}
_this.left = tempLeft;
} else {
_this.thumbClickable = true;
}
} else {
_this.thumbClickable = true;
}
});
};
Thumbnail.prototype.toogle = function() {
var _this = this;
if (_this.core.s.toogleThumb) {
_this.core.$outer.addClass('lg-can-toggle');
_this.$thumbOuter.append('<span class="lg-toogle-thumb lg-icon"></span>');
_this.core.$outer.find('.lg-toogle-thumb').on('click.lg', function() {
_this.core.$outer.toggleClass('lg-thumb-open');
});
}
};
Thumbnail.prototype.thumbkeyPress = function() {
var _this = this;
$(window).on('keydown.lg.thumb', function(e) {
if (e.keyCode === 38) {
e.preventDefault();
_this.core.$outer.addClass('lg-thumb-open');
} else if (e.keyCode === 40) {
e.preventDefault();
_this.core.$outer.removeClass('lg-thumb-open');
}
});
};
Thumbnail.prototype.destroy = function() {
if (this.core.s.thumbnail && this.core.$items.length > 1) {
$(window).off('resize.lg.thumb orientationchange.lg.thumb keydown.lg.thumb');
this.$thumbOuter.remove();
this.core.$outer.removeClass('lg-has-thumb');
}
};
$.fn.lightGallery.modules.Thumbnail = Thumbnail;
})(jQuery, window, document);
| reed23/cinemafilms | node_modules/lightgallery/dist/js/lg-thumbnail.js | JavaScript | gpl-2.0 | 15,685 |
<?php
class calendarData {
var $_year;
var $_month;
var $_day;
var $_row;
var $_date;
var $_datetext;
function calendarData() {
$this->_row = 0;
}
function setToday($year, $month, $day) {
$this->_year = $year;
$this->_month = $month;
$this->_day = $day;
}
function getDate($row, $d) {return $this->_date[$row][$d];}
function getDateText($row, $d) {return $this->_datetext[$row][$d];}
function getRow() {return $this->_row;}
function setCalendarData() {
$day = 1; // 当月開始日に設定
$firstw = getWeek($this->_year, $this->_month, $day); // 当月開始日の曜日
$lastday = getLastDay($this->_year, $this->_month); // 当月最終日
$lastw = getWeek($this->_year, $this->_month, $lastday); // 当月最終日の曜日
// 1週目
for ($d = 0; $d <= 6; $d++) {
if ($firstw == $d) {
$this->_date[0][$d] = sprintf("%04d-%02d-%02d", $this->_year, $this->_month, $day);
$this->_datetext[0][$d] = $day;
} elseif ($firstw < $d) {
list($this->_year, $this->_month, $day) = getNextDay($this->_year, $this->_month, $day);
$this->_date[0][$d] = sprintf("%04d-%02d-%02d", $this->_year, $this->_month, $day);
$this->_datetext[0][$d] = $day;
} else {
$this->_date[0][$d] = "";
$this->_datetext[0][$d] = "";
}
}
// 2~4週目
for ($d = 0; $d <= 6; $d++) {
list($this->_year, $this->_month, $day) = getNextDay($this->_year, $this->_month, $day);
$this->_date[1][$d] = sprintf("%04d-%02d-%02d", $this->_year, $this->_month, $day);
$this->_datetext[1][$d] = $day;
}
for ($d = 0; $d <= 6; $d++) {
list($this->_year, $this->_month, $day) = getNextDay($this->_year, $this->_month, $day);
$this->_date[2][$d] = sprintf("%04d-%02d-%02d", $this->_year, $this->_month, $day);
$this->_datetext[2][$d] = $day;
}
for ($d = 0; $d <= 6; $d++) {
list($this->_year, $this->_month, $day) = getNextDay($this->_year, $this->_month, $day);
$this->_date[3][$d] = sprintf("%04d-%02d-%02d", $this->_year, $this->_month, $day);
$this->_datetext[3][$d] = $day;
}
// 5週目
for ($d = 0; $d <= 6; $d++) {
if ($lastday == $day) {
break;
} else {
list($this->_year, $this->_month, $day) = getNextDay($this->_year, $this->_month, $day);
$this->_date[4][$d] = sprintf("%04d-%02d-%02d", $this->_year, $this->_month, $day);
$this->_datetext[4][$d] = $day;
}
}
if ( 0 < $d && $d <= 6) {
while ($d <= 6) {
$this->_date[4][$d] = "";
$this->_datetext[4][$d] = "";
$d++;
}
} elseif( $d !== 0 ) {
// 6週目
for ($d = 0; $d <= 6; $d++) {
if ($lastday == $day) {
break;
} else {
list($this->_year, $this->_month, $day) = getNextDay($this->_year, $this->_month, $day);
$this->_date[5][$d] = sprintf("%04d-%02d-%02d", $this->_year, $this->_month, $day);
$this->_datetext[5][$d] = $day;
}
}
if ($d > 0) {
while ($d <= 6) {
$this->_date[5][$d] = "";
$this->_datetext[5][$d] = "";
$d++;
}
}
}
$this->_row = count($this->_date);
}
}
?>
| toyo213/linehair | wp-content/plugins/usc-e-shop/classes/calendar.class.php | PHP | gpl-2.0 | 3,047 |
/**
Represents an asynchronous operation. Provides a
standard API for subscribing to the moment that the operation completes either
successfully (`fulfill()`) or unsuccessfully (`reject()`).
@class Promise.Resolver
@constructor
@param {Promise} promise The promise instance this resolver will be handling
**/
function Resolver(promise) {
/**
List of success callbacks
@property _callbacks
@type Array
@private
**/
this._callbacks = [];
/**
List of failure callbacks
@property _errbacks
@type Array
@private
**/
this._errbacks = [];
/**
The promise for this Resolver.
@property promise
@type Promise
**/
this.promise = promise;
/**
The status of the operation. This property may take only one of the following
values: 'pending', 'fulfilled' or 'rejected'.
@property _status
@type String
@default 'pending'
@private
**/
this._status = 'pending';
}
Y.mix(Resolver.prototype, {
/**
Resolves the promise, signaling successful completion of the
represented operation. All "onFulfilled" subscriptions are executed and passed
the value provided to this method. After calling `fulfill()`, `reject()` and
`notify()` are disabled.
@method fulfill
@param {Any} value Value to pass along to the "onFulfilled" subscribers
**/
fulfill: function (value) {
if (this._status === 'pending') {
this._result = value;
}
if (this._status !== 'rejected') {
this._notify(this._callbacks, this._result);
// Reset the callback list so that future calls to fulfill()
// won't call the same callbacks again. Promises keep a list
// of callbacks, they're not the same as events. In practice,
// calls to fulfill() after the first one should not be made by
// the user but by then()
this._callbacks = [];
// Once a promise gets fulfilled it can't be rejected, so
// there is no point in keeping the list. Remove it to help
// garbage collection
this._errbacks = null;
this._status = 'fulfilled';
}
},
/**
Resolves the promise, signaling *un*successful completion of the
represented operation. All "onRejected" subscriptions are executed with
the value provided to this method. After calling `reject()`, `resolve()`
and `notify()` are disabled.
@method reject
@param {Any} value Value to pass along to the "reject" subscribers
**/
reject: function (reason) {
if (this._status === 'pending') {
this._result = reason;
}
if (this._status !== 'fulfilled') {
this._notify(this._errbacks, this._result);
// See fulfill()
this._callbacks = null;
this._errbacks = [];
this._status = 'rejected';
}
},
/**
Schedule execution of a callback to either or both of "resolve" and
"reject" resolutions for the Resolver. The callbacks
are wrapped in a new Resolver and that Resolver's corresponding promise
is returned. This allows operation chaining ala
`functionA().then(functionB).then(functionC)` where `functionA` returns
a promise, and `functionB` and `functionC` _may_ return promises.
@method then
@param {Function} [callback] function to execute if the Resolver
resolves successfully
@param {Function} [errback] function to execute if the Resolver
resolves unsuccessfully
@return {Promise} The promise of a new Resolver wrapping the resolution
of either "resolve" or "reject" callback
**/
then: function (callback, errback) {
// When the current promise is fulfilled or rejected, either the
// callback or errback will be executed via the function pushed onto
// this._callbacks or this._errbacks. However, to allow then()
// chaining, the execution of either function needs to be represented
// by a Resolver (the same Resolver can represent both flow paths), and
// its promise returned.
var promise = this.promise,
thenFulfill, thenReject,
// using promise constructor allows for customized promises to be
// returned instead of plain ones
then = new promise.constructor(function (fulfill, reject) {
thenFulfill = fulfill;
thenReject = reject;
}),
callbackList = this._callbacks || [],
errbackList = this._errbacks || [];
// Because the callback and errback are represented by a Resolver, it
// must be fulfilled or rejected to propagate through the then() chain.
// The same logic applies to resolve() and reject() for fulfillment.
callbackList.push(typeof callback === 'function' ?
this._wrap(thenFulfill, thenReject, callback) : thenFulfill);
errbackList.push(typeof errback === 'function' ?
this._wrap(thenFulfill, thenReject, errback) : thenReject);
// If a promise is already fulfilled or rejected, notify the newly added
// callbacks by calling fulfill() or reject()
if (this._status === 'fulfilled') {
this.fulfill(this._result);
} else if (this._status === 'rejected') {
this.reject(this._result);
}
return then;
},
/**
Wraps the callback in Y.soon to guarantee its asynchronous execution. It
also catches exceptions to turn them into rejections and links promises
returned from the `then` callback.
@method _wrap
@param {Function} thenFulfill Fulfillment function of the resolver that
handles this promise
@param {Function} thenReject Rejection function of the resolver that
handles this promise
@param {Function} fn Callback to wrap
@return {Function}
@private
**/
_wrap: function (thenFulfill, thenReject, fn) {
// callbacks and errbacks only get one argument
return function (valueOrReason) {
var result;
// Promises model exception handling through callbacks
// making both synchronous and asynchronous errors behave
// the same way
try {
// Use the argument coming in to the callback/errback from the
// resolution of the parent promise.
// The function must be called as a normal function, with no
// special value for |this|, as per Promises A+
result = fn(valueOrReason);
} catch (e) {
// calling return only to stop here
return thenReject(e);
}
if (Promise.isPromise(result)) {
// Returning a promise from a callback makes the current
// promise sync up with the returned promise
result.then(thenFulfill, thenReject);
} else {
// Non-promise return values always trigger resolve()
// because callback is affirmative, and errback is
// recovery. To continue on the rejection path, errbacks
// must return rejected promises or throw.
thenFulfill(result);
}
};
},
/**
Returns the current status of the Resolver as a string "pending",
"fulfilled", or "rejected".
@method getStatus
@return {String}
**/
getStatus: function () {
return this._status;
},
/**
Executes an array of callbacks from a specified context, passing a set of
arguments.
@method _notify
@param {Function[]} subs The array of subscriber callbacks
@param {Any} result Value to pass the callbacks
@protected
**/
_notify: function (subs, result) {
// Since callback lists are reset synchronously, the subs list never
// changes after _notify() receives it. Avoid calling Y.soon() for
// an empty list
if (subs.length) {
// Calling all callbacks after Y.soon to guarantee
// asynchronicity. Because setTimeout can cause unnecessary
// delays that *can* become noticeable in some situations
// (especially in Node.js)
Y.soon(function () {
var i, len;
for (i = 0, len = subs.length; i < len; ++i) {
subs[i](result);
}
});
}
}
}, true);
Y.Promise.Resolver = Resolver;
| schancel/gameserver | public/js/yui3-3.12.0/src/promise/js/resolver.js | JavaScript | gpl-2.0 | 8,693 |
<h3>Edit Guru</h3>
<div class="isikanan"><!--Awal class isi kanan-->
<div class="judulisikanan">
<div class="menuhorisontalaktif-ujung"><a href="guru_staff.php">Guru</a></div>
<div class="menuhorisontal"><a href="staff.php">Staff</a></div>
<div class="menuhorisontal"><a href="jabatan.php">Jabatan</a></div>
</div>
<table class="isian">
<form method='POST' <?php echo "action='$database?pilih=guru&untukdi=edit'";?> name='editguru' id='editguru' enctype="multipart/form-data">
<?php
$edit=mysql_query("SELECT * FROM sh_guru_staff, sh_mapel WHERE sh_guru_staff.id_mapel=sh_mapel.id_mapel AND id_gurustaff='$_GET[id]'");
$r=mysql_fetch_array($edit);
echo "<input type='hidden' name='id' value='$r[id_gurustaff]'";
?>
<tr><td class="isiankanan" width="175px">Nama Guru</td><td class="isian"><input type="text" name="nama_guru" class="maksimal" value="<?php echo"$r[nama_gurustaff]";?>"></td></tr>
<tr><td class="isiankanan" width="175px">NIP</td><td class="isian"><input type="text" name="nip" class="pendek" value="<?php echo"$r[nip]";?>"></td></tr>
<tr><td class="isiankanan" width="175px">Password</td><td class="isian">
<a href="javascript:void(0)"onclick="window.open('<?php echo "aplikasi/guru_password.php?id=$r[id_gurustaff]"; ?>','linkname','height=315, width=500,scrollbars=yes')"><b><u>Ganti Password</u></b></a></td></tr>
<tr><td class="isiankanan" width="175px">Foto</td><td class="isian"><img src="../images/foto/guru/<?php echo "$r[foto]";?>" width="200px">
<?php if ($r[foto] !='no_photo.jpg'){?>
<br><br>
<a href="<?php echo "$database?pilih=guru&untukdi=hapusgambar&id=$r[id_gurustaff]";?>"><b><u>Hapus gambar</u></b></a>
<?php }?>
</td></tr>
<tr><td class="isiankanan" width="175px">Ganti Foto</td><td class="isian"><input type="file" name="fupload"></td></tr>
<tr><td class="isiankanan" width="175px">Jenis Kelamin</td>
<td class="isian">
<?php if ($r[jenkel]=='L'){ ?>
<input type="radio" name="jk" value="L" checked/>Laki-laki
<input type="radio" name="jk" value="P"/>Perempuan
<?php }
else { ?>
<input type="radio" name="jk" value="L"/>Laki-laki
<input type="radio" name="jk" value="P" checked/>Perempuan
<?php } ?>
</td></tr>
<tr><td class="isiankanan" width="175px">Tempat, Tanggal Lahir</td><td class="isian">
<input type="text" name="tempat_lahir" class="pendek" value="<?php echo"$r[tempat_lahir]";?>">,
<input type="text" id="tanggal" name="tanggal_lahir" class="pendek" style="width:20%" value="<?php echo"$r[tanggal_lahir]";?>"></td></tr>
<tr><td class="isiankanan" width="175px">Mengajar</td>
<td class="isian">
<select name="mata_pelajaran">
<option value="<?php echo "$r[id_mapel]";?>" selected><?php echo "$r[nama_mapel]";?></option>
<?php
$mapel=mysql_query("SELECT * FROM sh_mapel ORDER BY nama_mapel ASC");
while ($m=mysql_fetch_array($mapel)){
echo "<option value='$m[id_mapel]'>$m[nama_mapel]</option>"; }
?>
</select>
</td></tr>
<tr><td class="isiankanan" width="175px">Alamat</td><td class="isian"><textarea name="alamat" style="height: 100px"><?php echo"$r[alamat]";?></textarea></td></tr>
<tr><td class="isiankanan" width="175px">Pendidikan Terakhir</td>
<td class="isian">
<select name="pendidikan">
<option value="<?php echo "$r[pendidikan_terakhir]";?>" selected><?php echo "$r[pendidikan_terakhir]";?></option>
<option value="SMA sederajat">SMA sederajat</option>
<option value="Diploma 1 (D1)">Diploma 1 (D1)</option>
<option value="Diploma 2 (D2)">Diploma 2 (D2)</option>
<option value="Diploma 3 (D3)">Diploma 3 (D3)</option>
<option value="Strata 1 (S1)">Strata 1 (S1)</option>
<option value="Magister (S2)">Magister (S2)</option>
<option value="Doktor (S3)">Doktor (S3)</option>
</select>
</td></tr>
<tr><td class="isiankanan" width="175px">Tahun Masuk</td><td class="isian">
<?php
$thn_skrg=date("Y");
echo "<select name=tahun_masuk>
<option value='$r[tahun_masuk]' selected>$r[tahun_masuk]</option>";
for ($thn=1990;$thn<=$thn_skrg;$thn++){
echo "<option value=$thn>$thn</option>";
}
echo "</select>"; ?>
</td></tr>
<tr><td class="isiankanan" width="175px">Status Perkawinan</td>
<td class="isian">
<select name="status_kawin">
<option value="<?php echo "$r[status_kawin]";?>" selected><?php echo "$r[status_kawin]";?></option>
<option value="Menikah">Menikah</option>
<option value="Belum Menikah">Belum menikah</option>
<option value="Duda">Duda</option>
<option value="Janda">Janda</option>
</select>
</td></tr>
<tr><td class="isiankanan" width="175px">Email</td><td class="isian"><input type="text" name="email" class="pendek" value="<?php echo"$r[email]";?>"></td></tr>
<tr><td class="isiankanan" width="175px">Telepon/ HP</td><td class="isian"><input type="text" name="telepon" class="pendek" value="<?php echo"$r[telepon]";?>"></td></tr>
<tr><td class="isian" colspan="2">
<input type="submit" class="pencet" value="Update">
<input type="button" class="hapus" value="Batal" onclick="self.history.back()">
</td></tr>
</form>
<script language="JavaScript" type="text/javascript" xml:space="preserve">
//<![CDATA[
var frmvalidator = new Validator("editguru");
frmvalidator.addValidation("nama_guru","req","Nama guru harus diisi");
frmvalidator.addValidation("nama_guru","maxlen=30","Nama guru maksimal 30 karakter");
frmvalidator.addValidation("nama_guru","minlen=3","Nama guru minimal 3 karakter");
frmvalidator.addValidation("nip","req","NIP guru harus diisi");
frmvalidator.addValidation("nip","maxlen=18","NIP guru maksimal 18 karakter");
frmvalidator.addValidation("nip","minlen=9","NIP guru minimal 9 karakter");
frmvalidator.addValidation("nip","numeric","NIP ditulis dengan angka");
frmvalidator.addValidation("fupload","file_extn=jpg;gif;png","Jenis file yang diterima untuk gambar adalah : jpg, gif, png");
frmvalidator.addValidation("mata_pelajaran","req","Anda belum memilih mata pelajaran");
frmvalidator.addValidation("pendidikan","req","Anda belum memilih pendidikan terakhir");
frmvalidator.addValidation("status_kawin","req","Anda belum memilih status perkawinan");
frmvalidator.addValidation("tahun_masuk","req","Tahun masuk harus diisi");
frmvalidator.addValidation("tempat_lahir","req","Tempat lahir harus diisi");
frmvalidator.addValidation("tanggal_lahir","req","Tanggal lahir harus diisi");
frmvalidator.addValidation("email","email","Format email salah");
//]]>
</script>
</table>
</div><!--Akhir class isi kanan--> | zuhzwan/synp02 | adminpanel/aplikasi/guru_edit.php | PHP | gpl-2.0 | 6,763 |
/*******************************************************************************
* Copyright (C) 2013 JMaNGOS <http://jmangos.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/>.
******************************************************************************/
/**
*
*/
package org.jmangos.commons.entities.skills.pet;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import org.jmangos.commons.entities.CharacterSkill;
/**
* @author MinimaJack
*
*/
@Entity
@DiscriminatorValue(value = "787")
public class PetExoticCoreHound extends CharacterSkill {
/**
*
*/
private static final long serialVersionUID = -2165567397248362584L;
}
| JMaNGOS/JMaNGOS | Commons/src/main/java/org/jmangos/commons/entities/skills/pet/PetExoticCoreHound.java | Java | gpl-2.0 | 1,292 |
package pl.metaminers.game;
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import pl.metaminers.game.MineFooGame;
public class IOSLauncher extends IOSApplication.Delegate {
@Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
return new IOSApplication(new MineFooGame(), config);
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
} | tmachows/slavic-miners-game | ios/src/pl/metaminers/game/IOSLauncher.java | Java | gpl-2.0 | 764 |
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// MarineStandalone is a minecraft server software and API.
// Copyright (C) MarineMC (marinemc.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.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package org.marinemc.world;
/**
* @author Fozie
*/
public enum BiomeID {
UNKNOWN(-1, "unknowned"), OCEAN(0, "Ocean"), PLAINS(1, "Plains"), DESERT(2,
"Desert"), EXTREAM_HILLS(3, "Extreme Hills"), FOREST(4, "Forest"), TAIGA(
5, "Taiga"), SWAMPLAND(6, "Swampland"), RIVER(7, "River"), NETHER(
8, "Nether"), THE_END(9, "End"), FROZEN_OCEAN(10, "Frozen Ocean"), FROZEN_RIVER(
11, "Frozen River"), ICE_PLAINS(12, "Ice Plains"), ICE_MOUNTIANS(
13, "Ice Mountains"), MUSHROOM_ISLAND(14, "Mushroom Island"), MUSHROOM_ISLAND_SHORE(
15, "Mushroom Island Shore"), BEACH(16, "Beach"), DESERT_HILLS(17,
"Desert Hills"), FOREST_HILLS(18, "Forest Hills"), TAIGA_HILLS(19,
"Taiga Hills"), EXTREAM_HILLS_EDGE(20, "Extreme Hills Edge"), JUNGLE(
21, "Jungle"), JUNGLE_HILLS(22, "Jungle Hills"), JUNGLE_EDGE(23,
"Jungle Edge"), DEEP_OCEAN(24, "Deep Ocean"), STONE_BEACH(25,
"Stone Beach"), COLD_BEACH(26, "Cold Beach"), BIRCH_FOREST(27,
"Birch Forest"), BIRCH_FOREST_HILLS(28, "Birch Forest Hills"), ROOFED_FOREST(
29, "Roofed Forest"), COLD_TAIGA(30, "Cold Taiga"), COLD_TAIGA_HILLS(
31, "Cold Taiga Hills"), MEGA_TAIGA(32, "Mega Taiga"), MEGA_TAIGA_HILLS(
33, "Mega Taiga Hills"), EXTREAM_HILLS_EXTRA(34, "Extreme Hills+"), SAVANNA(
35, "Savanna"), SAVANNA_PLATEAU(36, "Savanna Plateau"), MESA(37,
"Mesa"), MESA_PLATEUA_F(38, "Mesa Plateau F"), MESA_PLATEAU(39,
"Mesa Plateau"), SUNFLOWER_PLAINS(129, "Sunflower Plains"), DESERT_M(
130, "Desert M"), EXTREAM_HILLS_M(131, "Extreme Hills M"), FLOWER_FOREST(
132, "Flower Forest"), TAIGA_M(133, "Taiga M"), SWAMPLAND_M(134,
"Swampland M"), ICE_PLAINS_SPIKES(140, "Ice Plains Spikes"), JUNGLE_M(
149, "Jungle M"), JUNGLE_EDGE_M(151, "JungleEdge M"), BIRCH_FOREST_M(
155, "Birch Forest M"), BIRCH_FOREST_HILLS_M(156,
"Birch Forest Hills M"), ROOFED_FOREST_M(157, "Roofed Forest M"), COLD_TAIGA_M(
158, "Cold Taiga M"), MEGA_SPRUCE_TAIGA(160, "Mega Spruce Taiga"), REDWOOD_TAIGA_HILLS_M(
161, "Redwood Taiga Hills M"), EXTREME_HILLS_EXTRA_M(162,
"Extreme Hills+ M"), SAVANNA_M(163, "Savanna M"), SAVANNA_PLATEAU_M(
164, "Savanna Plateau M"), MESA_BRYCE(165, "Mesa (Bryce)"), MESA_PLATEAU_F_M(
166, "Mesa Plateau F M"), MESA_PLATEAU_M(167, "Mesa Plateau M");
private final byte ID;
private final String name;
private BiomeID(final int id, final String name) {
ID = (byte) id;
this.name = name;
}
public byte getID() {
return ID;
}
public String getName() {
return name;
}
} | MarineMC/MarineStandalone | src/main/java/org/marinemc/world/BiomeID.java | Java | gpl-2.0 | 3,562 |
<?php
/**
* rejestr ulubionych sektorów
*
* @version $Rev: 460 $
* @package Engine
*/
class favSectorsRegistry extends simpleRegistry {
/**
* Wyrenderowanie rejestru ulubionych sektorów
*
* @param int $userID
* @return string
*/
public function get() {
$retVal = '';
$retVal .= "<h1>" . TranslateController::getDefault()->get ( 'favSectors' ) . "</h1>";
$retVal .= "<table class=\"transactionList\" cellspacing=\"2\" cellpadding=\"0\">";
$retVal .= "<tr>";
$retVal .= "<th>" . TranslateController::getDefault()->get ( 'sector' ) . "</th>";
$retVal .= "<th style=\"width: 6em;\"> </th>";
$retVal .= "</tr>";
$tQuery = "SELECT System, X, Y FROM favouritesectors WHERE UserID='{$this->userID}' ORDER BY System, X, Y";
$tQuery = \Database\Controller::getInstance()->execute ( $tQuery );
while ( $tResult = \Database\Controller::getInstance()->fetch ( $tQuery ) ) {
$retVal .= '<tr>';
$retVal .= '<td >' . $tResult->System . '/' . $tResult->X . '/' . $tResult->Y . '</td>';
$tString = '';
$tString .= \General\Controls::renderImgButton ( 'delete', "executeAction('deleteFavSector','',null,'{$tResult->System}/{$tResult->X}/{$tResult->Y}');", TranslateController::getDefault()->get('delete') );
$tString .= \General\Controls::renderImgButton ( 'rightFar', "systemMap.plot('{$tResult->System}','{$tResult->X}','{$tResult->Y}');", TranslateController::getDefault()->get ( 'setNavPoint' ));
if (empty ( $tString )) {
$tString = ' ';
}
$retVal .= '<td>' . $tString . '</td>';
$retVal .= '</tr>';
}
$retVal .= "</table>";
return $retVal;
}
} | DzikuVx/playpulsar | gameplay/engine/classes/favSectorsRegistry.php | PHP | gpl-2.0 | 1,630 |
<?php
$any_bad_inputs = false;
$changes_saved = false;
$_SESSION['collected_data'] = null;
if($_POST['collected_data'] != null) {
foreach((array)$_POST['collected_data'] as $value_id => $value) {
$form_sql = "SELECT * FROM `".WPSC_TABLE_CHECKOUT_FORMS."` WHERE `id` = '$value_id' LIMIT 1";
$form_data = $wpdb->get_results($form_sql,ARRAY_A);
$form_data = $form_data[0];
$bad_input = false;
if($form_data['mandatory'] == 1) {
switch($form_data['type']) {
case "email":
if(!preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-.]+\.[a-zA-Z]{2,5}$/",$value)) {
$any_bad_inputs = true;
$bad_input = true;
}
break;
case "delivery_country":
if(($value != null)) {
$_SESSION['delivery_country'] == $value;
}
break;
default:
break;
}
if($bad_input === true) {
switch($form_data['name']) {
case __('First Name', 'wpsc'):
$bad_input_message .= __('Please enter a valid name', 'wpsc') . "";
break;
case __('Last Name', 'wpsc'):
$bad_input_message .= __('Please enter a valid surname', 'wpsc') . "";
break;
case __('Email', 'wpsc'):
$bad_input_message .= __('Please enter a valid email address', 'wpsc') . "";
break;
case __('Address 1', 'wpsc'):
case __('Address 2', 'wpsc'):
$bad_input_message .= __('Please enter a valid address', 'wpsc') . "";
break;
case __('City', 'wpsc'):
$bad_input_message .= __('Please enter your town or city.', 'wpsc') . "";
break;
case __('Phone', 'wpsc'):
$bad_input_message .= __('Please enter a valid phone number', 'wpsc') . "";
break;
case __('Country', 'wpsc'):
$bad_input_message .= __('Please select your country from the list.', 'wpsc') . "";
break;
default:
$bad_input_message .= __('Please enter a valid', 'wpsc') . " " . strtolower($form_data['name']) . ".";
break;
}
$bad_input_message .= "<br />";
} else {
$meta_data[$value_id] = $value;
}
} else {
$meta_data[$value_id] = $value;
}
}
$new_meta_data = serialize($meta_data);
update_usermeta($user_ID, 'wpshpcrt_usr_profile', $meta_data);
}
?>
<div class="wrap" style=''>
<?php
echo " <div class='user-profile-links'><a href='".get_option('user_account_url')."'>Purchase History</a> | <a href='".get_option('user_account_url').$seperator."edit_profile=true'>Your Details</a> | <a href='".get_option('user_account_url').$seperator."downloads=true'>Your Downloads</a></div><br />";
?>
<form method='post' action=''>
<?php
if($changes_saved == true) {
echo __('Thanks, your changes have been saved.', 'wpsc');
} else {
echo $bad_input_message;
}
?>
<table>
<?php
// arr, this here be where the data will be saved
$meta_data = null;
$saved_data_sql = "SELECT * FROM `".$wpdb->usermeta."` WHERE `user_id` = '".$user_ID."' AND `meta_key` = 'wpshpcrt_usr_profile';";
$saved_data = $wpdb->get_row($saved_data_sql,ARRAY_A);
$meta_data = get_usermeta($user_ID, 'wpshpcrt_usr_profile');
$form_sql = "SELECT * FROM `".WPSC_TABLE_CHECKOUT_FORMS."` WHERE `active` = '1' ORDER BY `order`;";
$form_data = $wpdb->get_results($form_sql,ARRAY_A);
foreach($form_data as $form_field)
{
$meta_data[$form_field['id']] = htmlentities(stripslashes($meta_data[$form_field['id']]), ENT_QUOTES);
if($form_field['type'] == 'heading')
{
echo "
<tr>
<td colspan='2'>\n\r";
echo "<strong>".$form_field['name']."</strong>";
echo "
</td>
</tr>\n\r";
}
else
{
if($form_field['type'] == "country")
{
continue;
}
echo "
<tr>
<td align='left'>\n\r";
echo $form_field['name'];
if($form_field['mandatory'] == 1)
{
if(!(($form_field['type'] == 'country') || ($form_field['type'] == 'delivery_country')))
{
echo "*";
}
}
echo "
</td>\n\r
<td align='left'>\n\r";
switch($form_field['type'])
{
case "text":
case "city":
case "delivery_city":
echo "<input type='text' value='".$meta_data[$form_field['id']]."' name='collected_data[".$form_field['id']."]' />";
break;
case "address":
case "delivery_address":
case "textarea":
echo "<textarea name='collected_data[".$form_field['id']."]'>".$meta_data[$form_field['id']]."</textarea>";
break;
case "region":
case "delivery_region":
echo "<select name='collected_data[".$form_field['id']."]'>".nzshpcrt_region_list($_SESSION['collected_data'][$form_field['id']])."</select>";
break;
case "country":
break;
case "delivery_country":
echo "<select name='collected_data[".$form_field['id']."]' >".nzshpcrt_country_list($meta_data[$form_field['id']])."</select>";
break;
case "email":
echo "<input type='text' value='".$meta_data[$form_field['id']]."' name='collected_data[".$form_field['id']."]' />";
break;
default:
echo "<input type='text' value='".$meta_data[$form_field['id']]."' name='collected_data[".$form_field['id']."]' />";
break;
}
echo "
</td>
</tr>\n\r";
}
}
?>
<?php
if(isset($gateway_checkout_form_fields))
{
echo $gateway_checkout_form_fields;
}
?>
<tr>
<td>
</td>
<td>
<input type='hidden' value='true' name='submitwpcheckout_profile' />
<input type='submit' value='<?php echo __('Save Profile', 'wpsc');?>' name='submit' />
</td>
</tr>
</table>
</form>
</div> | Jonathonbyrd/wp-ecommerce | edit-profile.php | PHP | gpl-2.0 | 5,939 |
/*
Ucieszony Chat Client
Copyright (C) 2013-2015 Paweł Ostrowski
This file is part of Ucieszony Chat Client.
Ucieszony Chat Client 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.
Ucieszony Chat Client 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 Ucieszony Chat Client (in the file LICENSE); if not,
see <http://www.gnu.org/licenses/gpl-2.0.html>.
*/
#include <sstream> // std::string, std::stringstream
#include <algorithm> // std::find
#include <sys/time.h> // gettimeofday()
// -std=c++11 - std::system(), std::to_string()
#include "irc_parser.hpp"
#include "chat_utils.hpp"
#include "window_utils.hpp"
#include "form_conv.hpp"
#include "enc_str.hpp"
#include "network.hpp"
#include "auth.hpp"
#include "ucc_global.hpp"
std::string get_value_from_buf(std::string &in_buf, std::string expr_before, std::string expr_after)
{
/*
Znajdź i pobierz wartość pomiędzy wyrażeniem początkowym i końcowym.
*/
std::string value_from_buf;
// znajdź pozycję początku szukanego wyrażenia
size_t pos_expr_before = in_buf.find(expr_before);
if(pos_expr_before != std::string::npos)
{
// znajdź pozycję końca szukanego wyrażenia, zaczynając od znalezionego początku + jego jego długości
size_t pos_expr_after = in_buf.find(expr_after, pos_expr_before + expr_before.size());
if(pos_expr_after != std::string::npos)
{
// wstaw szukaną wartość
value_from_buf.insert(0, in_buf, pos_expr_before + expr_before.size(), pos_expr_after - pos_expr_before - expr_before.size());
}
}
// zwróć szukaną wartość między wyrażeniami lub pusty bufor, gdy nie znaleziono początku lub końca
return value_from_buf;
}
std::string get_rest_from_buf(std::string &in_buf, std::string expr_before)
{
/*
Znajdź i pobierz resztę bufora od szukanej wartości (z jej pominięciem).
*/
std::string rest_from_buf;
// znajdź pozycję początku szukanego wyrażenia
size_t pos_expr_before = in_buf.find(expr_before);
if(pos_expr_before != std::string::npos)
{
// wstaw szukaną wartość
rest_from_buf.insert(0, in_buf, pos_expr_before + expr_before.size(), in_buf.size() - pos_expr_before - expr_before.size());
}
// zwróć szukaną resztę po wyrażeniu początkowym aż do końca bufora lub pusty bufor, gdy nie znaleziono początku
return rest_from_buf;
}
std::string get_raw_parm(std::string &raw_buf, int raw_parm_number)
{
/*
Pobierz parametr RAW o numerze w raw_parm_number (liczonym od zera).
*/
std::stringstream raw_buf_stream(raw_buf);
std::string raw_parm;
int raw_parm_index = 0;
while(raw_parm_index <= raw_parm_number)
{
if(! std::getline(raw_buf_stream, raw_parm, ' '))
{
// gdy szukany parametr jest poza buforem, zwróć pusty parametr (normalnie zostałby ostatnio odczytany) i zakończ pętlę
raw_parm.clear();
break;
}
// nie zwiększaj numeru indeksu odczytanego parametru, gdy odczytana zostanie spacja (ma to miejsce, gdy jest kilka spacji obok siebie)
if(raw_parm.size() > 0)
{
++raw_parm_index;
}
}
// jeśli na początku odczytanego parametru jest dwukropek, usuń go
if(raw_parm.size() > 0 && raw_parm[0] == ':')
{
raw_parm.erase(0, 1);
}
return raw_parm;
}
void irc_parser(struct global_args &ga, struct channel_irc *ci[], std::string dbg_irc_msg, bool test_parser)
{
std::string irc_recv_buf;
// normalne użycie parsera najpierw pobiera dane z serwera
if(! test_parser)
{
// pobierz odpowiedź z serwera
irc_recv(ga, ci, irc_recv_buf, dbg_irc_msg);
// w przypadku błędu podczas pobierania danych zakończ
if(! ga.irc_ok)
{
return;
}
}
// testowanie parsera pobiera dane z dbg_irc_msg
else
{
irc_recv_buf = dbg_irc_msg;
}
std::stringstream irc_recv_buf_stream(irc_recv_buf);
std::string raw_buf, raw_parm0, raw_parm1;
bool raw_unknown;
// obsłuż bufor (wiersz po wierszu)
while(std::getline(irc_recv_buf_stream, raw_buf))
{
// pobierz parametry RAW, aby wykryć dalej, jaki to rodzaj RAW
raw_parm0 = get_raw_parm(raw_buf, 0);
raw_parm1 = get_raw_parm(raw_buf, 1);
/*
Zależnie od rodzaju RAW wywołaj odpowiednią funkcję.
*/
raw_unknown = false;
/*
RAW zwykłe nienumeryczne oraz numeryczne.
*/
/*
RAW zwykłe nienumeryczne, gdzie nazwa RAW jest jako pierwsza.
*/
if(raw_parm0 == "ERROR")
{
raw_error(ga, ci, raw_buf);
}
else if(raw_parm0 == "PING")
{
raw_ping(ga, ci, raw_parm1);
}
/*
Koniec RAW zwykłych nienumerycznych, gdzie nazwa RAW jest jako pierwsza.
*/
else if(raw_parm1 != "NOTICE")
{
switch(std::stoi("0" + raw_parm1)) // drugi parametr RAW
{
/*
RAW zwykłe nienumeryczne.
*/
case 0:
{
if(raw_parm1 == "INVIGNORE")
{
raw_invignore(ga, ci, raw_buf);
}
else if(raw_parm1 == "INVITE")
{
raw_invite(ga, ci, raw_buf);
}
else if(raw_parm1 == "INVREJECT")
{
raw_invreject(ga, ci, raw_buf);
}
else if(raw_parm1 == "JOIN")
{
raw_join(ga, ci, raw_buf);
}
else if(raw_parm1 == "KICK")
{
raw_kick(ga, ci, raw_buf);
}
else if(raw_parm1 == "MODE")
{
raw_mode(ga, ci, raw_buf, raw_parm0);
}
// else if(raw_parm1 == "MODERATE")
// {
// }
else if(raw_parm1 == "MODERMSG")
{
raw_modermsg(ga, ci, raw_buf);
}
// else if(raw_parm1 == "MODERNOTICE")
// {
// }
else if(raw_parm1 == "PART")
{
raw_part(ga, ci, raw_buf);
}
else if(raw_parm1 == "PONG")
{
raw_pong(ga, raw_buf);
}
else if(raw_parm1 == "PRIVMSG")
{
raw_privmsg(ga, ci, raw_buf);
}
else if(raw_parm1 == "QUIT")
{
raw_quit(ga, ci, raw_buf);
}
else if(raw_parm1 == "TOPIC")
{
raw_topic(ga, ci, raw_buf, raw_parm0);
}
// nieznany lub niezaimplementowany jeszcze RAW zwykły nienumeryczny
else
{
raw_unknown = true;
}
break;
} //case 0
/*
Koniec RAW zwykłych nienumerycznych.
*/
/*
RAW zwykłe numeryczne.
*/
case 001:
raw_001(ga, ci, raw_buf);
break;
case 002:
raw_002();
break;
case 003:
raw_003();
break;
case 004:
raw_004();
break;
case 005:
raw_005();
break;
case 251:
raw_251(ga, ci, raw_buf, raw_parm0);
break;
case 252:
raw_252(ga, ci, raw_buf, raw_parm0);
break;
case 253:
raw_253(ga, ci, raw_buf, raw_parm0);
break;
case 254:
raw_254(ga, ci, raw_buf, raw_parm0);
break;
case 255:
raw_255(ga, ci, raw_buf, raw_parm0);
break;
case 256:
raw_256(ga, ci, raw_buf, raw_parm0);
break;
case 257:
raw_257(ga, ci, raw_buf, raw_parm0);
break;
case 258:
raw_258(ga, ci, raw_buf, raw_parm0);
break;
case 259:
raw_259(ga, ci, raw_buf, raw_parm0);
break;
case 265:
raw_265(ga, ci, raw_buf, raw_parm0);
break;
case 266:
raw_266(ga, ci, raw_buf, raw_parm0);
break;
case 301:
raw_301(ga, ci, raw_buf);
break;
case 303:
raw_303(ga, ci, raw_buf);
break;
case 304:
raw_304(ga, ci, raw_buf);
break;
case 305:
raw_305(ga, ci);
break;
case 306:
raw_306(ga, ci);
break;
case 307:
raw_307(ga, ci, raw_buf);
break;
case 311:
raw_311(ga, ci, raw_buf);
break;
case 312:
raw_312(ga, ci, raw_buf);
break;
case 313:
raw_313(ga, ci, raw_buf);
break;
case 314:
raw_314(ga, ci, raw_buf);
break;
case 317:
raw_317(ga, ci, raw_buf);
break;
case 318:
raw_318(ga, ci, raw_buf);
break;
case 319:
raw_319(ga, ci, raw_buf);
break;
case 332:
raw_332(ga, ci, raw_buf, get_raw_parm(raw_buf, 3));
break;
case 333:
raw_333(ga, ci, raw_buf);
break;
case 335:
raw_335(ga, ci, raw_buf);
break;
case 341:
raw_341();
break;
case 353:
raw_353(ga, ci, raw_buf);
break;
case 366:
raw_366(ga, ci, raw_buf);
break;
case 369:
raw_369(ga, ci, raw_buf);
break;
case 371:
raw_371(ga, ci, raw_buf, raw_parm0);
break;
case 372:
raw_372(ga, ci, raw_buf);
break;
case 374:
raw_374();
break;
case 375:
raw_375(ga, ci);
break;
case 376:
raw_376();
break;
case 378:
raw_378(ga, ci, raw_buf);
break;
case 391:
raw_391(ga, ci, raw_buf);
break;
case 396:
raw_396(ga, ci, raw_buf);
break;
case 401:
raw_401(ga, ci, raw_buf);
break;
case 402:
raw_402(ga, ci, raw_buf);
break;
case 403:
raw_403(ga, ci, raw_buf);
break;
case 404:
raw_404(ga, ci, raw_buf);
break;
case 405:
raw_405(ga, ci, raw_buf);
break;
case 406:
raw_406(ga, ci, raw_buf);
break;
case 412:
raw_412(ga, ci);
break;
case 421:
raw_421(ga, ci, raw_buf);
break;
case 433:
raw_433(ga, ci, raw_buf);
break;
case 441:
raw_441(ga, ci, raw_buf);
break;
case 442:
raw_442(ga, ci, raw_buf);
break;
case 443:
raw_443(ga, ci, raw_buf);
break;
case 445:
raw_445(ga, ci, raw_buf);
break;
case 446:
raw_446(ga, ci, raw_buf);
break;
case 451:
raw_451(ga, ci, raw_buf);
break;
case 461:
raw_461(ga, ci, raw_buf);
break;
case 462:
raw_462(ga, ci);
break;
case 471:
raw_471(ga, ci, raw_buf);
break;
case 473:
raw_473(ga, ci, raw_buf);
break;
case 474:
raw_474(ga, ci, raw_buf);
break;
case 475:
raw_475(ga, ci, raw_buf);
break;
case 480:
raw_480(ga, ci, raw_buf);
break;
case 481:
raw_481(ga, ci, raw_buf);
break;
case 482:
raw_482(ga, ci, raw_buf);
break;
case 484:
raw_484(ga, ci, raw_buf);
break;
case 492:
raw_492(ga, ci, raw_buf);
break;
case 495:
raw_495(ga, ci, raw_buf);
break;
case 530:
raw_530(ga, ci, raw_buf);
break;
case 531:
raw_531(ga, ci, raw_buf);
break;
case 600:
raw_600(ga, ci, raw_buf);
break;
case 601:
raw_601(ga, ci, raw_buf);
break;
case 602:
raw_602(ga, raw_buf);
break;
case 604:
raw_604(ga, ci, raw_buf);
break;
case 605:
raw_605(ga, ci, raw_buf);
break;
case 607:
raw_607();
break;
case 666:
raw_666(ga, ci, raw_buf);
break;
case 801:
raw_801(ga, ci, raw_buf);
break;
case 807:
raw_807(ga, ci);
break;
case 808:
raw_808(ga, ci);
break;
case 809:
raw_809(ga, ci, raw_buf);
break;
case 811:
raw_811(ga, ci, raw_buf);
break;
case 812:
raw_812(ga, ci, raw_buf);
break;
case 815:
raw_815(ga, ci, raw_buf);
break;
case 816:
raw_816(ga, ci, raw_buf);
break;
case 817:
raw_817(ga, ci, raw_buf);
break;
case 942:
raw_942(ga, ci, raw_buf);
break;
case 950:
raw_950(ga, ci, raw_buf);
break;
case 951:
raw_951(ga, ci, raw_buf);
break;
// nieznany lub niezaimplementowany jeszcze RAW zwykły numeryczny
default:
raw_unknown = true;
/*
Koniec RAW zwykłych numerycznych.
*/
} // switch(std::stoi("0" + raw_parm1))
} // else if(raw_parm1 != "NOTICE")
/*
Koniec RAW zwykłych nienumerycznych oraz numerycznych.
*/
/*
RAW NOTICE nienumeryczne oraz numeryczne.
*/
else
{
switch(std::stoi("0" + get_raw_parm(raw_buf, 3))) // czwarty parametr RAW
{
/*
RAW NOTICE nienumeryczne.
*/
case 0:
raw_notice(ga, ci, raw_buf, raw_parm0);
break;
/*
Koniec RAW NOTICE nienumerycznych.
*/
/*
RAW NOTICE numeryczne.
*/
case 100:
raw_notice_100(ga, ci, raw_buf);
break;
case 109:
raw_notice_109(ga, ci, raw_buf);
break;
case 111:
raw_notice_111(ga, ci, raw_buf);
break;
case 112:
raw_notice_112(ga, ci, raw_buf);
break;
case 121:
raw_notice_121(ga, raw_buf);
break;
case 122:
raw_notice_122(ga, ci);
break;
case 131:
raw_notice_131(ga, raw_buf);
break;
case 132:
raw_notice_132(ga, ci);
break;
case 141:
raw_notice_141(ga, raw_buf);
break;
case 142:
raw_notice_142(ga, ci);
break;
case 151:
raw_notice_151(ga, raw_buf);
break;
case 152:
raw_notice_152(ga, ci, raw_buf);
break;
case 160:
raw_notice_160(ga, raw_buf);
break;
case 161:
raw_notice_161(ga, raw_buf);
break;
case 162:
raw_notice_162(ga, raw_buf);
break;
case 163:
raw_notice_163(ga, raw_buf);
break;
case 164:
raw_notice_164(ga, ci, raw_buf);
break;
case 165:
raw_notice_165(ga, raw_buf);
break;
case 210:
raw_notice_210(ga, ci, raw_buf);
break;
case 211:
raw_notice_211(ga, ci, raw_buf);
break;
case 220:
raw_notice_220(ga, ci, raw_buf);
break;
case 221:
raw_notice_221(ga, ci, raw_buf);
break;
case 230:
raw_notice_230(ga, ci, raw_buf);
break;
case 231:
raw_notice_231(ga, ci, raw_buf);
break;
case 240:
raw_notice_240(ga, ci, raw_buf);
break;
case 241:
raw_notice_241(ga, ci, raw_buf);
break;
case 250:
raw_notice_250(ga, ci, raw_buf);
break;
case 251:
raw_notice_251(ga, ci, raw_buf);
break;
case 252:
raw_notice_252();
break;
case 253:
raw_notice_253();
break;
case 254:
raw_notice_254(ga, ci, raw_buf);
break;
case 255:
raw_notice_255();
break;
case 256:
raw_notice_256(ga, ci, raw_buf);
break;
case 257:
raw_notice_257();
break;
case 258:
raw_notice_258(ga, ci, raw_buf);
break;
case 259:
raw_notice_259(ga, ci, raw_buf);
break;
case 260:
raw_notice_260(ga, ci, raw_buf);
break;
case 261:
raw_notice_261();
break;
case 400:
raw_notice_400(ga, ci);
break;
case 401:
raw_notice_401(ga, ci, raw_buf);
break;
case 402:
raw_notice_402(ga, ci, raw_buf);
break;
case 403:
raw_notice_403(ga, ci, raw_buf);
break;
case 404:
raw_notice_404(ga, ci, raw_buf);
break;
case 406:
raw_notice_406(ga, ci, raw_buf);
break;
case 407:
raw_notice_407(ga, ci, raw_buf);
break;
case 408:
raw_notice_408(ga, ci, raw_buf);
break;
case 409:
raw_notice_409(ga, ci, raw_buf);
break;
case 411:
raw_notice_411(ga, ci, raw_buf);
break;
case 415:
raw_notice_415(ga, ci, raw_buf);
break;
case 416:
raw_notice_416(ga, ci, raw_buf);
break;
case 420:
raw_notice_420(ga, ci, raw_buf);
break;
case 421:
raw_notice_421(ga, ci, raw_buf);
break;
case 430:
raw_notice_430(ga, ci, raw_buf);
break;
case 431:
raw_notice_431(ga, ci, raw_buf);
break;
case 440:
raw_notice_440(ga, ci, raw_buf);
break;
case 441:
raw_notice_441(ga, ci, raw_buf);
break;
case 452:
raw_notice_452(ga, ci, raw_buf);
break;
case 453:
raw_notice_453(ga, ci, raw_buf);
break;
case 454:
raw_notice_454(ga, ci, raw_buf);
break;
case 458:
raw_notice_458(ga, ci, raw_buf);
break;
case 459:
raw_notice_459(ga, ci, raw_buf);
break;
case 461:
raw_notice_461(ga, ci, raw_buf);
break;
case 463:
raw_notice_463(ga, ci, raw_buf);
break;
case 464:
raw_notice_464(ga, ci, raw_buf);
break;
case 465:
raw_notice_465(ga, ci, raw_buf);
break;
case 467:
raw_notice_467(ga, ci, raw_buf);
break;
case 468:
raw_notice_468(ga, ci, raw_buf);
break;
case 470:
raw_notice_470(ga, ci, raw_buf);
break;
case 472:
raw_notice_472(ga, ci, raw_buf);
break;
// nieznany lub niezaimplementowany jeszcze RAW NOTICE numeryczny
default:
raw_unknown = true;
/*
Koniec RAW NOTICE numerycznych.
*/
} // switch(std::stoi("0" + get_raw_parm(raw_buf, 3)))
} // else
/*
Koniec RAW NOTICE nienumerycznych oraz numerycznych.
*/
// nieznany lub niezaimplementowany RAW (każdego typu) wyświetl bez zmian w oknie "RawUnknown" (zostanie utworzone, jeśli nie jest)
if(raw_unknown)
{
new_chan_raw_unknown(ga, ci); // jeśli istnieje, funkcja nie utworzy ponownie pokoju
win_buf_add_str(ga, ci, "RawUnknown", xWHITE + raw_buf, true, 2, true, false); // aby zwrócić uwagę, pokaż aktywność typu 2
}
} // while(std::getline(irc_recv_buf_stream, raw_buf))
}
/*
Poniżej obsługa RAW ERROR i PING, które występują w odpowiedzi serwera na pierwszej pozycji (w kolejności alfabetycznej).
*/
/*
ERROR
ERROR :Closing link (76995189@adei211.neoplus.adsl.tpnet.pl) [Client exited]
ERROR :Closing link (76995189@adei211.neoplus.adsl.tpnet.pl) [Quit: z/w]
ERROR :Closing link (unknown@eqw75.neoplus.adsl.tpnet.pl) [Registration timeout]
*/
void raw_error(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
ga.irc_ok = false;
if(ga.ucc_quit_time)
{
ga.ucc_quit = true;
}
std::string srv_msg = form_from_chat(get_rest_from_buf(raw_buf, " :"));
// dodaj przed "]" formatowanie wyłączające ewentualnie użyte w komunikacie formatowanie tekstu (przywracające żółty kolor dla nawiasu zamykającego)
if(srv_msg.size() > 0 && srv_msg[srv_msg.size() - 1] == ']')
{
srv_msg.insert(srv_msg.size() - 1, xNORMAL xYELLOW);
}
win_buf_all_chan_msg(ga, ci, (get_value_from_buf(raw_buf, "ERROR :", " (") == "Closing link"
? oOUTn xYELLOW "Zamykanie połączenia " + get_rest_from_buf(srv_msg, " link ")
: oOUTn xYELLOW + srv_msg));
}
/*
PING
PING :cf1f1.onet
*/
void raw_ping(struct global_args &ga, struct channel_irc *ci[], std::string &raw_parm1)
{
// odpowiedz PONG na PING
irc_send(ga, ci, "PONG :" + raw_parm1);
// normalnie przy wysyłaniu przez ucc PING, serwer sam nie wysyła PING, ale zdarzyło się, że tak zrobił (brak PONG), dlatego na wszelki wypadek
// odebranie z serwera PING kasuje lag, aby nie zerwało połączenia (aby to działało, timeout w ucc musi być większy z zapasem od PING z serwera)
ga.lag = 0;
ga.lag_timeout = false;
}
/*
Poniżej obsługa RAW nienumerycznych, które występują w odpowiedzi serwera na drugiej pozycji (w kolejności alfabetycznej).
*/
/*
INVIGNORE
:Kernel_Panic!78259658@87edcc.6bc2d5.f4e8a2.b9d18c INVIGNORE ucc_test ^cf1f2753898
:Kernel_Panic!78259658@87edcc.6bc2d5.f4e8a2.b9d18c INVIGNORE ucc_test #ucc
*/
void raw_invignore(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// jeśli użytkownik zignorował zaproszenia do rozmów prywatnych i do pokoi, ale odpowiedź dotyczyła rozmowy prywatnej
if(raw_parm3.size() > 0 && raw_parm3[0] == '^')
{
// informacja w pokoju z rozmową prywatną
win_buf_add_str(ga, ci, raw_parm3,
oINFOn xRED + nick_who + " [" + nick_zuo_ip + "] zignorował(a) Twoje wszelkie zaproszenia do rozmów prywatnych oraz do "
"pokoi.");
}
// jeśli użytkownik zignorował zaproszenia do rozmów prywatnych i do pokoi, ale odpowiedź dotyczyła pokoju
else
{
// informacja w aktywnym pokoju (o ile to nie "Status", "DebugIRC" i "RawUnknown")
if(ga.current < CHAN_CHAT)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xRED + nick_who + " [" + nick_zuo_ip + "] zignorował(a) Twoje wszelkie zaproszenia do rozmów prywatnych oraz do "
"pokoi, w tym do " + raw_parm3);
}
// ta sama informacja w "Status"
win_buf_add_str(ga, ci, "Status",
oINFOn xRED + nick_who + " [" + nick_zuo_ip + "] zignorował(a) Twoje wszelkie zaproszenia do rozmów prywatnych oraz do "
"pokoi, w tym do " + raw_parm3);
}
}
/*
INVITE
:Kernel_Panic!78259658@87edcc.6bc2d5.9f815e.0d56cc INVITE ucc_test :^cf1f1551082
:ucieszony86!50256503@87edcc.6bc2d5.ee917f.54dae7 INVITE ucc_test :#ucc
*/
void raw_invite(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// jeśli to zaproszenie do rozmowy prywatnej
if(raw_parm3.size() > 0 && raw_parm3[0] == '^')
{
// informacja w aktywnym pokoju (o ile to nie "Status", "DebugIRC" i "RawUnknown")
if(ga.current < CHAN_CHAT)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOb xYELLOW_BLACK + nick_who
+ " [" + nick_zuo_ip + "] zaprasza Cię do rozmowy prywatnej, aby dołączyć, wpisz " xCYAN "/join " + raw_parm3);
}
// ta sama informacja w "Status"
win_buf_add_str(ga, ci, "Status",
oINFOb xYELLOW_BLACK + nick_who
+ " [" + nick_zuo_ip + "] zaprasza Cię do rozmowy prywatnej, aby dołączyć, wpisz " xCYAN "/join " + raw_parm3);
}
// jeśli to zaproszenie do pokoju
else
{
// po /join wytnij #, ale nie wycinaj go w pierwszej części zdania, dlatego użyj innego bufora
std::string chan_tmp = raw_parm3;
if(chan_tmp.size() > 0)
{
chan_tmp.erase(0, 1);
}
// informacja w aktywnym pokoju (o ile to nie "Status", "DebugIRC" i "RawUnknown")
if(ga.current < CHAN_CHAT)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOb xYELLOW_BLACK + nick_who
+ " [" + nick_zuo_ip + "] zaprasza Cię do pokoju " + raw_parm3 + ", aby dołączyć, wpisz " xCYAN "/join " + chan_tmp);
}
// ta sama informacja w "Status"
win_buf_add_str(ga, ci, "Status",
oINFOb xYELLOW_BLACK + nick_who
+ " [" + nick_zuo_ip + "] zaprasza Cię do pokoju " + raw_parm3 + ", aby dołączyć, wpisz " xCYAN "/join " + chan_tmp);
}
}
/*
INVREJECT
:Kernel_Panic!78259658@87edcc.6bc2d5.f4e8a2.b9d18c INVREJECT ucc_test ^cf1f1123456
:Kernel_Panic!78259658@87edcc.6bc2d5.f4e8a2.b9d18c INVREJECT ucc_test #ucc
*/
void raw_invreject(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// jeśli użytkownik odrzucił zaproszenie do rozmowy prywatnej
if(raw_parm3.size() > 0 && raw_parm3[0] == '^')
{
// informacja w pokoju z rozmową prywatną
win_buf_add_str(ga, ci, raw_parm3, oINFOn xRED + nick_who + " [" + nick_zuo_ip + "] odrzucił(a) Twoje zaproszenie do rozmowy prywatnej.");
}
// jeśli użytkownik odrzucił zaproszenie do pokoju
else
{
// informacja w aktywnym pokoju (o ile to nie "Status", "DebugIRC" i "RawUnknown")
if(ga.current < CHAN_CHAT)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xRED + nick_who + " [" + nick_zuo_ip + "] odrzucił(a) Twoje zaproszenie do pokoju " + raw_parm3);
}
// ta sama informacja w "Status"
win_buf_add_str(ga, ci, "Status", oINFOn xRED + nick_who + " [" + nick_zuo_ip + "] odrzucił(a) Twoje zaproszenie do pokoju " + raw_parm3);
}
}
/*
JOIN
:ucc_test!76995189@e0c697.bbe735.fea2d4.23661c JOIN #ucc :rx,0
:ucc_test!76995189@87edcc.6bc2d5.9f815e.0d56cc JOIN ^cf1f1551083 :rx,0
*/
void raw_join(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// jeśli to ja wchodzę, utwórz nowy kanał (jeśli wpisano /join, przechodź od razu do tego pokoju - ga.cf.join_priv)
if(nick_who == ga.zuousername && ! new_chan_chat(ga, ci, raw_parm2, ga.cf.join_priv))
{
// w przypadku błędu opuść pokój (i tak nie byłoby widać jego komunikatów)
irc_send(ga, ci, "PART " + raw_parm2 + " :Channel index out of range.");
// przełącz na "Status"
ga.current = CHAN_STATUS;
ga.win_chat_refresh = true;
// wyświetl ostrzeżenie
win_buf_add_str(ga, ci, "Status", uINFOn xRED "Nie udało się wejść do pokoju " + raw_parm2 + " (brak pamięci w tablicy pokoi).");
return;
}
// jeśli jest ^ (rozmowa prywatna), wyświetl odpowiedni komunikat
else if(raw_parm2.size() > 0 && raw_parm2[0] == '^')
{
// jeśli to ja dołączam do rozmowy prywatnej, komunikat będzie inny, niż jeśli to ktoś dołącza
win_buf_add_str(ga, ci, raw_parm2, (nick_who == ga.zuousername
? oINn xGREEN "Dołączasz do rozmowy prywatnej."
: oINn xGREEN + nick_who + " [" + nick_zuo_ip + "] dołącza do rozmowy prywatnej."));
}
// w przeciwnym razie wyświetl komunikat dla wejścia do pokoju
else
{
win_buf_add_str(ga, ci, raw_parm2, oINn xGREEN + nick_who + " [" + nick_zuo_ip + "] wchodzi do pokoju " + raw_parm2);
}
// pobierz wybrane flagi nicka
struct nick_flags flags = {};
std::string join_flags = get_rest_from_buf(raw_buf, " :");
if(join_flags.find("W") != std::string::npos)
{
flags.public_webcam = true;
}
if(join_flags.find("V") != std::string::npos)
{
flags.private_webcam = true;
}
if(join_flags.find("b") != std::string::npos)
{
flags.busy = true;
}
// dodaj nick do listy
new_or_update_nick_chan(ga, ci, raw_parm2, nick_who, nick_zuo_ip, flags);
// jeśli nick ma kamerkę, wyświetl o tym informację
if(flags.public_webcam)
{
win_buf_add_str(ga, ci, raw_parm2, oINFOn xWHITE + nick_who + " [" + nick_zuo_ip + "] posiada włączoną publiczną kamerkę.");
}
else if(flags.private_webcam)
{
win_buf_add_str(ga, ci, raw_parm2, oINFOn xWHITE + nick_who + " [" + nick_zuo_ip + "] posiada włączoną prywatną kamerkę.");
}
// odśwież listę w aktualnie otwartym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła nicka, który też jest w tym pokoju)
if(ga.win_info_state && ci[ga.current]->channel == raw_parm2)
{
ga.win_info_refresh = true;
}
}
/*
KICK
:AT89S8253!70914256@aaa2a7.a7f7a6.88308b.464974 KICK #ucc ucc_test :
:AT89S8253!70914256@aaa2a7.a7f7a6.88308b.464974 KICK #ucc ucc_test :Zachowuj się!
*/
void raw_kick(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
// pobierz powód, jeśli podano
std::string reason = form_from_chat(get_rest_from_buf(raw_buf, " :"));
if(reason.size() > 0)
{
reason.insert(0, " [");
reason += xNORMAL xRED "]";
}
// jeśli to mnie wyrzucono, pokaż inny komunikat
if(raw_parm3 == ga.zuousername)
{
// usuń kanał z programu
del_chan_chat(ga, ci, raw_parm2);
// komunikat o wyrzuceniu pokaż w "Status"
win_buf_add_str(ga, ci, "Status", oOUTn xRED "Zostajesz wyrzucony(-na) z pokoju " + raw_parm2 + " przez " + nick_who + reason);
}
else
{
// klucz nicka trzymany jest wielkimi literami
std::string nick_key = buf_lower2upper(raw_parm3);
// jeśli nick wszedł po mnie, to jego ZUO i IP jest na liście, wtedy dodaj je do komunikatu
std::string nick_zuo_ip;
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_key);
if(it != ci[i]->ni.end())
{
nick_zuo_ip = it->second.zuo_ip;
}
break;
}
}
// wyświetl powód wyrzucenia w pokoju, w którym wyrzucono nick
win_buf_add_str(ga, ci, raw_parm2,
// początek komunikatu (nick)
oOUTn xRED + raw_parm3 + (nick_zuo_ip.size() > 0
// jeśli było ZUO i IP
? " [" + nick_zuo_ip + "] zostaje wyrzucony(-na) z pokoju "
// jeśli nie było ZUO i IP
: " zostaje wyrzucony(-na) z pokoju ")
// reszta komunikatu oraz powód wyrzucenia (jeśli podano)
+ raw_parm2 + " przez " + nick_who + reason);
// usuń nick z listy
del_nick_chan(ga, ci, raw_parm2, raw_parm3);
// odśwież listę w aktualnie otwartym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła nicka, który też jest w tym pokoju)
if(ga.win_info_state && ci[ga.current]->channel == raw_parm2)
{
ga.win_info_refresh = true;
}
}
}
/*
MODE
Zmiany flag pokoju (przykładowe RAW):
:ChanServ!service@service.onet MODE #Towarzyski +b *!12345678@*
:ChanServ!service@service.onet MODE #Suwałki +b *!*@87edcc.6bc2d5.ee917f.54dae7
:ChanServ!service@service.onet MODE #ucc +qo ucieszony86 ucieszony86
:cf1f1.onet MODE #Suwałki +oq ucieszony86 ucieszony86
:ChanServ!service@service.onet MODE #ucc +h ucc_test
:ChanServ!service@service.onet MODE #ucc -b+eh *!76995189@* *!76995189@* ucc_test
:ChanServ!service@service.onet MODE #ucc +eh *!76995189@* ucc_test
:ChanServ!service@service.onet MODE #Towarzyski -m
:GuardServ!service@service.onet MODE #scc -I *!6@*
:Panie_kierowniku!57643619@devel.onet MODE #scc +J 120
:Panie_kierowniku!57643619@devel.onet MODE #ucc +J 1
:Panie_kierowniku!57643619@devel.onet MODE #ucc -J
:GuardServ!service@service.onet MODE #ucc +V
:ChanServ!service@service.onet MODE #ucc -ips
:ChanServ!service@service.onet MODE #ucc -e+e-oq+qo *!50256503@* *!80810606@* ucieszony86 ucieszony86 ucc ucc
:ChanServ!service@service.onet MODE #ucc +ks abc
:ChanServ!service@service.onet MODE #ucc +l 300
:ChanServ!service@service.onet MODE #pokój +F 1
:ChanServ!service@service.onet MODE #nowy_test +il-e 1 *!50256503@*
:ChanServ!service@service.onet MODE #nowy_test +il-ee 1 *!70914256@* *!50256503@*
Zmiany flag nicka (przykładowe RAW):
:Darom!12265854@devel.onet MODE Darom :+O
:Panie_kierowniku!57643619@devel.onet MODE Panie_kierowniku :+O
:nick1!80541395@87edcc.6f9b99.6bd006.aee4fc MODE nick1 +W
:ucc_test!76995189@87edcc.6bc2d5.1917ec.38c71e MODE ucc_test +x
:NickServ!service@service.onet MODE ucc_test +r
:cf1f4.onet MODE ucc_test +b
:Kernel_Panic!78259658@87edcc.6bc2d5.9f815e.0d56cc MODE Kernel_Panic :+b
Do zaimplementowania:
:ChanServ!service@service.onet MODE #ucc +c 1
*/
void raw_mode(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
// wyjaśnienie:
// nick_gives - nick, który nadaje/odbiera uprawnienia/statusy
// nick_receives - nick, który otrzymuje/któremu zabierane są uprawnienia/statusy
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
int raw_parm3_len = raw_parm3.size();
// flagi używane przy wchodzeniu do pokoi, które były otwarte po rozłączeniu, a program nie był zamknięty
bool my_flag_x = false, my_flag_r = false;
std::string a, nick_gives, chan_join;
// sprawdź, czy nick to typowy zapis np. ChanServ!service@service.onet, wtedy pobierz część przed !
// w przeciwnym razie (np. cf1f1.onet) pobierz całą część
nick_gives = (raw_parm0.find("!") != std::string::npos ? get_value_from_buf(raw_buf, ":", "!") : raw_parm0);
// wykryj, że to zwykły użytkownik czata (a nie np. ChanServ) ustawił daną flagę, dodaj wtedy "(a) " po "ustawił",
// nick_gives.find(".") == std::string::npos - nie dodawaj "(a) " dla nicka w stylu cf1f4.onet
if(nick_gives != "ChanServ" && nick_gives != "GuardServ" && nick_gives != "NickServ" && nick_gives.find(".") == std::string::npos)
{
a = "(a) ";
}
else
{
a = " ";
}
/*
Zmiany flag pokoju (grupowe, wybrane pozycje).
*/
if(raw_parm2.size() > 0 && raw_parm2[0] == '#' && (raw_parm3 == "+qo" || raw_parm3 == "+oq") && raw_parm4 == raw_parm5)
{
std::string nick_receives_key = buf_lower2upper(raw_parm4);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA + raw_parm4 + " jest teraz właścicielem i superoperatorem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagi
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.owner = true;
it->second.nf.op = true;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła nicka,
// który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2.size() > 0 && raw_parm2[0] == '#' && (raw_parm3 == "-qo" || raw_parm3 == "-oq") && raw_parm4 == raw_parm5)
{
std::string nick_receives_key = buf_lower2upper(raw_parm4);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA + raw_parm4 + " nie jest już właścicielem i superoperatorem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagi
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.owner = false;
it->second.nf.op = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła nicka,
// który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2.size() > 0 && raw_parm2[0] == '#' && raw_parm3 == "+ips")
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA "Pokój " + raw_parm2 + " jest teraz niewidoczny, prywatny i sekretny (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2.size() > 0 && raw_parm2[0] == '#' && raw_parm3 == "-ips")
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie jest już niewidoczny, prywatny i sekretny (ustawił" + a + nick_gives + ").");
}
else
{
int s = 0; // pozycja znaku +/- od początku raw_parm3
int o = 3; // offset argumentu względem początku flag (licząc od zera)
for(int f = 0; f < raw_parm3_len; ++f)
{
if(raw_parm3[f] == '+' || raw_parm3[f] == '-')
{
s = f;
continue; // gdy znaleziono znak + lub -, powróć do początku
}
/*
Zmiany flag pokoju (nie trzeba sprawdzać, czy raw_parm2 ma rozmiar większy od zera, bo wejście do tej pętli zawdzięczamy raw_parm3 większemu od zera).
*/
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'q' && raw_parm3[s] == '+')
{
++o; // flaga z argumentem
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA + nick_receives + " jest teraz właścicielem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.owner = true;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'q' && raw_parm3[s] == '-')
{
++o; // flaga z argumentem
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE + nick_receives + " nie jest już właścicielem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.owner = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'o' && raw_parm3[s] == '+')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA + nick_receives + " jest teraz superoperatorem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.op = true;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'o' && raw_parm3[s] == '-')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE + nick_receives + " nie jest już superoperatorem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.op = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'h' && raw_parm3[s] == '+')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA + nick_receives + " jest teraz operatorem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.halfop = true;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'h' && raw_parm3[s] == '-')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE + nick_receives + " nie jest już operatorem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.halfop = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'v' && raw_parm3[s] == '+')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xBLUE + nick_receives + " jest teraz gościem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.voice = true;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'v' && raw_parm3[s] == '-')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE + nick_receives + " nie jest już gościem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.voice = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'X' && raw_parm3[s] == '+')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA + nick_receives + " jest teraz moderatorem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.moderator = true;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'X' && raw_parm3[s] == '-')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
std::string nick_receives_key = buf_lower2upper(nick_receives);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE + nick_receives + " nie jest już moderatorem pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
// zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
it->second.nf.moderator = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
break;
}
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'b' && raw_parm3[s] == '+')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xRED + nick_receives + " otrzymuje bana w pokoju " + raw_parm2 + " (ustawił" + a + nick_gives + ").");
// wykryj, czy serwer odpowiedział na /kban lub /kbanip, po którym należy wysłać KICK
std::string kban_nick_key = buf_lower2upper(nick_receives);
auto it = ga.kb.find(kban_nick_key);
// it != ga.kb.end() - czy to nick, który otrzymał ode mnie /kban lub /kbanip
// ga.zuousername == nick_gives - czy to ja mu dałem /kban lub /kbanip
// it->second.chan == raw_parm2 - czy to pokój, w którym otrzymał /kban lub /kbanip
if(it != ga.kb.end() && ga.zuousername == nick_gives && it->second.chan == raw_parm2)
{
irc_send(ga, ci, "KICK " + it->second.chan + " " + it->second.nick + " :" + it->second.reason);
// po użyciu wyczyść użycie /kban lub /kbanip
ga.kb.erase(kban_nick_key);
}
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'b' && raw_parm3[s] == '-')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE + nick_receives + " nie posiada już bana w pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'e' && raw_parm3[s] == '+')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA + nick_receives + " posiada teraz wyjątek od bana w pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'e' && raw_parm3[s] == '-')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE + nick_receives + " nie posiada już wyjątku od bana w pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'I' && raw_parm3[s] == '+')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA + nick_receives + " jest teraz na liście zaproszonych w pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'I' && raw_parm3[s] == '-')
{
++o;
std::string nick_receives = get_raw_parm(raw_buf, o);
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE + nick_receives + " nie jest już na liście zaproszonych w pokoju " + raw_parm2
+ " (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'J' && raw_parm3[s] == '+')
{
++o;
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA "Pokój " + raw_parm2 + " posiada teraz blokadę, ustawioną na "
+ get_raw_parm(raw_buf, o) + "s, uniemożliwiającą użytkownikom automatyczny powrót po wyrzuceniu "
"ich z pokoju (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'J' && raw_parm3[s] == '-')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie posiada już blokady, uniemożliwiającej użytkownikom automatyczny "
"powrót po wyrzuceniu ich z pokoju (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'V' && raw_parm3[s] == '+')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xRED "Pokój " + raw_parm2 + " posiada teraz blokadę zaproszeń (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'V' && raw_parm3[s] == '-')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie posiada już blokady zaproszeń (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'm' && raw_parm3[s] == '+')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA "Pokój " + raw_parm2 + " jest teraz moderowany (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'm' && raw_parm3[s] == '-')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie jest już moderowany (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'k' && raw_parm3[s] == '+')
{
++o;
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA "Pokój " + raw_parm2 + " posiada teraz hasło dostępu: " xBOLD_ON
+ get_raw_parm(raw_buf, o) + xBOLD_OFF " (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'k' && raw_parm3[s] == '-')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie posiada już hasła dostępu (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'l' && raw_parm3[s] == '+')
{
++o;
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA "Pokój " + raw_parm2 + " posiada teraz limit osób jednocześnie przebywających w pokoju "
"(" + get_raw_parm(raw_buf, o) + ") (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'l' && raw_parm3[s] == '-')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie posiada już limitu osób jednocześnie przebywających w pokoju "
"(ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'F' && raw_parm3[s] == '+')
{
++o;
std::string rank = get_raw_parm(raw_buf, o);
// bez 0, bo + oznacza zwiększanie rangi
if(rank == "1")
{
rank = "Oswojony";
}
else if(rank == "2")
{
rank = "Z klasą";
}
else if(rank == "3")
{
rank = "Kultowy";
}
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA "Pokój " + raw_parm2 + " posiada teraz rangę \"" + rank
+ "\" (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'F' && raw_parm3[s] == '-')
{
++o;
std::string rank = get_raw_parm(raw_buf, o);
// bez 3, bo - oznacza zmniejszenie rangi
if(rank == "2")
{
rank = "Z klasą";
}
else if(rank == "1")
{
rank = "Oswojony";
}
else if(rank == "0")
{
rank = "Dziki";
}
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie posiada już rangi \"" + rank
+ "\" (ustawił" + a + nick_gives + ").");
}
// czasem poniższe flagi (ips) pojawiają się oddzielnie, dlatego zostawiono je, mimo wcześniejszego wykrycia +/-ips)
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'i' && raw_parm3[s] == '+')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA "Pokój " + raw_parm2 + " jest teraz niewidoczny (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'i' && raw_parm3[s] == '-')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie jest już niewidoczny (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'p' && raw_parm3[s] == '+')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA "Pokój " + raw_parm2 + " jest teraz prywatny (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 'p' && raw_parm3[s] == '-')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie jest już prywatny (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 's' && raw_parm3[s] == '+')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xMAGENTA "Pokój " + raw_parm2 + " jest teraz sekretny (ustawił" + a + nick_gives + ").");
}
else if(raw_parm2[0] == '#' && raw_parm3[f] == 's' && raw_parm3[s] == '-')
{
win_buf_add_str(ga, ci, raw_parm2,
oINFOn xWHITE "Pokój " + raw_parm2 + " nie jest już sekretny (ustawił" + a + nick_gives + ").");
}
/*
Zmiany flag osób.
*/
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'O' && raw_parm3[s] == '+')
{
std::string nick_receives = raw_parm2;
std::string nick_receives_key = buf_lower2upper(nick_receives);
// pokaż informację we wszystkich pokojach, gdzie jest dany nick
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->ni.find(nick_receives_key) != ci[i]->ni.end())
{
win_buf_add_str(ga, ci, ci[i]->channel,
oINFOn xMAGENTA + nick_receives + " jest teraz netadministratorem czata (ustawił"
+ a + nick_gives + ").");
}
}
}
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'O' && raw_parm3[s] == '-')
{
std::string nick_receives = raw_parm2;
std::string nick_receives_key = buf_lower2upper(nick_receives);
// pokaż informację we wszystkich pokojach, gdzie jest dany nick
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->ni.find(nick_receives_key) != ci[i]->ni.end())
{
win_buf_add_str(ga, ci, ci[i]->channel,
oINFOn xWHITE + nick_receives + " nie jest już netadministratorem czata (ustawił"
+ a + nick_gives + ").");
}
}
}
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'W' && raw_parm3[s] == '+')
{
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_who_key = buf_lower2upper(nick_who);
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// pokaż informację we wszystkich pokojach, gdzie jest dany nick oraz zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i])
{
auto it = ci[i]->ni.find(nick_who_key);
if(it != ci[i]->ni.end())
{
win_buf_add_str(ga, ci, ci[i]->channel,
oINFOn xWHITE + nick_who + " [" + nick_zuo_ip + "] włącza publiczną kamerkę.");
// zaktualizuj flagę
it->second.nf.public_webcam = true;
// ze względu na obecny brak zmiany flagi V (brak MODE) należy ją wyzerować po włączeniu W
it->second.nf.private_webcam = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
}
}
}
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'W' && raw_parm3[s] == '-')
{
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_who_key = buf_lower2upper(nick_who);
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// pokaż informację we wszystkich pokojach, gdzie jest dany nick oraz zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i])
{
auto it = ci[i]->ni.find(nick_who_key);
if(it != ci[i]->ni.end())
{
win_buf_add_str(ga, ci, ci[i]->channel,
oINFOn xWHITE + nick_who + " [" + nick_zuo_ip + "] wyłącza publiczną kamerkę.");
// zaktualizuj flagę
it->second.nf.public_webcam = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
}
}
}
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'V' && raw_parm3[s] == '+')
{
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_who_key = buf_lower2upper(nick_who);
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// pokaż informację we wszystkich pokojach, gdzie jest dany nick oraz zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i])
{
auto it = ci[i]->ni.find(nick_who_key);
if(it != ci[i]->ni.end())
{
win_buf_add_str(ga, ci, ci[i]->channel,
oINFOn xWHITE + nick_who + " [" + nick_zuo_ip + "] włącza prywatną kamerkę.");
// zaktualizuj flagę
it->second.nf.private_webcam = true;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
}
}
}
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'V' && raw_parm3[s] == '-')
{
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_who_key = buf_lower2upper(nick_who);
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// pokaż informację we wszystkich pokojach, gdzie jest dany nick oraz zaktualizuj flagę
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i])
{
auto it = ci[i]->ni.find(nick_who_key);
if(it != ci[i]->ni.end())
{
win_buf_add_str(ga, ci, ci[i]->channel,
oINFOn xWHITE + nick_who + " [" + nick_zuo_ip + "] wyłącza prywatną kamerkę.");
// zaktualizuj flagę
it->second.nf.private_webcam = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
}
}
}
// aktualizacja flagi busy na liście nicków
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'b' && raw_parm3[s] == '+')
{
std::string nick_receives_key = buf_lower2upper(raw_parm2);
// zaktualizuj flagę we wszystkich pokojach, gdzie jest dany nick
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i])
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
// zaktualizuj flagę
it->second.nf.busy = true;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
}
}
}
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'b' && raw_parm3[s] == '-')
{
std::string nick_receives_key = buf_lower2upper(raw_parm2);
// zaktualizuj flagę we wszystkich pokojach, gdzie jest dany nick
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i])
{
auto it = ci[i]->ni.find(nick_receives_key);
if(it != ci[i]->ni.end())
{
// zaktualizuj flagę
it->second.nf.busy = false;
// odśwież listę w aktualnym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła
// nicka, który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
}
}
}
// pokazuj tylko informację o mnie, że mam szyfrowanie IP (w pokoju "Status")
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'x' && raw_parm3[s] == '+' && raw_parm2 == ga.zuousername)
{
std::string nick_ip = get_value_from_buf(raw_buf, "@", " ");
win_buf_add_str(ga, ci, "Status", oINFOn xGREEN "Twój adres IP jest teraz wyświetlany w formie zaszyfrowanej ("
+ nick_ip + ").");
my_flag_x = true;
}
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'x' && raw_parm3[s] == '-' && raw_parm2 == ga.zuousername)
{
std::string nick_ip = get_value_from_buf(raw_buf, "@", " ");
win_buf_add_str(ga, ci, "Status", oINFOn xRED "Twój adres IP nie jest już wyświetlany w formie zaszyfrowanej ("
+ nick_ip + ").");
}
// pokazuj tylko mój zarejestrowany nick (w pokoju "Status")
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'r' && raw_parm3[s] == '+' && raw_parm2 == ga.zuousername)
{
win_buf_add_str(ga, ci, "Status", oINFOn xGREEN "Jesteś teraz zarejestrowanym użytkownikiem (ustawił"
+ a + nick_gives + ").");
my_flag_r = true;
}
else if(raw_parm2[0] != '#' && raw_parm3[f] == 'r' && raw_parm3[s] == '-' && raw_parm2 == ga.zuousername)
{
win_buf_add_str(ga, ci, "Status", oINFOn xRED "Nie jesteś już zarejestrowanym użytkownikiem (ustawił"
+ a + nick_gives + ").");
}
// nieznane lub niezaimplementowane RAW MODE wyświetl bez zmian w oknie "RawUnknown"
else
{
new_chan_raw_unknown(ga, ci); // jeśli istnieje, funkcja nie utworzy ponownie pokoju
win_buf_add_str(ga, ci, "RawUnknown", xWHITE + raw_buf, true, 2, true, false); // aby zwrócić uwagę, pokaż aktywność typu 2
}
}
}
// jeśli wylogowaliśmy się, ale nie zamknęliśmy programu i były otwarte jakieś pokoje, wejdź do nich ponownie po zalogowaniu
// - po +r dla nicka zarejestrowanego
// - po +x dla nicka tymczasowego
if(my_flag_r || (my_flag_x && ga.zuousername.size() > 0 && ga.zuousername[0] == '~'))
{
for(int i = 0; i < CHAN_CHAT; ++i) // szukaj jedynie pokoi czata, bez "Status", "DebugIRC" i "RawUnknown"
{
if(ci[i] && ci[i]->channel.size() > 0)
{
// pierwszy pokój przepisz bez zmian, kolejne pokoje muszą być rozdzielone przecinkiem
chan_join += (chan_join.size() == 0 ? "" : ",") + ci[i]->channel;
}
}
}
if(chan_join.size() > 0)
{
irc_send(ga, ci, "JOIN " + chan_join);
}
}
/*
MODERMSG
:M_X!36866915@d2d929.646f7c.4180a1.bd429d MODERMSG ucc_test - #Towarzyski :Moderowany?
:M_X!36866915@d2d929.646f7c.4180a1.bd429d MODERMSG nick1 - #Towarzyski :%Fb%text
*/
void raw_modermsg(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
// wiadomość użytkownika
std::string user_msg = form_from_chat(get_rest_from_buf(raw_buf, " :"));
std::string form_start;
int act_type;
// jeśli ktoś mnie woła, jego nick wyświetl w żółtym kolorze
if(user_msg.find(ga.zuousername) != std::string::npos)
{
form_start = xYELLOW;
// gdy ktoś mnie woła, pokaż aktywność typu 3
act_type = 3;
// testowa wersja dźwięku, do poprawy jeszcze
if(std::system("aplay -q /usr/share/sounds/pop.wav 2>/dev/null &") != 0) {}
}
else
{
// gdy ktoś pisze, ale mnie nie woła, pokaż aktywność typu 2
act_type = 2;
}
// wykryj, gdy ktoś pisze przez użycie /me
std::string user_msg_action = get_value_from_buf(user_msg, "\x01" "ACTION", "\x01");
win_buf_add_str(ga, ci, raw_parm4, (user_msg_action.size() > 0 && user_msg_action[0] == ' '
// tekst pisany z użyciem /me
? xMAGENTA "* " + form_start + raw_parm2 + xNORMAL + user_msg_action
// tekst normalny
: xCYAN + form_start + "<" + raw_parm2 + ">" + xNORMAL " " + user_msg)
// reszta komunikatu
+ " " xNORMAL xUNDERLINE_ON xRED "[Moderowany przez " + nick_who + "]", true, act_type);
}
/*
PART
:ucc_test!76995189@e0c697.bbe735.fea2d4.23661c PART #ucc
:ucc_test!76995189@e0c697.bbe735.fea2d4.23661c PART #ucc :Bye
:ucc_test!76995189@87edcc.6bc2d5.9f815e.0d56cc PART ^cf1f3561508
:ucc_test!76995189@87edcc.6bc2d5.9f815e.0d56cc PART ^cf1f1552723 :Koniec rozmowy
*/
void raw_part(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// pobierz powód, jeśli podano
std::string reason = form_from_chat(get_rest_from_buf(raw_buf, " :"));
if(reason.size() > 0)
{
reason.insert(0, " [");
reason += xNORMAL xCYAN "]";
}
// jeśli jest ^ (rozmowa prywatna), wyświetl odpowiedni komunikat
if(raw_parm2.size() > 0 && raw_parm2[0] == '^')
{
if(reason.size() == 0)
{
reason = ".";
}
win_buf_add_str(ga, ci, raw_parm2, (nick_who == ga.zuousername
// jeśli to ja opuszczam rozmowę prywatną
? oOUTn xCYAN "Opuszczasz rozmowę prywatną"
// jeśli osoba, z którą pisałem, opuszcza rozmowę prywatną
: oOUTn xCYAN + nick_who + " [" + nick_zuo_ip + "] opuszcza rozmowę prywatną")
// powód wyjścia (gdy podano)
+ reason);
}
// w przeciwnym razie wyświetl komunikat dla wyjścia z pokoju
else
{
win_buf_add_str(ga, ci, raw_parm2, oOUTn xCYAN + nick_who + " [" + nick_zuo_ip + "] wychodzi z pokoju " + raw_parm2 + reason);
}
// jeśli to ja wychodzę, usuń kanał z programu
if(nick_who == ga.zuousername)
{
del_chan_chat(ga, ci, raw_parm2);
}
else
{
// usuń nick z listy
del_nick_chan(ga, ci, raw_parm2, nick_who);
// odśwież listę w aktualnie otwartym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła nicka, który też jest w tym pokoju)
if(ga.win_info_state && ci[ga.current]->channel == raw_parm2)
{
ga.win_info_refresh = true;
}
}
}
/*
PONG (odpowiedź serwera na wysłany PING)
:cf1f4.onet PONG cf1f4.onet :1404173770345
*/
void raw_pong(struct global_args &ga, std::string &raw_buf)
{
// niereagowanie na wpisanie '/raw PING coś' (trzeba znać wysłaną wartość, a ręcznie jest to praktycznie niemożliwe do określenia), aby nie
// fałszować informacji o lag wyświetlanej na dolnym pasku
if(std::to_string(ga.ping) == get_raw_parm(raw_buf, 3))
{
struct timeval tv_pong;
int64_t pong_sec, pong_usec;
gettimeofday(&tv_pong, NULL);
pong_sec = tv_pong.tv_sec;
pong_usec = tv_pong.tv_usec;
ga.pong = (pong_sec * 1000) + (pong_usec / 1000);
ga.lag = ga.pong - ga.ping;
ga.lag_timeout = false;
}
}
/*
PRIVMSG
:AT89S8253!70914256@aaa2a7.a7f7a6.88308b.464974 PRIVMSG #ucc :Hello.
:Kernel_Panic!78259658@87edcc.6bc2d5.1917ec.38c71e PRIVMSG #ucc :\1ACTION %Cff0000%widzi co się dzieje.\1
*/
void raw_privmsg(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
// wiadomość użytkownika
std::string user_msg = form_from_chat(get_rest_from_buf(raw_buf, " :"));
std::string form_start;
int act_type;
// jeśli ktoś mnie woła, pogrub jego nick i wyświetl w żółtym kolorze
if(user_msg.find(ga.zuousername) != std::string::npos)
{
form_start = xBOLD_ON xYELLOW_BLACK;
// gdy ktoś mnie woła, pokaż aktywność typu 3
act_type = 3;
// testowa wersja dźwięku, do poprawy jeszcze
if(std::system("aplay -q /usr/share/sounds/pop.wav 2>/dev/null &") != 0) {}
}
else
{
// gdy ktoś pisze, ale mnie nie woła, pokaż aktywność typu 2
act_type = 2;
}
// wykryj, gdy ktoś pisze przez użycie /me
std::string user_msg_action = get_value_from_buf(user_msg, "\x01" "ACTION", "\x01");
// tekst pisany z użyciem /me
if(user_msg_action.size() > 0 && user_msg_action[0] == ' ')
{
win_buf_add_str(ga, ci, raw_parm2, xBOLD_ON xMAGENTA "* " + form_start + nick_who + xNORMAL + user_msg_action, true, act_type);
}
// tekst normalny
else
{
std::string nick_stat;
// jeśli pokazywanie statusu nicka jest włączone, dodaj je do nicka (busy również ma wpływ na nick)
if(ga.show_stat_in_win_chat)
{
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
auto it = ci[i]->ni.find(buf_lower2upper(nick_who));
if(it != ci[i]->ni.end())
{
nick_stat = xNORMAL + get_flags_nick(ga, ci, i, it->first);
}
break;
}
}
}
win_buf_add_str(ga, ci, raw_parm2,
form_start + "<" + nick_stat + form_start + nick_who
+ (form_start.size() > 0 ? form_start + ">" xNORMAL " " : xNORMAL "> ") + user_msg, true, act_type);
// przy włączonym away pokazuj w "Status" odpowiednie powiadomienia, gdy ktoś pisze do mnie
if(act_type == 3 && ga.my_away)
{
win_buf_add_str(ga, ci, "Status",
"[" + get_time_full() + "] " xGREEN + raw_parm2 + xWHITE ":" xTERMC " " xBOLD_ON xYELLOW_BLACK
"<" + nick_who + ">" xNORMAL " " + user_msg, true, 3, false);
}
}
}
/*
QUIT
:Kernel_Panic!78259658@e0c697.bbe735.fea2d4.23661c QUIT :Client exited
:Kernel_Panic!78259658@e0c697.bbe735.fea2d4.23661c QUIT :Quit: Do potem
*/
void raw_quit(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
// klucz nicka trzymany jest wielkimi literami
std::string nick_who_key = buf_lower2upper(nick_who);
// usuń nick ze wszystkich pokoi z listy, gdzie przebywał i wyświetl w tych pokojach komunikat o tym
for(int i = 0; i < CHAN_CHAT; ++i) // szukaj jedynie pokoi czata, bez "Status", "DebugIRC" i "RawUnknown"
{
// usuwać można tylko w otwartych pokojach oraz nie usuwaj nicka, jeśli takiego nie było w pokoju
if(ci[i] && ci[i]->ni.find(nick_who_key) != ci[i]->ni.end())
{
// w pokoju, w którym był nick wyświetl komunikat o jego wyjściu
win_buf_add_str(ga, ci, ci[i]->channel,
oOUTn xYELLOW + nick_who + " [" + nick_zuo_ip + "] wychodzi z czata ["
+ form_from_chat(get_rest_from_buf(raw_buf, " :")) + xNORMAL xYELLOW "]");
// usuń nick z listy
ci[i]->ni.erase(nick_who_key);
// odśwież listę w aktualnie otwartym pokoju (o ile włączone jest okno informacyjne oraz zmiana dotyczyła nicka,
// który też jest w tym pokoju)
if(ga.win_info_state && i == ga.current)
{
ga.win_info_refresh = true;
}
}
}
}
/*
TOPIC (CS SET #pokój TOPIC ...)
:cf1f3.onet TOPIC #ucc :Ucieszony Chat Client
TOPIC (TOPIC #pokój :...)
:ucc_test!76995189@87edcc.30c29e.b9c507.d5c6b7 TOPIC #ucc :nowy temat
*/
void raw_topic(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
// gdy ustawiono temat przez (tak robi program): CS SET #pokój TOPIC ...
// wtedy inaczej zwracany jest nick
if(raw_parm0.find("!") == std::string::npos)
{
win_buf_add_str(ga, ci, raw_parm2, oINFOn xMAGENTA + raw_parm0 + " zmienił temat pokoju " + raw_parm2);
}
// w przeciwnym razie temat ustawiony przez: TOPIC #pokój :...
else
{
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
std::string nick_zuo_ip = get_value_from_buf(raw_buf, "!", " ");
win_buf_add_str(ga, ci, raw_parm2, oINFOn xMAGENTA + nick_who + " [" + nick_zuo_ip + "] zmienił(a) temat pokoju " + raw_parm2);
}
// sam temat również wyświetl i wpisz do bufora tematu kanału, aby wyświetlić go na górnym pasku
// (reszta jest identyczna jak w obsłudze RAW 332, trzeba tylko zamiast raw_parm3 wysłać raw_parm2)
raw_332(ga, ci, raw_buf, raw_parm2);
}
/*
Poniżej obsługa RAW numerycznych, które występują w odpowiedzi serwera na drugiej pozycji (w kolejności numerycznej).
*/
/*
001
:cf1f2.onet 001 ucc_test :Welcome to the OnetCzat IRC Network ucc_test!76995189@acvy210.neoplus.adsl.tpnet.pl
*/
void raw_001(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
// pobierz mój numer ZUO
ga.my_zuo = get_value_from_buf(raw_buf, ga.zuousername + "!", "@");
// test - znajdź plik vhost.txt, jeśli jest, wczytaj go i wyślij na serwer, aby zmienić swój host (do poprawy jeszcze)
std::ifstream vhost_file;
vhost_file.open(ga.user_dir + "/vhost.txt");
if(vhost_file.good())
{
// uwaga - nie jest sprawdzana poprawność zapisu pliku (jedynie, że coś jest w nim), zakłada się, że plik zawiera login i hasło (do poprawy)
std::string vhost_str;
std::getline(vhost_file, vhost_str);
if(vhost_str.size() > 0)
{
irc_send(ga, ci, "VHOST " + vhost_str);
}
vhost_file.close();
}
}
/*
002
:cf1f2.onet 002 ucc_test :Your host is cf1f2.onet, running version InspIRCd-1.1
*/
void raw_002()
{
}
/*
003
:cf1f2.onet 003 ucc_test :This server was created 02:35:04 Feb 16 2011
*/
void raw_003()
{
}
/*
004
:cf1f2.onet 004 ucc_test cf1f2.onet InspIRCd-1.1 BOQRVWbinoqrswx DFIKMRVXYabcehiklmnopqrstuv FIXYabcehkloqv
*/
void raw_004()
{
}
/*
005
:cf1f2.onet 005 ucc_test WALLCHOPS WALLVOICES MODES=19 CHANTYPES=^# PREFIX=(qaohXYv)`&@%!=+ MAP MAXCHANNELS=20 MAXBANS=60 VBANLIST NICKLEN=32 CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii :are supported by this server
:cf1f2.onet 005 ucc_test TOPICLEN=203 KICKLEN=255 MAXTARGETS=20 AWAYLEN=200 CHANMODES=Ibe,k,Fcl,DKMRVimnprstu FNC NETWORK=OnetCzat MAXPARA=32 ELIST=MU OVERRIDE ONETNAMESX INVEX=I EXCEPTS=e :are supported by this server
:cf1f2.onet 005 ucc_test INVIGNORE=100 USERIP ESILENCE SILENCE=100 WATCH=200 NAMESX :are supported by this server
*/
void raw_005()
{
}
/*
251 (LUSERS)
:cf1f2.onet 251 ucc_test :There are 1933 users and 5 invisible on 10 servers
*/
void raw_251(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
if(ga.cf.lusers)
{
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm8 = get_raw_parm(raw_buf, 8);
std::string raw_parm11 = get_raw_parm(raw_buf, 11);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
// początek komunikatu (nazwa serwera)
xBOLD_ON "-" xBLUE + raw_parm0 +
// wykryj ciąg z RAW powyżej
(srv_msg == "There are " + raw_parm5 + " users and " + raw_parm8 + " invisible on " + raw_parm11 + " servers"
// jeśli szukany ciąg istnieje, przetłumacz go
? xTERMC "- Liczba użytkowników: " + raw_parm5 + ", niewidoczni: " + raw_parm8 + ", liczba serwerów: " + raw_parm11
// jeśli szukany ciąg nie istnieje (np. został zmieniony), wyświetl komunikat w formie oryginalnej
: xTERMC "- " + srv_msg));
}
}
/*
252 (LUSERS)
:cf1f2.onet 252 ucc_test 8 :operator(s) online
*/
void raw_252(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
if(ga.cf.lusers)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
// początek komunikatu (nazwa serwera)
xBOLD_ON "-" xBLUE + raw_parm0 +
// wykryj ciąg z RAW powyżej
(srv_msg == "operator(s) online"
// jeśli szukany ciąg istnieje, przetłumacz go
? xTERMC "-" xNORMAL " Zalogowani operatorzy: " + raw_parm3
// jeśli szukany ciąg nie istnieje (np. został zmieniony), wyświetl komunikat w formie oryginalnej
: xTERMC "-" xNORMAL " " + raw_parm3 + " " + srv_msg));
}
}
/*
253 (LUSERS)
:cf1f1.onet 253 ucc_test 1 :unknown connections
*/
void raw_253(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
if(ga.cf.lusers)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
// początek komunikatu (nazwa serwera)
xBOLD_ON "-" xBLUE + raw_parm0 +
// wykryj ciąg z RAW powyżej
(srv_msg == "unknown connections"
// jeśli szukany ciąg istnieje, przetłumacz go
? xTERMC "-" xNORMAL " Nieznane połączenia: " + raw_parm3
// jeśli szukany ciąg nie istnieje (np. został zmieniony), wyświetl komunikat w formie oryginalnej
: xTERMC "-" xNORMAL " " + raw_parm3 + " " + srv_msg));
}
}
/*
254 (LUSERS)
:cf1f2.onet 254 ucc_test 2422 :channels formed
*/
void raw_254(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
if(ga.cf.lusers)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
// początek komunikatu (nazwa serwera)
xBOLD_ON "-" xBLUE + raw_parm0 +
// wykryj ciąg z RAW powyżej
(srv_msg == "channels formed"
// jeśli szukany ciąg istnieje, przetłumacz go
? xTERMC "-" xNORMAL " Utworzone pokoje: " + raw_parm3
// jeśli szukany ciąg nie istnieje (np. został zmieniony), wyświetl komunikat w formie oryginalnej
: xTERMC "-" xNORMAL " " + raw_parm3 + " " + srv_msg));
}
}
/*
255 (LUSERS)
:cf1f2.onet 255 ucc_test :I have 478 clients and 1 servers
*/
void raw_255(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
if(ga.cf.lusers)
{
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm8 = get_raw_parm(raw_buf, 8);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
// początek komunikatu (nazwa serwera)
xBOLD_ON "-" xBLUE + raw_parm0 +
// wykryj ciąg z RAW powyżej
(srv_msg == "I have " + raw_parm5 + " clients and " + raw_parm8 + " servers"
// jeśli szukany ciąg istnieje, przetłumacz go
? xTERMC "-" xNORMAL " Posiadana liczba klientów: " + raw_parm5 + ", serwerów: " + raw_parm8
// jeśli szukany ciąg nie istnieje (np. został zmieniony), wyświetl komunikat w formie oryginalnej
: xTERMC "-" xNORMAL " " + srv_msg));
}
}
/*
256 (ADMIN)
:cf1f3.onet 256 ucc_test :Administrative info for cf1f3.onet
*/
void raw_256(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, xBOLD_ON "-" xBLUE + raw_parm0 + xTERMC "- " + get_rest_from_buf(raw_buf, " :"));
}
/*
257 (ADMIN)
:cf1f3.onet 257 ucc_test :Name - Czat Admin
*/
void raw_257(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, xBOLD_ON "-" xBLUE + raw_parm0 + xTERMC "-" xNORMAL " " + get_rest_from_buf(raw_buf, " :"));
}
/*
258 (ADMIN)
:cf1f3.onet 258 ucc_test :Nickname - czat_admin
*/
void raw_258(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, xBOLD_ON "-" xBLUE + raw_parm0 + xTERMC "-" xNORMAL " " + get_rest_from_buf(raw_buf, " :"));
}
/*
259 (ADMIN)
:cf1f3.onet 259 ucc_test :E-Mail - czat_admin@czat.onet.pl
*/
void raw_259(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, xBOLD_ON "-" xBLUE + raw_parm0 + xTERMC "-" xNORMAL " " + get_rest_from_buf(raw_buf, " :"));
}
/*
265 (LUSERS)
:cf1f2.onet 265 ucc_test :Current Local Users: 478 Max: 619
*/
void raw_265(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
if(ga.cf.lusers)
{
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
std::string raw_parm8 = get_raw_parm(raw_buf, 8);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
// początek komunikatu (nazwa serwera)
xBOLD_ON "-" xBLUE + raw_parm0 +
// wykryj ciąg z RAW powyżej
(srv_msg == "Current Local Users: " + raw_parm6 + " Max: " + raw_parm8
// jeśli szukany ciąg istnieje, przetłumacz go
? xTERMC "-" xNORMAL " Użytkownicy obecni lokalnie: " + raw_parm6 + ", maksymalnie: " + raw_parm8
// jeśli szukany ciąg nie istnieje (np. został zmieniony), wyświetl komunikat w formie oryginalnej
: xTERMC "-" xNORMAL " " + srv_msg));
}
}
/*
266 (LUSERS)
:cf1f2.onet 266 ucc_test :Current Global Users: 1938 Max: 2487
*/
void raw_266(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
if(ga.cf.lusers)
{
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
std::string raw_parm8 = get_raw_parm(raw_buf, 8);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
// początek komunikatu (nazwa serwera)
xBOLD_ON "-" xBLUE + raw_parm0 +
// wykryj ciąg z RAW powyżej
(srv_msg == "Current Global Users: " + raw_parm6 + " Max: " + raw_parm8
// jeśli szukany ciąg istnieje, przetłumacz go
? xTERMC "-" xNORMAL " Użytkownicy obecni globalnie: " + raw_parm6 + ", maksymalnie: " + raw_parm8
// jeśli szukany ciąg nie istnieje (np. został zmieniony), wyświetl komunikat w formie oryginalnej
: xTERMC "-" xNORMAL " " + srv_msg));
}
}
/*
301 (WHOIS - away)
:cf1f2.onet 301 ucc_test ucc_test :test away
*/
void raw_301(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string away_msg = form_from_chat(get_rest_from_buf(raw_buf, " :"));
// jeśli użyto /whois, dodaj wynik do bufora
if(ga.cf.whois)
{
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
ga.whois[raw_parm3].push_back(oINFOn " Jest nieobecny(-na) z powodu: " + away_msg);
}
}
// w przeciwnym razie wyświetl od razu (ma znaczenie np. podczas pisania na priv, gdy osoba ma away)
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + raw_parm3 + " jest nieobecny(-na) z powodu: " + away_msg);
}
}
/*
303 (ISON nick1 nick2 - zwraca nicki, które są online)
:cf1f1.onet 303 ucc_test :Kernel_Panic
*/
void raw_303(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string ison_list = get_rest_from_buf(raw_buf, " :");
if(ison_list.size() > 0)
{
std::stringstream ison_list_stream(ison_list);
std::string nick, nicklist_show;
while(std::getline(ison_list_stream, nick, ' '))
{
if(nick.size() > 0)
{
nicklist_show += (nicklist_show.size() == 0 ? xCYAN "" : xTERMC ", " xCYAN) + nick;
}
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn "Użytkownicy dostępni dla zapytania ISON: " + nicklist_show);
}
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Brak dostępnych użytkowników dla zapytania ISON.");
}
}
/*
304
:cf1f3.onet 304 ucc_test :SYNTAX PRIVMSG <target>{,<target>} <message>
:cf1f4.onet 304 ucc_test :SYNTAX NICK <newnick>
*/
void raw_304(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
(raw_buf.find(" :SYNTAX ") != std::string::npos
// jeśli był ciąg 'SYNTAX', zamień go na 'Składnia:'
? oINFOn xRED "Składnia:" + get_rest_from_buf(raw_buf, " :SYNTAX")
// jeśli nie było ciągu 'SYNTAX', wyświetl komunikat bez zmian
: oINFOn xRED + get_rest_from_buf(raw_buf, " :")));
}
/*
305 (AWAY - bez wiadomości wyłącza)
:cf1f1.onet 305 ucc_test :You are no longer marked as being away
*/
void raw_305(struct global_args &ga, struct channel_irc *ci[])
{
ga.my_away = false;
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Nie jesteś już oznaczony(-na) jako nieobecny(-na).");
}
/*
306 (AWAY - z wiadomością włącza)
:cf1f1.onet 306 ucc_test :You have been marked as being away
*/
void raw_306(struct global_args &ga, struct channel_irc *ci[])
{
ga.my_away = true;
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Jesteś teraz oznaczony(-na) jako nieobecny(-na) z powodu:" xNORMAL " " + ga.away_msg);
ga.away_msg.clear();
}
/*
307 (WHOIS)
:cf1f1.onet 307 ucc_test ucc_test :is a registered nick
*/
void raw_307(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
ga.whois[raw_parm3].push_back(oINFOn " Jest zarejestrowanym użytkownikiem.");
}
}
/*
311 (WHOIS - początek, gdy nick jest na czacie)
:cf1f2.onet 311 ucc_test AT89S8253 70914256 aaa2a7.a7f7a6.88308b.464974 * :tururu!
:cf1f1.onet 311 ucc_test ucc_test 76995189 e0c697.bbe735.1b1f7f.56f6ee * :hmm test s
:cf1f2.onet 311 ucc_test ucc_test 76995189 87edcc.30c29e.611774.3140a3 * :ucc_test
*/
void raw_311(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
ga.whois[raw_parm3].push_back(oINFOb xGREEN + raw_parm3 + xTERMC " [" + raw_parm4 + "@" + raw_parm5 + "]");
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
ga.whois[raw_parm3].push_back(oINFOn " Nazwa: " + get_rest_from_buf(raw_buf, " :"));
}
}
/*
312 (WHOIS)
:cf1f2.onet 312 ucc_test AT89S8253 cf1f3.onet :cf1f3
:cf1f4.onet 312 ucc_test RankServ rankserv.onet :Ranking service
312 (WHOWAS)
:cf1f2.onet 312 ucc_test ucieszony86 cf1f2.onet :Mon May 26 21:39:35 2014
*/
void raw_312(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
// jeśli WHOIS
if(ga.cf.whois)
{
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
ga.whois[raw_parm3].push_back(oINFOn " Używa serwera: " + raw_parm4 + " [" + get_rest_from_buf(raw_buf, " :") + "]");
}
}
// jeśli WHOWAS
else
{
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
std::string raw_parm7 = get_raw_parm(raw_buf, 7);
std::string raw_parm8 = get_raw_parm(raw_buf, 8);
std::string raw_parm9 = get_raw_parm(raw_buf, 9);
ga.whowas[raw_parm3].push_back(oINFOn " Używał(a) serwera: " + raw_parm4);
ga.whowas[raw_parm3].push_back(oINFOn " Był(a) zalogowany(-na) od: "
+ day_en_to_pl(raw_parm5) + ", " + raw_parm7 + " " + month_en_to_pl(raw_parm6) + " " + raw_parm9 + ", " + raw_parm8);
}
}
/*
313 (WHOIS)
:cf1f2.onet 313 ucc_test Onet-KaOwiec :is a Service on OnetCzat
*/
void raw_313(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
ga.whois[raw_parm3].push_back((srv_msg == "is a Service on OnetCzat"
? oINFOn " Jest serwisem na Onet Czacie."
: oINFOn " " + srv_msg));
}
}
/*
314 (WHOWAS - początek, gdy nick był na czacie)
:cf1f3.onet 314 ucc_test ucieszony86 50256503 e0c697.bbe735.1b1f7f.56f6ee * :ucieszony86
:cf1f3.onet 314 ucc_test ucc_test 76995189 e0c697.bbe735.1b1f7f.56f6ee * :hmm test s
*/
void raw_314(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
ga.whowas[raw_parm3].push_back(oINFOb xCYAN + raw_parm3 + xTERMC " [" + raw_parm4 + "@" + raw_parm5 + "]");
ga.whowas[raw_parm3].push_back(oINFOn " Nazwa: " + get_rest_from_buf(raw_buf, " :"));
}
/*
317 (WHOIS)
:cf1f1.onet 317 ucc_test AT89S8253 532 1400636388 :seconds idle, signon time
*/
void raw_317(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
// time_t time_g;
// time(&time_g);
// int64_t idle_diff = time_g - std::stol(raw_parm4);
// std::string idle_diff_str = std::to_string(idle_diff);
ga.whois[raw_parm3].push_back(oINFOn " Jest nieaktywny(-na) przez: " + time_sec2time(raw_parm4));
// ga.whois[raw_parm3].push_back(oINFOn " Jest nieaktywny(-na) od: " + unixtimestamp2local_full(idle_diff_str));
ga.whois[raw_parm3].push_back(oINFOn " Jest zalogowany(-na) od: " + unixtimestamp2local_full(raw_parm5));
}
}
/*
318 (WHOIS - koniec)
:cf1f1.onet 318 ucc_test AT89S8253 :End of /WHOIS list.
*/
void raw_318(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
auto it = ga.whois.find(raw_parm3);
// nie reaguj na /whois dla nicka, którego nie ma na czacie
if(it != ga.whois.end())
{
int whois_len = it->second.size();
// wyświetl informacje o użytkowniku
for(int i = 0; i < whois_len; ++i)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, it->second[i]);
}
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn "Koniec informacji o użytkowniku " xBOLD_ON + it->first);
}
// wyczyść informację o nicku po przetworzeniu /whois
ga.whois.erase(raw_parm3);
}
// wyczyść ewentualne użycie opcji 's' we /whois
ga.whois_short.clear();
}
/*
319 (WHOIS)
:cf1f2.onet 319 ucc_test AT89S8253 :@#Learning_English %#Linux %#zua_zuy_zuo @#Computers @#Augustów %#ateizm #scc @#PHP @#ucc @#Suwałki
*/
void raw_319(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
std::map<std::string, std::string> chanlist;
std::stringstream chanlist_stream(get_rest_from_buf(raw_buf, " :"));
std::string chan, chan_key, chanlist_show;
while(std::getline(chanlist_stream, chan, ' '))
{
if(chan.size() > 0)
{
chan_key = buf_lower2upper(chan);
// dodanie cyfry na początku klucza posortuje pokoje wg uprawnień osoby
if(chan[0] == '`')
{
// za symbolem uprawnienia wstaw kolor zielony
if(chan.size() > 1)
{
chan.insert(1, xGREEN);
}
chanlist["1" + chan_key] = chan;
}
else if(chan[0] == '@')
{
if(chan.size() > 1)
{
chan.insert(1, xGREEN);
}
chanlist["2" + chan_key] = chan;
}
else if(chan[0] == '%')
{
if(chan.size() > 1)
{
chan.insert(1, xGREEN);
}
chanlist["3" + chan_key] = chan;
}
else if(chan[0] == '!')
{
if(chan.size() > 1)
{
chan.insert(1, xGREEN);
}
chanlist["4" + chan_key] = chan;
}
else if(chan[0] == '+')
{
if(chan.size() > 1)
{
chan.insert(1, xGREEN);
}
chanlist["5" + chan_key] = chan;
}
else
{
chanlist["6" + chan_key] = xGREEN + chan;
}
}
}
for(auto it = chanlist.begin(); it != chanlist.end(); ++it)
{
chanlist_show += (chanlist_show.size() == 0 ? "" : xTERMC ", ") + it->second;
}
ga.whois[raw_parm3].push_back(oINFOn " Przebywa w pokojach (" + std::to_string(chanlist.size()) + "): " + chanlist_show);
}
}
/*
332 (temat pokoju)
:cf1f3.onet 332 ucc_test #ucc :Ucieszony Chat Client
*/
void raw_332(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string raw_parm3)
{
// najpierw wyświetl temat (tylko, gdy jest ustawiony lub informację o braku tematu)
std::string topic = form_from_chat(get_rest_from_buf(raw_buf, " :"));
win_buf_add_str(ga, ci, raw_parm3,
// początek komunikatu
oINFOn xWHITE "Temat pokoju " xGREEN + raw_parm3 + (buf_chars(topic) > 0
// gdy temat był ustawiony
? xWHITE ": " xNORMAL + topic
// gdy temat nie był ustawiony
: xWHITE " nie został ustawiony (jest pusty)."));
// teraz znajdź pokój, do którego należy temat, wpisz go do jego bufora "topic" i wyświetl na górnym pasku
for(int i = 0; i < CHAN_CHAT; ++i) // szukaj jedynie pokoi czata, bez "Status", "DebugIRC" i "RawUnknown"
{
if(ci[i] && ci[i]->channel == raw_parm3) // znajdź pokój, do którego należy temat
{
// usuń z tematu formatowanie fontu i kolorów (na pasku nie jest obsługiwane)
ci[i]->topic = remove_form(topic);
break;
}
}
}
/*
333 (kto i kiedy ustawił temat)
:cf1f4.onet 333 ucc_test #ucc ucc_test!76995189 1404519605
:cf1f4.onet 333 ucc_test #ucc ucc_test!76995189@87edcc.30c29e.b9c507.d5c6b7 1400889719
*/
void raw_333(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
win_buf_add_str(ga, ci, raw_parm3,
oINFOn xWHITE "Temat pokoju " xGREEN + raw_parm3 + xWHITE " ustawiony przez " xCYAN
+ get_value_from_buf(raw_buf, raw_parm3 + " ", "!") + " [" + get_value_from_buf(raw_buf, "!", " ") + "]" xWHITE
" (" + unixtimestamp2local_full(raw_parm5) + ").");
}
/*
335 (WHOIS)
:cf1f2.onet 335 ucc_test Onet-KaOwiec :is a bot on OnetCzat
*/
void raw_335(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
ga.whois[raw_parm3].push_back((srv_msg == "is a bot on OnetCzat"
? oINFOn " Jest botem na Onet Czacie."
: oINFOn " " + srv_msg));
}
}
/*
341 (INVITE - pojawia się, gdy ja zapraszam; bez informowania, bo podobną informację zwraca RAW NOTICE)
:cf1f3.onet 341 ucc_test Kernel_Panic #ucc
*/
void raw_341()
{
}
/*
353 (NAMES)
:cf1f1.onet 353 ucc_test = #scc :%ucc_test|rx,0 AT89S8253|brx,0 %Husar|rx,1 ~Ayindida|x,0 YouTube_Dekoder|rx,0 StyX1|rx,0 %Radowsky|rx,1 fml|rx,0
:cf1f3.onet 353 ucieszony86 = ^cf1f2xxxxxx :ucieszony86|rx,1 Kernel_Panic|rx,0
*/
void raw_353(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
if(raw_parm4.size() > 0)
{
ga.names[raw_parm4] += get_rest_from_buf(raw_buf, " :");
// jeśli to NAMES dla rozmowy prywatnej i to ja wchodzę (bo jest już tam nick osoby, z którą będę rozmawiać), to dodaj go do bufora
if(raw_parm4[0] == '^' && raw_parm6.size() > 0)
{
// znajdź, który nick nie jest mój (nie ma żadnej reguły, w jakiej kolejności podane są nicki) i ten wybierz
std::string nick_priv = (raw_parm5.find(ga.zuousername) == std::string::npos) ? raw_parm5 : raw_parm6;
// usuń z nicka jego statusy
size_t nick_stat_pos = nick_priv.find("|");
if(nick_stat_pos != std::string::npos)
{
nick_priv.erase(nick_stat_pos, nick_priv.size() - nick_stat_pos);
}
// dodanie nicka, który wyświetli się na dolnym pasku w nazwie pokoju oraz w tytule
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm4)
{
ci[i]->chan_priv = "^" + nick_priv;
ci[i]->topic = "Rozmowa prywatna z " + nick_priv;
// po odnalezieniu pokoju przerwij pętlę
break;
}
}
}
}
}
/*
366 (koniec NAMES)
:cf1f4.onet 366 ucc_test #scc :End of /NAMES list.
*/
void raw_366(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
int nick_len;
struct nick_flags flags;
bool was_open_chan = false;
std::stringstream names_stream(ga.names[raw_parm3]);
std::string nick;
// zmienne używane, gdy wpiszemy /names wraz z podaniem pokoju (w celu wyświetlenia osób w oknie, a nie na liście)
std::string nick_onet, nick_key;
std::map<std::string, struct nick_irc> nick_chan;
// sprawdź, czy szukany pokój jest na liście otwartych pokoi (aby dopisać osoby na listę, gdy wpiszemy /names z podaniem pokoju)
if(ga.cf.names && ! ga.cf.names_empty)
{
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm3)
{
was_open_chan = true;
break;
}
}
}
while(std::getline(names_stream, nick, ' '))
{
nick_len = nick.size();
// nie reaguj na nadmiarowe spacje, wtedy nick będzie pusty (mało prawdopodobne, ale trzeba się przygotować na wszystko)
if(nick_len > 0)
{
nick_onet = nick;
// zacznij od wyzerowanych flag
flags = {};
// pobierz statusy użytkownika
for(int i = 0; i < nick_len; ++i)
{
if(nick[i] == '`')
{
flags.owner = true;
}
else if(nick[i] == '@')
{
flags.op = true;
}
else if(nick[i] == '%')
{
flags.halfop = true;
}
else if(nick[i] == '!')
{
flags.moderator = true;
}
else if(nick[i] == '+')
{
flags.voice = true;
}
// gdy już są znaki inne, niż statusy powyżej, usuń statusy i przerwij pętlę szukającą statusów użytkownika
else
{
nick.erase(0, i);
break;
}
}
// pobierz pozostałe flagi (wybrane)
size_t rest_flags = nick.find("|");
if(rest_flags != std::string::npos)
{
if(nick.find("W", rest_flags) != std::string::npos)
{
flags.public_webcam = true;
}
if(nick.find("V", rest_flags) != std::string::npos)
{
flags.private_webcam = true;
}
if(nick.find("b", rest_flags) != std::string::npos)
{
flags.busy = true;
}
// po pobraniu reszty flag usuń je z nicka
nick.erase(rest_flags, nick.size() - rest_flags);
}
// jeśli to NAMES po wejściu do pokoju po użyciu /join, wczytaj nicki na listę, tak samo jeśli to NAMES po użyciu /names bez podania
// pokoju (ma znaczenie przy kamerkach prywatnych, bo serwer nie zwraca obecnie flagi V dla MODE, za wyjątkiem własnego nicka,
// a dzięki temu można zaktualizować listę osób z kamerkami prywatnymi, bo NAMES zwraca flagę V), wczytaj również nicki, jeśli
// szukany pokój jest na liście otwartych pokoi, a wpisano /names z podaniem pokoju
if(! ga.cf.names || ga.cf.names_empty || was_open_chan)
{
// ! ga.cf.names - występuje po /join pokój (wtedy flaga ta jest na false)
// ga.cf.names_empty - występuje po /names bez podania pokoju
// was_open_chan - występuje po /names z podaniem pokoju, o ile sprawdzany pokój jest na liście otwartych pokoi
// wpisz nick na listę
new_or_update_nick_chan(ga, ci, raw_parm3, nick, "", flags);
}
// jeśli to NAMES po użyciu /names z podaniem pokoju, pobierz listę nicków, która zostanie później wyświetlona w oknie rozmowy
// (można podejrzeć listę osób, nie będąc w tym pokoju)
if(ga.cf.names && ! ga.cf.names_empty)
{
// klucz nicka trzymaj wielkimi literami w celu poprawienia sortowania zapewnianego przez std::map
nick_key = buf_lower2upper(nick);
// na listę wpisz już nick w formie odebranej przez serwer
nick_chan[nick_key] = {nick_onet, "", flags};
}
}
}
// odśwież listę (o ile włączone jest okno informacyjne oraz zmiana dotyczyła aktualnie otwartego pokoju)
if(ga.win_info_state && ci[ga.current]->channel == raw_parm3)
{
ga.win_info_refresh = true;
}
// jeśli to było /names bez podania pokoju, pokaż komunikat o aktualizacji listy pokoi
if(ga.cf.names && ga.cf.names_empty)
{
win_buf_add_str(ga, ci, raw_parm3, uINFOn xWHITE "Zaktualizowano listę użytkowników w pokoju " + raw_parm3, false);
}
// jeśli wpisano /names wraz z podaniem pokoju, wyświetl w oknie rozmowy nicki (w formie zwracanej przez serwer) w kolejności statusów, alfabetycznie
else if(ga.cf.names && ! ga.cf.names_empty)
{
if(nick_chan.size() > 0)
{
std::string nicklist, nick_owner, nick_op, nick_halfop, nick_moderator, nick_voice, nick_pub_webcam, nick_priv_webcam, nick_normal;
std::string nicklist_part;
int width = getmaxx(ga.win_chat) - ga.time_len; // odejmij rozmiar zajmowany przez wyświetlenie czasu
int nick_len;
int count_char = 0;
int spaces;
for(auto it = nick_chan.begin(); it != nick_chan.end(); ++it)
{
if(it->second.nf.owner)
{
nick_owner += it->second.nick + "\n";
}
else if(it->second.nf.op)
{
nick_op += it->second.nick + "\n";
}
else if(it->second.nf.halfop)
{
nick_halfop += it->second.nick + "\n";
}
else if(it->second.nf.moderator)
{
nick_moderator += it->second.nick + "\n";
}
else if(it->second.nf.voice)
{
nick_voice += it->second.nick + "\n";
}
else if(it->second.nf.public_webcam)
{
nick_pub_webcam += it->second.nick + "\n";
}
else if(it->second.nf.private_webcam)
{
nick_priv_webcam += it->second.nick + "\n";
}
else
{
nick_normal += it->second.nick + "\n";
}
}
nicklist = nick_owner + nick_op + nick_halfop + nick_moderator + nick_voice + nick_pub_webcam + nick_priv_webcam + nick_normal;
std::stringstream nicklist_stream(nicklist);
std::getline(nicklist_stream, nick);
nick_len = buf_chars(nick) + 2; // + 2 na nawias
bool parity = false; // co drugi wiersz pokaż jaśniejszym kolorem, aby łatwiej było czytać listę nicków
while(true)
{
if(count_char == 0)
{
if(! parity)
{
nicklist_part += xTERMC;
parity = true;
}
else
{
nicklist_part += xWHITE;
parity = false;
}
}
nicklist_part += "[" + nick + "]";
count_char += nick_len;
spaces = (nick_len <= 20 ? 21 : 42) - nick_len;
count_char += spaces;
if(! std::getline(nicklist_stream, nick))
{
break;
}
nick_len = buf_chars(nick) + 2;
if(width - count_char > nick_len - 1)
{
for(int i = 0; i < spaces; ++i)
{
nicklist_part += " ";
}
}
else
{
count_char = 0;
nicklist_part += "\n";
}
}
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xGREEN "Użytkownicy przebywający w pokoju " + raw_parm3 + " (" + std::to_string(nick_chan.size()) + "):");
win_buf_add_str(ga, ci, ci[ga.current]->channel, nicklist_part);
}
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xGREEN "Nikt nie przebywa w pokoju " + raw_parm3);
}
}
// po wyświetleniu nicków wyczyść bufor przetwarzanego pokoju
ga.names.erase(raw_parm3);
}
/*
369 (WHOWAS - koniec)
:cf1f3.onet 369 ucc_test ucieszony86 :End of WHOWAS
*/
void raw_369(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
auto it = ga.whowas.find(raw_parm3);
// nie reaguj na /whowas dla nicka, o którym nie ma informacji
if(it != ga.whowas.end())
{
int whowas_len = it->second.size();
// wyświetl informacje o użytkowniku
for(int i = 0; i < whowas_len; ++i)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, it->second[i]);
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn "Koniec informacji o użytkowniku " xBOLD_ON + it->first);
// wyczyść informacje po przetworzeniu /whowas dla danego użytkownika
ga.whowas.erase(raw_parm3);
}
}
/*
371 (INFO)
:cf1f1.onet 371 ucieszony86 : -/\- InspIRCd -\/-
*/
void raw_371(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
xBOLD_ON "-" xBLUE + raw_parm0
// jeśli to początek INFO (RAW jak powyżej), pogrub tekst
+ (srv_msg == " -/\\- InspIRCd -\\/-" ? xTERMC "- " : xTERMC "-" xNORMAL " ") + srv_msg);
}
/*
372 (MOTD - wiadomość dnia, właściwa wiadomość)
:cf1f2.onet 372 ucc_test :- Onet Czat. Inny Wymiar Czatowania. Witamy!
:cf1f2.onet 372 ucc_test :- UWAGA - Nie daj się oszukać! Zanim wyślesz jakikolwiek SMS, zapoznaj się z filmem: http://www.youtube.com/watch?v=4skUNAyIN_c
:cf1f2.onet 372 ucc_test :-
*/
void raw_372(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
win_buf_add_str(ga, ci, "Status", oINFOn xYELLOW + form_from_chat(get_rest_from_buf(raw_buf, " :")));
}
/*
374 (INFO - koniec)
:cf1f1.onet 374 ucieszony86 :End of /INFO list
*/
void raw_374()
{
}
/*
375 (MOTD - wiadomość dnia, początek)
:cf1f2.onet 375 ucc_test :cf1f2.onet message of the day
*/
void raw_375(struct global_args &ga, struct channel_irc *ci[])
{
win_buf_add_str(ga, ci, "Status", oINFOn xYELLOW "Wiadomość dnia:");
}
/*
376(MOTD - wiadomość dnia, koniec)
:cf1f2.onet 376 ucc_test :End of message of the day.
*/
void raw_376()
{
}
/*
378 (WHOIS)
:cf1f1.onet 378 ucc_test ucc_test :is connecting from 76995189@adin155.neoplus.adsl.tpnet.pl 79.184.195.155
*/
void raw_378(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
ga.whois[raw_parm3].push_back(oINFOn " Jest połączony(-na) z: " + get_rest_from_buf(raw_buf, "from "));
}
}
/*
391 (TIME)
:cf1f4.onet 391 ucc_test cf1f4.onet :Tue May 27 08:59:41 2014
*/
void raw_391(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
std::string raw_parm7 = get_raw_parm(raw_buf, 7);
std::string raw_parm8 = get_raw_parm(raw_buf, 8);
// przekształć zwracaną datę i godzinę na formę poprawną dla polskiego zapisu
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xWHITE "Data i czas na serwerze " xMAGENTA + raw_parm3 + xWHITE ": "
+ day_en_to_pl(raw_parm4) + ", " + raw_parm6 + " " + month_en_to_pl(raw_parm5) + " " + raw_parm8 + ", " + raw_parm7);
}
/*
396
:cf1f2.onet 396 ucc_test 87edcc.6bc2d5.1917ec.38c71e :is now your displayed host
*/
void raw_396(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// wyświetl w pokoju "Status" jeśli to odpowiedź po zalogowaniu lub w aktualnym pokoju, jeśli to odpowiedź po użyciu /vhost
// (komunikat zależny od tego, czy udało się pobrać wcześniej ZUO)
win_buf_add_str(ga, ci, (ga.cf.vhost ? ci[ga.current]->channel : "Status"), (ga.my_zuo.size() > 0
// gdy udało się wcześniej pobrać ZUO (w zasadzie nie powinno zdarzyć się inaczej)
? oINFOn xGREEN "Twoim wyświetlanym ZUO oraz hostem jest teraz: " + ga.my_zuo + "@"
// gdyby jakimś cudem nie udało się wcześniej pobrać numeru ZUO
: oINFOn xGREEN "Twoim wyświetlanym hostem jest teraz: ")
// dodaj host
+ raw_parm3);
}
/*
401 (WHOIS - początek, gdy nick nie został znaleziony lub gdy podano nieprawidłowy format nicka)
:cf1f4.onet 401 ucc_test xyz :No such nick/channel
:cf1f4.onet 401 ucc_test #xyz :No such nick/channel
401 (INVITE, KICK - podanie nicka, którego nie ma na czacie)
:cf1f2.onet 401 ucc abc :No such nick/channel
401 (TOPIC, NAMES, INVITE - przy podaniu nieistniejącego pokoju lub nieprawidłowego pokoju, gdy brakuje #)
:cf1f4.onet 401 ucc_test #ucc: :No such nick/channel
:cf1f4.onet 401 ucc_test abc :No such nick/channel
401 (INVREJECT - błędny nick, podanie nicka, którego nie ma na czacie)
:cf1f1.onet 401 Kernel_Panic abc :No such nick
401 (INVREJECT - błędny pokój)
- odrzucenie nieistniejącej rozmowy prywatnej lub odrzucenie rozmowy prywatnej, gdy nicka nie ma na czacie
:cf1f1.onet 401 ucc ^cf1f3123456 :No such channel
- wpisanie nieprawidłowego formatu rozmowy prywatnej
:cf1f1.onet 401 ucc ^qwerty :No such channel
- odrzucenie nieistniejącego pokoju
:cf1f2.onet 401 ucc #abc :No such channel
- wpisanie nieprawidłowej nazwy pokoju
:cf1f2.onet 401 ucc abc :No such channel
*/
void raw_401(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
// WHOIS, INVITE lub INVREJECT przy błędnym nicku
if(ga.cf.whois || (ga.cf.invite && raw_parm3.size() > 0 && raw_parm3[0] != '#') || ga.cf.kick || srv_msg == "No such nick")
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOb xGREEN + raw_parm3 + xNORMAL " - nie ma takiego użytkownika na czacie.");
}
// TOPIC, NAMES itd. przy nieistniejącym lub błędnie wpisanym pokoju
else if(srv_msg == "No such nick/channel")
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, (raw_parm3.size() > 0 && raw_parm3[0] == '#'
? oINFOn xRED + raw_parm3 + " - nie ma takiego pokoju."
: oINFOn xRED + raw_parm3 + " - nieprawidłowa nazwa pokoju."));
}
// INVREJECT przy błędnym pokoju lub PART do rozmowy, która już nie istnieje (po przelogowaniu się bez zamykania tego priva)
else if(srv_msg == "No such channel")
{
// jeśli to PART do rozmowy, która nie istnieje (jeśli ten pokój istnieje), usuń pokój z pamięci programu (zamknij go)
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm3)
{
del_chan_chat(ga, ci, raw_parm3);
// po odnalezieniu pokoju zakończ
return;
}
}
// gdy to nie był PART do nieaktywnego priva, wyświetl komunikat
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + raw_parm3 + " - wybrana rozmowa prywatna nie istnieje.");
}
// nieznany powód wyświetl bez zmian
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - " + srv_msg);
}
}
/*
402 (MOTD, TIME - podanie nieistniejącego serwera)
:cf1f4.onet 402 ucc_test abc :No such server
*/
void raw_402(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - nie ma takiego serwera.");
}
/*
403 (JOIN do nieistniejącego priva lub do pokoju bez podania # na początku)
:cf1f4.onet 403 ucc_test sc :Invalid channel name
:cf1f2.onet 403 ucc_test ^cf1f2123456 :Invalid channel name
*/
void raw_403(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
if(raw_parm3.size() > 0 && raw_parm3[0] != '^')
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - nieprawidłowa nazwa pokoju.");
}
else
{
// jeśli to był otwarty priv i nie da się do niego wejść (po przelogowaniu), pokaż nazwę z nickiem
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm3)
{
win_buf_add_str(ga, ci, raw_parm3, oINFOn xWHITE + ci[i]->chan_priv + " - wybrana rozmowa prywatna nie istnieje.");
// po odnalezieniu pokoju zakończ
return;
}
}
// w przeciwnym razie pokaż zwykłe ostrzeżenie w aktualnie otwartym pokoju
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + raw_parm3 + " - wybrana rozmowa prywatna nie istnieje.");
}
}
/*
404 (próba wysłania wiadomości do kanału, w którym nie przebywamy)
:cf1f1.onet 404 ucc_test #ucc :Cannot send to channel (no external messages)
404 (próba wysłania wiadomości w pokoju moderowanym, gdzie nie mamy uprawnień)
:cf1f2.onet 404 ucc_test #Suwałki :Cannot send to channel (+m)
*/
void raw_404(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
if(srv_msg == "Cannot send to channel (no external messages)")
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xRED "Nie można wysłać wiadomości do pokoju " + raw_parm3 + " (nie przebywasz w nim).");
}
else if(srv_msg == "Cannot send to channel (+m)")
{
win_buf_add_str(ga, ci, raw_parm3,
oINFOn xRED "Nie możesz pisać w pokoju " + raw_parm3 + " (pokój jest moderowany i nie posiadasz uprawnień).");
}
// nieznany powód wyświetl bez zmian
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - " + srv_msg);
}
}
/*
405 (próba wejścia do zbyt dużej liczby pokoi)
:cf1f2.onet 405 ucieszony86 #abc :You are on too many channels
*/
void raw_405(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xRED "Nie możesz wejść do pokoju " + raw_parm3 + " (przekroczono dopuszczalny limit jednocześnie otwartych pokoi).");
}
/*
406 (WHOWAS - początek, gdy nie było takiego nicka)
:cf1f3.onet 406 ucc_test abc :There was no such nickname
*/
void raw_406(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOb xCYAN + raw_parm3 + xNORMAL " - brak informacji o tym użytkowniku.");
}
/*
412 (PRIVMSG #pokój :)
:cf1f2.onet 412 ucc_test :No text to send
*/
void raw_412(struct global_args &ga, struct channel_irc *ci[])
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nie wysłano tekstu.");
}
/*
421
:cf1f2.onet 421 ucc_test WHO :This command has been disabled.
:cf1f2.onet 421 ucc_test ABC :Unknown command
*/
void raw_421(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
// jeśli polecenie jest wyłączone
if(srv_msg == "This command has been disabled.")
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - to polecenie czata zostało wyłączone.");
}
// jeśli polecenie jest nieznane
else if(srv_msg == "Unknown command")
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - nieznane polecenie czata.");
}
// gdy inna odpowiedź serwera, wyświetl oryginalny tekst
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - " + srv_msg);
}
}
/*
433
:cf1f4.onet 433 * ucc_test :Nickname is already in use.
*/
void raw_433(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xRED "Nick " + raw_parm3 + " jest już w użyciu. Spróbuj wpisać " xCYAN "/connect o " xRED "lub " xCYAN "/c o");
// w przypadku użycia już nicka, wyślij polecenie rozłączenia się
irc_send(ga, ci, "QUIT");
// ustawienie tej flagi spowoduje przerwanie dalszej autoryzacji do IRC
ga.nick_in_use = true;
}
/*
441 (KICK #pokój nick :<...> - gdy nie ma nicka w pokoju)
:cf1f1.onet 441 ucieszony86 Kernel_Panic #ucc :They are not on that channel
*/
void raw_441(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, raw_parm4, oINFOn xRED "Nie możesz wyrzucić " + raw_parm3 + ", ponieważ nie przebywa w pokoju " + raw_parm4);
}
/*
442 (KICK, INVITE, jeśli nie przebywamy w danym pokoju)
:cf1f1.onet 442 ucc_test #ucc :You're not on that channel!
*/
void raw_442(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nie przebywasz w pokoju " + raw_parm3);
}
/*
443 (INVITE, gdy osoba już przebywa w tym pokoju)
:cf1f1.onet 443 ucc_test AT89S8253 #ucc :is already on channel
*/
void raw_443(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, raw_parm4, oINFOn xWHITE + raw_parm3 + " przebywa już w pokoju " + raw_parm4);
}
/*
445 (SUMMON)
:cf1f2.onet 445 ucieszony86 :SUMMON has been disabled (depreciated command)
*/
void raw_445(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - to polecenie czata zostało wyłączone (jest przestarzałe).");
}
/*
446 (USERS)
:cf1f2.onet 446 ucieszony86 :USERS has been disabled (depreciated command)
*/
void raw_446(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - to polecenie czata zostało wyłączone (jest przestarzałe).");
}
/*
451
:cf1f4.onet 451 PING :You have not registered
:cf1f3.onet 451 VHOST :You have not registered
*/
void raw_451(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm2 + " - nie posiadasz zarejestrowanego nicka.");
}
/*
461
:cf1f3.onet 461 ucc_test PRIVMSG :Not enough parameters.
:cf1f4.onet 461 ucc_test NICK :Not enough parameters.
*/
void raw_461(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - brak wystarczającej liczby parametrów.");
}
/*
462 (USER)
:cf1f3.onet 462 ucc :You may not reregister
*/
void raw_462(struct global_args &ga, struct channel_irc *ci[])
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nie możesz zarejestrować się ponownie.");
}
/*
471 (JOIN gdy pokój jest pełny)
:cf1f2.onet 471 Kernel_Panic #ucc :Cannot join channel (Channel is full)
*/
void raw_471(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xRED "Nie możesz wejść do pokoju " + raw_parm3 + " (przekroczono limit osób jednocześnie przebywających w pokoju).");
}
/*
473 (JOIN do pokoju, który jest prywatny i nie mam zaproszenia)
:cf1f2.onet 473 ucc_test #a :Cannot join channel (Invite only)
*/
void raw_473(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nie możesz wejść do pokoju " + raw_parm3 + " (nie posiadasz zaproszenia).");
}
/*
474 (JOIN do pokoju, w którym mam bana)
:cf1f3.onet 474 ucc #ucc :Cannot join channel (You're banned)
*/
void raw_474(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nie możesz wejść do pokoju " + raw_parm3 + " (jesteś zbanowany(-na)).");
}
/*
475 (JOIN do pokoju z hasłem gdy podamy złe hasło lub jego brak)
:cf1f2.onet 475 ucieszony86 #ucc :Cannot join channel (Incorrect channel key)
*/
void raw_475(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nie możesz wejść do pokoju " + raw_parm3 + " (nieprawidłowe hasło dostępu).");
}
/*
480 (KNOCK #pokój :text) - obecnie wyłączony, dlatego komunikat nie będzie tłumaczony, dodano na wszelki wypadek, gdyby KNOCK kiedyś wrócił
:cf1f2.onet 480 Kernel_Panic :Can't KNOCK on #ucc, channel is not invite only so knocking is pointless!
*/
void raw_480(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + srv_msg);
}
/*
481 (SQUIT, CONNECT, TRACE, KILL, REHASH, DIE, RESTART, WALLOPS, KLINE - przy braku uprawnień, to otrzyma każdy, kto nie jest adminem)
:cf1f1.onet 481 Kernel_Panic :Permission Denied - You do not have the required operator privileges
*/
void raw_481(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel, (srv_msg == "Permission Denied - You do not have the required operator privileges"
? oINFOn xRED "Dostęp zabroniony, nie posiadasz wymaganych uprawnień operatora."
: oINFOn xRED + srv_msg));
}
/*
482
*/
void raw_482(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
// TOPIC
// :cf1f1.onet 482 Kernel_Panic #Suwałki :You must be at least a half-operator to change the topic on this channel
if(srv_msg == "You must be at least a half-operator to change the topic on this channel")
{
win_buf_add_str(ga, ci, raw_parm3, oINFOn xRED "Nie posiadasz uprawnień do zmiany tematu w pokoju " + raw_parm3);
}
// KICK sopa, będąc opem
// :cf1f2.onet 482 ucc_test #ucc :You must be a channel operator
else if(srv_msg == "You must be a channel operator")
{
win_buf_add_str(ga, ci, raw_parm3, oINFOn xRED "Musisz być przynajmniej superoperatorem pokoju " + raw_parm3);
}
// KICK sopa lub opa, nie mając żadnych uprawnień
// :cf1f3.onet 482 ucc_test #irc :You must be a channel half-operator
else if(srv_msg == "You must be a channel half-operator")
{
win_buf_add_str(ga, ci, raw_parm3, oINFOn xRED "Musisz być przynajmniej operatorem pokoju " + raw_parm3);
}
// KICK np. ChanServ
// :cf1f4.onet 482 ucc_test #ucc :Only a u-line may kick a u-line from a channel.
// a tego nie będę tłumaczyć, niech wyświetli się w else
// nieznany lub niezaimplementowany powód wyświetl bez zmian
else
{
win_buf_add_str(ga, ci, raw_parm3, oINFOn xRED + srv_msg);
}
}
/*
484
*/
void raw_484(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
std::string nick_kick = get_value_from_buf(srv_msg, "kick ", " as");
// KICK #pokój nick :<...> - próba wyrzucenia właściciela
// :cf1f1.onet 484 ucieszony86 #ucc :Can't kick ucieszony86 as they're a channel founder
if(srv_msg == "Can't kick " + nick_kick + " as they're a channel founder")
{
win_buf_add_str(ga, ci, raw_parm3, oINFOn xRED "Nie możesz wyrzucić " + nick_kick + ", ponieważ jest właścicielem pokoju " + raw_parm3);
}
// KICK #pokój nick :<...> - próba wyrzucenia sopa przez innego sopa, opa przez innego opa lub nicka bez uprawnień, gdy sami ich nie posiadamy
// :cf1f1.onet 484 ucieszony86 #Computers :Can't kick AT89S8253 as your spells are not good enough
else if(srv_msg == "Can't kick " + nick_kick + " as your spells are not good enough")
{
win_buf_add_str(ga, ci, raw_parm3,
oINFOn xRED "Nie posiadasz wystarczających uprawnień, aby wyrzucić " + nick_kick + " z pokoju " + raw_parm3);
}
// nieznany powód wyświetl bez zmian
else
{
win_buf_add_str(ga, ci, raw_parm3, oINFOn xRED + srv_msg);
}
}
/*
492 (INVITE nick #pokój - przy blokadzie zaproszeń)
:cf1f4.onet 492 ucc_test #ucc :Can't invite Kernel_Panic to channel (+V set)
*/
void raw_492(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
if(srv_msg == "Can't invite " + raw_parm6 + " to channel (+V set)")
{
win_buf_add_str(ga, ci, raw_parm3,
oINFOn xRED "Nie możesz zaprosić " + raw_parm6 + " do pokoju " + raw_parm3 + " (ustawiona blokada zaproszeń).");
}
else
{
win_buf_add_str(ga, ci, raw_parm3, oINFOn xRED + srv_msg);
}
}
/*
495 (JOIN #pokój - gdy wyrzucono mnie i jest aktywny kickrejoin)
:cf1f1.onet 495 Kernel_Panic #ucc :You cannot rejoin this channel yet after being kicked (+J)
*/
void raw_495(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
if(srv_msg == "You cannot rejoin this channel yet after being kicked (+J)")
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xRED "Nie możesz wejść do pokoju " + raw_parm3
+ " (posiada blokadę uniemożliwiającą użytkownikom automatyczny powrót przez określony czas po wyrzuceniu ich z pokoju).");
}
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - " + srv_msg);
}
}
/*
530 (JOIN #sc - nieistniejący pokój)
:cf1f3.onet 530 ucc_test #sc :Only IRC operators may create new channels
*/
void raw_530(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - nie ma takiego pokoju.");
}
/*
531 (PRIVMSG user :text, NOTICE user :text)
:cf1f1.onet 531 Kernel_Panic AT89S8253 :You are not permitted to send private messages to this user
*/
void raw_531(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nie posiadasz uprawnień do wysłania wiadomości prywatnej do " + raw_parm3);
}
/*
600
:cf1f2.onet 600 ucc_test ucieszony86 50256503 87edcc.6bc2d5.4c33d7.76ada2 1401337308 :arrived online
*/
void raw_600(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
// informacja w aktywnym pokoju (o ile to nie "Status", "DebugIRC" i "RawUnknown")
if(ga.current < CHAN_CHAT)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xMAGENTA "Twój przyjaciel " xBOLD_ON + raw_parm3 + xBOLD_OFF " [" + raw_parm4 + "@" + raw_parm5
+ "] pojawia się na czacie.");
}
// informacja w "Status" wraz z datą i godziną
win_buf_add_str(ga, ci, "Status",
oINFOn xMAGENTA "Twój przyjaciel " xBOLD_ON + raw_parm3 + xBOLD_OFF " [" + raw_parm4 + "@" + raw_parm5
+ "] pojawia się na czacie (" + unixtimestamp2local_full(raw_parm6) + ").");
// dodaj nick do listy zalogowanych przyjaciół
ga.my_friends_online.push_back(raw_parm3);
}
/*
601
:cf1f2.onet 601 ucc_test ucieszony86 50256503 87edcc.6bc2d5.4c33d7.76ada2 1401337863 :went offline
*/
void raw_601(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
// informacja w aktywnym pokoju (o ile to nie "Status", "DebugIRC" i "RawUnknown")
if(ga.current < CHAN_CHAT)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xWHITE "Twój przyjaciel " xBOLD_ON xTERMC + raw_parm3 + xBOLD_OFF xWHITE " [" + raw_parm4 + "@" + raw_parm5
+ "] wychodzi z czata.");
}
// informacja w "Status" wraz z datą i godziną
win_buf_add_str(ga, ci, "Status",
oINFOn xWHITE "Twój przyjaciel " xBOLD_ON xTERMC + raw_parm3 + xBOLD_OFF xWHITE " [" + raw_parm4 + "@" + raw_parm5
+ "] wychodzi z czata (" + unixtimestamp2local_full(raw_parm6) + ").");
// usuń nick z listy zalogowanych przyjaciół
auto it = std::find(ga.my_friends_online.begin(), ga.my_friends_online.end(), raw_parm3);
if(it != ga.my_friends_online.end())
{
ga.my_friends_online.erase(it);
}
}
/*
602
:cf1f2.onet 602 ucc_test ucieszony86 50256503 87edcc.6bc2d5.4c33d7.76ada2 1401337308 :stopped watching
:cf1f2.onet 602 ucc_test ucieszony86 * * 0 :stopped watching
*/
void raw_602(struct global_args &ga, std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// usuń nick z listy zalogowanych przyjaciół
auto it = std::find(ga.my_friends_online.begin(), ga.my_friends_online.end(), raw_parm3);
if(it != ga.my_friends_online.end())
{
ga.my_friends_online.erase(it);
}
}
/*
604
:cf1f2.onet 604 ucc_test ucieszony86 50256503 87edcc.6bc2d5.4c33d7.76ada2 1401337308 :is online
*/
void raw_604(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
// wyświetl w pokoju "Status" lub w aktywnym po użyciu /friends bez parametrów
win_buf_add_str(ga, ci, (ga.cf.friends ? ci[ga.current]->channel : "Status"),
oINFOn xMAGENTA "Twój przyjaciel " + raw_parm3 + " [" + raw_parm4 + "@" + raw_parm5 + "] jest na czacie od: "
+ unixtimestamp2local_full(raw_parm6));
// dodaj nick do listy zalogowanych przyjaciół
ga.my_friends_online.push_back(raw_parm3);
}
/*
605
:cf1f1.onet 605 ucc nick1 * * 0 :is offline
*/
void raw_605(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// wyświetl w pokoju "Status" lub w aktywnym po użyciu /friends bez parametrów
win_buf_add_str(ga, ci, (ga.cf.friends ? ci[ga.current]->channel : "Status"),
oINFOn xWHITE "Twojego przyjaciela " + raw_parm3 + " nie ma na czacie.");
}
/*
607 (WATCH)
:cf1f4.onet 607 ucieszony86 :End of WATCH list
*/
void raw_607()
{
}
/*
666 (SERVER)
:cf1f2.onet 666 ucieszony86 :You cannot identify as a server, you are a USER. IRC Operators informed.
*/
void raw_666(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
(srv_msg == "You cannot identify as a server, you are a USER. IRC Operators informed."
// dla komunikatu powyżej pokaż przetłumaczoną wersję
? oINFOn xRED "Nie możesz zidentyfikować się jako serwer, jesteś użytkownikiem. Operatorzy IRC poinformowani."
// w przeciwnym razie pokaż oryginalny tekst (już nie na czerwono)
: oINFOn xWHITE + srv_msg));
}
/*
801 (AUTHKEY)
:cf1f4.onet 801 ucc_test :authKey
*/
void raw_801(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string authkey = get_raw_parm(raw_buf, 3);
// konwersja authKey
auth_code(authkey);
if(authkey.size() != 16)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, uINFOn xRED "authKey nie zawiera oczekiwanych 16 znaków (możliwa zmiana autoryzacji).");
// wyślij polecenie rozłączenia się
irc_send(ga, ci, "QUIT");
// ustawienie tej flagi spowoduje przerwanie dalszej autoryzacji do IRC
ga.authkey_failed = true;
}
else
{
// wyślij przekonwertowany authKey:
// AUTHKEY authKey
irc_send(ga, ci, "AUTHKEY " + authkey, "authIrc3b: "); // to 3b część autoryzacji, dlatego dodano informację o tym przy błędzie
}
}
/*
807 (BUSY 1)
:cf1f3.onet 807 ucc_test :You are marked as busy
*/
void raw_807(struct global_args &ga, struct channel_irc *ci[])
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xWHITE "Jesteś teraz oznaczony(-na) jako zajęty(-ta) i nie będziesz otrzymywać zaproszeń do rozmów prywatnych.");
ga.my_busy = true;
}
/*
808 (BUSY 0)
:cf1f3.onet 808 ucc_test :You are no longer marked busy
*/
void raw_808(struct global_args &ga, struct channel_irc *ci[])
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xWHITE "Nie jesteś już oznaczony(-na) jako zajęty(-ta) i możesz otrzymywać zaproszenia do rozmów prywatnych.");
ga.my_busy = false;
}
/*
809 (WHOIS)
:cf1f2.onet 809 ucc_test AT89S8253 :is busy
*/
void raw_809(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// jeśli użyto /whois, dodaj wynik do bufora
if(ga.cf.whois)
{
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
ga.whois[raw_parm3].push_back(oINFOn " Jest zajęty(-ta) i nie przyjmuje zaproszeń do rozmów prywatnych.");
}
}
// w przeciwnym razie wyświetl od razu (ma znaczenie podczas zapraszania na priv)
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xWHITE + raw_parm3 + " jest zajęty(-ta) i nie przyjmuje zaproszeń do rozmów prywatnych.");
}
}
/*
811 (INVIGNORE)
:cf1f2.onet 811 ucc_test Kernel_Panic :Ignore invites
*/
void raw_811(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Zignorowano wszelkie zaproszenia od " + raw_parm3);
}
/*
812 (INVREJECT)
:cf1f4.onet 812 ucc_test Kernel_Panic ^cf1f2754610 :Invite rejected
*/
void raw_812(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
// poprawić na odróżnianie pokoi od rozmów prywatnych
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Odrzucono zaproszenie od " + raw_parm3 + " do " + raw_parm4);
}
/*
815 (WHOIS)
:cf1f4.onet 815 ucc_test ucieszony86 :Public webcam
*/
void raw_815(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
ga.whois[raw_parm3].push_back(oINFOn " Posiada włączoną publiczną kamerkę.");
}
}
/*
816 (WHOIS)
:cf1f4.onet 816 ucc_test ucieszony86 :Private webcam
*/
void raw_816(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
// ukryj informację o użytkowniku, jeśli użyto opcji 's' we /whois
if(ga.whois_short != buf_lower2upper(raw_parm3))
{
ga.whois[raw_parm3].push_back(oINFOn " Posiada włączoną prywatną kamerkę.");
}
}
/*
817 (historia)
:cf1f4.onet 817 ucc_test #scc 1401032138 Damian - :bardzo korzystne oferty maja i w sumie dosc rozwiniety jak na Polskie standardy panel chmury
:cf1f4.onet 817 ucc_test #ucc 1401176793 ucc_test - :\1ACTION test\1
*/
void raw_817(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string user_msg = form_from_chat(get_rest_from_buf(raw_buf, " :"));
// wykryj, gdy ktoś pisze przez użycie /me
std::string user_msg_action = get_value_from_buf(user_msg, "\x01" "ACTION", "\x01");
win_buf_add_str(ga, ci, raw_parm3,
// początek komunikatu (czas)
unixtimestamp2local(raw_parm4) + (user_msg_action.size() > 0 && user_msg_action[0] == ' '
// tekst pisany z użyciem /me
? xMAGENTA "* " + raw_parm5 + xNORMAL + user_msg_action
// tekst normalny
: xBOLD_ON xDARK "<" + raw_parm5 + ">" xNORMAL " " + user_msg), true, 2, false);
}
/*
942 (np. gdy przyjaciel usunie swój nick)
:cf1f1.onet 942 ucieszony86 nick_porzucony.123456 :Invalid nickname
*/
void raw_942(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm3 = get_raw_parm(raw_buf, 3);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + raw_parm3 + " - nieprawidłowy nick.");
}
/*
950 (NS IGNORE DEL nick)
:cf1f2.onet 950 ucc ucc :Removed ucc_test!*@* <privatemessages,channelmessages,invites> from silence list
*/
void raw_950(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xWHITE "Usunięto " + raw_parm5 + " z listy ignorowanych, możesz teraz otrzymywać od niego zaproszenia oraz powiadomienia.");
}
/*
951 (NS IGNORE ADD nick, a także po zalogowaniu)
:cf1f1.onet 951 ucieszony86 ucieszony86 :Added Bot!*@* <privatemessages,channelmessages,invites> to silence list
*/
void raw_951(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
// informacja w "Status" lub w aktywnym pokoju po użyciu /ignore bez parametrów
win_buf_add_str(ga, ci, (ga.cf.ignore ? ci[ga.current]->channel : "Status"),
oINFOn xYELLOW "Dodano " + raw_parm5 + " do listy ignorowanych, nie będziesz otrzymywać od niego zaproszeń ani powiadomień.");
}
/*
Poniżej obsługa RAW NOTICE nienumerycznych.
*/
/*
NOTICE nienumeryczny
*/
void raw_notice(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf, std::string &raw_parm0)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
// jeśli to typowy nick w stylu AT89S8253!70914256@aaa2a7.a7f7a6.88308b.464974, pobierz część przed !
// w przeciwnym razie (np. cf1f1.onet) pobierz całą część
std::string nick_who = (raw_parm0.find("!") != std::string::npos ? get_value_from_buf(raw_buf, ":", "!") : raw_parm0);
// pobierz zwracany komunikat serwera
std::string srv_msg = get_rest_from_buf(raw_buf, " :");
// :cf1f4.onet NOTICE Auth :*** Looking up your hostname...
if(raw_parm2 == "Auth" && srv_msg == "*** Looking up your hostname...")
{
win_buf_add_str(ga, ci, "Status", xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " Wyszukiwanie Twojej nazwy hosta...");
}
// :cf1f3.onet NOTICE Auth :*** Found your hostname (eik220.neoplus.adsl.tpnet.pl)
else if(raw_parm2 == "Auth" && srv_msg == "*** Found your hostname (" + get_value_from_buf(srv_msg, "(", ")") + ")")
{
win_buf_add_str(ga, ci, "Status",
xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " Znaleziono Twoją nazwę hosta "
+ get_rest_from_buf(srv_msg, "hostname ") + ".");
}
// :cf1f1.onet NOTICE Auth :*** Found your hostname (eik220.neoplus.adsl.tpnet.pl) -- cached
else if(raw_parm2 == "Auth" && srv_msg == "*** Found your hostname (" + get_value_from_buf(srv_msg, "(", ") ") + ") -- cached")
{
win_buf_add_str(ga, ci, "Status",
xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " Znaleziono Twoją nazwę hosta "
+ get_value_from_buf(srv_msg, "hostname ", " ") + " - była zbuforowana na serwerze.");
}
// :cf1f2.onet NOTICE Auth :*** Could not resolve your hostname: Domain name not found; using your IP address (93.159.185.10) instead.
else if(raw_parm2 == "Auth" && srv_msg == "*** Could not resolve your hostname: Domain name not found; using your IP address ("
+ get_value_from_buf(srv_msg, "(", ")") + ") instead.")
{
win_buf_add_str(ga, ci, "Status",
xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " Nie można rozwiązać Twojej nazwy hosta (nie znaleziono nazwy "
"domeny). Zamiast tego użyto Twojego adresu IP " + get_value_from_buf(srv_msg, " address ", " instead.") + ".");
}
// :cf1f3.onet NOTICE Auth :Welcome to OnetCzat!
else if(raw_parm2 == "Auth" && srv_msg == "Welcome to OnetCzat!")
{
win_buf_add_str(ga, ci, "Status",
xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " " + ga.zuousername + ", witaj na Onet Czacie!");
}
// :cf1f4.onet NOTICE ucc_test :Setting your VHost: ucc
// ignoruj tę sekwencję dla zwykłych nicków, czyli takich, które mają ! w raw_parm0
else if(raw_parm0.find("!") == std::string::npos && srv_msg == "Setting your VHost:" + get_rest_from_buf(srv_msg, "VHost:"))
{
// wyświetl w aktualnie otwartym pokoju, jeśli to odpowiedź po użyciu /vhost lub w "Status", jeśli to odpowiedź po zalogowaniu się
win_buf_add_str(ga, ci, (ga.cf.vhost ? ci[ga.current]->channel : "Status"),
xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " Ustawiam Twój VHost:" + get_rest_from_buf(srv_msg, "VHost:"));
}
// :cf1f1.onet NOTICE ucieszony86 :Invalid username or password.
// np. dla VHost
// ignoruj tę sekwencję dla zwykłych nicków, czyli takich, które mają ! w raw_parm0
else if(raw_parm0.find("!") == std::string::npos && srv_msg == "Invalid username or password.")
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " Nieprawidłowa nazwa użytkownika lub hasło.");
}
// :cf1f1.onet NOTICE ^cf1f1756979 :*** ucc_test invited Kernel_Panic into the channel
// jeśli to zaproszenie do rozmowy prywatnej, komunikat skieruj do pokoju z tą rozmową (pojawia się po wysłaniu zaproszenia dla nicka);
// ignoruj tę sekwencję dla zwykłych nicków, czyli takich, które mają ! w raw_parm0
else if(raw_parm0.find("!") == std::string::npos && raw_parm2.size() > 0 && raw_parm2[0] == '^'
&& srv_msg == "*** " + raw_parm4 + " invited " + raw_parm6 + " into the channel")
{
win_buf_add_str(ga, ci, raw_parm2, oINFOn xWHITE "Wysłano zaproszenie do rozmowy prywatnej dla " + raw_parm6);
// dodanie nicka, który wyświetli się na dolnym pasku w nazwie pokoju oraz w tytule
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
ci[i]->chan_priv = "^" + raw_parm6;
ci[i]->topic = "Rozmowa prywatna z " + raw_parm6;
// po odnalezieniu pokoju przerwij pętlę
break;
}
}
}
// :cf1f2.onet NOTICE #Computers :*** drew_barrymore invited aga271980 into the channel
// jeśli to zaproszenie do pokoju, komunikat skieruj do właściwego pokoju;
// ignoruj tę sekwencję dla zwykłych nicków, czyli takich, które mają ! w raw_parm0
else if(raw_parm0.find("!") == std::string::npos && raw_parm2.size() > 0 && raw_parm2[0] == '#'
&& srv_msg == "*** " + raw_parm4 + " invited " + raw_parm6 + " into the channel")
{
win_buf_add_str(ga, ci, raw_parm2, oINFOn xWHITE + raw_parm6 + " został(a) zaproszony(-na) do pokoju " + raw_parm2 + " przez " + raw_parm4);
}
// :AT89S8253!70914256@aaa2a7.a7f7a6.88308b.464974 NOTICE #ucc :test
// jeśli to wiadomość dla pokoju, a nie nicka, komunikat skieruj do właściwego pokoju
else if(raw_parm2.size() > 0 && raw_parm2[0] == '#')
{
win_buf_add_str(ga, ci, raw_parm2, xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " " + form_from_chat(srv_msg));
}
// jeśli to wiadomość dla nicka (mojego), komunikat skieruj do aktualnie otwartego pokoju
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " " + form_from_chat(srv_msg));
}
}
/*
Poniżej obsługa RAW NOTICE numerycznych.
*/
/*
NOTICE 100
:Onet-Informuje!bot@service.onet NOTICE $* :100 #jakis_pokoj 1401386400 :jakis tekst
*/
void raw_notice_100(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
// ogłoszenia serwera wrzucaj do "Status"
win_buf_add_str(ga, ci, "Status",
xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL + " W pokoju " + raw_parm4
+ " (" + unixtimestamp2local_full(raw_parm5) + "): " + form_from_chat(get_rest_from_buf(raw_buf, raw_parm5 + " :")));
}
/*
NOTICE 109
:GuardServ!service@service.onet NOTICE ucc_test :109 #Suwałki :oszczędzaj enter - pisz w jednej linijce
:GuardServ!service@service.onet NOTICE ucc_test :109 #Suwałki :rzucanie mięsem nie będzie tolerowane
*/
void raw_notice_109(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, raw_parm4,
xBOLD_ON "-" xMAGENTA + nick_who + xTERMC "-" xNORMAL " " + form_from_chat(get_rest_from_buf(raw_buf, raw_parm4 + " :")));
}
/*
NOTICE 111 (NS INFO nick - początek)
*/
void raw_notice_111(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 avatar :http://foto0.m.ocdn.eu/_m/3e7c4b7dec69eb13ed9f013f1fa2abd4,1,19,0.jpg
if(raw_parm5 == "avatar")
{
ga.co[raw_parm4].avatar = get_rest_from_buf(raw_buf, "avatar :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 birthdate :1986-02-12
else if(raw_parm5 == "birthdate")
{
ga.co[raw_parm4].birthdate = get_rest_from_buf(raw_buf, "birthdate :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 city :
else if(raw_parm5 == "city")
{
ga.co[raw_parm4].city = get_rest_from_buf(raw_buf, "city :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 country :
else if(raw_parm5 == "country")
{
ga.co[raw_parm4].country = get_rest_from_buf(raw_buf, "country :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 email :
else if(raw_parm5 == "email")
{
ga.co[raw_parm4].email = get_rest_from_buf(raw_buf, "email :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 longDesc :
else if(raw_parm5 == "longDesc")
{
ga.co[raw_parm4].long_desc = form_from_chat(get_rest_from_buf(raw_buf, "longDesc :"));
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 offmsg :friend
else if(raw_parm5 == "offmsg")
{
ga.co[raw_parm4].offmsg = get_rest_from_buf(raw_buf, "offmsg :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 prefs :111000001001110100;1|100|100|0;verdana;006699;14
else if(raw_parm5 == "prefs")
{
ga.co[raw_parm4].prefs = get_rest_from_buf(raw_buf, "prefs :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 rank :1.6087
else if(raw_parm5 == "rank")
{
ga.co[raw_parm4].rank = get_rest_from_buf(raw_buf, "rank :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 sex :M
else if(raw_parm5 == "sex")
{
ga.co[raw_parm4].sex = get_rest_from_buf(raw_buf, "sex :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 shortDesc :Timeout.
else if(raw_parm5 == "shortDesc")
{
ga.co[raw_parm4].short_desc = form_from_chat(get_rest_from_buf(raw_buf, "shortDesc :"));
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 type :1
else if(raw_parm5 == "type")
{
ga.co[raw_parm4].type = get_rest_from_buf(raw_buf, "type :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 vEmail :0
else if(raw_parm5 == "vEmail")
{
ga.co[raw_parm4].v_email = get_rest_from_buf(raw_buf, "vEmail :");
}
// :NickServ!service@service.onet NOTICE ucieszony86 :111 ucieszony86 www :
else if(raw_parm5 == "www")
{
ga.co[raw_parm4].www = get_rest_from_buf(raw_buf, "www :");
}
// nieznany typ danych w wizytówce pokaż w "RawUnknown"
else
{
new_chan_raw_unknown(ga, ci); // jeśli istnieje, funkcja nie utworzy ponownie pokoju
win_buf_add_str(ga, ci, "RawUnknown", xWHITE + raw_buf, true, 2, true, false); // aby zwrócić uwagę, pokaż aktywność typu 2
}
}
/*
NOTICE 112 (NS INFO nick - koniec)
:NickServ!service@service.onet NOTICE ucieszony86 :112 ucieszony86 :end of user info
*/
void raw_notice_112(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
// wyświetl wizytówkę tylko po użyciu polecenia /card, natomiast ukryj ją po zalogowaniu na czat
if(ga.cf.card)
{
auto it = ga.co.find(raw_parm4);
if(it != ga.co.end())
{
std::string card_color;
// kolor nicka zależny od płci
if(it->second.sex.size() > 0 && it->second.sex == "M")
{
card_color = xBLUE;
}
else if(it->second.sex.size() > 0 && it->second.sex == "F")
{
card_color = xMAGENTA;
}
// gdy płeć nie jest ustawiona, nick będzie ciemnoszary
else
{
card_color = xDARK;
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOb + card_color + raw_parm4 + xTERMC " [Wizytówka]");
if(it->second.avatar.size() > 0)
{
size_t card_avatar_full = it->second.avatar.find(",1");
if(card_avatar_full != std::string::npos)
{
it->second.avatar.replace(card_avatar_full + 1, 1, "0");
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Awatar: " + it->second.avatar);
}
if(it->second.sex.size() > 0)
{
if(it->second.sex == "M")
{
it->second.sex = "mężczyzna";
}
else if(it->second.sex == "F")
{
it->second.sex = "kobieta";
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Płeć: " + it->second.sex);
}
if(it->second.birthdate.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Data urodzenia: " + it->second.birthdate);
// oblicz wiek (wersja uproszczona zakłada, że data zapisana jest za pomocą 10 znaków łącznie z separatorami)
if(it->second.birthdate.size() == 10)
{
std::string y_bd_str, m_bd_str, d_bd_str;
y_bd_str.insert(0, it->second.birthdate, 0, 4);
int y_bd = std::stoi("0" + y_bd_str);
m_bd_str.insert(0, it->second.birthdate, 5, 2);
int m_bd = std::stoi("0" + m_bd_str);
d_bd_str.insert(0, it->second.birthdate, 8, 2);
int d_bd = std::stoi("0" + d_bd_str);
// żadna z liczb nie może być zerem
if(y_bd != 0 && m_bd != 0 && d_bd != 0)
{
// pobierz aktualną datę
time_t time_g;
struct tm *time_l;
time(&time_g);
time_l = localtime(&time_g);
int y = time_l->tm_year + 1900; // + 1900, bo rok jest liczony od 1900
int m = time_l->tm_mon + 1; // + 1, bo miesiąc jest od zera
int d = time_l->tm_mday;
int age = y - y_bd;
// wykryj urodziny, jeśli ich jeszcze nie było w danym roku, trzeba odjąć rok
if(m < m_bd || (m <= m_bd && d < d_bd))
{
--age;
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Wiek: " + std::to_string(age));
}
}
}
if(it->second.city.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Miasto: " + it->second.city);
}
if(it->second.country.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Kraj: " + it->second.country);
}
if(it->second.short_desc.size() > 0)
{
std::string short_desc = it->second.short_desc;
// jeśli w opisie były tylko ciągi formatujące, nie pokazuj tekstu
if(buf_chars(short_desc) > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Krótki opis: " + short_desc);
}
}
if(it->second.long_desc.size() > 0)
{
std::string long_desc = it->second.long_desc;
// jeśli w opisie były tylko ciągi formatujące, nie pokazuj tekstu
if(buf_chars(long_desc) > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Długi opis: " + long_desc);
}
}
if(it->second.email.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Adres email: " + it->second.email);
/*
if(it->second.v_email.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " vEmail: " + it->second.v_email);
}
*/
}
if(it->second.www.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Strona internetowa: " + it->second.www);
}
if(it->second.offmsg.size() > 0)
{
if(it->second.offmsg == "all")
{
it->second.offmsg = "przyjmuje od wszystkich";
}
else if(it->second.offmsg == "friend")
{
it->second.offmsg = "przyjmuje od przyjaciół";
}
else if(it->second.offmsg == "none")
{
it->second.offmsg = "nie przyjmuje";
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Wiadomości offline: " + it->second.offmsg);
}
if(it->second.type.size() > 0)
{
if(it->second.type == "0")
{
it->second.type = "nowicjusz";
}
else if(it->second.type == "1")
{
it->second.type = "bywalec";
}
else if(it->second.type == "2")
{
it->second.type = "wyjadacz";
}
else if(it->second.type == "3")
{
it->second.type = "guru";
}
// dla mojego nicka zwracana jest dokładniejsza informacja o randze, dodaj ją w nawiasie
if(it->second.rank.size() > 0)
{
it->second.type += " (" + it->second.rank + ")";
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Ranga: " + it->second.type);
}
/*
if(it->second.prefs.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Preferencje: " + it->second.prefs);
}
*/
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn "Koniec informacji o użytkowniku " xBOLD_ON + it->first);
}
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
uINFOn xRED "Wystąpił błąd podczas przetwarzania wizytówki użytkownika " + raw_parm4);
}
}
// po przetworzeniu wizytówki wyczyść informacje o użytkowniku
ga.co.erase(raw_parm4);
}
/*
NOTICE 121 (ulubione nicki - lista)
:NickServ!service@service.onet NOTICE ucieszony86 :121 :nick1 nick2 nick3
*/
void raw_notice_121(struct global_args &ga, std::string &raw_buf)
{
if(ga.cf.friends_empty)
{
if(ga.my_friends.size() > 0)
{
ga.my_friends += " ";
}
ga.my_friends += get_rest_from_buf(raw_buf, ":121 :");
}
}
/*
NOTICE 122 (ulubione nicki - koniec listy)
:NickServ!service@service.onet NOTICE ucieszony86 :122 :end of friend list
*/
void raw_notice_122(struct global_args &ga, struct channel_irc *ci[])
{
if(ga.cf.friends_empty)
{
if(ga.my_friends.size() > 0)
{
std::map<std::string, std::string> nicklist;
std::stringstream my_friends_stream(ga.my_friends);
std::string nick, nick_key, nicklist_show;
while(std::getline(my_friends_stream, nick, ' '))
{
if(nick.size() > 0)
{
nick_key = buf_lower2upper(nick);
// jeśli osoba z listy przyjaciół jest online, jej kolor będzie inny, niż gdy jest offline,
// nick ten będzie też przed osobami offline na liście
if(std::find(ga.my_friends_online.begin(), ga.my_friends_online.end(), nick) != ga.my_friends_online.end())
{
// przy braku obsługi kolorów podkreśl nick dla odróżnienia, że jest online
nicklist["1" + nick_key] = (ga.use_colors ? xBOLD_ON xGREEN : xBOLD_ON xUNDERLINE_ON) + nick;
}
else
{
nicklist["2" + nick_key] = xBOLD_ON xDARK + nick;
}
}
}
for(auto it = nicklist.begin(); it != nicklist.end(); ++it)
{
nicklist_show += (nicklist_show.size() == 0 ? "" : xNORMAL ", ") + it->second;
}
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn "Osoby dodane do listy przyjaciół (" + std::to_string(nicklist.size()) + "): " + nicklist_show);
}
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Nie posiadasz osób dodanych do listy przyjaciół.");
}
}
ga.my_friends.clear();
}
/*
NOTICE 131 (ignorowane nicki - lista)
:NickServ!service@service.onet NOTICE ucieszony86 :131 :Bot
*/
void raw_notice_131(struct global_args &ga, std::string &raw_buf)
{
if(ga.cf.ignore_empty)
{
if(ga.my_ignore.size() > 0)
{
ga.my_ignore += " ";
}
ga.my_ignore += get_rest_from_buf(raw_buf, ":131 :");
}
}
/*
NOTICE 132 (ignorowane nicki - koniec listy)
:NickServ!service@service.onet NOTICE ucieszony86 :132 :end of ignore list
*/
void raw_notice_132(struct global_args &ga, struct channel_irc *ci[])
{
if(ga.cf.ignore_empty)
{
if(ga.my_ignore.size() > 0)
{
std::map<std::string, std::string> nicklist;
std::stringstream my_friends_stream(ga.my_ignore);
std::string nick, nick_key, nicklist_show;
while(std::getline(my_friends_stream, nick, ' '))
{
if(nick.size() > 0)
{
nick_key = buf_lower2upper(nick);
nicklist[nick_key] = nick;
}
}
for(auto it = nicklist.begin(); it != nicklist.end(); ++it)
{
nicklist_show += (nicklist_show.size() == 0 ? xYELLOW "" : xTERMC ", " xYELLOW) + it->second;
}
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn "Osoby dodane do listy ignorowanych (" + std::to_string(nicklist.size()) + "): " + nicklist_show);
}
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Nie posiadasz osób dodanych do listy ignorowanych.");
}
}
ga.my_ignore.clear();
}
/*
NOTICE 141 (ulubione pokoje - lista)
:NickServ!service@service.onet NOTICE ucieszony86 :141 :#pokój1 #pokój2 #pokój3
*/
void raw_notice_141(struct global_args &ga, std::string &raw_buf)
{
if(ga.my_favourites.size() > 0)
{
ga.my_favourites += " ";
}
ga.my_favourites += get_rest_from_buf(raw_buf, ":141 :");
}
/*
NOTICE 142 (ulubione pokoje - koniec listy)
:NickServ!service@service.onet NOTICE ucieszony86 :142 :end of favourites list
*/
void raw_notice_142(struct global_args &ga, struct channel_irc *ci[])
{
// pokaż listę ulubionych pokoi lub wejdź do ulubionych pokoi w kolejności alfabetycznej (później dodać opcję wyboru)
std::map<std::string, std::string> chanlist;
std::stringstream my_favourites_stream(ga.my_favourites);
std::string chan, chan_key;
// pobierz pokoje z bufora i wpisz do std::map
while(std::getline(my_favourites_stream, chan, ' '))
{
// nie reaguj na nadmiarowe spacje, wtedy chan będzie pusty (mało prawdopodobne, ale trzeba się przygotować na wszystko)
if(chan.size() > 0)
{
// w kluczu trzymaj pokój zapisany wielkimi literami (w celu poprawienia sortowania zapewnianego przez std::map)
chan_key = buf_lower2upper(chan);
// dodaj pokój do listy w std::map
chanlist[chan_key] = chan;
}
}
if(ga.cf.favourites_empty)
{
std::string chanlist_show;
for(auto it = chanlist.begin(); it != chanlist.end(); ++it)
{
chanlist_show += (chanlist_show.size() == 0 ? xGREEN "" : xTERMC ", " xGREEN) + it->second;
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, (chanlist_show.size() > 0
? oINFOn "Pokoje dodane do listy ulubionych (" + std::to_string(chanlist.size()) + "): " + chanlist_show
: oINFOn xWHITE "Nie posiadasz pokoi dodanych do listy ulubionych."));
}
else
{
std::string chanlist_join;
bool was_chan;
// pomiń te pokoje, które już były (po wylogowaniu i ponownym zalogowaniu się, nie dotyczy pierwszego logowania po uruchomieniu programu)
for(auto it = chanlist.begin(); it != chanlist.end(); ++it)
{
was_chan = false;
for(int i = 0; i < CHAN_CHAT; ++i) // szukaj jedynie pokoi czata, bez "Status", "DebugIRC" i "RawUnknown"
{
if(ci[i] && ci[i]->channel == it->second)
{
was_chan = true;
break;
}
}
if(! was_chan)
{
// pierwszy pokój przepisz bez zmian, kolejne pokoje muszą być rozdzielone przecinkiem
chanlist_join += (chanlist_join.size() == 0 ? "" : ",") + it->second;
}
}
// wejdź do ulubionych po pominięciu ewentualnych pokoi, w których program już był (jeśli jakieś zostały do wejścia)
if(chanlist_join.size() > 0)
{
irc_send(ga, ci, "JOIN " + chanlist_join);
}
}
// po użyciu wyczyść listę
ga.my_favourites.clear();
}
/*
NOTICE 151 (CS HOMES - gdzie mamy opcje)
:ChanServ!service@service.onet NOTICE ucc_test :151 :h#ucc h#Linux h#Suwałki h#scc
*/
void raw_notice_151(struct global_args &ga, std::string &raw_buf)
{
if(ga.cs_homes.size() > 0)
{
ga.cs_homes += " ";
}
ga.cs_homes += get_rest_from_buf(raw_buf, ":151 :");
}
/*
NOTICE 152 (CS HOMES)
:ChanServ!service@service.onet NOTICE ucc_test :152 :end of homes list
NOTICE 152 (po zalogowaniu)
:NickServ!service@service.onet NOTICE ucc_test :152 :end of offline senders list
*/
void raw_notice_152(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string srv_msg = get_rest_from_buf(raw_buf, ":152 :");
if(srv_msg == "end of homes list")
{
if(ga.cs_homes.size() > 0)
{
std::map<std::string, std::string> chanlist;
std::stringstream chanlist_stream(ga.cs_homes);
std::string chan, chan_key, chanlist_show;
while(std::getline(chanlist_stream, chan, ' '))
{
if(chan.size() > 0)
{
chan_key = buf_lower2upper(chan);
if(chan[0] == 'q')
{
if(chan.size() > 1)
{
chan.insert(1, xGREEN);
}
chanlist["1" + chan_key] = chan;
}
else if(chan[0] == 'o')
{
if(chan.size() > 1)
{
chan.insert(1, xGREEN);
}
chanlist["2" + chan_key] = chan;
}
else if(chan[0] == 'h')
{
if(chan.size() > 1)
{
chan.insert(1, xGREEN);
}
chanlist["3" + chan_key] = chan;
}
else
{
// jako wyjątek wrzuć na początek listy
chanlist["0" + chan_key] = xGREEN + chan;
}
}
}
for(auto it = chanlist.begin(); it != chanlist.end(); ++it)
{
chanlist_show += (chanlist_show.size() == 0 ? "" : xTERMC ", ") + it->second;
}
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn "Pokoje, w których posiadasz uprawnienia (" + std::to_string(chanlist.size()) + "): " + chanlist_show);
}
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Nie posiadasz uprawnień w żadnym pokoju.");
}
// po użyciu wyczyść bufor, aby kolejne użycie CS HOMES wpisało wartość od nowa, a nie nadpisało
ga.cs_homes.clear();
}
else if(srv_msg == "end of offline senders list")
{
// feature
}
// gdyby pojawiła się nieoczekiwana wartość, wyświetl ją bez zmian
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xWHITE + get_value_from_buf(raw_buf, ":", "!") + ": " + srv_msg);
}
}
/*
NOTICE 160 (CS INFO #pokój)
:ChanServ!service@service.onet NOTICE ucieszony86 :160 #ucc :Jakiś temat pokoju
*/
void raw_notice_160(struct global_args &ga, std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
ga.cs_i[raw_parm4].topic = form_from_chat(get_rest_from_buf(raw_buf, raw_parm4 + " :"));
}
/*
NOTICE 161 (CS INFO #pokój)
:ChanServ!service@service.onet NOTICE ucieszony86 :161 #ucc :topicAuthor=ucieszony86 rank=0.9100 topicDate=1424534155 private=0 type=0 createdDate=1381197987 password= limit=0 vEmail=0 www= catMajor=4 moderated=0 avatar= guardian=0 kickRejoin=120 email= auditorium=0
*/
void raw_notice_161(struct global_args &ga, std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
// dodaj spację na końcu bufora, aby parser wyciągający dane działał prawidłowo dla ostatniej wartości w buforze
raw_buf += " ";
// pobierz informacje o pokoju
ga.cs_i[raw_parm4].topic_author = get_value_from_buf(raw_buf, "topicAuthor=", " "); //
ga.cs_i[raw_parm4].rank = get_value_from_buf(raw_buf, "rank=", " "); //
ga.cs_i[raw_parm4].topic_date = get_value_from_buf(raw_buf, "topicDate=", " "); //
ga.cs_i[raw_parm4].priv = get_value_from_buf(raw_buf, "private=", " "); //
ga.cs_i[raw_parm4].type = get_value_from_buf(raw_buf, "type=", " "); //
ga.cs_i[raw_parm4].created_date = get_value_from_buf(raw_buf, "createdDate=", " "); //
ga.cs_i[raw_parm4].password = get_value_from_buf(raw_buf, "password=", " ");
ga.cs_i[raw_parm4].limit = get_value_from_buf(raw_buf, "limit=", " ");
ga.cs_i[raw_parm4].v_email = get_value_from_buf(raw_buf, "vEmail=", " ");
ga.cs_i[raw_parm4].www = get_value_from_buf(raw_buf, "www=", " "); //
ga.cs_i[raw_parm4].cat_major = get_value_from_buf(raw_buf, "catMajor=", " ");
ga.cs_i[raw_parm4].moderated = get_value_from_buf(raw_buf, "moderated=", " ");
ga.cs_i[raw_parm4].avatar = get_value_from_buf(raw_buf, "avatar=", " "); //
ga.cs_i[raw_parm4].guardian = get_value_from_buf(raw_buf, "guardian=", " ");
ga.cs_i[raw_parm4].kick_rejoin = get_value_from_buf(raw_buf, "kickRejoin=", " ");
ga.cs_i[raw_parm4].email = get_value_from_buf(raw_buf, "email=", " "); //
ga.cs_i[raw_parm4].auditorium = get_value_from_buf(raw_buf, "auditorium=", " ");
}
/*
NOTICE 162 (CS INFO #pokój)
:ChanServ!service@service.onet NOTICE ucieszony86 :162 #ucc :q,ucieszony86 (i inne opy/sopy)
*/
void raw_notice_162(struct global_args &ga, std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
ga.cs_i[raw_parm4].stats = get_rest_from_buf(raw_buf, raw_parm4 + " :");
}
/*
NOTICE 163 (CS INFO #pokój)
:ChanServ!service@service.onet NOTICE ucieszony86 :163 #ucc b nick ucieszony86 1402408270 :
:ChanServ!service@service.onet NOTICE ucieszony86 :163 #ucc b *!*@host ucieszony86 1423269397 :nick
:ChanServ!service@service.onet NOTICE ucieszony86 :163 #ucc I test!*@* ucieszony86 1424732412 :
*/
void raw_notice_163(struct global_args &ga, std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
std::string raw_parm7 = get_raw_parm(raw_buf, 7);
std::string raw_parm8 = get_raw_parm(raw_buf, 8);
std::string raw_parm_rest = get_rest_from_buf(raw_buf, raw_parm8 + " :");
/*
Dodawanie użytkowników po kluczu z daty dodania posortuje ich wg daty dodania.
*/
if(raw_parm5 == "b")
{
if(raw_parm_rest.size() == 0)
{
// zbanowany nick, który istnieje
if(raw_parm6.find("!") == std::string::npos)
{
ga.cs_i[raw_parm4].banned[raw_parm8] = xRED + raw_parm6 + xTERMC " " xWHITE "przez" xTERMC " " + raw_parm7
+ " " xWHITE "(" + unixtimestamp2local_full(raw_parm8) + ")";
}
// zbanowanie po masce
else
{
ga.cs_i[raw_parm4].banned[raw_parm8] = raw_parm6 + " " xWHITE "przez" xTERMC " " + raw_parm7
+ " " xWHITE "(" + unixtimestamp2local_full(raw_parm8) + ")";
}
}
else
{
// zbanowany nick po IP, który istnieje
ga.cs_i[raw_parm4].banned[raw_parm8] = raw_parm6 + " (" xRED + raw_parm_rest + xTERMC ") " xWHITE "przez" xTERMC " " + raw_parm7
+ " " xWHITE "(" + unixtimestamp2local_full(raw_parm8) + ")";
}
}
else
{
if(raw_parm6.find("!") == std::string::npos)
{
// zaproszony nick, który istnieje
ga.cs_i[raw_parm4].invited[raw_parm8] = xGREEN + raw_parm6 + xTERMC " " xWHITE "przez" xTERMC " " + raw_parm7
+ " " xWHITE "(" + unixtimestamp2local_full(raw_parm8) + ")";
}
else
{
// zaproszenie po masce
ga.cs_i[raw_parm4].invited[raw_parm8] = raw_parm6 + " " xWHITE "przez" xTERMC " " + raw_parm7
+ " " xWHITE "(" + unixtimestamp2local_full(raw_parm8) + ")";
}
}
}
/*
NOTICE 164 (CS INFO #pokój)
:ChanServ!service@service.onet NOTICE ucieszony86 :164 #ucc :end of channel info
*/
void raw_notice_164(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
auto it = ga.cs_i.find(raw_parm4);
if(it != ga.cs_i.end())
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOb xYELLOW_BLACK + raw_parm4 + xTERMC + " [Informacje]");
if(it->second.created_date.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn " Data utworzenia pokoju: " + unixtimestamp2local_full(it->second.created_date));
}
win_buf_add_str(ga, ci, ci[ga.current]->channel,
(it->second.topic.size() > 0
? oINFOn " Temat: " + it->second.topic
: oINFOn " Temat pokoju nie został ustawiony (jest pusty)."));
if(it->second.topic_author.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Autor tematu: " + it->second.topic_author);
}
if(it->second.topic_date.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn " Data ustawienia tematu: " + unixtimestamp2local_full(it->second.topic_date));
}
if(it->second.avatar.size() > 0)
{
size_t avatar_full = it->second.avatar.find(",1");
if(avatar_full != std::string::npos)
{
it->second.avatar.replace(avatar_full + 1, 1, "0");
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Awatar: " + it->second.avatar);
}
if(it->second.desc.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Opis: " + it->second.desc);
}
if(it->second.email.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Adres email: " + it->second.email);
}
if(it->second.www.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Strona internetowa: " + it->second.www);
}
if(it->second.type.size() > 0)
{
if(it->second.type == "0")
{
it->second.type = "Dziki";
}
else if(it->second.type == "1")
{
it->second.type = "Oswojony";
}
else if(it->second.type == "2")
{
it->second.type = "Z klasą";
}
else if(it->second.type == "3")
{
it->second.type = "Kultowy";
}
if(it->second.rank.size() > 0)
{
it->second.type += " (" + it->second.rank + ")";
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " Ranga: " + it->second.type);
}
if(it->second.priv == "1")
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED " Pokój jest prywatny.");
}
if(it->second.stats.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOb " Uprawnienia:");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " " + it->second.stats);
}
if(it->second.banned.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOb " Zbanowani:");
for(auto it2 = it->second.banned.begin(); it2 != it->second.banned.end(); ++it2)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " " + it2->second);
}
}
if(it->second.invited.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOb " Zaproszeni:");
for(auto it2 = it->second.invited.begin(); it2 != it->second.invited.end(); ++it2)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn " " + it2->second);
}
}
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn "Koniec informacji o pokoju " xBOLD_ON + raw_parm4);
}
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, uINFOn xRED "Wystąpił błąd podczas przetwarzania informacji o pokoju " + raw_parm4);
}
// po przetworzeniu informacji o pokoju wyczyść jego dane
ga.cs_i.erase(raw_parm4);
}
/*
NOTICE 165 (CS INFO #pokój)
:ChanServ!service@service.onet NOTICE ucieszony86 :165 #ucc :Opis pokoju
*/
void raw_notice_165(struct global_args &ga, std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
ga.cs_i[raw_parm4].desc = form_from_chat(get_rest_from_buf(raw_buf, raw_parm4 + " :"));
}
/*
NOTICE 210 (NS SET LONGDESC - gdy nie podano opcji do zmiany)
:NickServ!service@service.onet NOTICE ucieszony86 :210 :nothing changed
*/
void raw_notice_210(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + nick_who + ": niczego nie zmieniono.");
}
/*
NOTICE 211 (NS SET SHORTDESC - gdy nie podano opcji do zmiany, a wcześniej była ustawiona jakaś wartość)
:NickServ!service@service.onet NOTICE ucieszony86 :211 shortDesc :value unset
*/
void raw_notice_211(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + nick_who + ": " + raw_parm4 + " - wartość wyłączona.");
}
/*
NOTICE 220 (NS FRIENDS ADD nick)
:NickServ!service@service.onet NOTICE ucc_test :220 ucieszony86 :friend added to list
*/
void raw_notice_220(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + raw_parm4 + " został(a) dodany(-na) do listy przyjaciół.");
}
/*
NOTICE 221 (NS FRIENDS DEL nick)
:NickServ!service@service.onet NOTICE ucc_test :221 ucieszony86 :friend removed from list
*/
void raw_notice_221(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + raw_parm4 + " został(a) usunięty(-ta) z listy przyjaciół.");
}
/*
NOTICE 230 (NS IGNORE ADD nick)
:NickServ!service@service.onet NOTICE ucc :230 ucc_test :ignore added to list
*/
void raw_notice_230(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + raw_parm4 + " został(a) dodany(-na) do listy ignorowanych.");
}
/*
NOTICE 231 (NS IGNORE DEL nick)
:NickServ!service@service.onet NOTICE ucc :231 ucc_test :ignore removed from list
*/
void raw_notice_231(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + raw_parm4 + " został(a) usunięty(-ta) z listy ignorowanych.");
}
/*
NOTICE 240 (NS FAVOURITES ADD #pokój)
:NickServ!service@service.onet NOTICE ucc_test :240 #Linux :favourite added to list
*/
void raw_notice_240(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Pokój " + raw_parm4 + " został dodany do listy ulubionych.");
}
/*
NOTICE 241 (NS FAVOURITES DEL #pokój)
:NickServ!service@service.onet NOTICE ucc_test :241 #ucc :favourite removed from list
*/
void raw_notice_241(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Pokój " + raw_parm4 + " został usunięty z listy ulubionych.");
}
/*
NOTICE 250 (CS REGISTER #pokój)
:ChanServ!service@service.onet NOTICE ucieszony86 :250 #nowy_test :channel registered
*/
void raw_notice_250(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xGREEN "Pomyślnie utworzono nowy pokój " + raw_parm4);
}
/*
NOTICE 251 (CS DROP #pokój)
:ChanServ!service@service.onet NOTICE ucieszony86 :251 #nowy_test :has been dropped
*/
void raw_notice_251(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
// informacja w aktywnym pokoju (o ile to nie "Status", "DebugIRC" i "RawUnknown")
if(ga.current < CHAN_CHAT)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Pokój " + raw_parm4 + " został usunięty przez " + raw_parm2);
}
// pokaż również w "Status"
win_buf_add_str(ga, ci, "Status", oINFOn xRED "Pokój " + raw_parm4 + " został usunięty przez " + raw_parm2);
}
/*
NOTICE 252 (CS DROP #pokój - pojawia się, gdy to ja usuwam pokój, ale podobna informacja pojawia się w RAW NOTICE 252 i 261, więc tę ukryj)
:ChanServ!service@service.onet NOTICE #nowy_test :252 ucieszony86 :has dropped this channel
*/
void raw_notice_252()
{
}
/*
NOTICE 253 (CS TRANSFER #pokój nick - pojawia się, gdy to ja przekazuję komuś pokój, ale podobna informacja jest w RAW NOTICE 254, więc tę ukryj)
:ChanServ!service@service.onet NOTICE ucieszony86 :253 #ucc ucc :channel owner changed
*/
void raw_notice_253()
{
}
/*
NOTICE 254 (CS TRANSFER #pokój nick)
:ChanServ!service@service.onet NOTICE #ucc :254 ucieszony86 ucc :changed channel owner
*/
void raw_notice_254(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
// informacja w pokoju
win_buf_add_str(ga, ci, raw_parm2, oINFOn xMAGENTA + raw_parm4 + " przekazał(a) pokój " + raw_parm2 + " dla " + raw_parm5);
// pokaż również w "Status"
win_buf_add_str(ga, ci, "Status", oINFOn xMAGENTA + raw_parm4 + " przekazał(a) pokój " + raw_parm2 + " dla " + raw_parm5);
}
/*
NOTICE 255 (pojawia się, gdy to ja zmieniam ustawienia, ale podobna informacja pojawia się w RAW NOTICE 256, więc tę ukryj)
:ChanServ!service@service.onet NOTICE ucc_test :255 #ucc -h ucc_test :channel privilege changed
:ChanServ!service@service.onet NOTICE ucc_test :255 #ucc +v AT89S8253 :channel privilege changed
*/
void raw_notice_255()
{
}
/*
NOTICE 256
:ChanServ!service@service.onet NOTICE #ucc :256 ucieszony86 +b ucc_test :channel privilege changed
:ChanServ!service@service.onet NOTICE #ucc :256 ucieszony86 -h ucc_test :channel privilege changed
:ChanServ!service@service.onet NOTICE #ucc :256 ucieszony86 -o AT89S8253 :channel privilege changed
:ChanServ!service@service.onet NOTICE #ucc :256 ucc_test +v AT89S8253 :channel privilege changed
:ChanServ!service@service.onet NOTICE #ucc :256 Kernel_Panic +I abc!*@* :channel privilege changed
*/
void raw_notice_256(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
// przebuduj parametry tak, aby pasowały do funkcji raw_mode(), aby nie dublować tego samego; poniżej przykładowy RAW z MODE:
// :ChanServ!service@service.onet MODE #ucc +h ucc_test
// w ten sposób należy przebudować parametry, aby pasowały do raw_mode()
// 0 - tu wrzucić 4
// 1 - bez znaczenia
// 2 - pozostaje bez zmian
// 3 - tu wrzucić 5
// 4 - tu wrzucić wszystko od 6 do końca bufora (czyli za 5)
std::string raw_parm0 = get_raw_parm(raw_buf, 4);
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string raw_parm3 = get_raw_parm(raw_buf, 5);
std::string raw_rest = get_rest_from_buf(raw_buf, raw_parm3 + " ");
// w miejscu raw_parm0 i raw_parm1 trzeba coś wpisać (cokolwiek), dlatego wpisano kropkę (należy pamiętać, że raw_parm0 jest wysyłany jako parametr)
std::string raw_buf_new = ". . " + raw_parm2 + " " + raw_parm3 + " " + raw_rest;
// przykładowy RAW z NOTICE 256:
// :ChanServ!service@service.onet NOTICE #ucc :256 ucieszony86 -h ucc_test :channel privilege changed
// i po przebudowaniu (należy pamiętać, że raw_parm0 jest wysyłany jako parametr w raw_mode() ):
// . . #ucc -h ucc_test :channel privilege changed
raw_mode(ga, ci, raw_buf_new, raw_parm0);
}
/*
NOTICE 257 (pojawia się, gdy to ja zmieniam ustawienia, ale podobna informacja pojawia się w RAW NOTICE 258, więc tę ukryj)
:ChanServ!service@service.onet NOTICE ucieszony86 :257 #ucc * :settings changed
*/
void raw_notice_257()
{
}
/*
NOTICE 258 (np. CS SET #ucc GUARDIAN 0 - zwraca 'i')
:ChanServ!service@service.onet NOTICE #ucc :258 ucieszony86 * :channel settings changed
:ChanServ!service@service.onet NOTICE #ucc :258 ucieszony86 i :channel settings changed
*/
void raw_notice_258(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm2 = get_raw_parm(raw_buf, 2);
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
win_buf_add_str(ga, ci, raw_parm2, oINFOn xMAGENTA + raw_parm4 + " zmienił(a) ustawienia pokoju " + raw_parm2 + " [" + raw_parm5 + "]");
}
/*
NOTICE 259 (np. wpisanie 2x tego samego tematu: CS SET #ucc TOPIC abc)
:ChanServ!service@service.onet NOTICE ucieszony86 :259 #ucc :nothing changed
*/
void raw_notice_259(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, raw_parm4, oINFOn xWHITE "Niczego nie zmieniono w pokoju " + raw_parm4);
}
/*
NOTICE 260 (pokazywać tylko wtedy, gdy nie przebywamy w pokoju, którego zmiana dotyczy, bo w przeciwnym razie pokaże się dwa razy)
:ChanServ!service@service.onet NOTICE ucc_test :260 ucc_test #ucc -h :channel privilege changed
:ChanServ!service@service.onet NOTICE ucc_test :260 AT89S8253 #ucc -h :channel privilege changed
:ChanServ!service@service.onet NOTICE ucieszony86 :260 ucieszony86 #ucc -q :channel privilege changed
*/
void raw_notice_260(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
// przebuduj parametry tak, aby pasowały do funkcji raw_mode(), aby nie dublować tego samego; poniżej przykładowy RAW z MODE:
// :ChanServ!service@service.onet MODE #ucc +h ucc_test
// w ten sposób należy przebudować parametry, aby pasowały do raw_mode()
// 0 - tu wrzucić 4
// 1 - bez znaczenia
// 2 - tu wrzucić 5
// 3 - tu wrzucić 6
// 4 - tu wrzucić 2
std::string raw_parm0 = get_raw_parm(raw_buf, 4);
std::string raw_parm2 = get_raw_parm(raw_buf, 5);
std::string raw_parm3 = get_raw_parm(raw_buf, 6);
std::string raw_parm4 = get_raw_parm(raw_buf, 2);
// w miejscu raw_parm0 i raw_parm1 trzeba coś wpisać (cokolwiek), dlatego wpisano kropkę (należy pamiętać, że raw_parm0 jest wysyłany jako parametr)
std::string raw_buf_new = ". . " + raw_parm2 + " " + raw_parm3 + " " + raw_parm4;
// przykładowy RAW z NOTICE 260:
// :ChanServ!service@service.onet NOTICE Kernel_Panic :260 ucieszony86 #ucc +h :channel privilege changed
// i po przebudowaniu (należy pamiętać, że raw_parm0 jest wysyłany jako parametr w raw_mode() ):
// . . #ucc +h Kernel_Panic
// nie pokazuj, jeśli pokój, którego zmiana dotyczy jest pokojem, w którym jesteśmy
for(int i = 0; i < CHAN_CHAT; ++i)
{
if(ci[i] && ci[i]->channel == raw_parm2)
{
return;
}
}
raw_mode(ga, ci, raw_buf_new, raw_parm0);
}
/*
NOTICE 261 (CS DROP #pokój - podobną informację pokazuje RAW NOTICE 251 i RAW NOTICE 252, więc tę ukryj)
:ChanServ!service@service.onet NOTICE ucieszony86 :261 ucieszony86 #nowy_test :has dropped this channel
*/
void raw_notice_261()
{
}
/*
NOTICE 400 (NS FAVOURITES ADD/DEL #pokój, NS FRIENDS ADD/DEL nick - wykonywane na nicku tymczasowym)
:NickServ!service@service.onet NOTICE ~zyxewq :400 :you are not registered
*/
void raw_notice_400(struct global_args &ga, struct channel_irc *ci[])
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nie jesteś zarejestrowany(-na).");
}
/*
NOTICE 401 (NS FRIENDS ADD ~nick - podanie nicka tymczasowego)
:NickServ!service@service.onet NOTICE ucc :401 ~abc :no such nick
NOTICE 401 (NS INFO nick)
:NickServ!service@service.onet NOTICE ucc_test :401 t :no such nick
:NickServ!service@service.onet NOTICE ucc_test :401 :no such nick
*/
void raw_notice_401(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":401 ", " :");
if(ga.cf.friends && raw_arg.size() > 0 && raw_arg[0] == '~')
{
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOb xMAGENTA + raw_arg + xNORMAL " - nie można dodać nicka tymczasowego do listy przyjaciół.");
}
else if(raw_arg.size() > 0)
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOb xDARK + raw_arg + xNORMAL " - nie ma takiego użytkownika na czacie.");
}
// jeśli po ADD lub INFO wpisano 4 lub więcej spacji
else
{
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + get_value_from_buf(raw_buf, ":", "!") + ": nie podano nicka.");
}
}
/*
NOTICE 402 (NS IGNORE ADD - 4 lub więcej spacji po ADD)
:NickServ!service@service.onet NOTICE ucc :402 :invalid mask
NOTICE 402 (CS BAN #pokój ADD anonymous@IP - nieprawidłowa maska)
:ChanServ!service@service.onet NOTICE ucieszony86 :402 anonymous@IP!*@* :invalid mask
*/
void raw_notice_402(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":402 ", " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel, (! ga.cf.ignore
? oINFOn xRED + raw_arg + " - nieprawidłowa maska."
: oINFOn xRED + get_value_from_buf(raw_buf, ":", "!") + ": nie podano nicka."));
}
/*
NOTICE 403 (RS INFO nick, CS VOICE/MODERATOR #pokój ADD nick - gdy nie ma nicka)
:RankServ!service@service.onet NOTICE ucc_test :403 abc :user is not on-line
:RankServ!service@service.onet NOTICE ucc_test :403 :user is not on-line
*/
void raw_notice_403(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":403 ", " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel, (raw_arg.size() > 0
// opcja dla pierwszego RAW powyżej
? oINFOb xYELLOW_BLACK + raw_arg + xNORMAL " - nie ma takiego użytkownika na czacie."
// jeśli po INFO wpisano 4 lub więcej spacji
: oINFOn xRED + get_value_from_buf(raw_buf, ":", "!") + ": nie podano nicka."));
}
/*
NOTICE 404 (NS INFO nick - dla nicka tymczasowego)
:NickServ!service@service.onet NOTICE ucc_test :404 ~zyxewq :user is not registered
*/
void raw_notice_404(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOb xMAGENTA + raw_parm4 + xNORMAL " - użytkownik nie jest zarejestrowany.");
}
/*
NOTICE 406 (NS/CS/RS/GS nieznane_polecenie)
:NickServ!service@service.onet NOTICE ucc_test :406 ABC :unknown command
*/
void raw_notice_406(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":406 ", " :");
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + nick_who + ": " + raw_arg + " - nieznane polecenie.");
}
/*
NOTICE 407 (NS/CS/RS SET)
:ChanServ!service@service.onet NOTICE ucieszony86 :407 SET :not enough parameters
*/
void raw_notice_407(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + nick_who + ": " + raw_parm4 + " - brak wystarczającej liczby parametrów.");
}
/*
NOTICE 408 (NS FAVOURITES ADD/CS DROP - 4 lub więcej spacji po ADD)
:NickServ!service@service.onet NOTICE ucc :408 # :no such channel
NOTICE 408 (CS INFO #pokój/CS DROP #pokój)
:ChanServ!service@service.onet NOTICE ucc_test :408 abc :no such channel
:ChanServ!service@service.onet NOTICE ucc_test :408 :no such channel
*/
void raw_notice_408(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":408 ", " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel, (raw_arg.size() > 0 && ! ga.cf.favourites_empty
? oINFOn xRED + raw_arg + xNORMAL " - nie ma takiego pokoju."
// jeśli po ADD lub INFO wpisano 4 lub więcej spacji
: oINFOn xRED + get_value_from_buf(raw_buf, ":", "!") + ": nie podano pokoju."));
}
/*
NOTICE 409 (NS SET opcja_do_zmiany - brak argumentu)
:NickServ!service@service.onet NOTICE ucieszony86 :409 OFFMSG :invalid argument
*/
void raw_notice_409(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + nick_who + ": nieprawidłowy argument dla " + raw_parm4);
}
/*
NOTICE 411 (NS/CS/RS SET - 4 lub więcej spacji po SET)
:NickServ!service@service.onet NOTICE ucc :411 :no such setting
NOTICE 411 (NS SET ABC)
:NickServ!service@service.onet NOTICE ucieszony86 :411 ABC :no such setting
*/
void raw_notice_411(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":411 ", " :");
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xRED + nick_who + (raw_arg.size() > 0
? ": " + raw_arg + " - nie ma takiego ustawienia."
: ": brak wystarczającej liczby parametrów."));
}
/*
NOTICE 415 (RS INFO nick - gdy jest online i nie mamy dostępu do informacji)
:RankServ!service@service.onet NOTICE ucc_test :415 ucieszony86 :permission denied
*/
void raw_notice_415(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + nick_who + ": " + raw_parm4 + " - dostęp do informacji zabroniony.");
}
/*
NOTICE 416 (RS INFO #pokój - gdy nie mamy dostępu do informacji, musimy być w danym pokoju i być minimum opem, aby uzyskać informacje o nim)
:RankServ!service@service.onet NOTICE ucc_test :416 #ucc :permission denied
*/
void raw_notice_416(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + nick_who + ": " + raw_parm4 + " - dostęp do informacji zabroniony.");
}
/*
NOTICE 420 (NS FRIENDS ADD nick - gdy nick już dodano do listy)
:NickServ!service@service.onet NOTICE ucieszony86 :420 legionella :is already on your friend list
*/
void raw_notice_420(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + raw_parm4 + " jest już na liście przyjaciół.");
}
/*
NOTICE 421 (NS FRIENDS DEL nick - gdy nicka nie było na liście)
:NickServ!service@service.onet NOTICE ucieszony86 :421 abc :is not on your friend list
*/
void raw_notice_421(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":421 ", " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel, (raw_arg.size() > 0
? oINFOn xWHITE + raw_arg + " nie był(a) dodany(-na) do listy przyjaciół."
// jeśli po DEL wpisano 4 lub więcej spacji
: oINFOn xRED + get_value_from_buf(raw_buf, ":", "!") + ": nie podano nicka."));
}
/*
NOTICE 430 (NS IGNORE ADD nick - gdy nick już dodano do listy)
:NickServ!service@service.onet NOTICE ucc :430 ucc_test :is already on your ignore list
*/
void raw_notice_430(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE + raw_parm4 + " jest już na liście ignorowanych.");
}
/*
NOTICE 431 (NS IGNORE DEL nick - gdy nicka nie było na liście)
:NickServ!service@service.onet NOTICE ucc :431 ucc_test :is not on your ignore list
*/
void raw_notice_431(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":431 ", " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel, (raw_arg.size() > 0
? oINFOn xWHITE + raw_arg + " nie był(a) dodany(-na) do listy ignorowanych."
// jeśli po DEL wpisano 4 lub więcej spacji
: oINFOn xRED + get_value_from_buf(raw_buf, ":", "!") + ": nie podano nicka."));
}
/*
NOTICE 440 (NS FAVOURITES ADD #pokój - gdy pokój już jest na liście ulubionych)
:NickServ!service@service.onet NOTICE ucieszony86 :440 #Towarzyski :is already on your favourite list
*/
void raw_notice_440(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xWHITE "Pokój " + raw_parm4 + " jest już na liście ulubionych.");
}
/*
NOTICE 441 (NS FAVOURITES DEL #pokój - gdy pokój nie został dodany do listy ulubionych)
:NickServ!service@service.onet NOTICE ucieszony86 :441 #Towarzyski :is not on your favourite list
*/
void raw_notice_441(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":441 ", " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel, (raw_arg.size() > 0
? oINFOn xWHITE "Pokój " + raw_arg + " nie był dodany do listy ulubionych."
// jeśli po DEL wpisano 4 lub więcej spacji
: oINFOn xRED + get_value_from_buf(raw_buf, ":", "!") + ": nie podano pokoju."));
}
/*
NOTICE 452 (CS REGISTER #pokój - gdy pokój już istnieje)
:ChanServ!service@service.onet NOTICE ucieszony86 :452 #ertt :channel name already in use
*/
void raw_notice_452(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Pokój " + raw_parm4 + " już istnieje.");
}
/*
NOTICE 453 (CS REGISTER #nieprawidłowa_nazwa_pokoju - np. $ lub podanie przynajmniej czterech spacji)
:ChanServ!service@service.onet NOTICE ucieszony86 :453 #$ :is not valid channel name
*/
void raw_notice_453(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":453 ", " :");
win_buf_add_str(ga, ci, ci[ga.current]->channel, (raw_arg.size() > 1
? oINFOn xRED "Nazwa pokoju " + raw_arg + " jest nieprawidłowa, wybierz inną."
// jeśli po REGISTER wpisano 4 lub więcej spacji
: oINFOn xRED + get_value_from_buf(raw_buf, ":", "!") + ": nie podano pokoju."));
}
/*
NOTICE 454 (CS REGISTER #xyzz - nazwa pokoju jest za mało unikalna, cokolwiek to znaczy)
:ChanServ!service@service.onet NOTICE ucc_test :454 #xyzz :not enough unique channel name
*/
void raw_notice_454(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nazwa pokoju " + raw_parm4 + " jest za mało unikalna, wybierz inną.");
}
/*
NOTICE 458 (CS opcja #pokój DEL nick - próba zdjęcia nienadanego statusu/uprawnienia)
:ChanServ!service@service.onet NOTICE ucieszony86 :458 #pokój b anonymous@IP!*@* :unable to remove non-existent privilege
*/
void raw_notice_458(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
// poprawić na rozróżnianie uprawnień
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
win_buf_add_str(ga, ci, raw_parm4, oINFOn xWHITE "Nie można usunąć nienadanego uprawnienia dla " + raw_parm6 + " (" + raw_parm5 + ").");
}
/*
NOTICE 459 (CS opcja #pokój ADD nick - nadanie istniejącego już statusu/uprawnienia)
:ChanServ!service@service.onet NOTICE ucieszony86 :459 #ucc q ucieszony86 :channel privilege already given
:ChanServ!service@service.onet NOTICE ucieszony86 :459 #ucc v ucieszony86 :channel privilege already given
*/
void raw_notice_459(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
// poprawić na rozróżnianie uprawnień
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
win_buf_add_str(ga, ci, raw_parm4, oINFOn xWHITE + raw_parm6 + " posiada już nadane uprawnienie (" + raw_parm5 + ").");
}
/*
NOTICE 461 (CS BAN #pokój ADD nick - ban na superoperatora/operatora)
:ChanServ!service@service.onet NOTICE ucieszony86 :461 #ucc ucc :channel operators cannot be banned
*/
void raw_notice_461(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
win_buf_add_str(ga, ci, raw_parm4,
oINFOn xRED + raw_parm5 + " jest superoperatorem lub operatorem pokoju " + raw_parm4 + ", nie może zostać zbanowany(-na).");
}
/*
NOTICE 463
*/
void raw_notice_463(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm5 = get_raw_parm(raw_buf, 5);
// CS SET #pokój MODERATED ON/OFF - przy braku uprawnień
// :ChanServ!service@service.onet NOTICE ucieszony86 :463 #Suwałki MODERATED :permission denied, insufficient privileges
if(raw_parm5 == "MODERATED")
{
win_buf_add_str(ga, ci, raw_parm4, oINFOn xRED "Nie posiadasz uprawnień do zmiany stanu moderacji w pokoju " + raw_parm4);
}
// CS SET #pokój PASSWORD xyz - przy braku uprawnień
// :ChanServ!service@service.onet NOTICE ucc_test :463 #ucc PASSWORD :permission denied, insufficient privileges
else if(raw_parm5 == "PASSWORD")
{
win_buf_add_str(ga, ci, raw_parm4, oINFOn xRED "Nie posiadasz uprawnień do zmiany hasła w pokoju " + raw_parm4);
}
// CS SET #pokój PRIVATE ON/OFF - przy braku uprawnień
// :ChanServ!service@service.onet NOTICE ucieszony86 :463 #zua_zuy_zuo PRIVATE :permission denied, insufficient privileges
else if(raw_parm5 == "PRIVATE")
{
win_buf_add_str(ga, ci, raw_parm4, oINFOn xRED "Nie posiadasz uprawnień do zmiany statusu prywatności w pokoju " + raw_parm4);
}
// CS SET #pokój TOPIC ... - w pokoju bez uprawnień
// :ChanServ!service@service.onet NOTICE ucc_test :463 #zua_zuy_zuo TOPIC :permission denied, insufficient privileges
else if(raw_parm5 == "TOPIC")
{
win_buf_add_str(ga, ci, raw_parm4, oINFOn xRED "Nie posiadasz uprawnień do zmiany tematu w pokoju " + raw_parm4);
}
// nieznany lub niezaimplementowany powód zmiany ustawień
else
{
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, raw_parm4, oINFOn xRED + nick_who + ": " + raw_parm5 + " - nie posiadasz uprawnień do zmiany tego ustawienia.");
}
}
/*
NOTICE 464 (np. CS SET #pokój TOPIC za długi temat)
:ChanServ!service@service.onet NOTICE ucc_test :464 TOPIC :invalid argument
:ChanServ!service@service.onet NOTICE ucieszony86 :464 MODERATED :invalid argument
*/
void raw_notice_464(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED + nick_who + ": nieprawidłowy argument dla " + raw_parm4);
}
/*
NOTICE 465 (CS SET #pokój nieznane_ustawienie)
:ChanServ!service@service.onet NOTICE ucc_test :465 ABC :no such setting
*/
void raw_notice_465(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_arg = get_value_from_buf(raw_buf, ":465 ", " :");
std::string nick_who = get_value_from_buf(raw_buf, ":", "!");
win_buf_add_str(ga, ci, ci[ga.current]->channel,
oINFOn xRED + nick_who + (raw_arg.size() > 0
? ": " + raw_arg + " - nie ma takiego ustawienia."
: ": brak wystarczającej liczby parametrów."));
}
/*
NOTICE 467 (CS TRANSFER #pokój nick - gdy nie jestem właścicielem pokoju)
:ChanServ!service@service.onet NOTICE ucieszony86 :467 #ucc :permission denied, you are not a channel owner
*/
void raw_notice_467(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Dostęp zabroniony, nie jesteś właścicielem pokoju " + raw_parm4);
}
/*
NOTICE 468 (CS opcja #pokój ADD nick - przy braku uprawnień)
:ChanServ!service@service.onet NOTICE ucieszony86 :468 #Learning_English :permission denied, insufficient privileges
*/
void raw_notice_468(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Dostęp zabroniony, nie posiadasz wystarczających uprawnień w pokoju " + raw_parm4);
}
/*
NOTICE 470 (CS REGISTER #pokój - wulgarne słowo w nazwie pokoju)
:ChanServ!service@service.onet NOTICE ucc_test :470 #bluzg :channel name is vulgar
*/
void raw_notice_470(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Nazwa pokoju " + raw_parm4 + " jest wulgarna, wybierz inną.");
}
/*
NOTICE 472 (CS REGISTER #pokój - zbyt szybkie zakładanie pokoi po sobie)
:ChanServ!service@service.onet NOTICE ucieszony86 :472 #ert :wait 60 seconds before next REGISTER
*/
void raw_notice_472(struct global_args &ga, struct channel_irc *ci[], std::string &raw_buf)
{
std::string raw_parm4 = get_raw_parm(raw_buf, 4);
std::string raw_parm6 = get_raw_parm(raw_buf, 6);
win_buf_add_str(ga, ci, ci[ga.current]->channel, oINFOn xRED "Musisz odczekać " + raw_parm6 + "s przed próbą utworzenia pokoju " + raw_parm4);
}
| pawelostrowski/ucc | src/irc_parser.cpp | C++ | gpl-2.0 | 201,117 |
<?php
/* This helps define aditional configurations for emails notifications. Templates and automatic emails are also defined here.
* Author: Leonardo Martinez.
*/
/******************************************************************************/
/* EMAIL SMTP CONFIGURATION */
/******************************************************************************/
/*
Email settings for closettine
*/
add_action( 'phpmailer_init', 'config_mail_contact' );
function config_mail_contact( $phpmailer ) {
$phpmailer->Host = 'smtp.gmail.com';
$phpmailer->Port = 465; // could be different
$phpmailer->Username = 'breakpointcontactus@gmail.com'; // if required
$phpmailer->Password = '2Alvaro0Arelis1Leo6'; // if required
$phpmailer->SMTPAuth = true; // if required
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->IsSMTP();
}
//Filtro para indicar que email debe ser enviado en modo HTML
add_filter('wp_mail_content_type',create_function('', 'return "text/html";'));
//Cambiamos el remitente del email que en Wordpress por defecto es tu email de admin
add_filter('wp_mail_from','emailRemitente');
function emailRemitente($content_type) {
return 'noreply@breakpoint.com';
}
//Cambiamos el nombre del remitente del email que en Wordpress por defecto es "Wordpress"
add_filter('wp_mail_from_name','nombreRemitente');
function nombreRemitente($name) {
return 'Break Point';
}
/******************************************************************************/
/* EMAIL TEMPLATES */
/******************************************************************************/
/*
* Regurns css styles for emails.
*/
function get_email_styles(){
$styles = '
body {
font-size: 15px;
width: 600px;
font-family: "Josefin Sans", sans-serif;
text-align: justify;
background: #FFF;
}
img {
display: inline-block;
}
h1, h2, h3, h4, h5 {
color: #006699;
}
.body-inner {
padding: 10%;
margin: 0;
border-right: 50px solid #00283C;
border-left: 50px solid #00283C;
}
a {
color: #006699 !important;
text-decoration: none;
font-weight: bolder;
}
a:hover {
color: #006699;
text-decoration: underline;
}
button {
color: #00283C !important;
background: none;
margin: 2vw auto;
border: 1px solid #006699;
border-radius: 5px;
width: 150px;
height: 25px;
text-align: center;
font-size: 15px;
display: block;
}
button:hover,
button:active,
button:focus {
color: white !important;
background-color: #006699;
}
';
return $styles;
}
/*
* Generic template for all *most* emails.
*/
function generic_template($title = "", $content) {
$message = '
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<style type="text/css">
'.get_email_styles().'
</style>
</head>
<body>
<div class="body-inner">
<img style="margin: 0 auto; display: block;"
src="https://docs.google.com/uc?id=0B4X9fCHEUJBCRmNOeWJRWjNlcXM"
alt="breakpointlogo" height="70px" width="70px"/>
<center><h2> '.$title. '</h2></center><br>
<p>'.$content.'</p>
<br>
<br>
<center>
<a href="https://www.facebook.com/breakpointpage"><img src="https://docs.google.com/uc?id=0B4X9fCHEUJBCNE9XOUFDVEpRdlE"></a>
<a href="https://twitter.com/breakpointpage"><img src="https://docs.google.com/uc?id=0B4X9fCHEUJBCdW85ZGhHTUhQeGs"></a>
<a href="https://www.instagram.com/breakpointpage/"><img src="https://docs.google.com/uc?id=0B4X9fCHEUJBCNzBkdnhMLVhyLXM"></a>
</center>
<center><p style="font-size: 10px;">© Break-Point '.date("Y").'. Derechos Reservados.</p></center>
</body>
</html>';
return $message;
}
function contact_reply_template($title = "¡Gracias por escribirnos!") {
$message = '
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<style type="text/css">
'.get_email_styles().'
</style>
</head>
<body>
<div class="body-inner">
<img style="margin: 0 auto; display: block;"
src="https://docs.google.com/uc?id=0B4X9fCHEUJBCRmNOeWJRWjNlcXM"
alt="breakpointlogo" height="70px" width="70px"/>
<center>
<h2>'.$title.'</h2><br>
<p>Mientras esperas nuestra respuesta ¡Explora nuestro contenido!</p>
</center>
<a href="'.get_bloginfo('url')."/blog".'">
<img style="margin: 15px auto; display: block;"
src="https://docs.google.com/uc?id=0B4X9fCHEUJBCQ1hFdEZUZnRHTTg"
alt="breakpointblog" height="125px" width="125px"/>
</a>
<center><a href="'.get_bloginfo('url')."/blog".'"><h2>Blog</h2></a></center>
<br>
<br>
<center>
<a href="https://www.facebook.com/breakpointpage"><img src="https://docs.google.com/uc?id=0B4X9fCHEUJBCNE9XOUFDVEpRdlE"></a>
<a href="https://twitter.com/breakpointpage"><img src="https://docs.google.com/uc?id=0B4X9fCHEUJBCdW85ZGhHTUhQeGs"></a>
<a href="https://www.instagram.com/breakpointpage/"><img src="https://docs.google.com/uc?id=0B4X9fCHEUJBCNzBkdnhMLVhyLXM"></a>
</center>
<center><p style="font-size: 10px;">© Break-Point '.date("Y").'. Derechos Reservados.</p></center>
</body>
</html>';
return $message;
}
https://drive.google.com/open?id=0B4X9fCHEUJBCNzBkdnhMLVhyLXM
| leotms/break-point-theme-2017 | inc/break-point-emailconfig.php | PHP | gpl-2.0 | 5,587 |
#include "hermes2d.h"
#include "solver_umfpack.h"
#include "function.h"
// This example shows how to combine the Newton's method with
// automatic adaptivity.
//
// PDE: stationary heat transfer equation with nonlinear thermal
// conductivity, - div[lambda(u)grad u] = 0
//
// Domain: unit square (-10,10)^2
//
// BC: Dirichlet, see function dir_lift() below.
//
// The following parameters can be changed:
const int P_INIT = 1; // Initial polynomial degree
const int PROJ_TYPE = 1; // For the projection of the initial condition
// on the initial mesh: 1 = H1 projection, 0 = L2 projection
const int INIT_GLOB_REF_NUM = 1; // Number of initial uniform mesh refinements
const int INIT_BDY_REF_NUM = 0; // Number of initial refinements towards boundary
const double THRESHOLD = 0.2; // This is a quantitative parameter of the adapt(...) function and
// it has different meanings for various adaptive strategies (see below).
const int STRATEGY = 1; // Adaptive strategy:
// STRATEGY = 0 ... refine elements until sqrt(THRESHOLD) times total
// error is processed. If more elements have similar errors, refine
// all to keep the mesh symmetric.
// STRATEGY = 1 ... refine all elements whose error is larger
// than THRESHOLD times maximum element error.
// STRATEGY = 2 ... refine all elements whose error is larger
// than THRESHOLD.
// More adaptive strategies can be created in adapt_ortho_h1.cpp.
const int ADAPT_TYPE = 0; // Type of automatic adaptivity:
// ADAPT_TYPE = 0 ... adaptive hp-FEM (default),
// ADAPT_TYPE = 1 ... adaptive h-FEM,
// ADAPT_TYPE = 2 ... adaptive p-FEM.
const bool ISO_ONLY = false; // Isotropic refinement flag (concerns quadrilateral elements only).
// ISO_ONLY = false ... anisotropic refinement of quad elements
// is allowed (default),
// ISO_ONLY = true ... only isotropic refinements of quad elements
// are allowed.
const int MESH_REGULARITY = -1; // Maximum allowed level of hanging nodes:
// MESH_REGULARITY = -1 ... arbitrary level hangning nodes (default),
// MESH_REGULARITY = 1 ... at most one-level hanging nodes,
// MESH_REGULARITY = 2 ... at most two-level hanging nodes, etc.
// Note that regular meshes are not supported, this is due to
// their notoriously bad performance.
const double ERR_STOP = 0.001; // Stopping criterion for adaptivity (rel. error tolerance between the
// fine mesh and coarse mesh solution in percent).
const int NDOF_STOP = 60000; // Adaptivity process stops when the number of degrees of freedom grows
// over this limit. This is to prevent h-adaptivity to go on forever.
const double NEWTON_TOL = 1e-6; // Stopping criterion for the Newton's method on coarse mesh
const double NEWTON_TOL_REF = 1e-6; // Stopping criterion for the Newton's method on fine mesh
// Thermal conductivity (temperature-dependent)
// Note: for any u, this function has to be positive
template<typename Real>
Real lam(Real u)
{
return 1 + pow(u, 4);
}
// Derivative of the thermal conductivity with respect to 'u'
template<typename Real>
Real dlam_du(Real u) {
return 4*pow(u, 3);
}
// This function is used to define Dirichlet boundary conditions
double dir_lift(double x, double y, double& dx, double& dy) {
dx = (y+10)/10.;
dy = (x+10)/10.;
return (x+10)*(y+10)/100.;
}
// This function will be projected on the initial mesh and
// used as initial guess for the Newton's method
scalar init_cond(double x, double y, double& dx, double& dy)
{
// using the Dirichlet lift elevated by two
double val = dir_lift(x, y, dx, dy) + 2;
return val;
}
// Boundary condition type (essential = Dirichlet)
int bc_types(int marker)
{
return BC_ESSENTIAL;
}
// Dirichlet boundary condition values
scalar bc_values(int marker, double x, double y)
{
double dx, dy;
return dir_lift(x, y, dx, dy);
}
// Heat sources (can be a general function of 'x' and 'y')
template<typename Real>
Real heat_src(Real x, Real y)
{
return 1.0;
}
// Jacobian matrix
template<typename Real, typename Scalar>
Scalar jac(int n, double *wt, Func<Real> *u, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
Func<Scalar>* u_prev = ext->fn[0];
for (int i = 0; i < n; i++)
result += wt[i] * (dlam_du(u_prev->val[i]) * u->val[i] * (u_prev->dx[i] * v->dx[i] + u_prev->dy[i] * v->dy[i])
+ lam(u_prev->val[i]) * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i]));
return result;
}
// Fesidual vector
template<typename Real, typename Scalar>
Scalar res(int n, double *wt, Func<Real> *v, Geom<Real> *e, ExtData<Scalar> *ext)
{
Scalar result = 0;
Func<Scalar>* u_prev = ext->fn[0];
for (int i = 0; i < n; i++)
result += wt[i] * (lam(u_prev->val[i]) * (u_prev->dx[i] * v->dx[i] + u_prev->dy[i] * v->dy[i])
- heat_src(e->x[i], e->y[i]) * v->val[i]);
return result;
}
int main(int argc, char* argv[])
{
// load the mesh file
Mesh mesh;
H2DReader mloader;
mloader.load("square.mesh", &mesh);
// initial mesh refinements
for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh.refine_all_elements();
mesh.refine_towards_boundary(1,INIT_BDY_REF_NUM);
// initialize the shapeset and the cache
H1Shapeset shapeset;
PrecalcShapeset pss(&shapeset);
// create an H1 space
H1Space space(&mesh, &shapeset);
space.set_bc_types(bc_types);
space.set_bc_values(bc_values);
space.set_uniform_order(P_INIT);
space.assign_dofs();
// previous solution for the Newton's iteration
Solution u_prev;
// initialize the weak formulation
WeakForm wf(1);
wf.add_biform(0, 0, callback(jac), UNSYM, ANY, 1, &u_prev);
wf.add_liform(0, callback(res), ANY, 1, &u_prev);
// initialize the nonlinear system and solver
UmfpackSolver umfpack;
NonlinSystem nls(&wf, &umfpack);
nls.set_spaces(1, &space);
nls.set_pss(1, &pss);
// DOF and CPU convergence graphs
SimpleGraph graph_dof, graph_cpu;
// project the function init_cond() on the mesh
// to obtain initial guess u_prev for the Newton's method
nls.set_ic(init_cond, &mesh, &u_prev, PROJ_TYPE);
// visualise the initial ocndition
ScalarView view("Initial condition", 0, 0, 700, 600);
view.show(&u_prev);
OrderView oview("Initial mesh", 720, 0, 700, 600);
oview.show(&space);
//printf("Click into the image window and press any key to proceed.\n");
//view.wait_for_keypress();
// adaptivity loop
double cpu = 0.0, err_est;
int a_step = 1;
bool done = false;
do {
a_step++;
// Newton's loop on the coarse mesh
int it = 1;
double res_l2_norm;
Solution sln_coarse;
do
{
info("\n---- Adapt step %d, Newton iter %d (coarse mesh) ---------------------------------\n", a_step, it++);
printf("ndof = %d\n", space.get_num_dofs());
// time measurement
begin_time();
// assemble the Jacobian matrix and residual vector,
// solve the system
nls.assemble();
nls.solve(1, &sln_coarse);
// calculate the l2-norm of residual vector
res_l2_norm = nls.get_residuum_l2_norm();
info("Residuum L2 norm: %g\n", res_l2_norm);
// time measurement
cpu += end_time();
// visualise the solution
char title[100];
sprintf(title, "Temperature (coarse mesh), Newton iteration %d", it-1);
view.set_title(title);
view.show(&sln_coarse);
sprintf(title, "Coarse mesh, Newton iteration %d", it-1);
oview.set_title(title);
oview.show(&space);
//printf("Click into the image window and press any key to proceed.\n");
//view.wait_for_keypress();
// save the new solution as "previous" for the
// next Newton's iteration
u_prev.copy(&sln_coarse);
}
while (res_l2_norm > NEWTON_TOL);
// Setting initial guess for the Newton's method on the fine mesh
Solution sln_fine, u_prev_fine;
RefNonlinSystem rs(&nls);
rs.prepare();
rs.set_ic(&u_prev, &u_prev);
// Newton's loop on the fine mesh
it = 1;
do {
info("\n---- Adapt step %d, Newton iter %d (fine mesh) ---------------------------------\n", a_step, it++);
// time measurement
begin_time();
// assemble the Jacobian matrix and residual vector,
// solve the system
rs.assemble();
rs.solve(1, &sln_fine);
// calculate the l2-norm of residual vector
res_l2_norm = rs.get_residuum_l2_norm();
info("Residuum L2 norm: %g\n", res_l2_norm);
// time measurement
cpu += end_time();
// visualise the solution
char title[100];
sprintf(title, "Temperature (fine mesh), Newton iteration %d", it-1);
view.set_title(title);
view.show(&sln_fine);
sprintf(title, "Fine mesh, Newton iteration %d", it-1);
oview.set_title(title);
oview.show(rs.get_ref_space(0));
//printf("Click into the image window and press any key to proceed.\n");
//view.wait_for_keypress();
u_prev.copy(&sln_fine);
} while (res_l2_norm > NEWTON_TOL_REF);
// time measurement
begin_time();
// calculate element errors and total error estimate
H1OrthoHP hp(1, &space);
err_est = hp.calc_error(&sln_coarse, &sln_fine) * 100;
info("Error estimate: %g%%", err_est);
// add entry to DOF convergence graph
graph_dof.add_values(space.get_num_dofs(), err_est);
graph_dof.save("conv_dof.dat");
// add entry to CPU convergence graph
graph_cpu.add_values(cpu, err_est);
graph_cpu.save("conv_cpu.dat");
// if err_est too large, adapt the mesh
if (err_est < ERR_STOP) done = true;
else {
hp.adapt(THRESHOLD, STRATEGY, ADAPT_TYPE, ISO_ONLY, MESH_REGULARITY);
int ndof = space.assign_dofs();
if (ndof >= NDOF_STOP) done = true;
}
// time measurement
cpu += end_time();
}
while (!done);
verbose("Total running time: %g sec", cpu);
// wait for keyboard or mouse input
View::wait();
return 0;
}
| davidquantum/hermes2dold | tutorial/15-newton-elliptic-adapt/main.cpp | C++ | gpl-2.0 | 10,885 |
<?php
/**
* JCH Optimize - Joomla! plugin to aggregate and minify external resources for
* optmized downloads
*
* @author Samuel Marshall <sdmarshall73@gmail.com>
* @copyright Copyright (c) 2014 Samuel Marshall
* @license GNU/GPLv3, See LICENSE file
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* If LICENSE file missing, see <http://www.gnu.org/licenses/>.
*/
defined('_WP_EXEC') or die('Restricted access');
class JchPlatformExcludes implements JchInterfaceExcludes
{
/**
*
* @param type $type
* @param type $section
* @return type
*/
public static function body($type, $section = 'file')
{
if ($type == 'js')
{
if ($section == 'script')
{
return array();
}
else
{
return array();
}
}
if ($type == 'css')
{
return array();
}
}
/**
*
* @return type
*/
public static function extensions()
{
return JchPlatformPaths::rewriteBase();
}
/**
*
* @param type $type
* @param type $section
* @return type
*/
public static function head($type, $section = 'file')
{
if ($type == 'js')
{
if ($section == 'script')
{
return array();
}
else
{
return array();
}
}
if ($type == 'css')
{
return array();
}
}
/**
*
* @param type $url
* @return type
*/
public static function editors($url)
{
return (preg_match('#/editors/#i', $url));
}
}
| frammawiliansyah/web | wp-content/plugins/jch-optimize/platform/excludes.php | PHP | gpl-2.0 | 2,673 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2012 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
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 "InputEvents.hpp"
#include "Language/Language.hpp"
#include "Message.hpp"
#include "Interface.hpp"
#include "Pages.hpp"
#include "Profile/Profile.hpp"
#include "Profile/ProfileKeys.hpp"
#include "MainWindow.hpp"
#include "MapWindow/GlueMapWindow.hpp"
#include "Units/Units.hpp"
#include "Asset.hpp"
// eventAutoZoom - Turn on|off|toggle AutoZoom
// misc:
// auto on - Turn on if not already
// auto off - Turn off if not already
// auto toggle - Toggle current full screen status
// auto show - Shows autozoom status
// + - Zoom in
// ++ - Zoom in near
// - - Zoom out
// -- - Zoom out far
// n.n - Zoom to a set scale
// show - Show current zoom scale
void
InputEvents::eventZoom(const TCHAR* misc)
{
// JMW pass through to handler in MapWindow
// here:
// -1 means toggle
// 0 means off
// 1 means on
MapSettings &settings_map = CommonInterface::SetMapSettings();
if (StringIsEqual(misc, _T("auto toggle")))
sub_AutoZoom(-1);
else if (StringIsEqual(misc, _T("auto on")))
sub_AutoZoom(1);
else if (StringIsEqual(misc, _T("auto off")))
sub_AutoZoom(0);
else if (StringIsEqual(misc, _T("auto show"))) {
if (settings_map.auto_zoom_enabled)
Message::AddMessage(_("Auto. zoom on"));
else
Message::AddMessage(_("Auto. zoom off"));
} else if (StringIsEqual(misc, _T("slowout")))
sub_ScaleZoom(-1);
else if (StringIsEqual(misc, _T("slowin")))
sub_ScaleZoom(1);
else if (StringIsEqual(misc, _T("out")))
sub_ScaleZoom(-1);
else if (StringIsEqual(misc, _T("in")))
sub_ScaleZoom(1);
else if (StringIsEqual(misc, _T("-")))
sub_ScaleZoom(-1);
else if (StringIsEqual(misc, _T("+")))
sub_ScaleZoom(1);
else if (StringIsEqual(misc, _T("--")))
sub_ScaleZoom(-2);
else if (StringIsEqual(misc, _T("++")))
sub_ScaleZoom(2);
else if (StringIsEqual(misc, _T("circlezoom toggle"))) {
settings_map.circle_zoom_enabled = !settings_map.circle_zoom_enabled;
} else if (StringIsEqual(misc, _T("circlezoom on"))) {
settings_map.circle_zoom_enabled = true;
} else if (StringIsEqual(misc, _T("circlezoom off"))) {
settings_map.circle_zoom_enabled = false;
} else if (StringIsEqual(misc, _T("circlezoom show"))) {
if (settings_map.circle_zoom_enabled)
Message::AddMessage(_("Circling zoom on"));
else
Message::AddMessage(_("Circling zoom off"));
} else {
TCHAR *endptr;
double zoom = _tcstod(misc, &endptr);
if (endptr == misc)
return;
sub_SetZoom(Units::ToSysDistance(fixed(zoom)));
}
XCSoarInterface::SendMapSettings(true);
}
/**
* This function handles all "pan" input events
* @param misc A string describing the desired pan action.
* on Turn pan on
* off Turn pan off
* toogle Toogles pan mode
* supertoggle Toggles pan mode and fullscreen
* up Pan up
* down Pan down
* left Pan left
* right Pan right
* @todo feature: n,n Go that direction - +/-
* @todo feature: ??? Go to particular point
* @todo feature: ??? Go to waypoint (eg: next, named)
*/
void
InputEvents::eventPan(const TCHAR *misc)
{
if (StringIsEqual(misc, _T("toggle")) ||
/* deprecated: */ StringIsEqual(misc, _T("supertoggle")))
TogglePan();
else if (StringIsEqual(misc, _T("on")))
SetPan(true);
else if (StringIsEqual(misc, _T("off")))
SetPan(false);
else if (StringIsEqual(misc, _T("up")))
if (IsHP31X())
// Scroll wheel on the HP31x series should zoom in pan mode
sub_ScaleZoom(1);
else
sub_PanCursor(0, 1);
else if (StringIsEqual(misc, _T("down")))
if (IsHP31X())
// Scroll wheel on the HP31x series should zoom in pan mode
sub_ScaleZoom(-1);
else
sub_PanCursor(0, -1);
else if (StringIsEqual(misc, _T("left")))
sub_PanCursor(1, 0);
else if (StringIsEqual(misc, _T("right")))
sub_PanCursor(-1, 0);
XCSoarInterface::SendMapSettings(true);
}
void
InputEvents::SetPan(bool enable)
{
GlueMapWindow *map_window = CommonInterface::main_window.ActivateMap();
if (map_window == NULL)
return;
if (enable == map_window->IsPanning())
return;
map_window->SetPan(enable);
if (enable) {
setMode(MODE_PAN);
XCSoarInterface::main_window.SetFullScreen(true);
} else {
setMode(MODE_DEFAULT);
Pages::Update();
}
}
void
InputEvents::TogglePan()
{
const GlueMapWindow *map_window = CommonInterface::main_window.ActivateMap();
if (map_window == NULL)
return;
SetPan(!map_window->IsPanning());
}
void
InputEvents::LeavePan()
{
const GlueMapWindow *map_window =
CommonInterface::main_window.GetMapIfActive();
if (map_window == NULL)
return;
SetPan(false);
}
void
InputEvents::sub_PanCursor(int dx, int dy)
{
GlueMapWindow *map_window = CommonInterface::main_window.GetMapIfActive();
if (map_window == NULL || !map_window->IsPanning())
return;
const WindowProjection &projection = map_window->VisibleProjection();
RasterPoint pt = projection.GetScreenOrigin();
pt.x -= dx * projection.GetScreenWidth() / 4;
pt.y -= dy * projection.GetScreenHeight() / 4;
map_window->SetLocation(projection.ScreenToGeo(pt));
map_window->QuickRedraw();
}
// called from UI or input event handler (same thread)
void
InputEvents::sub_AutoZoom(int vswitch)
{
MapSettings &settings_map = CommonInterface::SetMapSettings();
if (vswitch == -1)
settings_map.auto_zoom_enabled = !settings_map.auto_zoom_enabled;
else
settings_map.auto_zoom_enabled = (vswitch != 0); // 0 off, 1 on
Profile::Set(szProfileAutoZoom, settings_map.auto_zoom_enabled);
if (settings_map.auto_zoom_enabled &&
CommonInterface::main_window.GetMap() != NULL)
CommonInterface::main_window.GetMap()->SetPan(false);
ActionInterface::SendMapSettings(true);
}
void
InputEvents::sub_SetZoom(fixed value)
{
MapSettings &settings_map = CommonInterface::SetMapSettings();
GlueMapWindow *map_window = CommonInterface::main_window.ActivateMap();
if (map_window == NULL)
return;
DisplayMode displayMode = XCSoarInterface::main_window.GetDisplayMode();
if (settings_map.auto_zoom_enabled &&
!(displayMode == DM_CIRCLING && settings_map.circle_zoom_enabled) &&
!CommonInterface::IsPanning()) {
settings_map.auto_zoom_enabled = false; // disable autozoom if user manually changes zoom
Profile::Set(szProfileAutoZoom, false);
Message::AddMessage(_("Auto. zoom off"));
}
fixed vmin = CommonInterface::GetComputerSettings().polar.glide_polar_task.GetVMin();
fixed scale_2min_distance = vmin * fixed_int_constant(12);
const fixed scale_500m = fixed_int_constant(50);
const fixed scale_1600km = fixed_int_constant(1600*100);
fixed minreasonable = (displayMode == DM_CIRCLING) ?
scale_500m : max(scale_500m, scale_2min_distance);
value = max(minreasonable, min(scale_1600km, value));
map_window->SetMapScale(value);
map_window->QuickRedraw();
}
void
InputEvents::sub_ScaleZoom(int vswitch)
{
const GlueMapWindow *map_window = CommonInterface::main_window.ActivateMap();
if (map_window == NULL)
return;
const MapWindowProjection &projection =
map_window->VisibleProjection();
fixed value = projection.GetMapScale();
if (projection.HaveScaleList()) {
value = projection.StepMapScale(value, -vswitch);
} else {
if (vswitch == 1)
// zoom in a little
value /= fixed_sqrt_two;
else if (vswitch == -1)
// zoom out a little
value *= fixed_sqrt_two;
else if (vswitch == 2)
// zoom in a lot
value /= 2;
else if (vswitch == -2)
// zoom out a lot
value *= 2;
}
sub_SetZoom(value);
}
void
InputEvents::eventMap(const TCHAR *misc)
{
if (StringIsEqual(misc, _T("show")))
CommonInterface::main_window.ActivateMap();
}
| aharrison24/XCSoar | src/Input/InputEventsMap.cpp | C++ | gpl-2.0 | 8,748 |
/**
* Copyright (c) 2008- Samuli Jrvel
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html. If redistributing this code,
* this entire header must remain intact.
*/
mollify.registerPlugin(new ArchiverPlugin());
function ArchiverPlugin() {
var that = this;
this.getPluginInfo = function() { return { id: "plugin_archiver" }; }
this.initialize = function(env) {
that.env = env;
that.env.addItemContextProvider(that.getItemContext);
$.getScript(that.env.pluginUrl("Archiver") + "client/texts_" + that.env.texts().locale + ".js");
}
this.getItemContext = function(item, details) {
if (!details["plugin_archiver"] || !details["plugin_archiver"]["action_extract"]) return null;
var extractServiceUrl = details["plugin_archiver"]["action_extract"];
return {
actions : {
secondary: [
{ title: "-" },
{
title: that.env.texts().get("plugin_archiver_extractAction"),
callback: function(item) { that.onExtract(extractServiceUrl, false); }
}
]
}
}
}
this.onExtract = function(url, allowOverwrite) {
var wd = that.env.dialog().showWait(that.env.texts().get("pleaseWait"));
var params = { overwrite: allowOverwrite };
that.env.service().post(url, params,
function(result) {
wd.close();
that.env.fileview().refresh();
},
function(code, error) {
wd.close();
if (code == 205) {
that.env.dialog().showConfirmation({
title: that.env.texts().get("plugin_archiver_extractFolderAlreadyExistsTitle"),
message: that.env.texts().get("plugin_archiver_extractFolderAlreadyExistsMessage"),
on_confirm: function() { that.onExtract(url, true); }
});
return;
}
alert("Extract error: "+code+"/"+error);
}
);
}
} | janosgyerik/TheToolbox | mollify/backend/plugin/Archiver/client/plugin.js | JavaScript | gpl-2.0 | 1,939 |
/*
* Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package java.awt;
/**
* The <code>DisplayMode</code> class encapsulates the bit depth, height,
* width, and refresh rate of a <code>GraphicsDevice</code>. The ability to
* change graphics device's display mode is platform- and
* configuration-dependent and may not always be available
* (see {@link GraphicsDevice#isDisplayChangeSupported}).
* <p>
* For more information on full-screen exclusive mode API, see the
* <a href="http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html">
* Full-Screen Exclusive Mode API Tutorial</a>.
*
* @see GraphicsDevice
* @see GraphicsDevice#isDisplayChangeSupported
* @see GraphicsDevice#getDisplayModes
* @see GraphicsDevice#setDisplayMode
* @author Michael Martak
* @since 1.4
*/
public final class DisplayMode {
private Dimension size;
private int bitDepth;
private int refreshRate;
/**
* Create a new display mode object with the supplied parameters.
* @param width the width of the display, in pixels
* @param height the height of the display, in pixels
* @param bitDepth the bit depth of the display, in bits per
* pixel. This can be <code>BIT_DEPTH_MULTI</code> if multiple
* bit depths are available.
* @param refreshRate the refresh rate of the display, in hertz.
* This can be <code>REFRESH_RATE_UNKNOWN</code> if the
* information is not available.
* @see #BIT_DEPTH_MULTI
* @see #REFRESH_RATE_UNKNOWN
*/
public DisplayMode(int width, int height, int bitDepth, int refreshRate) {
this.size = new Dimension(width, height);
this.bitDepth = bitDepth;
this.refreshRate = refreshRate;
}
/**
* Returns the height of the display, in pixels.
* @return the height of the display, in pixels
*/
public int getHeight() {
return size.height;
}
/**
* Returns the width of the display, in pixels.
* @return the width of the display, in pixels
*/
public int getWidth() {
return size.width;
}
/**
* Value of the bit depth if multiple bit depths are supported in this
* display mode.
* @see #getBitDepth
*/
public final static int BIT_DEPTH_MULTI = -1;
/**
* Returns the bit depth of the display, in bits per pixel. This may be
* <code>BIT_DEPTH_MULTI</code> if multiple bit depths are supported in
* this display mode.
*
* @return the bit depth of the display, in bits per pixel.
* @see #BIT_DEPTH_MULTI
*/
public int getBitDepth() {
return bitDepth;
}
/**
* Value of the refresh rate if not known.
* @see #getRefreshRate
*/
public final static int REFRESH_RATE_UNKNOWN = 0;
/**
* Returns the refresh rate of the display, in hertz. This may be
* <code>REFRESH_RATE_UNKNOWN</code> if the information is not available.
*
* @return the refresh rate of the display, in hertz.
* @see #REFRESH_RATE_UNKNOWN
*/
public int getRefreshRate() {
return refreshRate;
}
/**
* Returns whether the two display modes are equal.
* @return whether the two display modes are equal
*/
public boolean equals(DisplayMode dm) {
if (dm == null) {
return false;
}
return (getHeight() == dm.getHeight()
&& getWidth() == dm.getWidth()
&& getBitDepth() == dm.getBitDepth()
&& getRefreshRate() == dm.getRefreshRate());
}
/**
* {@inheritDoc}
*/
public boolean equals(Object dm) {
if (dm instanceof DisplayMode) {
return equals((DisplayMode)dm);
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return getWidth() + getHeight() + getBitDepth() * 7
+ getRefreshRate() * 13;
}
}
| TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/java/awt/DisplayMode.java | Java | gpl-2.0 | 5,123 |
#include "ViewDelegatesFactory.h"
#include "CategoryViewDelegate.h"
#include "ClientViewDelegate.h"
ViewDelegatesFactory* ViewDelegatesFactory:: ViewDelegatesFactory_ = nullptr;
ViewDelegatesFactory::ViewDelegatesFactory( QObject * parent)
{
oAvail["Category"] = new CategoryViewDelegate(parent);
oAvail["Client"] = new ClientViewDelegate(parent);
}
ViewDelegates* ViewDelegatesFactory::Get(QString ViewName, QObject * parent)
{
if (ViewDelegatesFactory_ == nullptr)
ViewDelegatesFactory_ = new ViewDelegatesFactory(parent);
return ViewDelegatesFactory_->oAvail[ViewName];
}
ViewDelegatesFactory:: ~ViewDelegatesFactory()
{
for(auto it = oAvail.begin(); it != oAvail.end(); ++it)
delete it.value();
delete ViewDelegatesFactory_;
}
| mmbeyrem/GStock | ViewDelegates/ViewDelegatesFactory.cpp | C++ | gpl-2.0 | 776 |
# -*- coding: utf-8 -*-
"""
Script: GotoLineCol.py
Utility: 1. Moves the cursor position to the specified line and column for a file in Notepad++.
Especially useful for inspecting data files in fixed-width record formats.
2. Also, displays the character code (SBCS & LTR) in decimal and hex at the specified position.
Requires: Python Script plugin in Notepad++
Customizable parameters for the goToLineCol function call in main():
bRepeatPrompt: Whether to repeat prompting when the specified number value is out of range
iEdgeBuffer: Ensures that the caret will be that many characters inside the left and right edges of the editor viewing area, when possible
iCaretHiliteDuration: Caret will be in Block mode for specified seconds
bCallTipAutoHide: Whether to hide the call tip automatically in sync when caret highlighting is turned off
bBraceHilite: Whether to use brace highlighting style for the character at the specified position. Automatically turns off when current line changes.
Known Issues: 1. Character code display in the call tip is functional with SBCS (Single-Byte Character Sets) and LTR (left-to-right) direction.
With MBCS (Bulti-Bytes Character Sets) or RTL (right-to-left) direction, results will not be reliable.
2. If iCaretHiliteDuration is set to a high value (>3 seconds), and the user tries to rerun the script
while the previous execution is still running, the Python Script plugin will display an error message:
"Another script is still running..." So set this parameter to 3 seconds or lower.
Author: Shridhar Kumar
Date: 2019-08-15
"""
def main():
goToLineCol(bRepeatPrompt = True,
iEdgeBuffer = 5,
iCaretHiliteDuration = 5,
bCallTipAutoHide = False,
bBraceHilite = True)
def getDisplayLineCol():
iCurrLine = editor.lineFromPosition(editor.getCurrentPos())
iCurrCol = editor.getCurrentPos() - editor.positionFromLine(iCurrLine)
return str(iCurrLine + 1), str(iCurrCol + 1)
def promptValue(sInfoText, sTitleText, sDefaultVal, iMinVal, iMaxVal, sRangeError, bRepeatPrompt):
while True:
sNewVal = notepad.prompt(sInfoText, sTitleText, sDefaultVal)
if sNewVal == None:
return None
try:
iNewVal = int(sNewVal)
if iMinVal <= iNewVal <= iMaxVal:
return iNewVal
else:
raise
except:
notepad.messageBox(sRangeError + '.\n\nYou specified: ' + sNewVal +
'\n\nPlease specify a number between ' + str(iMinVal) + ' and ' + str(iMaxVal) + '.',
'Specified value is out of range')
if not bRepeatPrompt:
return None
def goToLineCol(bRepeatPrompt, iEdgeBuffer, iCaretHiliteDuration, bCallTipAutoHide, bBraceHilite):
import time
sCurrLine, sCurrCol = getDisplayLineCol()
iMaxLines = editor.getLineCount()
iNewLine = promptValue(sInfoText = 'Line number (between 1 and ' + str(iMaxLines) + '):',
sTitleText = 'Specify line number',
sDefaultVal = sCurrLine,
iMinVal = 1,
iMaxVal = iMaxLines,
sRangeError = 'File line count is only ' + str(iMaxLines),
bRepeatPrompt = bRepeatPrompt)
if iNewLine == None:
return
# Get the character count plus 1 for the specified line
# Plus 1 is to account for the caret position at the end of the line, past all characters but before EOL/EOF
# Since lineLength already includes EOL, we just need to subtract 1 only when EOL is 2 chars. i.e., CRLF
# For the last line in file, there is no 2-character CRLF EOL; only a single character EOF.
iMaxCols = max(1, editor.lineLength(iNewLine - 1))
if (editor.getEOLMode() == ENDOFLINE.CRLF) and (iNewLine < iMaxLines):
iMaxCols -= 1
iNewCol = promptValue(sInfoText = 'Column position (between 1 and ' + str(iMaxCols) + ') for line ' + str(iNewLine) + ':',
sTitleText = 'Specify column position',
sDefaultVal = sCurrCol,
iMinVal = 1,
iMaxVal = iMaxCols,
sRangeError = 'There are only ' + str(iMaxCols) + ' characters in line ' + str(iNewLine),
bRepeatPrompt = bRepeatPrompt)
# Navigate to the specified position in the document
iLineStartPos = editor.positionFromLine(iNewLine - 1)
iNewPos = iLineStartPos + iNewCol - 1
editor.ensureVisible(iNewLine - 1)
editor.gotoPos( min(iLineStartPos + iMaxCols, iNewPos + iEdgeBuffer) ) # Ensure that caret is 'iEdgeBuffer' characters inside right edge when possible
editor.gotoPos( max(iLineStartPos, iNewPos - iEdgeBuffer) ) # Ensure that caret is 'iEdgeBuffer' characters inside left edge when possible
editor.gotoPos(iNewPos) # Finally, move caret to the specified position
# Obtain current caret style to restore it later on
currCS = editor.getCaretStyle()
# Set the caret to block style to highlight the new position
editor.setCaretStyle(CARETSTYLE.BLOCK)
# Display a call tip with the new line and column numbers with verification
# Also display the character code in decimal and hex
sCurrLine, sCurrCol = getDisplayLineCol()
editor.callTipShow(iNewPos, ' Line: ' + sCurrLine +
'\n Column: ' + sCurrCol +
'\nChar Code: ' + str(editor.getCharAt(iNewPos)) + ' [' + hex(editor.getCharAt(iNewPos)) + ']')
if iCaretHiliteDuration > 0:
time.sleep(iCaretHiliteDuration)
# Reset the caret style
editor.setCaretStyle(currCS)
if bCallTipAutoHide:
editor.callTipCancel()
if bBraceHilite:
editor.braceHighlight(iNewPos, iNewPos)
main()
| bruderstein/PythonScript | scripts/Samples/GotoLineCol.py | Python | gpl-2.0 | 6,088 |
/*
* JSExceptionArgNoBool.cpp
*
* Created on: 15/gen/2015
* Author: Paolo Achdjian
*/
#include <sstream>
#include "JSExceptionArgNoBool.h"
namespace zigbee {
JSExceptionArgNoBool::JSExceptionArgNoBool() {
std::stringstream stream;
stream << "Invalid parameter: expected an argument of type boolean";
message = stream.str();
}
JSExceptionArgNoBool::~JSExceptionArgNoBool() {
}
} /* namespace zigbee */
| paoloach/zdomus | domusEngine/src/JavaScript/Exceptions/JSExceptionArgNoBool.cpp | C++ | gpl-2.0 | 422 |
'''
Created on 22/02/2015
@author: Ismail Faizi
'''
import models
class ModelFactory(object):
"""
Factory for creating entities of models
"""
@classmethod
def create_user(cls, name, email, training_journal):
"""
Factory method for creating User entity.
NOTE: you must explicitly call the put() method
"""
user = models.User(parent=models.USER_KEY)
user.name = name
user.email = email
user.training_journal = training_journal.key
return user
@classmethod
def create_training_journal(cls):
"""
Factory method for creating TrainingJournal entity.
NOTE: you must explicitly call the put() method
"""
return models.TrainingJournal(parent=models.TRAINING_JOURNAL_KEY)
@classmethod
def create_workout_session(cls, started_at, ended_at, training_journal):
"""
Factory method for creating WorkoutSession entity.
NOTE: you must explicitly call the put() method
"""
workout_session = models.WorkoutSession(parent=models.WORKOUT_SESSION_KEY)
workout_session.started_at = started_at
workout_session.ended_at = ended_at
workout_session.training_journal = training_journal.key
return workout_session
@classmethod
def create_workout_set(cls, repetitions, weight, workout_session, workout):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout_set = models.WorkoutSet(parent=models.WORKOUT_SET_KEY)
workout_set.repetitions = repetitions
workout_set.weight = weight
workout_set.workout_session = workout_session.key
workout_set.workout = workout.key
return workout_set
@classmethod
def create_workout(cls, muscle_group, names=[], description='', images=[]):
"""
Factory method for creating WorkoutSet entity.
NOTE: you must explicitly call the put() method
"""
workout = models.Workout(parent=models.WORKOUT_KEY)
workout.names = names
workout.muscle_group = muscle_group
workout.description = description
workout.images = images
return workout
| kanafghan/fiziq-backend | src/models/factories.py | Python | gpl-2.0 | 2,302 |
<?php
class AQ_Cats_Masonry_Block extends AQ_Block {
function __construct() {
$block_options = array(
'name' => __('Cats - Masonry', 'aqpb-l10n'),
'size' => 'span12',
);
parent::__construct('aq_cats_masonry_block', $block_options);
}
function update($new_instance, $old_instance) {
return stripslashes_deep($new_instance);
}
function form($instance) {
global $cats_arr, $orderby_arr, $order_arr;
$defaults = array(
'title' => 'Masonry',
'cats' => 0,
'num_excerpt' => 25,
'post_count' => 3,
'width' => 300,
'custom_title' => false
);
$instance = wp_parse_args($instance, $defaults);
extract($instance);
?>
<div class="controls half">
<h4><?php _e('Title (optional)','presslayer');?></h4>
<?php echo aq_field_input('title', $block_id, $title, $size = 'full') ?>
</div>
<div class="controls half last">
<h4><?php _e('Show Custom Title','presslayer');?></h4>
<label><?php echo aq_field_checkbox('custom_title', $block_id, $custom_title); ?> <?php _e('Show custom title for blog.','presslayer');?></label>
</div>
<div class="controls half">
<h4><?php _e('Categories','presslayer');?></h4>
<?php echo field_multiselect('cats', $block_id, $cats_arr, $cats) ?>
<p><?php _e('Leave blank to show all categories.','presslayer');?></p>
</div>
<div class="controls half last">
<h4><?php _e('Column width','presslayer');?></h4>
<?php echo field_select('width', $block_id, array('200' => 'Small','300'=>'Medium','450'=>'Large'), $width) ?>
</div>
<div class="controls half">
<h4>Length of excerpt</h4>
<?php echo aq_field_input('num_excerpt', $block_id, $num_excerpt); ?>
</div>
<div class="controls half last">
<h4><?php _e('Posts count','presslayer');?></h4>
<?php echo aq_field_input('post_count', $block_id, $post_count); ?>
<p><?php _e('Set number of posts for each category.','presslayer');?></p>
</div>
<?php
}
function block($instance) {
extract($instance);
if(!isset($cats)) $cats = 0;
if( $cats == 0 ) {
$categories_obj = get_categories('orderby=id&order=asc');
foreach ($categories_obj as $cat) {
$list_cats[] = $cat->cat_ID;
}
} else {
$list_cats = $cats;
}
if($custom_title == true and $title!='') {?>
<div class="prl-article w-box blog-heading">
<div class="w-box-inner">
<h4 class="prl-category-title"><?php echo esc_html($title);?></h4>
</div>
</div>
<?php }
if($list_cats!='' && is_array($list_cats)):?>
<div class="tu-container">
<?php
foreach($list_cats as $cat_ID){
?>
<div class="post-entry post-item post-cats">
<div class="post-cats-head">
<h3 class="widget-title"><span><a href="<?php echo get_category_link($cat_ID);?>" ><?php echo esc_html(get_cat_name($cat_ID));?></a></span></h3>
</div>
<?php
$args = array( 'posts_per_page' => $post_count );
$args['cat'] = $cat_ID;
// Formats
$tax_query=array();
$tax_query = array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array('post-format-aside','post-format-link','post-format-quote'),
'operator' => 'NOT IN'
)
);
$args['tax_query'] = $tax_query;
$new_query = new WP_Query($args);
$count = 0;
?>
<?php while ( $new_query->have_posts() ) : $new_query->the_post();?>
<?php
if($count < 1){
global $more; $more = 0;
$format = get_post_format();
if($format!='') include(locate_template('content-'.$format.'.php'));
else include(locate_template('content.php'));
if( $format == '' || $format == 'video' || $format == 'audio' || $format == 'gallery' ) get_template_part( 'content', 'bottom' );
} else {?>
<div class="w-box small-post cleafix">
<span class="small-post-thumb"><a href="<?php the_permalink();?>" title="<?php the_title_attribute();?>" rel="bookmark" itemprop="url" class="small-thumb"><?php echo the_post_thumbnail(); ?></a></span>
<h5 itemprop="headline"><a href="<?php the_permalink();?>" title="<?php the_title_attribute();?>" rel="bookmark" itemprop="url"><?php the_title(); ?></a></h5>
<?php tu_post_meta('author=0&cat=0&class=no-underline');?>
<div class="clear"></div>
</div>
<?php
}
$count++;
?>
<?php endwhile; wp_reset_postdata(); ?>
</div><!-- .post-item -->
<?php }?>
</div><!-- .tu-container -->
<?php endif;?>
<script type="text/javascript">
jQuery(function($) {
var $container = $('.tu-container');
var gutter = 20;
var min_width = <?php echo $width;?>;
$container.imagesLoaded( function(){
$container.masonry({
itemSelector : '.post-item',
gutterWidth: gutter,
isAnimated: true,
columnWidth: function( containerWidth ) {
var box_width = (((containerWidth - 2*gutter)/3) | 0) ;
if (box_width < min_width) {box_width = (((containerWidth - gutter)/2) | 0);}
if (box_width < min_width) {box_width = containerWidth;}
$('.post-item').width(box_width);
return box_width;
}
});
});
});
</script>
<?php
}
}
| Gtskk/menpai | wp-content/themes/liquid/page-builder/blocks/aq-cats-masonry-block.php | PHP | gpl-2.0 | 5,650 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MySQLCLI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MySQLCLI")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("7edbfc12-f00f-48b0-8037-8aa390850327")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Xackery/CsharpMySQL | MySQLCLI/MySQLCLI/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,392 |
//////////////////////////////////////////////////////////////////////////////
// Copyright 2004-2014, SenseGraphics AB
//
// This file is part of H3D API.
//
// H3D API 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.
//
// H3D API 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 H3D API; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// A commercial license is also available. Please contact us at
// www.sensegraphics.com for more information.
//
//
/// \file FBODebugger.cpp
/// \brief CPP file for FBODebugger, X3D scene-graph node
///
//
//
//////////////////////////////////////////////////////////////////////////////
#include <H3D/FBODebugger.h>
#include <H3D/FrameBufferTextureGenerator.h>
#include <H3D/Appearance.h>
using namespace H3D;
// Add this node to the H3DNodeDatabase system.
H3DNodeDatabase FBODebugger::database( "FBODebugger",
&(newInstance<FBODebugger>),
typeid( FBODebugger ),
&X3DChildNode::database );
namespace FBODebuggerInternals {
FIELDDB_ELEMENT( FBODebugger, fbo, INPUT_OUTPUT );
FIELDDB_ELEMENT( FBODebugger, buffer, INPUT_OUTPUT );
const string x3d_fbo =
"<Group> \n"
" <Shape> \n"
" <Appearance DEF=\"APP\" > \n"
" <Material/> \n"
" <RenderProperties depthTestEnabled=\"FALSE\" blendEnabled=\"FALSE\" /> \n"
" </Appearance> \n"
" <FullscreenRectangle zValue=\"0.99\"/> \n"
" </Shape> \n"
"</Group>\n";
}
FBODebugger::FBODebugger( Inst< SFNode> _metadata,
Inst< SFString > _fbo,
Inst< SFString > _buffer ) :
X3DChildNode( _metadata ),
fbo( _fbo ),
buffer( _buffer ),
render_target_texture( new RenderTargetTexture ) {
type_name = "FBODebugger";
database.initFields( this );
fbo->addValidValue( "NONE" );
fbo->setValue( "NONE" );
buffer->addValidValue( "DEPTH" );
buffer->addValidValue( "COLOR0" );
buffer->addValidValue( "COLOR1" );
buffer->setValue( "COLOR0" );
current_fbo = "NONE";
current_buffer = "COLOR0";
texture_scene.reset( X3D::createX3DFromString( FBODebuggerInternals::x3d_fbo, &texture_scene_dn ) );
}
void FBODebugger::traverseSG( TraverseInfo &ti ) {
// add the valid values for the fbo field
if( FrameBufferTextureGenerator::fbo_nodes.size() != fbo->getValidValues().size() ) {
fbo->clearValidValues();
fbo->addValidValue( "NONE" );
for( set< FrameBufferTextureGenerator * >::const_iterator i = FrameBufferTextureGenerator::fbo_nodes.begin();
i != FrameBufferTextureGenerator::fbo_nodes.end(); i++ ) {
FrameBufferTextureGenerator *fbo_node = *i;
fbo->addValidValue( fbo_node->getName() );
}
}
// find the FrameBufferTextureGenerator that matches the name in the fbo field
FrameBufferTextureGenerator *selected_fbo_node = NULL;
for( set< FrameBufferTextureGenerator * >::const_iterator i = FrameBufferTextureGenerator::fbo_nodes.begin();
i != FrameBufferTextureGenerator::fbo_nodes.end(); i++ ) {
FrameBufferTextureGenerator *fbo_node = *i;
if( fbo_node->getName() == fbo->getValue() ) {
selected_fbo_node = *i;
break;
}
}
if( selected_fbo_node ) {
// choose the texture to be shown based on the buffer field.
string selected_fbo_name = selected_fbo_node->getName();
if( selected_fbo_name != current_fbo ||
buffer->getValue() != current_buffer ) {
Appearance *app;
texture_scene_dn.getNode( "APP", app );
if( app ) {
const string &selected_buffer = buffer->getValue();
if( selected_buffer == "DEPTH" ) {
app->texture->setValue( selected_fbo_node->depthTexture->getValue() );
if( !selected_fbo_node->generateDepthTexture->getValue() ) {
Console(4) << "Warning (FBODebugger): Cannot show DEPTH texture as no depth texture is generated by \"" << selected_fbo_name << "\" fbo" << endl;
}
} else if( selected_buffer == "COLOR0" ) {
if( selected_fbo_node->colorTextures->size() > 0 ) {
app->texture->setValue( render_target_texture );
render_target_texture->generator->setValue( selected_fbo_node );
render_target_texture->index->setValue( 0 );
} else {
Console(4) << "Warning (FBODebugger): Cannot show COLOR0 texture as no color textures is generated by \"" << selected_fbo_name << "\" fbo" << endl;
app->texture->setValue( NULL );
}
} else if( selected_buffer == "COLOR1" ) {
if( selected_fbo_node->colorTextures->size() > 1 ) {
app->texture->setValue( render_target_texture.get() );
render_target_texture->generator->setValue( selected_fbo_node );
render_target_texture->index->setValue( 1 );
} else {
Console(4) << "Warning (FBODebugger): Cannot show COLOR1 texture as no such color texture is generated by \"" << selected_fbo_name << "\" fbo" << endl;
app->texture->setValue( NULL );
}
}
}
}
}
// save the values of the currently selected fbo and buffer
current_fbo = fbo->getValue();
current_buffer = buffer->getValue();
}
void FBODebugger::render() {
if( fbo->getValue() != "NONE" ) {
texture_scene->render();
}
}
| JakeFountain/H3DAPIwithOculusSupport | src/FBODebugger.cpp | C++ | gpl-2.0 | 5,754 |
class Win32API
@@RGSSWINDOW=nil
@@GetCurrentThreadId=Win32API.new('kernel32','GetCurrentThreadId', '%w()','l')
@@GetWindowThreadProcessId=Win32API.new('user32','GetWindowThreadProcessId', '%w(l p)','l')
@@FindWindowEx=Win32API.new('user32','FindWindowEx', '%w(l l p p)','l')
def Win32API.SetWindowText(text)
hWnd = pbFindRgssWindow
swp = Win32API.new('user32', 'SetWindowTextA', %(l, p), 'i')
swp.call(hWnd, text.to_s)
end
# Added by Peter O. as a more reliable way to get the RGSS window
def Win32API.pbFindRgssWindow
return @@RGSSWINDOW if @@RGSSWINDOW
processid=[0].pack('l')
threadid=@@GetCurrentThreadId.call
nextwindow=0
begin
nextwindow=@@FindWindowEx.call(0,nextwindow,"RGSS Player",0)
if nextwindow!=0
wndthreadid=@@GetWindowThreadProcessId.call(nextwindow,processid)
if wndthreadid==threadid
@@RGSSWINDOW=nextwindow
return @@RGSSWINDOW
end
end
end until nextwindow==0
raise "Can't find RGSS player window"
return 0
end
def Win32API.SetWindowPos(w, h)
hWnd = pbFindRgssWindow
windowrect=Win32API.GetWindowRect
clientsize=Win32API.client_size
xExtra=windowrect.width-clientsize[0]
yExtra=windowrect.height-clientsize[1]
swp = Win32API.new('user32', 'SetWindowPos', %(l, l, i, i, i, i, i), 'i')
win = swp.call(hWnd, 0, windowrect.x, windowrect.y,w+xExtra,h+yExtra, 0)
return win
end
def Win32API.client_size
hWnd = pbFindRgssWindow
rect = [0, 0, 0, 0].pack('l4')
Win32API.new('user32', 'GetClientRect', %w(l p), 'i').call(hWnd, rect)
width, height = rect.unpack('l4')[2..3]
return width, height
end
def Win32API.GetWindowRect
hWnd = pbFindRgssWindow
rect = [0, 0, 0, 0].pack('l4')
Win32API.new('user32', 'GetWindowRect', %w(l p), 'i').call(hWnd, rect)
x,y,width, height = rect.unpack('l4')
return Rect.new(x,y,width-x,height-y)
end
def Win32API.focusWindow
window = Win32API.new('user32', 'ShowWindow', 'LL' ,'L')
hWnd = pbFindRgssWindow
window.call(hWnd, 9)
end
def Win32API.fillScreen
setWindowLong = Win32API.new('user32', 'SetWindowLong', 'LLL', 'L')
setWindowPos = Win32API.new('user32', 'SetWindowPos', 'LLIIIII', 'I')
metrics = Win32API.new('user32', 'GetSystemMetrics', 'I', 'I')
hWnd = pbFindRgssWindow
width = metrics.call(0)
height = metrics.call(1)
setWindowLong.call(hWnd, -16, 0x00000000)
setWindowPos.call(hWnd, 0, 0, 0, width, height, 0)
Win32API.focusWindow
return [width,height]
end
def Win32API.restoreScreen
setWindowLong = Win32API.new('user32', 'SetWindowLong', 'LLL', 'L')
setWindowPos = Win32API.new('user32', 'SetWindowPos', 'LLIIIII', 'I')
metrics = Win32API.new('user32', 'GetSystemMetrics', 'I', 'I')
hWnd = pbFindRgssWindow
width = DEFAULTSCREENWIDTH*$ResizeFactor
height = DEFAULTSCREENHEIGHT*$ResizeFactor
if $PokemonSystem && $PokemonSystem.border==1
width += BORDERWIDTH*2*$ResizeFactor
height += BORDERHEIGHT*2*$ResizeFactor
end
x = [(metrics.call(0)-width)/2,0].max
y = [(metrics.call(1)-height)/2,0].max
setWindowLong.call(hWnd, -16, 0x14CA0000)
setWindowPos.call(hWnd, 0, x, y, width+6, height+29, 0)
Win32API.focusWindow
return [width,height]
end
end | chacu34/PokemonKawaii | Script Database/[5]Win32API.rb | Ruby | gpl-2.0 | 3,353 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use PHPExiftool\Driver\AbstractTag;
class CenterOfCircExposControlSensRegion extends AbstractTag
{
protected $Id = '0018,9440';
protected $Name = 'CenterOfCircExposControlSensRegion';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Center Of Circ Expos Control Sens Region';
}
| Droces/casabio | vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/DICOM/CenterOfCircExposControlSensRegion.php | PHP | gpl-2.0 | 775 |
package com.toet.TinyVoxel.Renderer;
import com.toet.TinyVoxel.Config;
import com.toet.TinyVoxel.Renderer.Bundles.Grid;
import com.toet.TinyVoxel.Renderer.Bundles.TinyGrid;
import java.nio.FloatBuffer;
/**
* Created by Kajos on 20-1-14.
*/
public class BlockBuilder {
public static float low = .0001f;
public static final boolean[] CUBE = {
// x-
false,false,false,
false,false, true,
false, true, true,
false,false,false,
false, true, true,
false, true,false,
// x+
true, true, true,
true,false,false,
true, true,false,
true,false,false,
true, true, true,
true,false, true,
// y-
true,false, true,
false,false, true,
false,false,false,
true,false, true,
false,false,false,
true,false,false,
// y+
true, true, true,
true, true,false,
false, true,false,
true, true, true,
false, true,false,
false, true, true,
// z-
true, true,false,
false,false,false,
false, true,false,
true, true,false,
true,false,false,
false,false,false,
// z+
true, true, true,
false, true, true,
true, false, true,
false, true, true,
false, false, true,
true,false, true,
};
public static TinyGrid getNeighbor(Grid grid, int x, int y, int z, int dx, int dy, int dz) {
if (dx < 0) {
TinyGrid cont = null;
if (x == 0) {
Grid nGrid = grid.owner.getGridSafe(grid.x - 1, grid.y, grid.z);
if (nGrid != null) {
cont = nGrid.getTinyGrid(Config.GRID_SIZE - 1, y, z);
}
} else {
cont = grid.getTinyGrid(x - 1, y, z);
}
return cont;
} else if (dy < 0) {
TinyGrid cont = null;
if (y == 0) {
Grid nGrid = grid.owner.getGridSafe(grid.x, grid.y - 1, grid.z);
if (nGrid != null) {
cont = nGrid.getTinyGrid(x, Config.GRID_SIZE - 1, z);
}
} else {
cont = grid.getTinyGrid(x, y - 1, z);
}
return cont;
} else if (dz < 0) {
TinyGrid cont = null;
if (z == 0) {
Grid nGrid = grid.owner.getGridSafe(grid.x, grid.y, grid.z - 1);
if (nGrid != null) {
cont = nGrid.getTinyGrid(x, y, Config.GRID_SIZE - 1);
}
} else {
cont = grid.getTinyGrid(x, y, z - 1);
}
return cont;
} else if (dx > 0) {
TinyGrid cont = null;
if (x >= Config.GRID_SIZE - 1) {
Grid nGrid = grid.owner.getGridSafe(grid.x + 1, grid.y, grid.z);
if (nGrid != null) {
cont = nGrid.getTinyGrid(0, y, z);
}
} else {
cont = grid.getTinyGrid(x + 1, y, z);
}
return cont;
} else if (dy > 0) {
TinyGrid cont = null;
if (y >= Config.GRID_SIZE - 1) {
Grid nGrid = grid.owner.getGridSafe(grid.x, grid.y + 1, grid.z);
if (nGrid != null) {
cont = nGrid.getTinyGrid(x, 0, z);
}
} else {
cont = grid.getTinyGrid(x, y + 1, z);
}
return cont;
} else if (dz > 0) {
TinyGrid cont = null;
if (z >= Config.GRID_SIZE - 1) {
Grid nGrid = grid.owner.getGridSafe(grid.x, grid.y, grid.z + 1);
if (nGrid != null) {
cont = nGrid.getTinyGrid(x, y, 0);
}
} else {
cont = grid.getTinyGrid(x, y, z + 1);
}
return cont;
}
return null;
}
public static void fillInPalette(FloatBuffer vertices, int start, int end, int palette) {
for (int i = start + 4; i < end; i+=5) {
vertices.put(i, palette);
}
}
static boolean[] skipArray = new boolean[6];
static int skipCount;
public static boolean generateBox(FloatBuffer vertices, int x, int y, int z, Grid grid) {
TinyGrid cont = grid.getTinyGrid(x, y, z);
if (cont == null)
return false;
TinyGrid gCont;
for(int i = 0; i < skipArray.length; i++) {
skipArray[i] = false;
}
skipCount = 0;
if (cont.minX == 0) {
gCont = getNeighbor(grid, x, y, z, -1, 0, 0);
if (gCont != null) {
if (gCont.fullSides[1]) {
skipArray[0] = true;
skipCount++;
}
}
}
if (cont.maxX == Config.TINY_GRID_SIZE) {
gCont = getNeighbor(grid, x, y, z, +1, 0, 0);
if (gCont != null) {
if (gCont.fullSides[0]) {
skipArray[1] = true;
skipCount++;
}
}
}
if (cont.minY == 0) {
gCont = getNeighbor(grid, x, y, z, 0, -1, 0);
if (gCont != null) {
if (gCont.fullSides[3]) {
skipArray[2] = true;
skipCount++;
}
}
}
if (cont.maxY == Config.TINY_GRID_SIZE) {
gCont = getNeighbor(grid, x, y, z, 0, +1, 0);
if (gCont != null) {
if (gCont.fullSides[2]) {
skipArray[3] = true;
skipCount++;
}
}
}
if (cont.minZ == 0) {
gCont = getNeighbor(grid, x, y, z, 0, 0, -1);
if (gCont != null) {
if (gCont.fullSides[5]) {
skipArray[4] = true;
skipCount++;
}
}
}
if (cont.maxZ == Config.TINY_GRID_SIZE) {
gCont = getNeighbor(grid, x, y, z, 0, 0, +1);
if (gCont != null) {
if (gCont.fullSides[4]) {
skipArray[5] = true;
skipCount++;
}
}
}
FloatBuffer write = vertices;
float divide = (float)(Config.TINY_GRID_SIZE);
float minXf = (float)cont.minX / divide;
float minYf = (float)cont.minY / divide;
float minZf = (float)cont.minZ / divide;
minXf += low;
minYf += low;
minZf += low;
float maxXf = (float)cont.maxX / divide;
float maxYf = (float)cont.maxY / divide;
float maxZf = (float)cont.maxZ / divide;
maxXf -= low;
maxYf -= low;
maxZf -= low;
minXf += x;
minYf += y;
minZf += z;
maxXf += x;
maxYf += y;
maxZf += z;
boolean hasWritten = false;
if (skipCount != 6) {
int side;
for (int i = 0; i < CUBE.length; i += 3) {
side = i / (3 * 6);
if (skipArray[side])
continue;
if (CUBE[i])
write.put(maxXf);
else
write.put(minXf);
if (CUBE[i + 1])
write.put(maxYf);
else
write.put(minYf);
if (CUBE[i + 2])
write.put(maxZf);
else
write.put(minZf);
if (side < 2) { // x
write.put(.5f);
} else if (side < 4) { // y
write.put(1f);
} else { // z
write.put(1.5f);
}
// palette is filled in later
write.put(0f);
hasWritten = true;
}
}
return hasWritten;
}
}
| neuroradiology/TinyVoxel | core/src/com/toet/TinyVoxel/Renderer/BlockBuilder.java | Java | gpl-2.0 | 8,245 |
package pl.foltak.mybudget.server.security;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
/**
* This filter adds CORS headers and make api accessible for javascript.
*/
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext requestContext,
final ContainerResponseContext cres) throws IOException {
cres.getHeaders().add("Access-Control-Allow-Origin", "*");
cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization, Authorization-User, Authorization-Password");
cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
cres.getHeaders().add("Access-Control-Max-Age", "1209600");
}
}
| mariuszfoltak/my-budget | server/src/main/java/pl/foltak/mybudget/server/security/CORSFilter.java | Java | gpl-2.0 | 1,050 |
package game.object.enemy;
import game.framework.math.Vector2d;
import game.framework.resources.Textures;
/**
* Created by Addy on 23.02.2015.
*/
public class EnemyHeavy extends Enemy {
public EnemyHeavy(Vector2d[] wayPoints) {
super(Textures.runnerTexture, 25, 1.0d, 8, wayPoints);
}
}
| JannesP/java_tower_defense | src/game/object/enemy/EnemyHeavy.java | Java | gpl-2.0 | 309 |
<?php
class JConfig {
public $offline = '0';
public $offline_message = 'Diese Website ist zurzeit im Wartungsmodus.<br />Bitte später wiederkommen.';
public $display_offline_message = '1';
public $offline_image = '';
public $sitename = 'Hallenturnier';
public $editor = 'tinymce';
public $captcha = '0';
public $list_limit = '20';
public $access = '1';
public $debug = '0';
public $debug_lang = '0';
public $dbtype = 'mysqli';
public $host = 'localhost';
public $user = 'root';
public $password = '';
public $db = 'hallenturnier';
public $dbprefix = 'i78q0_';
public $live_site = '';
public $secret = 'G67cpOyTPnArzg1i';
public $gzip = '0';
public $error_reporting = 'default';
public $helpurl = 'http://help.joomla.org/proxy/index.php?option=com_help&keyref=Help{major}{minor}:{keyref}';
public $ftp_host = '';
public $ftp_port = '';
public $ftp_user = '';
public $ftp_pass = '';
public $ftp_root = '';
public $ftp_enable = '';
public $offset = 'UTC';
public $mailonline = '1';
public $mailer = 'mail';
public $mailfrom = 'christian.lochmatter@gmail.com';
public $fromname = 'Hallenturnier';
public $sendmail = '/usr/sbin/sendmail';
public $smtpauth = '0';
public $smtpuser = '';
public $smtppass = '';
public $smtphost = 'localhost';
public $smtpsecure = 'none';
public $smtpport = '25';
public $caching = '0';
public $cache_handler = 'file';
public $cachetime = '15';
public $MetaDesc = '';
public $MetaKeys = '';
public $MetaTitle = '1';
public $MetaAuthor = '1';
public $MetaVersion = '0';
public $robots = '';
public $sef = '1';
public $sef_rewrite = '0';
public $sef_suffix = '0';
public $unicodeslugs = '0';
public $feed_limit = '10';
public $log_path = 'E:\\kjoff\\bin\\xampp-win32-1.8.1-VC9\\xampp\\htdocs\\joomla_hallenturnier/logs';
public $tmp_path = 'E:\\kjoff\\bin\\xampp-win32-1.8.1-VC9\\xampp\\htdocs\\joomla_hallenturnier/tmp';
public $lifetime = '15';
public $session_handler = 'database';
} | clo/joomla_hallenturnier | configuration.php | PHP | gpl-2.0 | 1,973 |
<?php include_once "common/header.php"; ?>
<div id="main">
<noscript>This site just doesn't work, period, without JavaScript</noscript>
<!-- IF LOGGED IN -->
<!-- Content here -->
<!-- IF LOGGED OUT -->
<!-- Alternate content here -->
</div>
<?php include_once "common/footer.php"; ?>
| Istorian/official | index.php | PHP | gpl-2.0 | 322 |
#include "daku.h"
namespace daku {
void bigBang()
{
av_register_all();
}
}
| dokidaku/libdaku | daku.cpp | C++ | gpl-2.0 | 82 |
/********************************************************************************
* Tangram Library - version 8.0 *
*********************************************************************************
* Copyright (C) 2002-2015 by Tangram Team. All Rights Reserved. *
*
* THIS SOURCE FILE IS THE PROPERTY OF TANGRAM TEAM AND IS NOT TO
* BE RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED
* WRITTEN CONSENT OF TANGRAM TEAM.
*
* THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS
* OUTLINED IN THE GPL LICENSE AGREEMENT.TANGRAM TEAM
* GRANTS TO YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE
* THIS SOFTWARE ON A SINGLE COMPUTER.
*
* CONTACT INFORMATION:
* mailto:sunhui@tangramfx.com
* http://www.tangramFX.com
*
*
********************************************************************************/
#include "stdafx.h"
#include "CommonIncludes.h"
#include "TangramToolWindow.h"
#include "TangramVSIApp.h"
const GUID& CTangramToolWnd::GetToolWindowGuid() const
{
return CLSID_guidPersistanceSlot;
}
void CTangramToolWnd::PostCreate()
{
CComVariant srpvt;
srpvt.vt = VT_I4;
srpvt.intVal = IDB_IMAGES;
// We don't want to make the window creation fail only becuase we can not set
// the icon, so we will not throw if SetProperty fails.
if (SUCCEEDED(GetIVsWindowFrame()->SetProperty(VSFPROPID_BitmapResource, srpvt)))
{
srpvt.intVal = 1;
GetIVsWindowFrame()->SetProperty(VSFPROPID_BitmapIndex, srpvt);
}
if (theApp.m_pTangramCore&&m_pPane)
{
HWND h = m_pPane->m_hWnd;
//Begin add By Tangram Team: Step 2
theApp.m_pTangramCore->put_ToolWndHandle((LONGLONG)(h));
theApp.m_hVSToolWnd = h;
theApp.m_pTangramCore->CreateTangram((LONGLONG)::GetParent(h), &m_pTangram);
if (m_pTangram)
{
CComBSTR strAppStartFilePath(L"res://StartupPage.dll/start.htm");
//CComBSTR strAppStartFilePath(L"http://tangramcloud.com/static/startup.html");
m_pTangram->put_URL(strAppStartFilePath);
}
}
//End add By Tangram Team!
}
| tangramfx/TANGRAM | TangramPackage/TangramToolWindow.cpp | C++ | gpl-2.0 | 2,052 |
<?php
// A simple use case of RecursiveArrayIterator::offsetGet method
function offsetGetTest() {
$array = array(
'a' => 'a text',
'b' => array(
'b_1' => 'b_1 text',
'b_2' => 'b_2 text',
),
'c' => array(
'c_1' => array(
'c_1_1' => 'c_1_1 text',
),
'c_2' => array(
'c_2_1' => 'c_2_1 text',
'c_2_2' => 'c_2_2 text',
),
),
);
$object = json_decode( json_encode( $array )); // in case of array with associative keys
//++ $object = array_to_object( $array ); // in case of array with numeric and/or associative keys
//** $object = new ArrayObject( $array, 0, "RecursiveArrayIterator" );
$iterator = new RecursiveIteratorIterator( new RecursiveArrayIterator( $object ), RecursiveIteratorIterator::SELF_FIRST );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$value = '';
foreach( $iterator as $key => $current ) {
if( $key == 'a' ) {
$value = $iterator->getInnerIterator()->offsetGet( $key );
$iterator->getInnerIterator()->offsetUnset( $key );
}
if( $key == 'c_1_1' ) {
$iterator->getInnerIterator()->offsetSet( $key, $value );
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
print_r($object);
}
offsetGetTest();
/* Result
stdClass Object
(
[b] => stdClass Object
(
[b_1] => b_1 text
[b_2] => b_2 text
)
[c] => stdClass Object
(
[c_1] => stdClass Object
(
[c_1_1] => a text
)
[c_2] => stdClass Object
(
[c_2_1] => c_2_1 text
[c_2_2] => c_2_2 text
)
)
)
| NaMarPi/PHP-SPL-Recursive-Examples | RecursiveArrayIterator/offsetGet.php | PHP | gpl-2.0 | 2,142 |
//COBERTURA EXCLUDE THIS FILE
/*
Copyright (C) 2000 Chr. Clemens Lee <clemens@kclee.com>.
This file is part of JavaNCSS
(http://www.kclee.com/clemens/java/javancss/).
JavaNCSS 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.
JavaNCSS 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 JavaNCSS; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
package javancss;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.*;
import ccl.swing.AboutDialog;
import ccl.swing.AnimationPanel;
import ccl.swing.AutoGridBagLayout;
import ccl.swing.MainJFrame;
import ccl.swing.SwingUtil;
import ccl.util.FileUtil;
import ccl.util.Init;
import ccl.util.Util;
/**
* Main class used to start JavaNCSS in GUI mode from other
* java applications. To start JavaNCSS from the command line,
* gui mode or not, class 'Main' is used.
*
* @author <a href="http://www.kclee.com/clemens/">Chr. Clemens Lee</a> (<a href="mailto:clemens@kclee.com"><i>clemens@kclee.com</i></a>)
* @version $Id: JavancssFrame.java 121 2009-01-17 22:19:45Z hboutemy $
*/
public class JavancssFrame extends MainJFrame {
public static final String S_PACKAGES = "Packages";
public static final String S_CLASSES = "Classes";
public static final String S_METHODS = "Methods";
private static final String S_MN_F_SAVE = "Save";
private int _oldThreadPriority = -1;
private AnimationPanel _pAnimationPanel = null;
private JTextArea _txtPackage;
private JTextArea _txtObject;
private JTextArea _txtFunction;
private JTextArea _txtError;
private JTabbedPane _pTabbedPane = null;
private Font pFont = new Font("Monospaced", Font.PLAIN, 12);
private boolean _bNoError = true;
private String _sProjectName = null;
private String _sProjectPath = null;
private Init _pInit = null;
public void save() {
String sFullProjectName = FileUtil.concatPath
(_sProjectPath, _sProjectName.toLowerCase());
String sPackagesFullFileName = sFullProjectName +
".packages.txt";
String sClassesFullFileName = sFullProjectName +
".classes.txt";
String sMethodsFullFileName = sFullProjectName +
".methods.txt";
String sSuccessMessage = "Data appended successfully to the following files:";
try {
FileUtil.appendFile(sPackagesFullFileName,
_txtPackage.getText());
sSuccessMessage += "\n" + sPackagesFullFileName;
} catch(Exception ePackages) {
SwingUtil.showMessage(this, "Error: could not append to file '" +
sPackagesFullFileName + "'.\n" + ePackages);
}
try {
FileUtil.appendFile(sClassesFullFileName,
_txtObject.getText());
sSuccessMessage += "\n" + sClassesFullFileName;
} catch(Exception eClasses) {
SwingUtil.showMessage(this, "Error: could not append to file '" +
sClassesFullFileName + "'.\n" + eClasses);
}
try {
FileUtil.appendFile(sMethodsFullFileName,
_txtFunction.getText());
sSuccessMessage += "\n" + sMethodsFullFileName;
} catch(Exception eMethods) {
SwingUtil.showMessage(this, "Error: could not append to file '" +
sMethodsFullFileName + "'.\n" + eMethods);
}
SwingUtil.showMessage(this, sSuccessMessage);
}
private void _setMenuBar() {
Vector vMenus = new Vector();
Vector vFileMenu = new Vector();
Vector vHelpMenu = new Vector();
vFileMenu.addElement("File");
vFileMenu.addElement(S_MN_F_SAVE);
vFileMenu.addElement("Exit");
vHelpMenu.addElement("Help");
vHelpMenu.addElement("&Contents...");
vHelpMenu.addElement("---");
vHelpMenu.addElement("About...");
vMenus.addElement(vFileMenu);
vMenus.addElement(vHelpMenu);
setMenuBar(vMenus);
}
/**
* Returns init object provided with constructor.
*/
public Init getInit() {
return _pInit;
}
public JavancssFrame(Init pInit_) {
super( "JavaNCSS: " + pInit_.getFileName() );
_pInit = pInit_;
getInit().setAuthor( "Chr. Clemens Lee" );
super.setBackground( _pInit.getBackground() );
_sProjectName = pInit_.getFileName();
_sProjectPath = pInit_.getFilePath();
if (Util.isEmpty(_sProjectName)) {
_sProjectName = pInit_.getApplicationName();
_sProjectPath = pInit_.getApplicationPath();
}
_setMenuBar();
_bAboutSelected = false;
AutoGridBagLayout pAutoGridBagLayout = new AutoGridBagLayout();
getContentPane().setLayout(pAutoGridBagLayout);
Image pImage = Toolkit.getDefaultToolkit().
getImage( SwingUtil.createCCLBorder().getClass().getResource
( "anim_recycle_brown.gif" ) );
_pAnimationPanel = new AnimationPanel( pImage, 350 );
JPanel pPanel = new JPanel();
pPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
pPanel.add(_pAnimationPanel, BorderLayout.CENTER);
getContentPane().add(pPanel);
pack();
setSize(640, 480);
SwingUtil.centerComponent(this);
}
public void showJavancss(Javancss pJavancss_) {
_bStop = false;
_bSave = false;
if (_oldThreadPriority != -1) {
Thread.currentThread().setPriority(_oldThreadPriority);
_pAnimationPanel.stop();
}
getContentPane().removeAll();
getContentPane().setLayout(new BorderLayout());
_bNoError = true;
if (pJavancss_.getLastErrorMessage() != null && pJavancss_.getNcss() <= 0) {
_bNoError = false;
JTextArea txtError = new JTextArea();
String sError = "Error in Javancss: " +
pJavancss_.getLastErrorMessage();
txtError.setText(sError);
JScrollPane jspError = new JScrollPane(txtError);
getContentPane().add(jspError, BorderLayout.CENTER);
} else {
Util.debug("JavancssFrame.showJavancss(..).NOERROR");
JPanel pPanel = new JPanel(true);
pPanel.setLayout(new BorderLayout());
_pTabbedPane = new JTabbedPane();
_pTabbedPane.setDoubleBuffered(true);
_txtPackage = new JTextArea();
_txtPackage.setFont(pFont);
JScrollPane jspPackage = new JScrollPane(_txtPackage);
int inset = 5;
jspPackage.setBorder( BorderFactory.
createEmptyBorder
( inset, inset, inset, inset ) );
_pTabbedPane.addTab("Packages", null, jspPackage);
_txtObject = new JTextArea();
_txtObject.setFont(pFont);
JScrollPane jspObject = new JScrollPane(_txtObject);
jspObject.setBorder( BorderFactory.
createEmptyBorder
( inset, inset, inset, inset ) );
_pTabbedPane.addTab("Classes", null, jspObject);
_txtFunction = new JTextArea();
_txtFunction.setFont(pFont);
JScrollPane jspFunction = new JScrollPane(_txtFunction);
jspFunction.setBorder( BorderFactory.
createEmptyBorder
( inset, inset, inset, inset ) );
_pTabbedPane.addTab("Methods", null, jspFunction);
// date and time
String sTimeZoneID = System.getProperty("user.timezone");
if (sTimeZoneID.equals("CET")) {
sTimeZoneID = "ECT";
}
TimeZone pTimeZone = TimeZone.getTimeZone(sTimeZoneID);
Util.debug("JavancssFrame.showJavancss(..).pTimeZone.getID(): " + pTimeZone.getID());
SimpleDateFormat pSimpleDateFormat
= new SimpleDateFormat("EEE, MMM dd, yyyy HH:mm:ss");//"yyyy.mm.dd e 'at' hh:mm:ss a z");
pSimpleDateFormat.setTimeZone(pTimeZone);
String sDate = pSimpleDateFormat.format(new Date()) + " " + pTimeZone.getID();
_txtPackage.setText(sDate + "\n\n" + pJavancss_.printPackageNcss());
_txtObject.setText(sDate + "\n\n" + pJavancss_.printObjectNcss());
_txtFunction.setText(sDate + "\n\n" + pJavancss_.printFunctionNcss());
if (pJavancss_.getLastErrorMessage() != null) {
_txtError = new JTextArea();
String sError = "Errors in Javancss:\n\n" +
pJavancss_.getLastErrorMessage();
_txtError.setText(sError);
JScrollPane jspError = new JScrollPane(_txtError);
jspError.setBorder( BorderFactory.
createEmptyBorder
( inset, inset, inset, inset ) );
getContentPane().add(jspError, BorderLayout.CENTER);
_pTabbedPane.addTab("Errors", null, jspError);
}
pPanel.add(_pTabbedPane, BorderLayout.CENTER);
getContentPane().add(pPanel, BorderLayout.CENTER);
}
validate();
repaint();
}
private boolean _bStop = false;
private boolean _bSave = false;
public void run() {
_bSave = false;
while(!_bStop) {
if (_bSave) {
save();
_bSave = false;
}
if (isExitSet()) {
exit();
_bStop = true;
break;
}
if (_bAboutSelected) {
_bAboutSelected = false;
AboutDialog dlgAbout = new AboutDialog
( this,
getInit().getAuthor(),
javancss.Main.S_RCS_HEADER );
dlgAbout.dispose();
requestFocus();
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
public void setVisible(boolean bVisible_) {
if (bVisible_) {
_oldThreadPriority = Thread.currentThread().getPriority();
_pAnimationPanel.start();
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
} else {
_pAnimationPanel.stop();
}
super.setVisible(bVisible_);
}
public void setSelectedTab(String sTab_) {
Util.panicIf(Util.isEmpty(sTab_));
if (!_bNoError) {
return;
}
if (sTab_.equals(S_METHODS)) {
/*_pTabbedPane.setSelectedComponent(_txtFunction);*/
_pTabbedPane.setSelectedIndex(2);
} else if (sTab_.equals(S_CLASSES)) {
/*_pTabbedPane.setSelectedComponent(_txtObject);*/
_pTabbedPane.setSelectedIndex(1);
} else {
/*_pTabbedPane.setSelectedComponent(_txtPackage);*/
_pTabbedPane.setSelectedIndex(0);
}
}
private boolean _bAboutSelected = false;
public void actionPerformed(ActionEvent pActionEvent_) {
Util.debug("JavancssFrame.actionPerformed(..).1");
Object oSource = pActionEvent_.getSource();
if (oSource instanceof JMenuItem) {
String sMenuItem = ((JMenuItem)oSource).getText();
if (sMenuItem.equals("Beenden") || sMenuItem.equals("Exit")) {
processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
} else if (sMenuItem.equals(S_MN_F_SAVE)) {
_bSave = true;
} else if (sMenuItem.equals("Info...") || sMenuItem.equals("About...") ||
sMenuItem.equals("Info") || sMenuItem.equals("About"))
{
_bAboutSelected = true;
} else if (sMenuItem.equals("Inhalt...") || sMenuItem.equals("Contents...") ||
sMenuItem.equals("Inhalt") || sMenuItem.equals("Contents"))
{
String sStartURL = FileUtil.concatPath(FileUtil.getPackagePath("javancss"),
S_DOC_DIR) + File.separator +
"index.html";
if (Util.isEmpty(sStartURL)) {
return;
}
sStartURL = sStartURL.replace('\\', '/');
if (sStartURL.charAt(0) != '/') {
sStartURL = "/" + sStartURL;
}
sStartURL = "file:" + sStartURL;
Util.debug("JavancssFrame.actionPerformed(): sStartURL: " + sStartURL);
/*try {
URL urlHelpDocument = new URL(sStartURL);
//HtmlViewer pHtmlViewer = new HtmlViewer(urlHelpDocument);
} catch(Exception pException) {
Util.debug("JavancssFrame.actionPerformed(..).pException: " + pException);
}*/
}
}
}
}
| hsun/cobertura-fork | javancss/src/main/java/javancss/JavancssFrame.java | Java | gpl-2.0 | 13,787 |
/*****************************************************************************
* Web3d.org Copyright (c) 2001
* Java Source
*
* This source is licensed under the GNU LGPL v2.1
* Please read http://www.gnu.org/copyleft/lgpl.html for more information
*
* This software comes with the standard NO WARRANTY disclaimer for any
* purpose. Use it at your own risk. If there's a problem you get to fix it.
*
****************************************************************************/
package org.web3d.vrml.export.compressors;
// Standard library imports
import java.io.DataOutputStream;
import java.io.IOException;
// Application specific imports
import org.web3d.vrml.lang.*;
import org.web3d.vrml.nodes.VRMLNodeType;
/**
* A FieldCompressor that works by compressing the range of data. Floats are
* converted to ints before range compression.
*
* @author Alan Hudson
* @version $Revision: 1.4 $
*/
public class RangeCompressor extends BinaryFieldEncoder {
/**
* Compress this field and deposit the output to the bitstream
*
* @param dos The stream to output the result
* @param fieldType The type of field to compress from FieldConstants.
* @param data The field data
*/
public void compress(DataOutputStream dos, int fieldType, int[] data)
throws IOException {
CompressionTools.rangeCompressIntArray(dos,false,1,data);
}
/**
* Compress this field and deposit the output to the bitstream
*
* @param dos The stream to output the result
* @param fieldType The type of field to compress from FieldConstants.
* @param data The field data
*/
public void compress(DataOutputStream dos, int fieldType, float[] data)
throws IOException {
switch(fieldType) {
case FieldConstants.SFCOLOR:
case FieldConstants.SFVEC3F:
case FieldConstants.SFROTATION:
case FieldConstants.SFCOLORRGBA:
case FieldConstants.SFVEC2F:
for(int i=0; i < data.length; i++) {
dos.writeFloat(data[i]);
}
break;
case FieldConstants.MFCOLOR:
case FieldConstants.MFVEC3F:
case FieldConstants.MFFLOAT:
case FieldConstants.MFROTATION:
case FieldConstants.MFCOLORRGBA:
case FieldConstants.MFVEC2F:
CompressionTools.compressFloatArray(dos, false,1,data);
break;
default:
System.out.println("Unhandled datatype in compress float[]: " + fieldType);
}
}
}
| Norkart/NK-VirtualGlobe | Xj3D/src/java/org/web3d/vrml/export/compressors/RangeCompressor.java | Java | gpl-2.0 | 2,664 |
<?php
/**
* The template for displaying the footer.
*
* Contains the closing of the #content div and all content after
*
* @package curtains
*/
?>
</div> <!-- .container -->
</div><!-- #content -->
<footer id="colophon" class="site-footer" role="contentinfo">
<?php
$footer_widgets = get_theme_mod( 'footer_widgets',true );
if( $footer_widgets ) : ?>
<div class="footer-widgets">
<div class="container">
<?php get_template_part('footer','widgets'); ?>
</div>
</div>
<?php endif; ?>
<div class="site-info">
<div class="container">
<div class="copyright eight columns">
<?php if( get_theme_mod('copyright') ) : ?>
<p><?php echo get_theme_mod('copyright'); ?></p>
<?php else :
do_action('curtains_credits');
endif; ?>
</div>
<div class="footer-right eight columns">
<?php dynamic_sidebar( 'footer-nav' ); ?>
</div>
</div>
</div><!-- .site-info -->
</footer><!-- #colophon -->
</div><!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
| yosagarrane/testsite | wp-content/themes/curtains/footer.php | PHP | gpl-2.0 | 1,052 |
#############################################################################
##
## Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
## Contact: Qt Software Information (qt-info@nokia.com)
##
## This file is part of the Graphics Dojo project on Qt Labs.
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 or 3.0 as published by the Free Software Foundation
## and appearing in the file LICENSE.GPL included in the packaging of
## this file. Please review the following information to ensure GNU
## General Public Licensing requirements will be met:
## http:#www.fsf.org/licensing/licenses/info/GPLv2.html and
## http:#www.gnu.org/copyleft/gpl.html.
##
## If you are unsure which license is appropriate for your use, please
## contact the sales department at qt-sales@nokia.com.
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
#############################################################################
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
if QT_VERSION < 0x0040500:
sys.stderr.write("You need Qt 4.5 or newer to run this example.\n")
sys.exit(1)
SNAP_THRESHOLD = 10
class SnapView(QWebView):
def __init__(self):
QWebView.__init__(self)
self.snapEnabled = True
self.setWindowTitle(self.tr("Snap-scrolling is ON"))
# rects hit by the line, in main frame's view coordinate
def hitBoundingRects(self, line):
hitRects = []
points = 8
delta = QPoint(line.dx() / points, line.dy() / points)
point = line.p1()
i = 0
while i < points - 1:
point += delta
hit = self.page().mainFrame().hitTestContent(point)
if not hit.boundingRect().isEmpty():
hitRects.append(hit.boundingRect())
i += 1
return hitRects
def keyPressEvent(self, event):
# toggle snapping
if event.key() == Qt.Key_F3:
self.snapEnabled = not self.snapEnabled
if self.snapEnabled:
self.setWindowTitle(self.tr("Snap-scrolling is ON"))
else:
self.setWindowTitle(self.tr("Snap-scrolling is OFF"))
event.accept()
return
# no snapping? do not bother...
if not self.snapEnabled:
QWebView.keyReleaseEvent(self, event)
return
previousOffset = self.page().mainFrame().scrollPosition()
QWebView.keyReleaseEvent(self, event)
if not event.isAccepted():
return
if event.key() == Qt.Key_Down:
ofs = self.page().mainFrame().scrollPosition()
jump = ofs.y() - previousOffset.y()
if jump == 0:
return
jump += SNAP_THRESHOLD
rects = self.hitBoundingRects(QLine(1, 1, self.width() - 1, 1))
i = 0
while i < len(rects):
j = rects[i].top() - previousOffset.y()
if j > SNAP_THRESHOLD and j < jump:
jump = j
i += 1
self.page().mainFrame().setScrollPosition(previousOffset + QPoint(0, jump))
if __name__ == "__main__":
app = QApplication(sys.argv)
view = SnapView()
view.load(QUrl("http://news.bbc.co.uk/text_only.stm"))
view.resize(320, 500)
view.show()
QMessageBox.information(view, "Hint", "Use F3 to toggle snapping on and off")
sys.exit(app.exec_())
| anak10thn/graphics-dojo-qt5 | snapscroll/snapscroll.py | Python | gpl-2.0 | 3,660 |