code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_72) on Thu Nov 20 19:27:36 ICT 2014 -->
<title>KeyPoint</title>
<meta name="date" content="2014-11-20">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="KeyPoint";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/opencv/features2d/GenericDescriptorMatcher.html" title="class in org.opencv.features2d"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/opencv/features2d/KeyPoint.html" target="_top">Frames</a></li>
<li><a href="KeyPoint.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.opencv.features2d</div>
<h2 title="Class KeyPoint" class="title">Class KeyPoint</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.opencv.features2d.KeyPoint</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">KeyPoint</span>
extends java.lang.Object</pre>
<div class="block"><p>Data structure for salient point detectors.</p>
<p>coordinates of the keypoint</p>
<p>diameter of the meaningful keypoint neighborhood <code></p>
<p>// C++ code:</p>
<p>computed orientation of the keypoint (-1 if not applicable). Its possible
values are in a range [0,360) degrees. It is measured relative to image
coordinate system (y-axis is directed downward), ie in clockwise.</p>
<p>the response by which the most strong keypoints have been selected. Can be
used for further sorting or subsampling</p>
<p>octave (pyramid layer) from which the keypoint has been extracted</p>
<p>object id that can be used to clustered keypoints by an object they belong to</p></div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html#keypoint">org.opencv.features2d.KeyPoint</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>float</code></td>
<td class="colLast"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#angle">angle</a></strong></code>
<div class="block">Computed orientation of the keypoint (-1 if not applicable).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#class_id">class_id</a></strong></code>
<div class="block">Object ID, that can be used to cluster keypoints by an object they
belong to.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#octave">octave</a></strong></code>
<div class="block">Octave (pyramid layer), from which the keypoint has been extracted.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../org/opencv/core/Point.html" title="class in org.opencv.core">Point</a></code></td>
<td class="colLast"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#pt">pt</a></strong></code>
<div class="block">Coordinates of the keypoint.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>float</code></td>
<td class="colLast"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#response">response</a></strong></code>
<div class="block">The response, by which the strongest keypoints have been selected.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>float</code></td>
<td class="colLast"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#size">size</a></strong></code>
<div class="block">Diameter of the useful keypoint adjacent area.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#KeyPoint()">KeyPoint</a></strong>()</code>
<div class="block">The keypoint constructors</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#KeyPoint(float,%20float,%20float)">KeyPoint</a></strong>(float x,
float y,
float _size)</code>
<div class="block">The keypoint constructors</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#KeyPoint(float,%20float,%20float,%20float)">KeyPoint</a></strong>(float x,
float y,
float _size,
float _angle)</code>
<div class="block">The keypoint constructors</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#KeyPoint(float,%20float,%20float,%20float,%20float)">KeyPoint</a></strong>(float x,
float y,
float _size,
float _angle,
float _response)</code>
<div class="block">The keypoint constructors</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#KeyPoint(float,%20float,%20float,%20float,%20float,%20int)">KeyPoint</a></strong>(float x,
float y,
float _size,
float _angle,
float _response,
int _octave)</code>
<div class="block">The keypoint constructors</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#KeyPoint(float,%20float,%20float,%20float,%20float,%20int,%20int)">KeyPoint</a></strong>(float x,
float y,
float _size,
float _angle,
float _response,
int _octave,
int _class_id)</code>
<div class="block">The keypoint constructors</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../org/opencv/features2d/KeyPoint.html#toString()">toString</a></strong>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="pt">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>pt</h4>
<pre>public <a href="../../../org/opencv/core/Point.html" title="class in org.opencv.core">Point</a> pt</pre>
<div class="block">Coordinates of the keypoint.</div>
</li>
</ul>
<a name="size">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>size</h4>
<pre>public float size</pre>
<div class="block">Diameter of the useful keypoint adjacent area.</div>
</li>
</ul>
<a name="angle">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>angle</h4>
<pre>public float angle</pre>
<div class="block">Computed orientation of the keypoint (-1 if not applicable).</div>
</li>
</ul>
<a name="response">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>response</h4>
<pre>public float response</pre>
<div class="block">The response, by which the strongest keypoints have been selected. Can
be used for further sorting or subsampling.</div>
</li>
</ul>
<a name="octave">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>octave</h4>
<pre>public int octave</pre>
<div class="block">Octave (pyramid layer), from which the keypoint has been extracted.</div>
</li>
</ul>
<a name="class_id">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>class_id</h4>
<pre>public int class_id</pre>
<div class="block">Object ID, that can be used to cluster keypoints by an object they
belong to.</div>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="KeyPoint(float, float, float, float, float, int, int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>KeyPoint</h4>
<pre>public KeyPoint(float x,
float y,
float _size,
float _angle,
float _response,
int _octave,
int _class_id)</pre>
<div class="block"><p>The keypoint constructors</p></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>x</code> - x-coordinate of the keypoint</dd><dd><code>y</code> - y-coordinate of the keypoint</dd><dd><code>_size</code> - keypoint diameter</dd><dd><code>_angle</code> - keypoint orientation</dd><dd><code>_response</code> - keypoint detector response on the keypoint (that is,
strength of the keypoint)</dd><dd><code>_octave</code> - pyramid octave in which the keypoint has been detected</dd><dd><code>_class_id</code> - object id</dd><dt><span class="strong">See Also:</span></dt><dd><a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html#keypoint-keypoint">org.opencv.features2d.KeyPoint.KeyPoint</a></dd></dl>
</li>
</ul>
<a name="KeyPoint()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>KeyPoint</h4>
<pre>public KeyPoint()</pre>
<div class="block"><p>The keypoint constructors</p></div>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html#keypoint-keypoint">org.opencv.features2d.KeyPoint.KeyPoint</a></dd></dl>
</li>
</ul>
<a name="KeyPoint(float, float, float, float, float, int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>KeyPoint</h4>
<pre>public KeyPoint(float x,
float y,
float _size,
float _angle,
float _response,
int _octave)</pre>
<div class="block"><p>The keypoint constructors</p></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>x</code> - x-coordinate of the keypoint</dd><dd><code>y</code> - y-coordinate of the keypoint</dd><dd><code>_size</code> - keypoint diameter</dd><dd><code>_angle</code> - keypoint orientation</dd><dd><code>_response</code> - keypoint detector response on the keypoint (that is,
strength of the keypoint)</dd><dd><code>_octave</code> - pyramid octave in which the keypoint has been detected</dd><dt><span class="strong">See Also:</span></dt><dd><a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html#keypoint-keypoint">org.opencv.features2d.KeyPoint.KeyPoint</a></dd></dl>
</li>
</ul>
<a name="KeyPoint(float, float, float, float, float)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>KeyPoint</h4>
<pre>public KeyPoint(float x,
float y,
float _size,
float _angle,
float _response)</pre>
<div class="block"><p>The keypoint constructors</p></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>x</code> - x-coordinate of the keypoint</dd><dd><code>y</code> - y-coordinate of the keypoint</dd><dd><code>_size</code> - keypoint diameter</dd><dd><code>_angle</code> - keypoint orientation</dd><dd><code>_response</code> - keypoint detector response on the keypoint (that is,
strength of the keypoint)</dd><dt><span class="strong">See Also:</span></dt><dd><a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html#keypoint-keypoint">org.opencv.features2d.KeyPoint.KeyPoint</a></dd></dl>
</li>
</ul>
<a name="KeyPoint(float, float, float, float)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>KeyPoint</h4>
<pre>public KeyPoint(float x,
float y,
float _size,
float _angle)</pre>
<div class="block"><p>The keypoint constructors</p></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>x</code> - x-coordinate of the keypoint</dd><dd><code>y</code> - y-coordinate of the keypoint</dd><dd><code>_size</code> - keypoint diameter</dd><dd><code>_angle</code> - keypoint orientation</dd><dt><span class="strong">See Also:</span></dt><dd><a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html#keypoint-keypoint">org.opencv.features2d.KeyPoint.KeyPoint</a></dd></dl>
</li>
</ul>
<a name="KeyPoint(float, float, float)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>KeyPoint</h4>
<pre>public KeyPoint(float x,
float y,
float _size)</pre>
<div class="block"><p>The keypoint constructors</p></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>x</code> - x-coordinate of the keypoint</dd><dd><code>y</code> - y-coordinate of the keypoint</dd><dd><code>_size</code> - keypoint diameter</dd><dt><span class="strong">See Also:</span></dt><dd><a href="http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html#keypoint-keypoint">org.opencv.features2d.KeyPoint.KeyPoint</a></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="toString()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>toString</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/opencv/features2d/GenericDescriptorMatcher.html" title="class in org.opencv.features2d"><span class="strong">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/opencv/features2d/KeyPoint.html" target="_top">Frames</a></li>
<li><a href="KeyPoint.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| xdien/my_androidproject | doc/org/opencv/features2d/KeyPoint.html | HTML | gpl-2.0 | 19,690 |
#! /usr/bin/env python3
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
includefiles = ['windows/libusb-1.0.dll',
('icons/buzzer.png', 'icons/buzzer.png'),
'README.md',
'LICENSE',
'C:\\Windows\\SysWOW64\\msvcr110.dll']
excludes = []
packages = []
buildOptions = {'packages': packages,
'excludes': excludes,
'include_files':includefiles
}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [
Executable('pyPardy.py', base=base),
Executable('pyPardyEdit.py', base=base)
]
setup(
name='pyPardy',
#long_description='',
keywords='game jeopardy',
version='0.2',
author='Christian Wichmann',
author_email='christian@freenono.org',
packages=['data', 'gui'],
url='',
license='LICENSE',
description='Jeopardy(tm) game system',
platforms=['any'],
classifiers=[
'Intended Audience :: End Users/Desktop',
'Development Status :: 4 - Beta',
'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)',
'Operating System :: OS Independent',
'Natural Language :: English',
'Natural Language :: German',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Games/Entertainment',
],
options=dict(build_exe=buildOptions),
executables=executables, requires=['PyQt4', 'libusb1'],
#data_files=[('libs', 'windows/libusb-1.0.dll'),
# ('icons', 'icons/buzzer.png')],
)
| wichmann/pyPardy | setup.py | Python | gpl-2.0 | 1,810 |
<?php
/**
* Prefix rendered output with HTML comment stating filename of the rendered template
*
* PHP version 7
*
* Copyright (C) project swissbib, University Library Basel, Switzerland
* http://www.swissbib.org / http://www.swissbib.ch / http://www.ub.unibas.ch
*
* Date: 1/2/13
* Time: 4:09 PM
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category Swissbib_VuFind
* @package Filter
* @author Guenter Hipler <guenter.hipler@unibas.ch>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://www.swissbib.org
*/
namespace Swissbib\Filter;
use Laminas\Filter\AbstractFilter;
use Laminas\ServiceManager\ServiceLocatorInterface;
/**
* Class SbTemplateFilenameFilter
*
* Content filter to wrap rendered template content with HTML comments,
* indicating which template file implemented a section of output.
* Every template section is wrapped by comments to mark the 1) beginning and 2)
* ending of a template file.
*
* Activating the filter: call SbTemplateFilenameFilter::onBootstrap() from within
* the onBootstap() method of the module class (\path\to\module\Namespace\Module.php)
*
* @category Swissbib_Filter
* @package Filter
* @author Guenter Hipler <guenter.hipler@unibas.ch>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org
*/
class TemplateFilenameFilter extends AbstractFilter
{
/**
* ServiceLocator
*
* @var ServiceLocatorInterface
*/
protected $serviceLocator;
/**
* Filter
*
* @param Mixed $content Content
*
* @return Mixed|String
*/
public function filter($content)
{
$sm = $this->serviceLocator;
/**
* PhpRenderer
*
* @var $phpRenderer \Laminas\View\Renderer\PhpRenderer
*/
$phpRenderer = $sm->get('Laminas\View\Renderer\PhpRenderer');
// Fetch private property PhpRenderer::__file via reflection
$rendererReflection = new \ReflectionObject($phpRenderer);
$fileProperty = $rendererReflection->getProperty('__file');
$fileProperty->setAccessible(true);
$templateFilename = $fileProperty->getValue($phpRenderer);
// Don't wrap export stuff and swagger
if ((stristr($templateFilename, 'export-') !== false)
|| (stristr($templateFilename, '/email/') !== false)
|| (stristr($templateFilename, '/searchapi/') !== false)
|| (stristr($templateFilename, '/api/') !== false)
|| (stristr($templateFilename, '/link') !== false)
) {
return $content;
}
// Remove possibly confidential server details from path
$directoryDelimiter = 'themes' . DIRECTORY_SEPARATOR;
$templateFilename = substr(
$templateFilename, strpos($templateFilename, $directoryDelimiter) + 7
);
return $this->_wrapContentWithComment($content, $templateFilename);
}
/**
* Wraps contents with comments
*
* @param String $content Content
* @param String $templateFilename Template file
*
* @return String
*/
private function _wrapContentWithComment($content, $templateFilename)
{
$templateFilename = str_replace('\\', '/', $templateFilename);
$isStartOfHtml = strstr($content, '<html') !== false
|| strstr($content, '<xml') !== false;
return $isStartOfHtml ? $content :
"\n" . '<!-- Begin' . (!empty($type) ? ' ' . $type : '') . ': '
. $templateFilename . ' -->'
. "\n" . $content
. "\n" . '<!-- End: ' . $templateFilename . ' -->'
. "\n";
}
/**
* Set ServiceLocator
*
* @param ServiceLocatorInterface $serviceLocator ServiceLocator
*
* @return void
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
/**
* Get ServiceLocator
*
* @return ServiceLocatorInterface
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
}
| swissbib/vufind | module/Swissbib/src/Swissbib/Filter/TemplateFilenameFilter.php | PHP | gpl-2.0 | 4,845 |
package com.yh.hr.component.unit.service;
import com.yh.hr.res.unit.dto.UtOrgDTO;
import com.yh.hr.res.unit.dto.UtUnitDTO;
import com.yh.platform.core.exception.ServiceException;
public interface UtOrganizationComService {
/**
* 同步创建机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseCreateUnitInfo(UtUnitDTO utUnitDTO) throws ServiceException;
/**
* 同步更新机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseUpdateUnitInfo(UtUnitDTO utUnitDTO) throws ServiceException;
/**
* 同步创建内设机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseCreateOrgInfo(UtOrgDTO utOrgDTO) throws ServiceException;
/**
* 同步更新内设机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseUpdateOrgInfo(UtOrgDTO utOrgDTO) throws ServiceException;
/**
* 同步删除内设机构信息
* @param utUnitDTO
* @throws ServiceException
* @author lenghh
*/
public void synchroniseDeleteOrgInfo(Long orgOid) throws ServiceException;
/**
* 查找单位主管单位
* @param unitOid
* @return UtUnitDTO
* @throws ServiceException
*/
public UtUnitDTO getAdminUnit(Long unitOid) throws ServiceException;
}
| meijmOrg/Repo-test | freelance-hr-component/src/java/com/yh/hr/component/unit/service/UtOrganizationComService.java | Java | gpl-2.0 | 1,418 |
#include <filezilla.h>
#include "manual_transfer.h"
#include "auto_ascii_files.h"
#include "state.h"
#include "Options.h"
#include "sitemanager.h"
#include "queue.h"
#include "QueueView.h"
#include "xrc_helper.h"
#include <libfilezilla/local_filesys.hpp>
BEGIN_EVENT_TABLE(CManualTransfer, wxDialogEx)
EVT_TEXT(XRCID("ID_LOCALFILE"), CManualTransfer::OnLocalChanged)
EVT_TEXT(XRCID("ID_REMOTEFILE"), CManualTransfer::OnRemoteChanged)
EVT_BUTTON(XRCID("ID_BROWSE"), CManualTransfer::OnLocalBrowse)
EVT_RADIOBUTTON(XRCID("ID_DOWNLOAD"), CManualTransfer::OnDirection)
EVT_RADIOBUTTON(XRCID("ID_UPLOAD"), CManualTransfer::OnDirection)
EVT_RADIOBUTTON(XRCID("ID_SERVER_CURRENT"), CManualTransfer::OnServerTypeChanged)
EVT_RADIOBUTTON(XRCID("ID_SERVER_SITE"), CManualTransfer::OnServerTypeChanged)
EVT_RADIOBUTTON(XRCID("ID_SERVER_CUSTOM"), CManualTransfer::OnServerTypeChanged)
EVT_BUTTON(XRCID("wxID_OK"), CManualTransfer::OnOK)
EVT_BUTTON(XRCID("ID_SERVER_SITE_SELECT"), CManualTransfer::OnSelectSite)
EVT_MENU(wxID_ANY, CManualTransfer::OnSelectedSite)
EVT_CHOICE(XRCID("ID_LOGONTYPE"), CManualTransfer::OnLogontypeSelChanged)
END_EVENT_TABLE()
CManualTransfer::CManualTransfer(CQueueView* pQueueView)
: m_local_file_exists()
, m_pServer()
, m_pLastSite()
, m_pState()
, m_pQueueView(pQueueView)
{
}
CManualTransfer::~CManualTransfer()
{
delete m_pServer;
delete m_pLastSite;
}
void CManualTransfer::Run(wxWindow* pParent, CState* pState)
{
if (!Load(pParent, _T("ID_MANUALTRANSFER")))
return;
m_pState = pState;
wxChoice *pProtocol = XRCCTRL(*this, "ID_PROTOCOL", wxChoice);
if (pProtocol) {
pProtocol->Append(CServer::GetProtocolName(FTP));
pProtocol->Append(CServer::GetProtocolName(SFTP));
pProtocol->Append(CServer::GetProtocolName(FTPS));
pProtocol->Append(CServer::GetProtocolName(FTPES));
pProtocol->Append(CServer::GetProtocolName(INSECURE_FTP));
}
wxChoice* pChoice = XRCCTRL(*this, "ID_LOGONTYPE", wxChoice);
wxASSERT(pChoice);
for (int i = 0; i < LOGONTYPE_MAX; ++i)
pChoice->Append(CServer::GetNameFromLogonType((enum LogonType)i));
if (m_pState->GetServer()) {
m_pServer = new CServer(*m_pState->GetServer());
XRCCTRL(*this, "ID_SERVER_CURRENT", wxRadioButton)->SetValue(true);
DisplayServer();
}
else {
XRCCTRL(*this, "ID_SERVER_CUSTOM", wxRadioButton)->SetValue(true);
XRCCTRL(*this, "ID_SERVER_CURRENT", wxRadioButton)->Disable();
DisplayServer();
}
wxString localPath = m_pState->GetLocalDir().GetPath();
XRCCTRL(*this, "ID_LOCALFILE", wxTextCtrl)->ChangeValue(localPath);
XRCCTRL(*this, "ID_REMOTEPATH", wxTextCtrl)->ChangeValue(m_pState->GetRemotePath().GetPath());
SetControlState();
switch(COptions::Get()->GetOptionVal(OPTION_ASCIIBINARY))
{
case 1:
XRCCTRL(*this, "ID_TYPE_ASCII", wxRadioButton)->SetValue(true);
break;
case 2:
XRCCTRL(*this, "ID_TYPE_BINARY", wxRadioButton)->SetValue(true);
break;
default:
XRCCTRL(*this, "ID_TYPE_AUTO", wxRadioButton)->SetValue(true);
break;
}
wxSize minSize = GetSizer()->GetMinSize();
SetClientSize(minSize);
ShowModal();
}
void CManualTransfer::SetControlState()
{
SetServerState();
SetAutoAsciiState();
XRCCTRL(*this, "ID_SERVER_SITE_SELECT", wxButton)->Enable(XRCCTRL(*this, "ID_SERVER_SITE", wxRadioButton)->GetValue());
}
void CManualTransfer::SetAutoAsciiState()
{
if (XRCCTRL(*this, "ID_DOWNLOAD", wxRadioButton)->GetValue()) {
wxString remote_file = XRCCTRL(*this, "ID_REMOTEFILE", wxTextCtrl)->GetValue();
if (remote_file.empty()) {
XRCCTRL(*this, "ID_TYPE_AUTO_ASCII", wxStaticText)->Hide();
XRCCTRL(*this, "ID_TYPE_AUTO_BINARY", wxStaticText)->Hide();
}
else if (CAutoAsciiFiles::TransferLocalAsAscii(remote_file, m_pServer ? m_pServer->GetType() : UNIX)) {
XRCCTRL(*this, "ID_TYPE_AUTO_ASCII", wxStaticText)->Show();
XRCCTRL(*this, "ID_TYPE_AUTO_BINARY", wxStaticText)->Hide();
}
else {
XRCCTRL(*this, "ID_TYPE_AUTO_ASCII", wxStaticText)->Hide();
XRCCTRL(*this, "ID_TYPE_AUTO_BINARY", wxStaticText)->Show();
}
}
else {
wxString local_file = XRCCTRL(*this, "ID_LOCALFILE", wxTextCtrl)->GetValue();
if (!m_local_file_exists) {
XRCCTRL(*this, "ID_TYPE_AUTO_ASCII", wxStaticText)->Hide();
XRCCTRL(*this, "ID_TYPE_AUTO_BINARY", wxStaticText)->Hide();
}
else if (CAutoAsciiFiles::TransferLocalAsAscii(local_file, m_pServer ? m_pServer->GetType() : UNIX)) {
XRCCTRL(*this, "ID_TYPE_AUTO_ASCII", wxStaticText)->Show();
XRCCTRL(*this, "ID_TYPE_AUTO_BINARY", wxStaticText)->Hide();
}
else {
XRCCTRL(*this, "ID_TYPE_AUTO_ASCII", wxStaticText)->Hide();
XRCCTRL(*this, "ID_TYPE_AUTO_BINARY", wxStaticText)->Show();
}
}
XRCCTRL(*this, "ID_TYPE_AUTO_ASCII", wxStaticText)->GetContainingSizer()->Layout();
}
void CManualTransfer::SetServerState()
{
bool server_enabled = XRCCTRL(*this, "ID_SERVER_CUSTOM", wxRadioButton)->GetValue();
XRCCTRL(*this, "ID_HOST", wxWindow)->Enable(server_enabled);
XRCCTRL(*this, "ID_PORT", wxWindow)->Enable(server_enabled);
XRCCTRL(*this, "ID_PROTOCOL", wxWindow)->Enable(server_enabled);
XRCCTRL(*this, "ID_LOGONTYPE", wxWindow)->Enable(server_enabled);
wxString logon_type = XRCCTRL(*this, "ID_LOGONTYPE", wxChoice)->GetStringSelection();
XRCCTRL(*this, "ID_USER", wxTextCtrl)->Enable(server_enabled && logon_type != _("Anonymous"));
XRCCTRL(*this, "ID_PASS", wxTextCtrl)->Enable(server_enabled && (logon_type == _("Normal") || logon_type == _("Account")));
XRCCTRL(*this, "ID_ACCOUNT", wxTextCtrl)->Enable(server_enabled && logon_type == _("Account"));
}
void CManualTransfer::DisplayServer()
{
if (m_pServer)
{
XRCCTRL(*this, "ID_HOST", wxTextCtrl)->ChangeValue(m_pServer->Format(ServerFormat::host_only));
unsigned int port = m_pServer->GetPort();
if (port != CServer::GetDefaultPort(m_pServer->GetProtocol()))
XRCCTRL(*this, "ID_PORT", wxTextCtrl)->ChangeValue(wxString::Format(_T("%d"), port));
else
XRCCTRL(*this, "ID_PORT", wxTextCtrl)->ChangeValue(_T(""));
const wxString& protocolName = CServer::GetProtocolName(m_pServer->GetProtocol());
if (!protocolName.empty())
XRCCTRL(*this, "ID_PROTOCOL", wxChoice)->SetStringSelection(protocolName);
else
XRCCTRL(*this, "ID_PROTOCOL", wxChoice)->SetStringSelection(CServer::GetProtocolName(FTP));
switch (m_pServer->GetLogonType())
{
case NORMAL:
XRCCTRL(*this, "ID_LOGONTYPE", wxChoice)->SetStringSelection(_("Normal"));
break;
case ASK:
XRCCTRL(*this, "ID_LOGONTYPE", wxChoice)->SetStringSelection(_("Ask for password"));
break;
case INTERACTIVE:
XRCCTRL(*this, "ID_LOGONTYPE", wxChoice)->SetStringSelection(_("Interactive"));
break;
case ACCOUNT:
XRCCTRL(*this, "ID_LOGONTYPE", wxChoice)->SetStringSelection(_("Account"));
break;
default:
XRCCTRL(*this, "ID_LOGONTYPE", wxChoice)->SetStringSelection(_("Anonymous"));
break;
}
XRCCTRL(*this, "ID_USER", wxTextCtrl)->ChangeValue(m_pServer->GetUser());
XRCCTRL(*this, "ID_ACCOUNT", wxTextCtrl)->ChangeValue(m_pServer->GetAccount());
XRCCTRL(*this, "ID_PASS", wxTextCtrl)->ChangeValue(m_pServer->GetPass());
}
else
{
XRCCTRL(*this, "ID_HOST", wxTextCtrl)->ChangeValue(_T(""));
XRCCTRL(*this, "ID_PORT", wxTextCtrl)->ChangeValue(_T(""));
XRCCTRL(*this, "ID_PROTOCOL", wxChoice)->SetStringSelection(CServer::GetProtocolName(FTP));
XRCCTRL(*this, "ID_USER", wxTextCtrl)->Enable(false);
XRCCTRL(*this, "ID_PASS", wxTextCtrl)->Enable(false);
XRCCTRL(*this, "ID_ACCOUNT", wxTextCtrl)->Enable(false);
XRCCTRL(*this, "ID_LOGONTYPE", wxChoice)->SetStringSelection(_("Anonymous"));
XRCCTRL(*this, "ID_USER", wxTextCtrl)->ChangeValue(_T(""));
XRCCTRL(*this, "ID_ACCOUNT", wxTextCtrl)->ChangeValue(_T(""));
XRCCTRL(*this, "ID_PASS", wxTextCtrl)->ChangeValue(_T(""));
}
}
void CManualTransfer::OnLocalChanged(wxCommandEvent&)
{
if (XRCCTRL(*this, "ID_DOWNLOAD", wxRadioButton)->GetValue())
return;
wxString file = XRCCTRL(*this, "ID_LOCALFILE", wxTextCtrl)->GetValue();
m_local_file_exists = fz::local_filesys::get_file_type(fz::to_native(file)) == fz::local_filesys::file;
SetAutoAsciiState();
}
void CManualTransfer::OnRemoteChanged(wxCommandEvent&)
{
SetAutoAsciiState();
}
void CManualTransfer::OnLocalBrowse(wxCommandEvent&)
{
int flags;
wxString title;
if (xrc_call(*this, "ID_DOWNLOAD", &wxRadioButton::GetValue)) {
flags = wxFD_SAVE | wxFD_OVERWRITE_PROMPT;
title = _("Select target filename");
}
else {
flags = wxFD_OPEN | wxFD_FILE_MUST_EXIST;
title = _("Select file to upload");
}
wxFileDialog dlg(this, title, _T(""), _T(""), _T("*.*"), flags);
int res = dlg.ShowModal();
if (res != wxID_OK)
return;
// SetValue on purpose
xrc_call(*this, "ID_LOCALFILE", &wxTextCtrl::SetValue, dlg.GetPath());
}
void CManualTransfer::OnDirection(wxCommandEvent& event)
{
if (xrc_call(*this, "ID_DOWNLOAD", &wxRadioButton::GetValue))
SetAutoAsciiState();
else {
// Need to check for file existence
OnLocalChanged(event);
}
}
void CManualTransfer::OnServerTypeChanged(wxCommandEvent& event)
{
if (event.GetId() == XRCID("ID_SERVER_CURRENT")) {
delete m_pServer;
if (m_pState->GetServer())
m_pServer = new CServer(*m_pState->GetServer());
else
m_pServer = 0;
}
else if (event.GetId() == XRCID("ID_SERVER_SITE")) {
delete m_pServer;
if (m_pLastSite)
m_pServer = new CServer(*m_pLastSite);
else
m_pServer = 0;
}
xrc_call(*this, "ID_SERVER_SITE_SELECT", &wxButton::Enable, event.GetId() == XRCID("ID_SERVER_SITE"));
DisplayServer();
SetServerState();
}
void CManualTransfer::OnOK(wxCommandEvent&)
{
if (!UpdateServer())
return;
bool download = xrc_call(*this, "ID_DOWNLOAD", &wxRadioButton::GetValue);
bool start = xrc_call(*this, "ID_START", &wxCheckBox::GetValue);
if (!m_pServer) {
wxMessageBoxEx(_("You need to specify a server."), _("Manual transfer"), wxICON_EXCLAMATION);
return;
}
wxString local_file = xrc_call(*this, "ID_LOCALFILE", &wxTextCtrl::GetValue);
if (local_file.empty()) {
wxMessageBoxEx(_("You need to specify a local file."), _("Manual transfer"), wxICON_EXCLAMATION);
return;
}
fz::local_filesys::type type = fz::local_filesys::get_file_type(fz::to_native(local_file));
if (type == fz::local_filesys::dir) {
wxMessageBoxEx(_("Local file is a directory instead of a regular file."), _("Manual transfer"), wxICON_EXCLAMATION);
return;
}
if (!download && type != fz::local_filesys::file && start) {
wxMessageBoxEx(_("Local file does not exist."), _("Manual transfer"), wxICON_EXCLAMATION);
return;
}
wxString remote_file = xrc_call(*this, "ID_REMOTEFILE", &wxTextCtrl::GetValue);
if (remote_file.empty()) {
wxMessageBoxEx(_("You need to specify a remote file."), _("Manual transfer"), wxICON_EXCLAMATION);
return;
}
wxString remote_path_str = xrc_call(*this, "ID_REMOTEPATH", &wxTextCtrl::GetValue);
if (remote_path_str.empty()) {
wxMessageBoxEx(_("You need to specify a remote path."), _("Manual transfer"), wxICON_EXCLAMATION);
return;
}
CServerPath path(remote_path_str, m_pServer->GetType());
if (path.empty()) {
wxMessageBoxEx(_("Remote path could not be parsed."), _("Manual transfer"), wxICON_EXCLAMATION);
return;
}
int old_data_type = COptions::Get()->GetOptionVal(OPTION_ASCIIBINARY);
// Set data type for the file to add
if (xrc_call(*this, "ID_TYPE_ASCII", &wxRadioButton::GetValue))
COptions::Get()->SetOption(OPTION_ASCIIBINARY, 1);
else if (xrc_call(*this, "ID_TYPE_BINARY", &wxRadioButton::GetValue))
COptions::Get()->SetOption(OPTION_ASCIIBINARY, 2);
else
COptions::Get()->SetOption(OPTION_ASCIIBINARY, 0);
wxString name;
CLocalPath localPath(local_file, &name);
if (name.empty()) {
wxMessageBoxEx(_("Local file is not a valid filename."), _("Manual transfer"), wxICON_EXCLAMATION);
return;
}
m_pQueueView->QueueFile(!start, download,
download ? remote_file : name,
(remote_file != name) ? (download ? name : remote_file) : wxString(),
localPath, path, *m_pServer, -1);
// Restore old data type
COptions::Get()->SetOption(OPTION_ASCIIBINARY, old_data_type);
m_pQueueView->QueueFile_Finish(start);
EndModal(wxID_OK);
}
bool CManualTransfer::UpdateServer()
{
if (!xrc_call(*this, "ID_SERVER_CUSTOM", &wxRadioButton::GetValue))
return true;
if (!VerifyServer())
return false;
CServer server;
unsigned long port;
if (!xrc_call(*this, "ID_PORT", &wxTextCtrl::GetValue).ToULong(&port)) {
return false;
}
wxString host = xrc_call(*this, "ID_HOST", &wxTextCtrl::GetValue);
// SetHost does not accept URL syntax
if (!host.empty() && host[0] == '[') {
host.RemoveLast();
host = host.Mid(1);
}
server.SetHost(host, port);
const wxString& protocolName = xrc_call(*this, "ID_PROTOCOL", &wxChoice::GetStringSelection);
const enum ServerProtocol protocol = CServer::GetProtocolFromName(protocolName);
if (protocol != UNKNOWN)
server.SetProtocol(protocol);
else
server.SetProtocol(FTP);
enum LogonType logon_type = CServer::GetLogonTypeFromName(xrc_call(*this, "ID_LOGONTYPE", &wxChoice::GetStringSelection));
server.SetLogonType(logon_type);
server.SetUser(xrc_call(*this, "ID_USER", &wxTextCtrl::GetValue),
xrc_call(*this, "ID_PASS", &wxTextCtrl::GetValue));
server.SetAccount(xrc_call(*this, "ID_ACCOUNT", &wxTextCtrl::GetValue));
delete m_pServer;
m_pServer = new CServer(server);
return true;
}
bool CManualTransfer::VerifyServer()
{
const wxString& host = xrc_call(*this, "ID_HOST", &wxTextCtrl::GetValue);
if (host.empty()) {
xrc_call(*this, "ID_HOST", &wxTextCtrl::SetFocus);
wxMessageBoxEx(_("You have to enter a hostname."));
return false;
}
enum LogonType logon_type = CServer::GetLogonTypeFromName(xrc_call(*this, "ID_LOGONTYPE", &wxChoice::GetStringSelection));
wxString protocolName = xrc_call(*this, "ID_PROTOCOL", &wxChoice::GetStringSelection);
enum ServerProtocol protocol = CServer::GetProtocolFromName(protocolName);
if (protocol == SFTP &&
logon_type == ACCOUNT)
{
xrc_call(*this, "ID_LOGONTYPE", &wxChoice::SetFocus);
wxMessageBoxEx(_("'Account' logontype not supported by selected protocol"));
return false;
}
if (COptions::Get()->GetOptionVal(OPTION_DEFAULT_KIOSKMODE) != 0 &&
(logon_type == ACCOUNT || logon_type == NORMAL))
{
xrc_call(*this, "ID_LOGONTYPE", &wxChoice::SetFocus);
wxString msg;
if (COptions::Get()->OptionFromFzDefaultsXml(OPTION_DEFAULT_KIOSKMODE))
msg = _("Saving of password has been disabled by your system administrator.");
else
msg = _("Saving of passwords has been disabled by you.");
msg += _T("\n");
msg += _("'Normal' and 'Account' logontypes are not available, using 'Ask for password' instead.");
xrc_call(*this, "ID_LOGONTYPE", &wxChoice::SetStringSelection, CServer::GetNameFromLogonType(ASK));
xrc_call(*this, "ID_PASS", &wxTextCtrl::ChangeValue, _T(""));
logon_type = ASK;
wxMessageBoxEx(msg, _("Cannot remember password"), wxICON_INFORMATION, this);
}
CServer server;
// Set selected type
server.SetLogonType(logon_type);
if (protocol != UNKNOWN)
server.SetProtocol(protocol);
CServerPath path;
wxString error;
if (!server.ParseUrl(host, xrc_call(*this, "ID_PORT", &wxTextCtrl::GetValue), wxString(), wxString(), error, path)) {
xrc_call(*this, "ID_HOST", &wxTextCtrl::SetFocus);
wxMessageBoxEx(error);
return false;
}
xrc_call(*this, "ID_HOST", &wxTextCtrl::ChangeValue, server.Format(ServerFormat::host_only));
xrc_call(*this, "ID_PORT", &wxTextCtrl::ChangeValue, wxString::Format(_T("%d"), server.GetPort()));
protocolName = CServer::GetProtocolName(server.GetProtocol());
if (protocolName.empty())
CServer::GetProtocolName(FTP);
xrc_call(*this, "ID_PROTOCOL", &wxChoice::SetStringSelection, protocolName);
// Require username for non-anonymous, non-ask logon type
const wxString user = xrc_call(*this, "ID_USER", &wxTextCtrl::GetValue);
if (logon_type != ANONYMOUS &&
logon_type != ASK &&
logon_type != INTERACTIVE &&
user.empty())
{
xrc_call(*this, "ID_USER", &wxTextCtrl::SetFocus);
wxMessageBoxEx(_("You have to specify a user name"));
return false;
}
// We don't allow username of only spaces, confuses both users and XML libraries
if (!user.empty()) {
bool space_only = true;
for (unsigned int i = 0; i < user.Len(); ++i) {
if (user[i] != ' ') {
space_only = false;
break;
}
}
if (space_only) {
xrc_call(*this, "ID_USER", &wxTextCtrl::SetFocus);
wxMessageBoxEx(_("Username cannot be a series of spaces"));
return false;
}
}
// Require account for account logon type
if (logon_type == ACCOUNT &&
xrc_call(*this, "ID_ACCOUNT", &wxTextCtrl::GetValue).empty())
{
xrc_call(*this, "ID_ACCOUNT", &wxTextCtrl::SetFocus);
wxMessageBoxEx(_("You have to enter an account name"));
return false;
}
return true;
}
void CManualTransfer::OnSelectSite(wxCommandEvent&)
{
std::unique_ptr<wxMenu> pMenu = CSiteManager::GetSitesMenu();
if (pMenu) {
PopupMenu(pMenu.get());
}
}
void CManualTransfer::OnSelectedSite(wxCommandEvent& event)
{
std::unique_ptr<CSiteManagerItemData_Site> pData = CSiteManager::GetSiteById(event.GetId());
if (!pData)
return;
delete m_pServer;
m_pServer = new CServer(pData->m_server);
delete m_pLastSite;
m_pLastSite = new CServer(pData->m_server);
xrc_call(*this, "ID_SERVER_SITE_SERVER", &wxStaticText::SetLabel, m_pServer->GetName());
DisplayServer();
}
void CManualTransfer::OnLogontypeSelChanged(wxCommandEvent& event)
{
xrc_call(*this, "ID_USER", &wxTextCtrl::Enable, event.GetString() != _("Anonymous"));
xrc_call(*this, "ID_PASS", &wxTextCtrl::Enable, event.GetString() == _("Normal") || event.GetString() == _("Account"));
xrc_call(*this, "ID_ACCOUNT", &wxTextCtrl::Enable, event.GetString() == _("Account"));
}
| llbraughler/filezilla-mod | src/interface/manual_transfer.cpp | C++ | gpl-2.0 | 17,675 |
/*
* Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package consulo.internal.com.sun.jdi;
/**
* Thrown to indicate that the requested operation cannot be
* completed because the target VM has run out of memory.
*
* @author Gordon Hirsch
* @since 1.3
*/
public class VMOutOfMemoryException extends RuntimeException {
private static final long serialVersionUID = 71504228548910686L;
public VMOutOfMemoryException() {
super();
}
public VMOutOfMemoryException(String s) {
super(s);
}
}
| consulo/jdi | lib/src/main/java/consulo/internal/com/sun/jdi/VMOutOfMemoryException.java | Java | gpl-2.0 | 1,689 |
/*
* Copyright (C) 2006-2012 David Robillard <d@drobilla.net>
* Copyright (C) 2006-2019 Paul Davis <paul@linuxaudiosystems.com>
* Copyright (C) 2007-2011 Carl Hetherington <carl@carlh.net>
* Copyright (C) 2015-2019 Robin Gareus <robin@gareus.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.
*/
#ifdef WAF_BUILD
#include "libardour-config.h"
#endif
#include "pbd/compose.h"
#include "pbd/error.h"
#include "pbd/failed_constructor.h"
#include "pbd/i18n.h"
#include "ardour/audioengine.h"
#include "ardour/debug.h"
#include "ardour/port.h"
#include "ardour/port_engine.h"
#include "ardour/rc_configuration.h"
using namespace std;
using namespace ARDOUR;
using namespace PBD;
PBD::Signal2<void,boost::shared_ptr<Port>, boost::shared_ptr<Port> > Port::PostDisconnect;
PBD::Signal0<void> Port::PortDrop;
PBD::Signal0<void> Port::PortSignalDrop;
bool Port::_connecting_blocked = false;
pframes_t Port::_global_port_buffer_offset = 0;
pframes_t Port::_cycle_nframes = 0;
double Port::_speed_ratio = 1.0;
std::string Port::state_node_name = X_("Port");
const uint32_t Port::_resampler_quality = 12;
/* a handy define to shorten what would otherwise be a needlessly verbose
* repeated phrase
*/
#define port_engine AudioEngine::instance()->port_engine()
#define port_manager AudioEngine::instance()
/** @param n Port short name */
Port::Port (std::string const & n, DataType t, PortFlags f)
: _name (n)
, _flags (f)
, _last_monitor (false)
, _externally_connected (0)
{
_private_playback_latency.min = 0;
_private_playback_latency.max = 0;
_private_capture_latency.min = 0;
_private_capture_latency.max = 0;
/* Unfortunately we have to pass the DataType into this constructor so that
we can create the right kind of port; aside from this we'll use the
virtual function type () to establish type.
*/
assert (_name.find_first_of (':') == std::string::npos);
if (!port_manager->running ()) {
DEBUG_TRACE (DEBUG::Ports, string_compose ("port-engine n/a postpone registering %1\n", name()));
_port_handle = 0; // created during ::reestablish() later
} else if ((_port_handle = port_engine.register_port (_name, t, _flags)) == 0) {
cerr << "Failed to register port \"" << _name << "\", reason is unknown from here\n";
throw failed_constructor ();
}
DEBUG_TRACE (DEBUG::Ports, string_compose ("registed port %1 handle %2\n", name(), _port_handle));
PortDrop.connect_same_thread (drop_connection, boost::bind (&Port::drop, this));
PortSignalDrop.connect_same_thread (drop_connection, boost::bind (&Port::signal_drop, this));
port_manager->PortConnectedOrDisconnected.connect_same_thread (engine_connection, boost::bind (&Port::port_connected_or_disconnected, this, _1, _3, _5));
}
/** Port destructor */
Port::~Port ()
{
DEBUG_TRACE (DEBUG::Destruction, string_compose ("destroying port @ %1 named %2\n", this, name()));
drop ();
}
std::string
Port::pretty_name(bool fallback_to_name) const
{
if (_port_handle) {
std::string value;
std::string type;
if (0 == port_engine.get_port_property (_port_handle,
"http://jackaudio.org/metadata/pretty-name",
value, type))
{
return value;
}
}
if (fallback_to_name) {
return name ();
}
return "";
}
bool
Port::set_pretty_name(const std::string& n)
{
if (_port_handle) {
if (0 == port_engine.set_port_property (_port_handle,
"http://jackaudio.org/metadata/pretty-name", n, ""))
{
return true;
}
}
return false;
}
void
Port::signal_drop ()
{
engine_connection.disconnect ();
}
void
Port::drop ()
{
if (_port_handle) {
DEBUG_TRACE (DEBUG::Ports, string_compose ("drop handle for port %1\n", name()));
port_engine.unregister_port (_port_handle);
_port_handle = 0;
}
}
void
Port::port_connected_or_disconnected (boost::weak_ptr<Port> w0, boost::weak_ptr<Port> w1, bool con)
{
if (con) {
/* we're only interested in disconnect */
return;
}
boost::shared_ptr<Port> p0 = w0.lock ();
boost::shared_ptr<Port> p1 = w1.lock ();
/* a cheaper, less hacky way to do boost::shared_from_this() ... */
boost::shared_ptr<Port> pself = AudioEngine::instance()->get_port_by_name (name());
if (p0 == pself) {
PostDisconnect (p0, p1); // emit signal
}
if (p1 == pself) {
PostDisconnect (p1, p0); // emit signal
}
}
/** @return true if this port is connected to anything */
bool
Port::connected () const
{
if (_port_handle) {
return (port_engine.connected (_port_handle) != 0);
}
return false;
}
int
Port::disconnect_all ()
{
if (_port_handle) {
std::vector<std::string> connections;
get_connections (connections);
port_engine.disconnect_all (_port_handle);
_connections.clear ();
/* a cheaper, less hacky way to do boost::shared_from_this() ...
*/
boost::shared_ptr<Port> pself = port_manager->get_port_by_name (name());
for (vector<string>::const_iterator c = connections.begin(); c != connections.end() && pself; ++c) {
boost::shared_ptr<Port> pother = AudioEngine::instance()->get_port_by_name (*c);
if (pother) {
PostDisconnect (pself, pother); // emit signal
}
}
}
return 0;
}
/** @param o Port name
* @return true if this port is connected to o, otherwise false.
*/
bool
Port::connected_to (std::string const & o) const
{
if (!_port_handle) {
return false;
}
if (!port_manager->running()) {
return false;
}
return port_engine.connected_to (_port_handle, AudioEngine::instance()->make_port_name_non_relative (o));
}
int
Port::get_connections (std::vector<std::string> & c) const
{
if (!port_manager->running()) {
c.insert (c.end(), _connections.begin(), _connections.end());
return c.size();
}
if (_port_handle) {
return port_engine.get_connections (_port_handle, c);
}
return 0;
}
int
Port::connect (std::string const & other)
{
std::string const other_name = AudioEngine::instance()->make_port_name_non_relative (other);
std::string const our_name = AudioEngine::instance()->make_port_name_non_relative (_name);
int r = 0;
if (_connecting_blocked) {
return r;
}
if (sends_output ()) {
DEBUG_TRACE (DEBUG::Ports, string_compose ("Connect %1 to %2\n", our_name, other_name));
r = port_engine.connect (our_name, other_name);
} else {
DEBUG_TRACE (DEBUG::Ports, string_compose ("Connect %1 to %2\n", other_name, our_name));
r = port_engine.connect (other_name, our_name);
}
if (r == 0) {
_connections.insert (other);
}
return r;
}
int
Port::disconnect (std::string const & other)
{
std::string const other_fullname = port_manager->make_port_name_non_relative (other);
std::string const this_fullname = port_manager->make_port_name_non_relative (_name);
int r = 0;
if (sends_output ()) {
r = port_engine.disconnect (this_fullname, other_fullname);
} else {
r = port_engine.disconnect (other_fullname, this_fullname);
}
if (r == 0) {
_connections.erase (other);
}
/* a cheaper, less hacky way to do boost::shared_from_this() ... */
boost::shared_ptr<Port> pself = AudioEngine::instance()->get_port_by_name (name());
boost::shared_ptr<Port> pother = AudioEngine::instance()->get_port_by_name (other);
if (pself && pother) {
/* Disconnecting from another Ardour port: need to allow
a check on whether this may affect anything that we
need to know about.
*/
PostDisconnect (pself, pother); // emit signal
}
return r;
}
bool
Port::connected_to (Port* o) const
{
return connected_to (o->name ());
}
int
Port::connect (Port* o)
{
return connect (o->name ());
}
int
Port::disconnect (Port* o)
{
return disconnect (o->name ());
}
void
Port::request_input_monitoring (bool yn)
{
if (_port_handle) {
port_engine.request_input_monitoring (_port_handle, yn);
}
}
void
Port::ensure_input_monitoring (bool yn)
{
if (_port_handle) {
port_engine.ensure_input_monitoring (_port_handle, yn);
}
}
bool
Port::monitoring_input () const
{
if (_port_handle) {
return port_engine.monitoring_input (_port_handle);
}
return false;
}
void
Port::reset ()
{
_last_monitor = false;
}
void
Port::cycle_start (pframes_t)
{
}
void
Port::set_public_latency_range (LatencyRange const& range, bool playback) const
{
/* this sets the visible latency that the rest of the port system
sees. because we do latency compensation, all (most) of our visible
port latency values are identical.
*/
DEBUG_TRACE (DEBUG::Latency,
string_compose ("SET PORT %1 %4 PUBLIC latency now [%2 - %3]\n",
name(), range.min, range.max,
(playback ? "PLAYBACK" : "CAPTURE")));;
if (_port_handle) {
LatencyRange r (range);
if (externally_connected ()) {
#if 0
r.min *= _speed_ratio;
r.max *= _speed_ratio;
#endif
if (type () == DataType::AUDIO) {
r.min += (_resampler_quality - 1);
r.max += (_resampler_quality - 1);
}
}
port_engine.set_latency_range (_port_handle, playback, r);
}
}
void
Port::set_private_latency_range (LatencyRange& range, bool playback)
{
if (playback) {
_private_playback_latency = range;
DEBUG_TRACE (DEBUG::Latency, string_compose (
"SET PORT %1 playback PRIVATE latency now [%2 - %3]\n",
name(),
_private_playback_latency.min,
_private_playback_latency.max));
} else {
_private_capture_latency = range;
DEBUG_TRACE (DEBUG::Latency, string_compose (
"SET PORT %1 capture PRIVATE latency now [%2 - %3]\n",
name(),
_private_capture_latency.min,
_private_capture_latency.max));
}
/* push to public (port system) location so that everyone else can see it */
set_public_latency_range (range, playback);
}
const LatencyRange&
Port::private_latency_range (bool playback) const
{
if (playback) {
DEBUG_TRACE (DEBUG::Latency, string_compose (
"GET PORT %1 playback PRIVATE latency now [%2 - %3]\n",
name(),
_private_playback_latency.min,
_private_playback_latency.max));
return _private_playback_latency;
} else {
DEBUG_TRACE (DEBUG::Latency, string_compose (
"GET PORT %1 capture PRIVATE latency now [%2 - %3]\n",
name(),
_private_playback_latency.min,
_private_playback_latency.max));
return _private_capture_latency;
}
}
LatencyRange
Port::public_latency_range (bool /*playback*/) const
{
LatencyRange r;
if (_port_handle) {
r = port_engine.get_latency_range (_port_handle, sends_output() ? true : false);
if (externally_connected ()) {
#if 0
r.min /= _speed_ratio;
r.max /= _speed_ratio;
#endif
if (type () == DataType::AUDIO) {
r.min += (_resampler_quality - 1);
r.max += (_resampler_quality - 1);
}
}
DEBUG_TRACE (DEBUG::Latency, string_compose (
"GET PORT %1: %4 PUBLIC latency range %2 .. %3\n",
name(), r.min, r.max,
sends_output() ? "PLAYBACK" : "CAPTURE"));
}
return r;
}
void
Port::get_connected_latency_range (LatencyRange& range, bool playback) const
{
vector<string> connections;
get_connections (connections);
if (!connections.empty()) {
range.min = ~((pframes_t) 0);
range.max = 0;
DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: %2 connections to check for latency range\n", name(), connections.size()));
for (vector<string>::const_iterator c = connections.begin();
c != connections.end(); ++c) {
LatencyRange lr;
if (!AudioEngine::instance()->port_is_mine (*c)) {
/* port belongs to some other port-system client, use
* the port engine to lookup its latency information.
*/
PortEngine::PortHandle remote_port = port_engine.get_port_by_name (*c);
if (remote_port) {
lr = port_engine.get_latency_range (remote_port, playback);
if (externally_connected ()) {
#if 0
lr.min /= _speed_ratio;
lr.max /= _speed_ratio;
#endif
if (type () == DataType::AUDIO) {
lr.min += (_resampler_quality - 1);
lr.max += (_resampler_quality - 1);
}
}
DEBUG_TRACE (DEBUG::Latency, string_compose (
"\t%1 <-> %2 : latter has latency range %3 .. %4\n",
name(), *c, lr.min, lr.max));
range.min = min (range.min, lr.min);
range.max = max (range.max, lr.max);
}
} else {
/* port belongs to this instance of ardour,
* so look up its latency information
* internally, because our published/public
* values already contain our plugin
* latency compensation.
*/
boost::shared_ptr<Port> remote_port = AudioEngine::instance()->get_port_by_name (*c);
if (remote_port) {
lr = remote_port->private_latency_range ((playback ? true : false));
DEBUG_TRACE (DEBUG::Latency, string_compose (
"\t%1 <-LOCAL-> %2 : latter has latency range %3 .. %4\n",
name(), *c, lr.min, lr.max));
range.min = min (range.min, lr.min);
range.max = max (range.max, lr.max);
}
}
}
} else {
DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: not connected to anything\n", name()));
range.min = 0;
range.max = 0;
}
DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: final connected latency range [ %2 .. %3 ] \n", name(), range.min, range.max));
}
int
Port::reestablish ()
{
DEBUG_TRACE (DEBUG::Ports, string_compose ("re-establish %1 port %2\n", type().to_string(), _name));
_port_handle = port_engine.register_port (_name, type(), _flags);
if (_port_handle == 0) {
PBD::error << string_compose (_("could not reregister %1"), _name) << endmsg;
return -1;
}
DEBUG_TRACE (DEBUG::Ports, string_compose ("Port::reestablish %1 handle %2\n", name(), _port_handle));
reset ();
port_manager->PortConnectedOrDisconnected.connect_same_thread (engine_connection, boost::bind (&Port::port_connected_or_disconnected, this, _1, _3, _5));
return 0;
}
int
Port::reconnect ()
{
/* caller must hold process lock; intended to be used only after reestablish() */
DEBUG_TRACE (DEBUG::Ports, string_compose ("Connect %1 to %2 destinations\n",name(), _connections.size()));
for (std::set<string>::iterator i = _connections.begin(); i != _connections.end(); ++i) {
if (connect (*i)) {
return -1;
}
}
return 0;
}
/** @param n Short port name (no port-system client name) */
int
Port::set_name (std::string const & n)
{
if (n == _name || !_port_handle) {
return 0;
}
int const r = port_engine.set_port_name (_port_handle, n);
if (r == 0) {
AudioEngine::instance()->port_renamed (_name, n);
_name = n;
}
return r;
}
bool
Port::physically_connected () const
{
if (!_port_handle) {
return false;
}
return port_engine.physically_connected (_port_handle);
}
XMLNode&
Port::get_state () const
{
XMLNode* root = new XMLNode (state_node_name);
root->set_property (X_("name"), AudioEngine::instance()->make_port_name_relative (name()));
if (receives_input()) {
root->set_property (X_("direction"), X_("input"));
} else {
root->set_property (X_("direction"), X_("output"));
}
vector<string> c;
get_connections (c);
for (vector<string>::const_iterator i = c.begin(); i != c.end(); ++i) {
XMLNode* child = new XMLNode (X_("Connection"));
child->set_property (X_("other"), *i);
root->add_child_nocopy (*child);
}
return *root;
}
int
Port::set_state (const XMLNode& node, int)
{
if (node.name() != state_node_name) {
return -1;
}
std::string str;
if (node.get_property (X_("name"), str)) {
set_name (str);
}
const XMLNodeList& children (node.children());
_connections.clear ();
for (XMLNodeList::const_iterator c = children.begin(); c != children.end(); ++c) {
if ((*c)->name() != X_("Connection")) {
continue;
}
if (!(*c)->get_property (X_("other"), str)) {
continue;
}
_connections.insert (str);
}
return 0;
}
/*static*/ void
Port::set_speed_ratio (double s) {
/* see VMResampler::set_rratio() for min/max range */
if (s == 0.0) {
/* no resampling when stopped */
_speed_ratio = 1.0;
} else {
_speed_ratio = std::min ((double) Config->get_max_transport_speed(), std::max (0.02, fabs (s)));
}
}
/*static*/ void
Port::set_cycle_samplecnt (pframes_t n)
{
_cycle_nframes = floor (n * _speed_ratio);
}
| chaot4/ardour | libs/ardour/port.cc | C++ | gpl-2.0 | 16,818 |
<?php
/**
* Record loader tests.
*
* PHP version 7
*
* Copyright (C) Villanova University 2010.
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Tests
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:testing:unit_tests Wiki
*/
namespace VuFindTest\Record;
use VuFind\Record\Cache;
use VuFind\Record\FallbackLoader\PluginManager as FallbackLoader;
use VuFind\Record\Loader;
use VuFind\RecordDriver\AbstractBase as RecordDriver;
use VuFind\RecordDriver\PluginManager as RecordFactory;
use VuFindSearch\ParamBag;
use VuFindSearch\Response\RecordCollectionInterface;
use VuFindSearch\Service as SearchService;
use VuFindTest\Unit\TestCase as TestCase;
/**
* Record loader tests.
*
* @category VuFind
* @package Tests
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:testing:unit_tests Wiki
*/
class LoaderTest extends TestCase
{
/**
* Test exception for missing record.
*
* @return void
*
*/
public function testMissingRecord()
{
$this->expectException(\VuFind\Exception\RecordMissing::class);
$this->expectExceptionMessage('Record Solr:test does not exist.');
$collection = $this->getCollection([]);
$service = $this->createMock(\VuFindSearch\Service::class);
$service->expects($this->once())->method('retrieve')
->with($this->equalTo('Solr'), $this->equalTo('test'))
->will($this->returnValue($collection));
$loader = $this->getLoader($service);
$loader->load('test');
}
/**
* Test that the fallback loader gets called successfully for a missing record.
*
* @return void
*/
public function testMissingRecordWithFallback()
{
$collection = $this->getCollection([]);
$service = $this->createMock(\VuFindSearch\Service::class);
$service->expects($this->once())->method('retrieve')
->with($this->equalTo('Summon'), $this->equalTo('test'))
->will($this->returnValue($collection));
$driver = $this->getDriver();
$fallbackLoader = $this->getFallbackLoader([$driver]);
$loader = $this->getLoader($service, null, null, $fallbackLoader);
$this->assertEquals($driver, $loader->load('test', 'Summon'));
}
/**
* Test "tolerate missing records" feature.
*
* @return void
*/
public function testToleratedMissingRecord()
{
$collection = $this->getCollection([]);
$service = $this->createMock(\VuFindSearch\Service::class);
$service->expects($this->once())->method('retrieve')
->with($this->equalTo('Solr'), $this->equalTo('test'))
->will($this->returnValue($collection));
$missing = $this->getDriver('missing', 'Missing');
$factory = $this->createMock(\VuFind\RecordDriver\PluginManager::class);
$factory->expects($this->once())->method('get')
->with($this->equalTo('Missing'))
->will($this->returnValue($missing));
$loader = $this->getLoader($service, $factory);
$record = $loader->load('test', 'Solr', true);
$this->assertEquals($missing, $record);
}
/**
* Test single record.
*
* @return void
*/
public function testSingleRecord()
{
$driver = $this->getDriver();
$collection = $this->getCollection([$driver]);
$service = $this->createMock(\VuFindSearch\Service::class);
$service->expects($this->once())->method('retrieve')
->with($this->equalTo('Solr'), $this->equalTo('test'))
->will($this->returnValue($collection));
$loader = $this->getLoader($service);
$this->assertEquals($driver, $loader->load('test'));
}
/**
* Test single record with backend parameters.
*
* @return void
*/
public function testSingleRecordWithBackendParameters()
{
$params = new ParamBag();
$params->set('fq', 'id:test');
$driver = $this->getDriver();
$collection = $this->getCollection([$driver]);
$service = $this->createMock(\VuFindSearch\Service::class);
$service->expects($this->once())->method('retrieve')
->with(
$this->equalTo('Solr'),
$this->equalTo('test'),
$this->equalTo($params)
)
->will($this->returnValue($collection));
$loader = $this->getLoader($service);
$this->assertEquals($driver, $loader->load('test', 'Solr', false, $params));
}
/**
* Test batch load.
*
* @return void
*/
public function testBatchLoad()
{
$driver1 = $this->getDriver('test1', 'Solr');
$driver2 = $this->getDriver('test2', 'Solr');
$driver3 = $this->getDriver('test3', 'Summon');
$missing = $this->getDriver('missing', 'Missing');
$collection1 = $this->getCollection([$driver1, $driver2]);
$collection2 = $this->getCollection([$driver3]);
$collection3 = $this->getCollection([]);
$solrParams = new ParamBag();
$solrParams->set('fq', 'id:test1');
$worldCatParams = new ParamBag();
$worldCatParams->set('fq', 'id:test4');
$factory = $this->createMock(\VuFind\RecordDriver\PluginManager::class);
$factory->expects($this->once())->method('get')
->with($this->equalTo('Missing'))
->will($this->returnValue($missing));
$service = $this->createMock(\VuFindSearch\Service::class);
$service->expects($this->at(0))->method('retrieveBatch')
->with(
$this->equalTo('Solr'), $this->equalTo(['test1', 'test2']),
$this->equalTo($solrParams)
)
->will($this->returnValue($collection1));
$service->expects($this->at(1))->method('retrieveBatch')
->with(
$this->equalTo('Summon'), $this->equalTo(['test3']),
$this->equalTo(null)
)
->will($this->returnValue($collection2));
$service->expects($this->at(2))->method('retrieveBatch')
->with(
$this->equalTo('WorldCat'), $this->equalTo(['test4']),
$this->equalTo($worldCatParams)
)
->will($this->returnValue($collection3));
$loader = $this->getLoader($service, $factory);
$input = [
['source' => 'Solr', 'id' => 'test1'],
'Solr|test2', 'Summon|test3', 'WorldCat|test4'
];
$this->assertEquals(
[$driver1, $driver2, $driver3, $missing],
$loader->loadBatch(
$input, false, ['Solr' => $solrParams, 'WorldCat' => $worldCatParams]
)
);
}
/**
* Test batch load with fallback loader.
*
* @return void
*/
public function testBatchLoadWithFallback()
{
$driver1 = $this->getDriver('test1', 'Solr');
$driver2 = $this->getDriver('test2', 'Solr');
$driver3 = $this->getDriver('test3', 'Summon');
$collection1 = $this->getCollection([$driver1, $driver2]);
$collection2 = $this->getCollection([]);
$solrParams = new ParamBag();
$solrParams->set('fq', 'id:test1');
$service = $this->createMock(\VuFindSearch\Service::class);
$service->expects($this->at(0))->method('retrieveBatch')
->with(
$this->equalTo('Solr'), $this->equalTo(['test1', 'test2']),
$this->equalTo($solrParams)
)
->will($this->returnValue($collection1));
$service->expects($this->at(1))->method('retrieveBatch')
->with(
$this->equalTo('Summon'), $this->equalTo(['test3']),
$this->equalTo(null)
)
->will($this->returnValue($collection2));
$fallbackLoader = $this->getFallbackLoader([$driver3]);
$loader = $this->getLoader($service, null, null, $fallbackLoader);
$input = [
['source' => 'Solr', 'id' => 'test1'],
'Solr|test2', 'Summon|test3'
];
$this->assertEquals(
[$driver1, $driver2, $driver3],
$loader->loadBatch(
$input, false, ['Solr' => $solrParams]
)
);
}
/**
* Get test record driver object
*
* @param string $id Record ID
* @param string $source Record source
*
* @return RecordDriver
*/
protected function getDriver($id = 'test', $source = 'Solr')
{
$driver = $this->createMock(\VuFind\RecordDriver\AbstractBase::class);
$driver->expects($this->any())->method('getUniqueId')
->will($this->returnValue($id));
$driver->expects($this->any())->method('getSourceIdentifier')
->will($this->returnValue($source));
return $driver;
}
/**
* Build a loader to test.
*
* @param SearchService $service Search service
* @param RecordFactory $factory Record factory (optional)
* @param Cache $recordCache Record Cache
* @param FallbackLoader $fallbackLoader Fallback record loader
*
* @return Loader
*/
protected function getLoader(SearchService $service,
RecordFactory $factory = null, Cache $recordCache = null,
FallbackLoader $fallbackLoader = null
) {
if (null === $factory) {
$factory = $this->createMock(\VuFind\RecordDriver\PluginManager::class);
}
return new Loader($service, $factory, $recordCache, $fallbackLoader);
}
/**
* Get a fallback loader (currently assumes Summon plugin will be used).
*
* @param array $records Records to return from the fallback plugin
*
* @return FallbackLoader
*/
protected function getFallbackLoader($records)
{
$fallbackPlugin = $this
->getMockBuilder(\VuFind\Record\FallbackLoader\Summon::class)
->disableOriginalConstructor()
->setMethods(['load'])
->getMock();
$callback = function ($r) {
return $r->getUniqueId();
};
$expectedIds = array_map($callback, $records);
$fallbackPlugin->expects($this->once())->method('load')
->with($this->equalTo($expectedIds))
->will($this->returnValue($records));
$fallbackLoader = $this->getMockBuilder(FallbackLoader::class)
->disableOriginalConstructor()
->setMethods(['get', 'has'])
->getMock();
$fallbackLoader->expects($this->once())->method('has')
->with($this->equalTo('Summon'))
->will($this->returnValue(true));
$fallbackLoader->expects($this->once())->method('get')
->with($this->equalTo('Summon'))
->will($this->returnValue($fallbackPlugin));
return $fallbackLoader;
}
/**
* Get a fake record collection.
*
* @param array $records Record(s) to retrieve
*
* @return RecordCollectionInterface
*/
protected function getCollection($records)
{
$collection = $this->createMock(\VuFindSearch\Response\RecordCollectionInterface::class);
$collection->expects($this->any())->method('getRecords')->will($this->returnValue($records));
$collection->expects($this->any())->method('count')->will($this->returnValue(count($records)));
return $collection;
}
}
| crhallberg/vufind | module/VuFind/tests/unit-tests/src/VuFindTest/Record/LoaderTest.php | PHP | gpl-2.0 | 12,380 |
# Copyright (C) 1991-2014 Free Software Foundation, Inc.
# This file is part of the GNU C Library.
# The GNU C Library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# The GNU C Library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with the GNU C Library; if not, see
# <http://www.gnu.org/licenses/>.
#
# Sub-makefile for misc portion of the library.
#
# Some system-dependent implementations of these functions use option
# groups (see sysdeps/unix/sysv/linux/Makefile, for example).
include ../option-groups.mak
subdir := misc
headers := sys/uio.h bits/uio.h sys/ioctl.h bits/ioctls.h bits/ioctl-types.h \
sys/ptrace.h sys/file.h sys/dir.h sys/cdefs.h \
ar.h a.out.h libgen.h stab.h bits/stab.def sgtty.h \
ttyent.h paths.h sys/reboot.h \
sys/mman.h sys/param.h bits/param.h \
fstab.h mntent.h search.h err.h error.h \
sys/queue.h sysexits.h syscall.h sys/syscall.h sys/swap.h \
sys/select.h ustat.h sys/ustat.h bits/ustat.h sys/sysinfo.h \
regexp.h bits/select.h bits/mman.h sys/xattr.h \
syslog.h sys/syslog.h \
bits/syslog.h bits/syslog-ldbl.h bits/syslog-path.h bits/error.h \
bits/select2.h bits/hwcap.h sys/auxv.h
routines := brk sbrk sstk ioctl \
readv writev preadv preadv64 pwritev pwritev64 \
setreuid setregid \
seteuid setegid \
getpagesize \
getdtsz \
gethostname sethostname getdomain setdomain \
select pselect \
acct chroot fsync sync fdatasync syncfs reboot \
gethostid sethostid \
vhangup \
swapon swapoff mktemp mkstemp mkstemp64 mkdtemp \
mkostemp mkostemp64 mkstemps mkstemps64 mkostemps mkostemps64 \
ualarm usleep \
gtty stty \
ptrace \
mntent mntent_r \
utimes lutimes futimes futimesat \
truncate ftruncate truncate64 ftruncate64 \
insremque getttyent getusershell getpass ttyslot \
syslog syscall daemon \
mmap mmap64 munmap mprotect msync madvise mincore remap_file_pages\
mlock munlock mlockall munlockall \
hsearch hsearch_r tsearch lsearch \
err error ustat \
getsysstats dirname \
getloadavg getclktck \
fgetxattr flistxattr fremovexattr fsetxattr getxattr \
listxattr lgetxattr llistxattr lremovexattr lsetxattr \
removexattr setxattr getauxval ifunc-impl-list
routines-$(OPTION_POSIX_REGEXP) += regexp
routines-$(OPTION_EGLIBC_FSTAB) += fstab
routines-$(OPTION_EGLIBC_BSD) += chflags fchflags revoke
routines-$(OPTION_EGLIBC_FCVT) += efgcvt efgcvt_r qefgcvt qefgcvt_r
generated := tst-error1.mtrace tst-error1-mem
include ../Makeconfig
aux := init-misc
install-lib := libg.a
gpl2lgpl := error.c error.h
tests := tst-dirname tst-tsearch tst-fdset tst-mntent tst-hsearch \
tst-pselect tst-insremque tst-mntent2 bug-hsearch1
tests-$(OPTION_POSIX_WIDE_CHAR_DEVICE_IO) += tst-error1
tests-$(OPTION_EGLIBC_FCVT) += tst-efgcvt
ifeq ($(run-built-tests),yes)
ifeq (y,$(OPTION_POSIX_WIDE_CHAR_DEVICE_IO))
tests: $(objpfx)tst-error1-mem
endif
endif
CFLAGS-select.c = -fexceptions -fasynchronous-unwind-tables
CFLAGS-tsearch.c = $(uses-callbacks)
CFLAGS-lsearch.c = $(uses-callbacks)
CFLAGS-pselect.c = -fexceptions
CFLAGS-readv.c = -fexceptions -fasynchronous-unwind-tables
CFLAGS-writev.c = -fexceptions -fasynchronous-unwind-tables
CFLAGS-usleep.c = -fexceptions
CFLAGS-syslog.c = -fexceptions
CFLAGS-error.c = -fexceptions
CFLAGS-getpass.c = -fexceptions
CFLAGS-mkstemp.c = -fexceptions
CFLAGS-mkstemp64.c = -fexceptions
CFLAGS-getsysstats.c = -fexceptions
CFLAGS-getusershell.c = -fexceptions
CFLAGS-err.c = -fexceptions
CFLAGS-tst-tsearch.c = $(stack-align-test-flags)
include ../Rules
$(objpfx)libg.a: $(dep-dummy-lib); $(make-dummy-lib)
ifeq ($(build-shared),yes)
$(objpfx)tst-tsearch: $(common-objpfx)math/libm.so$(libm.so-version)
else
$(objpfx)tst-tsearch: $(common-objpfx)math/libm.a
endif
tst-error1-ENV = MALLOC_TRACE=$(objpfx)tst-error1.mtrace
tst-error1-ARGS = $(objpfx)tst-error1.out
$(objpfx)tst-error1-mem: $(objpfx)tst-error1.out
$(common-objpfx)malloc/mtrace $(objpfx)tst-error1.mtrace > $@
| n1koo/eglibc-trusty | .pc/kfreebsd/submitted-auxv.diff/misc/Makefile | Makefile | gpl-2.0 | 4,513 |
/*
Copyright 2011 Alexander Peyser & Wolfgang Nonner
This file is part of Deuterostome.
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/>.
*/
/*===================== D Machine 3.0 (dsp2.c) =============================
- digital signal processing and math operators
- complexFFT
- realFFT
- sineFFT
- decompLU
- backsubLU
- invertLU
- matmul
- mattranspose
- matvecmul
*/
#include "dm.h"
#include "threads.h"
#include "dmnum.h"
#include <inttypes.h>
#include <stdio.h>
#include "dsp2def.h"
/*------------------------------ internal library ---------------------------*/
/*--------------------------------------- FFT: complex-> complex
(Press et al, page 507)
data - on input: alternating real and imaginary parts
_ on return: alternating real and imaginary parts of transform,
starting at 0 freq
nn - # of complex points in data (must be power of 2)
dir - 1: forward transform
-1: inverse transform (note: results NOT divided by nn)
NOTE: call with 'data' pointing one below the first element
*/
#define SWAP(a,b) do {tempr = (a); (a) = (b); (b) = tempr;} while (0)
#define TwoPi 6.28318530717959
#define Pi 3.141592653589793
DM_INLINE_STATIC void four1(D *data, L32 nn, LBIG dir)
{
L32 n, mmax, m, j, istep, i;
D wtemp, wr, wpr, wpi, wi, theta, tempr, tempi;
n = nn << 1;
j = 1;
for (i=1; i<n; i+=2) {
if (j>i) {
SWAP(data[j],data[i]);
SWAP(data[j+1],data[i+1]);
}
m = n>>1;
while (m>=2 && j>m) {
j -= m;
m >>= 1;
}
j += m;
}
mmax = 2;
while (n>mmax) {
istep = mmax<<1;
theta = dir * (TwoPi/mmax);
wtemp = sin(0.5 * theta);
wpr = -2.0 * wtemp * wtemp;
wpi = sin(theta);
wr = 1.0;
wi = 0.0;
for (m=1; m<mmax; m+=2) {
for (i=m; i<=n; i+=istep) {
j = i + mmax;
tempr = wr * data[j] - wi * data[j+1];
tempi = wr * data[j+1] + wi * data[j];
data[j] = data[i] - tempr;
data[j+1] = data[i+1] - tempi;
data[i] += tempr;
data[i+1] += tempi;
}
wr = (wtemp=wr) * wpr - wi * wpi + wr;
wi = wi * wpr + wtemp * wpi + wi;
}
mmax = istep;
}
}
/*------------------------------------ FFT: one real -> complex
(Press et al., page 513)
data - on input: real parts
_ on return: element 0 and 1 are the real first and last spectrum
points; the other elements contain alternating real and imaginary
parts
n - # of real points in data (must be power of 2)
dir - 1: forward transform
-1: inverse transform (note: results NOT divided by n/2)
NOTE: call with 'data' pointing one below the first element
*/
DM_INLINE_STATIC void realft(D *data, L32 n, LBIG dir)
{
L32 i, i1, i2, i3, i4, np3;
D c1, c2, h1r, h1i, h2r, h2i, wr, wi, wpr, wpi, wtemp, theta;
c1 = 0.5;
theta = Pi / (D)(n>>1);
if (dir == 1) {
c2 = -0.5;
four1(data,n>>1,1);
}
else {
c2 = 0.5;
theta = -theta;
}
wtemp = sin(0.5 * theta);
wpr = -2.0 * wtemp * wtemp;
wpi = sin(theta);
wr = 1.0 + wpr;
wi = wpi;
np3 = n + 3;
for (i=2; i<=(n>>2); i++) {
i4 = 1 + ( i3 = np3 - ( i2 = 1 + (i1 = i + i - 1)));
h1r = c1 * (data[i1] + data[i3]);
h1i = c1 * (data[i2] - data[i4]);
h2r = -c2 * (data[i2] + data[i4]);
h2i = c2 * (data[i1] - data[i3]);
data[i1] = h1r + wr * h2r - wi * h2i;
data[i2] = h1i + wr * h2i + wi * h2r;
data[i3] = h1r - wr * h2r + wi * h2i;
data[i4] = -h1i + wr * h2i + wi * h2r;
wr = (wtemp = wr) * wpr - wi * wpi + wr;
wi = wi * wpr + wtemp * wpi + wi;
}
if (dir == 1) {
data[1] = (h1r = data[1]) + data[2];
data[2] = h1r - data[2];
}
else {
data[1] = c1 * ((h1r = data[1]) + data[2]);
data[2] = c1 * (h1r - data[2]);
four1(data, n>>1, -1);
}
}
/*---------------------------------------- FFT: sine
(Press et al., page 517)
- data is a double array of length N where N is a power of 2
- on input, data contains the real data to be forward-transformed or
sine-spectrum to be backtransformed
- on return data contains the real amplitudes of the sine spectrum or
the real data
- this function effects both forward and inverse transforms, but
NOTE: the inverse transform does NOT divide the result by N/2
*/
DM_INLINE_STATIC void sinft(D *y, L32 n)
{
L32 j, n2;
D sum, y1, y2, theta, wi, wr, wpi, wpr, wtemp;
n2 = n + 2;
wi = 0.0;
wr = 1.0;
theta = Pi/ (D)n;
wtemp = sin(0.5 * theta);
wpr = -2.0 * wtemp * wtemp;
wpi = sin(theta);
y[1] = 0.0;
for (j=2; j<=(n>>1)+1; j++) {
wr = (wtemp = wr) * wpr - wi * wpi + wr;
wi = wi * wpr + wtemp * wpi + wi;
y1 = wi * (y[j] + y[n2-j]);
y2 = 0.5 * (y[j] - y[n2-j]);
y[j] = y1 + y2;
y[n2-j] = y1 - y2;
}
realft(y,n,1);
y[1] *= 0.5;
sum = y[2] = 0.0;
for (j=1; j<=n-1; j+=2) {
sum += y[j];
y[j] = y[j+1];
y[j+1] = sum;
}
}
/*------------------------------------------------------ LU decomposition
(Press et al., page 46
*/
DM_INLINE_STATIC BOOLEAN ludcmp(D **a, L32 n, L32 *indx, D *d, D *vv)
{
L32 i, imax = 0, j, k;
D big, dum, sum, temp, TINY;
TINY = 1e-20;
*d = 1.0;
for (i=1; i<=n; i++) {
big = 0.0;
for (j=1; j<=n; j++) if ((temp = fabs(a[i][j])) > big) big = temp;
if (big == 0.0) return FALSE;
vv[i] = 1.0 / big;
}
for (j=1; j<=n; j++) {
for (i=1; i<j; i++) {
sum = a[i][j];
for (k=1; k<i; k++) sum -= a[i][k] * a[k][j];
a[i][j] = sum;
}
big = 0.0;
for (i=j; i<=n; i++) {
sum = a[i][j];
for (k=1; k<j; k++) sum -= a[i][k] * a[k][j];
a[i][j] = sum;
if ((dum = vv[i] * fabs(sum)) >= big) {
big = dum;
imax = i;
}
}
if (j != imax) {
for (k=1; k<=n; k++) {
dum = a[imax][k];
a[imax][k] = a[j][k];
a[j][k] = dum;
}
*d = -(*d);
vv[imax] = vv[j];
}
indx[j] = imax;
if (a[j][j] == 0.0) a[j][j] = TINY;
if (j != n) {
dum = 1.0 / a[j][j];
for (i=j+1; i<=n; i++) a[i][j] *= dum;
}
}
return TRUE;
}
/*------------------------------------------------------ LU backsubstitution
(Press et al., page 47)
*/
DM_INLINE_STATIC void lubksb(D **a, L32 n, L32 *indx, D *b)
{
L32 i, ii, ip, j;
D sum;
ii = 0;
for (i=1; i<=n; i++) {
ip = indx[i];
sum = b[ip];
b[ip] = b[i];
if (ii) for (j=ii; j<=i-1; j++) sum -= a[i][j] * b[j];
else if (sum) ii=i;
b[i] = sum;
}
for (i=n; i>=1; i--) {
sum = b[i];
for (j=i+1; j<=n; j++) sum -= a[i][j] * b[j];
b[i] = sum / a[i][i];
}
}
/*---------------------------------------------------- complexFFT
data dir | data
- data is a double array of length 2N where N is a power of 2
- on input, data contains the complex (alternating real, imaginary parts) of
the data to be transformed
- on return data contains the results of the transform (alternating real,
imaginary parts, in order)
- dir controls the transform: 1 - forward; -1 - inverse
- two successive transforms give the original data
*/
P op_complexFFT(void)
{
L32 N2, logN2, j;
LBIG dir;
D f, *data;
if (o_2 < FLOORopds) return OPDS_UNF;
if ((TAG(o_2) != (ARRAY | DOUBLETYPE)) || (CLASS(o_1) != NUM))
return OPD_CLA;
N2 = ARRAY_SIZE(o_2);
logN2 = 0;
while ((N2 >>= 1) > 0) logN2 += 1;
if ((N2 = ARRAY_SIZE(o_2)) != (1 << logN2)) return RNG_CHK;
if (!VALUE(o_1,&dir)) return UNDF_VAL;
if (imaxabs(dir) != 1) return RNG_CHK;
four1((data = ((D*) VALUE_PTR(o_2))) - 1, N2>>1, dir);
if (dir == -1) {
f = 2.0 / N2;
for (j=0; j<N2; j++) data[j] *= f;
}
FREEopds = o_1;
return OK;
}
/*---------------------------------------------------- realFFT
data dir | data
- data is a double array of length N where N is a power of 2
- on input, data contains the real data to be forward-transformed or the
complex spectrum (in format described under 'return') for the backtransform
- on return' data contains the results of the forward transform (real parts of
first and last spectral point, then alternating real, imaginary parts; only
the positive half of the spectrum is returned because of symmetry) or the
real results of the backtransform)
- dir controls the transform: 1 - forward; -1 - inverse
- successive forward and inverse transforms yield the original data
*/
P op_realFFT(void)
{
L32 N, logN, j;
LBIG dir;
D f, *data;
if (o_2 < FLOORopds) return OPDS_UNF;
if ((TAG(o_2) != (ARRAY | DOUBLETYPE)) || (CLASS(o_1) != NUM))
return OPD_CLA;
N = ARRAY_SIZE(o_2);
logN = 0;
while ((N >>= 1) > 0) logN += 1;
if ((N = ARRAY_SIZE(o_2)) != (1 << logN)) return RNG_CHK;
if (! VALUE(o_1,&dir)) return UNDF_VAL;
if (imaxabs(dir) != 1) return RNG_CHK;
realft((data = ((D*) VALUE_PTR(o_2))) - 1, N, dir);
if (dir == -1) {
f = 2.0 / N;
for (j=0; j<N; j++) data[j] *= f;
}
FREEopds = o_1;
return OK;
}
/*---------------------------------------------------- sineFFT
data dir | data
- data is a double array of length N where N is a power of 2
- on input, data contains the real data to be forward-transformed or
sine-spectrum to be backtransformed
- on return data contains the real amplitudes of the sine spectrum or
the real data
- dir defines the transform: 1 - forward, -1 - inverse
*/
P op_sineFFT(void)
{
L32 N, logN, j;
LBIG dir;
D f, *data;
if (o_2 < FLOORopds) return OPDS_UNF;
if ((TAG(o_2) != (ARRAY | DOUBLETYPE)) || (CLASS(o_1) != NUM))
return (OPD_CLA);
N = ARRAY_SIZE(o_2);
logN = 0;
while ((N >>= 1) > 0) logN += 1;
if ((N = ARRAY_SIZE(o_2)) != (1 << logN)) return RNG_CHK;
if (!VALUE(o_1, &dir)) return UNDF_VAL;
if (imaxabs(dir) != 1) return RNG_CHK;
sinft((data = ((D*) VALUE_PTR(o_2))) - 1, N);
if (dir == -1) {
f = 2.0 / N;
for (j=0; j<N; j++) data[j] *= f;
}
FREEopds = o_1;
return OK;
}
/*-------------------------------------------------------- decompLU
a_list idx_array | d true
| false
- a_list is a list of double row arrays containing
on input: the matrix to be decomposed
on return: the decomposed matrix
- idx_array is long and receives row permutation info for backsubLU
- d signals even/odd number of permutations for backsubLU
- returns false upon detecting singular matrix
*/
P op_decompLU(void)
{
L32 N, k;
L32 *idxp;
B *fp;
D **ap, *vec, d;
if (o_2 < FLOORopds) return OPDS_UNF;
if (CLASS(o_2) != LIST) return OPD_CLA;
N = (LIST_CEIL(o_2) - VALUE_BASE(o_2)) / FRAMEBYTES;
if (N<=0) return RNG_CHK;
if (FREEvm + DALIGN(N * sizeof(D *)) + N * sizeof(D) > CEILvm)
return VM_OVF;
ap = (D **)FREEvm;
fp = (B *)VALUE_BASE(o_2);
for (k=0; k<N; k++) {
if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (ARRAY_SIZE(fp) != N) return RNG_CHK;
*(ap++) = ((D *)VALUE_BASE(fp)) - 1;
fp += FRAMEBYTES;
}
vec = (D *)DALIGN(ap);
if (TAG(o_1) != (ARRAY | LONG32TYPE)) return OPD_ERR;
if (ARRAY_SIZE(o_1) != N) return RNG_CHK;
idxp = (L32 *)VALUE_BASE(o_1);
if (ludcmp(((D **)FREEvm)-1, N, idxp-1, &d, vec-1)) {
TAG(o_2) = NUM | DOUBLETYPE;
*((D *)(NUM_VAL(o_2))) = d;
TAG(o_1) = BOOL; BOOL_VAL(o_1) = TRUE;
}
else {
TAG(o_2) = BOOL; BOOL_VAL(o_2) = FALSE;
FREEopds = o_1;
}
return OK;
}
/*-------------------------------------------------------- backsubLU
a_list idx_array b_array | b_array
- a_list is a list of double row arrays containing a previously
LU-decomposed matrix
- idx_array is long and provides the permutation info of the previous
decomposition
- b inputs the right-hand side for which the eqn system is to be solved
and returns the solution
*/
P op_backsubLU(void)
{
L32 N, k;
L32 *idxp;
B *fp;
D **ap, *bp;
if (o_3 < FLOORopds) return OPDS_UNF;
if ( CLASS(o_3) != LIST) return OPD_CLA;
N = (LIST_CEIL(o_3) - VALUE_BASE(o_3)) / FRAMEBYTES;
if (N<=0) return RNG_CHK;
if (FREEvm + N * sizeof(D *) > CEILvm) return VM_OVF;
ap = (D **)FREEvm; fp = (B *)VALUE_BASE(o_3);
for (k=0; k<N; k++) {
if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (ARRAY_SIZE(fp) != N) return RNG_CHK;
*(ap++) = ((D *)VALUE_BASE(fp)) - 1;
fp += FRAMEBYTES;
}
if (TAG(o_2) != (ARRAY | LONG32TYPE)) return OPD_ERR;
if (ARRAY_SIZE(o_2) != N) return RNG_CHK;
idxp = (L32 *)VALUE_BASE(o_2);
if (TAG(o_1) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (ARRAY_SIZE(o_1) != N) return RNG_CHK;
bp = (D *)VALUE_BASE(o_1);
lubksb(((D **)FREEvm)-1, N, idxp-1, bp-1);
moveframe(o_1,o_3);
FREEopds = o_2;
return OK;
}
/*-------------------------------------------------------- invertLU
a_list idx_array a_1_list | a_1_list true
| false
- a_list is a list of double row arrays containing
on input: the matrix to be decomposed
on return: the decomposed matrix
- idx_array is long and receives row permutation info (e.g., for backsubLU)
- returns false upon detecting singular matrix
*/
P op_invertLU(void)
{
L32 N, k, i, j;
L32 *idxp;
B *fp;
D **ap, **a1p, *vec, d;
if (o_3 < FLOORopds) return OPDS_UNF;
if ( CLASS(o_3) != LIST) return OPD_CLA;
N = (LIST_CEIL(o_3) - VALUE_BASE(o_3)) / FRAMEBYTES;
if (N<=0) return RNG_CHK;
if (CLASS(o_1) != LIST) return OPD_CLA;
if (N != (LIST_CEIL(o_1) - VALUE_BASE(o_1)) / FRAMEBYTES) return RNG_CHK;
if (FREEvm + DALIGN(N * (2 * sizeof(D *)) + N * sizeof(D)) > CEILvm)
return VM_OVF;
ap = (D **)FREEvm;
fp = (B *)VALUE_BASE(o_3);
for (k=0; k<N; k++) { if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (ARRAY_SIZE(fp) != N) return RNG_CHK;
*(ap++) = ((D *)VALUE_BASE(fp)) - 1;
fp += FRAMEBYTES;
}
a1p = ap;
fp = (B *)VALUE_BASE(o_1);
for (k=0; k<N; k++) {
if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (ARRAY_SIZE(fp) != N) return RNG_CHK;
*(ap++) = ((D *)VALUE_BASE(fp)) - 1;
fp += FRAMEBYTES;
}
vec = (D *)DALIGN(ap)-1;
if (TAG(o_2) != (ARRAY | LONG32TYPE)) return OPD_ERR;
if (ARRAY_SIZE(o_2) != N) return RNG_CHK;
idxp = (L32 *)VALUE_BASE(o_2)-1;
if (ludcmp(((D **)FREEvm)-1, N, idxp, &d, vec)) {
for (j=1; j<=N; j++) {
for (i=1; i<=N; i++) vec[i] = 0.0;
vec[j] = 1.0;
lubksb(((D **)FREEvm)-1, N, idxp, vec);
for (i=1; i<=N; i++)
(a1p-1)[i][j] = vec[i];
}
moveframe(o_1,o_3);
TAG(o_2) = BOOL; BOOL_VAL(o_2) = TRUE;
FREEopds = o_1;
}
else {
TAG(o_3) = BOOL; BOOL_VAL(o_3) = FALSE;
FREEopds = o_2;
}
return OK;
}
/*----------------------------------------------- matmul
c a b | c a * b -> c
- each argument is a list of row vectors
- number of columns in a equals number of rows in b
- in c, the number of rows is the same as that in a, and the
number of columns is the same as that in b
*/
#if ENABLE_THREADS
typedef struct {
L32 Ncolc, Ncola;
D *restrict *restrict ap,
*restrict *restrict bp,
*restrict *restrict cp;
UL32 perthread;
UL32 leftover;
} matmult;
P thread_matmul(UL32 id, const void* global,
void* local __attribute__ ((__unused__))) {
const matmult* restrict m = (const matmult*) global;
UL32 n = m->perthread + (thread_max() == id ? m->leftover : 0);
UL32 i_ = m->perthread*id;
UL32 i, j;
for (i = i_; i < i_ + n; i++)
for (j = 0; j < (UL32) m->Ncolc; j++)
MATMUL_INNER(m->Ncola, m->ap, m->bp, m->cp);
return OK;
}
#endif
P op_matmul(void)
{
UL32 Nrowa, Nrowb, Nrowc, Ncola , Ncolb, Ncolc, i, j, k;
B *fp;
D **p, **ap, **bp, **cp;
#if ENABLE_THREADS
UL32 nways;
#endif
if (o_3 < FLOORopds) return OPDS_UNF;
if (CLASS(o_3) != LIST) return OPD_CLA;
if (ATTR(o_3) & READONLY) return OPD_ATR;
Nrowc = (LIST_CEIL(o_3) - VALUE_BASE(o_3)) / FRAMEBYTES;
if ( CLASS(o_2) != LIST) return OPD_CLA;
Nrowa = (LIST_CEIL(o_2) - VALUE_BASE(o_2)) / FRAMEBYTES;
if ( CLASS(o_1) != LIST) return OPD_CLA;
Nrowb = (LIST_CEIL(o_1) - VALUE_BASE(o_1)) / FRAMEBYTES;
if ((FREEvm + (Nrowc + Nrowa + Nrowb) * sizeof(D *)) > CEILvm)
return VM_OVF;
cp = p = (D **)FREEvm;
fp = (B *)VALUE_BASE(o_3);
Ncolc = 0;
for (k=0; k<Nrowc; k++) {
if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (Ncolc == 0) Ncolc = ARRAY_SIZE(fp);
else if ((UL32) ARRAY_SIZE(fp) != Ncolc) return RNG_CHK;
*(p++) = ((D *)VALUE_BASE(fp));
fp += FRAMEBYTES;
}
ap = p;
fp = (B *)VALUE_BASE(o_2);
Ncola = 0;
for (k=0; k<Nrowa; k++) {
if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (Ncola == 0) Ncola = ARRAY_SIZE(fp);
else if ((UL32) ARRAY_SIZE(fp) != Ncola) return RNG_CHK;
*(p++) = ((D *) VALUE_BASE(fp));
fp += FRAMEBYTES;
}
bp = p;
fp = (B *)VALUE_BASE(o_1);
Ncolb = 0;
for (k=0; k<Nrowb; k++) {
if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (Ncolb == 0) Ncolb = ARRAY_SIZE(fp);
else if ((UL32) ARRAY_SIZE(fp) != Ncolb) return RNG_CHK;
*(p++) = ((D*) VALUE_BASE(fp));
fp += FRAMEBYTES;
}
if ((Ncola != Nrowb) || (Nrowa != Nrowc) || (Ncolb != Ncolc)) return RNG_CHK;
#if ENABLE_THREADS
if (thread_num() > 1 && ! serialized && Nrowc > 1) {
nways = Nrowc*Ncolc*Ncola/(THREADMUL << ROLLBITS)
+ ((Nrowc*Ncolc*Ncola%(THREADMUL << ROLLBITS)) ? 1: 0);
if (nways > Nrowc) nways = Nrowc;
}
else nways = 1;
if (nways == 1) {
#endif
for (i=0; i<Nrowc; i++)
for (j=0; j<Ncolc; j++)
MATMUL_INNER(Ncola, ap, bp, cp);
#if ENABLE_THREADS
}
else {
matmult m;
if (nways > thread_num()) nways = thread_num();
m.perthread = Nrowc / nways;
m.leftover = Nrowc % nways;
m.Ncolc = Ncolc; m.Ncola = Ncola;
m.ap = ap; m.bp = bp; m.cp = cp;
threads_do(nways, thread_matmul, &m);
}
#endif //ENABLE_THREADS
FREEopds = o_2;
return OK;
}
/*----------------------------------------------- mattranspose
b a | b a* -> b
- each argument is a list of row vectors
- number of columns in a equals number of rows in b
- number of rows in a equals number of colums in b
*/
#if ENABLE_THREADS
typedef struct {
L32 Ncola;
UL32 perthread;
UL32 leftover;
D *restrict *restrict ap, *restrict *restrict bp;
} mattransposet;
P thread_mattranspose(UL32 id,
const void* global,
void* local __attribute__ ((__unused__))) {
const mattransposet* restrict m = (const mattransposet*) global;
UL32 n = m->perthread + (thread_max() == id ? m->leftover : 0);
const UL32 i_ = m->perthread*id;
UL32 i;
for (i = i_; i < i_ + n; ++i)
MATTRANSPOSE_INNER(m->Ncola, m->ap, m->bp);
return OK;
}
#endif //ENABLE_THREADS
P op_mattranspose(void)
{
UL32 Nrowa, Nrowb, Ncola , Ncolb, i, k;
B *fp;
D **p, **ap, **bp;
#if ENABLE_THREADS
UL32 nways;
#endif //ENABLE_THREADS
if (o_2 < FLOORopds) return OPDS_UNF;
if (CLASS(o_2) != LIST) return OPD_CLA;
if (ATTR(o_2) & READONLY) return OPD_ATR;
Nrowb = (LIST_CEIL(o_2) - VALUE_BASE(o_2)) / FRAMEBYTES;
if (CLASS(o_1) != LIST) return OPD_CLA;
Nrowa = (LIST_CEIL(o_1) - VALUE_BASE(o_1)) / FRAMEBYTES;
if ((FREEvm + (Nrowa + Nrowb) * sizeof(D *)) > CEILvm) return VM_OVF;
bp = p = (D **)FREEvm;
fp = (B *)VALUE_BASE(o_2);
Ncolb = 0;
for (k=0; k<Nrowb; k++) {
if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (Ncolb == 0) Ncolb = ARRAY_SIZE(fp);
else if ((UL32) ARRAY_SIZE(fp) != Ncolb) return RNG_CHK;
*(p++) = ((D*) VALUE_BASE(fp));
fp += FRAMEBYTES;
}
ap = p;
fp = (B *)VALUE_BASE(o_1);
Ncola = 0;
for (k=0; k<Nrowa; k++) {
if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (Ncola == 0) Ncola = ARRAY_SIZE(fp);
else if ((UL32) ARRAY_SIZE(fp) != Ncola) return RNG_CHK;
*(p++) = ((D*) VALUE_BASE(fp));
fp += FRAMEBYTES;
}
if ((Ncola != Nrowb) || (Nrowa != Ncolb)) return RNG_CHK;
#if ENABLE_THREADS
if (thread_num() > 1 && ! serialized && Nrowa > 1) {
nways = Nrowa*Ncola/(THREADMUL << ROLLBITS)
+ ((Nrowa*Ncola%(THREADMUL << ROLLBITS)) ? 1 : 0);
if (nways > Nrowa) nways = Nrowa;
}
else nways = 1;
if (nways == 1) {
#endif //ENABLE_THREADS
for (i=0; i<Nrowa; i++)
MATTRANSPOSE_INNER(Ncola, ap, bp);
#if ENABLE_THREADS
}
else {
mattransposet m;
if (nways > thread_num()) nways = thread_num();
m.perthread = Nrowa / nways;
m.leftover = Nrowa % nways;
m.Ncola = Ncola;
m.bp = bp; m.ap = ap;
threads_do(nways, thread_mattranspose, &m);
}
#endif //ENABLE_THREADS
FREEopds = o_1;
return OK;
}
/*----------------------------------------------- matvecmul
c a b | c a * b -> c
- a is a list of row vectors
- b is a column vector
- c is a column vector
- if a is n*m, then b is m in length, and c is n
*/
#if ENABLE_THREADS
typedef struct {
D *restrict *restrict ap,
*restrict bp,
*restrict cp;
UL32 perthread;
UL32 leftover;
L32 Ncola;
} matvecmult;
P thread_matvecmul(UL32 id,
const void* global,
void* local __attribute__ ((__unused__))) {
const matvecmult *restrict m = (const matvecmult*) global;
const UL32 n = m->perthread + (thread_max() == id ? m->leftover : 0);
const UL32 i_ = m->perthread * id;
UL32 i;
for (i = i_; i < i_ + n; ++i)
MATVECMUL_INNER(m->Ncola, m->ap, m->bp, m->cp);
return OK;
}
#endif //ENABLE_THREADS
P op_matvecmul(void)
{
UL32 Nrowa, Nrowb, Nrowc, Ncola, i, k;
B *fp;
D **p, **ap, *bp, *cp;
#if ENABLE_THREADS
UL32 nways;
#endif //ENABLE_THREADS
if (o_3 < FLOORopds) return OPDS_UNF;
if ( CLASS(o_3) != ARRAY) return OPD_CLA;
if (ATTR(o_3) & READONLY) return OPD_ATR;
Nrowc = ARRAY_SIZE(o_3);
if ( CLASS(o_2) != LIST) return OPD_CLA;
Nrowa = (LIST_CEIL(o_2) - VALUE_BASE(o_2)) / FRAMEBYTES;
if ( CLASS(o_1) != ARRAY) return OPD_CLA;
Nrowb = ARRAY_SIZE(o_1);
if ((FREEvm + Nrowa * sizeof(D *)) > CEILvm) return VM_OVF;
p = (D **)FREEvm;
ap = p;
fp = (B *)VALUE_BASE(o_2);
Ncola = 0;
for (k=0; k<Nrowa; k++) {
if (TAG(fp) != (ARRAY | DOUBLETYPE)) return OPD_ERR;
if (Ncola == 0) Ncola = ARRAY_SIZE(fp);
else if ((UL32) ARRAY_SIZE(fp) != Ncola) return RNG_CHK;
*(p++) = ((D*) VALUE_BASE(fp));
fp += FRAMEBYTES;
}
if ((Ncola != Nrowb) || (Nrowa != Nrowc)) return RNG_CHK;
bp = (D*) VALUE_BASE(o_1); cp = (D*) VALUE_BASE(o_3);
#if ENABLE_THREADS
if (thread_num() > 1 && ! serialized && Nrowc > 1) {
nways = Nrowc*Ncola/(THREADMUL << ROLLBITS)
+ ((Nrowc*Ncola % (THREADMUL << ROLLBITS)) ? 1 : 0);
if (nways > Nrowc) nways = Nrowc;
}
else nways = 1;
if (nways == 1) {
#endif //ENABLE_THREADS
for (i=0; i<Nrowc; i++)
MATVECMUL_INNER(Ncola, ap, bp, cp);
#if ENABLE_THREADS
}
else {
matvecmult m;
if (nways > thread_num()) nways = thread_num();
m.perthread = Nrowc / nways;
m.leftover = Nrowc % nways;
m.Ncola = Ncola;
m.ap = ap; m.bp = bp; m.cp = cp;
threads_do(nways, thread_matvecmul, &m);
}
#endif //ENABLE_THREADS
FREEopds = o_2;
return OK;
}
| apeyser/Deuterostome | src/dsp2.c | C | gpl-2.0 | 23,957 |
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sara Golemon <pollita@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id: php_hash_haval.h 293036 2010-01-03 09:23:27Z sebastian $ */
#ifndef PHP_HASH_HAVAL_H
#define PHP_HASH_HAVAL_H
#include "ext/standard/basic_functions.h"
/* HAVAL context. */
typedef struct {
php_hash_uint32 state[8];
php_hash_uint32 count[2];
unsigned char buffer[128];
char passes;
short output;
void (*Transform)(php_hash_uint32 state[8], const unsigned char block[128]);
} PHP_HAVAL_CTX;
#define PHP_HASH_HAVAL_INIT_DECL(p,b) PHP_HASH_API void PHP_##p##HAVAL##b##Init(PHP_HAVAL_CTX *); \
PHP_HASH_API void PHP_HAVAL##b##Final(unsigned char*, PHP_HAVAL_CTX *);
PHP_HASH_API void PHP_HAVALUpdate(PHP_HAVAL_CTX *, const unsigned char *, unsigned int);
PHP_HASH_HAVAL_INIT_DECL(3,128)
PHP_HASH_HAVAL_INIT_DECL(3,160)
PHP_HASH_HAVAL_INIT_DECL(3,192)
PHP_HASH_HAVAL_INIT_DECL(3,224)
PHP_HASH_HAVAL_INIT_DECL(3,256)
PHP_HASH_HAVAL_INIT_DECL(4,128)
PHP_HASH_HAVAL_INIT_DECL(4,160)
PHP_HASH_HAVAL_INIT_DECL(4,192)
PHP_HASH_HAVAL_INIT_DECL(4,224)
PHP_HASH_HAVAL_INIT_DECL(4,256)
PHP_HASH_HAVAL_INIT_DECL(5,128)
PHP_HASH_HAVAL_INIT_DECL(5,160)
PHP_HASH_HAVAL_INIT_DECL(5,192)
PHP_HASH_HAVAL_INIT_DECL(5,224)
PHP_HASH_HAVAL_INIT_DECL(5,256)
#endif
| sschiesser/ASK_server | MacOSX10.6/usr/include/php/ext/hash/php_hash_haval.h | C | gpl-2.0 | 2,318 |
<?php
/**
* WooCommerce cart
*
* The WooCommerce cart class stores cart data and active coupons as well as handling customer sessions and some cart related urls.
* The cart class also has a price calculation function which calls upon other classes to calculate totals.
*
* @class WC_Cart
* @version 2.1.0
* @package WooCommerce/Classes
* @category Class
* @author WooThemes
*/
class WC_Cart {
/** @var array Contains an array of cart items. */
public $cart_contents = array();
/** @var array Contains an array of removed cart items. */
public $removed_cart_contents = array();
/** @var array Contains an array of coupon codes applied to the cart. */
public $applied_coupons = array();
/** @var array Contains an array of coupon code discounts after they have been applied. */
public $coupon_discount_amounts = array();
/** @var array Contains an array of coupon code discount taxes. Used for tax incl pricing. */
public $coupon_discount_tax_amounts = array();
/** @var array Contains an array of coupon usage counts after they have been applied. */
public $coupon_applied_count = array();
/** @var array Array of coupons */
public $coupons = array();
/** @var float The total cost of the cart items. */
public $cart_contents_total;
/** @var float The total weight of the cart items. */
public $cart_contents_weight;
/** @var float The total count of the cart items. */
public $cart_contents_count;
/** @var float Cart grand total. */
public $total;
/** @var float Cart subtotal. */
public $subtotal;
/** @var float Cart subtotal without tax. */
public $subtotal_ex_tax;
/** @var float Total cart tax. */
public $tax_total;
/** @var array An array of taxes/tax rates for the cart. */
public $taxes;
/** @var array An array of taxes/tax rates for the shipping. */
public $shipping_taxes;
/** @var float Discount amount before tax */
public $discount_cart;
/** @var float Discounted tax amount. Used predominantly for displaying tax inclusive prices correctly */
public $discount_cart_tax;
/** @var float Total for additional fees. */
public $fee_total;
/** @var float Shipping cost. */
public $shipping_total;
/** @var float Shipping tax. */
public $shipping_tax_total;
/** @var array cart_session_data. Array of data the cart calculates and stores in the session with defaults */
public $cart_session_data = array(
'cart_contents_total' => 0,
'cart_contents_weight' => 0,
'cart_contents_count' => 0,
'total' => 0,
'subtotal' => 0,
'subtotal_ex_tax' => 0,
'tax_total' => 0,
'taxes' => array(),
'shipping_taxes' => array(),
'discount_cart' => 0,
'shipping_total' => 0,
'shipping_tax_total' => 0,
'coupon_discount_amounts' => array(),
'coupon_discount_tax_amounts' => array(),
'fee_total' => 0,
'fees' => array()
);
/** @var array An array of fees. */
public $fees = array();
/** @var boolean Prices inc tax */
public $prices_include_tax;
/** @var boolean */
public $round_at_subtotal;
/** @var string */
public $tax_display_cart;
/** @var int Prices inc tax */
public $dp;
/** @var boolean */
public $display_totals_ex_tax;
/** @var boolean */
public $display_cart_ex_tax;
/**
* Constructor for the cart class. Loads options and hooks in the init method.
*/
public function __construct() {
$this->prices_include_tax = wc_prices_include_tax();
$this->round_at_subtotal = get_option( 'woocommerce_tax_round_at_subtotal' ) == 'yes';
$this->tax_display_cart = get_option( 'woocommerce_tax_display_cart' );
$this->dp = wc_get_price_decimals();
$this->display_totals_ex_tax = $this->tax_display_cart == 'excl';
$this->display_cart_ex_tax = $this->tax_display_cart == 'excl';
add_action( 'wp_loaded', array( $this, 'init' ) ); // Get cart after WP and plugins are loaded.
add_action( 'wp', array( $this, 'maybe_set_cart_cookies' ), 99 ); // Set cookies
add_action( 'shutdown', array( $this, 'maybe_set_cart_cookies' ), 0 ); // Set cookies before shutdown and ob flushing
add_action( 'woocommerce_add_to_cart', array( $this, 'calculate_totals' ), 20, 0 );
add_action( 'woocommerce_applied_coupon', array( $this, 'calculate_totals' ), 20, 0 );
}
/**
* Auto-load in-accessible properties on demand.
*
* @param mixed $key
* @return mixed
*/
public function __get( $key ) {
switch ( $key ) {
case 'tax':
_deprecated_argument( 'WC_Cart->tax', '2.3', 'Use WC_Tax:: directly' );
$this->tax = new WC_Tax();
return $this->tax;
case 'discount_total':
_deprecated_argument( 'WC_Cart->discount_total', '2.3', 'After tax coupons are no longer supported. For more information see: http://develop.woothemes.com/woocommerce/2014/12/upcoming-coupon-changes-in-woocommerce-2-3/' );
return 0;
}
}
/**
* Loads the cart data from the PHP session during WordPress init and hooks in other methods.
*/
public function init() {
$this->get_cart_from_session();
add_action( 'woocommerce_check_cart_items', array( $this, 'check_cart_items' ), 1 );
add_action( 'woocommerce_check_cart_items', array( $this, 'check_cart_coupons' ), 1 );
add_action( 'woocommerce_after_checkout_validation', array( $this, 'check_customer_coupons' ), 1 );
}
/**
* Will set cart cookies if needed, once, during WP hook
*/
public function maybe_set_cart_cookies() {
if ( ! headers_sent() ) {
if ( sizeof( $this->cart_contents ) > 0 ) {
$this->set_cart_cookies( true );
} elseif ( isset( $_COOKIE['woocommerce_items_in_cart'] ) ) {
$this->set_cart_cookies( false );
}
}
}
/**
* Set cart hash cookie and items in cart.
*
* @access private
* @param bool $set (default: true)
*/
private function set_cart_cookies( $set = true ) {
if ( $set ) {
wc_setcookie( 'woocommerce_items_in_cart', 1 );
wc_setcookie( 'woocommerce_cart_hash', md5( json_encode( $this->get_cart() ) ) );
} elseif ( isset( $_COOKIE['woocommerce_items_in_cart'] ) ) {
wc_setcookie( 'woocommerce_items_in_cart', 0, time() - HOUR_IN_SECONDS );
wc_setcookie( 'woocommerce_cart_hash', '', time() - HOUR_IN_SECONDS );
}
do_action( 'woocommerce_set_cart_cookies', $set );
}
/*-----------------------------------------------------------------------------------*/
/* Cart Session Handling */
/*-----------------------------------------------------------------------------------*/
/**
* Get the cart data from the PHP session and store it in class variables.
*/
public function get_cart_from_session() {
// Load cart session data from session
foreach ( $this->cart_session_data as $key => $default ) {
$this->$key = WC()->session->get( $key, $default );
}
$update_cart_session = false;
$this->removed_cart_contents = array_filter( WC()->session->get( 'removed_cart_contents', array() ) );
$this->applied_coupons = array_filter( WC()->session->get( 'applied_coupons', array() ) );
/**
* Load the cart object. This defaults to the persistant cart if null.
*/
$cart = WC()->session->get( 'cart', null );
if ( is_null( $cart ) && ( $saved_cart = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart', true ) ) ) {
$cart = $saved_cart['cart'];
$update_cart_session = true;
} elseif ( is_null( $cart ) ) {
$cart = array();
}
if ( is_array( $cart ) ) {
foreach ( $cart as $key => $values ) {
$_product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );
if ( ! empty( $_product ) && $_product->exists() && $values['quantity'] > 0 ) {
if ( ! $_product->is_purchasable() ) {
// Flag to indicate the stored cart should be update
$update_cart_session = true;
wc_add_notice( sprintf( __( '%s has been removed from your cart because it can no longer be purchased. Please contact us if you need assistance.', 'woocommerce' ), $_product->get_title() ), 'error' );
do_action( 'woocommerce_remove_cart_item_from_session', $key, $values );
} else {
// Put session data into array. Run through filter so other plugins can load their own session data
$session_data = array_merge( $values, array( 'data' => $_product ) );
$this->cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
}
}
}
}
if ( $update_cart_session ) {
WC()->session->cart = $this->get_cart_for_session();
}
// Trigger action
do_action( 'woocommerce_cart_loaded_from_session', $this );
// Queue re-calc if subtotal is not set
if ( ( ! $this->subtotal && sizeof( $this->cart_contents ) > 0 ) || $update_cart_session ) {
$this->calculate_totals();
}
}
/**
* Sets the php session data for the cart and coupons.
*/
public function set_session() {
// Set cart and coupon session data
$cart_session = $this->get_cart_for_session();
WC()->session->set( 'cart', $cart_session );
WC()->session->set( 'applied_coupons', $this->applied_coupons );
WC()->session->set( 'coupon_discount_amounts', $this->coupon_discount_amounts );
WC()->session->set( 'coupon_discount_tax_amounts', $this->coupon_discount_tax_amounts );
WC()->session->set( 'removed_cart_contents', $this->removed_cart_contents );
foreach ( $this->cart_session_data as $key => $default ) {
WC()->session->set( $key, $this->$key );
}
if ( get_current_user_id() ) {
$this->persistent_cart_update();
}
do_action( 'woocommerce_cart_updated' );
}
/**
* Empties the cart and optionally the persistent cart too.
*
* @param bool $clear_persistent_cart (default: true)
*/
public function empty_cart( $clear_persistent_cart = true ) {
$this->cart_contents = array();
$this->reset( true );
unset( WC()->session->order_awaiting_payment, WC()->session->applied_coupons, WC()->session->coupon_discount_amounts, WC()->session->coupon_discount_tax_amounts, WC()->session->cart );
if ( $clear_persistent_cart && get_current_user_id() ) {
$this->persistent_cart_destroy();
}
do_action( 'woocommerce_cart_emptied' );
}
/*-----------------------------------------------------------------------------------*/
/* Persistent cart handling */
/*-----------------------------------------------------------------------------------*/
/**
* Save the persistent cart when the cart is updated.
*/
public function persistent_cart_update() {
update_user_meta( get_current_user_id(), '_woocommerce_persistent_cart', array(
'cart' => WC()->session->get( 'cart' )
) );
}
/**
* Delete the persistent cart permanently.
*/
public function persistent_cart_destroy() {
delete_user_meta( get_current_user_id(), '_woocommerce_persistent_cart' );
}
/*-----------------------------------------------------------------------------------*/
/* Cart Data Functions */
/*-----------------------------------------------------------------------------------*/
/**
* Coupons enabled function. Filterable.
*
* @return bool
*/
public function coupons_enabled() {
return apply_filters( 'woocommerce_coupons_enabled', get_option( 'woocommerce_enable_coupons' ) == 'yes' );
}
/**
* Get number of items in the cart.
*
* @return int
*/
public function get_cart_contents_count() {
return apply_filters( 'woocommerce_cart_contents_count', $this->cart_contents_count );
}
/**
* Check all cart items for errors.
*/
public function check_cart_items() {
// Result
$return = true;
// Check cart item validity
$result = $this->check_cart_item_validity();
if ( is_wp_error( $result ) ) {
wc_add_notice( $result->get_error_message(), 'error' );
$return = false;
}
// Check item stock
$result = $this->check_cart_item_stock();
if ( is_wp_error( $result ) ) {
wc_add_notice( $result->get_error_message(), 'error' );
$return = false;
}
return $return;
}
/**
* Check cart coupons for errors.
*/
public function check_cart_coupons() {
foreach ( $this->applied_coupons as $code ) {
$coupon = new WC_Coupon( $code );
if ( ! $coupon->is_valid() ) {
// Error message
$coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_INVALID_REMOVED );
// Remove the coupon
$this->remove_coupon( $code );
// Flag totals for refresh
WC()->session->set( 'refresh_totals', true );
}
}
}
/**
* Get cart items quantities - merged so we can do accurate stock checks on items across multiple lines.
*
* @return array
*/
public function get_cart_item_quantities() {
$quantities = array();
foreach ( $this->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->is_type( 'variation' ) && true === $_product->managing_stock() ) {
// Variation has stock levels defined so its handled individually
$quantities[ $values['variation_id'] ] = isset( $quantities[ $values['variation_id'] ] ) ? $quantities[ $values['variation_id'] ] + $values['quantity'] : $values['quantity'];
} else {
$quantities[ $values['product_id'] ] = isset( $quantities[ $values['product_id'] ] ) ? $quantities[ $values['product_id'] ] + $values['quantity'] : $values['quantity'];
}
}
return $quantities;
}
/**
* Looks through cart items and checks the posts are not trashed or deleted.
*
* @return bool|WP_Error
*/
public function check_cart_item_validity() {
foreach ( $this->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( ! $_product || ! $_product->exists() || $_product->post->post_status == 'trash' ) {
$this->set_quantity( $cart_item_key, 0 );
return new WP_Error( 'invalid', __( 'An item which is no longer available was removed from your cart.', 'woocommerce' ) );
}
}
return true;
}
/**
* Looks through the cart to check each item is in stock. If not, add an error.
*
* @return bool|WP_Error
*/
public function check_cart_item_stock() {
global $wpdb;
$error = new WP_Error();
$product_qty_in_cart = $this->get_cart_item_quantities();
// First stock check loop
foreach ( $this->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
/**
* Check stock based on stock-status
*/
if ( ! $_product->is_in_stock() ) {
$error->add( 'out-of-stock', sprintf(__( 'Sorry, "%s" is not in stock. Please edit your cart and try again. We apologise for any inconvenience caused.', 'woocommerce' ), $_product->get_title() ) );
return $error;
}
if ( ! $_product->managing_stock() ) {
continue;
}
$check_qty = $_product->is_type( 'variation' ) && true === $_product->managing_stock() ? $product_qty_in_cart[ $values['variation_id'] ] : $product_qty_in_cart[ $values['product_id'] ];
/**
* Check stock based on all items in the cart
*/
if ( ! $_product->has_enough_stock( $check_qty ) ) {
$error->add( 'out-of-stock', sprintf(__( 'Sorry, we do not have enough "%s" in stock to fulfill your order (%s in stock). Please edit your cart and try again. We apologise for any inconvenience caused.', 'woocommerce' ), $_product->get_title(), $_product->get_stock_quantity() ) );
return $error;
}
/**
* Finally consider any held stock, from pending orders
*/
if ( get_option( 'woocommerce_hold_stock_minutes' ) > 0 && ! $_product->backorders_allowed() ) {
$order_id = isset( WC()->session->order_awaiting_payment ) ? absint( WC()->session->order_awaiting_payment ) : 0;
$held_stock = $wpdb->get_var(
$wpdb->prepare( "
SELECT SUM( order_item_meta.meta_value ) AS held_qty
FROM {$wpdb->posts} AS posts
LEFT JOIN {$wpdb->prefix}woocommerce_order_items as order_items ON posts.ID = order_items.order_id
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta2 ON order_items.order_item_id = order_item_meta2.order_item_id
WHERE order_item_meta.meta_key = '_qty'
AND order_item_meta2.meta_key = %s AND order_item_meta2.meta_value = %d
AND posts.post_type IN ( '" . implode( "','", wc_get_order_types() ) . "' )
AND posts.post_status = 'wc-pending'
AND posts.ID != %d;",
$_product->is_type( 'variation' ) && true === $_product->managing_stock() ? '_variation_id' : '_product_id',
$_product->is_type( 'variation' ) && true === $_product->managing_stock() ? $values['variation_id'] : $values['product_id'],
$order_id
)
);
$not_enough_stock = false;
if ( $_product->is_type( 'variation' ) && 'parent' === $_product->managing_stock() && $_product->parent->get_stock_quantity() < ( $held_stock + $check_qty ) ) {
$not_enough_stock = true;
} elseif ( $_product->get_stock_quantity() < ( $held_stock + $check_qty ) ) {
$not_enough_stock = true;
}
if ( $not_enough_stock ) {
$error->add( 'out-of-stock', sprintf(__( 'Sorry, we do not have enough "%s" in stock to fulfill your order right now. Please try again in %d minutes or edit your cart and try again. We apologise for any inconvenience caused.', 'woocommerce' ), $_product->get_title(), get_option( 'woocommerce_hold_stock_minutes' ) ) );
return $error;
}
}
}
return true;
}
/**
* Gets and formats a list of cart item data + variations for display on the frontend.
*
* @param array $cart_item
* @param bool $flat (default: false)
* @return string
*/
public function get_item_data( $cart_item, $flat = false ) {
$item_data = array();
// Variation data
if ( ! empty( $cart_item['data']->variation_id ) && is_array( $cart_item['variation'] ) ) {
foreach ( $cart_item['variation'] as $name => $value ) {
if ( '' === $value )
continue;
$taxonomy = wc_attribute_taxonomy_name( str_replace( 'attribute_pa_', '', urldecode( $name ) ) );
// If this is a term slug, get the term's nice name
if ( taxonomy_exists( $taxonomy ) ) {
$term = get_term_by( 'slug', $value, $taxonomy );
if ( ! is_wp_error( $term ) && $term && $term->name ) {
$value = $term->name;
}
$label = wc_attribute_label( $taxonomy );
// If this is a custom option slug, get the options name
} else {
$value = apply_filters( 'woocommerce_variation_option_name', $value );
$product_attributes = $cart_item['data']->get_attributes();
if ( isset( $product_attributes[ str_replace( 'attribute_', '', $name ) ] ) ) {
$label = wc_attribute_label( $product_attributes[ str_replace( 'attribute_', '', $name ) ]['name'] );
} else {
$label = $name;
}
}
$item_data[] = array(
'key' => $label,
'value' => $value
);
}
}
// Other data - returned as array with name/value values
$other_data = apply_filters( 'woocommerce_get_item_data', array(), $cart_item );
if ( $other_data && is_array( $other_data ) && sizeof( $other_data ) > 0 ) {
foreach ( $other_data as $data ) {
// Set hidden to true to not display meta on cart.
if ( empty( $data['hidden'] ) ) {
$display_value = ! empty( $data['display'] ) ? $data['display'] : $data['value'];
$item_data[] = array(
'key' => $data['name'],
'value' => $display_value
);
}
}
}
// Output flat or in list format
if ( sizeof( $item_data ) > 0 ) {
ob_start();
if ( $flat ) {
foreach ( $item_data as $data ) {
echo esc_html( $data['key'] ) . ': ' . wp_kses_post( $data['value'] ) . "\n";
}
} else {
wc_get_template( 'cart/cart-item-data.php', array( 'item_data' => $item_data ) );
}
return ob_get_clean();
}
return '';
}
/**
* Gets cross sells based on the items in the cart.
*
* @return array cross_sells (item ids)
*/
public function get_cross_sells() {
$cross_sells = array();
$in_cart = array();
if ( sizeof( $this->get_cart() ) > 0 ) {
foreach ( $this->get_cart() as $cart_item_key => $values ) {
if ( $values['quantity'] > 0 ) {
$cross_sells = array_merge( $values['data']->get_cross_sells(), $cross_sells );
$in_cart[] = $values['product_id'];
}
}
}
$cross_sells = array_diff( $cross_sells, $in_cart );
return $cross_sells;
}
/**
* Gets the url to the cart page.
*
* @return string url to page
*/
public function get_cart_url() {
$cart_page_id = wc_get_page_id( 'cart' );
return apply_filters( 'woocommerce_get_cart_url', $cart_page_id ? get_permalink( $cart_page_id ) : '' );
}
/**
* Gets the url to the checkout page.
*
* @return string url to page
*/
public function get_checkout_url() {
$checkout_page_id = wc_get_page_id( 'checkout' );
$checkout_url = '';
if ( $checkout_page_id ) {
// Get the checkout URL
$checkout_url = get_permalink( $checkout_page_id );
// Force SSL if needed
if ( is_ssl() || 'yes' === get_option( 'woocommerce_force_ssl_checkout' ) ) {
$checkout_url = str_replace( 'http:', 'https:', $checkout_url );
}
}
return apply_filters( 'woocommerce_get_checkout_url', $checkout_url );
}
/**
* Gets the url to remove an item from the cart.
*
* @param string cart_item_key contains the id of the cart item
* @return string url to page
*/
public function get_remove_url( $cart_item_key ) {
$cart_page_id = wc_get_page_id('cart');
return apply_filters( 'woocommerce_get_remove_url', $cart_page_id ? wp_nonce_url( add_query_arg( 'remove_item', $cart_item_key, get_permalink( $cart_page_id ) ), 'woocommerce-cart' ) : '' );
}
/**
* Gets the url to re-add an item into the cart.
*
* @param string $cart_item_key
* @return string url to page
*/
public function get_undo_url( $cart_item_key ) {
$cart_page_id = wc_get_page_id( 'cart' );
$query_args = array(
'undo_item' => $cart_item_key,
);
return apply_filters( 'woocommerce_get_undo_url', $cart_page_id ? wp_nonce_url( add_query_arg( $query_args, get_permalink( $cart_page_id ) ), 'woocommerce-cart' ) : '' );
}
/**
* Returns the contents of the cart in an array.
*
* @return array contents of the cart
*/
public function get_cart() {
if ( ! did_action( 'wp_loaded' ) ) {
$this->get_cart_from_session();
_doing_it_wrong( __FUNCTION__, __( 'Get cart should not be called before the wp_loaded action.', 'woocommerce' ), '2.3' );
}
return array_filter( (array) $this->cart_contents );
}
/**
* Returns the contents of the cart in an array without the 'data' element.
*
* @return array contents of the cart
*/
private function get_cart_for_session() {
$cart_session = array();
if ( $this->get_cart() ) {
foreach ( $this->get_cart() as $key => $values ) {
$cart_session[ $key ] = $values;
unset( $cart_session[ $key ]['data'] ); // Unset product object
}
}
return $cart_session;
}
/**
* Returns a specific item in the cart
*
* @return array item data
*/
public function get_cart_item( $item_key ) {
if ( isset( $this->cart_contents[ $item_key ] ) ) {
return $this->cart_contents[ $item_key ];
}
return array();
}
/**
* Returns the cart and shipping taxes, merged.
*
* @return array merged taxes
*/
public function get_taxes() {
$taxes = array();
// Merge
foreach ( array_keys( $this->taxes + $this->shipping_taxes ) as $key ) {
$taxes[ $key ] = ( isset( $this->shipping_taxes[ $key ] ) ? $this->shipping_taxes[ $key ] : 0 ) + ( isset( $this->taxes[ $key ] ) ? $this->taxes[ $key ] : 0 );
}
return apply_filters( 'woocommerce_cart_get_taxes', $taxes, $this );
}
/**
* Get taxes, merged by code, formatted ready for output.
*
* @return array
*/
public function get_tax_totals() {
$taxes = $this->get_taxes();
$tax_totals = array();
foreach ( $taxes as $key => $tax ) {
$code = WC_Tax::get_rate_code( $key );
if ( $code || $key === apply_filters( 'woocommerce_cart_remove_taxes_zero_rate_id', 'zero-rated' ) ) {
if ( ! isset( $tax_totals[ $code ] ) ) {
$tax_totals[ $code ] = new stdClass();
$tax_totals[ $code ]->amount = 0;
}
$tax_totals[ $code ]->tax_rate_id = $key;
$tax_totals[ $code ]->is_compound = WC_Tax::is_compound( $key );
$tax_totals[ $code ]->label = WC_Tax::get_rate_label( $key );
$tax_totals[ $code ]->amount += wc_round_tax_total( $tax );
$tax_totals[ $code ]->formatted_amount = wc_price( wc_round_tax_total( $tax_totals[ $code ]->amount ) );
}
}
return apply_filters( 'woocommerce_cart_tax_totals', $tax_totals, $this );
}
/**
* Get all tax classes for items in the cart
* @return array
*/
public function get_cart_item_tax_classes() {
$found_tax_classes = array();
foreach ( WC()->cart->get_cart() as $item ) {
$found_tax_classes[] = $item['data']->get_tax_class();
}
return array_unique( $found_tax_classes );
}
/*-----------------------------------------------------------------------------------*/
/* Add to cart handling */
/*-----------------------------------------------------------------------------------*/
/**
* Check if product is in the cart and return cart item key.
*
* Cart item key will be unique based on the item and its properties, such as variations.
*
* @param mixed id of product to find in the cart
* @return string cart item key
*/
public function find_product_in_cart( $cart_id = false ) {
if ( $cart_id !== false ) {
if ( is_array( $this->cart_contents ) ) {
foreach ( $this->cart_contents as $cart_item_key => $cart_item ) {
if ( $cart_item_key == $cart_id ) {
return $cart_item_key;
}
}
}
}
return '';
}
/**
* Generate a unique ID for the cart item being added.
*
* @param int $product_id - id of the product the key is being generated for
* @param int $variation_id of the product the key is being generated for
* @param array $variation data for the cart item
* @param array $cart_item_data other cart item data passed which affects this items uniqueness in the cart
* @return string cart item key
*/
public function generate_cart_id( $product_id, $variation_id = 0, $variation = array(), $cart_item_data = array() ) {
$id_parts = array( $product_id );
if ( $variation_id && 0 != $variation_id ) {
$id_parts[] = $variation_id;
}
if ( is_array( $variation ) && ! empty( $variation ) ) {
$variation_key = '';
foreach ( $variation as $key => $value ) {
$variation_key .= trim( $key ) . trim( $value );
}
$id_parts[] = $variation_key;
}
if ( is_array( $cart_item_data ) && ! empty( $cart_item_data ) ) {
$cart_item_data_key = '';
foreach ( $cart_item_data as $key => $value ) {
if ( is_array( $value ) ) {
$value = http_build_query( $value );
}
$cart_item_data_key .= trim( $key ) . trim( $value );
}
$id_parts[] = $cart_item_data_key;
}
return md5( implode( '_', $id_parts ) );
}
/**
* Add a product to the cart.
*
* @param string $product_id contains the id of the product to add to the cart
* @param integer $quantity contains the quantity of the item to add
* @param int $variation_id
* @param array $variation attribute values
* @param array $cart_item_data extra cart item data we want to pass into the item
* @return string $cart_item_key
*/
public function add_to_cart( $product_id, $quantity = 1, $variation_id = '', $variation = array(), $cart_item_data = array() ) {
// Wrap in try catch so plugins can throw an exception to prevent adding to cart
try {
// Ensure we don't add a variation to the cart directly by variation ID
if ( 'product_variation' == get_post_type( $product_id ) ) {
$variation_id = $product_id;
$product_id = wp_get_post_parent_id( $variation_id );
}
// Get the product
$product_data = wc_get_product( $variation_id ? $variation_id : $product_id );
// Sanitity check
if ( $quantity <= 0 || ! $product_data || 'trash' === $product_data->post->post_status ) {
throw new Exception();
}
// Load cart item data - may be added by other plugins
$cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id );
// Generate a ID based on product ID, variation ID, variation data, and other cart item data
$cart_id = $this->generate_cart_id( $product_id, $variation_id, $variation, $cart_item_data );
// Find the cart item key in the existing cart
$cart_item_key = $this->find_product_in_cart( $cart_id );
// Force quantity to 1 if sold individually and check for exisitng item in cart
if ( $product_data->is_sold_individually() ) {
$quantity = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data );
$in_cart_quantity = $cart_item_key ? $this->cart_contents[ $cart_item_key ]['quantity'] : 0;
if ( $in_cart_quantity > 0 ) {
throw new Exception( sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', $this->get_cart_url(), __( 'View Quote', 'woocommerce' ), sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data->get_title() ) ) );
}
}
// Check product is_purchasable
if ( ! $product_data->is_purchasable() ) {
throw new Exception( __( 'Sorry, this product cannot be purchased.', 'woocommerce' ) );
}
// Stock check - only check if we're managing stock and backorders are not allowed
if ( ! $product_data->is_in_stock() ) {
throw new Exception( sprintf( __( 'You cannot add "%s" to the cart because the product is out of stock.', 'woocommerce' ), $product_data->get_title() ) );
}
if ( ! $product_data->has_enough_stock( $quantity ) ) {
throw new Exception( sprintf(__( 'You cannot add that amount of "%s" to the cart because there is not enough stock (%s remaining).', 'woocommerce' ), $product_data->get_title(), $product_data->get_stock_quantity() ) );
}
// Stock check - this time accounting for whats already in-cart
if ( $managing_stock = $product_data->managing_stock() ) {
$products_qty_in_cart = $this->get_cart_item_quantities();
if ( $product_data->is_type( 'variation' ) && true === $managing_stock ) {
$check_qty = isset( $products_qty_in_cart[ $variation_id ] ) ? $products_qty_in_cart[ $variation_id ] : 0;
} else {
$check_qty = isset( $products_qty_in_cart[ $product_id ] ) ? $products_qty_in_cart[ $product_id ] : 0;
}
/**
* Check stock based on all items in the cart
*/
if ( ! $product_data->has_enough_stock( $check_qty + $quantity ) ) {
throw new Exception( sprintf(
'<a href="%s" class="button wc-forward">%s</a> %s',
$this->get_cart_url(),
__( 'View Quote', 'woocommerce' ),
sprintf( __( 'You cannot add that amount to the cart — we have %s in stock and you already have %s in your cart.', 'woocommerce' ), $product_data->get_stock_quantity(), $check_qty )
) );
}
}
// If cart_item_key is set, the item is already in the cart
if ( $cart_item_key ) {
$new_quantity = $quantity + $this->cart_contents[ $cart_item_key ]['quantity'];
$this->set_quantity( $cart_item_key, $new_quantity, false );
} else {
$cart_item_key = $cart_id;
// Add item after merging with $cart_item_data - hook to allow plugins to modify cart item
$this->cart_contents[ $cart_item_key ] = apply_filters( 'woocommerce_add_cart_item', array_merge( $cart_item_data, array(
'product_id' => $product_id,
'variation_id' => $variation_id,
'variation' => $variation,
'quantity' => $quantity,
'data' => $product_data
) ), $cart_item_key );
}
if ( did_action( 'wp' ) ) {
$this->set_cart_cookies( sizeof( $this->cart_contents ) > 0 );
}
do_action( 'woocommerce_add_to_cart', $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data );
return $cart_item_key;
} catch ( Exception $e ) {
if ( $e->getMessage() ) {
wc_add_notice( $e->getMessage(), 'error' );
}
return false;
}
}
/**
* Remove a cart item
*
* @since 2.3.0
* @param string $cart_item_key
* @return bool
*/
public function remove_cart_item( $cart_item_key ) {
if ( isset( $this->cart_contents[ $cart_item_key ] ) ) {
$remove = $this->cart_contents[ $cart_item_key ];
$this->removed_cart_contents[ $cart_item_key ] = $remove;
unset( $this->cart_contents[ $cart_item_key ] );
do_action( 'woocommerce_cart_item_removed', $cart_item_key, $this );
$this->calculate_totals();
return true;
}
return false;
}
/**
* Restore a cart item
*
* @param string $cart_item_key
* @return bool
*/
public function restore_cart_item( $cart_item_key ) {
if ( isset( $this->removed_cart_contents[ $cart_item_key ] ) ) {
$restore = $this->removed_cart_contents[ $cart_item_key ];
$this->cart_contents[ $cart_item_key ] = $restore;
unset( $this->removed_cart_contents[ $cart_item_key ] );
do_action( 'woocommerce_cart_item_restored', $cart_item_key, $this );
$this->calculate_totals();
return true;
}
return false;
}
/**
* Set the quantity for an item in the cart.
*
* @param string cart_item_key contains the id of the cart item
* @param string quantity contains the quantity of the item
* @param boolean $refresh_totals whether or not to calculate totals after setting the new qty
*
* @return bool
*/
public function set_quantity( $cart_item_key, $quantity = 1, $refresh_totals = true ) {
if ( $quantity == 0 || $quantity < 0 ) {
do_action( 'woocommerce_before_cart_item_quantity_zero', $cart_item_key );
unset( $this->cart_contents[ $cart_item_key ] );
} else {
$old_quantity = $this->cart_contents[ $cart_item_key ]['quantity'];
$this->cart_contents[ $cart_item_key ]['quantity'] = $quantity;
do_action( 'woocommerce_after_cart_item_quantity_update', $cart_item_key, $quantity, $old_quantity );
}
if ( $refresh_totals ) {
$this->calculate_totals();
}
return true;
}
/*-----------------------------------------------------------------------------------*/
/* Cart Calculation Functions */
/*-----------------------------------------------------------------------------------*/
/**
* Reset cart totals to the defaults. Useful before running calculations.
*
* @param bool $unset_session If true, the session data will be forced unset.
* @access private
*/
private function reset( $unset_session = false ) {
foreach ( $this->cart_session_data as $key => $default ) {
$this->$key = $default;
if ( $unset_session ) {
unset( WC()->session->$key );
}
}
do_action( 'woocommerce_cart_reset', $this, $unset_session );
}
/**
* Calculate totals for the items in the cart.
*/
public function calculate_totals() {
$this->reset();
$this->coupons = $this->get_coupons();
do_action( 'woocommerce_before_calculate_totals', $this );
if ( sizeof( $this->get_cart() ) == 0 ) {
$this->set_session();
return;
}
$tax_rates = array();
$shop_tax_rates = array();
/**
* Calculate subtotals for items. This is done first so that discount logic can use the values.
*/
foreach ( $this->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
// Count items + weight
$this->cart_contents_weight += $_product->get_weight() * $values['quantity'];
$this->cart_contents_count += $values['quantity'];
// Prices
$line_price = $_product->get_price() * $values['quantity'];
$line_subtotal = 0;
$line_subtotal_tax = 0;
/**
* No tax to calculate
*/
if ( ! $_product->is_taxable() ) {
// Subtotal is the undiscounted price
$this->subtotal += $line_price;
$this->subtotal_ex_tax += $line_price;
/**
* Prices include tax
*
* To prevent rounding issues we need to work with the inclusive price where possible
* otherwise we'll see errors such as when working with a 9.99 inc price, 20% VAT which would
* be 8.325 leading to totals being 1p off
*
* Pre tax coupons come off the price the customer thinks they are paying - tax is calculated
* afterwards.
*
* e.g. $100 bike with $10 coupon = customer pays $90 and tax worked backwards from that
*/
} elseif ( $this->prices_include_tax ) {
// Get base tax rates
if ( empty( $shop_tax_rates[ $_product->tax_class ] ) ) {
$shop_tax_rates[ $_product->tax_class ] = WC_Tax::get_base_tax_rates( $_product->tax_class );
}
// Get item tax rates
if ( empty( $tax_rates[ $_product->get_tax_class() ] ) ) {
$tax_rates[ $_product->get_tax_class() ] = WC_Tax::get_rates( $_product->get_tax_class() );
}
$base_tax_rates = $shop_tax_rates[ $_product->tax_class ];
$item_tax_rates = $tax_rates[ $_product->get_tax_class() ];
/**
* ADJUST TAX - Calculations when base tax is not equal to the item tax
*/
if ( $item_tax_rates !== $base_tax_rates ) {
// Work out a new base price without the shop's base tax
$taxes = WC_Tax::calc_tax( $line_price, $base_tax_rates, true, true );
// Now we have a new item price (excluding TAX)
$line_subtotal = $line_price - array_sum( $taxes );
// Now add modified taxes
$tax_result = WC_Tax::calc_tax( $line_subtotal, $item_tax_rates );
$line_subtotal_tax = array_sum( $tax_result );
/**
* Regular tax calculation (customer inside base and the tax class is unmodified
*/
} else {
// Calc tax normally
$taxes = WC_Tax::calc_tax( $line_price, $item_tax_rates, true );
$line_subtotal_tax = array_sum( $taxes );
$line_subtotal = $line_price - array_sum( $taxes );
}
/**
* Prices exclude tax
*
* This calculation is simpler - work with the base, untaxed price.
*/
} else {
// Get item tax rates
if ( empty( $tax_rates[ $_product->get_tax_class() ] ) ) {
$tax_rates[ $_product->get_tax_class() ] = WC_Tax::get_rates( $_product->get_tax_class() );
}
$item_tax_rates = $tax_rates[ $_product->get_tax_class() ];
// Base tax for line before discount - we will store this in the order data
$taxes = WC_Tax::calc_tax( $line_price, $item_tax_rates );
$line_subtotal_tax = array_sum( $taxes );
$line_subtotal = $line_price;
}
// Add to main subtotal
$this->subtotal += $line_subtotal + $line_subtotal_tax;
$this->subtotal_ex_tax += $line_subtotal;
}
/**
* Calculate totals for items
*/
foreach ( $this->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
// Prices
$base_price = $_product->get_price();
$line_price = $_product->get_price() * $values['quantity'];
// Tax data
$taxes = array();
$discounted_taxes = array();
/**
* No tax to calculate
*/
if ( ! $_product->is_taxable() ) {
// Discounted Price (price with any pre-tax discounts applied)
$discounted_price = $this->get_discounted_price( $values, $base_price, true );
$line_subtotal_tax = 0;
$line_subtotal = $line_price;
$line_tax = 0;
$line_total = WC_Tax::round( $discounted_price * $values['quantity'] );
/**
* Prices include tax
*/
} elseif ( $this->prices_include_tax ) {
$base_tax_rates = $shop_tax_rates[ $_product->tax_class ];
$item_tax_rates = $tax_rates[ $_product->get_tax_class() ];
/**
* ADJUST TAX - Calculations when base tax is not equal to the item tax
*/
if ( $item_tax_rates !== $base_tax_rates ) {
// Work out a new base price without the shop's base tax
$taxes = WC_Tax::calc_tax( $line_price, $base_tax_rates, true, true );
// Now we have a new item price (excluding TAX)
$line_subtotal = round( $line_price - array_sum( $taxes ), WC_ROUNDING_PRECISION );
$taxes = WC_Tax::calc_tax( $line_subtotal, $item_tax_rates );
$line_subtotal_tax = array_sum( $taxes );
// Adjusted price (this is the price including the new tax rate)
$adjusted_price = ( $line_subtotal + $line_subtotal_tax ) / $values['quantity'];
// Apply discounts
$discounted_price = $this->get_discounted_price( $values, $adjusted_price, true );
$discounted_taxes = WC_Tax::calc_tax( $discounted_price * $values['quantity'], $item_tax_rates, true );
$line_tax = array_sum( $discounted_taxes );
$line_total = ( $discounted_price * $values['quantity'] ) - $line_tax;
/**
* Regular tax calculation (customer inside base and the tax class is unmodified
*/
} else {
// Work out a new base price without the item tax
$taxes = WC_Tax::calc_tax( $line_price, $item_tax_rates, true );
// Now we have a new item price (excluding TAX)
$line_subtotal = $line_price - array_sum( $taxes );
$line_subtotal_tax = array_sum( $taxes );
// Calc prices and tax (discounted)
$discounted_price = $this->get_discounted_price( $values, $base_price, true );
$discounted_taxes = WC_Tax::calc_tax( $discounted_price * $values['quantity'], $item_tax_rates, true );
$line_tax = array_sum( $discounted_taxes );
$line_total = ( $discounted_price * $values['quantity'] ) - $line_tax;
}
// Tax rows - merge the totals we just got
foreach ( array_keys( $this->taxes + $discounted_taxes ) as $key ) {
$this->taxes[ $key ] = ( isset( $discounted_taxes[ $key ] ) ? $discounted_taxes[ $key ] : 0 ) + ( isset( $this->taxes[ $key ] ) ? $this->taxes[ $key ] : 0 );
}
/**
* Prices exclude tax
*/
} else {
$item_tax_rates = $tax_rates[ $_product->get_tax_class() ];
// Work out a new base price without the shop's base tax
$taxes = WC_Tax::calc_tax( $line_price, $item_tax_rates );
// Now we have the item price (excluding TAX)
$line_subtotal = $line_price;
$line_subtotal_tax = array_sum( $taxes );
// Now calc product rates
$discounted_price = $this->get_discounted_price( $values, $base_price, true );
$discounted_taxes = WC_Tax::calc_tax( $discounted_price * $values['quantity'], $item_tax_rates );
$discounted_tax_amount = array_sum( $discounted_taxes );
$line_tax = $discounted_tax_amount;
$line_total = $discounted_price * $values['quantity'];
// Tax rows - merge the totals we just got
foreach ( array_keys( $this->taxes + $discounted_taxes ) as $key ) {
$this->taxes[ $key ] = ( isset( $discounted_taxes[ $key ] ) ? $discounted_taxes[ $key ] : 0 ) + ( isset( $this->taxes[ $key ] ) ? $this->taxes[ $key ] : 0 );
}
}
// Cart contents total is based on discounted prices and is used for the final total calculation
$this->cart_contents_total += $line_total;
// Store costs + taxes for lines
$this->cart_contents[ $cart_item_key ]['line_total'] = $line_total;
$this->cart_contents[ $cart_item_key ]['line_tax'] = $line_tax;
$this->cart_contents[ $cart_item_key ]['line_subtotal'] = $line_subtotal;
$this->cart_contents[ $cart_item_key ]['line_subtotal_tax'] = $line_subtotal_tax;
// Store rates ID and costs - Since 2.2
$this->cart_contents[ $cart_item_key ]['line_tax_data'] = array( 'total' => $discounted_taxes, 'subtotal' => $taxes );
}
// Only calculate the grand total + shipping if on the cart/checkout
if ( is_checkout() || is_cart() || defined('WOOCOMMERCE_CHECKOUT') || defined('WOOCOMMERCE_CART') ) {
// Calculate the Shipping
$this->calculate_shipping();
// Trigger the fees API where developers can add fees to the cart
$this->calculate_fees();
// Total up/round taxes and shipping taxes
if ( $this->round_at_subtotal ) {
$this->tax_total = WC_Tax::get_tax_total( $this->taxes );
$this->shipping_tax_total = WC_Tax::get_tax_total( $this->shipping_taxes );
$this->taxes = array_map( array( 'WC_Tax', 'round' ), $this->taxes );
$this->shipping_taxes = array_map( array( 'WC_Tax', 'round' ), $this->shipping_taxes );
} else {
$this->tax_total = array_sum( $this->taxes );
$this->shipping_tax_total = array_sum( $this->shipping_taxes );
}
// VAT exemption done at this point - so all totals are correct before exemption
if ( WC()->customer->is_vat_exempt() ) {
$this->remove_taxes();
}
// Allow plugins to hook and alter totals before final total is calculated
do_action( 'woocommerce_calculate_totals', $this );
// Grand Total - Discounted product prices, discounted tax, shipping cost + tax
$this->total = max( 0, apply_filters( 'woocommerce_calculated_total', round( $this->cart_contents_total + $this->tax_total + $this->shipping_tax_total + $this->shipping_total + $this->fee_total, $this->dp ), $this ) );
} else {
// Set tax total to sum of all tax rows
$this->tax_total = WC_Tax::get_tax_total( $this->taxes );
// VAT exemption done at this point - so all totals are correct before exemption
if ( WC()->customer->is_vat_exempt() ) {
$this->remove_taxes();
}
}
do_action( 'woocommerce_after_calculate_totals', $this );
$this->set_session();
}
/**
* remove_taxes function.
*/
public function remove_taxes() {
$this->shipping_tax_total = $this->tax_total = 0;
$this->subtotal = $this->subtotal_ex_tax;
foreach ( $this->cart_contents as $cart_item_key => $item ) {
$this->cart_contents[ $cart_item_key ]['line_subtotal_tax'] = $this->cart_contents[ $cart_item_key ]['line_tax'] = 0;
$this->cart_contents[ $cart_item_key ]['line_tax_data'] = array( 'total' => array(), 'subtotal' => array() );
}
// If true, zero rate is applied so '0' tax is displayed on the frontend rather than nothing.
if ( apply_filters( 'woocommerce_cart_remove_taxes_apply_zero_rate', true ) ) {
$this->taxes = $this->shipping_taxes = array( apply_filters( 'woocommerce_cart_remove_taxes_zero_rate_id', 'zero-rated' ) => 0 );
} else {
$this->taxes = $this->shipping_taxes = array();
}
}
/**
* looks at the totals to see if payment is actually required.
*
* @return bool
*/
public function needs_payment() {
return apply_filters( 'woocommerce_cart_needs_payment', $this->total > 0, $this );
}
/*-----------------------------------------------------------------------------------*/
/* Shipping related functions */
/*-----------------------------------------------------------------------------------*/
/**
* Uses the shipping class to calculate shipping then gets the totals when its finished.
*/
public function calculate_shipping() {
if ( $this->needs_shipping() && $this->show_shipping() ) {
WC()->shipping->calculate_shipping( $this->get_shipping_packages() );
} else {
WC()->shipping->reset_shipping();
}
// Get totals for the chosen shipping method
$this->shipping_total = WC()->shipping->shipping_total; // Shipping Total
$this->shipping_taxes = WC()->shipping->shipping_taxes; // Shipping Taxes
}
/**
* Get packages to calculate shipping for.
*
* This lets us calculate costs for carts that are shipped to multiple locations.
*
* Shipping methods are responsible for looping through these packages.
*
* By default we pass the cart itself as a package - plugins can change this
* through the filter and break it up.
*
* @since 1.5.4
* @return array of cart items
*/
public function get_shipping_packages() {
// Packages array for storing 'carts'
$packages = array();
$packages[0]['contents'] = $this->get_cart(); // Items in the package
$packages[0]['contents_cost'] = 0; // Cost of items in the package, set below
$packages[0]['applied_coupons'] = $this->applied_coupons;
$packages[0]['user']['ID'] = get_current_user_id();
$packages[0]['destination']['country'] = WC()->customer->get_shipping_country();
$packages[0]['destination']['state'] = WC()->customer->get_shipping_state();
$packages[0]['destination']['postcode'] = WC()->customer->get_shipping_postcode();
$packages[0]['destination']['city'] = WC()->customer->get_shipping_city();
$packages[0]['destination']['address'] = WC()->customer->get_shipping_address();
$packages[0]['destination']['address_2'] = WC()->customer->get_shipping_address_2();
foreach ( $this->get_cart() as $item ) {
if ( $item['data']->needs_shipping() ) {
if ( isset( $item['line_total'] ) ) {
$packages[0]['contents_cost'] += $item['line_total'];
}
}
}
return apply_filters( 'woocommerce_cart_shipping_packages', $packages );
}
/**
* Looks through the cart to see if shipping is actually required.
*
* @return bool whether or not the cart needs shipping
*/
public function needs_shipping() {
if ( get_option( 'woocommerce_calc_shipping' ) === 'no' ) {
return false;
}
$needs_shipping = false;
if ( $this->cart_contents ) {
foreach ( $this->cart_contents as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->needs_shipping() ) {
$needs_shipping = true;
}
}
}
return apply_filters( 'woocommerce_cart_needs_shipping', $needs_shipping );
}
/**
* Should the shipping address form be shown
*
* @return bool
*/
function needs_shipping_address() {
$needs_shipping_address = false;
if ( $this->needs_shipping() === true && ! $this->ship_to_billing_address_only() ) {
$needs_shipping_address = true;
}
return apply_filters( 'woocommerce_cart_needs_shipping_address', $needs_shipping_address );
}
/**
* Sees if the customer has entered enough data to calc the shipping yet.
*
* @return bool
*/
public function show_shipping() {
if ( get_option('woocommerce_calc_shipping') == 'no' || ! is_array( $this->cart_contents ) )
return false;
if ( get_option( 'woocommerce_shipping_cost_requires_address' ) == 'yes' ) {
if ( ! WC()->customer->has_calculated_shipping() ) {
if ( ! WC()->customer->get_shipping_country() || ( ! WC()->customer->get_shipping_state() && ! WC()->customer->get_shipping_postcode() ) )
return false;
}
}
$show_shipping = true;
return apply_filters( 'woocommerce_cart_ready_to_calc_shipping', $show_shipping );
}
/**
* Sees if we need a shipping address.
*
* @return bool
*/
public function ship_to_billing_address_only() {
return wc_ship_to_billing_address_only();
}
/**
* Gets the shipping total (after calculation).
*
* @return string price or string for the shipping total
*/
public function get_cart_shipping_total() {
if ( isset( $this->shipping_total ) ) {
if ( $this->shipping_total > 0 ) {
// Display varies depending on settings
if ( $this->tax_display_cart == 'excl' ) {
$return = wc_price( $this->shipping_total );
if ( $this->shipping_tax_total > 0 && $this->prices_include_tax ) {
$return .= ' <small>' . WC()->countries->ex_tax_or_vat() . '</small>';
}
return $return;
} else {
$return = wc_price( $this->shipping_total + $this->shipping_tax_total );
if ( $this->shipping_tax_total > 0 && ! $this->prices_include_tax ) {
$return .= ' <small>' . WC()->countries->inc_tax_or_vat() . '</small>';
}
return $return;
}
} else {
return __( 'Free!', 'woocommerce' );
}
}
return '';
}
/*-----------------------------------------------------------------------------------*/
/* Coupons/Discount related functions */
/*-----------------------------------------------------------------------------------*/
/**
* Check for user coupons (now that we have billing email). If a coupon is invalid, add an error.
*
* Checks two types of coupons:
* 1. Where a list of customer emails are set (limits coupon usage to those defined)
* 2. Where a usage_limit_per_user is set (limits coupon usage to a number based on user ID and email)
*
* @param array $posted
*/
public function check_customer_coupons( $posted ) {
if ( ! empty( $this->applied_coupons ) ) {
foreach ( $this->applied_coupons as $code ) {
$coupon = new WC_Coupon( $code );
if ( $coupon->is_valid() ) {
// Limit to defined email addresses
if ( is_array( $coupon->customer_email ) && sizeof( $coupon->customer_email ) > 0 ) {
$check_emails = array();
$coupon->customer_email = array_map( 'sanitize_email', $coupon->customer_email );
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$check_emails[] = $current_user->user_email;
}
$check_emails[] = $posted['billing_email'];
$check_emails = array_map( 'sanitize_email', array_map( 'strtolower', $check_emails ) );
if ( 0 == sizeof( array_intersect( $check_emails, $coupon->customer_email ) ) ) {
$coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_NOT_YOURS_REMOVED );
// Remove the coupon
$this->remove_coupon( $code );
// Flag totals for refresh
WC()->session->set( 'refresh_totals', true );
}
}
// Usage limits per user - check against billing and user email and user ID
if ( $coupon->usage_limit_per_user > 0 ) {
$check_emails = array();
$used_by = array_filter( (array) get_post_meta( $coupon->id, '_used_by' ) );
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$check_emails[] = sanitize_email( $current_user->user_email );
$usage_count = sizeof( array_keys( $used_by, get_current_user_id() ) );
} else {
$check_emails[] = sanitize_email( $posted['billing_email'] );
$user = get_user_by( 'email', $posted['billing_email'] );
if ( $user ) {
$usage_count = sizeof( array_keys( $used_by, $user->ID ) );
} else {
$usage_count = 0;
}
}
foreach ( $check_emails as $check_email ) {
$usage_count = $usage_count + sizeof( array_keys( $used_by, $check_email ) );
}
if ( $usage_count >= $coupon->usage_limit_per_user ) {
$coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_USAGE_LIMIT_REACHED );
// Remove the coupon
$this->remove_coupon( $code );
// Flag totals for refresh
WC()->session->set( 'refresh_totals', true );
}
}
}
}
}
}
/**
* Returns whether or not a discount has been applied.
*
* @return bool
*/
public function has_discount( $coupon_code ) {
return in_array( apply_filters( 'woocommerce_coupon_code', $coupon_code ), $this->applied_coupons );
}
/**
* Applies a coupon code passed to the method.
*
* @param string $coupon_code - The code to apply
* @return bool True if the coupon is applied, false if it does not exist or cannot be applied
*/
public function add_discount( $coupon_code ) {
// Coupons are globally disabled
if ( ! $this->coupons_enabled() ) {
return false;
}
// Sanitize coupon code
$coupon_code = apply_filters( 'woocommerce_coupon_code', $coupon_code );
// Get the coupon
$the_coupon = new WC_Coupon( $coupon_code );
// Check it can be used with cart
if ( ! $the_coupon->is_valid() ) {
wc_add_notice( $the_coupon->get_error_message(), 'error' );
return false;
}
// Check if applied
if ( $this->has_discount( $coupon_code ) ) {
$the_coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_ALREADY_APPLIED );
return false;
}
// If its individual use then remove other coupons
if ( $the_coupon->individual_use == 'yes' ) {
$this->applied_coupons = apply_filters( 'woocommerce_apply_individual_use_coupon', array(), $the_coupon, $this->applied_coupons );
}
if ( $this->applied_coupons ) {
foreach ( $this->applied_coupons as $code ) {
$coupon = new WC_Coupon( $code );
if ( $coupon->individual_use == 'yes' && false === apply_filters( 'woocommerce_apply_with_individual_use_coupon', false, $the_coupon, $coupon, $this->applied_coupons ) ) {
// Reject new coupon
$coupon->add_coupon_message( WC_Coupon::E_WC_COUPON_ALREADY_APPLIED_INDIV_USE_ONLY );
return false;
}
}
}
$this->applied_coupons[] = $coupon_code;
// Choose free shipping
if ( $the_coupon->enable_free_shipping() ) {
$packages = WC()->shipping->get_packages();
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
foreach ( $packages as $i => $package ) {
$chosen_shipping_methods[ $i ] = 'free_shipping';
}
WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
}
$the_coupon->add_coupon_message( WC_Coupon::WC_COUPON_SUCCESS );
do_action( 'woocommerce_applied_coupon', $coupon_code );
return true;
}
/**
* Get array of applied coupon objects and codes.
* @return array of applied coupons
*/
public function get_coupons( $deprecated = null ) {
$coupons = array();
if ( 'order' === $deprecated ) {
return $coupons;
}
foreach ( $this->get_applied_coupons() as $code ) {
$coupon = new WC_Coupon( $code );
$coupons[ $code ] = $coupon;
}
return $coupons;
}
/**
* Gets the array of applied coupon codes.
*
* @return array of applied coupons
*/
public function get_applied_coupons() {
return $this->applied_coupons;
}
/**
* Get the discount amount for a used coupon
* @param string $code coupon code
* @param bool inc or ex tax
* @return float discount amount
*/
public function get_coupon_discount_amount( $code, $ex_tax = true ) {
$discount_amount = isset( $this->coupon_discount_amounts[ $code ] ) ? $this->coupon_discount_amounts[ $code ] : 0;
if ( $ex_tax ) {
return $discount_amount;
} else {
return $discount_amount + $this->get_coupon_discount_tax_amount( $code );
}
}
/**
* Get the discount tax amount for a used coupon (for tax inclusive prices)
* @param string $code coupon code
* @param bool inc or ex tax
* @return float discount amount
*/
public function get_coupon_discount_tax_amount( $code ) {
return isset( $this->coupon_discount_tax_amounts[ $code ] ) ? $this->coupon_discount_tax_amounts[ $code ] : 0;
}
/**
* Remove coupons from the cart of a defined type. Type 1 is before tax, type 2 is after tax.
*/
public function remove_coupons( $deprecated = null ) {
$this->applied_coupons = $this->coupon_discount_amounts = $this->coupon_discount_tax_amounts = $this->coupon_applied_count = array();
WC()->session->set( 'applied_coupons', array() );
WC()->session->set( 'coupon_discount_amounts', array() );
WC()->session->set( 'coupon_discount_tax_amounts', array() );
}
/**
* Remove a single coupon by code
* @param string $coupon_code Code of the coupon to remove
* @return bool
*/
public function remove_coupon( $coupon_code ) {
// Coupons are globally disabled
if ( ! $this->coupons_enabled() )
return false;
// Get the coupon
$coupon_code = apply_filters( 'woocommerce_coupon_code', $coupon_code );
$position = array_search( $coupon_code, $this->applied_coupons );
if ( $position !== false )
unset( $this->applied_coupons[ $position ] );
WC()->session->set( 'applied_coupons', $this->applied_coupons );
return true;
}
/**
* Function to apply discounts to a product and get the discounted price (before tax is applied).
*
* @param mixed $values
* @param mixed $price
* @param bool $add_totals (default: false)
* @return float price
*/
public function get_discounted_price( $values, $price, $add_totals = false ) {
if ( ! $price ) {
return $price;
}
if ( ! empty( $this->coupons ) ) {
$product = $values['data'];
foreach ( $this->coupons as $code => $coupon ) {
if ( $coupon->is_valid() && ( $coupon->is_valid_for_product( $product, $values ) || $coupon->is_valid_for_cart() ) ) {
$discount_amount = $coupon->get_discount_amount( $price, $values, $single = true );
$price = max( $price - $discount_amount, 0 );
// Store the totals for DISPLAY in the cart
if ( $add_totals ) {
$total_discount = $discount_amount * $values['quantity'];
$total_discount_tax = 0;
// Calc discounted tax
$tax_rates = WC_Tax::get_rates( $product->get_tax_class() );
$taxes = WC_Tax::calc_tax( $discount_amount, $tax_rates, $this->prices_include_tax );
$total_discount_tax = WC_Tax::get_tax_total( $taxes ) * $values['quantity'];
$total_discount = $this->prices_include_tax ? $total_discount - $total_discount_tax : $total_discount;
$this->discount_cart += $total_discount;
$this->discount_cart_tax += $total_discount_tax;
$this->increase_coupon_discount_amount( $code, $total_discount, $total_discount_tax );
$this->increase_coupon_applied_count( $code, $values['quantity'] );
}
}
}
}
return apply_filters( 'woocommerce_get_discounted_price', $price, $values, $this );
}
/**
* Store how much discount each coupon grants.
*
* @access private
* @param string $code
* @param double $amount
* @param double $tax
*/
private function increase_coupon_discount_amount( $code, $amount, $tax ) {
$this->coupon_discount_amounts[ $code ] = isset( $this->coupon_discount_amounts[ $code ] ) ? $this->coupon_discount_amounts[ $code ] + $amount : $amount;
$this->coupon_discount_tax_amounts[ $code ] = isset( $this->coupon_discount_tax_amounts[ $code ] ) ? $this->coupon_discount_tax_amounts[ $code ] + $tax : $tax;
}
/**
* Store how many times each coupon is applied to cart/items
*
* @access private
* @param string $code
* @param integer $count
*/
private function increase_coupon_applied_count( $code, $count = 1 ) {
if ( empty( $this->coupon_applied_count[ $code ] ) ) {
$this->coupon_applied_count[ $code ] = 0;
}
$this->coupon_applied_count[ $code ] += $count;
}
/*-----------------------------------------------------------------------------------*/
/* Fees API to add additional costs to orders */
/*-----------------------------------------------------------------------------------*/
/**
* add_fee function.
*
* @param mixed $name
* @param mixed $amount
* @param bool $taxable (default: false)
* @param string $tax_class (default: '')
*/
public function add_fee( $name, $amount, $taxable = false, $tax_class = '' ) {
$new_fee_id = sanitize_title( $name );
// Only add each fee once
foreach ( $this->fees as $fee ) {
if ( $fee->id == $new_fee_id ) {
return;
}
}
$new_fee = new stdClass();
$new_fee->id = $new_fee_id;
$new_fee->name = esc_attr( $name );
$new_fee->amount = (float) esc_attr( $amount );
$new_fee->tax_class = $tax_class;
$new_fee->taxable = $taxable ? true : false;
$new_fee->tax = 0;
$new_fee->tax_data = array();
$this->fees[] = $new_fee;
}
/**
* get_fees function.
*
* @return array
*/
public function get_fees() {
return array_filter( (array) $this->fees );
}
/**
* Calculate fees
*/
public function calculate_fees() {
// Reset fees before calculation
$this->fee_total = 0;
$this->fees = array();
// Fire an action where developers can add their fees
do_action( 'woocommerce_cart_calculate_fees', $this );
// If fees were added, total them and calculate tax
if ( ! empty( $this->fees ) ) {
foreach ( $this->fees as $fee_key => $fee ) {
$this->fee_total += $fee->amount;
if ( $fee->taxable ) {
// Get tax rates
$tax_rates = WC_Tax::get_rates( $fee->tax_class );
$fee_taxes = WC_Tax::calc_tax( $fee->amount, $tax_rates, false );
if ( ! empty( $fee_taxes ) ) {
// Set the tax total for this fee
$this->fees[ $fee_key ]->tax = array_sum( $fee_taxes );
// Set tax data - Since 2.2
$this->fees[ $fee_key ]->tax_data = $fee_taxes;
// Tax rows - merge the totals we just got
foreach ( array_keys( $this->taxes + $fee_taxes ) as $key ) {
$this->taxes[ $key ] = ( isset( $fee_taxes[ $key ] ) ? $fee_taxes[ $key ] : 0 ) + ( isset( $this->taxes[ $key ] ) ? $this->taxes[ $key ] : 0 );
}
}
}
}
}
}
/*-----------------------------------------------------------------------------------*/
/* Get Formatted Totals */
/*-----------------------------------------------------------------------------------*/
/**
* Gets the order total (after calculation).
*
* @return string formatted price
*/
public function get_total() {
return apply_filters( 'woocommerce_cart_total', wc_price( $this->total ) );
}
/**
* Gets the total excluding taxes.
*
* @return string formatted price
*/
public function get_total_ex_tax() {
$total = $this->total - $this->tax_total - $this->shipping_tax_total;
if ( $total < 0 ) {
$total = 0;
}
return apply_filters( 'woocommerce_cart_total_ex_tax', wc_price( $total ) );
}
/**
* Gets the cart contents total (after calculation).
*
* @return string formatted price
*/
public function get_cart_total() {
if ( ! $this->prices_include_tax ) {
$cart_contents_total = wc_price( $this->cart_contents_total );
} else {
$cart_contents_total = wc_price( $this->cart_contents_total + $this->tax_total );
}
return apply_filters( 'woocommerce_cart_contents_total', $cart_contents_total );
}
/**
* Gets the sub total (after calculation).
*
* @params bool whether to include compound taxes
* @return string formatted price
*/
public function get_cart_subtotal( $compound = false ) {
// If the cart has compound tax, we want to show the subtotal as
// cart + shipping + non-compound taxes (after discount)
if ( $compound ) {
$cart_subtotal = wc_price( $this->cart_contents_total + $this->shipping_total + $this->get_taxes_total( false, false ) );
// Otherwise we show cart items totals only (before discount)
} else {
// Display varies depending on settings
if ( $this->tax_display_cart == 'excl' ) {
$cart_subtotal = wc_price( $this->subtotal_ex_tax );
if ( $this->tax_total > 0 && $this->prices_include_tax ) {
$cart_subtotal .= ' <small>' . WC()->countries->ex_tax_or_vat() . '</small>';
}
} else {
$cart_subtotal = wc_price( $this->subtotal );
if ( $this->tax_total > 0 && !$this->prices_include_tax ) {
$cart_subtotal .= ' <small>' . WC()->countries->inc_tax_or_vat() . '</small>';
}
}
}
return apply_filters( 'woocommerce_cart_subtotal', $cart_subtotal, $compound, $this );
}
/**
* Get the product row price per item.
*
* @param WC_Product $_product
* @return string formatted price
*/
public function get_product_price( $_product ) {
if ( $this->tax_display_cart == 'excl' ) {
$product_price = $_product->get_price_excluding_tax();
} else {
$product_price = $_product->get_price_including_tax();
}
return apply_filters( 'woocommerce_cart_product_price', wc_price( $product_price ), $_product );
}
/**
* Get the product row subtotal.
*
* Gets the tax etc to avoid rounding issues.
*
* When on the checkout (review order), this will get the subtotal based on the customer's tax rate rather than the base rate
*
* @param WC_Product $_product
* @param int quantity
* @return string formatted price
*/
public function get_product_subtotal( $_product, $quantity ) {
$price = $_product->get_price();
$taxable = $_product->is_taxable();
// Taxable
if ( $taxable ) {
if ( $this->tax_display_cart == 'excl' ) {
$row_price = $_product->get_price_excluding_tax( $quantity );
$product_subtotal = wc_price( $row_price );
if ( $this->prices_include_tax && $this->tax_total > 0 ) {
$product_subtotal .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
}
} else {
$row_price = $_product->get_price_including_tax( $quantity );
$product_subtotal = wc_price( $row_price );
if ( ! $this->prices_include_tax && $this->tax_total > 0 ) {
$product_subtotal .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
}
}
// Non-taxable
} else {
$row_price = $price * $quantity;
$product_subtotal = wc_price( $row_price );
}
return apply_filters( 'woocommerce_cart_product_subtotal', $product_subtotal, $_product, $quantity, $this );
}
/**
* Gets the cart tax (after calculation).
*
* @return string formatted price
*/
public function get_cart_tax() {
$cart_total_tax = wc_round_tax_total( $this->tax_total + $this->shipping_tax_total );
return apply_filters( 'woocommerce_get_cart_tax', $cart_total_tax ? wc_price( $cart_total_tax ) : '' );
}
/**
* Get a tax amount
* @param string $tax_rate_id
* @return float amount
*/
public function get_tax_amount( $tax_rate_id ) {
return isset( $this->taxes[ $tax_rate_id ] ) ? $this->taxes[ $tax_rate_id ] : 0;
}
/**
* Get a tax amount
* @param string $tax_rate_id
* @return float amount
*/
public function get_shipping_tax_amount( $tax_rate_id ) {
return isset( $this->shipping_taxes[ $tax_rate_id ] ) ? $this->shipping_taxes[ $tax_rate_id ] : 0;
}
/**
* Get tax row amounts with or without compound taxes includes.
*
* @param boolean $compound True if getting compound taxes
* @param boolean $display True if getting total to display
* @return float price
*/
public function get_taxes_total( $compound = true, $display = true ) {
$total = 0;
foreach ( $this->taxes as $key => $tax ) {
if ( ! $compound && WC_Tax::is_compound( $key ) ) continue;
$total += $tax;
}
foreach ( $this->shipping_taxes as $key => $tax ) {
if ( ! $compound && WC_Tax::is_compound( $key ) ) continue;
$total += $tax;
}
if ( $display ) {
$total = wc_round_tax_total( $total );
}
return apply_filters( 'woocommerce_cart_taxes_total', $total, $compound, $display, $this );
}
/**
* Get the total of all cart discounts
*
* @return float
*/
public function get_cart_discount_total() {
return $this->discount_cart;
}
/**
* Get the total of all cart tax discounts (used for discounts on tax inclusive prices)
*
* @return float
*/
public function get_cart_discount_tax_total() {
return $this->discount_cart_tax;
}
/**
* Gets the total discount amount - both kinds.
*
* @return mixed formatted price or false if there are none
*/
public function get_total_discount() {
if ( $this->discount_cart ) {
$total_discount = wc_price( $this->discount_cart );
} else {
$total_discount = false;
}
return apply_filters( 'woocommerce_cart_total_discount', $total_discount, $this );
}
/**
* Gets the total (product) discount amount - these are applied before tax.
*
* @deprecated Order discounts (after tax) removed in 2.3 so multiple methods for discounts are no longer required.
* @return mixed formatted price or false if there are none
*/
public function get_discounts_before_tax() {
_deprecated_function( 'get_discounts_before_tax', '2.3', 'get_total_discount' );
if ( $this->discount_cart ) {
$discounts_before_tax = wc_price( $this->discount_cart );
} else {
$discounts_before_tax = false;
}
return apply_filters( 'woocommerce_cart_discounts_before_tax', $discounts_before_tax, $this );
}
/**
* Get the total of all order discounts (after tax discounts).
*
* @deprecated Order discounts (after tax) removed in 2.3
* @return integer
*/
public function get_order_discount_total() {
_deprecated_function( 'get_order_discount_total', '2.3' );
return 0;
}
/**
* Function to apply cart discounts after tax.
* @deprecated Coupons can not be applied after tax
*/
public function apply_cart_discounts_after_tax( $values, $price ) {
_deprecated_function( 'apply_cart_discounts_after_tax', '2.3' );
}
/**
* Function to apply product discounts after tax.
* @deprecated Coupons can not be applied after tax
*/
public function apply_product_discounts_after_tax( $values, $price ) {
_deprecated_function( 'apply_product_discounts_after_tax', '2.3' );
}
/**
* Gets the order discount amount - these are applied after tax.
* @deprecated Coupons can not be applied after tax
*/
public function get_discounts_after_tax() {
_deprecated_function( 'get_discounts_after_tax', '2.3' );
}
}
| abesamislyndon/femaccms | wp-content/plugins/woocommerce/includes/class-wc-cart1.php | PHP | gpl-2.0 | 74,450 |
<!-- displays "There was a problem validating this field. Please check your internet connection." -->
<p ng-message="exception" translate> FORM.VALIDATION.EXCEPTION </p>
<!-- displays "This field must be unique. This value is already taken. -->
<p ng-message="unique" translate> FORM.VALIDATION.UNIQUE </p>
<!-- displays "This field cannot be empty." -->
<p ng-message="required" translate> FORM.VALIDATION.REQUIRED </p>
<!-- displays "This value must be a whole number (integer)." -->
<p ng-message="integer" translate> FORM.VALIDATION.INTEGER </p>
<!-- displays "This value is too small for this field." -->
<p ng-message="min" translate> FORM.VALIDATION.MIN </p>
<p ng-message="maxInteger" translate> FORM.VALIDATION.MAX </p>
<!-- displays "This field cannot be empty." -->
<p ng-message="required" translate> FORM.VALIDATION.REQUIRED </p>
<!-- displays "This field must be a valid email." -->
<p ng-message="email" translate> FORM.VALIDATION.EMAIL </p>
<!-- displays "This input is too short." -->
<p ng-message="minlength" translate> FORM.VALIDATION.MINLENGTH </p>
<!-- displays "This input is too long." -->
<p ng-message="maxlength" translate> FORM.VALIDATION.MAXLENGTH </p>
<!-- displays "This field must be a valid number." -->
<p ng-message="number" translate > FORM.VALIDATION.NUMBER </p>
<!-- displays "This field must be a valid date." -->
<p ng-message="date" translate> FORM.VALIDATION.DATE </p>
<!-- displays: "This value is required" -->
<p ng-message="required" translate> FORM.ERRORS.REQUIRED </p>
<!-- displays: "This value is too big " -->
<p ng-message="max" translate>FORM.ERRORS.VALUE_GREATER </p>
<!-- displays: "You must enter a valid number." -->
<p ng-message="number" translate>FORM.ERRORS.NUMBER </p>
<!-- displays: "The uploaded file is too large!" -->
<p ng-message="maxSize" style="margin-bottom: 0;">
<i class="fa fa-warning"></i> <span translate>FORM.VALIDATION.UPLOAD_TOO_LARGE</span>
</p>
| IMA-WorldHealth/bhima | client/src/modules/templates/messages.tmpl.html | HTML | gpl-2.0 | 1,954 |
# Backlight & LCD drivers
obj-$(CONFIG_LCD_CLASS_DEVICE) += lcd.o
obj-$(CONFIG_LCD_CORGI) += corgi_lcd.o
obj-$(CONFIG_LCD_HP700) += jornada720_lcd.o
obj-$(CONFIG_LCD_LMS283GF05) += lms283gf05.o
obj-$(CONFIG_LCD_LTV350QV) += ltv350qv.o
obj-$(CONFIG_LCD_ILI9320) += ili9320.o
obj-$(CONFIG_LCD_PLATFORM) += platform_lcd.o
obj-$(CONFIG_LCD_VGG2432A4) += vgg2432a4.o
obj-$(CONFIG_LCD_TDO24M) += tdo24m.o
obj-$(CONFIG_LCD_TOSA) += tosa_lcd.o
obj-$(CONFIG_LCD_GPM940B0) += gpm940b0.o
obj-$(CONFIG_BACKLIGHT_CLASS_DEVICE) += backlight.o
obj-$(CONFIG_BACKLIGHT_ATMEL_PWM) += atmel-pwm-bl.o
obj-$(CONFIG_BACKLIGHT_GENERIC) += generic_bl.o
obj-$(CONFIG_BACKLIGHT_HP700) += jornada720_bl.o
obj-$(CONFIG_BACKLIGHT_HP680) += hp680_bl.o
obj-$(CONFIG_BACKLIGHT_LOCOMO) += locomolcd.o
obj-$(CONFIG_BACKLIGHT_OMAP1) += omap1_bl.o
obj-$(CONFIG_BACKLIGHT_PROGEAR) += progear_bl.o
obj-$(CONFIG_BACKLIGHT_CARILLO_RANCH) += cr_bllcd.o
obj-$(CONFIG_BACKLIGHT_PWM) += pwm_bl.o
obj-$(CONFIG_BACKLIGHT_DA903X) += da903x_bl.o
obj-$(CONFIG_BACKLIGHT_MBP_NVIDIA) += mbp_nvidia_bl.o
obj-$(CONFIG_BACKLIGHT_TOSA) += tosa_bl.o
obj-$(CONFIG_BACKLIGHT_SAHARA) += kb3886_bl.o
obj-$(CONFIG_BACKLIGHT_WM831X) += wm831x_bl.o
obj-$(CONFIG_BACKLIGHT_ADX) += adx_bl.o
obj-$(CONFIG_BACKLIGHT_ADP5520) += adp5520_bl.o
| kyak/qi-kernel | drivers/video/backlight/Makefile | Makefile | gpl-2.0 | 1,320 |
<?php
/* Template name: Event page */
if ( isset($_GET['cdir']) ) {
$cdir = $_GET['cdir']; }
else {
$cdir = "";
}
if ( isset($_GET['cat']) ){
$cat_id = $_GET['cat'];}
else {
$cat_id = "";
}
get_header();
$tzone = get_option('timezone_string');
if ( $tzone ) date_default_timezone_set($tzone);
if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div class="col-lg-8 col-md-8 col-sm-7 col-sx-12 white ">
<div class="row">
<div class='breadcrumbs'>
<?php if(function_exists('bcn_display') && !is_front_page()) {
bcn_display();
}?>
</div>
</div>
<h1><?php the_title(); ?>
<?php
$pub = get_terms( 'event-type', 'orderby=count&hide_empty=1' );
if (count($pub)>0 and $cat_id!=''){
foreach ($pub as $sc) {
if ($cat_id == $sc->slug) { echo ' - '.$sc->name; }
}
}
?>
</h1>
<?php the_content(); ?>
<?php
$sdate=date('Ymd');
$stime=date('H:i:s');
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$posts_per_page = get_option('posts_per_page',10);
if ($cat_id!=''){ // show events by type
$cquery = array(
'tax_query' => array(
array(
'taxonomy' => 'event-type',
'field' => 'slug',
'terms' => $cat_id,
),
),
'meta_query' => array(
array(
'key' => 'event_start_date',
'value' => $sdate,
'compare' => '>=',
'type' => 'DATE',
)
),
'orderby' => 'meta_value',
'meta_key' => 'event_start_date',
'order' => 'ASC',
'post_type' => 'event',
'posts_per_page' => $posts_per_page,
'paged' => $paged
);
} else { //all events
$cquery = array(
'post_type' => 'event',
'posts_per_page' => $posts_per_page,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'event_end_date',
'value' => $sdate,
'compare' => '>',
'type' => 'DATE',
),
array(
'relation' => 'AND',
array(
'key' => 'event_end_date',
'value' => $sdate,
'compare' => '=',
'type' => 'DATE',
),
array(
'key' => 'event_end_time',
'value' => $stime,
'compare' => '>',
),
),
),
'orderby' => 'meta_value',
'meta_key' => 'event_start_date',
'order' => 'ASC',
'paged' => $paged
);
}
$customquery = new WP_Query($cquery);
if (!$customquery->have_posts()){
echo "<p>" . __('Nothing to show' ,'govintranet') . ".</p>";
}
if ( $customquery->have_posts() ) {
while ( $customquery->have_posts() ) {
$customquery->the_post();
echo "<div class='media'>";
if ( has_post_thumbnail( $post->ID ) ) {
the_post_thumbnail('thumbnail',"class=alignleft");
}
echo "<div class='media-body'><h3><a href='" .get_permalink() . "'>" . get_the_title() . "</a></h3>";
$thisdate = get_post_meta($post->ID,'event_start_date',true);
$thistime = get_post_meta($post->ID,'event_start_time',true);
if ( $thisdate ) {
echo "<strong>".date(get_option('date_format'),strtotime($thisdate));
if ( $thistime ) {
echo " " . date(get_option('time_format'),strtotime($thistime));
}
echo "</strong>";
}
the_excerpt();
echo "</div></div>";
}
}
wp_reset_query();
echo $timetravel;
if ( $customquery->max_num_pages > 1 ) :
if (function_exists('wp_pagenavi')) :
wp_pagenavi(array('query' => $customquery));
else :
next_posts_link(__('← Older items','govintranet'), $customquery->max_num_pages);
previous_posts_link(__('Newer items →','govintranet'), $customquery->max_num_pages);
endif;
endif; ?>
</div>
<div class="col-lg-4 col-md-4 col-sm-5 col-sx-12" id="sidebar">
<h2 class="sr-only">Sidebar</h2>
<?php
get_template_part("part", "sidebar");
get_template_part("part", "related");
dynamic_sidebar('eventslanding-widget-area');
$taxonomies=array();
$post_type = array();
$taxonomies[] = 'event-type';
$post_type[] = 'event';
$post_cat = get_terms_by_post_type( $taxonomies, $post_type);
if ($post_cat){
echo "<div class='widget-box'><h3 class='widget-title'>". __('Categories' , 'govintranet') . "</h3>";
echo "<p class='taglisting {$post->post_type}'>";
echo "<span><a class='wptag t' href='".get_permalink(get_the_id())."/?cdir=".$cdir."'>" . __('All' , 'govintranet') . "</a></span> ";
foreach($post_cat as $cat){
if ($cat->term_id > 1 && $cat->name){
$newname = str_replace(" ", " ", $cat->name );
echo "<span><a class='wptag t".$cat->term_id."' href='".get_permalink(get_the_id())."?cat=".$cat->slug."&cdir=".$cdir."'>".$newname."</a></span> ";
}
}
echo "</p></div>";
}
$eventcloud = gi_howto_tag_cloud('event');
if ($eventcloud) :?>
<div class="widget-box">
<h3 class='widget-title'><?php _e('Browse by tag' , 'govintranet'); ?></h3>
<?php echo $eventcloud; ?>
</div>
<br>
<?php endif; ?>
</div>
<?php endwhile; ?>
<?php get_footer(); ?> | helpful/govintranet | govintranet/page-event.php | PHP | gpl-2.0 | 5,376 |
<?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 may use a
* different template.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package elme
*/
get_header(); ?>
<section class="section section--padded section--banner imgTarget2">
<div class="section__inner">
<h1 class="h1 section__title">Get in Touch</h1>
<?php the_post_thumbnail( null, array("class" => "imgSrc2")); ?>
</div>
</section>
<section class="section section--padded">
<div class="section__inner">
<div class="row-fluid">
<div class="col-12 col-md-6 col-lg-7">
<?php if ( have_posts() ) :
while ( have_posts() ) : the_post();
the_content();
endwhile;
endif;
?>
<p>
<svg class="icon icon-location">
<use xlink:href="#icon-location"></use>
</svg>
<a href="https://www.google.com.ph/maps/place/Seventh-Day+Adventist+Church/@10.248783,123.8255972,19z/data=!4m5!3m4!1s0x33a99d1610cfee23:0xb18badb335b57fd0!8m2!3d10.2485918!4d123.8253868" target="_blank" class="highlights">
Mohon, Talisay City, Cebu Philippines
</a></p>
<p>
<svg class="icon icon-phone">
<use xlink:href="#icon-phone"></use>
</svg>
<a href="tel:639956446246" class="highlights">+63 9956 446 246</a></p>
<p>
<svg class="icon icon-bubbles">
<use xlink:href="#icon-bubbles"></use>
</svg>
<a href="mailto:" class="highlights">sample@email.com</a></p>
<nav class="social-2">
<span>Follow Us: </span>
<a href="" target="_blank" class="social__item">
<svg class="icon icon-facebook">
<use xlink:href="#icon-facebook"></use>
</svg>
</a>
<a href="" target="_blank" class="social__item">
<svg class="icon icon-twitter">
<use xlink:href="#icon-twitter"></use>
</svg>
</a>
<a href="" target="_blank" class="social__item">
<svg class="icon icon-instagram">
<use xlink:href="#icon-instagram"></use>
</svg>
</a>
</nav>
</div>
<div class="col-12 col-md-6 col-lg-5">
<div class="card">
<div class="message">
</div>
<form id="user-post" v-on:submit.prevent="checkForm">
<?php //wp_nonce_field( basename( __FILE__ ), 'user-submitted-inquiry'); ?>
<div class="form__group">
<label class="form__label" for="user-name">Name</label>
<input type="text" name="user-name" id="user-name" class="important form__control" v-model="name">
</div>
<div class="form__group">
<label class="form__label" for="user-email">E-mail</label>
<input type="email" name="user-email" id="user-email" class="important form__control" v-model="email">
</div>
<div class="form__group">
<label class="form__label" for="user-phone">Phone</label>
<input type="text" name="user-phone" id="user-phone" class="important form__control" v-model="phone">
</div>
<div class="form__group">
<label class="form__label" for="type">Subject</label>
<select name="type" id="type" class="important form__control" v-model="type">
<?php
$terms = get_terms( 'type', array(
'hide_empty' => false,
) );
foreach($terms as $term) {
echo '<option value="'. $term->name .'">' . $term->name .'</option>';
}
?>
</select>
</div>
<div class="form__group">
<label class="form__label" for="user-message">Message</label>
<textarea name="user-message" id="user-message" cols="30" class="important form__control" v-model="message"></textarea>
</div>
<div class="form__group">
<div class="g-recaptcha" :data-sitekey="captcha" data-sitekey="6LfZ1DUUAAAAAGZCgx_5HpVrhX0JGgaQcpNnNZYD"></div>
</div>
<input type="submit" id="user-submit-btn" class="btn btn--full btn--black" value="Submit">
</form>
</div>
</div>
</div>
<!-- <div class="admin-quick-add">
<h3>Quick Add Post</h3>
<input type="text" name="title" placeholder="Title">
<textarea name="content" placeholder="Content"></textarea>
<button id="quick-add-button">Create Post</button>
</div> -->
</div>
</section>
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<script src="https://unpkg.com/vue-recaptcha@latest/dist/vue-recaptcha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js" defer></script>
<script>
// window.onload = (function(){
// var srcTarget2 = document.getElementsByClassName("imgTarget2"),
// // source
// imgSrc2 = document.getElementsByClassName("imgSrc2");
// function setBackground(from, to, option){
// Array.prototype.map.call(from, (el, idx) => {
// if(from != null || from != "undefined") {
// to[idx].style.background = "url(" + el.src + ") center center / cover no-repeat";
// if(option == "none") {el.style.display = "none"; } else
// { el.style.opacity = 0;}
// }
// });
// }
// setBackground(imgSrc2, srcTarget2, "none");
// })();
</script>
<?php
get_footer();
| iamelme/mohon | page-contact.php | PHP | gpl-2.0 | 5,437 |
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (15) on Sun May 23 12:20:22 PDT 2021 -->
<title>PreviewListener (Makelangelo 7.24.5 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2021-05-23">
<meta name="description" content="declaration: package: com.marginallyclever.makelangelo.preview, interface: PreviewListener">
<meta name="generator" content="javadoc/ClassWriterImpl">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery-ui.overrides.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
<script type="text/javascript" src="../../../../script-dir/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="../../../../script-dir/jquery-ui.min.js"></script>
</head>
<body class="class-declaration-page">
<script type="text/javascript">var data = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "alt-color";
var rowColor = "row-color";
var tableTab = "table-tab";
var activeTableTab = "active-table-tab";
var pathtoroot = "../../../../";
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="flex-box">
<header role="banner" class="flex-header">
<nav role="navigation">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="top-nav" id="navbar.top">
<div class="skip-nav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<ul id="navbar.top.firstrow" class="nav-list" title="Navigation">
<li><a href="../../../../index.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="nav-bar-cell1-rev">Class</li>
<li><a href="class-use/PreviewListener.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="sub-nav">
<div>
<ul class="sub-nav-list">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="sub-nav-list">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<div class="nav-list-search"><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</div>
</div>
<!-- ========= END OF TOP NAVBAR ========= -->
<span class="skip-nav" id="skip.navbar.top">
<!-- -->
</span></nav>
</header>
<div class="flex-content">
<main role="main">
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="sub-title"><span class="package-label-in-type">Package</span> <a href="package-summary.html">com.marginallyclever.makelangelo.preview</a></div>
<h1 title="Interface PreviewListener" class="title">Interface PreviewListener</h1>
</div>
<section class="description">
<dl class="notes">
<dt>All Known Implementing Classes:</dt>
<dd><code><a href="../../makelangeloRobot/MakelangeloRobot.html" title="class in com.marginallyclever.makelangeloRobot">MakelangeloRobot</a></code></dd>
</dl>
<hr>
<pre>public interface <span class="type-name-label">PreviewListener</span></pre>
<div class="block">PreviewListener classes are waiting for their turn to render to the WYSIWYG interface in Makelangelo software.</div>
<dl class="notes">
<dt>Author:</dt>
<dd>Dan Royer</dd>
</dl>
</section>
<section class="summary">
<ul class="summary-list">
<!-- ========== METHOD SUMMARY =========== -->
<li>
<section class="method-summary" id="method.summary">
<h2>Method Summary</h2>
<div class="member-summary" id="method-summary-table">
<div class="table-tabs" role="tablist" aria-orientation="horizontal"><button role="tab" aria-selected="true" aria-controls="method-summary-table.tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="active-table-tab">All Methods</button><button role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t2" class="table-tab" onclick="show(2);">Instance Methods</button><button role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t3" class="table-tab" onclick="show(4);">Abstract Methods</button></div>
<div id="method-summary-table.tabpanel" role="tabpanel">
<table class="summary-table" aria-labelledby="t0">
<thead>
<tr>
<th class="col-first" scope="col">Modifier and Type</th>
<th class="col-second" scope="col">Method</th>
<th class="col-last" scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr class="alt-color" id="i0">
<td class="col-first"><code>void</code></td>
<th class="col-second" scope="row"><code><span class="member-name-link"><a href="#render(com.jogamp.opengl.GL2)">render</a></span>​(com.jogamp.opengl.GL2 gl2)</code></th>
<td class="col-last"> </td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</li>
</ul>
</section>
<section class="details">
<ul class="details-list">
<!-- ============ METHOD DETAIL ========== -->
<li>
<section class="method-details" id="method.detail">
<h2>Method Details</h2>
<ul class="member-list">
<li>
<section class="detail" id="render(com.jogamp.opengl.GL2)">
<h3>render</h3>
<div class="member-signature"><span class="return-type">void</span> <span class="member-name">render</span>​(<span class="parameters">com.jogamp.opengl.GL2 gl2)</span></div>
</section>
</li>
</ul>
</section>
</li>
</ul>
</section>
<!-- ========= END OF CLASS DATA ========= -->
</main>
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottom-nav" id="navbar.bottom">
<div class="skip-nav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<ul id="navbar.bottom.firstrow" class="nav-list" title="Navigation">
<li><a href="../../../../index.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="nav-bar-cell1-rev">Class</li>
<li><a href="class-use/PreviewListener.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="sub-nav">
<div>
<ul class="sub-nav-list">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="sub-nav-list">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
</div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<span class="skip-nav" id="skip.navbar.bottom">
<!-- -->
</span></nav>
<p class="legal-copy"><small>Copyright © 2021 <a href="http://www.marginallyclever.com/">Marginally Clever Robots, Limited.</a>. All rights reserved.</small></p>
</footer>
</div>
</div>
</body>
</html>
| MarginallyClever/Makelangelo | docs/com/marginallyclever/makelangelo/preview/PreviewListener.html | HTML | gpl-2.0 | 7,526 |
#include "../frisbee.c"
/*
* This program 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 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 Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*/
/* Test Case 2
* Turn on LED, or Blink LED
*/
int main(void)
{
struct sched_t sched[NUM_LEDS];
init_microcontroller();
clearbit(PORTA, LED_RED);
//scheduler_fill(sched, 0, 0, 1);
for (;;)
{
//scheduler_run(sched);
/*
setbit(PORTA, PA0);
_delay_ms(1000);
clearbit(PORTA, PA0);
_delay_ms(1000);
*/
}
return 0;
}
| branstem/OperationAwesome | src/test2/test2.c | C | gpl-2.0 | 1,115 |
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\Utils;
class Helpers
{
/**
* Captures PHP output into a string.
*/
public static function capture(callable $func): string
{
ob_start(function () {});
try {
$func();
return ob_get_clean();
} catch (\Throwable $e) {
ob_end_clean();
throw $e;
}
}
/**
* Returns the last PHP error as plain string.
*/
public static function getLastError(): string
{
$message = error_get_last()['message'] ?? '';
$message = ini_get('html_errors') ? Html::htmlToText($message) : $message;
$message = preg_replace('#^\w+\(.*?\): #', '', $message);
return $message;
}
/**
* Converts false to null.
* @param mixed $val
* @return mixed
*/
public static function falseToNull($val)
{
return $val === false ? null : $val;
}
/**
* Finds the best suggestion (for 8-bit encoding).
* @param string[] $possibilities
*/
public static function getSuggestion(array $possibilities, string $value): ?string
{
$best = null;
$min = (strlen($value) / 4 + 1) * 10 + .1;
foreach (array_unique($possibilities) as $item) {
if ($item !== $value && ($len = levenshtein($item, $value, 10, 11, 10)) < $min) {
$min = $len;
$best = $item;
}
}
return $best;
}
}
| moravianlibrary/CPK | vendor/nette/utils/src/Utils/Helpers.php | PHP | gpl-2.0 | 1,393 |
/* $Id$ */
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <pjsua-lib/pjsua.h>
#include <pjsua-lib/pjsua_internal.h>
#define THIS_FILE "pjsua_acc.c"
enum
{
OUTBOUND_UNKNOWN, // status unknown
OUTBOUND_WANTED, // initiated in registration
OUTBOUND_ACTIVE, // got positive response from server
OUTBOUND_NA // not wanted or got negative response from server
};
static void schedule_reregistration(pjsua_acc *acc);
static void keep_alive_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te);
/*
* Get number of current accounts.
*/
PJ_DEF(unsigned) pjsua_acc_get_count(void)
{
return pjsua_var.acc_cnt;
}
/*
* Check if the specified account ID is valid.
*/
PJ_DEF(pj_bool_t) pjsua_acc_is_valid(pjsua_acc_id acc_id)
{
return acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc) &&
pjsua_var.acc[acc_id].valid;
}
/*
* Set default account
*/
PJ_DEF(pj_status_t) pjsua_acc_set_default(pjsua_acc_id acc_id)
{
pjsua_var.default_acc = acc_id;
return PJ_SUCCESS;
}
/*
* Get default account.
*/
PJ_DEF(pjsua_acc_id) pjsua_acc_get_default(void)
{
return pjsua_var.default_acc;
}
/*
* Copy account configuration.
*/
PJ_DEF(void) pjsua_acc_config_dup( pj_pool_t *pool,
pjsua_acc_config *dst,
const pjsua_acc_config *src)
{
unsigned i;
pj_memcpy(dst, src, sizeof(pjsua_acc_config));
pj_strdup_with_null(pool, &dst->id, &src->id);
pj_strdup_with_null(pool, &dst->reg_uri, &src->reg_uri);
pj_strdup_with_null(pool, &dst->force_contact, &src->force_contact);
pj_strdup_with_null(pool, &dst->contact_params, &src->contact_params);
pj_strdup_with_null(pool, &dst->contact_uri_params,
&src->contact_uri_params);
pj_strdup_with_null(pool, &dst->pidf_tuple_id, &src->pidf_tuple_id);
pj_strdup_with_null(pool, &dst->rfc5626_instance_id,
&src->rfc5626_instance_id);
pj_strdup_with_null(pool, &dst->rfc5626_reg_id, &src->rfc5626_reg_id);
dst->proxy_cnt = src->proxy_cnt;
for (i=0; i<src->proxy_cnt; ++i)
pj_strdup_with_null(pool, &dst->proxy[i], &src->proxy[i]);
dst->reg_timeout = src->reg_timeout;
dst->reg_delay_before_refresh = src->reg_delay_before_refresh;
dst->cred_count = src->cred_count;
for (i=0; i<src->cred_count; ++i) {
pjsip_cred_dup(pool, &dst->cred_info[i], &src->cred_info[i]);
}
pj_list_init(&dst->reg_hdr_list);
if (!pj_list_empty(&src->reg_hdr_list)) {
const pjsip_hdr *hdr;
hdr = src->reg_hdr_list.next;
while (hdr != &src->reg_hdr_list) {
pj_list_push_back(&dst->reg_hdr_list, pjsip_hdr_clone(pool, hdr));
hdr = hdr->next;
}
}
pj_list_init(&dst->sub_hdr_list);
if (!pj_list_empty(&src->sub_hdr_list)) {
const pjsip_hdr *hdr;
hdr = src->sub_hdr_list.next;
while (hdr != &src->sub_hdr_list) {
pj_list_push_back(&dst->sub_hdr_list, pjsip_hdr_clone(pool, hdr));
hdr = hdr->next;
}
}
pjsip_auth_clt_pref_dup(pool, &dst->auth_pref, &src->auth_pref);
pjsua_transport_config_dup(pool, &dst->rtp_cfg, &src->rtp_cfg);
pjsua_ice_config_dup(pool, &dst->ice_cfg, &src->ice_cfg);
pjsua_turn_config_dup(pool, &dst->turn_cfg, &src->turn_cfg);
pj_strdup(pool, &dst->ka_data, &src->ka_data);
}
/*
* Calculate CRC of proxy list.
*/
static pj_uint32_t calc_proxy_crc(const pj_str_t proxy[], pj_size_t cnt)
{
pj_crc32_context ctx;
unsigned i;
pj_crc32_init(&ctx);
for (i=0; i<cnt; ++i) {
pj_crc32_update(&ctx, (pj_uint8_t*)proxy[i].ptr, proxy[i].slen);
}
return pj_crc32_final(&ctx);
}
/*
* Initialize a new account (after configuration is set).
*/
static pj_status_t initialize_acc(unsigned acc_id)
{
pjsua_acc_config *acc_cfg = &pjsua_var.acc[acc_id].cfg;
pjsua_acc *acc = &pjsua_var.acc[acc_id];
pjsip_name_addr *name_addr;
pjsip_sip_uri *sip_reg_uri;
pj_status_t status;
unsigned i;
/* Need to parse local_uri to get the elements: */
name_addr = (pjsip_name_addr*)
pjsip_parse_uri(acc->pool, acc_cfg->id.ptr,
acc_cfg->id.slen,
PJSIP_PARSE_URI_AS_NAMEADDR);
if (name_addr == NULL) {
pjsua_perror(THIS_FILE, "Invalid local URI",
PJSIP_EINVALIDURI);
return PJSIP_EINVALIDURI;
}
/* Local URI MUST be a SIP or SIPS: */
if (!PJSIP_URI_SCHEME_IS_SIP(name_addr) &&
!PJSIP_URI_SCHEME_IS_SIPS(name_addr))
{
acc->display = name_addr->display;
acc->user_part = name_addr->display;
acc->srv_domain = pj_str("");
acc->srv_port = 0;
} else {
pjsip_sip_uri *sip_uri;
/* Get the SIP URI object: */
sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(name_addr);
/* Save the user and domain part. These will be used when finding an
* account for incoming requests.
*/
acc->display = name_addr->display;
acc->user_part = sip_uri->user;
acc->srv_domain = sip_uri->host;
acc->srv_port = 0;
}
acc->is_sips = PJSIP_URI_SCHEME_IS_SIPS(name_addr);
/* Parse registrar URI, if any */
if (acc_cfg->reg_uri.slen) {
pjsip_uri *reg_uri;
reg_uri = pjsip_parse_uri(acc->pool, acc_cfg->reg_uri.ptr,
acc_cfg->reg_uri.slen, 0);
if (reg_uri == NULL) {
pjsua_perror(THIS_FILE, "Invalid registrar URI",
PJSIP_EINVALIDURI);
return PJSIP_EINVALIDURI;
}
/* Registrar URI MUST be a SIP or SIPS: */
if (!PJSIP_URI_SCHEME_IS_SIP(reg_uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(reg_uri))
{
pjsua_perror(THIS_FILE, "Invalid registar URI",
PJSIP_EINVALIDSCHEME);
return PJSIP_EINVALIDSCHEME;
}
sip_reg_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(reg_uri);
} else {
sip_reg_uri = NULL;
}
if (sip_reg_uri) {
acc->srv_port = sip_reg_uri->port;
}
/* Create Contact header if not present. */
//if (acc_cfg->contact.slen == 0) {
// acc_cfg->contact = acc_cfg->id;
//}
/* Build account route-set from outbound proxies and route set from
* account configuration.
*/
pj_list_init(&acc->route_set);
if (!pj_list_empty(&pjsua_var.outbound_proxy)) {
pjsip_route_hdr *r;
r = pjsua_var.outbound_proxy.next;
while (r != &pjsua_var.outbound_proxy) {
pj_list_push_back(&acc->route_set,
pjsip_hdr_shallow_clone(acc->pool, r));
r = r->next;
}
}
for (i=0; i<acc_cfg->proxy_cnt; ++i) {
pj_str_t hname = { "Route", 5};
pjsip_route_hdr *r;
pj_str_t tmp;
pj_strdup_with_null(acc->pool, &tmp, &acc_cfg->proxy[i]);
r = (pjsip_route_hdr*)
pjsip_parse_hdr(acc->pool, &hname, tmp.ptr, tmp.slen, NULL);
if (r == NULL) {
pjsua_perror(THIS_FILE, "Invalid URI in account route set",
PJ_EINVAL);
return PJ_EINVAL;
}
pj_list_push_back(&acc->route_set, r);
}
/* Concatenate credentials from account config and global config */
acc->cred_cnt = 0;
for (i=0; i<acc_cfg->cred_count; ++i) {
acc->cred[acc->cred_cnt++] = acc_cfg->cred_info[i];
}
for (i=0; i<pjsua_var.ua_cfg.cred_count &&
acc->cred_cnt < PJ_ARRAY_SIZE(acc->cred); ++i)
{
acc->cred[acc->cred_cnt++] = pjsua_var.ua_cfg.cred_info[i];
}
/* If account's ICE and TURN customization is not set, then
* initialize it with the settings from the global media config.
*/
if (acc->cfg.ice_cfg_use == PJSUA_ICE_CONFIG_USE_DEFAULT) {
pjsua_ice_config_from_media_config(NULL, &acc->cfg.ice_cfg,
&pjsua_var.media_cfg);
}
if (acc->cfg.turn_cfg_use == PJSUA_TURN_CONFIG_USE_DEFAULT) {
pjsua_turn_config_from_media_config(NULL, &acc->cfg.turn_cfg,
&pjsua_var.media_cfg);
}
/* If ICE is enabled, add "+sip.ice" media feature tag in account's
* contact params.
*/
#if PJSUA_ADD_ICE_TAGS
if (acc_cfg->ice_cfg.enable_ice) {
pj_ssize_t new_len;
pj_str_t new_prm;
new_len = acc_cfg->contact_params.slen + 10;
new_prm.ptr = (char*)pj_pool_alloc(acc->pool, new_len);
pj_strcpy(&new_prm, &acc_cfg->contact_params);
pj_strcat2(&new_prm, ";+sip.ice");
acc_cfg->contact_params = new_prm;
}
#endif
status = pjsua_pres_init_acc(acc_id);
if (status != PJ_SUCCESS)
return status;
/* If SIP outbound is enabled, generate instance and reg ID if they are
* not specified
*/
if (acc_cfg->use_rfc5626) {
if (acc_cfg->rfc5626_instance_id.slen==0) {
const pj_str_t *hostname;
pj_uint32_t hval;
pj_size_t pos;
char instprm[] = ";+sip.instance=\"<urn:uuid:00000000-0000-0000-0000-0000CCDDEEFF>\"";
hostname = pj_gethostname();
pos = pj_ansi_strlen(instprm) - 10;
hval = pj_hash_calc(0, hostname->ptr, (unsigned)hostname->slen);
pj_val_to_hex_digit( ((char*)&hval)[0], instprm+pos+0);
pj_val_to_hex_digit( ((char*)&hval)[1], instprm+pos+2);
pj_val_to_hex_digit( ((char*)&hval)[2], instprm+pos+4);
pj_val_to_hex_digit( ((char*)&hval)[3], instprm+pos+6);
pj_strdup2(acc->pool, &acc->rfc5626_instprm, instprm);
} else {
const char *prmname = ";+sip.instance=\"";
pj_size_t len;
len = pj_ansi_strlen(prmname) + acc_cfg->rfc5626_instance_id.slen + 1;
acc->rfc5626_instprm.ptr = (char*)pj_pool_alloc(acc->pool, len+1);
pj_ansi_snprintf(acc->rfc5626_instprm.ptr, len+1,
"%s%.*s\"",
prmname,
(int)acc_cfg->rfc5626_instance_id.slen,
acc_cfg->rfc5626_instance_id.ptr);
acc->rfc5626_instprm.slen = len;
}
if (acc_cfg->rfc5626_reg_id.slen==0) {
acc->rfc5626_regprm = pj_str(";reg-id=1");
} else {
const char *prmname = ";reg-id=";
pj_size_t len;
len = pj_ansi_strlen(prmname) + acc_cfg->rfc5626_reg_id.slen;
acc->rfc5626_regprm.ptr = (char*)pj_pool_alloc(acc->pool, len+1);
pj_ansi_snprintf(acc->rfc5626_regprm.ptr, len+1,
"%s%.*s\"",
prmname,
(int)acc_cfg->rfc5626_reg_id.slen,
acc_cfg->rfc5626_reg_id.ptr);
acc->rfc5626_regprm.slen = len;
}
acc->rfc5626_status = OUTBOUND_WANTED;
}
/* Mark account as valid */
pjsua_var.acc[acc_id].valid = PJ_TRUE;
/* Insert account ID into account ID array, sorted by priority */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
if ( pjsua_var.acc[pjsua_var.acc_ids[i]].cfg.priority <
pjsua_var.acc[acc_id].cfg.priority)
{
break;
}
}
pj_array_insert(pjsua_var.acc_ids, sizeof(pjsua_var.acc_ids[0]),
pjsua_var.acc_cnt, i, &acc_id);
return PJ_SUCCESS;
}
/*
* Add a new account to pjsua.
*/
PJ_DEF(pj_status_t) pjsua_acc_add( const pjsua_acc_config *cfg,
pj_bool_t is_default,
pjsua_acc_id *p_acc_id)
{
pjsua_acc *acc;
unsigned i, id;
pj_status_t status = PJ_SUCCESS;
PJ_ASSERT_RETURN(cfg, PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc_cnt < PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_ETOOMANY);
/* Must have a transport */
PJ_ASSERT_RETURN(pjsua_var.tpdata[0].data.ptr != NULL, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Adding account: id=%.*s",
(int)cfg->id.slen, cfg->id.ptr));
pj_log_push_indent();
PJSUA_LOCK();
/* Find empty account id. */
for (id=0; id < PJ_ARRAY_SIZE(pjsua_var.acc); ++id) {
if (pjsua_var.acc[id].valid == PJ_FALSE)
break;
}
/* Expect to find a slot */
PJ_ASSERT_ON_FAIL( id < PJ_ARRAY_SIZE(pjsua_var.acc),
{PJSUA_UNLOCK(); return PJ_EBUG;});
acc = &pjsua_var.acc[id];
/* Create pool for this account. */
if (acc->pool)
pj_pool_reset(acc->pool);
else
acc->pool = pjsua_pool_create("acc%p", 512, 256);
/* Copy config */
pjsua_acc_config_dup(acc->pool, &pjsua_var.acc[id].cfg, cfg);
/* Normalize registration timeout and refresh delay */
if (pjsua_var.acc[id].cfg.reg_uri.slen) {
if (pjsua_var.acc[id].cfg.reg_timeout == 0) {
pjsua_var.acc[id].cfg.reg_timeout = PJSUA_REG_INTERVAL;
}
if (pjsua_var.acc[id].cfg.reg_delay_before_refresh == 0) {
pjsua_var.acc[id].cfg.reg_delay_before_refresh =
PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH;
}
}
/* Check the route URI's and force loose route if required */
for (i=0; i<acc->cfg.proxy_cnt; ++i) {
status = normalize_route_uri(acc->pool, &acc->cfg.proxy[i]);
if (status != PJ_SUCCESS) {
PJSUA_UNLOCK();
pj_log_pop_indent();
return status;
}
}
/* Get CRC of account proxy setting */
acc->local_route_crc = calc_proxy_crc(acc->cfg.proxy, acc->cfg.proxy_cnt);
/* Get CRC of global outbound proxy setting */
acc->global_route_crc=calc_proxy_crc(pjsua_var.ua_cfg.outbound_proxy,
pjsua_var.ua_cfg.outbound_proxy_cnt);
status = initialize_acc(id);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Error adding account", status);
pj_pool_release(acc->pool);
acc->pool = NULL;
PJSUA_UNLOCK();
pj_log_pop_indent();
return status;
}
if (is_default)
pjsua_var.default_acc = id;
if (p_acc_id)
*p_acc_id = id;
pjsua_var.acc_cnt++;
PJSUA_UNLOCK();
PJ_LOG(4,(THIS_FILE, "Account %.*s added with id %d",
(int)cfg->id.slen, cfg->id.ptr, id));
/* If accounts has registration enabled, start registration */
if (pjsua_var.acc[id].cfg.reg_uri.slen) {
if (pjsua_var.acc[id].cfg.register_on_acc_add)
pjsua_acc_set_registration(id, PJ_TRUE);
} else {
/* Otherwise subscribe to MWI, if it's enabled */
if (pjsua_var.acc[id].cfg.mwi_enabled)
pjsua_start_mwi(id, PJ_TRUE);
/* Start publish too */
if (acc->cfg.publish_enabled)
pjsua_pres_init_publish_acc(id);
}
pj_log_pop_indent();
return PJ_SUCCESS;
}
/*
* Add local account
*/
PJ_DEF(pj_status_t) pjsua_acc_add_local( pjsua_transport_id tid,
pj_bool_t is_default,
pjsua_acc_id *p_acc_id)
{
pjsua_acc_config cfg;
pjsua_transport_data *t = &pjsua_var.tpdata[tid];
const char *beginquote, *endquote;
char transport_param[32];
char uri[PJSIP_MAX_URL_SIZE];
/* ID must be valid */
PJ_ASSERT_RETURN(tid>=0 && tid<(int)PJ_ARRAY_SIZE(pjsua_var.tpdata),
PJ_EINVAL);
/* Transport must be valid */
PJ_ASSERT_RETURN(t->data.ptr != NULL, PJ_EINVAL);
pjsua_acc_config_default(&cfg);
/* Lower the priority of local account */
--cfg.priority;
/* Enclose IPv6 address in square brackets */
if (t->type & PJSIP_TRANSPORT_IPV6) {
beginquote = "[";
endquote = "]";
} else {
beginquote = endquote = "";
}
/* Don't add transport parameter if it's UDP */
if (t->type!=PJSIP_TRANSPORT_UDP && t->type!=PJSIP_TRANSPORT_UDP6) {
pj_ansi_snprintf(transport_param, sizeof(transport_param),
";transport=%s",
pjsip_transport_get_type_name(t->type));
} else {
transport_param[0] = '\0';
}
/* Build URI for the account */
pj_ansi_snprintf(uri, PJSIP_MAX_URL_SIZE,
"<sip:%s%.*s%s:%d%s>",
beginquote,
(int)t->local_name.host.slen,
t->local_name.host.ptr,
endquote,
t->local_name.port,
transport_param);
cfg.id = pj_str(uri);
return pjsua_acc_add(&cfg, is_default, p_acc_id);
}
/*
* Set arbitrary data to be associated with the account.
*/
PJ_DEF(pj_status_t) pjsua_acc_set_user_data(pjsua_acc_id acc_id,
void *user_data)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJSUA_LOCK();
pjsua_var.acc[acc_id].cfg.user_data = user_data;
PJSUA_UNLOCK();
return PJ_SUCCESS;
}
/*
* Retrieve arbitrary data associated with the account.
*/
PJ_DEF(void*) pjsua_acc_get_user_data(pjsua_acc_id acc_id)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
NULL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, NULL);
return pjsua_var.acc[acc_id].cfg.user_data;
}
/*
* Delete account.
*/
PJ_DEF(pj_status_t) pjsua_acc_del(pjsua_acc_id acc_id)
{
pjsua_acc *acc;
unsigned i;
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Deleting account %d..", acc_id));
pj_log_push_indent();
PJSUA_LOCK();
acc = &pjsua_var.acc[acc_id];
/* Cancel keep-alive timer, if any */
if (acc->ka_timer.id) {
pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer);
acc->ka_timer.id = PJ_FALSE;
}
if (acc->ka_transport) {
pjsip_transport_dec_ref(acc->ka_transport);
acc->ka_transport = NULL;
}
/* Cancel any re-registration timer */
if (acc->auto_rereg.timer.id) {
acc->auto_rereg.timer.id = PJ_FALSE;
pjsua_cancel_timer(&acc->auto_rereg.timer);
}
/* Delete registration */
if (acc->regc != NULL) {
pjsua_acc_set_registration(acc_id, PJ_FALSE);
if (acc->regc) {
pjsip_regc_destroy(acc->regc);
}
acc->regc = NULL;
}
/* Terminate mwi subscription */
if (acc->cfg.mwi_enabled) {
acc->cfg.mwi_enabled = PJ_FALSE;
pjsua_start_mwi(acc_id, PJ_FALSE);
}
/* Delete server presence subscription */
pjsua_pres_delete_acc(acc_id, 0);
/* Release account pool */
if (acc->pool) {
pj_pool_release(acc->pool);
acc->pool = NULL;
}
/* Invalidate */
acc->valid = PJ_FALSE;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
pj_bzero(&acc->via_addr, sizeof(acc->via_addr));
acc->via_tp = NULL;
acc->next_rtp_port = 0;
/* Remove from array */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
if (pjsua_var.acc_ids[i] == acc_id)
break;
}
if (i != pjsua_var.acc_cnt) {
pj_array_erase(pjsua_var.acc_ids, sizeof(pjsua_var.acc_ids[0]),
pjsua_var.acc_cnt, i);
--pjsua_var.acc_cnt;
}
/* Leave the calls intact, as I don't think calls need to
* access account once it's created
*/
/* Update default account */
if (pjsua_var.default_acc == acc_id)
pjsua_var.default_acc = 0;
PJSUA_UNLOCK();
PJ_LOG(4,(THIS_FILE, "Account id %d deleted", acc_id));
pj_log_pop_indent();
return PJ_SUCCESS;
}
/* Get config */
PJ_DEF(pj_status_t) pjsua_acc_get_config(pjsua_acc_id acc_id,
pj_pool_t *pool,
pjsua_acc_config *acc_cfg)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc)
&& pjsua_var.acc[acc_id].valid, PJ_EINVAL);
//this now would not work due to corrupt header list
//pj_memcpy(acc_cfg, &pjsua_var.acc[acc_id].cfg, sizeof(*acc_cfg));
pjsua_acc_config_dup(pool, acc_cfg, &pjsua_var.acc[acc_id].cfg);
return PJ_SUCCESS;
}
/* Compare two SIP headers. Return zero if equal */
static int pjsip_hdr_cmp(const pjsip_hdr *h1, const pjsip_hdr *h2)
{
char buf1[PJSIP_MAX_URL_SIZE];
char buf2[PJSIP_MAX_URL_SIZE];
pj_str_t p1, p2;
p1.ptr = buf1;
p1.slen = 0;
p2.ptr = buf2;
p2.slen = 0;
p1.slen = pjsip_hdr_print_on((void*)h1, buf1, sizeof(buf1));
if (p1.slen < 0)
p1.slen = 0;
p2.slen = pjsip_hdr_print_on((void*)h2, buf2, sizeof(buf2));
if (p2.slen < 0)
p2.slen = 0;
return pj_strcmp(&p1, &p2);
}
/* Update SIP header list from another list. Return PJ_TRUE if
* the list has been updated */
static pj_bool_t update_hdr_list(pj_pool_t *pool, pjsip_hdr *dst,
const pjsip_hdr *src)
{
pjsip_hdr *dst_i;
const pjsip_hdr *src_i;
pj_bool_t changed = PJ_FALSE;
/* Remove header that's no longer needed */
for (dst_i = dst->next; dst_i != dst; ) {
for (src_i = src->next; src_i != src; src_i = src_i->next) {
if (pjsip_hdr_cmp(dst_i, src_i) == 0)
break;
}
if (src_i == src) {
pjsip_hdr *next = dst_i->next;
pj_list_erase(dst_i);
changed = PJ_TRUE;
dst_i = next;
} else {
dst_i = dst_i->next;
}
}
/* Add new header */
for (src_i = src->next; src_i != src; src_i = src_i->next) {
for (dst_i = dst->next; dst_i != dst; dst_i = dst_i->next) {
if (pjsip_hdr_cmp(dst_i, src_i) == 0)
break;
}
if (dst_i == dst) {
dst_i = pjsip_hdr_clone(pool, src_i);
pj_list_push_back(dst, dst_i);
changed = PJ_TRUE;
}
}
return changed;
}
/*
* Modify account information.
*/
PJ_DEF(pj_status_t) pjsua_acc_modify( pjsua_acc_id acc_id,
const pjsua_acc_config *cfg)
{
pjsua_acc *acc;
pjsip_name_addr *id_name_addr = NULL;
pjsip_sip_uri *id_sip_uri = NULL;
pjsip_sip_uri *reg_sip_uri = NULL;
pj_uint32_t local_route_crc, global_route_crc;
pjsip_route_hdr global_route;
pjsip_route_hdr local_route;
pj_str_t acc_proxy[PJSUA_ACC_MAX_PROXIES];
pj_bool_t update_reg = PJ_FALSE;
pj_bool_t unreg_first = PJ_FALSE;
pj_bool_t update_mwi = PJ_FALSE;
pj_status_t status = PJ_SUCCESS;
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_LOG(4,(THIS_FILE, "Modifying accunt %d", acc_id));
pj_log_push_indent();
PJSUA_LOCK();
acc = &pjsua_var.acc[acc_id];
if (!acc->valid) {
status = PJ_EINVAL;
goto on_return;
}
/* == Validate first == */
/* Account id */
if (pj_strcmp(&acc->cfg.id, &cfg->id)) {
/* Need to parse id to get the elements: */
id_name_addr = (pjsip_name_addr*)
pjsip_parse_uri(acc->pool, cfg->id.ptr, cfg->id.slen,
PJSIP_PARSE_URI_AS_NAMEADDR);
if (id_name_addr == NULL) {
status = PJSIP_EINVALIDURI;
pjsua_perror(THIS_FILE, "Invalid local URI", status);
goto on_return;
}
/* URI MUST be a SIP or SIPS: */
if (!PJSIP_URI_SCHEME_IS_SIP(id_name_addr) &&
!PJSIP_URI_SCHEME_IS_SIPS(id_name_addr))
{
status = PJSIP_EINVALIDSCHEME;
pjsua_perror(THIS_FILE, "Invalid local URI", status);
goto on_return;
}
/* Get the SIP URI object: */
id_sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(id_name_addr);
}
/* Registrar URI */
if (pj_strcmp(&acc->cfg.reg_uri, &cfg->reg_uri) && cfg->reg_uri.slen) {
pjsip_uri *reg_uri;
/* Need to parse reg_uri to get the elements: */
reg_uri = pjsip_parse_uri(acc->pool, cfg->reg_uri.ptr,
cfg->reg_uri.slen, 0);
if (reg_uri == NULL) {
status = PJSIP_EINVALIDURI;
pjsua_perror(THIS_FILE, "Invalid registrar URI", status);
goto on_return;
}
/* Registrar URI MUST be a SIP or SIPS: */
if (!PJSIP_URI_SCHEME_IS_SIP(reg_uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(reg_uri))
{
status = PJSIP_EINVALIDSCHEME;
pjsua_perror(THIS_FILE, "Invalid registar URI", status);
goto on_return;
}
reg_sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(reg_uri);
}
/* REGISTER header list */
if (update_hdr_list(acc->pool, &acc->cfg.reg_hdr_list, &cfg->reg_hdr_list)) {
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* SUBSCRIBE header list */
update_hdr_list(acc->pool, &acc->cfg.sub_hdr_list, &cfg->sub_hdr_list);
/* Global outbound proxy */
global_route_crc = calc_proxy_crc(pjsua_var.ua_cfg.outbound_proxy,
pjsua_var.ua_cfg.outbound_proxy_cnt);
if (global_route_crc != acc->global_route_crc) {
pjsip_route_hdr *r;
/* Copy from global outbound proxies */
pj_list_init(&global_route);
r = pjsua_var.outbound_proxy.next;
while (r != &pjsua_var.outbound_proxy) {
pj_list_push_back(&global_route,
pjsip_hdr_shallow_clone(acc->pool, r));
r = r->next;
}
}
/* Account proxy */
local_route_crc = calc_proxy_crc(cfg->proxy, cfg->proxy_cnt);
if (local_route_crc != acc->local_route_crc) {
pjsip_route_hdr *r;
unsigned i;
/* Validate the local route and save it to temporary var */
pj_list_init(&local_route);
for (i=0; i<cfg->proxy_cnt; ++i) {
pj_str_t hname = { "Route", 5};
pj_strdup_with_null(acc->pool, &acc_proxy[i], &cfg->proxy[i]);
status = normalize_route_uri(acc->pool, &acc_proxy[i]);
if (status != PJ_SUCCESS)
goto on_return;
r = (pjsip_route_hdr*)
pjsip_parse_hdr(acc->pool, &hname, acc_proxy[i].ptr,
acc_proxy[i].slen, NULL);
if (r == NULL) {
status = PJSIP_EINVALIDURI;
pjsua_perror(THIS_FILE, "Invalid URI in account route set",
status);
goto on_return;
}
pj_list_push_back(&local_route, r);
}
/* Recalculate the CRC again after route URI normalization */
local_route_crc = calc_proxy_crc(acc_proxy, cfg->proxy_cnt);
}
/* == Apply the new config == */
/* Account ID. */
if (id_name_addr && id_sip_uri) {
pj_strdup_with_null(acc->pool, &acc->cfg.id, &cfg->id);
pj_strdup_with_null(acc->pool, &acc->display, &id_name_addr->display);
pj_strdup_with_null(acc->pool, &acc->user_part, &id_sip_uri->user);
pj_strdup_with_null(acc->pool, &acc->srv_domain, &id_sip_uri->host);
acc->srv_port = 0;
acc->is_sips = PJSIP_URI_SCHEME_IS_SIPS(id_name_addr);
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* User data */
acc->cfg.user_data = cfg->user_data;
/* Priority */
if (acc->cfg.priority != cfg->priority) {
unsigned i;
acc->cfg.priority = cfg->priority;
/* Resort accounts priority */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
if (pjsua_var.acc_ids[i] == acc_id)
break;
}
pj_assert(i < pjsua_var.acc_cnt);
pj_array_erase(pjsua_var.acc_ids, sizeof(acc_id),
pjsua_var.acc_cnt, i);
for (i=0; i<pjsua_var.acc_cnt; ++i) {
if (pjsua_var.acc[pjsua_var.acc_ids[i]].cfg.priority <
acc->cfg.priority)
{
break;
}
}
pj_array_insert(pjsua_var.acc_ids, sizeof(acc_id),
pjsua_var.acc_cnt, i, &acc_id);
}
/* MWI */
if (acc->cfg.mwi_enabled != cfg->mwi_enabled) {
acc->cfg.mwi_enabled = cfg->mwi_enabled;
update_mwi = PJ_TRUE;
}
if (acc->cfg.mwi_expires != cfg->mwi_expires && cfg->mwi_expires > 0) {
acc->cfg.mwi_expires = cfg->mwi_expires;
update_mwi = PJ_TRUE;
}
/* PIDF tuple ID */
if (pj_strcmp(&acc->cfg.pidf_tuple_id, &cfg->pidf_tuple_id))
pj_strdup_with_null(acc->pool, &acc->cfg.pidf_tuple_id,
&cfg->pidf_tuple_id);
/* Publish */
acc->cfg.publish_opt = cfg->publish_opt;
acc->cfg.unpublish_max_wait_time_msec = cfg->unpublish_max_wait_time_msec;
if (acc->cfg.publish_enabled != cfg->publish_enabled) {
acc->cfg.publish_enabled = cfg->publish_enabled;
if (!acc->cfg.publish_enabled)
pjsua_pres_unpublish(acc, 0);
else
update_reg = PJ_TRUE;
}
/* Force contact URI */
if (pj_strcmp(&acc->cfg.force_contact, &cfg->force_contact)) {
pj_strdup_with_null(acc->pool, &acc->cfg.force_contact,
&cfg->force_contact);
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Contact param */
if (pj_strcmp(&acc->cfg.contact_params, &cfg->contact_params)) {
pj_strdup_with_null(acc->pool, &acc->cfg.contact_params,
&cfg->contact_params);
update_reg = PJ_TRUE;
}
/* Contact URI params */
if (pj_strcmp(&acc->cfg.contact_uri_params, &cfg->contact_uri_params)) {
pj_strdup_with_null(acc->pool, &acc->cfg.contact_uri_params,
&cfg->contact_uri_params);
update_reg = PJ_TRUE;
}
/* Reliable provisional response */
acc->cfg.require_100rel = cfg->require_100rel;
/* Session timer */
acc->cfg.use_timer = cfg->use_timer;
acc->cfg.timer_setting = cfg->timer_setting;
/* Transport */
if (acc->cfg.transport_id != cfg->transport_id) {
acc->cfg.transport_id = cfg->transport_id;
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Update keep-alive */
if (acc->cfg.ka_interval != cfg->ka_interval ||
pj_strcmp(&acc->cfg.ka_data, &cfg->ka_data))
{
pjsip_transport *ka_transport = acc->ka_transport;
if (acc->ka_timer.id) {
pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer);
acc->ka_timer.id = PJ_FALSE;
}
if (acc->ka_transport) {
pjsip_transport_dec_ref(acc->ka_transport);
acc->ka_transport = NULL;
}
acc->cfg.ka_interval = cfg->ka_interval;
if (cfg->ka_interval) {
if (ka_transport) {
/* Keep-alive has been running so we can just restart it */
pj_time_val delay;
pjsip_transport_add_ref(ka_transport);
acc->ka_transport = ka_transport;
acc->ka_timer.cb = &keep_alive_timer_cb;
acc->ka_timer.user_data = (void*)acc;
delay.sec = acc->cfg.ka_interval;
delay.msec = 0;
status = pjsua_schedule_timer(&acc->ka_timer, &delay);
if (status == PJ_SUCCESS) {
acc->ka_timer.id = PJ_TRUE;
} else {
pjsip_transport_dec_ref(ka_transport);
acc->ka_transport = NULL;
pjsua_perror(THIS_FILE, "Error starting keep-alive timer",
status);
}
} else {
/* Keep-alive has not been running, we need to (re)register
* first.
*/
update_reg = PJ_TRUE;
}
}
}
if (pj_strcmp(&acc->cfg.ka_data, &cfg->ka_data))
pj_strdup(acc->pool, &acc->cfg.ka_data, &cfg->ka_data);
#if defined(PJMEDIA_HAS_SRTP) && (PJMEDIA_HAS_SRTP != 0)
acc->cfg.use_srtp = cfg->use_srtp;
acc->cfg.srtp_secure_signaling = cfg->srtp_secure_signaling;
acc->cfg.srtp_optional_dup_offer = cfg->srtp_optional_dup_offer;
#endif
#if defined(PJMEDIA_STREAM_ENABLE_KA) && (PJMEDIA_STREAM_ENABLE_KA != 0)
acc->cfg.use_stream_ka = cfg->use_stream_ka;
#endif
/* Use of proxy */
if (acc->cfg.reg_use_proxy != cfg->reg_use_proxy) {
acc->cfg.reg_use_proxy = cfg->reg_use_proxy;
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Global outbound proxy */
if (global_route_crc != acc->global_route_crc) {
unsigned i;
pj_size_t rcnt;
/* Remove the outbound proxies from the route set */
rcnt = pj_list_size(&acc->route_set);
for (i=0; i < rcnt - acc->cfg.proxy_cnt; ++i) {
pjsip_route_hdr *r = acc->route_set.next;
pj_list_erase(r);
}
/* Insert the outbound proxies to the beginning of route set */
pj_list_merge_first(&acc->route_set, &global_route);
/* Update global route CRC */
acc->global_route_crc = global_route_crc;
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Account proxy */
if (local_route_crc != acc->local_route_crc) {
unsigned i;
/* Remove the current account proxies from the route set */
for (i=0; i < acc->cfg.proxy_cnt; ++i) {
pjsip_route_hdr *r = acc->route_set.prev;
pj_list_erase(r);
}
/* Insert new proxy setting to the route set */
pj_list_merge_last(&acc->route_set, &local_route);
/* Update the proxy setting */
acc->cfg.proxy_cnt = cfg->proxy_cnt;
for (i = 0; i < cfg->proxy_cnt; ++i)
acc->cfg.proxy[i] = acc_proxy[i];
/* Update local route CRC */
acc->local_route_crc = local_route_crc;
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Credential info */
{
unsigned i;
pj_bool_t cred_changed = PJ_FALSE;
/* Selective update credential info. */
for (i = 0; i < cfg->cred_count; ++i) {
unsigned j;
pjsip_cred_info ci;
/* Find if this credential is already listed */
for (j = i; j < acc->cfg.cred_count; ++j) {
if (pjsip_cred_info_cmp(&acc->cfg.cred_info[j],
&cfg->cred_info[i]) == 0)
{
/* Found, but different index/position, swap */
if (j != i) {
ci = acc->cfg.cred_info[i];
acc->cfg.cred_info[i] = acc->cfg.cred_info[j];
acc->cfg.cred_info[j] = ci;
}
break;
}
}
/* Not found, insert this */
if (j == acc->cfg.cred_count) {
cred_changed = PJ_TRUE;
/* If account credential is full, discard the last one. */
if (acc->cfg.cred_count == PJ_ARRAY_SIZE(acc->cfg.cred_info)) {
pj_array_erase(acc->cfg.cred_info, sizeof(pjsip_cred_info),
acc->cfg.cred_count, acc->cfg.cred_count-1);
acc->cfg.cred_count--;
}
/* Insert this */
pjsip_cred_info_dup(acc->pool, &ci, &cfg->cred_info[i]);
pj_array_insert(acc->cfg.cred_info, sizeof(pjsip_cred_info),
acc->cfg.cred_count, i, &ci);
}
}
acc->cfg.cred_count = cfg->cred_count;
/* Concatenate credentials from account config and global config */
acc->cred_cnt = 0;
for (i=0; i<acc->cfg.cred_count; ++i) {
acc->cred[acc->cred_cnt++] = acc->cfg.cred_info[i];
}
for (i=0; i<pjsua_var.ua_cfg.cred_count &&
acc->cred_cnt < PJ_ARRAY_SIZE(acc->cred); ++i)
{
acc->cred[acc->cred_cnt++] = pjsua_var.ua_cfg.cred_info[i];
}
if (cred_changed) {
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
}
/* Authentication preference */
acc->cfg.auth_pref.initial_auth = cfg->auth_pref.initial_auth;
if (pj_strcmp(&acc->cfg.auth_pref.algorithm, &cfg->auth_pref.algorithm)) {
pj_strdup_with_null(acc->pool, &acc->cfg.auth_pref.algorithm,
&cfg->auth_pref.algorithm);
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* Registration */
if (acc->cfg.reg_timeout != cfg->reg_timeout) {
acc->cfg.reg_timeout = cfg->reg_timeout;
if (acc->regc != NULL)
pjsip_regc_update_expires(acc->regc, acc->cfg.reg_timeout);
update_reg = PJ_TRUE;
}
acc->cfg.unreg_timeout = cfg->unreg_timeout;
acc->cfg.allow_contact_rewrite = cfg->allow_contact_rewrite;
acc->cfg.reg_retry_interval = cfg->reg_retry_interval;
acc->cfg.reg_first_retry_interval = cfg->reg_first_retry_interval;
acc->cfg.reg_retry_random_interval = cfg->reg_retry_random_interval;
acc->cfg.drop_calls_on_reg_fail = cfg->drop_calls_on_reg_fail;
acc->cfg.register_on_acc_add = cfg->register_on_acc_add;
if (acc->cfg.reg_delay_before_refresh != cfg->reg_delay_before_refresh) {
acc->cfg.reg_delay_before_refresh = cfg->reg_delay_before_refresh;
if (acc->regc != NULL)
pjsip_regc_set_delay_before_refresh(acc->regc,
cfg->reg_delay_before_refresh);
}
/* Allow via rewrite */
if (acc->cfg.allow_via_rewrite != cfg->allow_via_rewrite) {
if (acc->regc != NULL) {
if (cfg->allow_via_rewrite) {
pjsip_regc_set_via_sent_by(acc->regc, &acc->via_addr,
acc->via_tp);
} else
pjsip_regc_set_via_sent_by(acc->regc, NULL, NULL);
}
if (acc->publish_sess != NULL) {
if (cfg->allow_via_rewrite) {
pjsip_publishc_set_via_sent_by(acc->publish_sess,
&acc->via_addr, acc->via_tp);
} else
pjsip_publishc_set_via_sent_by(acc->publish_sess, NULL, NULL);
}
acc->cfg.allow_via_rewrite = cfg->allow_via_rewrite;
}
/* Normalize registration timeout and refresh delay */
if (acc->cfg.reg_uri.slen ) {
if (acc->cfg.reg_timeout == 0) {
acc->cfg.reg_timeout = PJSUA_REG_INTERVAL;
}
if (acc->cfg.reg_delay_before_refresh == 0) {
acc->cfg.reg_delay_before_refresh =
PJSIP_REGISTER_CLIENT_DELAY_BEFORE_REFRESH;
}
}
/* Registrar URI */
if (pj_strcmp(&acc->cfg.reg_uri, &cfg->reg_uri)) {
if (cfg->reg_uri.slen) {
pj_strdup_with_null(acc->pool, &acc->cfg.reg_uri, &cfg->reg_uri);
if (reg_sip_uri)
acc->srv_port = reg_sip_uri->port;
}
update_reg = PJ_TRUE;
unreg_first = PJ_TRUE;
}
/* SIP outbound setting */
if (acc->cfg.use_rfc5626 != cfg->use_rfc5626 ||
pj_strcmp(&acc->cfg.rfc5626_instance_id, &cfg->rfc5626_instance_id) ||
pj_strcmp(&acc->cfg.rfc5626_reg_id, &cfg->rfc5626_reg_id))
{
update_reg = PJ_TRUE;
}
/* Video settings */
acc->cfg.vid_in_auto_show = cfg->vid_in_auto_show;
acc->cfg.vid_out_auto_transmit = cfg->vid_out_auto_transmit;
acc->cfg.vid_wnd_flags = cfg->vid_wnd_flags;
acc->cfg.vid_cap_dev = cfg->vid_cap_dev;
acc->cfg.vid_rend_dev = cfg->vid_rend_dev;
acc->cfg.vid_stream_rc_cfg = cfg->vid_stream_rc_cfg;
/* Media settings */
if (pj_stricmp(&acc->cfg.rtp_cfg.public_addr, &cfg->rtp_cfg.public_addr) ||
pj_stricmp(&acc->cfg.rtp_cfg.bound_addr, &cfg->rtp_cfg.bound_addr))
{
pjsua_transport_config_dup(acc->pool, &acc->cfg.rtp_cfg,
&cfg->rtp_cfg);
} else {
pj_str_t p_addr = acc->cfg.rtp_cfg.public_addr;
pj_str_t b_addr = acc->cfg.rtp_cfg.bound_addr;
/* ..to save memory by not using the pool */
acc->cfg.rtp_cfg = cfg->rtp_cfg;
acc->cfg.rtp_cfg.public_addr = p_addr;
acc->cfg.rtp_cfg.bound_addr = b_addr;
}
acc->cfg.ipv6_media_use = cfg->ipv6_media_use;
/* STUN and Media customization */
if (acc->cfg.sip_stun_use != cfg->sip_stun_use) {
acc->cfg.sip_stun_use = cfg->sip_stun_use;
update_reg = PJ_TRUE;
}
acc->cfg.media_stun_use = cfg->media_stun_use;
/* ICE settings */
acc->cfg.ice_cfg_use = cfg->ice_cfg_use;
switch (acc->cfg.ice_cfg_use) {
case PJSUA_ICE_CONFIG_USE_DEFAULT:
/* Copy ICE settings from media settings so that we don't need to
* check the media config if we look for ICE config.
*/
pjsua_ice_config_from_media_config(NULL, &acc->cfg.ice_cfg,
&pjsua_var.media_cfg);
break;
case PJSUA_ICE_CONFIG_USE_CUSTOM:
pjsua_ice_config_dup(acc->pool, &acc->cfg.ice_cfg, &cfg->ice_cfg);
break;
}
/* TURN settings */
acc->cfg.turn_cfg_use = cfg->turn_cfg_use;
switch (acc->cfg.turn_cfg_use) {
case PJSUA_TURN_CONFIG_USE_DEFAULT:
/* Copy TURN settings from media settings so that we don't need to
* check the media config if we look for TURN config.
*/
pjsua_turn_config_from_media_config(NULL, &acc->cfg.turn_cfg,
&pjsua_var.media_cfg);
break;
case PJSUA_TURN_CONFIG_USE_CUSTOM:
pjsua_turn_config_dup(acc->pool, &acc->cfg.turn_cfg,
&cfg->turn_cfg);
break;
}
acc->cfg.use_srtp = cfg->use_srtp;
/* Call hold type */
acc->cfg.call_hold_type = cfg->call_hold_type;
/* Unregister first */
if (unreg_first) {
status = pjsua_acc_set_registration(acc->index, PJ_FALSE);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Ignored failure in unregistering the "
"old account setting in modifying account", status);
/* Not really sure if we should return error */
status = PJ_SUCCESS;
}
if (acc->regc != NULL) {
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
}
if (!cfg->reg_uri.slen) {
/* Reg URI still needed, delay unset after sending unregister. */
pj_bzero(&acc->cfg.reg_uri, sizeof(acc->cfg.reg_uri));
}
}
/* Update registration */
if (update_reg) {
/* If accounts has registration enabled, start registration */
if (acc->cfg.reg_uri.slen) {
status = pjsua_acc_set_registration(acc->index, PJ_TRUE);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Failed to register with new account "
"setting in modifying account", status);
goto on_return;
}
}
}
/* Update MWI subscription */
if (update_mwi) {
status = pjsua_start_mwi(acc_id, PJ_TRUE);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Failed in starting MWI subscription for "
"new account setting in modifying account", status);
}
}
on_return:
PJSUA_UNLOCK();
pj_log_pop_indent();
return status;
}
/*
* Modify account's presence status to be advertised to remote/presence
* subscribers.
*/
PJ_DEF(pj_status_t) pjsua_acc_set_online_status( pjsua_acc_id acc_id,
pj_bool_t is_online)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Acc %d: setting online status to %d..",
acc_id, is_online));
pj_log_push_indent();
pjsua_var.acc[acc_id].online_status = is_online;
pj_bzero(&pjsua_var.acc[acc_id].rpid, sizeof(pjrpid_element));
pjsua_pres_update_acc(acc_id, PJ_FALSE);
pj_log_pop_indent();
return PJ_SUCCESS;
}
/*
* Set online status with extended information
*/
PJ_DEF(pj_status_t) pjsua_acc_set_online_status2( pjsua_acc_id acc_id,
pj_bool_t is_online,
const pjrpid_element *pr)
{
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Acc %d: setting online status to %d..",
acc_id, is_online));
pj_log_push_indent();
PJSUA_LOCK();
pjsua_var.acc[acc_id].online_status = is_online;
pjrpid_element_dup(pjsua_var.acc[acc_id].pool, &pjsua_var.acc[acc_id].rpid, pr);
PJSUA_UNLOCK();
pjsua_pres_update_acc(acc_id, PJ_TRUE);
pj_log_pop_indent();
return PJ_SUCCESS;
}
/* Create reg_contact, mainly for SIP outbound */
static void update_regc_contact(pjsua_acc *acc)
{
pjsua_acc_config *acc_cfg = &acc->cfg;
pj_bool_t need_outbound = PJ_FALSE;
const pj_str_t tcp_param = pj_str(";transport=tcp");
const pj_str_t tls_param = pj_str(";transport=tls");
if (!acc_cfg->use_rfc5626)
goto done;
/* Check if outbound has been requested and rejected */
if (acc->rfc5626_status == OUTBOUND_NA)
goto done;
if (pj_stristr(&acc->contact, &tcp_param)==NULL &&
pj_stristr(&acc->contact, &tls_param)==NULL)
{
/* Currently we can only do SIP outbound for TCP
* and TLS.
*/
goto done;
}
/* looks like we can use outbound */
need_outbound = PJ_TRUE;
done:
if (!need_outbound) {
/* Outbound is not needed/wanted for the account. acc->reg_contact
* is set to the same as acc->contact.
*/
acc->reg_contact = acc->contact;
acc->rfc5626_status = OUTBOUND_NA;
} else {
/* Need to use outbound, append the contact with +sip.instance and
* reg-id parameters.
*/
pj_ssize_t len;
pj_str_t reg_contact;
acc->rfc5626_status = OUTBOUND_WANTED;
len = acc->contact.slen + acc->rfc5626_instprm.slen +
acc->rfc5626_regprm.slen;
reg_contact.ptr = (char*) pj_pool_alloc(acc->pool, len);
pj_strcpy(®_contact, &acc->contact);
pj_strcat(®_contact, &acc->rfc5626_regprm);
pj_strcat(®_contact, &acc->rfc5626_instprm);
acc->reg_contact = reg_contact;
PJ_LOG(4,(THIS_FILE,
"Contact for acc %d updated for SIP outbound: %.*s",
acc->index,
(int)acc->reg_contact.slen,
acc->reg_contact.ptr));
}
}
/* Check if IP is private IP address */
static pj_bool_t is_private_ip(const pj_str_t *addr)
{
const pj_str_t private_net[] =
{
{ "10.", 3 },
{ "127.", 4 },
{ "172.16.", 7 }, { "172.17.", 7 }, { "172.18.", 7 }, { "172.19.", 7 },
{ "172.20.", 7 }, { "172.21.", 7 }, { "172.22.", 7 }, { "172.23.", 7 },
{ "172.24.", 7 }, { "172.25.", 7 }, { "172.26.", 7 }, { "172.27.", 7 },
{ "172.28.", 7 }, { "172.29.", 7 }, { "172.30.", 7 }, { "172.31.", 7 },
{ "192.168.", 8 }
};
unsigned i;
for (i=0; i<PJ_ARRAY_SIZE(private_net); ++i) {
if (pj_strncmp(addr, &private_net[i], private_net[i].slen)==0)
return PJ_TRUE;
}
return PJ_FALSE;
}
/* Update NAT address from the REGISTER response */
static pj_bool_t acc_check_nat_addr(pjsua_acc *acc,
int contact_rewrite_method,
struct pjsip_regc_cbparam *param)
{
pjsip_transport *tp;
const pj_str_t *via_addr;
pj_pool_t *pool;
int rport;
pjsip_sip_uri *uri;
pjsip_via_hdr *via;
pj_sockaddr contact_addr;
pj_sockaddr recv_addr;
pj_status_t status;
pj_bool_t matched;
pj_str_t srv_ip;
pjsip_contact_hdr *contact_hdr;
const pj_str_t STR_CONTACT = { "Contact", 7 };
tp = param->rdata->tp_info.transport;
/* Get the received and rport info */
via = param->rdata->msg_info.via;
if (via->rport_param < 1) {
/* Remote doesn't support rport */
rport = via->sent_by.port;
if (rport==0) {
pjsip_transport_type_e tp_type;
tp_type = (pjsip_transport_type_e) tp->key.type;
rport = pjsip_transport_get_default_port_for_type(tp_type);
}
} else
rport = via->rport_param;
if (via->recvd_param.slen != 0)
via_addr = &via->recvd_param;
else
via_addr = &via->sent_by.host;
/* If allow_via_rewrite is enabled, we save the Via "received" address
* from the response, if either of the following condition is met:
* - the Via "received" address differs from saved one (or we haven't
* saved any yet)
* - transport is different
* - only the port has changed, AND either the received address is
* public IP or allow_contact_rewrite is 2
*/
if (acc->cfg.allow_via_rewrite &&
(pj_strcmp(&acc->via_addr.host, via_addr) || acc->via_tp != tp ||
(acc->via_addr.port != rport &&
(!is_private_ip(via_addr) || acc->cfg.allow_contact_rewrite == 2))))
{
if (pj_strcmp(&acc->via_addr.host, via_addr))
pj_strdup(acc->pool, &acc->via_addr.host, via_addr);
acc->via_addr.port = rport;
acc->via_tp = tp;
pjsip_regc_set_via_sent_by(acc->regc, &acc->via_addr, acc->via_tp);
if (acc->publish_sess != NULL) {
pjsip_publishc_set_via_sent_by(acc->publish_sess,
&acc->via_addr, acc->via_tp);
}
}
/* Save mapped address if needed */
if (acc->cfg.allow_sdp_nat_rewrite &&
pj_strcmp(&acc->reg_mapped_addr, via_addr))
{
pj_strdup(acc->pool, &acc->reg_mapped_addr, via_addr);
}
/* Only update if account is configured to auto-update */
if (acc->cfg.allow_contact_rewrite == PJ_FALSE)
return PJ_FALSE;
/* If SIP outbound is active, no need to update */
if (acc->rfc5626_status == OUTBOUND_ACTIVE) {
PJ_LOG(4,(THIS_FILE, "Acc %d has SIP outbound active, no need to "
"update registration Contact", acc->index));
return PJ_FALSE;
}
#if 0
// Always update
// See http://lists.pjsip.org/pipermail/pjsip_lists.pjsip.org/2008-March/002178.html
/* For UDP, only update if STUN is enabled (for now).
* For TCP/TLS, always check.
*/
if ((tp->key.type == PJSIP_TRANSPORT_UDP &&
(pjsua_var.ua_cfg.stun_domain.slen != 0 ||
(pjsua_var.ua_cfg.stun_host.slen != 0)) ||
(tp->key.type == PJSIP_TRANSPORT_TCP) ||
(tp->key.type == PJSIP_TRANSPORT_TLS))
{
/* Yes we will check */
} else {
return PJ_FALSE;
}
#endif
/* Compare received and rport with the URI in our registration */
pool = pjsua_pool_create("tmp", 512, 512);
contact_hdr = (pjsip_contact_hdr*)
pjsip_parse_hdr(pool, &STR_CONTACT, acc->contact.ptr,
acc->contact.slen, NULL);
pj_assert(contact_hdr != NULL);
uri = (pjsip_sip_uri*) contact_hdr->uri;
pj_assert(uri != NULL);
uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri);
if (uri->port == 0) {
pjsip_transport_type_e tp_type;
tp_type = (pjsip_transport_type_e) tp->key.type;
uri->port = pjsip_transport_get_default_port_for_type(tp_type);
}
/* Convert IP address strings into sockaddr for comparison.
* (http://trac.pjsip.org/repos/ticket/863)
*/
status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &uri->host,
&contact_addr);
if (status == PJ_SUCCESS)
status = pj_sockaddr_parse(pj_AF_UNSPEC(), 0, via_addr,
&recv_addr);
if (status == PJ_SUCCESS) {
/* Compare the addresses as sockaddr according to the ticket above */
matched = (uri->port == rport &&
pj_sockaddr_cmp(&contact_addr, &recv_addr)==0);
} else {
/* Compare the addresses as string, as before */
matched = (uri->port == rport &&
pj_stricmp(&uri->host, via_addr)==0);
}
if (matched) {
/* Address doesn't change */
pj_pool_release(pool);
return PJ_FALSE;
}
/* Get server IP */
srv_ip = pj_str(param->rdata->pkt_info.src_name);
/* At this point we've detected that the address as seen by registrar.
* has changed.
*/
/* Do not switch if both Contact and server's IP address are
* public but response contains private IP. A NAT in the middle
* might have messed up with the SIP packets. See:
* http://trac.pjsip.org/repos/ticket/643
*
* This exception can be disabled by setting allow_contact_rewrite
* to 2. In this case, the switch will always be done whenever there
* is difference in the IP address in the response.
*/
if (acc->cfg.allow_contact_rewrite != 2 && !is_private_ip(&uri->host) &&
!is_private_ip(&srv_ip) && is_private_ip(via_addr))
{
/* Don't switch */
pj_pool_release(pool);
return PJ_FALSE;
}
/* Also don't switch if only the port number part is different, and
* the Via received address is private.
* See http://trac.pjsip.org/repos/ticket/864
*/
if (acc->cfg.allow_contact_rewrite != 2 &&
pj_sockaddr_cmp(&contact_addr, &recv_addr)==0 &&
is_private_ip(via_addr))
{
/* Don't switch */
pj_pool_release(pool);
return PJ_FALSE;
}
PJ_LOG(3,(THIS_FILE, "IP address change detected for account %d "
"(%.*s:%d --> %.*s:%d). Updating registration "
"(using method %d)",
acc->index,
(int)uri->host.slen,
uri->host.ptr,
uri->port,
(int)via_addr->slen,
via_addr->ptr,
rport,
contact_rewrite_method));
pj_assert(contact_rewrite_method == PJSUA_CONTACT_REWRITE_UNREGISTER ||
contact_rewrite_method == PJSUA_CONTACT_REWRITE_NO_UNREG ||
contact_rewrite_method == PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE);
if (contact_rewrite_method == PJSUA_CONTACT_REWRITE_UNREGISTER) {
/* Unregister current contact */
pjsua_acc_set_registration(acc->index, PJ_FALSE);
if (acc->regc != NULL) {
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
}
}
/*
* Build new Contact header
*/
{
const char *ob = ";ob";
char *tmp;
const char *beginquote, *endquote;
char transport_param[32];
int len;
pj_bool_t secure;
secure = pjsip_transport_get_flag_from_type(tp->key.type) &
PJSIP_TRANSPORT_SECURE;
/* Enclose IPv6 address in square brackets */
if (tp->key.type & PJSIP_TRANSPORT_IPV6) {
beginquote = "[";
endquote = "]";
} else {
beginquote = endquote = "";
}
/* Don't add transport parameter if it's UDP */
if (tp->key.type != PJSIP_TRANSPORT_UDP &&
tp->key.type != PJSIP_TRANSPORT_UDP6)
{
pj_ansi_snprintf(transport_param, sizeof(transport_param),
";transport=%s",
pjsip_transport_get_type_name(
(pjsip_transport_type_e)tp->key.type));
} else {
transport_param[0] = '\0';
}
tmp = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
len = pj_ansi_snprintf(tmp, PJSIP_MAX_URL_SIZE,
"<%s:%.*s%s%s%.*s%s:%d%s%.*s%s>%.*s",
((secure && acc->is_sips)? "sips" : "sip"),
(int)acc->user_part.slen,
acc->user_part.ptr,
(acc->user_part.slen? "@" : ""),
beginquote,
(int)via_addr->slen,
via_addr->ptr,
endquote,
rport,
transport_param,
(int)acc->cfg.contact_uri_params.slen,
acc->cfg.contact_uri_params.ptr,
(acc->cfg.use_rfc5626? ob: ""),
(int)acc->cfg.contact_params.slen,
acc->cfg.contact_params.ptr);
if (len < 1 || len >= PJSIP_MAX_URL_SIZE) {
PJ_LOG(1,(THIS_FILE, "URI too long"));
pj_pool_release(pool);
return PJ_FALSE;
}
pj_strdup2_with_null(acc->pool, &acc->contact, tmp);
update_regc_contact(acc);
/* Always update, by http://trac.pjsip.org/repos/ticket/864. */
/* Since the Via address will now be overwritten to the correct
* address by https://trac.pjsip.org/repos/ticket/1537, we do
* not need to update the transport address.
*/
/*
pj_strdup_with_null(tp->pool, &tp->local_name.host, via_addr);
tp->local_name.port = rport;
*/
}
if (contact_rewrite_method == PJSUA_CONTACT_REWRITE_NO_UNREG &&
acc->regc != NULL)
{
pjsip_regc_update_contact(acc->regc, 1, &acc->reg_contact);
}
/* Perform new registration */
if (contact_rewrite_method < PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE) {
pjsua_acc_set_registration(acc->index, PJ_TRUE);
}
pj_pool_release(pool);
return PJ_TRUE;
}
/* Check and update Service-Route header */
static void update_service_route(pjsua_acc *acc, pjsip_rx_data *rdata)
{
pjsip_generic_string_hdr *hsr = NULL;
pjsip_route_hdr *hr, *h;
const pj_str_t HNAME = { "Service-Route", 13 };
const pj_str_t HROUTE = { "Route", 5 };
pjsip_uri *uri[PJSUA_ACC_MAX_PROXIES];
unsigned i, uri_cnt = 0;
pj_size_t rcnt;
/* Find and parse Service-Route headers */
for (;;) {
char saved;
int parsed_len;
/* Find Service-Route header */
hsr = (pjsip_generic_string_hdr*)
pjsip_msg_find_hdr_by_name(rdata->msg_info.msg, &HNAME, hsr);
if (!hsr)
break;
/* Parse as Route header since the syntax is similar. This may
* return more than one headers.
*/
saved = hsr->hvalue.ptr[hsr->hvalue.slen];
hsr->hvalue.ptr[hsr->hvalue.slen] = '\0';
hr = (pjsip_route_hdr*)
pjsip_parse_hdr(rdata->tp_info.pool, &HROUTE, hsr->hvalue.ptr,
hsr->hvalue.slen, &parsed_len);
hsr->hvalue.ptr[hsr->hvalue.slen] = saved;
if (hr == NULL) {
/* Error */
PJ_LOG(1,(THIS_FILE, "Error parsing Service-Route header"));
return;
}
/* Save each URI in the result */
h = hr;
do {
if (!PJSIP_URI_SCHEME_IS_SIP(h->name_addr.uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(h->name_addr.uri))
{
PJ_LOG(1,(THIS_FILE,"Error: non SIP URI in Service-Route: %.*s",
(int)hsr->hvalue.slen, hsr->hvalue.ptr));
return;
}
uri[uri_cnt++] = h->name_addr.uri;
h = h->next;
} while (h != hr && uri_cnt != PJ_ARRAY_SIZE(uri));
if (h != hr) {
PJ_LOG(1,(THIS_FILE, "Error: too many Service-Route headers"));
return;
}
/* Prepare to find next Service-Route header */
hsr = hsr->next;
if ((void*)hsr == (void*)&rdata->msg_info.msg->hdr)
break;
}
if (uri_cnt == 0)
return;
/*
* Update account's route set
*/
/* First remove all routes which are not the outbound proxies */
rcnt = pj_list_size(&acc->route_set);
if (rcnt != pjsua_var.ua_cfg.outbound_proxy_cnt + acc->cfg.proxy_cnt) {
for (i=pjsua_var.ua_cfg.outbound_proxy_cnt + acc->cfg.proxy_cnt,
hr=acc->route_set.prev;
i<rcnt;
++i)
{
pjsip_route_hdr *prev = hr->prev;
pj_list_erase(hr);
hr = prev;
}
}
/* Then append the Service-Route URIs */
for (i=0; i<uri_cnt; ++i) {
hr = pjsip_route_hdr_create(acc->pool);
hr->name_addr.uri = (pjsip_uri*)pjsip_uri_clone(acc->pool, uri[i]);
pj_list_push_back(&acc->route_set, hr);
}
/* Done */
PJ_LOG(4,(THIS_FILE, "Service-Route updated for acc %d with %d URI(s)",
acc->index, uri_cnt));
}
/* Keep alive timer callback */
static void keep_alive_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te)
{
pjsua_acc *acc;
pjsip_tpselector tp_sel;
pj_time_val delay;
char addrtxt[PJ_INET6_ADDRSTRLEN];
pj_status_t status;
PJ_UNUSED_ARG(th);
PJSUA_LOCK();
te->id = PJ_FALSE;
acc = (pjsua_acc*) te->user_data;
/* Select the transport to send the packet */
pj_bzero(&tp_sel, sizeof(tp_sel));
tp_sel.type = PJSIP_TPSELECTOR_TRANSPORT;
tp_sel.u.transport = acc->ka_transport;
PJ_LOG(5,(THIS_FILE,
"Sending %d bytes keep-alive packet for acc %d to %s",
acc->cfg.ka_data.slen, acc->index,
pj_sockaddr_print(&acc->ka_target, addrtxt, sizeof(addrtxt),3)));
/* Send raw packet */
status = pjsip_tpmgr_send_raw(pjsip_endpt_get_tpmgr(pjsua_var.endpt),
PJSIP_TRANSPORT_UDP, &tp_sel,
NULL, acc->cfg.ka_data.ptr,
acc->cfg.ka_data.slen,
&acc->ka_target, acc->ka_target_len,
NULL, NULL);
if (status != PJ_SUCCESS && status != PJ_EPENDING) {
pjsua_perror(THIS_FILE, "Error sending keep-alive packet", status);
}
/* Check just in case keep-alive has been disabled. This shouldn't happen
* though as when ka_interval is changed this timer should have been
* cancelled.
*/
if (acc->cfg.ka_interval == 0)
goto on_return;
/* Reschedule next timer */
delay.sec = acc->cfg.ka_interval;
delay.msec = 0;
status = pjsip_endpt_schedule_timer(pjsua_var.endpt, te, &delay);
if (status == PJ_SUCCESS) {
te->id = PJ_TRUE;
} else {
pjsua_perror(THIS_FILE, "Error starting keep-alive timer", status);
}
on_return:
PJSUA_UNLOCK();
}
/* Update keep-alive for the account */
static void update_keep_alive(pjsua_acc *acc, pj_bool_t start,
struct pjsip_regc_cbparam *param)
{
/* In all cases, stop keep-alive timer if it's running. */
if (acc->ka_timer.id) {
pjsip_endpt_cancel_timer(pjsua_var.endpt, &acc->ka_timer);
acc->ka_timer.id = PJ_FALSE;
if (acc->ka_transport) {
pjsip_transport_dec_ref(acc->ka_transport);
acc->ka_transport = NULL;
}
}
if (start) {
pj_time_val delay;
pj_status_t status;
/* Only do keep-alive if:
* - ka_interval is not zero in the account, and
* - transport is UDP.
*
* Previously we only enabled keep-alive when STUN is enabled, since
* we thought that keep-alive is only needed in Internet situation.
* But it has been discovered that Windows Firewall on WinXP also
* needs to be kept-alive, otherwise incoming packets will be dropped.
* So because of this, now keep-alive is always enabled for UDP,
* regardless of whether STUN is enabled or not.
*
* Note that this applies only for UDP. For TCP/TLS, the keep-alive
* is done by the transport layer.
*/
if (/*pjsua_var.stun_srv.ipv4.sin_family == 0 ||*/
acc->cfg.ka_interval == 0 ||
param->rdata->tp_info.transport->key.type != PJSIP_TRANSPORT_UDP)
{
/* Keep alive is not necessary */
return;
}
/* Save transport and destination address. */
acc->ka_transport = param->rdata->tp_info.transport;
pjsip_transport_add_ref(acc->ka_transport);
/* https://trac.pjsip.org/repos/ticket/1607:
* Calculate the destination address from the original request. Some
* (broken) servers send the response using different source address
* than the one that receives the request, which is forbidden by RFC
* 3581.
*/
{
pjsip_transaction *tsx;
pjsip_tx_data *req;
tsx = pjsip_rdata_get_tsx(param->rdata);
PJ_ASSERT_ON_FAIL(tsx, return);
req = tsx->last_tx;
pj_memcpy(&acc->ka_target, &req->tp_info.dst_addr,
req->tp_info.dst_addr_len);
acc->ka_target_len = req->tp_info.dst_addr_len;
}
/* Setup and start the timer */
acc->ka_timer.cb = &keep_alive_timer_cb;
acc->ka_timer.user_data = (void*)acc;
delay.sec = acc->cfg.ka_interval;
delay.msec = 0;
status = pjsip_endpt_schedule_timer(pjsua_var.endpt, &acc->ka_timer,
&delay);
if (status == PJ_SUCCESS) {
acc->ka_timer.id = PJ_TRUE;
PJ_LOG(4,(THIS_FILE, "Keep-alive timer started for acc %d, "
"destination:%s:%d, interval:%ds",
acc->index,
param->rdata->pkt_info.src_name,
param->rdata->pkt_info.src_port,
acc->cfg.ka_interval));
} else {
acc->ka_timer.id = PJ_FALSE;
pjsip_transport_dec_ref(acc->ka_transport);
acc->ka_transport = NULL;
pjsua_perror(THIS_FILE, "Error starting keep-alive timer", status);
}
}
}
/* Update the status of SIP outbound registration request */
static void update_rfc5626_status(pjsua_acc *acc, pjsip_rx_data *rdata)
{
pjsip_require_hdr *hreq;
const pj_str_t STR_OUTBOUND = {"outbound", 8};
unsigned i;
if (acc->rfc5626_status == OUTBOUND_UNKNOWN) {
goto on_return;
}
hreq = rdata->msg_info.require;
if (!hreq) {
acc->rfc5626_status = OUTBOUND_NA;
goto on_return;
}
for (i=0; i<hreq->count; ++i) {
if (pj_stricmp(&hreq->values[i], &STR_OUTBOUND)==0) {
acc->rfc5626_status = OUTBOUND_ACTIVE;
goto on_return;
}
}
/* Server does not support outbound */
acc->rfc5626_status = OUTBOUND_NA;
on_return:
if (acc->rfc5626_status != OUTBOUND_ACTIVE) {
acc->reg_contact = acc->contact;
}
PJ_LOG(4,(THIS_FILE, "SIP outbound status for acc %d is %s",
acc->index, (acc->rfc5626_status==OUTBOUND_ACTIVE?
"active": "not active")));
}
static void regc_tsx_cb(struct pjsip_regc_tsx_cb_param *param)
{
pjsua_acc *acc = (pjsua_acc*) param->cbparam.token;
PJSUA_LOCK();
if (param->cbparam.regc != acc->regc) {
PJSUA_UNLOCK();
return;
}
pj_log_push_indent();
/* Check if we should do NAT bound address check for contact rewrite.
* Note that '!contact_rewritten' check here is to avoid overriding
* the current contact generated from last 2xx.
*/
if (!acc->contact_rewritten &&
(acc->cfg.contact_rewrite_method &
PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE) ==
PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE &&
param->cbparam.code >= 400 &&
param->cbparam.rdata)
{
if (acc_check_nat_addr(acc, PJSUA_CONTACT_REWRITE_ALWAYS_UPDATE,
¶m->cbparam))
{
param->contact_cnt = 1;
param->contact[0] = acc->reg_contact;
/* Don't set 'contact_rewritten' to PJ_TRUE here to allow
* further check of NAT bound address in 2xx response.
*/
}
}
PJSUA_UNLOCK();
pj_log_pop_indent();
}
/*
* This callback is called by pjsip_regc when outgoing register
* request has completed.
*/
static void regc_cb(struct pjsip_regc_cbparam *param)
{
pjsua_acc *acc = (pjsua_acc*) param->token;
PJSUA_LOCK();
if (param->regc != acc->regc) {
PJSUA_UNLOCK();
return;
}
pj_log_push_indent();
/*
* Print registration status.
*/
if (param->status!=PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "SIP registration error",
param->status);
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
/* Stop keep-alive timer if any. */
update_keep_alive(acc, PJ_FALSE, NULL);
} else if (param->code < 0 || param->code >= 300) {
PJ_LOG(2, (THIS_FILE, "SIP registration failed, status=%d (%.*s)",
param->code,
(int)param->reason.slen, param->reason.ptr));
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
/* Stop keep-alive timer if any. */
update_keep_alive(acc, PJ_FALSE, NULL);
} else if (PJSIP_IS_STATUS_IN_CLASS(param->code, 200)) {
/* Update auto registration flag */
acc->auto_rereg.active = PJ_FALSE;
acc->auto_rereg.attempt_cnt = 0;
if (param->expiration < 1) {
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
/* Stop keep-alive timer if any. */
update_keep_alive(acc, PJ_FALSE, NULL);
PJ_LOG(3,(THIS_FILE, "%s: unregistration success",
pjsua_var.acc[acc->index].cfg.id.ptr));
} else {
/* Check and update SIP outbound status first, since the result
* will determine if we should update re-registration
*/
update_rfc5626_status(acc, param->rdata);
/* Check NAT bound address if it hasn't been done before */
if (!acc->contact_rewritten &&
acc_check_nat_addr(acc, (acc->cfg.contact_rewrite_method & 3),
param))
{
PJSUA_UNLOCK();
pj_log_pop_indent();
/* Avoid another check of NAT bound address */
acc->contact_rewritten = PJ_TRUE;
return;
}
/* Check and update Service-Route header */
update_service_route(acc, param->rdata);
PJ_LOG(3, (THIS_FILE,
"%s: registration success, status=%d (%.*s), "
"will re-register in %d seconds",
pjsua_var.acc[acc->index].cfg.id.ptr,
param->code,
(int)param->reason.slen, param->reason.ptr,
param->expiration));
/* Start keep-alive timer if necessary. */
update_keep_alive(acc, PJ_TRUE, param);
/* Send initial PUBLISH if it is enabled */
if (acc->cfg.publish_enabled && acc->publish_sess==NULL)
pjsua_pres_init_publish_acc(acc->index);
/* Subscribe to MWI, if it's enabled */
if (acc->cfg.mwi_enabled)
pjsua_start_mwi(acc->index, PJ_FALSE);
}
} else {
PJ_LOG(4, (THIS_FILE, "SIP registration updated status=%d", param->code));
}
acc->reg_last_err = param->status;
acc->reg_last_code = param->code;
/* Reaching this point means no contact rewrite, so reset the flag */
acc->contact_rewritten = PJ_FALSE;
/* Check if we need to auto retry registration. Basically, registration
* failure codes triggering auto-retry are those of temporal failures
* considered to be recoverable in relatively short term.
*/
if (acc->cfg.reg_retry_interval &&
(param->code == PJSIP_SC_REQUEST_TIMEOUT ||
param->code == PJSIP_SC_INTERNAL_SERVER_ERROR ||
param->code == PJSIP_SC_BAD_GATEWAY ||
param->code == PJSIP_SC_SERVICE_UNAVAILABLE ||
param->code == PJSIP_SC_SERVER_TIMEOUT ||
param->code == PJSIP_SC_TEMPORARILY_UNAVAILABLE ||
PJSIP_IS_STATUS_IN_CLASS(param->code, 600))) /* Global failure */
{
schedule_reregistration(acc);
}
/* Call the registration status callback */
if (pjsua_var.ua_cfg.cb.on_reg_state) {
(*pjsua_var.ua_cfg.cb.on_reg_state)(acc->index);
}
if (pjsua_var.ua_cfg.cb.on_reg_state2) {
pjsua_reg_info reg_info;
reg_info.cbparam = param;
(*pjsua_var.ua_cfg.cb.on_reg_state2)(acc->index, ®_info);
}
PJSUA_UNLOCK();
pj_log_pop_indent();
}
/*
* Initialize client registration.
*/
static pj_status_t pjsua_regc_init(int acc_id)
{
pjsua_acc *acc;
pj_pool_t *pool;
pj_status_t status;
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
if (acc->cfg.reg_uri.slen == 0) {
PJ_LOG(3,(THIS_FILE, "Registrar URI is not specified"));
return PJ_SUCCESS;
}
/* Destroy existing session, if any */
if (acc->regc) {
pjsip_regc_destroy(acc->regc);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
}
/* initialize SIP registration if registrar is configured */
status = pjsip_regc_create( pjsua_var.endpt,
acc, ®c_cb, &acc->regc);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create client registration",
status);
return status;
}
pool = pjsua_pool_create("tmpregc", 512, 512);
if (acc->contact.slen == 0) {
pj_str_t tmp_contact;
status = pjsua_acc_create_uac_contact( pool, &tmp_contact,
acc_id, &acc->cfg.reg_uri);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to generate suitable Contact header"
" for registration",
status);
pjsip_regc_destroy(acc->regc);
pj_pool_release(pool);
acc->regc = NULL;
return status;
}
pj_strdup_with_null(acc->pool, &acc->contact, &tmp_contact);
update_regc_contact(acc);
}
status = pjsip_regc_init( acc->regc,
&acc->cfg.reg_uri,
&acc->cfg.id,
&acc->cfg.id,
1, &acc->reg_contact,
acc->cfg.reg_timeout);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE,
"Client registration initialization error",
status);
pjsip_regc_destroy(acc->regc);
pj_pool_release(pool);
acc->regc = NULL;
acc->contact.slen = 0;
acc->reg_mapped_addr.slen = 0;
acc->rfc5626_status = OUTBOUND_UNKNOWN;
return status;
}
pjsip_regc_set_reg_tsx_cb(acc->regc, regc_tsx_cb);
/* If account is locked to specific transport, then set transport to
* the client registration.
*/
if (pjsua_var.acc[acc_id].cfg.transport_id != PJSUA_INVALID_ID) {
pjsip_tpselector tp_sel;
pjsua_init_tpselector(pjsua_var.acc[acc_id].cfg.transport_id, &tp_sel);
pjsip_regc_set_transport(acc->regc, &tp_sel);
}
/* Set credentials
*/
if (acc->cred_cnt) {
pjsip_regc_set_credentials( acc->regc, acc->cred_cnt, acc->cred);
}
/* Set delay before registration refresh */
pjsip_regc_set_delay_before_refresh(acc->regc,
acc->cfg.reg_delay_before_refresh);
/* Set authentication preference */
pjsip_regc_set_prefs(acc->regc, &acc->cfg.auth_pref);
/* Set route-set
*/
if (acc->cfg.reg_use_proxy) {
pjsip_route_hdr route_set;
const pjsip_route_hdr *r;
pj_list_init(&route_set);
if (acc->cfg.reg_use_proxy & PJSUA_REG_USE_OUTBOUND_PROXY) {
r = pjsua_var.outbound_proxy.next;
while (r != &pjsua_var.outbound_proxy) {
pj_list_push_back(&route_set, pjsip_hdr_shallow_clone(pool, r));
r = r->next;
}
}
if (acc->cfg.reg_use_proxy & PJSUA_REG_USE_ACC_PROXY &&
acc->cfg.proxy_cnt)
{
int cnt = acc->cfg.proxy_cnt;
pjsip_route_hdr *pos = route_set.prev;
int i;
r = acc->route_set.prev;
for (i=0; i<cnt; ++i) {
pj_list_push_front(pos, pjsip_hdr_shallow_clone(pool, r));
r = r->prev;
}
}
if (!pj_list_empty(&route_set))
pjsip_regc_set_route_set( acc->regc, &route_set );
}
/* Add custom request headers specified in the account config */
pjsip_regc_add_headers(acc->regc, &acc->cfg.reg_hdr_list);
/* Add other request headers. */
if (pjsua_var.ua_cfg.user_agent.slen) {
pjsip_hdr hdr_list;
const pj_str_t STR_USER_AGENT = { "User-Agent", 10 };
pjsip_generic_string_hdr *h;
pj_list_init(&hdr_list);
h = pjsip_generic_string_hdr_create(pool, &STR_USER_AGENT,
&pjsua_var.ua_cfg.user_agent);
pj_list_push_back(&hdr_list, (pjsip_hdr*)h);
pjsip_regc_add_headers(acc->regc, &hdr_list);
}
/* If SIP outbound is used, add "Supported: outbound, path header" */
if (acc->rfc5626_status == OUTBOUND_WANTED ||
acc->rfc5626_status == OUTBOUND_ACTIVE)
{
pjsip_hdr hdr_list;
pjsip_supported_hdr *hsup;
pj_list_init(&hdr_list);
hsup = pjsip_supported_hdr_create(pool);
pj_list_push_back(&hdr_list, hsup);
hsup->count = 2;
hsup->values[0] = pj_str("outbound");
hsup->values[1] = pj_str("path");
pjsip_regc_add_headers(acc->regc, &hdr_list);
}
pj_pool_release(pool);
return PJ_SUCCESS;
}
pj_bool_t pjsua_sip_acc_is_using_stun(pjsua_acc_id acc_id)
{
pjsua_acc *acc = &pjsua_var.acc[acc_id];
return acc->cfg.sip_stun_use != PJSUA_STUN_USE_DISABLED &&
pjsua_var.ua_cfg.stun_srv_cnt != 0;
}
/*
* Update registration or perform unregistration.
*/
PJ_DEF(pj_status_t) pjsua_acc_set_registration( pjsua_acc_id acc_id,
pj_bool_t renew)
{
pjsua_acc *acc;
pj_status_t status = 0;
pjsip_tx_data *tdata = 0;
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJ_LOG(4,(THIS_FILE, "Acc %d: setting %sregistration..",
acc_id, (renew? "" : "un")));
pj_log_push_indent();
PJSUA_LOCK();
acc = &pjsua_var.acc[acc_id];
/* Cancel any re-registration timer */
if (pjsua_var.acc[acc_id].auto_rereg.timer.id) {
pjsua_var.acc[acc_id].auto_rereg.timer.id = PJ_FALSE;
pjsua_cancel_timer(&pjsua_var.acc[acc_id].auto_rereg.timer);
}
/* Reset pointer to registration transport */
pjsua_var.acc[acc_id].auto_rereg.reg_tp = NULL;
if (renew) {
if (pjsua_var.acc[acc_id].regc == NULL) {
status = pjsua_regc_init(acc_id);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create registration",
status);
goto on_return;
}
}
if (!pjsua_var.acc[acc_id].regc) {
status = PJ_EINVALIDOP;
goto on_return;
}
status = pjsip_regc_register(pjsua_var.acc[acc_id].regc, 1,
&tdata);
if (0 && status == PJ_SUCCESS && pjsua_var.acc[acc_id].cred_cnt) {
pjsua_acc *acc = &pjsua_var.acc[acc_id];
pjsip_authorization_hdr *h;
char *uri;
int d;
uri = (char*) pj_pool_alloc(tdata->pool, acc->cfg.reg_uri.slen+10);
d = pjsip_uri_print(PJSIP_URI_IN_REQ_URI, tdata->msg->line.req.uri,
uri, acc->cfg.reg_uri.slen+10);
pj_assert(d > 0);
h = pjsip_authorization_hdr_create(tdata->pool);
h->scheme = pj_str("Digest");
h->credential.digest.username = acc->cred[0].username;
h->credential.digest.realm = acc->srv_domain;
h->credential.digest.uri = pj_str(uri);
h->credential.digest.algorithm = pj_str("md5");
pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)h);
}
} else {
if (pjsua_var.acc[acc_id].regc == NULL) {
PJ_LOG(3,(THIS_FILE, "Currently not registered"));
status = PJ_EINVALIDOP;
goto on_return;
}
pjsua_pres_unpublish(&pjsua_var.acc[acc_id], 0);
status = pjsip_regc_unregister(pjsua_var.acc[acc_id].regc, &tdata);
}
if (status == PJ_SUCCESS) {
if (pjsua_var.acc[acc_id].cfg.allow_via_rewrite &&
pjsua_var.acc[acc_id].via_addr.host.slen > 0)
{
pjsip_regc_set_via_sent_by(pjsua_var.acc[acc_id].regc,
&pjsua_var.acc[acc_id].via_addr,
pjsua_var.acc[acc_id].via_tp);
} else if (!pjsua_sip_acc_is_using_stun(acc_id)) {
/* Choose local interface to use in Via if acc is not using
* STUN
*/
pjsua_acc_get_uac_addr(acc_id, tdata->pool,
&acc->cfg.reg_uri,
&tdata->via_addr,
NULL, NULL,
&tdata->via_tp);
}
//pjsua_process_msg_data(tdata, NULL);
status = pjsip_regc_send( pjsua_var.acc[acc_id].regc, tdata );
}
/* Update pointer to registration transport */
if (status == PJ_SUCCESS) {
pjsip_regc_info reg_info;
pjsip_regc_get_info(pjsua_var.acc[acc_id].regc, ®_info);
pjsua_var.acc[acc_id].auto_rereg.reg_tp = reg_info.transport;
if (pjsua_var.ua_cfg.cb.on_reg_started) {
(*pjsua_var.ua_cfg.cb.on_reg_started)(acc_id, renew);
}
}
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create/send REGISTER",
status);
} else {
PJ_LOG(4,(THIS_FILE, "Acc %d: %s sent", acc_id,
(renew? "Registration" : "Unregistration")));
}
on_return:
PJSUA_UNLOCK();
pj_log_pop_indent();
return status;
}
/*
* Get account information.
*/
PJ_DEF(pj_status_t) pjsua_acc_get_info( pjsua_acc_id acc_id,
pjsua_acc_info *info)
{
pjsua_acc *acc = &pjsua_var.acc[acc_id];
pjsua_acc_config *acc_cfg = &pjsua_var.acc[acc_id].cfg;
PJ_ASSERT_RETURN(info != NULL, PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
pj_bzero(info, sizeof(pjsua_acc_info));
PJ_ASSERT_RETURN(acc_id>=0 && acc_id<(int)PJ_ARRAY_SIZE(pjsua_var.acc),
PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_var.acc[acc_id].valid, PJ_EINVALIDOP);
PJSUA_LOCK();
if (pjsua_var.acc[acc_id].valid == PJ_FALSE) {
PJSUA_UNLOCK();
return PJ_EINVALIDOP;
}
info->id = acc_id;
info->is_default = (pjsua_var.default_acc == acc_id);
info->acc_uri = acc_cfg->id;
info->has_registration = (acc->cfg.reg_uri.slen > 0);
info->online_status = acc->online_status;
pj_memcpy(&info->rpid, &acc->rpid, sizeof(pjrpid_element));
if (info->rpid.note.slen)
info->online_status_text = info->rpid.note;
else if (info->online_status)
info->online_status_text = pj_str("Online");
else
info->online_status_text = pj_str("Offline");
if (acc->reg_last_code) {
if (info->has_registration) {
info->status = (pjsip_status_code) acc->reg_last_code;
info->status_text = *pjsip_get_status_text(acc->reg_last_code);
if (acc->reg_last_err)
info->reg_last_err = acc->reg_last_err;
} else {
info->status = (pjsip_status_code) 0;
info->status_text = pj_str("not registered");
}
} else if (acc->cfg.reg_uri.slen) {
info->status = PJSIP_SC_TRYING;
info->status_text = pj_str("In Progress");
} else {
info->status = (pjsip_status_code) 0;
info->status_text = pj_str("does not register");
}
if (acc->regc) {
pjsip_regc_info regc_info;
pjsip_regc_get_info(acc->regc, ®c_info);
info->expires = regc_info.next_reg;
} else {
info->expires = -1;
}
PJSUA_UNLOCK();
return PJ_SUCCESS;
}
/*
* Enum accounts all account ids.
*/
PJ_DEF(pj_status_t) pjsua_enum_accs(pjsua_acc_id ids[],
unsigned *count )
{
unsigned i, c;
PJ_ASSERT_RETURN(ids && *count, PJ_EINVAL);
PJSUA_LOCK();
for (i=0, c=0; c<*count && i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
if (!pjsua_var.acc[i].valid)
continue;
ids[c] = i;
++c;
}
*count = c;
PJSUA_UNLOCK();
return PJ_SUCCESS;
}
/*
* Enum accounts info.
*/
PJ_DEF(pj_status_t) pjsua_acc_enum_info( pjsua_acc_info info[],
unsigned *count )
{
unsigned i, c;
PJ_ASSERT_RETURN(info && *count, PJ_EINVAL);
PJSUA_LOCK();
for (i=0, c=0; c<*count && i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
if (!pjsua_var.acc[i].valid)
continue;
pjsua_acc_get_info(i, &info[c]);
++c;
}
*count = c;
PJSUA_UNLOCK();
return PJ_SUCCESS;
}
/*
* This is an internal function to find the most appropriate account to
* used to reach to the specified URL.
*/
PJ_DEF(pjsua_acc_id) pjsua_acc_find_for_outgoing(const pj_str_t *url)
{
pj_str_t tmp;
pjsip_uri *uri;
pjsip_sip_uri *sip_uri;
pj_pool_t *tmp_pool;
unsigned i;
PJSUA_LOCK();
tmp_pool = pjsua_pool_create("tmpacc10", 256, 256);
pj_strdup_with_null(tmp_pool, &tmp, url);
uri = pjsip_parse_uri(tmp_pool, tmp.ptr, tmp.slen, 0);
if (!uri) {
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return pjsua_var.default_acc;
}
if (!PJSIP_URI_SCHEME_IS_SIP(uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(uri))
{
/* Return the first account with proxy */
for (i=0; i<PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
if (!pjsua_var.acc[i].valid)
continue;
if (!pj_list_empty(&pjsua_var.acc[i].route_set))
break;
}
if (i != PJ_ARRAY_SIZE(pjsua_var.acc)) {
/* Found rather matching account */
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return i;
}
/* Not found, use default account */
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return pjsua_var.default_acc;
}
sip_uri = (pjsip_sip_uri*) pjsip_uri_get_uri(uri);
/* Find matching domain AND port */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
if (pj_stricmp(&pjsua_var.acc[acc_id].srv_domain, &sip_uri->host)==0 &&
pjsua_var.acc[acc_id].srv_port == sip_uri->port)
{
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return acc_id;
}
}
/* If no match, try to match the domain part only */
for (i=0; i<pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
if (pj_stricmp(&pjsua_var.acc[acc_id].srv_domain, &sip_uri->host)==0)
{
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return acc_id;
}
}
/* Still no match, just use default account */
pj_pool_release(tmp_pool);
PJSUA_UNLOCK();
return pjsua_var.default_acc;
}
/*
* This is an internal function to find the most appropriate account to be
* used to handle incoming calls.
*/
PJ_DEF(pjsua_acc_id) pjsua_acc_find_for_incoming(pjsip_rx_data *rdata)
{
pjsip_uri *uri;
pjsip_sip_uri *sip_uri;
pjsua_acc_id id = PJSUA_INVALID_ID;
unsigned i;
/* Check that there's at least one account configured */
PJ_ASSERT_RETURN(pjsua_var.acc_cnt!=0, pjsua_var.default_acc);
uri = rdata->msg_info.to->uri;
PJSUA_LOCK();
/* Use Req URI if To URI is not SIP */
if (!PJSIP_URI_SCHEME_IS_SIP(uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(uri))
{
if (rdata->msg_info.msg->type == PJSIP_REQUEST_MSG)
uri = rdata->msg_info.msg->line.req.uri;
else
goto on_return;
}
/* Just return default account if both To and Req URI are not SIP: */
if (!PJSIP_URI_SCHEME_IS_SIP(uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(uri))
{
goto on_return;
}
sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri);
/* Find account which has matching username and domain. */
for (i=0; i < pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
pjsua_acc *acc = &pjsua_var.acc[acc_id];
if (acc->valid && pj_stricmp(&acc->user_part, &sip_uri->user)==0 &&
pj_stricmp(&acc->srv_domain, &sip_uri->host)==0)
{
/* Match ! */
id = acc_id;
goto on_return;
}
}
/* No matching account, try match domain part only. */
for (i=0; i < pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
pjsua_acc *acc = &pjsua_var.acc[acc_id];
if (acc->valid && pj_stricmp(&acc->srv_domain, &sip_uri->host)==0) {
/* Match ! */
id = acc_id;
goto on_return;
}
}
/* No matching account, try match user part (and transport type) only. */
for (i=0; i < pjsua_var.acc_cnt; ++i) {
unsigned acc_id = pjsua_var.acc_ids[i];
pjsua_acc *acc = &pjsua_var.acc[acc_id];
if (acc->valid && pj_stricmp(&acc->user_part, &sip_uri->user)==0) {
if (acc->cfg.transport_id != PJSUA_INVALID_ID) {
pjsip_transport_type_e type;
type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
if (type == PJSIP_TRANSPORT_UNSPECIFIED)
type = PJSIP_TRANSPORT_UDP;
if (pjsua_var.tpdata[acc->cfg.transport_id].type != type)
continue;
}
/* Match ! */
id = acc_id;
goto on_return;
}
}
on_return:
PJSUA_UNLOCK();
/* Still no match, use default account */
if (id == PJSUA_INVALID_ID)
id = pjsua_var.default_acc;
/* Invoke account find callback */
if (pjsua_var.ua_cfg.cb.on_acc_find_for_incoming)
(*pjsua_var.ua_cfg.cb.on_acc_find_for_incoming)(rdata, &id);
/* Verify if the specified account id is valid */
if (!pjsua_acc_is_valid(id))
id = pjsua_var.default_acc;
return id;
}
/*
* Create arbitrary requests for this account.
*/
PJ_DEF(pj_status_t) pjsua_acc_create_request(pjsua_acc_id acc_id,
const pjsip_method *method,
const pj_str_t *target,
pjsip_tx_data **p_tdata)
{
pjsip_tx_data *tdata;
pjsua_acc *acc;
pjsip_route_hdr *r;
pj_status_t status;
PJ_ASSERT_RETURN(method && target && p_tdata, PJ_EINVAL);
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
status = pjsip_endpt_create_request(pjsua_var.endpt, method, target,
&acc->cfg.id, target,
NULL, NULL, -1, NULL, &tdata);
if (status != PJ_SUCCESS) {
pjsua_perror(THIS_FILE, "Unable to create request", status);
return status;
}
/* Copy routeset */
r = acc->route_set.next;
while (r != &acc->route_set) {
pjsip_msg_add_hdr(tdata->msg,
(pjsip_hdr*)pjsip_hdr_clone(tdata->pool, r));
r = r->next;
}
/* If account is locked to specific transport, then set that transport to
* the transmit data.
*/
if (pjsua_var.acc[acc_id].cfg.transport_id != PJSUA_INVALID_ID) {
pjsip_tpselector tp_sel;
pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel);
pjsip_tx_data_set_transport(tdata, &tp_sel);
}
/* If via_addr is set, use this address for the Via header. */
if (pjsua_var.acc[acc_id].cfg.allow_via_rewrite &&
pjsua_var.acc[acc_id].via_addr.host.slen > 0)
{
tdata->via_addr = pjsua_var.acc[acc_id].via_addr;
tdata->via_tp = pjsua_var.acc[acc_id].via_tp;
} else if (!pjsua_sip_acc_is_using_stun(acc_id)) {
/* Choose local interface to use in Via if acc is not using
* STUN
*/
pjsua_acc_get_uac_addr(acc_id, tdata->pool,
target,
&tdata->via_addr,
NULL, NULL,
&tdata->via_tp);
}
/* Done */
*p_tdata = tdata;
return PJ_SUCCESS;
}
/*
* Internal:
* determine if an address is a valid IP address, and if it is,
* return the IP version (4 or 6).
*/
static int get_ip_addr_ver(const pj_str_t *host)
{
pj_in_addr dummy;
pj_in6_addr dummy6;
/* First check with inet_aton() */
if (pj_inet_aton(host, &dummy) > 0)
return 4;
/* Then check if this is an IPv6 address */
if (pj_inet_pton(pj_AF_INET6(), host, &dummy6) == PJ_SUCCESS)
return 6;
/* Not an IP address */
return 0;
}
/* Get local transport address suitable to be used for Via or Contact address
* to send request to the specified destination URI.
*/
pj_status_t pjsua_acc_get_uac_addr(pjsua_acc_id acc_id,
pj_pool_t *pool,
const pj_str_t *dst_uri,
pjsip_host_port *addr,
pjsip_transport_type_e *p_tp_type,
int *secure,
const void **p_tp)
{
pjsua_acc *acc;
pjsip_sip_uri *sip_uri;
pj_status_t status;
pjsip_transport_type_e tp_type = PJSIP_TRANSPORT_UNSPECIFIED;
unsigned flag;
pjsip_tpselector tp_sel;
pjsip_tpmgr *tpmgr;
pjsip_tpmgr_fla2_param tfla2_prm;
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
/* If route-set is configured for the account, then URI is the
* first entry of the route-set.
*/
if (!pj_list_empty(&acc->route_set)) {
sip_uri = (pjsip_sip_uri*)
pjsip_uri_get_uri(acc->route_set.next->name_addr.uri);
} else {
pj_str_t tmp;
pjsip_uri *uri;
pj_strdup_with_null(pool, &tmp, dst_uri);
uri = pjsip_parse_uri(pool, tmp.ptr, tmp.slen, 0);
if (uri == NULL)
return PJSIP_EINVALIDURI;
/* For non-SIP scheme, route set should be configured */
if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))
return PJSIP_ENOROUTESET;
sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri);
}
/* Get transport type of the URI */
if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri))
tp_type = PJSIP_TRANSPORT_TLS;
else if (sip_uri->transport_param.slen == 0) {
tp_type = PJSIP_TRANSPORT_UDP;
} else
tp_type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
if (tp_type == PJSIP_TRANSPORT_UNSPECIFIED)
return PJSIP_EUNSUPTRANSPORT;
/* If destination URI specifies IPv6, then set transport type
* to use IPv6 as well.
*/
if (pj_strchr(&sip_uri->host, ':'))
tp_type = (pjsip_transport_type_e)(((int)tp_type) + PJSIP_TRANSPORT_IPV6);
flag = pjsip_transport_get_flag_from_type(tp_type);
/* Init transport selector. */
pjsua_init_tpselector(acc->cfg.transport_id, &tp_sel);
/* Get local address suitable to send request from */
pjsip_tpmgr_fla2_param_default(&tfla2_prm);
tfla2_prm.tp_type = tp_type;
tfla2_prm.tp_sel = &tp_sel;
tfla2_prm.dst_host = sip_uri->host;
tfla2_prm.local_if = (!pjsua_sip_acc_is_using_stun(acc_id) ||
(flag & PJSIP_TRANSPORT_RELIABLE));
tpmgr = pjsip_endpt_get_tpmgr(pjsua_var.endpt);
status = pjsip_tpmgr_find_local_addr2(tpmgr, pool, &tfla2_prm);
if (status != PJ_SUCCESS)
return status;
/* Set this as default return value. This may be changed below
* for TCP/TLS
*/
addr->host = tfla2_prm.ret_addr;
addr->port = tfla2_prm.ret_port;
/* For TCP/TLS, acc may request to specify source port */
if (acc->cfg.contact_use_src_port) {
pjsip_host_info dinfo;
pjsip_transport *tp = NULL;
pj_addrinfo ai;
pj_bool_t log_written = PJ_FALSE;
status = pjsip_get_dest_info((pjsip_uri*)sip_uri, NULL,
pool, &dinfo);
if (status==PJ_SUCCESS && (dinfo.flag & PJSIP_TRANSPORT_RELIABLE)==0) {
/* Not TCP or TLS. No need to do this */
status = PJ_EINVALIDOP;
log_written = PJ_TRUE;
}
if (status==PJ_SUCCESS &&
get_ip_addr_ver(&dinfo.addr.host)==0 &&
pjsua_var.ua_cfg.nameserver_count)
{
/* If nameserver is configured, PJSIP will resolve destinations
* by their DNS SRV record first. On the other hand, we will
* resolve destination with DNS A record via pj_getaddrinfo().
* They may yield different IP addresses, hence causing different
* TCP/TLS connection to be created and hence different source
* address.
*/
PJ_LOG(4,(THIS_FILE, "Warning: cannot use source TCP/TLS socket"
" address for Contact when nameserver is configured."));
status = PJ_ENOTSUP;
log_written = PJ_TRUE;
}
if (status == PJ_SUCCESS) {
unsigned cnt=1;
int af;
af = (dinfo.type & PJSIP_TRANSPORT_IPV6)? PJ_AF_INET6 : PJ_AF_INET;
status = pj_getaddrinfo(af, &dinfo.addr.host, &cnt, &ai);
}
if (status == PJ_SUCCESS) {
int addr_len = pj_sockaddr_get_len(&ai.ai_addr);
pj_uint16_t port = (pj_uint16_t)dinfo.addr.port;
if (port==0) {
port = (dinfo.flag & PJSIP_TRANSPORT_SECURE) ? 5061 : 5060;
}
pj_sockaddr_set_port(&ai.ai_addr, port);
status = pjsip_endpt_acquire_transport(pjsua_var.endpt,
dinfo.type,
&ai.ai_addr,
addr_len,
&tp_sel, &tp);
}
if (status == PJ_SUCCESS && (tp->local_name.port == 0 ||
tp->local_name.host.slen==0 ||
*tp->local_name.host.ptr=='0'))
{
/* Trap zero port or "0.0.0.0" address. */
/* The TCP/TLS transport is still connecting and unfortunately
* this OS doesn't report the bound local address in this state.
*/
PJ_LOG(4,(THIS_FILE, "Unable to get transport local port "
"for Contact address (OS doesn't support)"));
status = PJ_ENOTSUP;
log_written = PJ_TRUE;
}
if (status == PJ_SUCCESS) {
/* Got the local transport address */
pj_strdup(pool, &addr->host, &tp->local_name.host);
addr->port = tp->local_name.port;
}
if (tp) {
/* Here the transport's ref counter WILL reach zero. But the
* transport will NOT get destroyed because it should have an
* idle timer.
*/
pjsip_transport_dec_ref(tp);
tp = NULL;
}
if (status != PJ_SUCCESS && !log_written) {
PJ_PERROR(4,(THIS_FILE, status, "Unable to use source local "
"TCP socket address for Contact"));
}
status = PJ_SUCCESS;
}
if (p_tp_type)
*p_tp_type = tp_type;
if (secure) {
*secure = (flag & PJSIP_TRANSPORT_SECURE) != 0;
}
if (p_tp)
*p_tp = tfla2_prm.ret_tp;
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pjsua_acc_create_uac_contact( pj_pool_t *pool,
pj_str_t *contact,
pjsua_acc_id acc_id,
const pj_str_t *suri)
{
pjsua_acc *acc;
pj_status_t status;
pjsip_transport_type_e tp_type;
pjsip_host_port addr;
int secure;
const char *beginquote, *endquote;
char transport_param[32];
const char *ob = ";ob";
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
/* If force_contact is configured, then use use it */
if (acc->cfg.force_contact.slen) {
*contact = acc->cfg.force_contact;
return PJ_SUCCESS;
}
status = pjsua_acc_get_uac_addr(acc_id, pool, suri, &addr,
&tp_type, &secure, NULL);
if (status != PJ_SUCCESS)
return status;
/* Enclose IPv6 address in square brackets */
if (tp_type & PJSIP_TRANSPORT_IPV6) {
beginquote = "[";
endquote = "]";
} else {
beginquote = endquote = "";
}
/* Don't add transport parameter if it's UDP */
if (tp_type!=PJSIP_TRANSPORT_UDP && tp_type!=PJSIP_TRANSPORT_UDP6) {
pj_ansi_snprintf(transport_param, sizeof(transport_param),
";transport=%s",
pjsip_transport_get_type_name(tp_type));
} else {
transport_param[0] = '\0';
}
/* Create the contact header */
contact->ptr = (char*)pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE,
"%s%.*s%s<%s:%.*s%s%s%.*s%s:%d%s%.*s%s>%.*s",
(acc->display.slen?"\"" : ""),
(int)acc->display.slen,
acc->display.ptr,
(acc->display.slen?"\" " : ""),
((secure && acc->is_sips)? "sips" : "sip"),
(int)acc->user_part.slen,
acc->user_part.ptr,
(acc->user_part.slen?"@":""),
beginquote,
(int)addr.host.slen,
addr.host.ptr,
endquote,
addr.port,
transport_param,
(int)acc->cfg.contact_uri_params.slen,
acc->cfg.contact_uri_params.ptr,
(acc->cfg.use_rfc5626? ob: ""),
(int)acc->cfg.contact_params.slen,
acc->cfg.contact_params.ptr);
if (contact->slen < 1 || contact->slen >= (int)PJSIP_MAX_URL_SIZE)
return PJ_ETOOSMALL;
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pjsua_acc_create_uas_contact( pj_pool_t *pool,
pj_str_t *contact,
pjsua_acc_id acc_id,
pjsip_rx_data *rdata )
{
/*
* Section 12.1.1, paragraph about using SIPS URI in Contact.
* If the request that initiated the dialog contained a SIPS URI
* in the Request-URI or in the top Record-Route header field value,
* if there was any, or the Contact header field if there was no
* Record-Route header field, the Contact header field in the response
* MUST be a SIPS URI.
*/
pjsua_acc *acc;
pjsip_sip_uri *sip_uri;
pj_status_t status;
pjsip_transport_type_e tp_type = PJSIP_TRANSPORT_UNSPECIFIED;
pj_str_t local_addr;
pjsip_tpselector tp_sel;
pjsip_tpmgr *tpmgr;
pjsip_tpmgr_fla2_param tfla2_prm;
unsigned flag;
int secure;
int local_port;
const char *beginquote, *endquote;
char transport_param[32];
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
/* If force_contact is configured, then use use it */
if (acc->cfg.force_contact.slen) {
*contact = acc->cfg.force_contact;
return PJ_SUCCESS;
}
/* If Record-Route is present, then URI is the top Record-Route. */
if (rdata->msg_info.record_route) {
sip_uri = (pjsip_sip_uri*)
pjsip_uri_get_uri(rdata->msg_info.record_route->name_addr.uri);
} else {
pjsip_hdr *pos = NULL;
pjsip_contact_hdr *h_contact;
pjsip_uri *uri = NULL;
/* Otherwise URI is Contact URI.
* Iterate the Contact URI until we find sip: or sips: scheme.
*/
do {
h_contact = (pjsip_contact_hdr*)
pjsip_msg_find_hdr(rdata->msg_info.msg, PJSIP_H_CONTACT,
pos);
if (h_contact) {
if (h_contact->uri)
uri = (pjsip_uri*) pjsip_uri_get_uri(h_contact->uri);
else
uri = NULL;
if (!uri || (!PJSIP_URI_SCHEME_IS_SIP(uri) &&
!PJSIP_URI_SCHEME_IS_SIPS(uri)))
{
pos = (pjsip_hdr*)h_contact->next;
if (pos == &rdata->msg_info.msg->hdr)
h_contact = NULL;
} else {
break;
}
}
} while (h_contact);
/* Or if Contact URI is not present, take the remote URI from
* the From URI.
*/
if (uri == NULL)
uri = (pjsip_uri*) pjsip_uri_get_uri(rdata->msg_info.from->uri);
/* Can only do sip/sips scheme at present. */
if (!PJSIP_URI_SCHEME_IS_SIP(uri) && !PJSIP_URI_SCHEME_IS_SIPS(uri))
return PJSIP_EINVALIDREQURI;
sip_uri = (pjsip_sip_uri*)pjsip_uri_get_uri(uri);
}
/* Get transport type of the URI */
if (PJSIP_URI_SCHEME_IS_SIPS(sip_uri))
tp_type = PJSIP_TRANSPORT_TLS;
else if (sip_uri->transport_param.slen == 0) {
tp_type = PJSIP_TRANSPORT_UDP;
} else
tp_type = pjsip_transport_get_type_from_name(&sip_uri->transport_param);
if (tp_type == PJSIP_TRANSPORT_UNSPECIFIED)
return PJSIP_EUNSUPTRANSPORT;
/* If destination URI specifies IPv6, then set transport type
* to use IPv6 as well.
*/
if (pj_strchr(&sip_uri->host, ':'))
tp_type = (pjsip_transport_type_e)(((int)tp_type) + PJSIP_TRANSPORT_IPV6);
flag = pjsip_transport_get_flag_from_type(tp_type);
secure = (flag & PJSIP_TRANSPORT_SECURE) != 0;
/* Init transport selector. */
pjsua_init_tpselector(pjsua_var.acc[acc_id].cfg.transport_id, &tp_sel);
/* Get local address suitable to send request from */
pjsip_tpmgr_fla2_param_default(&tfla2_prm);
tfla2_prm.tp_type = tp_type;
tfla2_prm.tp_sel = &tp_sel;
tfla2_prm.dst_host = sip_uri->host;
tfla2_prm.local_if = (!pjsua_sip_acc_is_using_stun(acc_id) ||
(flag & PJSIP_TRANSPORT_RELIABLE));
tpmgr = pjsip_endpt_get_tpmgr(pjsua_var.endpt);
status = pjsip_tpmgr_find_local_addr2(tpmgr, pool, &tfla2_prm);
if (status != PJ_SUCCESS)
return status;
local_addr = tfla2_prm.ret_addr;
local_port = tfla2_prm.ret_port;
/* Enclose IPv6 address in square brackets */
if (tp_type & PJSIP_TRANSPORT_IPV6) {
beginquote = "[";
endquote = "]";
} else {
beginquote = endquote = "";
}
/* Don't add transport parameter if it's UDP */
if (tp_type!=PJSIP_TRANSPORT_UDP && tp_type!=PJSIP_TRANSPORT_UDP6) {
pj_ansi_snprintf(transport_param, sizeof(transport_param),
";transport=%s",
pjsip_transport_get_type_name(tp_type));
} else {
transport_param[0] = '\0';
}
/* Create the contact header */
contact->ptr = (char*) pj_pool_alloc(pool, PJSIP_MAX_URL_SIZE);
contact->slen = pj_ansi_snprintf(contact->ptr, PJSIP_MAX_URL_SIZE,
"%s%.*s%s<%s:%.*s%s%s%.*s%s:%d%s%.*s>%.*s",
(acc->display.slen?"\"" : ""),
(int)acc->display.slen,
acc->display.ptr,
(acc->display.slen?"\" " : ""),
((secure && acc->is_sips)? "sips" : "sip"),
(int)acc->user_part.slen,
acc->user_part.ptr,
(acc->user_part.slen?"@":""),
beginquote,
(int)local_addr.slen,
local_addr.ptr,
endquote,
local_port,
transport_param,
(int)acc->cfg.contact_uri_params.slen,
acc->cfg.contact_uri_params.ptr,
(int)acc->cfg.contact_params.slen,
acc->cfg.contact_params.ptr);
if (contact->slen < 1 || contact->slen >= (int)PJSIP_MAX_URL_SIZE)
return PJ_ETOOSMALL;
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pjsua_acc_set_transport( pjsua_acc_id acc_id,
pjsua_transport_id tp_id)
{
pjsua_acc *acc;
PJ_ASSERT_RETURN(pjsua_acc_is_valid(acc_id), PJ_EINVAL);
acc = &pjsua_var.acc[acc_id];
PJ_ASSERT_RETURN(tp_id >= 0 && tp_id < (int)PJ_ARRAY_SIZE(pjsua_var.tpdata),
PJ_EINVAL);
acc->cfg.transport_id = tp_id;
return PJ_SUCCESS;
}
/* Auto re-registration timeout callback */
static void auto_rereg_timer_cb(pj_timer_heap_t *th, pj_timer_entry *te)
{
pjsua_acc *acc;
pj_status_t status;
PJ_UNUSED_ARG(th);
acc = (pjsua_acc*) te->user_data;
pj_assert(acc);
PJSUA_LOCK();
/* Check if the reregistration timer is still valid, e.g: while waiting
* timeout timer application might have deleted the account or disabled
* the auto-reregistration.
*/
if (!acc->valid || !acc->auto_rereg.active ||
acc->cfg.reg_retry_interval == 0)
{
goto on_return;
}
/* Start re-registration */
acc->auto_rereg.attempt_cnt++;
status = pjsua_acc_set_registration(acc->index, PJ_TRUE);
if (status != PJ_SUCCESS)
schedule_reregistration(acc);
on_return:
PJSUA_UNLOCK();
}
/* Schedule reregistration for specified account. Note that the first
* re-registration after a registration failure will be done immediately.
* Also note that this function should be called within PJSUA mutex.
*/
static void schedule_reregistration(pjsua_acc *acc)
{
pj_time_val delay;
pj_assert(acc);
/* Validate the account and re-registration feature status */
if (!acc->valid || acc->cfg.reg_retry_interval == 0) {
return;
}
/* If configured, disconnect calls of this account after the first
* reregistration attempt failed.
*/
if (acc->cfg.drop_calls_on_reg_fail && acc->auto_rereg.attempt_cnt >= 1)
{
unsigned i, cnt;
for (i = 0, cnt = 0; i < pjsua_var.ua_cfg.max_calls; ++i) {
if (pjsua_var.calls[i].acc_id == acc->index) {
pjsua_call_hangup(i, 0, NULL, NULL);
++cnt;
}
}
if (cnt) {
PJ_LOG(3, (THIS_FILE, "Disconnecting %d call(s) of account #%d "
"after reregistration attempt failed",
cnt, acc->index));
}
}
/* Cancel any re-registration timer */
if (acc->auto_rereg.timer.id) {
acc->auto_rereg.timer.id = PJ_FALSE;
pjsua_cancel_timer(&acc->auto_rereg.timer);
}
/* Update re-registration flag */
acc->auto_rereg.active = PJ_TRUE;
/* Set up timer for reregistration */
acc->auto_rereg.timer.cb = &auto_rereg_timer_cb;
acc->auto_rereg.timer.user_data = acc;
/* Reregistration attempt. The first attempt will be done immediately. */
delay.sec = acc->auto_rereg.attempt_cnt? acc->cfg.reg_retry_interval :
acc->cfg.reg_first_retry_interval;
delay.msec = 0;
/* Randomize interval by +/- reg_retry_random_interval, if configured */
if (acc->cfg.reg_retry_random_interval) {
long rand_ms = acc->cfg.reg_retry_random_interval * 1000;
if (delay.sec >= (long)acc->cfg.reg_retry_random_interval) {
delay.msec = -rand_ms + (pj_rand() % (rand_ms * 2));
} else {
delay.sec = 0;
delay.msec = (pj_rand() % (delay.sec * 1000 + rand_ms));
}
}
pj_time_val_normalize(&delay);
PJ_LOG(4,(THIS_FILE,
"Scheduling re-registration retry for acc %d in %u seconds..",
acc->index, delay.sec));
acc->auto_rereg.timer.id = PJ_TRUE;
if (pjsua_schedule_timer(&acc->auto_rereg.timer, &delay) != PJ_SUCCESS)
acc->auto_rereg.timer.id = PJ_FALSE;
}
/* Internal function to perform auto-reregistration on transport
* connection/disconnection events.
*/
void pjsua_acc_on_tp_state_changed(pjsip_transport *tp,
pjsip_transport_state state,
const pjsip_transport_state_info *info)
{
unsigned i;
PJ_UNUSED_ARG(info);
/* Only care for transport disconnection events */
if (state != PJSIP_TP_STATE_DISCONNECTED)
return;
PJ_LOG(4,(THIS_FILE, "Disconnected notification for transport %s",
tp->obj_name));
pj_log_push_indent();
/* Shutdown this transport, to make sure that the transport manager
* will create a new transport for reconnection.
*/
pjsip_transport_shutdown(tp);
PJSUA_LOCK();
/* Enumerate accounts using this transport and perform actions
* based on the transport state.
*/
for (i = 0; i < PJ_ARRAY_SIZE(pjsua_var.acc); ++i) {
pjsua_acc *acc = &pjsua_var.acc[i];
/* Skip if this account is not valid OR auto re-registration
* feature is disabled OR this transport is not used by this account.
*/
if (!acc->valid || !acc->cfg.reg_retry_interval ||
tp != acc->auto_rereg.reg_tp)
{
continue;
}
/* Release regc transport immediately
* See https://trac.pjsip.org/repos/ticket/1481
*/
if (pjsua_var.acc[i].regc) {
pjsip_regc_release_transport(pjsua_var.acc[i].regc);
}
/* Schedule reregistration for this account */
schedule_reregistration(acc);
}
PJSUA_UNLOCK();
pj_log_pop_indent();
}
| ezrover/pjsip-2.3 | pjsip/src/pjsua-lib/pjsua_acc.c | C | gpl-2.0 | 103,589 |
/* RNG.h
* by Alex Chadwick
*
* Copyright (C) 2014, Alex Chadwick
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/* definitions of symbols inferred to exist in the RNG.h header file for
* which the brainslug symbol information is available which are specific to
* the game `New Super Mario Bros. Wii'. */
#ifndef _SMN_RNG_H_
#define _SMN_RNG_H_
typedef long rng_t;
/*
// Default non-rentrant RNG
void RNG_DefaultSeed(long seed);
// Returns a random float between 0 and 1
float RNG_DefaultRandFloat(void);
unsigned short RNG_DefaultRand(void);
float RNG_DefaultRandFloatRange(float max);
*/
// Rentrant RNG
unsigned int RNG_Rand(rng_t *rng, unsigned int max);
// Returns a random float between 0 and 1
float RNG_RandFloat(rng_t *rng);
// Returns a random float between -0.5 and 0.5
float RNG_RandFloatZeroed(rng_t *rng);
#endif /* _SMN_RNG_H_ */
| MrBean35000vr/netslug-wii | bslug_include/smn/RNG.h | C | gpl-2.0 | 1,891 |
{% extends "core/administration/base.html" %}
{% block styles %}
<style type="text/css">
{{ tables.style_columns([2], "border-left: 1px solid #ddd; border-right: 1px solid #ddd;") }}
{{ tables.style_headers([2], "border-left: 1px solid #ddd; border-right: 1px solid #ddd;") }}
{{ tables.size_columns([3], "25%") }}
{{ tables.size_columns([4], "75%") }}
{{ tables.style_columns([4, 5, 6], "font-size: 12px; color: #888;") }}
{{ tables.align_columns([6], "center") }}
</style>
{% endblock %}
{% block content %}
<h1>Menu Administration</h1>
<table>
<thead>
<th>{{ menus.build(actions) }}</th>
<th>{{ icons.glyph("picture") }}</th>
<th>Name</th>
<th>Address</th>
<th>Menu Bar</th>
<th>{{ icons.glyph("transfer") }}</th>
</thead>
<tbody>
<tr class="filters">
<td>{{ icons.glyph("filter") }}</td>
<td></td>
<td></td>
<td><input type="text" class="eowyne-table-filter"/></td>
<td><select class="eowyne-table-filter"/></td>
<td></td>
</tr>
{% for item in items %}
<tr class="{{ loop.cycle('odd', 'even') }}">
<td>{{ menus.context(item.actions, item.id) }}</td>
<td>{{ icons.glyph(item.image) }}</td>
<td>{{ item.name }}</td>
<td>{{ item.address }}</td>
<td>{{ item.menubar.name }}</td>
<td>{{ item.weight }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %} | dpetter/Eowyne | template/core/administration/menu-list.html | HTML | gpl-2.0 | 1,327 |
/**
* @package AcyMailing for Joomla!
* @version 5.0.1
* @author acyba.com
* @copyright (C) 2009-2015 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
@import url("component_default_classic_black.css");
#acyarchivelisting .button, #acymodifyform .button, #unsubbutton_div .button{
color:#4b7c8e !important;
}
#acyarchivelisting .button:hover, #acymodifyform .button:hover, #unsubbutton_div .button:hover{
color:#fff!important;
background-color:#4b7c8e !important;
}
#acyarchivelisting .contentheading{
color:#4b7c8e;
}
#acyarchivelisting .contentpane .contentdescription{
color:#6699ab;
}
#acyarchivelisting .contentpane tbody .sectiontableentry1 a:hover{
color:#6699ab;
}
#acyarchivelisting .contentpane tbody .sectiontableentry2 a:hover{
color:#6699ab;
}
#acyarchivelisting .sectiontableheader a:hover{
color:#6699ab;
}
#acyarchiveview .contentheading{
color:#6699ab;}
#acylistslisting .componentheading{
color:#4b7c8e;
}
#acylistslisting .list_name a{
color:#6699ab;
}
#acylistslisting .list_name a:hover, #acylistslisting .list_name a:focus {
color:#6699ab;
}
#acymodifyform legend{
color:#4b7c8e;
}
#acyusersubscription .list_name{
color: #6699ab;
}
#unsubpage .unsubsurveytext{
color:#4b7c8e;
}
#unsubpage .unsubintro{
color:#4b7c8e;
}
| Grifindorf/kolbaska | media/com_acymailing/css/component_default_classic_blue.css | CSS | gpl-2.0 | 1,385 |
namespace thewall9.api.Areas.HelpPage.ModelDescriptions
{
public class EnumValueDescription
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
} | ozalvarez/thewall9-CMS | thewall9.api/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs | C# | gpl-2.0 | 244 |
* {
margin: 0;
padding: 0;
}
#content {
width: 100%;
padding-left: 20px;
padding-right: 20px;
}
#content .section {
display: inline-block;
width: 100px;
margin: 0 auto;
height: 100px;
background-color: #DEDEDE;
position: relative;
}
.tips {
position: absolute;
left: 50%;
top: 20px;
margin-left: -12.5px;
}
.tips .icon {
display: block;
width: 25px;
height: 25px;
border-radius: 25px;
border: 3px solid #b0b0b0;
color: #b0b0b0;
font-size: 25px;
font-weight: bolder;
text-align: center;
line-height: 25px;
}
.tips .content {
z-index: 99999;
display: none;
position: absolute;
top: 45px;
left: -35px;
width: 250px;
padding: 20px;
text-align: left;
background-color: #f7e6dc;
}
.tips .content .tri {
position: absolute;
left: 40px;
top: -18px;
border: 10px solid transparent;
border-bottom: 10px solid #f7e6dc;
}
.tips:hover {
cursor: pointer;
}
.tips:hover .content {
display: block;
}
| zhouyoqin/zhouyoqin.github.io | self/tricks/index.css | CSS | gpl-2.0 | 966 |
package omoikane.producto.compras;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import javafx.application.Application;
import omoikane.principal.Principal;
import omoikane.producto.DummyJFXApp;
import omoikane.repository.ProductoRepo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import java.util.HashMap;
/**
* Created with IntelliJ IDEA.
* User: octavioruizcastillo
* Date: 16/02/13
* Time: 11:40
* To change this template use File | Settings | File Templates.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-test.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
//@DatabaseSetup("../repository/sampleDataLight.xml")
public class ComprasProductoTest {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ComprasProductoTest.class);
@Autowired
ProductoRepo productoRepo;
@Test
public void ListaDePreciosProductoViewTest() {
Principal.applicationContext = new ClassPathXmlApplicationContext("applicationContext-test.xml");
HashMap testProperties = (HashMap) Principal.applicationContext.getBean( "properties" );
testProperties.put("DummyJFXApp.viewBeanToTest", "comprasProductoView");
Application.launch(DummyJFXApp.class);
}
}
| ZooMMX/Omoikane | test/src/omoikane/producto/compras/ComprasProductoTest.java | Java | gpl-2.0 | 2,073 |
/*
* Default Palettes for Quicktime Files
* Automatically generated from a utility derived from XAnim:
* http://xanim.va.pubnix.com/home.html
*/
#ifndef QTPALETTE_H
#define QTPALETTE_H
unsigned char ff_qt_default_palette_4[4 * 4] = {
0x93, 0x65, 0x5E, 0x00,
0xFF, 0xFF, 0xFF, 0x00,
0xDF, 0xD0, 0xAB, 0x00,
0x00, 0x00, 0x00, 0x00
};
unsigned char ff_qt_default_palette_16[16 * 4] = {
0xFF, 0xFB, 0xFF, 0x00,
0xEF, 0xD9, 0xBB, 0x00,
0xE8, 0xC9, 0xB1, 0x00,
0x93, 0x65, 0x5E, 0x00,
0xFC, 0xDE, 0xE8, 0x00,
0x9D, 0x88, 0x91, 0x00,
0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00,
0xFF, 0xFF, 0xFF, 0x00,
0x47, 0x48, 0x37, 0x00,
0x7A, 0x5E, 0x55, 0x00,
0xDF, 0xD0, 0xAB, 0x00,
0xFF, 0xFB, 0xF9, 0x00,
0xE8, 0xCA, 0xC5, 0x00,
0x8A, 0x7C, 0x77, 0x00,
0x00, 0x00, 0x00, 0x00
};
unsigned char ff_qt_default_palette_256[256 * 4] = {
/* 0, 0x00 */ 0xFF, 0xFF, 0xFF, 0x00,
/* 1, 0x01 */ 0xFF, 0xFF, 0xCC, 0x00,
/* 2, 0x02 */ 0xFF, 0xFF, 0x99, 0x00,
/* 3, 0x03 */ 0xFF, 0xFF, 0x66, 0x00,
/* 4, 0x04 */ 0xFF, 0xFF, 0x33, 0x00,
/* 5, 0x05 */ 0xFF, 0xFF, 0x00, 0x00,
/* 6, 0x06 */ 0xFF, 0xCC, 0xFF, 0x00,
/* 7, 0x07 */ 0xFF, 0xCC, 0xCC, 0x00,
/* 8, 0x08 */ 0xFF, 0xCC, 0x99, 0x00,
/* 9, 0x09 */ 0xFF, 0xCC, 0x66, 0x00,
/* 10, 0x0A */ 0xFF, 0xCC, 0x33, 0x00,
/* 11, 0x0B */ 0xFF, 0xCC, 0x00, 0x00,
/* 12, 0x0C */ 0xFF, 0x99, 0xFF, 0x00,
/* 13, 0x0D */ 0xFF, 0x99, 0xCC, 0x00,
/* 14, 0x0E */ 0xFF, 0x99, 0x99, 0x00,
/* 15, 0x0F */ 0xFF, 0x99, 0x66, 0x00,
/* 16, 0x10 */ 0xFF, 0x99, 0x33, 0x00,
/* 17, 0x11 */ 0xFF, 0x99, 0x00, 0x00,
/* 18, 0x12 */ 0xFF, 0x66, 0xFF, 0x00,
/* 19, 0x13 */ 0xFF, 0x66, 0xCC, 0x00,
/* 20, 0x14 */ 0xFF, 0x66, 0x99, 0x00,
/* 21, 0x15 */ 0xFF, 0x66, 0x66, 0x00,
/* 22, 0x16 */ 0xFF, 0x66, 0x33, 0x00,
/* 23, 0x17 */ 0xFF, 0x66, 0x00, 0x00,
/* 24, 0x18 */ 0xFF, 0x33, 0xFF, 0x00,
/* 25, 0x19 */ 0xFF, 0x33, 0xCC, 0x00,
/* 26, 0x1A */ 0xFF, 0x33, 0x99, 0x00,
/* 27, 0x1B */ 0xFF, 0x33, 0x66, 0x00,
/* 28, 0x1C */ 0xFF, 0x33, 0x33, 0x00,
/* 29, 0x1D */ 0xFF, 0x33, 0x00, 0x00,
/* 30, 0x1E */ 0xFF, 0x00, 0xFF, 0x00,
/* 31, 0x1F */ 0xFF, 0x00, 0xCC, 0x00,
/* 32, 0x20 */ 0xFF, 0x00, 0x99, 0x00,
/* 33, 0x21 */ 0xFF, 0x00, 0x66, 0x00,
/* 34, 0x22 */ 0xFF, 0x00, 0x33, 0x00,
/* 35, 0x23 */ 0xFF, 0x00, 0x00, 0x00,
/* 36, 0x24 */ 0xCC, 0xFF, 0xFF, 0x00,
/* 37, 0x25 */ 0xCC, 0xFF, 0xCC, 0x00,
/* 38, 0x26 */ 0xCC, 0xFF, 0x99, 0x00,
/* 39, 0x27 */ 0xCC, 0xFF, 0x66, 0x00,
/* 40, 0x28 */ 0xCC, 0xFF, 0x33, 0x00,
/* 41, 0x29 */ 0xCC, 0xFF, 0x00, 0x00,
/* 42, 0x2A */ 0xCC, 0xCC, 0xFF, 0x00,
/* 43, 0x2B */ 0xCC, 0xCC, 0xCC, 0x00,
/* 44, 0x2C */ 0xCC, 0xCC, 0x99, 0x00,
/* 45, 0x2D */ 0xCC, 0xCC, 0x66, 0x00,
/* 46, 0x2E */ 0xCC, 0xCC, 0x33, 0x00,
/* 47, 0x2F */ 0xCC, 0xCC, 0x00, 0x00,
/* 48, 0x30 */ 0xCC, 0x99, 0xFF, 0x00,
/* 49, 0x31 */ 0xCC, 0x99, 0xCC, 0x00,
/* 50, 0x32 */ 0xCC, 0x99, 0x99, 0x00,
/* 51, 0x33 */ 0xCC, 0x99, 0x66, 0x00,
/* 52, 0x34 */ 0xCC, 0x99, 0x33, 0x00,
/* 53, 0x35 */ 0xCC, 0x99, 0x00, 0x00,
/* 54, 0x36 */ 0xCC, 0x66, 0xFF, 0x00,
/* 55, 0x37 */ 0xCC, 0x66, 0xCC, 0x00,
/* 56, 0x38 */ 0xCC, 0x66, 0x99, 0x00,
/* 57, 0x39 */ 0xCC, 0x66, 0x66, 0x00,
/* 58, 0x3A */ 0xCC, 0x66, 0x33, 0x00,
/* 59, 0x3B */ 0xCC, 0x66, 0x00, 0x00,
/* 60, 0x3C */ 0xCC, 0x33, 0xFF, 0x00,
/* 61, 0x3D */ 0xCC, 0x33, 0xCC, 0x00,
/* 62, 0x3E */ 0xCC, 0x33, 0x99, 0x00,
/* 63, 0x3F */ 0xCC, 0x33, 0x66, 0x00,
/* 64, 0x40 */ 0xCC, 0x33, 0x33, 0x00,
/* 65, 0x41 */ 0xCC, 0x33, 0x00, 0x00,
/* 66, 0x42 */ 0xCC, 0x00, 0xFF, 0x00,
/* 67, 0x43 */ 0xCC, 0x00, 0xCC, 0x00,
/* 68, 0x44 */ 0xCC, 0x00, 0x99, 0x00,
/* 69, 0x45 */ 0xCC, 0x00, 0x66, 0x00,
/* 70, 0x46 */ 0xCC, 0x00, 0x33, 0x00,
/* 71, 0x47 */ 0xCC, 0x00, 0x00, 0x00,
/* 72, 0x48 */ 0x99, 0xFF, 0xFF, 0x00,
/* 73, 0x49 */ 0x99, 0xFF, 0xCC, 0x00,
/* 74, 0x4A */ 0x99, 0xFF, 0x99, 0x00,
/* 75, 0x4B */ 0x99, 0xFF, 0x66, 0x00,
/* 76, 0x4C */ 0x99, 0xFF, 0x33, 0x00,
/* 77, 0x4D */ 0x99, 0xFF, 0x00, 0x00,
/* 78, 0x4E */ 0x99, 0xCC, 0xFF, 0x00,
/* 79, 0x4F */ 0x99, 0xCC, 0xCC, 0x00,
/* 80, 0x50 */ 0x99, 0xCC, 0x99, 0x00,
/* 81, 0x51 */ 0x99, 0xCC, 0x66, 0x00,
/* 82, 0x52 */ 0x99, 0xCC, 0x33, 0x00,
/* 83, 0x53 */ 0x99, 0xCC, 0x00, 0x00,
/* 84, 0x54 */ 0x99, 0x99, 0xFF, 0x00,
/* 85, 0x55 */ 0x99, 0x99, 0xCC, 0x00,
/* 86, 0x56 */ 0x99, 0x99, 0x99, 0x00,
/* 87, 0x57 */ 0x99, 0x99, 0x66, 0x00,
/* 88, 0x58 */ 0x99, 0x99, 0x33, 0x00,
/* 89, 0x59 */ 0x99, 0x99, 0x00, 0x00,
/* 90, 0x5A */ 0x99, 0x66, 0xFF, 0x00,
/* 91, 0x5B */ 0x99, 0x66, 0xCC, 0x00,
/* 92, 0x5C */ 0x99, 0x66, 0x99, 0x00,
/* 93, 0x5D */ 0x99, 0x66, 0x66, 0x00,
/* 94, 0x5E */ 0x99, 0x66, 0x33, 0x00,
/* 95, 0x5F */ 0x99, 0x66, 0x00, 0x00,
/* 96, 0x60 */ 0x99, 0x33, 0xFF, 0x00,
/* 97, 0x61 */ 0x99, 0x33, 0xCC, 0x00,
/* 98, 0x62 */ 0x99, 0x33, 0x99, 0x00,
/* 99, 0x63 */ 0x99, 0x33, 0x66, 0x00,
/* 100, 0x64 */ 0x99, 0x33, 0x33, 0x00,
/* 101, 0x65 */ 0x99, 0x33, 0x00, 0x00,
/* 102, 0x66 */ 0x99, 0x00, 0xFF, 0x00,
/* 103, 0x67 */ 0x99, 0x00, 0xCC, 0x00,
/* 104, 0x68 */ 0x99, 0x00, 0x99, 0x00,
/* 105, 0x69 */ 0x99, 0x00, 0x66, 0x00,
/* 106, 0x6A */ 0x99, 0x00, 0x33, 0x00,
/* 107, 0x6B */ 0x99, 0x00, 0x00, 0x00,
/* 108, 0x6C */ 0x66, 0xFF, 0xFF, 0x00,
/* 109, 0x6D */ 0x66, 0xFF, 0xCC, 0x00,
/* 110, 0x6E */ 0x66, 0xFF, 0x99, 0x00,
/* 111, 0x6F */ 0x66, 0xFF, 0x66, 0x00,
/* 112, 0x70 */ 0x66, 0xFF, 0x33, 0x00,
/* 113, 0x71 */ 0x66, 0xFF, 0x00, 0x00,
/* 114, 0x72 */ 0x66, 0xCC, 0xFF, 0x00,
/* 115, 0x73 */ 0x66, 0xCC, 0xCC, 0x00,
/* 116, 0x74 */ 0x66, 0xCC, 0x99, 0x00,
/* 117, 0x75 */ 0x66, 0xCC, 0x66, 0x00,
/* 118, 0x76 */ 0x66, 0xCC, 0x33, 0x00,
/* 119, 0x77 */ 0x66, 0xCC, 0x00, 0x00,
/* 120, 0x78 */ 0x66, 0x99, 0xFF, 0x00,
/* 121, 0x79 */ 0x66, 0x99, 0xCC, 0x00,
/* 122, 0x7A */ 0x66, 0x99, 0x99, 0x00,
/* 123, 0x7B */ 0x66, 0x99, 0x66, 0x00,
/* 124, 0x7C */ 0x66, 0x99, 0x33, 0x00,
/* 125, 0x7D */ 0x66, 0x99, 0x00, 0x00,
/* 126, 0x7E */ 0x66, 0x66, 0xFF, 0x00,
/* 127, 0x7F */ 0x66, 0x66, 0xCC, 0x00,
/* 128, 0x80 */ 0x66, 0x66, 0x99, 0x00,
/* 129, 0x81 */ 0x66, 0x66, 0x66, 0x00,
/* 130, 0x82 */ 0x66, 0x66, 0x33, 0x00,
/* 131, 0x83 */ 0x66, 0x66, 0x00, 0x00,
/* 132, 0x84 */ 0x66, 0x33, 0xFF, 0x00,
/* 133, 0x85 */ 0x66, 0x33, 0xCC, 0x00,
/* 134, 0x86 */ 0x66, 0x33, 0x99, 0x00,
/* 135, 0x87 */ 0x66, 0x33, 0x66, 0x00,
/* 136, 0x88 */ 0x66, 0x33, 0x33, 0x00,
/* 137, 0x89 */ 0x66, 0x33, 0x00, 0x00,
/* 138, 0x8A */ 0x66, 0x00, 0xFF, 0x00,
/* 139, 0x8B */ 0x66, 0x00, 0xCC, 0x00,
/* 140, 0x8C */ 0x66, 0x00, 0x99, 0x00,
/* 141, 0x8D */ 0x66, 0x00, 0x66, 0x00,
/* 142, 0x8E */ 0x66, 0x00, 0x33, 0x00,
/* 143, 0x8F */ 0x66, 0x00, 0x00, 0x00,
/* 144, 0x90 */ 0x33, 0xFF, 0xFF, 0x00,
/* 145, 0x91 */ 0x33, 0xFF, 0xCC, 0x00,
/* 146, 0x92 */ 0x33, 0xFF, 0x99, 0x00,
/* 147, 0x93 */ 0x33, 0xFF, 0x66, 0x00,
/* 148, 0x94 */ 0x33, 0xFF, 0x33, 0x00,
/* 149, 0x95 */ 0x33, 0xFF, 0x00, 0x00,
/* 150, 0x96 */ 0x33, 0xCC, 0xFF, 0x00,
/* 151, 0x97 */ 0x33, 0xCC, 0xCC, 0x00,
/* 152, 0x98 */ 0x33, 0xCC, 0x99, 0x00,
/* 153, 0x99 */ 0x33, 0xCC, 0x66, 0x00,
/* 154, 0x9A */ 0x33, 0xCC, 0x33, 0x00,
/* 155, 0x9B */ 0x33, 0xCC, 0x00, 0x00,
/* 156, 0x9C */ 0x33, 0x99, 0xFF, 0x00,
/* 157, 0x9D */ 0x33, 0x99, 0xCC, 0x00,
/* 158, 0x9E */ 0x33, 0x99, 0x99, 0x00,
/* 159, 0x9F */ 0x33, 0x99, 0x66, 0x00,
/* 160, 0xA0 */ 0x33, 0x99, 0x33, 0x00,
/* 161, 0xA1 */ 0x33, 0x99, 0x00, 0x00,
/* 162, 0xA2 */ 0x33, 0x66, 0xFF, 0x00,
/* 163, 0xA3 */ 0x33, 0x66, 0xCC, 0x00,
/* 164, 0xA4 */ 0x33, 0x66, 0x99, 0x00,
/* 165, 0xA5 */ 0x33, 0x66, 0x66, 0x00,
/* 166, 0xA6 */ 0x33, 0x66, 0x33, 0x00,
/* 167, 0xA7 */ 0x33, 0x66, 0x00, 0x00,
/* 168, 0xA8 */ 0x33, 0x33, 0xFF, 0x00,
/* 169, 0xA9 */ 0x33, 0x33, 0xCC, 0x00,
/* 170, 0xAA */ 0x33, 0x33, 0x99, 0x00,
/* 171, 0xAB */ 0x33, 0x33, 0x66, 0x00,
/* 172, 0xAC */ 0x33, 0x33, 0x33, 0x00,
/* 173, 0xAD */ 0x33, 0x33, 0x00, 0x00,
/* 174, 0xAE */ 0x33, 0x00, 0xFF, 0x00,
/* 175, 0xAF */ 0x33, 0x00, 0xCC, 0x00,
/* 176, 0xB0 */ 0x33, 0x00, 0x99, 0x00,
/* 177, 0xB1 */ 0x33, 0x00, 0x66, 0x00,
/* 178, 0xB2 */ 0x33, 0x00, 0x33, 0x00,
/* 179, 0xB3 */ 0x33, 0x00, 0x00, 0x00,
/* 180, 0xB4 */ 0x00, 0xFF, 0xFF, 0x00,
/* 181, 0xB5 */ 0x00, 0xFF, 0xCC, 0x00,
/* 182, 0xB6 */ 0x00, 0xFF, 0x99, 0x00,
/* 183, 0xB7 */ 0x00, 0xFF, 0x66, 0x00,
/* 184, 0xB8 */ 0x00, 0xFF, 0x33, 0x00,
/* 185, 0xB9 */ 0x00, 0xFF, 0x00, 0x00,
/* 186, 0xBA */ 0x00, 0xCC, 0xFF, 0x00,
/* 187, 0xBB */ 0x00, 0xCC, 0xCC, 0x00,
/* 188, 0xBC */ 0x00, 0xCC, 0x99, 0x00,
/* 189, 0xBD */ 0x00, 0xCC, 0x66, 0x00,
/* 190, 0xBE */ 0x00, 0xCC, 0x33, 0x00,
/* 191, 0xBF */ 0x00, 0xCC, 0x00, 0x00,
/* 192, 0xC0 */ 0x00, 0x99, 0xFF, 0x00,
/* 193, 0xC1 */ 0x00, 0x99, 0xCC, 0x00,
/* 194, 0xC2 */ 0x00, 0x99, 0x99, 0x00,
/* 195, 0xC3 */ 0x00, 0x99, 0x66, 0x00,
/* 196, 0xC4 */ 0x00, 0x99, 0x33, 0x00,
/* 197, 0xC5 */ 0x00, 0x99, 0x00, 0x00,
/* 198, 0xC6 */ 0x00, 0x66, 0xFF, 0x00,
/* 199, 0xC7 */ 0x00, 0x66, 0xCC, 0x00,
/* 200, 0xC8 */ 0x00, 0x66, 0x99, 0x00,
/* 201, 0xC9 */ 0x00, 0x66, 0x66, 0x00,
/* 202, 0xCA */ 0x00, 0x66, 0x33, 0x00,
/* 203, 0xCB */ 0x00, 0x66, 0x00, 0x00,
/* 204, 0xCC */ 0x00, 0x33, 0xFF, 0x00,
/* 205, 0xCD */ 0x00, 0x33, 0xCC, 0x00,
/* 206, 0xCE */ 0x00, 0x33, 0x99, 0x00,
/* 207, 0xCF */ 0x00, 0x33, 0x66, 0x00,
/* 208, 0xD0 */ 0x00, 0x33, 0x33, 0x00,
/* 209, 0xD1 */ 0x00, 0x33, 0x00, 0x00,
/* 210, 0xD2 */ 0x00, 0x00, 0xFF, 0x00,
/* 211, 0xD3 */ 0x00, 0x00, 0xCC, 0x00,
/* 212, 0xD4 */ 0x00, 0x00, 0x99, 0x00,
/* 213, 0xD5 */ 0x00, 0x00, 0x66, 0x00,
/* 214, 0xD6 */ 0x00, 0x00, 0x33, 0x00,
/* 215, 0xD7 */ 0xEE, 0x00, 0x00, 0x00,
/* 216, 0xD8 */ 0xDD, 0x00, 0x00, 0x00,
/* 217, 0xD9 */ 0xBB, 0x00, 0x00, 0x00,
/* 218, 0xDA */ 0xAA, 0x00, 0x00, 0x00,
/* 219, 0xDB */ 0x88, 0x00, 0x00, 0x00,
/* 220, 0xDC */ 0x77, 0x00, 0x00, 0x00,
/* 221, 0xDD */ 0x55, 0x00, 0x00, 0x00,
/* 222, 0xDE */ 0x44, 0x00, 0x00, 0x00,
/* 223, 0xDF */ 0x22, 0x00, 0x00, 0x00,
/* 224, 0xE0 */ 0x11, 0x00, 0x00, 0x00,
/* 225, 0xE1 */ 0x00, 0xEE, 0x00, 0x00,
/* 226, 0xE2 */ 0x00, 0xDD, 0x00, 0x00,
/* 227, 0xE3 */ 0x00, 0xBB, 0x00, 0x00,
/* 228, 0xE4 */ 0x00, 0xAA, 0x00, 0x00,
/* 229, 0xE5 */ 0x00, 0x88, 0x00, 0x00,
/* 230, 0xE6 */ 0x00, 0x77, 0x00, 0x00,
/* 231, 0xE7 */ 0x00, 0x55, 0x00, 0x00,
/* 232, 0xE8 */ 0x00, 0x44, 0x00, 0x00,
/* 233, 0xE9 */ 0x00, 0x22, 0x00, 0x00,
/* 234, 0xEA */ 0x00, 0x11, 0x00, 0x00,
/* 235, 0xEB */ 0x00, 0x00, 0xEE, 0x00,
/* 236, 0xEC */ 0x00, 0x00, 0xDD, 0x00,
/* 237, 0xED */ 0x00, 0x00, 0xBB, 0x00,
/* 238, 0xEE */ 0x00, 0x00, 0xAA, 0x00,
/* 239, 0xEF */ 0x00, 0x00, 0x88, 0x00,
/* 240, 0xF0 */ 0x00, 0x00, 0x77, 0x00,
/* 241, 0xF1 */ 0x00, 0x00, 0x55, 0x00,
/* 242, 0xF2 */ 0x00, 0x00, 0x44, 0x00,
/* 243, 0xF3 */ 0x00, 0x00, 0x22, 0x00,
/* 244, 0xF4 */ 0x00, 0x00, 0x11, 0x00,
/* 245, 0xF5 */ 0xEE, 0xEE, 0xEE, 0x00,
/* 246, 0xF6 */ 0xDD, 0xDD, 0xDD, 0x00,
/* 247, 0xF7 */ 0xBB, 0xBB, 0xBB, 0x00,
/* 248, 0xF8 */ 0xAA, 0xAA, 0xAA, 0x00,
/* 249, 0xF9 */ 0x88, 0x88, 0x88, 0x00,
/* 250, 0xFA */ 0x77, 0x77, 0x77, 0x00,
/* 251, 0xFB */ 0x55, 0x55, 0x55, 0x00,
/* 252, 0xFC */ 0x44, 0x44, 0x44, 0x00,
/* 253, 0xFD */ 0x22, 0x22, 0x22, 0x00,
/* 254, 0xFE */ 0x11, 0x11, 0x11, 0x00,
/* 255, 0xFF */ 0x00, 0x00, 0x00, 0x00
};
#endif
| sofian/drone | lib/ffmpeg/libavformat/qtpalette.h | C | gpl-2.0 | 11,892 |
/****************************************************************************
*
* NETUTILS.C - NSCA Network Utilities
*
* License: GPL
* Copyright (c) 1999-2002 Ethan Galstad (nagios@nagios.org)
*
* Last Modified: 10-24-2002
*
* Description:
*
* This file contains common network functions used in nrpe and check_nrpe.
*
* License Information:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
****************************************************************************/
#include "nsca.h"
extern void ntsl_log_error(char *, ...);
extern void ntsl_log_warning(char *, ...);
extern void ntsl_log_info(char *, ...);
/* opens a connection to a remote host/tcp port */
int my_tcp_connect(char *host_name,int port,SOCKET *sd){
int result;
result=my_connect(host_name,port,sd,"tcp");
return result;
}
/* opens a tcp or udp connection to a remote host */
int my_connect(char *host_name,int port,SOCKET *sd,char *proto){
struct sockaddr_in servaddr;
struct hostent *hp;
struct protoent *ptrp;
int result;
memset((char *)&servaddr,0,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port= htons((short)port);
/* try to bypass using a DNS lookup if this is just an IP address */
if(!my_inet_aton(host_name,&servaddr.sin_addr)){
/* else do a DNS lookup */
hp=gethostbyname((const char *)host_name);
if(hp==NULL){
ntsl_log_error("Invalid host name '%s'\n",host_name);
return STATE_UNKNOWN;
}
memcpy(&servaddr.sin_addr,hp->h_addr,hp->h_length);
}
/* map transport protocol name to protocol number */
if(((ptrp=getprotobyname(proto)))==NULL){
ntsl_log_error("Cannot map \"%s\" to protocol number\n",proto);
return STATE_UNKNOWN;
}
/* create a socket */
*sd=socket(PF_INET,(!strcmp(proto,"udp"))?SOCK_DGRAM:SOCK_STREAM,ptrp->p_proto);
if(*sd<0){
ntsl_log_error("Socket creation failed\n");
return STATE_UNKNOWN;
}
/* open a connection */
result=connect(*sd,(struct sockaddr *)&servaddr,sizeof(servaddr));
if(result<0){
// switch(errno){
// case ECONNREFUSED:
// ntsl_log_error("Connection refused by host\n");
// break;
// case ETIMEDOUT:
// ntsl_log_error("Timeout while attempting connection\n");
// break;
// case ENETUNREACH:
// ntsl_log_error("Network is unreachable\n");
// break;
// default:
ntsl_log_error("Connection refused or timed out\n");
// }
return STATE_CRITICAL;
}
return STATE_OK;
}
/* This code was taken from Fyodor's nmap utility, which was originally taken from
the GLIBC 2.0.6 libraries because Solaris doesn't contain the inet_aton() funtion. */
int my_inet_aton(register const char *cp, struct in_addr *addr){
register unsigned int val; /* changed from u_long --david */
register int base, n;
register char c;
u_int parts[4];
register u_int *pp = parts;
c=*cp;
for(;;){
/*
* Collect number up to ``.''.
* Values are specified as for C:
* 0x=hex, 0=octal, isdigit=decimal.
*/
if (!isdigit((int)c))
return (0);
val=0;
base=10;
if(c=='0'){
c=*++cp;
if(c=='x'||c=='X')
base=16,c=*++cp;
else
base=8;
}
for(;;){
if(isascii((int)c) && isdigit((int)c)){
val=(val*base)+(c -'0');
c=*++cp;
}
else if(base==16 && isascii((int)c) && isxdigit((int)c)){
val=(val<<4) | (c+10-(islower((int)c)?'a':'A'));
c = *++cp;
}
else
break;
}
if(c=='.'){
/*
* Internet format:
* a.b.c.d
* a.b.c (with c treated as 16 bits)
* a.b (with b treated as 24 bits)
*/
if(pp>=parts+3)
return (0);
*pp++=val;
c=*++cp;
}
else
break;
}
/* Check for trailing characters */
if(c!='\0' && (!isascii((int)c) || !isspace((int)c)))
return (0);
/* Concoct the address according to the number of parts specified */
n=(int)(pp-parts+1);
switch(n){
case 0:
return (0); /* initial nondigit */
case 1: /* a -- 32 bits */
break;
case 2: /* a.b -- 8.24 bits */
if(val>0xffffff)
return (0);
val|=parts[0]<<24;
break;
case 3: /* a.b.c -- 8.8.16 bits */
if(val>0xffff)
return (0);
val|=(parts[0]<< 24) | (parts[1]<<16);
break;
case 4: /* a.b.c.d -- 8.8.8.8 bits */
if(val>0xff)
return (0);
val|=(parts[0]<<24) | (parts[1]<<16) | (parts[2]<<8);
break;
}
if(addr)
addr->s_addr=htonl(val);
return (1);
}
/* sends all data - thanks to Beej's Guide to Network Programming */
int sendall(SOCKET s, char *buf, int *len, int timeout){
int total=0;
int bytesleft=*len;
int n;
time_t start_time;
time_t current_time;
int e;
time(&start_time);
while(total<*len){
n=send(s,buf+total,bytesleft,0);
if(n==-1) {
e = WSAGetLastError();
if ((e==EAGAIN) || (e==997L) || (e==996L) || (e==WSAEWOULDBLOCK) || (e==WSAEINTR)
#ifdef WINDOWS_NT
) {
#else
|| ( e==WSA_IO_INCOMPLETE ) || ( e==WSA_IO_PENDING ) ){
#endif
time(¤t_time);
if((current_time-start_time)>timeout) {
n=-20000;
break;
}
continue;
}
if(e > 0 ) { n = -e; }
break;
}
total+=n;
bytesleft-=n;
}
/* return number of bytes actually send here */
*len=total;
/* return -1 on failure, 0 on success */
return ((n<0)?-1:0);
}
/* receives all data - modelled after sendall() */
int recvall(SOCKET s, char *buf, int *len, int timeout){
int total=0;
int bytesleft=*len;
int n;
time_t start_time;
time_t current_time;
int e;
/* clear the receive buffer */
memset(buf,0,*len);
time(&start_time);
/* receive all data */
while(total<*len){
/* receive some data */
n=recv(s,buf+total,bytesleft,0);
if( n == 0 ) { break; }
/* no data has arrived yet (non-blocking socket) */
if(n==-1) {
e = WSAGetLastError();
if ((e==EAGAIN) || (e==997L) || (e==996L) || (e==WSAEWOULDBLOCK) || (e==WSAEINTR)
#ifdef WINDOWS_NT
) {
#else
|| ( e==WSA_IO_INCOMPLETE ) || ( e==WSA_IO_PENDING ) ){
#endif
time(¤t_time);
if((current_time-start_time)>timeout) {
n=-20000; // timeout
break;
}
// sleep(1); // this is windows, we can do ugly busywaits!
continue;
}
if(e > 0 ) { n = -e; }
break;
}
/* apply bytes we received */
total+=n;
bytesleft-=n;
}
/* return number of bytes actually received here */
*len=total;
/* return <=0 on failure, bytes received on success */
return (n<=0)?n:total;
}
| sshipway/nagevlog | nagevlog/nsca-netutils.c | C | gpl-2.0 | 7,084 |
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Opcodes.h"
#include "WorldSession.h"
#include "WorldPacket.h"
void WorldSession::SendAuthResponse(uint8 code, bool queued, uint32 queuePos)
{
QueryResult result = LoginDatabase.PQuery("SELECT class, expansion FROM realm_classes WHERE realmId = %u", realmID);
QueryResult result2 = LoginDatabase.PQuery("SELECT race, expansion FROM realm_races WHERE realmId = %u", realmID);
if (!result || !result2)
{
TC_LOG_ERROR(LOG_FILTER_GENERAL, "Unable to retrieve class or race data.");
return;
}
WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1 + 4 + 1 + 1 + (queued ? 4 : 0));
packet.WriteBit(0);
packet.WriteBit(1);
packet.WriteBit(0);
packet.WriteBit(0);
packet.WriteBits(result2->GetRowCount(), 23);
packet.WriteBit(0);
packet.WriteBits(0, 21);
packet.WriteBits(result->GetRowCount(), 23);
packet.WriteBits(0, 22);
packet.WriteBit(0);
packet.FlushBits();
packet << uint8(0);
do
{
Field* fields = result->Fetch();
packet << fields[1].GetUInt8();
packet << fields[0].GetUInt8();
}while(result->NextRow());
do
{
Field* fields = result2->Fetch();
packet << fields[1].GetUInt8();
packet << fields[0].GetUInt8();
}while(result2->NextRow());
packet << uint32(0);
packet << uint32(0);
packet << uint32(0);
packet << uint8(Expansion());
packet << uint8(Expansion());
packet << uint8(code);
SendPacket(&packet);
}
void WorldSession::SendClientCacheVersion(uint32 version)
{
WorldPacket data(SMSG_CLIENTCACHE_VERSION, 4);
data << uint32(version);
SendPacket(&data);
}
| WOWalmanserver/Mists-Of-Pandaria | src/server/game/Handlers/AuthHandler.cpp | C++ | gpl-2.0 | 2,416 |
// Generated on 02/23/2017 16:53:18
using System;
using System.Collections.Generic;
using System.Linq;
using DarkSoul.Network.Protocol.Types;
using DarkSoul.Network.Protocol.Message;
using DarkSoul.Core.Interfaces;
using DarkSoul.Core.IO;
namespace DarkSoul.Network.Protocol.Messages
{
public class GameActionFightDeathMessage : AbstractGameActionMessage
{
public override ushort Id => 1099;
public double targetId;
public GameActionFightDeathMessage()
{
}
public GameActionFightDeathMessage(ushort actionId, double sourceId, double targetId)
: base(actionId, sourceId)
{
this.targetId = targetId;
}
public override void Serialize(IWriter writer)
{
base.Serialize(writer);
writer.WriteDouble(targetId);
}
public override void Deserialize(IReader reader)
{
base.Deserialize(reader);
targetId = reader.ReadDouble();
}
}
} | LDOpenSource/DarkSoul | DarkSoul.Network/Protocol/Message/Messages/game/actions/fight/GameActionFightDeathMessage.cs | C# | gpl-2.0 | 1,083 |
cmd_/home/yutingkao23/linuxcnc-add-hal-ethercat/src/pluto_step.o := ld -m elf_i386 -r -o /home/yutingkao23/linuxcnc-add-hal-ethercat/src/pluto_step.o /home/yutingkao23/linuxcnc-add-hal-ethercat/src/objects/hal/drivers/pluto_step.o
| CalvinHsu1223/LinuxCNC-EtherCAT-HAL-Driver | src/.pluto_step.o.cmd | Batchfile | gpl-2.0 | 234 |
/**
* @package JCE IFrames
* @copyright Copyright (C) 2005 - 2010 Ryan Demmer. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see licence.txt
* JCE IFrames 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.
*/
.ui-tabs-panel {
height: 200px;
overflow: auto;
}
div.preview {
overflow: hidden;
padding: 6px 0;
margin: 0px;
text-align:left;
height: 150px;
position: relative;
}
#width, #height {
width: 50px;
text-align: center;
}
#constrain {
width: auto;
}
#src, #id, #title, #classlist, #style, #classes, #name {
width: 350px;
}
#margin_top, #margin_right, #margin_bottom, #margin_left {
margin: 0px 5px;
}
#align {
margin-right: 5px;
}
#jce table td {
padding: 3px 2px;
}
#jce.ie div.preview {
padding: 7px 0 7px 0;
}
#jce.ie7 .ui-tabs-panel {
height: 210px;
}
#jce.ie7 div.preview {
padding: 8px 0 10px 0;
}
label[for^="margin_"] {
min-width: 40px;
}
#margin_check + label {
min-width: 40px;
}
| Jak95/www.jak95.ru-joomla | components/com_jce/editor/tiny_mce/plugins/iframe/css/iframe.css | CSS | gpl-2.0 | 1,170 |
/*
* Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.print;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* Class <code>DocFlavor</code> encapsulates an object that specifies the
* format in which print data is supplied to a {@link DocPrintJob}.
* "Doc" is a short, easy-to-pronounce term that means "a piece of print data."
* The print data format, or "doc flavor", consists of two things:
* <UL>
* <LI>
* <B>MIME type.</B> This is a Multipurpose Internet Mail Extensions (MIME)
* media type (as defined in <A HREF="http://www.ietf.org/rfc/rfc2045.txt">RFC
* 2045</A> and <A HREF="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</A>)
* that specifies how the print data is to be interpreted.
* The charset of text data should be the IANA MIME-preferred name, or its
* canonical name if no preferred name is specified. Additionally a few
* historical names supported by earlier versions of the Java platform may
* be recognized.
* See <a href="../../java/lang/package-summary.html#charenc">
* character encodings</a> for more information on the character encodings
* supported on the Java platform.
*
* <LI>
* <B>Representation class name.</B> This specifies the fully-qualified name of
* the class of the object from which the actual print data comes, as returned
* by the {@link java.lang.Class#getName() Class.getName()} method.
* (Thus the class name for <CODE>byte[]</CODE> is <CODE>"[B"</CODE>, for
* <CODE>char[]</CODE> it is <CODE>"[C"</CODE>.)
* </UL>
* <P>
* A <code>DocPrintJob</code> obtains its print data by means of interface
* {@link Doc Doc}. A <code>Doc</code> object lets the <code>DocPrintJob</code>
* determine the doc flavor the client can supply. A <code>Doc</code> object
* also lets the <code>DocPrintJob</code> obtain an instance of the doc flavor's
* representation class, from which the <code>DocPrintJob</code> then obtains
* the actual print data.
*
* <HR>
* <H3>Client Formatted Print Data</H3>
* There are two broad categories of print data, client formatted print data
* and service formatted print data.
* <P>
* For <B>client formatted print data</B>, the client determines or knows the
* print data format.
* For example the client may have a JPEG encoded image, a URL for
* HTML code, or a disk file containing plain text in some encoding,
* possibly obtained from an external source, and
* requires a way to describe the data format to the print service.
* <p>
* The doc flavor's representation class is a conduit for the JPS
* <code>DocPrintJob</code> to obtain a sequence of characters or
* bytes from the client. The
* doc flavor's MIME type is one of the standard media types telling how to
* interpret the sequence of characters or bytes. For a list of standard media
* types, see the Internet Assigned Numbers Authority's (IANA's) <A
* HREF="http://www.iana.org/assignments/media-types/">Media Types
* Directory</A>. Interface {@link Doc Doc} provides two utility operations,
* {@link Doc#getReaderForText() getReaderForText} and
* {@link Doc#getStreamForBytes() getStreamForBytes()}, to help a
* <code>Doc</code> object's client extract client formatted print data.
* <P>
* For client formatted print data, the print data representation class is
* typically one of the following (although other representation classes are
* permitted):
* <UL>
* <LI>
* Character array (<CODE>char[]</CODE>) -- The print data consists of the
* Unicode characters in the array.
*
* <LI>
* <code>String</code> --
* The print data consists of the Unicode characters in the string.
*
* <LI>
* Character stream ({@link java.io.Reader java.io.Reader})
* -- The print data consists of the Unicode characters read from the stream
* up to the end-of-stream.
*
* <LI>
* Byte array (<CODE>byte[]</CODE>) -- The print data consists of the bytes in
* the array. The bytes are encoded in the character set specified by the doc
* flavor's MIME type. If the MIME type does not specify a character set, the
* default character set is US-ASCII.
*
* <LI>
* Byte stream ({@link java.io.InputStream java.io.InputStream}) --
* The print data consists of the bytes read from the stream up to the
* end-of-stream. The bytes are encoded in the character set specified by the
* doc flavor's MIME type. If the MIME type does not specify a character set,
* the default character set is US-ASCII.
* <LI>
* Uniform Resource Locator ({@link java.net.URL URL})
* -- The print data consists of the bytes read from the URL location.
* The bytes are encoded in the character set specified by the doc flavor's
* MIME type. If the MIME type does not specify a character set, the default
* character set is US-ASCII.
* <P>
* When the representation class is a URL, the print service itself accesses
* and downloads the document directly from its URL address, without involving
* the client. The service may be some form of network print service which
* is executing in a different environment.
* This means you should not use a URL print data flavor to print a
* document at a restricted URL that the client can see but the printer cannot
* see. This also means you should not use a URL print data flavor to print a
* document stored in a local file that is not available at a URL
* accessible independently of the client.
* For example, a file that is not served up by an HTTP server or FTP server.
* To print such documents, let the client open an input stream on the URL
* or file and use an input stream data flavor.
* </UL>
*
* <HR>
* <h3>Default and Platform Encodings</h3>
* <P>
* For byte print data where the doc flavor's MIME type does not include a
* <CODE>charset</CODE> parameter, the Java Print Service instance assumes the
* US-ASCII character set by default. This is in accordance with
* <A HREF="http://www.ietf.org/rfc/rfc2046.txt">RFC 2046</A>, which says the
* default character set is US-ASCII. Note that US-ASCII is a subset of
* UTF-8, so in the future this may be widened if a future RFC endorses
* UTF-8 as the default in a compatible manner.
* <p>
* Also note that this is different than the behaviour of the Java runtime
* when interpreting a stream of bytes as text data. That assumes the
* default encoding for the user's locale. Thus, when spooling a file in local
* encoding to a Java Print Service it is important to correctly specify
* the encoding. Developers working in the English locales should
* be particularly conscious of this, as their platform encoding corresponds
* to the default mime charset. By this coincidence that particular
* case may work without specifying the encoding of platform data.
* <p>
* Every instance of the Java virtual machine has a default character encoding
* determined during virtual-machine startup and typically depends upon the
* locale and charset being used by the underlying operating system.
* In a distributed environment there is no guarantee that two VM share
* the same default encoding. Thus clients which want to stream platform
* encoded text data from the host platform to a Java Print Service instance
* must explicitly declare the charset and not rely on defaults.
* <p>
* The preferred form is the official IANA primary name for an encoding.
* Applications which stream text data should always specify the charset
* in the mime type, which necessitates obtaining the encoding of the host
* platform for data (eg files) stored in that platform's encoding.
* A CharSet which corresponds to this and is suitable for use in a
* mime-type for a DocFlavor can be obtained
* from {@link DocFlavor#hostEncoding DocFlavor.hostEncoding}
* This may not always be the primary IANA name but is guaranteed to be
* understood by this VM.
* For common flavors, the pre-defined *HOST DocFlavors may be used.
* <p>
* See <a href="../../java/lang/package-summary.html#charenc">
* character encodings</a> for more information on the character encodings
* supported on the Java platform.
* <HR>
* <h3>Recommended DocFlavors</h3>
* <P>
* The Java Print Service API does not define any mandatorily supported
* DocFlavors.
* However, here are some examples of MIME types that a Java Print Service
* instance might support for client formatted print data.
* Nested classes inside class DocFlavor declare predefined static
* constant DocFlavor objects for these example doc flavors; class DocFlavor's
* constructor can be used to create an arbitrary doc flavor.
* <UL>
* <LI>Preformatted text
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
* <TR>
* <TD><CODE>"text/plain"</CODE></TD>
* <TD>Plain text in the default character set (US-ASCII)</TD>
* </TR>
* <TR>
* <TD><CODE>"text/plain; charset=<I>xxx</I>"</CODE></TD>
* <TD>Plain text in character set <I>xxx</I></TD>
* </TR>
* <TR>
* <TD><CODE>"text/html"</CODE></TD>
* <TD>HyperText Markup Language in the default character set (US-ASCII)</TD>
* </TR>
* <TR>
* <TD><CODE>"text/html; charset=<I>xxx</I>"</CODE></TD>
* <TD>HyperText Markup Language in character set <I>xxx</I></TD>
* </TR>
* </TABLE>
* <P>
* In general, preformatted text print data is provided either in a character
* oriented representation class (character array, String, Reader) or in a
* byte oriented representation class (byte array, InputStream, URL).
*
* <LI>Preformatted page description language (PDL) documents
*
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
*<TR>
* <TD><CODE>"application/pdf"</CODE></TD>
* <TD>Portable Document Format document</TD>
* </TR>
* <TR>
* <TD><CODE>"application/postscript"</CODE></TD>
* <TD>PostScript document</TD>
* </TR>
* <TR>
* <TD><CODE>"application/vnd.hp-PCL"</CODE></TD>
* <TD>Printer Control Language document</TD>
* </TR>
* </TABLE>
* <P>
* In general, preformatted PDL print data is provided in a byte oriented
* representation class (byte array, InputStream, URL).
*
* <LI>Preformatted images
*
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
*
* <TR>
* <TD><CODE>"image/gif"</CODE></TD>
* <TD>Graphics Interchange Format image</TD>
* </TR>
* <TR>
* <TD><CODE>"image/jpeg"</CODE></TD>
* <TD>Joint Photographic Experts Group image</TD>
* </TR>
* <TR>
* <TD><CODE>"image/png"</CODE></TD>
* <TD>Portable Network Graphics image</TD>
* </TR>
* </TABLE>
* <P>
* In general, preformatted image print data is provided in a byte oriented
* representation class (byte array, InputStream, URL).
*
* <LI>Preformatted autosense print data
*
* <TABLE BORDER=1 CELLPADDING=0 CELLSPACING=0 SUMMARY="MIME-Types and their descriptions">
* <TR>
* <TH>MIME-Type</TH><TH>Description</TH>
* </TR>
*
* <TR>
* <TD><CODE>"application/octet-stream"</CODE></TD>
* <TD>The print data format is unspecified (just an octet stream)</TD>
* </TABLE>
* <P>
* The printer decides how to interpret the print data; the way this
* "autosensing" works is implementation dependent. In general, preformatted
* autosense print data is provided in a byte oriented representation class
* (byte array, InputStream, URL).
* </UL>
*
* <HR>
* <H3>Service Formatted Print Data</H3>
* <P>
* For <B>service formatted print data</B>, the Java Print Service instance
* determines the print data format. The doc flavor's representation class
* denotes an interface whose methods the <code>DocPrintJob</code> invokes to
* determine the content to be printed -- such as a renderable image
* interface or a Java printable interface.
* The doc flavor's MIME type is the special value
* <CODE>"application/x-java-jvm-local-objectref"</CODE> indicating the client
* will supply a reference to a Java object that implements the interface
* named as the representation class.
* This MIME type is just a placeholder; what's
* important is the print data representation class.
* <P>
* For service formatted print data, the print data representation class is
* typically one of the following (although other representation classes are
* permitted). Nested classes inside class DocFlavor declare predefined static
* constant DocFlavor objects for these example doc flavors; class DocFlavor's
* constructor can be used to create an arbitrary doc flavor.
* <UL>
* <LI>
* Renderable image object -- The client supplies an object that implements
* interface
* {@link java.awt.image.renderable.RenderableImage RenderableImage}. The
* printer calls methods
* in that interface to obtain the image to be printed.
*
* <LI>
* Printable object -- The client supplies an object that implements interface
* {@link java.awt.print.Printable Printable}.
* The printer calls methods in that interface to obtain the pages to be
* printed, one by one.
* For each page, the printer supplies a graphics context, and whatever the
* client draws in that graphics context gets printed.
*
* <LI>
* Pageable object -- The client supplies an object that implements interface
* {@link java.awt.print.Pageable Pageable}. The printer calls
* methods in that interface to obtain the pages to be printed, one by one.
* For each page, the printer supplies a graphics context, and whatever
* the client draws in that graphics context gets printed.
* </UL>
*
* <HR>
*
* <HR>
* <H3>Pre-defined Doc Flavors</H3>
* A Java Print Service instance is not <B><I>required</I></B> to support the
* following print data formats and print data representation classes. In
* fact, a developer using this class should <b>never</b> assume that a
* particular print service supports the document types corresponding to
* these pre-defined doc flavors. Always query the print service
* to determine what doc flavors it supports. However,
* developers who have print services that support these doc flavors are
* encouraged to refer to the predefined singleton instances created here.
* <UL>
* <LI>
* Plain text print data provided through a byte stream. Specifically, the
* following doc flavors are recommended to be supported:
* <BR>·
* <CODE>("text/plain", "java.io.InputStream")</CODE>
* <BR>·
* <CODE>("text/plain; charset=us-ascii", "java.io.InputStream")</CODE>
* <BR>·
* <CODE>("text/plain; charset=utf-8", "java.io.InputStream")</CODE>
*
* <LI>
* Renderable image objects. Specifically, the following doc flavor is
* recommended to be supported:
* <BR>·
* <CODE>("application/x-java-jvm-local-objectref", "java.awt.image.renderable.RenderableImage")</CODE>
* </UL>
* <P>
* A Java Print Service instance is allowed to support any other doc flavors
* (or none) in addition to the above mandatory ones, at the implementation's
* choice.
* <P>
* Support for the above doc flavors is desirable so a printing client can rely
* on being able to print on any JPS printer, regardless of which doc flavors
* the printer supports. If the printer doesn't support the client's preferred
* doc flavor, the client can at least print plain text, or the client can
* convert its data to a renderable image and print the image.
* <P>
* Furthermore, every Java Print Service instance must fulfill these
* requirements for processing plain text print data:
* <UL>
* <LI>
* The character pair carriage return-line feed (CR-LF) means
* "go to column 1 of the next line."
* <LI>
* A carriage return (CR) character standing by itself means
* "go to column 1 of the next line."
* <LI>
* A line feed (LF) character standing by itself means
* "go to column 1 of the next line."
* <LI>
* </UL>
* <P>
* The client must itself perform all plain text print data formatting not
* addressed by the above requirements.
*
* <H3>Design Rationale</H3>
* <P>
* Class DocFlavor in package javax.print.data is similar to class
* {@link java.awt.datatransfer.DataFlavor DataFlavor}. Class
* <code>DataFlavor</code>
* is not used in the Java Print Service (JPS) API
* for three reasons which are all rooted in allowing the JPS API to be
* shared by other print services APIs which may need to run on Java profiles
* which do not include all of the Java Platform, Standard Edition.
* <OL TYPE=1>
* <LI>
* The JPS API is designed to be used in Java profiles which do not support
* AWT.
*
* <LI>
* The implementation of class <code>java.awt.datatransfer.DataFlavor</code>
* does not guarantee that equivalent data flavors will have the same
* serialized representation. DocFlavor does, and can be used in services
* which need this.
*
* <LI>
* The implementation of class <code>java.awt.datatransfer.DataFlavor</code>
* includes a human presentable name as part of the serialized representation.
* This is not appropriate as part of a service matching constraint.
* </OL>
* <P>
* Class DocFlavor's serialized representation uses the following
* canonical form of a MIME type string. Thus, two doc flavors with MIME types
* that are not identical but that are equivalent (that have the same
* canonical form) may be considered equal.
* <UL>
* <LI> The media type, media subtype, and parameters are retained, but all
* comments and whitespace characters are discarded.
* <LI> The media type, media subtype, and parameter names are converted to
* lowercase.
* <LI> The parameter values retain their original case, except a charset
* parameter value for a text media type is converted to lowercase.
* <LI> Quote characters surrounding parameter values are removed.
* <LI> Quoting backslash characters inside parameter values are removed.
* <LI> The parameters are arranged in ascending order of parameter name.
* </UL>
* <P>
* Class DocFlavor's serialized representation also contains the
* fully-qualified class <I>name</I> of the representation class
* (a String object), rather than the representation class itself
* (a Class object). This allows a client to examine the doc flavors a
* Java Print Service instance supports without having
* to load the representation classes, which may be problematic for
* limited-resource clients.
* <P>
*
* @author Alan Kaminsky
*/
public class DocFlavor implements Serializable, Cloneable {
private static final long serialVersionUID = -4512080796965449721L;
/**
* A String representing the host operating system encoding.
* This will follow the conventions documented in
* <a href="http://www.ietf.org/rfc/rfc2278.txt">
* <i>RFC 2278: IANA Charset Registration Procedures</i></a>
* except where historical names are returned for compatibility with
* previous versions of the Java platform.
* The value returned from method is valid only for the VM which
* returns it, for use in a DocFlavor.
* This is the charset for all the "HOST" pre-defined DocFlavors in
* the executing VM.
*/
public static final String hostEncoding;
static {
hostEncoding =
java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("file.encoding"));
}
/**
* MIME type.
*/
private transient MimeType myMimeType;
/**
* Representation class name.
* @serial
*/
private String myClassName;
/**
* String value for this doc flavor. Computed when needed and cached.
*/
private transient String myStringValue = null;
/**
* Constructs a new doc flavor object from the given MIME type and
* representation class name. The given MIME type is converted into
* canonical form and stored internally.
*
* @param mimeType MIME media type string.
* @param className Fully-qualified representation class name.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null or
* <CODE>className</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public DocFlavor(String mimeType, String className) {
if (className == null) {
throw new NullPointerException();
}
myMimeType = new MimeType (mimeType);
myClassName = className;
}
/**
* Returns this doc flavor object's MIME type string based on the
* canonical form. Each parameter value is enclosed in quotes.
* @return the mime type
*/
public String getMimeType() {
return myMimeType.getMimeType();
}
/**
* Returns this doc flavor object's media type (from the MIME type).
* @return the media type
*/
public String getMediaType() {
return myMimeType.getMediaType();
}
/**
* Returns this doc flavor object's media subtype (from the MIME type).
* @return the media sub-type
*/
public String getMediaSubtype() {
return myMimeType.getMediaSubtype();
}
/**
* Returns a <code>String</code> representing a MIME
* parameter.
* Mime types may include parameters which are usually optional.
* The charset for text types is a commonly useful example.
* This convenience method will return the value of the specified
* parameter if one was specified in the mime type for this flavor.
* <p>
* @param paramName the name of the paramater. This name is internally
* converted to the canonical lower case format before performing
* the match.
* @return String representing a mime parameter, or
* null if that parameter is not in the mime type string.
* @exception NullPointerException if paramName is null.
*/
public String getParameter(String paramName) {
return myMimeType.getParameterMap().get(paramName.toLowerCase());
}
/**
* Returns the name of this doc flavor object's representation class.
* @return the name of the representation class.
*/
public String getRepresentationClassName() {
return myClassName;
}
/**
* Converts this <code>DocFlavor</code> to a string.
*
* @return MIME type string based on the canonical form. Each parameter
* value is enclosed in quotes.
* A "class=" parameter is appended to the
* MIME type string to indicate the representation class name.
*/
public String toString() {
return getStringValue();
}
/**
* Returns a hash code for this doc flavor object.
*/
public int hashCode() {
return getStringValue().hashCode();
}
/**
* Determines if this doc flavor object is equal to the given object.
* The two are equal if the given object is not null, is an instance
* of <code>DocFlavor</code>, has a MIME type equivalent to this doc
* flavor object's MIME type (that is, the MIME types have the same media
* type, media subtype, and parameters), and has the same representation
* class name as this doc flavor object. Thus, if two doc flavor objects'
* MIME types are the same except for comments, they are considered equal.
* However, two doc flavor objects with MIME types of "text/plain" and
* "text/plain; charset=US-ASCII" are not considered equal, even though
* they represent the same media type (because the default character
* set for plain text is US-ASCII).
*
* @param obj Object to test.
*
* @return True if this doc flavor object equals <CODE>obj</CODE>, false
* otherwise.
*/
public boolean equals(Object obj) {
return
obj != null &&
obj instanceof DocFlavor &&
getStringValue().equals (((DocFlavor) obj).getStringValue());
}
/**
* Returns this doc flavor object's string value.
*/
private String getStringValue() {
if (myStringValue == null) {
myStringValue = myMimeType + "; class=\"" + myClassName + "\"";
}
return myStringValue;
}
/**
* Write the instance to a stream (ie serialize the object).
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeObject(myMimeType.getMimeType());
}
/**
* Reconstitute an instance from a stream (that is, deserialize it).
*
* @serialData
* The serialised form of a DocFlavor is the String naming the
* representation class followed by the String representing the canonical
* form of the mime type.
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
myMimeType = new MimeType((String)s.readObject());
}
/**
* Class DocFlavor.BYTE_ARRAY provides predefined static constant
* DocFlavor objects for example doc flavors using a byte array
* (<CODE>byte[]</CODE>) as the print data representation class.
* <P>
*
* @author Alan Kaminsky
*/
public static class BYTE_ARRAY extends DocFlavor {
private static final long serialVersionUID = -9065578006593857475L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of <CODE>"[B"</CODE> (byte array).
*
* @param mimeType MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public BYTE_ARRAY (String mimeType) {
super (mimeType, "[B");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_HOST =
new BYTE_ARRAY ("text/plain; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-8"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_8 =
new BYTE_ARRAY ("text/plain; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_16 =
new BYTE_ARRAY ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_16BE =
new BYTE_ARRAY ("text/plain; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_UTF_16LE =
new BYTE_ARRAY ("text/plain; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_PLAIN_US_ASCII =
new BYTE_ARRAY ("text/plain; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"text/html"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_HTML_HOST =
new BYTE_ARRAY ("text/html; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-8"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_8 =
new BYTE_ARRAY ("text/html; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_16 =
new BYTE_ARRAY ("text/html; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_16BE =
new BYTE_ARRAY ("text/html; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY TEXT_HTML_UTF_16LE =
new BYTE_ARRAY ("text/html; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY TEXT_HTML_US_ASCII =
new BYTE_ARRAY ("text/html; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"application/pdf"</CODE>, print
* data representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY PDF = new BYTE_ARRAY ("application/pdf");
/**
* Doc flavor with MIME type = <CODE>"application/postscript"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY POSTSCRIPT =
new BYTE_ARRAY ("application/postscript");
/**
* Doc flavor with MIME type = <CODE>"application/vnd.hp-PCL"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array).
*/
public static final BYTE_ARRAY PCL =
new BYTE_ARRAY ("application/vnd.hp-PCL");
/**
* Doc flavor with MIME type = <CODE>"image/gif"</CODE>, print data
* representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY GIF = new BYTE_ARRAY ("image/gif");
/**
* Doc flavor with MIME type = <CODE>"image/jpeg"</CODE>, print data
* representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY JPEG = new BYTE_ARRAY ("image/jpeg");
/**
* Doc flavor with MIME type = <CODE>"image/png"</CODE>, print data
* representation class name = <CODE>"[B"</CODE> (byte array).
*/
public static final BYTE_ARRAY PNG = new BYTE_ARRAY ("image/png");
/**
* Doc flavor with MIME type =
* <CODE>"application/octet-stream"</CODE>,
* print data representation class name = <CODE>"[B"</CODE> (byte
* array). The client must determine that data described
* using this DocFlavor is valid for the printer.
*/
public static final BYTE_ARRAY AUTOSENSE =
new BYTE_ARRAY ("application/octet-stream");
}
/**
* Class DocFlavor.INPUT_STREAM provides predefined static constant
* DocFlavor objects for example doc flavors using a byte stream ({@link
* java.io.InputStream java.io.InputStream}) as the print
* data representation class.
* <P>
*
* @author Alan Kaminsky
*/
public static class INPUT_STREAM extends DocFlavor {
private static final long serialVersionUID = -7045842700749194127L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*
* @param mimeType MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public INPUT_STREAM (String mimeType) {
super (mimeType, "java.io.InputStream");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_HOST =
new INPUT_STREAM ("text/plain; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_8 =
new INPUT_STREAM ("text/plain; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_16 =
new INPUT_STREAM ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_16BE =
new INPUT_STREAM ("text/plain; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_UTF_16LE =
new INPUT_STREAM ("text/plain; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_PLAIN_US_ASCII =
new INPUT_STREAM ("text/plain; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"text/html"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_HOST =
new INPUT_STREAM ("text/html; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_8 =
new INPUT_STREAM ("text/html; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_16 =
new INPUT_STREAM ("text/html; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_16BE =
new INPUT_STREAM ("text/html; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_UTF_16LE =
new INPUT_STREAM ("text/html; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM TEXT_HTML_US_ASCII =
new INPUT_STREAM ("text/html; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"application/pdf"</CODE>, print
* data representation class name = <CODE>"java.io.InputStream"</CODE>
* (byte stream).
*/
public static final INPUT_STREAM PDF = new INPUT_STREAM ("application/pdf");
/**
* Doc flavor with MIME type = <CODE>"application/postscript"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM POSTSCRIPT =
new INPUT_STREAM ("application/postscript");
/**
* Doc flavor with MIME type = <CODE>"application/vnd.hp-PCL"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM PCL =
new INPUT_STREAM ("application/vnd.hp-PCL");
/**
* Doc flavor with MIME type = <CODE>"image/gif"</CODE>, print data
* representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM GIF = new INPUT_STREAM ("image/gif");
/**
* Doc flavor with MIME type = <CODE>"image/jpeg"</CODE>, print data
* representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM JPEG = new INPUT_STREAM ("image/jpeg");
/**
* Doc flavor with MIME type = <CODE>"image/png"</CODE>, print data
* representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
*/
public static final INPUT_STREAM PNG = new INPUT_STREAM ("image/png");
/**
* Doc flavor with MIME type =
* <CODE>"application/octet-stream"</CODE>,
* print data representation class name =
* <CODE>"java.io.InputStream"</CODE> (byte stream).
* The client must determine that data described
* using this DocFlavor is valid for the printer.
*/
public static final INPUT_STREAM AUTOSENSE =
new INPUT_STREAM ("application/octet-stream");
}
/**
* Class DocFlavor.URL provides predefined static constant DocFlavor
* objects.
* For example doc flavors using a Uniform Resource Locator ({@link
* java.net.URL java.net.URL}) as the print data
* representation class.
* <P>
*
* @author Alan Kaminsky
*/
public static class URL extends DocFlavor {
private static final long serialVersionUID = 2936725788144902062L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of <CODE>"java.net.URL"</CODE>.
*
* @param mimeType MIME media type string.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public URL (String mimeType) {
super (mimeType, "java.net.URL");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_HOST =
new URL ("text/plain; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_8 =
new URL ("text/plain; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>java.net.URL""</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_16 =
new URL ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_16BE =
new URL ("text/plain; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_UTF_16LE =
new URL ("text/plain; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/plain; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_PLAIN_US_ASCII =
new URL ("text/plain; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"text/html"</CODE>,
* encoded in the host platform encoding.
* See {@link DocFlavor#hostEncoding hostEncoding}
* Print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_HOST =
new URL ("text/html; charset="+hostEncoding);
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-8"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_8 =
new URL ("text/html; charset=utf-8");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_16 =
new URL ("text/html; charset=utf-16");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16be"</CODE>
* (big-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_16BE =
new URL ("text/html; charset=utf-16be");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=utf-16le"</CODE>
* (little-endian byte ordering),
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_UTF_16LE =
new URL ("text/html; charset=utf-16le");
/**
* Doc flavor with MIME type =
* <CODE>"text/html; charset=us-ascii"</CODE>,
* print data representation class name =
* <CODE>"java.net.URL"</CODE> (byte stream).
*/
public static final URL TEXT_HTML_US_ASCII =
new URL ("text/html; charset=us-ascii");
/**
* Doc flavor with MIME type = <CODE>"application/pdf"</CODE>, print
* data representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL PDF = new URL ("application/pdf");
/**
* Doc flavor with MIME type = <CODE>"application/postscript"</CODE>,
* print data representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL POSTSCRIPT = new URL ("application/postscript");
/**
* Doc flavor with MIME type = <CODE>"application/vnd.hp-PCL"</CODE>,
* print data representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL PCL = new URL ("application/vnd.hp-PCL");
/**
* Doc flavor with MIME type = <CODE>"image/gif"</CODE>, print data
* representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL GIF = new URL ("image/gif");
/**
* Doc flavor with MIME type = <CODE>"image/jpeg"</CODE>, print data
* representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL JPEG = new URL ("image/jpeg");
/**
* Doc flavor with MIME type = <CODE>"image/png"</CODE>, print data
* representation class name = <CODE>"java.net.URL"</CODE>.
*/
public static final URL PNG = new URL ("image/png");
/**
* Doc flavor with MIME type =
* <CODE>"application/octet-stream"</CODE>,
* print data representation class name = <CODE>"java.net.URL"</CODE>.
* The client must determine that data described
* using this DocFlavor is valid for the printer.
*/
public static final URL AUTOSENSE = new URL ("application/octet-stream");
}
/**
* Class DocFlavor.CHAR_ARRAY provides predefined static constant
* DocFlavor objects for example doc flavors using a character array
* (<CODE>char[]</CODE>) as the print data representation class. As such,
* the character set is Unicode.
* <P>
*
* @author Alan Kaminsky
*/
public static class CHAR_ARRAY extends DocFlavor {
private static final long serialVersionUID = -8720590903724405128L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of
* <CODE>"[C"</CODE> (character array).
*
* @param mimeType MIME media type string. If it is a text media
* type, it is assumed to contain a
* <CODE>"charset=utf-16"</CODE> parameter.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public CHAR_ARRAY (String mimeType) {
super (mimeType, "[C");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"[C"</CODE> (character array).
*/
public static final CHAR_ARRAY TEXT_PLAIN =
new CHAR_ARRAY ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type = <CODE>"text/html;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"[C"</CODE> (character array).
*/
public static final CHAR_ARRAY TEXT_HTML =
new CHAR_ARRAY ("text/html; charset=utf-16");
}
/**
* Class DocFlavor.STRING provides predefined static constant DocFlavor
* objects for example doc flavors using a string ({@link java.lang.String
* java.lang.String}) as the print data representation class.
* As such, the character set is Unicode.
* <P>
*
* @author Alan Kaminsky
*/
public static class STRING extends DocFlavor {
private static final long serialVersionUID = 4414407504887034035L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of <CODE>"java.lang.String"</CODE>.
*
* @param mimeType MIME media type string. If it is a text media
* type, it is assumed to contain a
* <CODE>"charset=utf-16"</CODE> parameter.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public STRING (String mimeType) {
super (mimeType, "java.lang.String");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.lang.String"</CODE>.
*/
public static final STRING TEXT_PLAIN =
new STRING ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type = <CODE>"text/html;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.lang.String"</CODE>.
*/
public static final STRING TEXT_HTML =
new STRING ("text/html; charset=utf-16");
}
/**
* Class DocFlavor.READER provides predefined static constant DocFlavor
* objects for example doc flavors using a character stream ({@link
* java.io.Reader java.io.Reader}) as the print data
* representation class. As such, the character set is Unicode.
* <P>
*
* @author Alan Kaminsky
*/
public static class READER extends DocFlavor {
private static final long serialVersionUID = 7100295812579351567L;
/**
* Constructs a new doc flavor with the given MIME type and a print
* data representation class name of\
* <CODE>"java.io.Reader"</CODE> (character stream).
*
* @param mimeType MIME media type string. If it is a text media
* type, it is assumed to contain a
* <CODE>"charset=utf-16"</CODE> parameter.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> is null.
* @exception IllegalArgumentException
* (unchecked exception) Thrown if <CODE>mimeType</CODE> does not
* obey the syntax for a MIME media type string.
*/
public READER (String mimeType) {
super (mimeType, "java.io.Reader");
}
/**
* Doc flavor with MIME type = <CODE>"text/plain;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.io.Reader"</CODE> (character stream).
*/
public static final READER TEXT_PLAIN =
new READER ("text/plain; charset=utf-16");
/**
* Doc flavor with MIME type = <CODE>"text/html;
* charset=utf-16"</CODE>, print data representation class name =
* <CODE>"java.io.Reader"</CODE> (character stream).
*/
public static final READER TEXT_HTML =
new READER ("text/html; charset=utf-16");
}
/**
* Class DocFlavor.SERVICE_FORMATTED provides predefined static constant
* DocFlavor objects for example doc flavors for service formatted print
* data.
* <P>
*
* @author Alan Kaminsky
*/
public static class SERVICE_FORMATTED extends DocFlavor {
private static final long serialVersionUID = 6181337766266637256L;
/**
* Constructs a new doc flavor with a MIME type of
* <CODE>"application/x-java-jvm-local-objectref"</CODE> indicating
* service formatted print data and the given print data
* representation class name.
*
* @param className Fully-qualified representation class name.
*
* @exception NullPointerException
* (unchecked exception) Thrown if <CODE>className</CODE> is
* null.
*/
public SERVICE_FORMATTED (String className) {
super ("application/x-java-jvm-local-objectref", className);
}
/**
* Service formatted print data doc flavor with print data
* representation class name =
* <CODE>"java.awt.image.renderable.RenderableImage"</CODE>
* (renderable image object).
*/
public static final SERVICE_FORMATTED RENDERABLE_IMAGE =
new SERVICE_FORMATTED("java.awt.image.renderable.RenderableImage");
/**
* Service formatted print data doc flavor with print data
* representation class name = <CODE>"java.awt.print.Printable"</CODE>
* (printable object).
*/
public static final SERVICE_FORMATTED PRINTABLE =
new SERVICE_FORMATTED ("java.awt.print.Printable");
/**
* Service formatted print data doc flavor with print data
* representation class name = <CODE>"java.awt.print.Pageable"</CODE>
* (pageable object).
*/
public static final SERVICE_FORMATTED PAGEABLE =
new SERVICE_FORMATTED ("java.awt.print.Pageable");
}
}
| isaacl/openjdk-jdk | src/share/classes/javax/print/DocFlavor.java | Java | gpl-2.0 | 56,612 |
#!/usr/bin/env python3
# Copyright (c) 2008-9 Qtrac Ltd. All rights reserved.
# This program or module 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
# version 3 of the License, or (at your option) any later version. It is
# provided for educational purposes and 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.
from PyQt4.QtCore import (QDate, QString, Qt, SIGNAL, pyqtSignature)
from PyQt4.QtGui import (QApplication, QDialog, QDialogButtonBox)
import moviedata_ans as moviedata
import ui_addeditmoviedlg_ans as ui_addeditmoviedlg
class AddEditMovieDlg(QDialog,
ui_addeditmoviedlg.Ui_AddEditMovieDlg):
def __init__(self, movies, movie=None, parent=None):
super(AddEditMovieDlg, self).__init__(parent)
self.setupUi(self)
self.movies = movies
self.movie = movie
self.acquiredDateEdit.setDisplayFormat(moviedata.DATEFORMAT)
if movie is not None:
self.titleLineEdit.setText(movie.title)
self.yearSpinBox.setValue(movie.year)
self.minutesSpinBox.setValue(movie.minutes)
self.acquiredDateEdit.setDate(movie.acquired)
self.acquiredDateEdit.setEnabled(False)
self.locationLineEdit.setText(movie.location)
self.notesTextEdit.setPlainText(movie.notes)
self.notesTextEdit.setFocus()
self.buttonBox.button(QDialogButtonBox.Ok).setText(
"&Accept")
self.setWindowTitle("My Movies - Edit Movie")
else:
today = QDate.currentDate()
self.acquiredDateEdit.setDateRange(today.addDays(-5),
today)
self.acquiredDateEdit.setDate(today)
self.titleLineEdit.setFocus()
self.on_titleLineEdit_textEdited(QString())
@pyqtSignature("QString")
def on_titleLineEdit_textEdited(self, text):
self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(
not self.titleLineEdit.text().isEmpty())
def accept(self):
title = self.titleLineEdit.text()
year = self.yearSpinBox.value()
minutes = self.minutesSpinBox.value()
location = self.locationLineEdit.text()
notes = self.notesTextEdit.toPlainText()
if self.movie is None:
acquired = self.acquiredDateEdit.date()
self.movie = moviedata.Movie(title, year, minutes,
acquired, location, notes)
self.movies.add(self.movie)
else:
self.movies.updateMovie(self.movie, title, year,
minutes, location, notes)
QDialog.accept(self)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
form = AddEditMovieDlg(0)
form.show()
app.exec_()
| paradiseOffice/Bash_and_Cplus-plus | CPP/full_examples/pyqt/chap08/addeditmoviedlg_ans.py | Python | gpl-2.0 | 3,155 |
/*
* XBMC Media Center
* Copyright (c) 2002 d7o3g4q and RUNTiME
* Portions Copyright (c) by the authors of ffmpeg and xvid
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
// AsyncAudioRenderer.h: interface for the CAsyncDirectSound class.
//
//////////////////////////////////////////////////////////////////////
#ifndef __ALSA_DIRECT_SOUND_H__
#define __ALSA_DIRECT_SOUND_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "IAudioRenderer.h"
#include "cores/IAudioCallback.h"
#define ALSA_PCM_NEW_HW_PARAMS_API
#include <alsa/asoundlib.h>
#include "../../utils/PCMAmplifier.h"
extern void RegisterAudioCallback(IAudioCallback* pCallback);
extern void UnRegisterAudioCallback();
class CALSADirectSound : public IAudioRenderer
{
public:
virtual void UnRegisterAudioCallback();
virtual void RegisterAudioCallback(IAudioCallback* pCallback);
virtual unsigned int GetChunkLen();
virtual float GetDelay();
virtual float GetCacheTime();
virtual float GetCacheTotal();
CALSADirectSound();
virtual bool Initialize(IAudioCallback* pCallback, const CStdString& device, int iChannels, enum PCMChannels *channelMap, unsigned int uiSamplesPerSec, unsigned int uiBitsPerSample, bool bResample, bool bIsMusic=false, bool bPassthrough = false);
virtual ~CALSADirectSound();
virtual unsigned int AddPackets(const void* data, unsigned int len);
virtual unsigned int GetSpace();
virtual bool Deinitialize();
virtual bool Pause();
virtual bool Stop();
virtual bool Resume();
virtual long GetCurrentVolume() const;
virtual void Mute(bool bMute);
virtual bool SetCurrentVolume(long nVolume);
virtual void SetDynamicRangeCompression(long drc) { m_drc = drc; }
virtual int SetPlaySpeed(int iSpeed);
virtual void WaitCompletion();
virtual void SwitchChannels(int iAudioStream, bool bAudioOnAllSpeakers);
virtual void Flush();
static void EnumerateAudioSinks(AudioSinkList& vAudioSinks, bool passthrough);
private:
unsigned int GetSpaceFrames();
static bool SoundDeviceExists(const CStdString& device);
static void GenSoundLabel(AudioSinkList& vAudioSinks, CStdString sink, CStdString card, CStdString readableCard);
snd_pcm_t *m_pPlayHandle;
IAudioCallback* m_pCallback;
CPCMAmplifier m_amp;
long m_nCurrentVolume;
long m_drc;
snd_pcm_uframes_t m_dwFrameCount;
snd_pcm_uframes_t m_uiBufferSize;
unsigned int m_dwNumPackets;
bool m_bPause;
bool m_bIsAllocated;
bool m_bCanPause;
unsigned int m_uiSamplesPerSec;
unsigned int m_uiBitsPerSample;
unsigned int m_uiDataChannels;
unsigned int m_uiChannels;
bool m_bPassthrough;
};
#endif
| robclark/xbmc | xbmc/cores/AudioRenderers/ALSADirectSound.h | C | gpl-2.0 | 3,278 |
# ------------------------------------------------------------------------------
# Copyright (c) 2019 SUSE LLC, All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of version 2 of the GNU General Public License as published by the
# Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# ------------------------------------------------------------------------------
require "etc"
require "solv"
require "yast"
module Y2Packager
# This is a wrapper for the Solv::Pool class
class SolvablePool
include Yast::Logger
def initialize
@pool = Solv::Pool.new
@pool.setarch(arch)
end
#
# Load repository metadata to the pool.
#
# @param primary_xml [String] Path to the primary.xml.gz file
# @param name [String] Name of the repository
def add_rpmmd_repo(primary_xml, name)
repo = pool.add_repo(name)
File.open(primary_xml) do |gz|
fd = Solv.xfopen_fd(primary_xml, gz.fileno)
repo.add_rpmmd(fd, nil, 0)
end
pool.createwhatprovides
end
attr_reader :pool
private
# detect the system architecture
# @return [String] the machine architecture, equivalent to "uname -m"
def arch
# get the machine architecture name ("uname -m")
arch = Etc.uname[:machine]
log.info "Detected system architecture: #{arch}"
# use "armv7hl" packages on "armv7l" (bsc#1183795)
if arch == "armv7l"
arch = "armv7hl"
log.info "Using #{arch} package architecture"
end
arch
end
end
end
| yast/yast-packager | src/lib/y2packager/solvable_pool.rb | Ruby | gpl-2.0 | 1,809 |
/**
* Compiles LESS files into CSS.
*
* ---------------------------------------------------------------
*
* Only the `assets/styles/importer.less` is compiled.
* This allows you to control the ordering yourself, i.e. import your
* dependencies, mixins, variables, resets, etc. before other stylesheets)
*
* For usage docs see:
* https://github.com/gruntjs/grunt-contrib-less
*/
module.exports = function(grunt) {
grunt.config.set('less', {
dev: {
files: [/*{
expand: true,
cwd: 'assets/styles/',
src: ['importer.less'],
dest: '.tmp/public/styles/',
ext: '.css'
},*/
{
expand: true,
cwd: 'assets/styles/dashboard/',
src: ['dashboard.less'],
dest: '.tmp/public/styles/dashboard/',
ext: '.css'
}]
}
});
grunt.loadNpmTasks('grunt-contrib-less');
};
| Theadd/on-black-sails | tasks/config/less.js | JavaScript | gpl-2.0 | 868 |
///////////////////////////////////////////////////
// The Qcodo Object is used for everything in Qcodo
///////////////////////////////////////////////////
var qcodo = {
initialize: function() {
////////////////////////////////
// Browser-related functionality
////////////////////////////////
this.isBrowser = function(intBrowserType) {
return (intBrowserType & qcodo._intBrowserType);
};
this.IE = 1;
this.IE_6_0 = 2;
this.IE_7_0 = 4;
this.FIREFOX = 8;
this.FIREFOX_1_0 = 16;
this.FIREFOX_1_5 = 32;
this.FIREFOX_2_0 = 64;
this.SAFARI = 128;
this.SAFARI_2_0 = 256;
this.SAFARI_3_0 = 512;
this.MACINTOSH = 1024;
this.UNSUPPORTED = 2048;
// INTERNET EXPLORER (supporting versions 6.0 and 7.0)
if (navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
this._intBrowserType = this.IE;
if (navigator.userAgent.toLowerCase().indexOf("msie 6.0") >= 0)
this._intBrowserType = this._intBrowserType | this.IE_6_0;
else if (navigator.userAgent.toLowerCase().indexOf("msie 7.0") >= 0)
this._intBrowserType = this._intBrowserType | this.IE_7_0;
else
this._intBrowserType = this._intBrowserType | this.UNSUPPORTED;
// FIREFOX (supporting versions 1.0, 1.5 and 2.0)
} else if ((navigator.userAgent.toLowerCase().indexOf("firefox") >= 0) || (navigator.userAgent.toLowerCase().indexOf("iceweasel") >= 0)) {
this._intBrowserType = this.FIREFOX;
var strUserAgent = navigator.userAgent.toLowerCase();
strUserAgent = strUserAgent.replace('iceweasel/', 'firefox/');
if (strUserAgent.indexOf("firefox/1.0") >= 0)
this._intBrowserType = this._intBrowserType | this.FIREFOX_1_0;
else if (strUserAgent.indexOf("firefox/1.5") >= 0)
this._intBrowserType = this._intBrowserType | this.FIREFOX_1_5;
else if (strUserAgent.indexOf("firefox/2.0") >= 0)
this._intBrowserType = this._intBrowserType | this.FIREFOX_2_0;
else
this._intBrowserType = this._intBrowserType | this.UNSUPPORTED;
// SAFARI (supporting version 2.0 and eventually 3.0)
} else if (navigator.userAgent.toLowerCase().indexOf("safari") >= 0) {
this._intBrowserType = this.SAFARI;
if (navigator.userAgent.toLowerCase().indexOf("safari/41") >= 0)
this._intBrowserType = this._intBrowserType | this.SAFARI_2_0;
else if (navigator.userAgent.toLowerCase().indexOf("safari/52") >= 0)
this._intBrowserType = this._intBrowserType | this.SAFARI_3_0;
else
this._intBrowserType = this._intBrowserType | this.UNSUPPORTED;
// COMPLETELY UNSUPPORTED
} else
this._intBrowserType = this.UNSUPPORTED;
// MACINTOSH?
if (navigator.userAgent.toLowerCase().indexOf("macintosh") >= 0)
this._intBrowserType = this._intBrowserType | this.MACINTOSH;
////////////////////////////////
// Browser-related functionality
////////////////////////////////
this.loadJavaScriptFile = function(strScript, objCallback) {
strScript = qc.jsAssets + "/" + strScript;
var objNewScriptInclude = document.createElement("script");
objNewScriptInclude.setAttribute("type", "text/javascript");
objNewScriptInclude.setAttribute("src", strScript);
document.getElementById(document.getElementById("Qform__FormId").value).appendChild(objNewScriptInclude);
// IE does things differently...
if (qc.isBrowser(qcodo.IE)) {
objNewScriptInclude.callOnLoad = objCallback;
objNewScriptInclude.onreadystatechange = function() {
if ((this.readyState == "complete") || (this.readyState == "loaded"))
if (this.callOnLoad)
this.callOnLoad();
};
// ... than everyone else
} else {
objNewScriptInclude.onload = objCallback;
};
};
this.loadStyleSheetFile = function(strStyleSheetFile, strMediaType) {
// IE does things differently...
if (qc.isBrowser(qcodo.IE)) {
var objNewScriptInclude = document.createStyleSheet(strStyleSheetFile);
// ...than everyone else
} else {
var objNewScriptInclude = document.createElement("style");
objNewScriptInclude.setAttribute("type", "text/css");
objNewScriptInclude.setAttribute("media", strMediaType);
objNewScriptInclude.innerHTML = '@import "' + strStyleSheetFile + '";';
document.body.appendChild(objNewScriptInclude);
};
};
/////////////////////////////
// QForm-related functionality
/////////////////////////////
this.registerForm = function() {
// "Lookup" the QForm's FormId
var strFormId = document.getElementById("Qform__FormId").value;
// Register the Various Hidden Form Elements needed for QForms
this.registerFormHiddenElement("Qform__FormControl", strFormId);
this.registerFormHiddenElement("Qform__FormEvent", strFormId);
this.registerFormHiddenElement("Qform__FormParameter", strFormId);
this.registerFormHiddenElement("Qform__FormCallType", strFormId);
this.registerFormHiddenElement("Qform__FormUpdates", strFormId);
this.registerFormHiddenElement("Qform__FormCheckableControls", strFormId);
};
this.registerFormHiddenElement = function(strId, strFormId) {
var objHiddenElement = document.createElement("input");
objHiddenElement.type = "hidden";
objHiddenElement.id = strId;
objHiddenElement.name = strId;
document.getElementById(strFormId).appendChild(objHiddenElement);
};
this.wrappers = new Array();
////////////////////////////////////
// Mouse Drag Handling Functionality
////////////////////////////////////
this.enableMouseDrag = function() {
document.onmousedown = qcodo.handleMouseDown;
document.onmousemove = qcodo.handleMouseMove;
document.onmouseup = qcodo.handleMouseUp;
};
this.handleMouseDown = function(objEvent) {
objEvent = qcodo.handleEvent(objEvent);
var objHandle = qcodo.target;
if (!objHandle) return true;
var objWrapper = objHandle.wrapper;
if (!objWrapper) return true;
// Qcodo-Wide Mouse Handling Functions only operate on the Left Mouse Button
// (Control-specific events can respond to QRightMouse-based Events)
if (qcodo.mouse.left) {
if (objWrapper.handleMouseDown) {
// Specifically for Microsoft IE
if (objHandle.setCapture)
objHandle.setCapture();
// Ensure the Cleanliness of Dragging
objHandle.onmouseout = null;
if (document.selection)
document.selection.empty();
qcodo.currentMouseHandleControl = objWrapper;
return objWrapper.handleMouseDown(objEvent, objHandle);
};
};
qcodo.currentMouseHandleControl = null;
return true;
};
this.handleMouseMove = function(objEvent) {
objEvent = qcodo.handleEvent(objEvent);
if (qcodo.currentMouseHandleControl) {
var objWrapper = qcodo.currentMouseHandleControl;
var objHandle = objWrapper.handle;
// In case IE accidentally marks a selection...
if (document.selection)
document.selection.empty();
if (objWrapper.handleMouseMove)
return objWrapper.handleMouseMove(objEvent, objHandle);
};
return true;
};
this.handleMouseUp = function(objEvent) {
objEvent = qcodo.handleEvent(objEvent);
if (qcodo.currentMouseHandleControl) {
var objWrapper = qcodo.currentMouseHandleControl;
var objHandle = objWrapper.handle;
// In case IE accidentally marks a selection...
if (document.selection)
document.selection.empty();
// For IE to release release/setCapture
if (objHandle.releaseCapture) {
objHandle.releaseCapture();
objHandle.onmouseout = function() {this.releaseCapture()};
};
qcodo.currentMouseHandleControl = null;
if (objWrapper.handleMouseUp)
return objWrapper.handleMouseUp(objEvent, objHandle);
};
return true;
};
////////////////////////////////////
// Window Unloading
////////////////////////////////////
this.unloadFlag = false;
this.handleBeforeUnload = function() {
qcodo.unloadFlag = true;
};
window.onbeforeunload = this.handleBeforeUnload;
////////////////////////////////////
// Color Handling Functionality
////////////////////////////////////
this.colorRgbValues = function(strColor) {
strColor = strColor.replace("#", "");
try {
if (strColor.length == 3)
return new Array(
eval("0x" + strColor.substring(0, 1)),
eval("0x" + strColor.substring(1, 2)),
eval("0x" + strColor.substring(2, 3))
);
else if (strColor.length == 6)
return new Array(
eval("0x" + strColor.substring(0, 2)),
eval("0x" + strColor.substring(2, 4)),
eval("0x" + strColor.substring(4, 6))
);
} catch (Exception) {};
return new Array(0, 0, 0);
};
this.hexFromInt = function(intNumber) {
intNumber = (intNumber > 255) ? 255 : ((intNumber < 0) ? 0 : intNumber);
intFirst = Math.floor(intNumber / 16);
intSecond = intNumber % 16;
return intFirst.toString(16) + intSecond.toString(16);
};
this.colorRgbString = function(intRgbArray) {
return "#" + qcodo.hexFromInt(intRgbArray[0]) + qcodo.hexFromInt(intRgbArray[1]) + qcodo.hexFromInt(intRgbArray[2]);
};
}
};
////////////////////////////////
// Qcodo Shortcut and Initialize
////////////////////////////////
var qc = qcodo;
qc.initialize();
////////////////////////////////
// Logging-related functionality
////////////////////////////////
qcodo.logMessage = function(strMessage, blnReset, blnNonEscape) {
var objLogger = qcodo.getControl("Qform_Logger");
if (!objLogger) {
var objLogger = document.createElement("div");
objLogger.id = "Qform_Logger";
objLogger.style.display = "none";
objLogger.style.width = "400px";
objLogger.style.backgroundColor = "#dddddd";
objLogger.style.fontSize = "10px";
objLogger.style.fontFamily = "lucida console, courier, monospaced";
objLogger.style.padding = "6px";
objLogger.style.overflow = "auto";
if (qcodo.isBrowser(qcodo.IE))
objLogger.style.filter = "alpha(opacity=50)";
else
objLogger.style.opacity = 0.5;
document.body.appendChild(objLogger);
};
if (!blnNonEscape)
if (strMessage.replace)
strMessage = strMessage.replace(/</g, '<');
var strPosition = "fixed";
var strTop = "0px";
var strLeft = "0px";
if (qcodo.isBrowser(qcodo.IE)) {
// IE doesn't support position:fixed, so manually set positioning
strPosition = "absolute";
strTop = qcodo.scroll.y + "px";
strLeft = qcodo.scroll.x + "px";
};
objLogger.style.position = strPosition;
objLogger.style.top = strTop;
objLogger.style.left = strLeft;
objLogger.style.height = (qcodo.client.height - 100) + "px";
objLogger.style.display = 'inline';
var strHeader = '<a href="javascript:qcodo.logRemove()">Remove</a><br/><br/>';
if (blnReset)
objLogger.innerHTML = strHeader + strMessage + "<br/>";
else if (objLogger.innerHTML == "")
objLogger.innerHTML = strHeader + strMessage + "<br/>";
else
objLogger.innerHTML += strMessage + "<br/>";
};
qcodo.logRemove = function() {
var objLogger = qcodo.getControl('Qform_Logger');
if (objLogger)
objLogger.style.display = 'none';
};
qcodo.logEventStats = function(objEvent) {
objEvent = qcodo.handleEvent(objEvent);
var strMessage = "";
strMessage += "scroll (x, y): " + qcodo.scroll.x + ", " + qcodo.scroll.y + "<br/>";
strMessage += "scroll (width, height): " + qcodo.scroll.width + ", " + qcodo.scroll.height + "<br/>";
strMessage += "client (x, y): " + qcodo.client.x + ", " + qcodo.client.y + "<br/>";
strMessage += "client (width, height): " + qcodo.client.width + ", " + qcodo.client.height + "<br/>";
strMessage += "page (x, y): " + qcodo.page.x + ", " + qcodo.page.y + "<br/>";
strMessage += "page (width, height): " + qcodo.page.width + ", " + qcodo.page.height + "<br/>";
strMessage += "mouse (x, y): " + qcodo.mouse.x + ", " + qcodo.mouse.y + "<br/>";
strMessage += "mouse (left, middle, right): " + qcodo.mouse.left + ", " + qcodo.mouse.middle + ", " + qcodo.mouse.right + "<br/>";
strMessage += "key (alt, shift, control, code): " + qcodo.key.alt + ", " + qcodo.key.shift + ", " +
qcodo.key.control + ", " + qcodo.key.code;
qcodo.logMessage("Event Stats", true);
qcodo.logMessage(strMessage, false, true);
};
qcodo.logObject = function(objObject) {
var strDump = "";
for (var strKey in objObject) {
var strData = objObject[strKey];
strDump += strKey + ": ";
if (typeof strData == 'function')
strDump += "<FUNCTION>";
else if (typeof strData == 'object')
strDump += "<OBJECT>";
else if ((strKey == 'outerText') || (strKey == 'innerText') || (strKey == 'outerHTML') || (strKey == 'innerHTML'))
strDump += "<TEXT>";
else
strDump += strData;
strDump += "<br/>";
};
qcodo.logMessage("Object Stats", true);
qcodo.logMessage(strDump, false, true);
};///////////////////////////////
// Timers-related functionality
///////////////////////////////
qcodo._objTimers = new Object();
qcodo.clearTimeout = function(strTimerId) {
if (qcodo._objTimers[strTimerId]) {
clearTimeout(qcodo._objTimers[strTimerId]);
qcodo._objTimers[strTimerId] = null;
};
};
qcodo.setTimeout = function(strTimerId, strAction, intDelay) {
qcodo.clearTimeout(strTimerId);
qcodo._objTimers[strTimerId] = setTimeout(strAction, intDelay);
};
/////////////////////////////////////
// Event Object-related functionality
/////////////////////////////////////
qcodo.handleEvent = function(objEvent) {
objEvent = (objEvent) ? objEvent : ((typeof(event) == "object") ? event : null);
if (objEvent) {
if (typeof(objEvent.clientX) != "undefined") {
if (qcodo.isBrowser(qcodo.SAFARI)) {
qcodo.mouse.x = objEvent.clientX - window.document.body.scrollLeft;
qcodo.mouse.y = objEvent.clientY - window.document.body.scrollTop;
qcodo.client.x = objEvent.clientX - window.document.body.scrollLeft;
qcodo.client.y = objEvent.clientY - window.document.body.scrollTop;
} else {
qcodo.mouse.x = objEvent.clientX;
qcodo.mouse.y = objEvent.clientY;
qcodo.client.x = objEvent.clientX;
qcodo.client.y = objEvent.clientY;
};
};
if (qcodo.isBrowser(qcodo.IE)) {
qcodo.mouse.left = ((objEvent.button & 1) ? true : false);
qcodo.mouse.right = ((objEvent.button & 2) ? true : false);
qcodo.mouse.middle = ((objEvent.button & 4) ? true : false);
} else if (qcodo.isBrowser(qcodo.SAFARI)) {
qcodo.mouse.left = ((objEvent.button && !objEvent.ctrlKey) ? true : false);
qcodo.mouse.right = ((objEvent.button && objEvent.ctrlKey) ? true : false);
qcodo.mouse.middle = false;
} else {
qcodo.mouse.left = (objEvent.button == 0);
qcodo.mouse.right = (objEvent.button == 2);
qcodo.mouse.middle = (objEvent.button == 1);
};
qcodo.key.alt = (objEvent.altKey) ? true : false;
qcodo.key.control = (objEvent.ctrlKey) ? true : false;
qcodo.key.shift = (objEvent.shiftKey) ? true : false;
qcodo.key.code = (objEvent.keyCode) ? (objEvent.keyCode) : 0;
if (objEvent.originalTarget)
qcodo.target = objEvent.originalTarget;
else if (objEvent.srcElement)
qcodo.target = objEvent.srcElement;
else
qcodo.target = null;
};
/*
qcodo.client.width = (qcodo.isBrowser(qcodo.SAFARI)) ? window.innerWidth : window.document.body.clientWidth;
qcodo.client.height = (qcodo.isBrowser(qcodo.SAFARI)) ? window.innerHeight: window.document.body.clientHeight;
qcodo.page.x = qcodo.mouse.x + qcodo.scroll.x;
qcodo.page.y = qcodo.mouse.y + qcodo.scroll.y;
qcodo.page.width = Math.max(window.document.body.scrollWidth, qcodo.client.width);
qcodo.page.height = Math.max(window.document.body.scrollHeight, qcodo.client.height);
qcodo.scroll.x = window.scrollX || window.document.body.scrollLeft;
qcodo.scroll.y = window.scrollY || window.document.body.scrollTop;
qcodo.scroll.width = window.document.body.scrollWidth - qcodo.client.width;
qcodo.scroll.height = window.document.body.scrollHeight - qcodo.client.height;
*/
if (window.document.compatMode == "BackCompat") {
qcodo.client.width = (qcodo.isBrowser(qcodo.SAFARI)) ? window.innerWidth : window.document.body.clientWidth;
qcodo.client.height = (qcodo.isBrowser(qcodo.SAFARI)) ? window.innerHeight: window.document.body.clientHeight;
qcodo.page.width = Math.max(window.document.body.scrollWidth, qcodo.client.width);
qcodo.page.height = Math.max(window.document.body.scrollHeight, qcodo.client.height);
qcodo.scroll.x = window.scrollX || window.document.body.scrollLeft;
qcodo.scroll.y = window.scrollY || window.document.body.scrollTop;
} else if (qcodo.isBrowser(qcodo.SAFARI)) {
qcodo.client.width = window.innerWidth;
qcodo.client.height = window.innerHeight;
qcodo.page.width = Math.max(window.document.body.scrollWidth, qcodo.client.width);
qcodo.page.height = Math.max(window.document.body.scrollHeight, qcodo.client.height);
qcodo.scroll.x = window.scrollX || window.document.body.scrollLeft;
qcodo.scroll.y = window.scrollY || window.document.body.scrollTop;
} else if (qcodo.isBrowser(qcodo.IE)) {
qcodo.client.width = window.document.documentElement.offsetWidth;
qcodo.client.height = window.document.documentElement.offsetHeight;
qcodo.page.width = Math.max(window.document.documentElement.scrollWidth, qcodo.client.width);
qcodo.page.height = Math.max(window.document.documentElement.scrollHeight, qcodo.client.height);
qcodo.scroll.x = window.document.documentElement.scrollLeft;
qcodo.scroll.y = window.document.documentElement.scrollTop;
} else {
if (window.scrollMaxY)
// Take the Y Scroll Bar into account by subtracting 15 pixels
qcodo.client.width = window.innerWidth - 15;
else
qcodo.client.width = window.innerWidth;
if (window.scrollMaxX)
// Take the X Scroll Bar into account by subtracting 15 pixels
qcodo.client.height = window.innerHeight - 15;
else
qcodo.client.height = window.innerHeight;
qcodo.page.width = window.scrollMaxX + qcodo.client.width;
qcodo.page.height = window.scrollMaxY + qcodo.client.height;
qcodo.scroll.x = window.scrollX;
qcodo.scroll.y = window.scrollY;
};
// These Values are "By Definition"
qcodo.page.x = qcodo.mouse.x + qcodo.scroll.x;
qcodo.page.y = qcodo.mouse.y + qcodo.scroll.y;
qcodo.scroll.width = qcodo.page.width - qcodo.client.width;
qcodo.scroll.height = qcodo.page.height - qcodo.client.height;
return objEvent;
};
qcodo.terminateEvent = function(objEvent) {
objEvent = qcodo.handleEvent(objEvent);
if (objEvent) {
// Stop Propogation
if (objEvent.preventDefault)
objEvent.preventDefault();
if (objEvent.stopPropagation)
objEvent.stopPropagation();
objEvent.cancelBubble = true;
objEvent.returnValue = false;
};
return false;
};
///////////////////////////////
// Event Stats-Releated Objects
///////////////////////////////
qcodo.key = {
control: false,
alt: false,
shift: false,
code: null
};
qcodo.mouse = {
x: 0,
y: 0,
left: false,
middle: false,
right: false
};
qcodo.client = {
x: null,
y: null,
width: null,
height: null
// width: (qcodo.isBrowser(qcodo.IE)) ? window.document.body.clientWidth : window.innerWidth,
// height: (qcodo.isBrowser(qcodo.IE)) ? window.document.body.clientHeight : window.innerHeight
};
qcodo.page = {
x: null,
y: null,
width: null,
height: null
// width: window.document.body.scrollWidth,
// height: window.document.body.scrollHeight
};
qcodo.scroll = {
x: window.scrollX || (window.document.body) ? window.document.body.scrollLeft : null,
y: window.scrollY || (window.document.body) ? window.document.body.scrollTop : null,
// x: null,
// y: null,
width: (window.document.body) ? (window.document.body.scrollWidth - qcodo.client.width) : null,
height: (window.document.body) ? (window.document.body.scrollHeight - qcodo.client.height) : null
// width: null,
// height: null
};
////////////////////////////////////////////
// PostBack and AjaxPostBack
////////////////////////////////////////////
qcodo.postBack = function(strForm, strControl, strEvent, strParameter) {
var objForm = document.getElementById(strForm);
objForm.Qform__FormControl.value = strControl;
objForm.Qform__FormEvent.value = strEvent;
objForm.Qform__FormParameter.value = strParameter;
objForm.Qform__FormCallType.value = "Server";
objForm.Qform__FormUpdates.value = this.formUpdates();
objForm.Qform__FormCheckableControls.value = this.formCheckableControls(strForm, "Server");
objForm.submit();
};
qcodo.formUpdates = function() {
var strToReturn = "";
for (var strControlId in qcodo.controlModifications)
for (var strProperty in qcodo.controlModifications[strControlId])
strToReturn += strControlId + " " + strProperty + " " + qcodo.controlModifications[strControlId][strProperty] + "\n";
qcodo.controlModifications = new Array();
return strToReturn;
};
qcodo.formCheckableControls = function(strForm, strCallType) {
var objForm = document.getElementById(strForm);
var strToReturn = "";
for (var intIndex = 0; intIndex < objForm.elements.length; intIndex++) {
if (((objForm.elements[intIndex].type == "checkbox") ||
(objForm.elements[intIndex].type == "radio")) &&
((strCallType == "Ajax") ||
(!objForm.elements[intIndex].disabled))) {
// CheckBoxList
if (objForm.elements[intIndex].id.indexOf('[') >= 0) {
if (objForm.elements[intIndex].id.indexOf('[0]') >= 0)
strToReturn += " " + objForm.elements[intIndex].id.substring(0, objForm.elements[intIndex].id.length - 3);
// RadioButtonList
} else if (objForm.elements[intIndex].id.indexOf('_') >= 0) {
if (objForm.elements[intIndex].id.indexOf('_0') >= 0)
strToReturn += " " + objForm.elements[intIndex].id.substring(0, objForm.elements[intIndex].id.length - 2);
// Standard Radio or Checkbox
} else {
strToReturn += " " + objForm.elements[intIndex].id;
};
};
};
if (strToReturn.length > 0)
return strToReturn.substring(1);
else
return "";
};
qcodo.ajaxQueue = new Array();
qcodo.postAjax = function(strForm, strControl, strEvent, strParameter, strWaitIconControlId) {
// alert(strForm + " " + strControl + " " + strEvent + " " + strParameter);
// Figure out if Queue is Empty
var blnQueueEmpty = false;
if (qcodo.ajaxQueue.length == 0)
blnQueueEmpty = true;
// Enqueue the AJAX Request
qcodo.ajaxQueue.push(new Array(strForm, strControl, strEvent, strParameter, strWaitIconControlId));
// If the Queue was originally empty, call the Dequeue
if (blnQueueEmpty)
qcodo.dequeueAjaxQueue();
};
qcodo.clearAjaxQueue = function() {
qcodo.ajaxQueue = new Array();
};
qcodo.objAjaxWaitIcon = null;
qcodo.dequeueAjaxQueue = function() {
if (qcodo.ajaxQueue.length > 0) {
strForm = this.ajaxQueue[0][0];
strControl = this.ajaxQueue[0][1];
strEvent = this.ajaxQueue[0][2];
strParameter = this.ajaxQueue[0][3];
strWaitIconControlId = this.ajaxQueue[0][4];
// Display WaitIcon (if applicable)
if (strWaitIconControlId) {
this.objAjaxWaitIcon = this.getWrapper(strWaitIconControlId);
if (this.objAjaxWaitIcon)
this.objAjaxWaitIcon.style.display = 'inline';
};
var objForm = document.getElementById(strForm);
objForm.Qform__FormControl.value = strControl;
objForm.Qform__FormEvent.value = strEvent;
objForm.Qform__FormParameter.value = strParameter;
objForm.Qform__FormCallType.value = "Ajax";
objForm.Qform__FormUpdates.value = qcodo.formUpdates();
objForm.Qform__FormCheckableControls.value = this.formCheckableControls(strForm, "Ajax");
var strPostData = "";
for (var i = 0; i < objForm.elements.length; i++) {
switch (objForm.elements[i].type) {
case "checkbox":
case "radio":
if (objForm.elements[i].checked) {
var strTestName = objForm.elements[i].name + "_";
if (objForm.elements[i].id.substring(0, strTestName.length) == strTestName)
strPostData += "&" + objForm.elements[i].name + "=" + objForm.elements[i].id.substring(strTestName.length);
else
// strPostData += "&" + objForm.elements[i].id + "=" + "1";
strPostData += "&" + objForm.elements[i].id + "=" + objForm.elements[i].value;
};
break;
case "select-multiple":
var blnOneSelected = false;
for (var intIndex = 0; intIndex < objForm.elements[i].options.length; intIndex++)
if (objForm.elements[i].options[intIndex].selected) {
strPostData += "&" + objForm.elements[i].name + "=";
strPostData += objForm.elements[i].options[intIndex].value;
};
break;
default:
strPostData += "&" + objForm.elements[i].id + "=";
// For Internationalization -- we must escape the element's value properly
var strPostValue = objForm.elements[i].value;
if (strPostValue) {
strPostValue = strPostValue.replace(/\%/g, "%25");
strPostValue = strPostValue.replace(/&/g, escape('&'));
strPostValue = strPostValue.replace(/\+/g, "%2B");
};
strPostData += strPostValue;
break;
};
};
var strUri = objForm.action;
var objRequest;
if (window.XMLHttpRequest) {
objRequest = new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
objRequest = new ActiveXObject("Microsoft.XMLHTTP");
};
if (objRequest) {
objRequest.open("POST", strUri, true);
objRequest.setRequestHeader("Method", "POST " + strUri + " HTTP/1.1");
objRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
objRequest.onreadystatechange = function() {
if (!qcodo.unloadFlag && objRequest.readyState == 4) {
try {
var objXmlDoc = objRequest.responseXML;
// qcodo.logMessage(objRequest.responseText, true);
// alert('AJAX Response Received');
if (!objXmlDoc) {
alert("An error occurred during AJAX Response parsing.\r\n\r\nThe error response will appear in a new popup.");
var objErrorWindow = window.open('about:blank', 'qcodo_error','menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,width=1000,height=700,left=50,top=50');
objErrorWindow.focus();
objErrorWindow.document.write(objRequest.responseText);
return;
} else {
var intLength = 0;
// Go through Controls
var objXmlControls = objXmlDoc.getElementsByTagName('control');
intLength = objXmlControls.length;
for (var intIndex = 0; intIndex < intLength; intIndex++) {
var strControlId = objXmlControls[intIndex].attributes.getNamedItem('id').nodeValue;
var strControlHtml = "";
if (objXmlControls[intIndex].firstChild)
strControlHtml = objXmlControls[intIndex].firstChild.nodeValue;
if (qcodo.isBrowser(qcodo.FIREFOX))
strControlHtml = objXmlControls[intIndex].textContent;
// Perform Callback Responsibility
if (strControlId == "Qform__FormState") {
var objFormState = document.getElementById(strControlId);
objFormState.value = strControlHtml;
} else {
var objSpan = document.getElementById(strControlId + "_ctl");
if (objSpan)
objSpan.innerHTML = strControlHtml;
};
};
// Go through Commands
var objXmlCommands = objXmlDoc.getElementsByTagName('command');
intLength = objXmlCommands.length;
for (var intIndex = 0; intIndex < intLength; intIndex++) {
if (objXmlCommands[intIndex] && objXmlCommands[intIndex].firstChild) {
var strCommand = "";
intChildLength = objXmlCommands[intIndex].childNodes.length;
for (var intChildIndex = 0; intChildIndex < intChildLength; intChildIndex++)
strCommand += objXmlCommands[intIndex].childNodes[intChildIndex].nodeValue;
eval(strCommand);
};
};
};
} catch (objExc) {
alert(objExc.message + "\r\non line number " + objExc.lineNumber + "\r\nin file " + objExc.fileName);
alert("An error occurred during AJAX Response handling.\r\n\r\nThe error response will appear in a new popup.");
var objErrorWindow = window.open('about:blank', 'qcodo_error','menubar=no,toolbar=no,location=no,status=no,scrollbars=yes,resizable=yes,width=1000,height=700,left=50,top=50');
objErrorWindow.focus();
objErrorWindow.document.write(objRequest.responseText);
return;
};
// Perform the Dequeue
qcodo.ajaxQueue.reverse();
qcodo.ajaxQueue.pop();
qcodo.ajaxQueue.reverse();
// Hid the WaitIcon (if applicable)
if (qcodo.objAjaxWaitIcon)
qcodo.objAjaxWaitIcon.style.display = 'none';
// If there are still AjaxEvents in the queue, go ahead and process/dequeue them
if (qcodo.ajaxQueue.length > 0)
qcodo.dequeueAjaxQueue();
};
};
objRequest.send(strPostData);
};
};
};
//////////////////
// Qcodo Shortcuts
//////////////////
qc.pB = qcodo.postBack;
qc.pA = qcodo.postAjax;
/////////////////////////////////
// Controls-related functionality
/////////////////////////////////
qcodo.getControl = function(mixControl) {
if (typeof(mixControl) == 'string')
return document.getElementById(mixControl);
else
return mixControl;
};
qcodo.getWrapper = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
if (objControl)
return this.getControl(objControl.id + "_ctl");
else
return null;
};
/////////////////////////////
// Register Control - General
/////////////////////////////
qcodo.controlModifications = new Array();
qcodo.javascriptStyleToQcodo = new Array();
qcodo.javascriptStyleToQcodo["backgroundColor"] = "BackColor";
qcodo.javascriptStyleToQcodo["borderColor"] = "BorderColor";
qcodo.javascriptStyleToQcodo["borderStyle"] = "BorderStyle";
qcodo.javascriptStyleToQcodo["border"] = "BorderWidth";
qcodo.javascriptStyleToQcodo["height"] = "Height";
qcodo.javascriptStyleToQcodo["width"] = "Width";
qcodo.javascriptStyleToQcodo["text"] = "Text";
qcodo.javascriptWrapperStyleToQcodo = new Array();
qcodo.javascriptWrapperStyleToQcodo["position"] = "Position";
qcodo.javascriptWrapperStyleToQcodo["top"] = "Top";
qcodo.javascriptWrapperStyleToQcodo["left"] = "Left";
qcodo.recordControlModification = function(strControlId, strProperty, strNewValue) {
if (!qcodo.controlModifications[strControlId])
qcodo.controlModifications[strControlId] = new Array();
qcodo.controlModifications[strControlId][strProperty] = strNewValue;
};
qcodo.registerControl = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
// Link the Wrapper and the Control together
var objWrapper = this.getWrapper(objControl);
objControl.wrapper = objWrapper;
objWrapper.control = objControl;
// Add the wrapper to the global qcodo wrappers array
qcodo.wrappers[objWrapper.id] = objWrapper;
// Create New Methods, etc.
// Like: objWrapper.something = xyz;
// Updating Style-related Things
objWrapper.updateStyle = function(strStyleName, strNewValue) {
var objControl = this.control;
switch (strStyleName) {
case "className":
objControl.className = strNewValue;
qcodo.recordControlModification(objControl.id, "CssClass", strNewValue);
break;
case "parent":
if (strNewValue) {
var objNewParentControl = qcodo.getControl(strNewValue);
objNewParentControl.appendChild(this);
qcodo.recordControlModification(objControl.id, "Parent", strNewValue);
} else {
var objParentControl = this.parentNode;
objParentControl.removeChild(this);
qcodo.recordControlModification(objControl.id, "Parent", "");
};
break;
case "displayStyle":
objControl.style.display = strNewValue;
qcodo.recordControlModification(objControl.id, "DisplayStyle", strNewValue);
break;
case "display":
if (strNewValue) {
objWrapper.style.display = "inline";
qcodo.recordControlModification(objControl.id, "Display", "1");
} else {
objWrapper.style.display = "none";
qcodo.recordControlModification(objControl.id, "Display", "0");
};
break;
case "enabled":
if (strNewValue) {
objWrapper.control.disabled = false;
qcodo.recordControlModification(objControl.id, "Enabled", "1");
} else {
objWrapper.control.disabled = true;
qcodo.recordControlModification(objControl.id, "Enabled", "0");
};
break;
case "width":
case "height":
objControl.style[strStyleName] = strNewValue;
if (qcodo.javascriptStyleToQcodo[strStyleName])
qcodo.recordControlModification(objControl.id, qcodo.javascriptStyleToQcodo[strStyleName], strNewValue);
if (objWrapper.handle)
objWrapper.updateHandle();
break;
case "text":
objControl.innerHTML = strNewValue;
qcodo.recordControlModification(objControl.id, "Text", strNewValue);
break;
default:
if (qcodo.javascriptWrapperStyleToQcodo[strStyleName]) {
this.style[strStyleName] = strNewValue;
qcodo.recordControlModification(objControl.id, qcodo.javascriptWrapperStyleToQcodo[strStyleName], strNewValue);
} else {
objControl.style[strStyleName] = strNewValue;
if (qcodo.javascriptStyleToQcodo[strStyleName])
qcodo.recordControlModification(objControl.id, qcodo.javascriptStyleToQcodo[strStyleName], strNewValue);
};
break;
};
};
// Positioning-related functions
objWrapper.getAbsolutePosition = function() {
var intOffsetLeft = 0;
var intOffsetTop = 0;
var objControl = this.control;
while (objControl) {
// If we are IE, we don't want to include calculating
// controls who's wrappers are position:relative
if ((objControl.wrapper) && (objControl.wrapper.style.position == "relative")) {
} else {
intOffsetLeft += objControl.offsetLeft;
intOffsetTop += objControl.offsetTop;
};
objControl = objControl.offsetParent;
};
return {x:intOffsetLeft, y:intOffsetTop};
};
objWrapper.setAbsolutePosition = function(intNewX, intNewY, blnBindToParent) {
var objControl = this.offsetParent;
while (objControl) {
intNewX -= objControl.offsetLeft;
intNewY -= objControl.offsetTop;
objControl = objControl.offsetParent;
};
if (blnBindToParent) {
if (this.parentNode.nodeName.toLowerCase() != 'form') {
// intNewX and intNewY must be within the parent's control
intNewX = Math.max(intNewX, 0);
intNewY = Math.max(intNewY, 0);
intNewX = Math.min(intNewX, this.offsetParent.offsetWidth - this.offsetWidth);
intNewY = Math.min(intNewY, this.offsetParent.offsetHeight - this.offsetHeight);
};
};
this.updateStyle("left", intNewX + "px");
this.updateStyle("top", intNewY + "px");
};
objWrapper.setDropZoneMaskAbsolutePosition = function(intNewX, intNewY, blnBindToParent) {
/*
var objControl = this.offsetParent;
while (objControl) {
intNewX -= objControl.offsetLeft;
intNewY -= objControl.offsetTop;
objControl = objControl.offsetParent;
}
if (blnBindToParent) {
if (this.parentNode.nodeName.toLowerCase() != 'form') {
// intNewX and intNewY must be within the parent's control
intNewX = Math.max(intNewX, 0);
intNewY = Math.max(intNewY, 0);
intNewX = Math.min(intNewX, this.offsetParent.offsetWidth - this.offsetWidth);
intNewY = Math.min(intNewY, this.offsetParent.offsetHeight - this.offsetHeight);
}
}
qc.logObject(intNewX + " x " + intNewY);
*/
this.dropZoneMask.style.left = intNewX + "px";
this.dropZoneMask.style.top = intNewY + "px";
};
objWrapper.setMaskOffset = function(intDeltaX, intDeltaY) {
var objAbsolutePosition = this.getAbsolutePosition();
this.mask.style.left = (objAbsolutePosition.x + intDeltaX) + "px";
this.mask.style.top = (objAbsolutePosition.y + intDeltaY) + "px";
};
objWrapper.containsPoint = function(intX, intY) {
var objAbsolutePosition = this.getAbsolutePosition();
if ((intX >= objAbsolutePosition.x) && (intX <= objAbsolutePosition.x + this.control.offsetWidth) &&
(intY >= objAbsolutePosition.y) && (intY <= objAbsolutePosition.y + this.control.offsetHeight))
return true;
else
return false;
};
// Toggle Display / Enabled
objWrapper.toggleDisplay = function(strShowOrHide) {
// Toggles the display/hiding of the entire control (including any design/wrapper HTML)
// If ShowOrHide is blank, then we toggle
// Otherwise, we'll execute a "show" or a "hide"
if (strShowOrHide) {
if (strShowOrHide == "show")
this.updateStyle("display", true);
else
this.updateStyle("display", false);
} else
this.updateStyle("display", (this.style.display == "none") ? true : false);
};
objWrapper.toggleEnabled = function(strEnableOrDisable) {
if (strEnableOrDisable) {
if (strEnableOrDisable == "enable")
this.updateStyle("enabled", true);
else
this.updateStyle("enabled", false);
} else
this.updateStyle("enabled", (this.control.disabled) ? true : false);
};
objWrapper.registerClickPosition = function(objEvent) {
objEvent = (objEvent) ? objEvent : ((typeof(event) == "object") ? event : null);
qcodo.handleEvent(objEvent);
var intX = qcodo.mouse.x - this.getAbsolutePosition().x + qcodo.scroll.x;
var intY = qcodo.mouse.y - this.getAbsolutePosition().y + qcodo.scroll.y;
// Random IE Check
if (qcodo.isBrowser(qcodo.IE)) {
intX = intX - 2;
intY = intY - 2;
};
document.getElementById(this.control.id + "_x").value = intX;
document.getElementById(this.control.id + "_y").value = intY;
};
// Focus
objWrapper.focus = function() {
if (this.control.focus) {
if (qcodo.isBrowser(qcodo.IE) && (typeof (this.control.focus) == "object"))
this.control.focus();
else if (typeof (this.control.focus) == "function")
this.control.focus();
};
};
// Blink
objWrapper.blink = function(strFromColor, strToColor) {
objWrapper.blinkStart = qcodo.colorRgbValues(strFromColor);
objWrapper.blinkEnd = qcodo.colorRgbValues(strToColor);
objWrapper.blinkStep = new Array(
Math.round((objWrapper.blinkEnd[0] - objWrapper.blinkStart[0]) / 12.5),
Math.round((objWrapper.blinkEnd[1] - objWrapper.blinkStart[1]) / 12.5),
Math.round((objWrapper.blinkEnd[2] - objWrapper.blinkStart[2]) / 12.5)
);
objWrapper.blinkDown = new Array(
(objWrapper.blinkStep[0] < 0) ? true : false,
(objWrapper.blinkStep[1] < 0) ? true : false,
(objWrapper.blinkStep[2] < 0) ? true : false
);
objWrapper.blinkCurrent = objWrapper.blinkStart;
this.control.style.backgroundColor = qcodo.colorRgbString(objWrapper.blinkCurrent);
qcodo.setTimeout(objWrapper.id, "qc.getC('" + objWrapper.id + "').blinkHelper()", 20);
};
objWrapper.blinkHelper = function() {
objWrapper.blinkCurrent[0] += objWrapper.blinkStep[0];
objWrapper.blinkCurrent[1] += objWrapper.blinkStep[1];
objWrapper.blinkCurrent[2] += objWrapper.blinkStep[2];
if (((objWrapper.blinkDown[0]) && (objWrapper.blinkCurrent[0] < objWrapper.blinkEnd[0])) ||
((!objWrapper.blinkDown[0]) && (objWrapper.blinkCurrent[0] > objWrapper.blinkEnd[0])))
objWrapper.blinkCurrent[0] = objWrapper.blinkEnd[0];
if (((objWrapper.blinkDown[1]) && (objWrapper.blinkCurrent[1] < objWrapper.blinkEnd[1])) ||
((!objWrapper.blinkDown[1]) && (objWrapper.blinkCurrent[1] > objWrapper.blinkEnd[1])))
objWrapper.blinkCurrent[1] = objWrapper.blinkEnd[1];
if (((objWrapper.blinkDown[2]) && (objWrapper.blinkCurrent[2] < objWrapper.blinkEnd[2])) ||
((!objWrapper.blinkDown[2]) && (objWrapper.blinkCurrent[2] > objWrapper.blinkEnd[2])))
objWrapper.blinkCurrent[2] = objWrapper.blinkEnd[2];
this.control.style.backgroundColor = qcodo.colorRgbString(objWrapper.blinkCurrent);
if ((objWrapper.blinkCurrent[0] == objWrapper.blinkEnd[0]) &&
(objWrapper.blinkCurrent[1] == objWrapper.blinkEnd[1]) &&
(objWrapper.blinkCurrent[2] == objWrapper.blinkEnd[2])) {
// Done with Blink!
} else {
qcodo.setTimeout(objWrapper.id, "qc.getC('" + objWrapper.id + "').blinkHelper()", 20);
};
};
};
qcodo.registerControlArray = function(mixControlArray) {
var intLength = mixControlArray.length;
for (var intIndex = 0; intIndex < intLength; intIndex++)
qcodo.registerControl(mixControlArray[intIndex]);
};
//////////////////
// Qcodo Shortcuts
//////////////////
qc.getC = qcodo.getControl;
qc.getW = qcodo.getWrapper;
qc.regC = qcodo.registerControl;
qc.regCA = qcodo.registerControlArray;
/////////////////////////////////////////////
// Control: Dialog Box functionality
/////////////////////////////////////////////
qcodo.registerDialogBox = function(mixControl, strMatteColor, intMatteOpacity, blnMatteClickable, blnAnyKeyCloses) {
// Initialize the Event Handler
qcodo.handleEvent();
// Get Control/Wrapper
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
var objWrapper = objControl.wrapper;
// Setup the DialogBoxBackground (DbBg) if applicable
var objDbBg = objWrapper.dbBg;
if (!objDbBg) {
var objDbBg = document.createElement("div");
objDbBg.id = objWrapper.id + "dbbg";
document.getElementById(document.getElementById("Qform__FormId").value).appendChild(objDbBg);
// Setup the Object Links
objWrapper.dbBg = objDbBg;
objDbBg.wrapper = objWrapper;
if (qcodo.isBrowser(qcodo.IE)) {
var objIframe = document.createElement("iframe");
objIframe.id = objWrapper.id + "dbbgframe";
objIframe.style.left = "0px";
objIframe.style.top = "0px";
objIframe.style.position = "absolute";
objIframe.style.filter = "alpha(opacity=0)";
objIframe.src = "javascript: false;";
objIframe.frameBorder = 0;
objIframe.scrolling = "no";
objIframe.style.zIndex = 990;
objIframe.display = "none";
document.getElementById(document.getElementById("Qform__FormId").value).appendChild(objIframe);
objWrapper.dbBgFrame = objIframe;
};
};
objWrapper.handleResize = function(objEvent) {
objEvent = qcodo.handleEvent(objEvent);
if (objEvent.target) {
if ((objEvent.target.nodeName.toLowerCase() == 'div') || (objEvent.target.nodeName.toLowerCase() == 'span'))
return;
};
// Restore from Link
var objWrapper = qcodo.activeDialogBox;
var objDbBg = objWrapper.dbBg;
var objDbBgFrame = objWrapper.dbBgFrame;
// Hide Everything
objWrapper.style.display = "none";
objDbBg.style.display = "none";
if (objDbBgFrame) objDbBgFrame.style.display = "none";
// Setup Events
qcodo.handleEvent(objEvent);
// Show Everything
objWrapper.style.display = "inline";
objDbBg.style.display = "block";
if (objDbBgFrame) objDbBgFrame.style.display = "block";
// DbBg Re-Setup
objDbBg.style.width = Math.max(qcodo.page.width, qcodo.client.width) + "px";
objDbBg.style.height = Math.max(qcodo.page.height, qcodo.client.height) + "px";
if (objDbBgFrame) {
objDbBgFrame.style.width = Math.max(qcodo.page.width, qcodo.client.width) + "px";
objDbBgFrame.style.height = Math.max(qcodo.page.height, qcodo.client.height) + "px";
};
// Wrapper Re-Setup
var intWidth = objWrapper.offsetWidth;
var intHeight = objWrapper.offsetHeight;
var intTop = Math.round((qcodo.client.height - intHeight) / 2) + qcodo.scroll.y;
var intLeft = Math.round((qcodo.client.width - intWidth) / 2) + qcodo.scroll.x;
objWrapper.setAbsolutePosition(intLeft, intTop);
return true;
};
objWrapper.handleKeyPress = function(objEvent) {
objEvent = qcodo.handleEvent(objEvent);
qcodo.terminateEvent(objEvent);
var objWrapper = qcodo.activeDialogBox;
objWrapper.hideDialogBox();
return false;
};
objWrapper.showDialogBox = function() {
// Restore from Object Link
var objDbBg = this.dbBg;
var objDbBgFrame = this.dbBgFrame;
// Hide Everything
objWrapper.style.display = "none";
objDbBg.style.display = "none";
if (objDbBgFrame) objDbBgFrame.style.display = "none";
// Setup Events
qcodo.handleEvent();
// Show Everything
objDbBg.style.display = "block";
if (objDbBgFrame) objDbBgFrame.style.display = "block";
this.toggleDisplay("show");
// DbBg Re-Setup
objDbBg.style.width = Math.max(qcodo.page.width, qcodo.client.width) + "px";
objDbBg.style.height = Math.max(qcodo.page.height, qcodo.client.height) + "px";
if (objDbBgFrame) {
objDbBgFrame.style.width = Math.max(qcodo.page.width, qcodo.client.width) + "px";
objDbBgFrame.style.height = Math.max(qcodo.page.height, qcodo.client.height) + "px";
};
// Wrapper Re-Setup
var intWidth = objWrapper.offsetWidth;
var intHeight = objWrapper.offsetHeight;
var intTop = Math.round((qcodo.client.height - intHeight) / 2) + qcodo.scroll.y;
var intLeft = Math.round((qcodo.client.width - intWidth) / 2) + qcodo.scroll.x;
objWrapper.setAbsolutePosition(intLeft, intTop);
// Set Window OnResize Handling
window.onresize = this.handleResize;
window.onscroll = this.handleResize;
qcodo.activeDialogBox = this;
// If we have blnMatteClickable and blnAnyKeyCloses
if (objWrapper.anyKeyCloses) {
document.body.onkeypress = this.handleKeyPress;
objWrapper.control.focus();
};
};
objWrapper.hideDialogBox = function() {
var objWrapper = this;
if (this.id.indexOf("_ctldbbg") > 0)
objWrapper = this.wrapper;
objWrapper.dbBg.style.display = "none";
if (objWrapper.dbBgFrame) objWrapper.dbBgFrame.style.display = "none";
objWrapper.toggleDisplay("hide");
// Unsetup OnResize Handling
window.onresize = null;
window.onscroll = null;
// Unsetup KeyPress Closing
document.body.onkeypress = null;
// Unsetup ActiveDialogBox
qcodo.activeDialogBox = null;
};
// Initial Wrapper Setup
objWrapper.style.zIndex = 999;
objWrapper.position = "absolute";
objWrapper.anyKeyCloses = blnAnyKeyCloses;
// Initial DbBg Setup
objDbBg.style.position = "absolute";
objDbBg.style.zIndex = 998;
objDbBg.style.top = "0px";
objDbBg.style.left = "0px";
if (qcodo.isBrowser(qcodo.IE))
objDbBg.style.overflow = "auto";
else
objDbBg.style.overflow = "hide";
if (blnMatteClickable) {
objDbBg.style.cursor = "pointer";
objDbBg.onclick = objWrapper.hideDialogBox;
} else {
objDbBg.style.cursor = "url(" + qc.imageAssets + "/_core/move_nodrop.cur), auto";
objDbBg.onclick = null;
};
// Background Color and Opacity
objDbBg.style.backgroundColor = strMatteColor;
if (qcodo.isBrowser(qcodo.IE))
objDbBg.style.filter = "alpha(opacity=" + intMatteOpacity + ")";
else
objDbBg.style.opacity = intMatteOpacity / 100.0;
// Other Random Stuff
objDbBg.style.fontSize = "1px";
objDbBg.innerHTML = " ";
// Perform a Show or Hide (depending on state)
if (objWrapper.style.display == 'none')
objWrapper.hideDialogBox();
else
objWrapper.showDialogBox();
};
//////////////////
// Qcodo Shortcuts
//////////////////
qc.regDB = qcodo.registerDialogBox;///////////////////////////////
// Control Handle Functionality
///////////////////////////////
qcodo.registerControlHandle = function(mixControl, strCursor) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
var objWrapper = objControl.wrapper;
if (!objWrapper.handle) {
var objHandle = document.createElement("span");
objHandle.id = objWrapper.id + "handle";
objWrapper.parentNode.appendChild(objHandle);
objWrapper.handle = objHandle;
objHandle.wrapper = objWrapper;
if (!objWrapper.style.position) {
// The Wrapper is not defined as Positioned Relatively or Absolutely
// Therefore, no offsetTop/Left/Width/Height values are available on the wrapper itself
objHandle.style.width = objWrapper.control.style.width;
objHandle.style.height = objWrapper.control.style.height;
objHandle.style.top = objWrapper.control.offsetTop + "px";
objHandle.style.left = objWrapper.control.offsetLeft + "px";
} else {
objHandle.style.width = objWrapper.offsetWidth + "px";
objHandle.style.height = objWrapper.offsetHeight + "px";
objHandle.style.top = objWrapper.offsetTop + "px";
objHandle.style.left = objWrapper.offsetLeft + "px";
};
objHandle.style.cursor = strCursor;
objHandle.style.zIndex = 999;
objHandle.style.backgroundColor = "white";
if (qcodo.isBrowser(qcodo.IE))
objHandle.style.filter = "alpha(opacity=0)";
else
objHandle.style.opacity = 0.0;
objHandle.style.position = "absolute";
objHandle.style.fontSize = "1px";
objHandle.innerHTML = ".";
};
objWrapper.updateHandle = function(blnUpdateParent, strCursor) {
var objHandle = this.handle;
// Make Sure the Wrapper's Parent owns this Handle
if (blnUpdateParent)
this.parentNode.appendChild(objHandle);
// Fixup Size and Positioning
objHandle.style.top = this.offsetTop + "px";
objHandle.style.left = this.offsetLeft + "px";
objHandle.style.width = this.offsetWidth + "px";
objHandle.style.height = this.offsetHeight + "px";
// Update the Cursor
if (strCursor)
objHandle.style.cursor = strCursor;
};
};
//////////////////
// Qcodo Shortcuts
//////////////////
qc.regCH = qcodo.registerControlHandle;
/////////////////////////////////////////////
// Control: Moveable functionality
/////////////////////////////////////////////
qcodo.registerControlMoveable = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
var objWrapper = objControl.wrapper;
objWrapper.moveable = true;
// Control Handle and Mask
objWrapper.mask = qcodo.getControl(objWrapper.id + "mask");
if (!objWrapper.mask) {
var objSpanElement = document.createElement('span');
objSpanElement.id = objWrapper.id + "mask";
objSpanElement.style.position = "absolute";
document.getElementById(document.getElementById("Qform__FormId").value).appendChild(objSpanElement);
objWrapper.mask = objSpanElement;
};
objWrapper.mask.wrapper = objWrapper;
// Setup Mask
objMask = objWrapper.mask;
objMask.style.position = "absolute";
objMask.style.zIndex = 998;
if (qcodo.isBrowser(qcodo.IE))
objMask.style.filter = "alpha(opacity=50)";
else
objMask.style.opacity = 0.5;
objMask.style.display = "none";
objMask.innerHTML = "";
objMask.handleAnimateComplete = function(mixControl) {
this.style.display = "none";
};
};
// Update Absolutely-positioned children on Scroller (if applicable)
// to fix Firefox b/c firefox uses position:absolute incorrectly
/* if (qcodo.isBrowser(qcodo.FIREFOX) && (objControl.style.overflow == "auto"))
objControl.onscroll = function(objEvent) {
objEvent = qcodo.handleEvent(objEvent);
for (var intIndex = 0; intIndex < this.childNodes.length; intIndex++) {
if ((this.childNodes[intIndex].style) && (this.childNodes[intIndex].style.position == "absolute")) {
if (!this.childNodes[intIndex].originalX) {
this.childNodes[intIndex].originalX = this.childNodes[intIndex].offsetLeft;
this.childNodes[intIndex].originalY = this.childNodes[intIndex].offsetTop;
}
this.childNodes[intIndex].style.left = this.childNodes[intIndex].originalX - this.scrollLeft + "px";
this.childNodes[intIndex].style.top = this.childNodes[intIndex].originalY - this.scrollTop + "px";
}
}
}*/
///////////////////////////////////////////////
// Block Control: DropZone Target Functionality
///////////////////////////////////////////////
qcodo.registerControlDropZoneTarget = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
var objWrapper = objControl.wrapper;
// Control Handle and Mask
objWrapper.dropZoneMask = qcodo.getControl(objWrapper.id + "dzmask");
if (!objWrapper.dropZoneMask) {
//<span id="%s_ctldzmask" style="position:absolute;"><span style="font-size: 1px"> </span></span>
var objSpanElement = document.createElement("span");
objSpanElement.id = objWrapper.id + "dzmask";
objSpanElement.style.position = "absolute";
var objInnerSpanElement = document.createElement("span");
objInnerSpanElement.style.fontSize = "1px";
objInnerSpanElement.innerHTML = " ";
objSpanElement.appendChild(objInnerSpanElement);
document.getElementById(document.getElementById("Qform__FormId").value).appendChild(objSpanElement);
objWrapper.dropZoneMask = objSpanElement;
objWrapper.dropZoneMask.wrapper = objWrapper;
// Setup Mask
objMask = objWrapper.dropZoneMask;
objMask.style.position = "absolute";
objMask.style.top = "0px";
objMask.style.left = "0px";
objMask.style.borderColor = "#bb3399";
objMask.style.borderStyle = "solid";
objMask.style.borderWidth = "3px";
objMask.style.display = "none";
};
objWrapper.addToDropZoneGrouping = function(strGroupingId, blnAllowSelf, blnAllowSelfParent) {
if (!qcodo.dropZoneGrouping[strGroupingId])
qcodo.dropZoneGrouping[strGroupingId] = new Array();
qcodo.dropZoneGrouping[strGroupingId][this.control.id] = this;
qcodo.dropZoneGrouping[strGroupingId]["__allowSelf"] = (blnAllowSelf) ? true : false;
qcodo.dropZoneGrouping[strGroupingId]["__allowSelfParent"] = (blnAllowSelfParent) ? true : false;
qcodo.registerControlDropZoneTarget(this.control);
};
objWrapper.removeFromDropZoneGrouping = function(strGroupingId) {
if (!qcodo.dropZoneGrouping[strGroupingId])
qcodo.dropZoneGrouping[strGroupingId] = new Array();
else
qcodo.dropZoneGrouping[strGroupingId][this.control.id] = false;
};
// Qcodo Shortcuts
objWrapper.a2DZG = objWrapper.addToDropZoneGrouping;
objWrapper.rfDZG = objWrapper.removeFromDropZoneGrouping;
};
///////////////////////////////////
// Block Control: DropZone Grouping
///////////////////////////////////
qcodo.dropZoneGrouping = new Array();
///////////////////////////////////////////
// Block Control: Move Handle Functionality
///////////////////////////////////////////
qcodo.registerControlMoveHandle = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
var objWrapper = objControl.wrapper;
if (!objWrapper.handle) {
qcodo.registerControlHandle(objControl, 'move');
// Assign Event Handlers
qcodo.enableMouseDrag();
objWrapper.handleMouseDown = function(objEvent, objHandle) {
// Set the Handle's MoveControls Bounding Box
this.setupBoundingBox();
// Calculate the offset (the top-left page coordinates of the bounding box vs. where the mouse is on the page)
this.offsetX = qcodo.page.x - this.boundingBox.x;
this.offsetY = qcodo.page.y - this.boundingBox.y;
this.startDragX = qcodo.page.x;
this.startDragY = qcodo.page.y;
// Clear MaskReturn Timeout (if applicable)
if (qcodo.moveHandleReset)
qcodo.moveHandleReset.resetMasksCancel();
// Make the Masks appear (if applicable)
for (var strKey in this.moveControls) {
var objMoveControl = this.moveControls[strKey];
var objMask = objMoveControl.mask;
var objAbsolutePosition = objMoveControl.getAbsolutePosition();
objMask.style.display = "block";
objMask.style.top = objAbsolutePosition.y + "px";
objMask.style.left = objAbsolutePosition.x + "px";
objMask.innerHTML = "";
};
return qcodo.terminateEvent(objEvent);
};
objWrapper.handleMouseMove = function(objEvent, objHandle) {
// Do We Scroll?
if ((qcodo.client.x <= 30) || (qcodo.client.y >= (qcodo.client.height - 30)) ||
(qcodo.client.y <= 30) || (qcodo.client.x >= (qcodo.client.width - 30))) {
qcodo.scrollMoveHandle = this;
qcodo.handleScroll();
} else {
// Clear Handle Timeout
qcodo.clearTimeout(objWrapper.id);
this.moveMasks();
};
return qcodo.terminateEvent(objEvent);
};
objWrapper.handleMouseUp = function(objEvent, objHandle) {
// Calculate Move Delta
var objMoveDelta = this.calculateMoveDelta();
var intDeltaX = objMoveDelta.x;
var intDeltaY = objMoveDelta.y;
// Stop Scrolling
qcodo.clearTimeout(this.id);
// Validate Drop Zone
var objDropControl;
if ((intDeltaX == 0) && (intDeltaY == 0)) {
// Nothing Moved!
objDropControl = null;
} else {
objDropControl = this.getDropTarget();
};
if (objDropControl) {
// Update everything that's moving (e.g. all controls in qcodo.moveControls)
for (var strKey in this.moveControls) {
var objWrapper = this.moveControls[strKey];
var objMask = objWrapper.mask;
objMask.style.display = "none";
objMask.style.cursor = null;
// qcodo.moveControls[strKey] = null;
objWrapper.updateStyle("position", "absolute");
// Get Control's Position
var objAbsolutePosition = objWrapper.getAbsolutePosition();
// Update Parent -- Wrapper now belongs to a new DropControl
if (objDropControl.nodeName.toLowerCase() == 'form') {
if (objWrapper.parentNode != objDropControl)
objWrapper.updateStyle("parent", objDropControl.id);
} else {
if (objDropControl.id != objWrapper.parentNode.parentNode.id)
objWrapper.updateStyle("parent", objDropControl.control.id);
};
// Update Control's Position
objWrapper.setAbsolutePosition(objAbsolutePosition.x + intDeltaX, objAbsolutePosition.y + intDeltaY, true);
if (objWrapper.updateHandle)
objWrapper.updateHandle(true, "move");
// Setup OnMove (if applicable)
if (objWrapper.control.getAttribute("onqcodomove")) {
objWrapper.control.qcodomove = function(strOnMoveCommand) {
eval(strOnMoveCommand);
};
objWrapper.control.qcodomove(objWrapper.control.getAttribute("onqcodomove"));
};
};
} else {
// Rejected
for (var strKey in this.moveControls) {
var objWrapper = this.moveControls[strKey];
var objMask = objWrapper.mask;
objMask.style.cursor = null;
};
if (objWrapper.updateHandle)
objWrapper.updateHandle(false, "move");
if (qcodo.isBrowser(this.IE))
this.resetMasks(intDeltaX, intDeltaY, 25);
else
this.resetMasks(intDeltaX, intDeltaY, 50);
};
// If we haven't moved at all, go ahead and run the control's onclick method
// (if applicable) or just propogate the click up
if ((intDeltaX == 0) && (intDeltaY == 0)) {
if (this.control.onclick)
return this.control.onclick(objEvent);
else
return true;
} else {
return qcodo.terminateEvent(objEvent);
};
};
// Setup Move Targets
objWrapper.moveControls = new Object();
objWrapper.registerMoveTarget = function(mixControl) {
// If they pass in null, then register itself as the move target
if (mixControl == null) mixControl = this.control;
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
var objTargetWrapper = objControl.wrapper;
if (objTargetWrapper)
this.moveControls[objControl.id] = objTargetWrapper;
// this.registerDropZone(objTargetWrapper.parentNode);
};
objWrapper.unregisterMoveTarget = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
if (objControl.id)
this.moveControls[objControl.id] = null;
};
objWrapper.clearMoveTargets = function() {
this.moveControls = new Object();
};
// Setup Drop Zones
objWrapper.registerDropZone = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
if (objControl.wrapper) {
qcodo.registerControlDropZoneTarget(objControl);
this.dropControls[objControl.id] = objControl.wrapper;
} else
this.dropControls[objControl.id] = objControl;
};
objWrapper.unregisterDropZone = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
this.dropControls[objControl.id] = null;
};
objWrapper.clearDropZones = function() {
this.dropControls = new Object();
};
objWrapper.clearDropZones();
objWrapper.registerDropZoneGrouping = function(strGroupingId) {
if (!qcodo.dropZoneGrouping[strGroupingId])
qcodo.dropZoneGrouping[strGroupingId] = new Array();
this.dropGroupings[strGroupingId] = true;
};
objWrapper.clearDropZoneGroupings = function() {
this.dropGroupings = new Object();
};
objWrapper.clearDropZoneGroupings();
// Mouse Delta Calculator
objWrapper.calculateMoveDelta = function() {
// Calculate Move Delta
var intDeltaX = qcodo.page.x - this.startDragX;
var intDeltaY = qcodo.page.y - this.startDragY;
intDeltaX = Math.min(Math.max(intDeltaX, -1 * this.boundingBox.x), qcodo.page.width - this.boundingBox.boundX);
intDeltaY = Math.min(Math.max(intDeltaY, -1 * this.boundingBox.y), qcodo.page.height - this.boundingBox.boundY);
return {x: intDeltaX, y: intDeltaY};
};
objWrapper.setupBoundingBox = function() {
// Calculate moveControls aggregate bounding box (x,y,width,height,boundX,boundY)
// Note that boundX is just (x + width), and boundY is just (y + height)
var intMinX = null;
var intMinY = null;
var intMaxX = null;
var intMaxY = null;
for (var strKey in this.moveControls) {
var objMoveControl = this.moveControls[strKey];
var objAbsolutePosition = objMoveControl.getAbsolutePosition();
if (intMinX == null) {
intMinX = objAbsolutePosition.x;
intMinY = objAbsolutePosition.y;
intMaxX = objAbsolutePosition.x + objMoveControl.offsetWidth;
intMaxY = objAbsolutePosition.y + objMoveControl.offsetHeight;
} else {
intMinX = Math.min(intMinX, objAbsolutePosition.x);
intMinY = Math.min(intMinY, objAbsolutePosition.y);
intMaxX = Math.max(intMaxX, objAbsolutePosition.x + objMoveControl.offsetWidth);
intMaxY = Math.max(intMaxY, objAbsolutePosition.y + objMoveControl.offsetHeight);
};
};
if (!this.boundingBox)
this.boundingBox = new Object();
this.boundingBox.x = intMinX;
this.boundingBox.y = intMinY;
this.boundingBox.boundX = intMaxX;
this.boundingBox.boundY = intMaxY;
this.boundingBox.width = intMaxX - intMinX;
this.boundingBox.height = intMaxY - intMinY;
};
objWrapper.updateBoundingBox = function() {
// Just like SETUP BoundingBox, except now we're using the MASKS instead of the Controls
// (in case, becuase of hte move, the size of the control may have changed/been altered)
var intMinX = null;
var intMinY = null;
var intMaxX = null;
var intMaxY = null;
for (var strKey in this.moveControls) {
var objMoveControl = this.moveControls[strKey];
var objAbsolutePosition = objMoveControl.getAbsolutePosition();
if (intMinX == null) {
intMinX = objAbsolutePosition.x;
intMinY = objAbsolutePosition.y;
intMaxX = objAbsolutePosition.x + objMoveControl.mask.offsetWidth;
intMaxY = objAbsolutePosition.y + objMoveControl.mask.offsetHeight;
} else {
intMinX = Math.min(intMinX, objAbsolutePosition.x);
intMinY = Math.min(intMinY, objAbsolutePosition.y);
intMaxX = Math.max(intMaxX, objAbsolutePosition.x + objMoveControl.mask.offsetWidth);
intMaxY = Math.max(intMaxY, objAbsolutePosition.y + objMoveControl.mask.offsetHeight);
};
};
this.boundingBox.x = intMinX;
this.boundingBox.y = intMinY;
this.boundingBox.boundX = intMaxX;
this.boundingBox.boundY = intMaxY;
this.boundingBox.width = intMaxX - intMinX;
this.boundingBox.height = intMaxY - intMinY;
};
objWrapper.moveMasks = function() {
// Calculate Move Delta
var objMoveDelta = this.calculateMoveDelta();
var intDeltaX = objMoveDelta.x;
var intDeltaY = objMoveDelta.y;
var blnValidDropZone = this.validateDropZone();
if (blnValidDropZone)
this.handle.style.cursor = "url(" + qc.imageAssets + "/_core/move_drop.cur), auto";
else
this.handle.style.cursor = "url(" + qc.imageAssets + "/_core/move_nodrop.cur), auto";
// Update Everything that's Moving (e.g. all controls in qcodo.moveControls)
for (var strKey in this.moveControls) {
var objWrapper = this.moveControls[strKey];
var objMask = objWrapper.mask;
// Fixes a weird Firefox bug
if (objMask.innerHTML == "")
objMask.innerHTML = ".";
if (objMask.innerHTML == ".")
objMask.innerHTML = objWrapper.innerHTML.replace(' id="', ' id="invalid_mask_');
// Recalculate Widths
this.updateBoundingBox();
// Move this control's mask
objWrapper.setMaskOffset(intDeltaX, intDeltaY);
if (blnValidDropZone) {
objMask.style.cursor = "url(" + qc.imageAssets + "/_core/move_drop.cur), auto";
} else {
objMask.style.cursor = "url(" + qc.imageAssets + "/_core/move_nodrop.cur), auto";
};
};
};
objWrapper.getDropZoneControlWrappers = function() {
var arrayToReturn = new Array();
for (var strDropKey in this.dropControls) {
var objDropWrapper = this.dropControls[strDropKey];
if (objDropWrapper)
arrayToReturn[strDropKey] = objDropWrapper;
};
for (var strGroupingId in this.dropGroupings) {
if (this.dropGroupings[strGroupingId]) for (var strControlId in qcodo.dropZoneGrouping[strGroupingId]) {
if (strControlId.substring(0, 1) != "_") {
var objDropWrapper = qcodo.dropZoneGrouping[strGroupingId][strControlId];
if (objDropWrapper) {
if (objDropWrapper.control.id == objWrapper.control.id) {
if (qcodo.dropZoneGrouping[strGroupingId]["__allowSelf"])
arrayToReturn[strControlId] = objDropWrapper;
} else if (objDropWrapper.control.id == objWrapper.parentNode.id) {
if (qcodo.dropZoneGrouping[strGroupingId]["__allowSelfParent"])
arrayToReturn[strControlId] = objDropWrapper;
} else {
arrayToReturn[strControlId] = objDropWrapper;
};
};
};
};
};
return arrayToReturn;
};
objWrapper.validateDropZone = function() {
var blnFoundTarget = false;
var blnFormOkay = false;
var dropControls = this.getDropZoneControlWrappers();
for (var strDropKey in dropControls) {
var objDropWrapper = dropControls[strDropKey];
if (objDropWrapper) {
if (objDropWrapper.nodeName.toLowerCase() == 'form') {
blnFormOkay = true;
} else if (objDropWrapper.containsPoint(qcodo.page.x, qcodo.page.y)) {
if (blnFoundTarget) {
objDropWrapper.dropZoneMask.style.display = "none";
} else {
objDropWrapper.dropZoneMask.style.display = "block";
var objAbsolutePosition = objDropWrapper.getAbsolutePosition();
if (qcodo.isBrowser(qcodo.IE) && (window.document.compatMode == "BackCompat")) {
objDropWrapper.dropZoneMask.style.width = Math.max(7, objDropWrapper.control.offsetWidth) + "px";
objDropWrapper.dropZoneMask.style.height = Math.max(7, objDropWrapper.control.offsetHeight) + "px";
// if (objDropWrapper.style.position == 'absolute') {
var objAbsolutePosition = objDropWrapper.getAbsolutePosition();
// objDropWrapper.setDropZoneMaskAbsolutePosition(objAbsolutePosition.x + 10, objAbsolutePosition.y + 10);
objDropWrapper.setDropZoneMaskAbsolutePosition(objAbsolutePosition.x, objAbsolutePosition.y);
// };
} else {
objDropWrapper.dropZoneMask.style.width = Math.max(1, objDropWrapper.control.offsetWidth - 6) + "px";
objDropWrapper.dropZoneMask.style.height = Math.max(1, objDropWrapper.control.offsetHeight - 6) + "px";
// if (objDropWrapper.style.position != 'absolute') {
var objAbsolutePosition = objDropWrapper.getAbsolutePosition();
objDropWrapper.setDropZoneMaskAbsolutePosition(objAbsolutePosition.x, objAbsolutePosition.y);
// }
};
blnFoundTarget = true;
};
} else {
objDropWrapper.dropZoneMask.style.display = "none";
};
};
};
return (blnFoundTarget || blnFormOkay);
};
// Will return "NULL" if there was no target found
// Could also return the Form if not dropped on any valid target BUT tbe Form is still a drop zone
objWrapper.getDropTarget = function() {
var objForm = null;
var objToReturn = null;
var dropControls = this.getDropZoneControlWrappers();
for (var strDropKey in dropControls) {
var objDropWrapper = dropControls[strDropKey];
if (objDropWrapper) {
if (objDropWrapper.nodeName.toLowerCase() == 'form')
objForm = objDropWrapper;
else if (objDropWrapper.containsPoint(qcodo.page.x, qcodo.page.y)) {
objDropWrapper.dropZoneMask.style.display = "none";
if (!objToReturn)
objToReturn = objDropWrapper;
};
};
};
if (objToReturn)
return objToReturn;
if (objForm)
return objForm;
return null;
};
objWrapper.resetMasks = function(intDeltaX, intDeltaY, intSpeed) {
qcodo.moveHandleReset = this;
if (intDeltaX || intDeltaY) {
this.resetCurrentOffsetX = intDeltaX * 1.0;
this.resetCurrentOffsetY = intDeltaY * 1.0;
var fltTotalMove = Math.sqrt(Math.pow(intDeltaX, 2) + Math.pow(intDeltaY, 2));
var fltRatio = (intSpeed * 1.0) / fltTotalMove;
this.resetStepX = fltRatio * intDeltaX;
this.resetStepY = fltRatio * intDeltaY;
qcodo.setTimeout("move_mask_return", "qcodo.wrappers['" + this.id + "'].resetMaskHelper()", 10);
};
};
objWrapper.resetMaskHelper = function() {
if (this.resetCurrentOffsetX < 0)
this.resetCurrentOffsetX = Math.min(this.resetCurrentOffsetX - this.resetStepX, 0);
else
this.resetCurrentOffsetX = Math.max(this.resetCurrentOffsetX - this.resetStepX, 0);
if (this.resetCurrentOffsetY < 0)
this.resetCurrentOffsetY = Math.min(this.resetCurrentOffsetY - this.resetStepY, 0);
else
this.resetCurrentOffsetY = Math.max(this.resetCurrentOffsetY - this.resetStepY, 0);
for (var strKey in this.moveControls) {
var objWrapper = this.moveControls[strKey];
objWrapper.setMaskOffset(this.resetCurrentOffsetX, this.resetCurrentOffsetY);
if ((this.resetCurrentOffsetX == 0) && (this.resetCurrentOffsetY == 0)) {
objWrapper.mask.style.display = "none";
};
};
if ((this.resetCurrentOffsetX != 0) || (this.resetCurrentOffsetY != 0))
qcodo.setTimeout("move_mask_return", "qcodo.wrappers['" + this.id + "'].resetMaskHelper()", 10);
else
qcodo.moveHandleReset = null;
};
objWrapper.resetMasksCancel = function() {
qcodo.clearTimeout("move_mask_return");
qcodo.moveHandleReset = null;
for (var strKey in this.moveControls) {
var objWrapper = this.moveControls[strKey];
objWrapper.mask.style.display = "none";
};
};
// Wrapper Shortcuts
objWrapper.regMT = objWrapper.registerMoveTarget;
objWrapper.regDZ = objWrapper.registerDropZone;
objWrapper.regDZG = objWrapper.registerDropZoneGrouping;
} else {
objWrapper.updateHandle();
};
};
qcodo.animateMove = function(mixControl, intDestinationX, intDestinationY, intSpeed) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
// Record Destination Coordinates
objControl.destinationX = intDestinationX;
objControl.destinationY = intDestinationY;
// Get Starting Coordinates
var objAbsolutePosition = qcodo.getAbsolutePosition(objControl);
objControl.currentX = objAbsolutePosition.x * 1.0;
objControl.currentY = objAbsolutePosition.y * 1.0;
// Calculate the amount to move in the X- and Y- direction per step
var fltTotalMove = Math.sqrt(Math.pow(objControl.destinationY - objControl.currentY, 2) + Math.pow(objControl.destinationX - objControl.currentX, 2));
var fltTotalMoveX = (objControl.destinationX * 1.0) - objControl.currentX;
var fltTotalMoveY = (objControl.destinationY * 1.0) - objControl.currentY;
objControl.stepMoveX = ((intSpeed * 1.0) / fltTotalMove) * fltTotalMoveX;
objControl.stepMoveY = ((intSpeed * 1.0) / fltTotalMove) * fltTotalMoveY;
qcodo.setTimeout(objControl, "qcodo.handleAnimateMove('" + objControl.id + "');", 10);
};
qcodo.handleAnimateMove = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
// Update Current Coordinates
if (objControl.stepMoveX < 0)
objControl.currentX = Math.max(objControl.destinationX, objControl.currentX + objControl.stepMoveX);
else
objControl.currentX = Math.min(objControl.destinationX, objControl.currentX + objControl.stepMoveX);
if (objControl.stepMoveY < 0)
objControl.currentY = Math.max(objControl.destinationY, objControl.currentY + objControl.stepMoveY);
else
objControl.currentY = Math.min(objControl.destinationY, objControl.currentY + objControl.stepMoveY);
qcodo.setAbsolutePosition(objControl, Math.round(objControl.currentX), Math.round(objControl.currentY));
if ((Math.round(objControl.currentX) == objControl.destinationX) &&
(Math.round(objControl.currentY) == objControl.destinationY)) {
// We are done
if (objControl.handleAnimateComplete)
objControl.handleAnimateComplete(objControl);
} else {
// Do it again
qcodo.setTimeout(objControl, "qcodo.handleAnimateMove('" + objControl.id + "');", 10);
};
};
qcodo.handleScroll = function() {
var objHandle = qcodo.scrollMoveHandle;
// Clear Timeout
qcodo.clearTimeout(objHandle.id);
// How much to scroll by
var intScrollByX = 0;
var intScrollByY = 0;
// Calculate our ScrollByY amount
if (qcodo.client.y <= 30) {
var intDivisor = (qcodo.isBrowser(qcodo.IE)) ? 1.5 : 3;
intScrollByY = Math.round((qcodo.client.y - 30) / intDivisor);
} else if (qcodo.client.y >= (qcodo.client.height - 30)) {
var intDivisor = (qcodo.isBrowser(qcodo.IE)) ? 1.5 : 3;
intScrollByY = Math.round((qcodo.client.y - (qcodo.client.height - 30)) / intDivisor);
};
// Calculate our ScrollByX amount
if (qcodo.client.x <= 30) {
var intDivisor = (qcodo.isBrowser(qcodo.IE)) ? 1 : 2;
intScrollByX = Math.round((qcodo.client.x - 30) / intDivisor);
} else if (qcodo.client.x >= (qcodo.client.width - 30)) {
var intDivisor = (qcodo.isBrowser(qcodo.IE)) ? 1 : 2;
intScrollByX = Math.round((qcodo.client.x - (qcodo.client.width - 30)) / intDivisor);
};
// Limit ScrollBy amounts (dependent on current scroll and scroll.max's)
if (intScrollByX < 0) {
// Scroll to Left
intScrollByX = Math.max(intScrollByX, 0 - qcodo.scroll.x);
} else if (intScrollByX > 0) {
// Scroll to Right
intScrollByX = Math.min(intScrollByX, qcodo.scroll.width - qcodo.scroll.x);
};
if (intScrollByY < 0) {
// Scroll to Left
intScrollByY = Math.max(intScrollByY, 0 - qcodo.scroll.y);
} else if (intScrollByY > 0) {
// Scroll to Right
intScrollByY = Math.min(intScrollByY, qcodo.scroll.height - qcodo.scroll.y);
};
// Perform the Scroll
window.scrollBy(intScrollByX, intScrollByY);
// Update Event Stats
qcodo.handleEvent(null);
// Update Handle Offset
objHandle.offsetX -= intScrollByX;
objHandle.offsetY -= intScrollByY;
objHandle.moveMasks();
if (intScrollByX || intScrollByY)
qcodo.setTimeout(objHandle.id, "qcodo.handleScroll()", 25);
};
//////////////////
// Qcodo Shortcuts
//////////////////
qc.regCM = qcodo.registerControlMoveable;
qc.regCMH = qcodo.registerControlMoveHandle;
/////////////////////////////////////////////
// Block Control: Resize Handle functionality
/////////////////////////////////////////////
qcodo.registerControlResizeHandle = function(mixControl, blnVertical) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
var objWrapper = objControl.wrapper;
objWrapper.resizeHandle = true;
objWrapper.resizeDirectionVertical = blnVertical;
objWrapper.resizeUpperControls = new Array();
objWrapper.resizeLowerControls = new Array();
if (!objWrapper.handle) {
if (qcodo.isBrowser(qcodo.SAFARI))
qcodo.registerControlHandle(objControl, 'move');
else if (qcodo.isBrowser(qcodo.IE)) {
if (objWrapper.resizeDirectionVertical)
qcodo.registerControlHandle(objControl, 'row-resize');
else
qcodo.registerControlHandle(objControl, 'col-resize');
} else {
if (objWrapper.resizeDirectionVertical)
qcodo.registerControlHandle(objControl, 'ns-resize');
else
qcodo.registerControlHandle(objControl, 'ew-resize');
};
// Assign Event Handlers
qcodo.enableMouseDrag();
objWrapper.handleMouseDown = function(objEvent, objHandle) {
this.startUpperSizes = new Array();
this.startLowerSizes = new Array();
this.startLowerPositions = new Array();
if (this.resizeDirectionVertical) {
this.offsetY = qcodo.page.y - this.getAbsolutePosition().y;
this.startDragY = qcodo.page.y;
for (var intIndex = 0; intIndex < this.resizeUpperControls.length; intIndex++) {
var objUpperControl = this.resizeUpperControls[intIndex];
this.startUpperSizes[intIndex] = eval(objUpperControl.control.style.height.replace(/px/, ""));
};
for (var intIndex = 0; intIndex < this.resizeLowerControls.length; intIndex++) {
var objLowerControl = this.resizeLowerControls[intIndex];
this.startLowerPositions[intIndex] = objLowerControl.getAbsolutePosition().y;
this.startLowerSizes[intIndex] = eval(objLowerControl.control.style.height.replace(/px/, ""));
};
if (this.resizeMinimum != null)
this.resizeMinimumY = this.getAbsolutePosition().y - (this.offsetTop - this.resizeMinimum);
else
this.resizeMinimumY = null;
if (this.resizeMaximum != null)
this.resizeMaximumY = this.getAbsolutePosition().y - (this.offsetTop - this.resizeMaximum);
else
this.resizeMaximumY = null;
} else {
this.offsetX = qcodo.page.x - this.getAbsolutePosition().x;
this.startDragX = qcodo.page.x;
for (var intIndex = 0; intIndex < this.resizeUpperControls.length; intIndex++) {
var objUpperControl = this.resizeUpperControls[intIndex];
this.startUpperSizes[intIndex] = eval(objUpperControl.control.style.width.replace(/px/, ""));
};
for (var intIndex = 0; intIndex < this.resizeLowerControls.length; intIndex++) {
var objLowerControl = this.resizeLowerControls[intIndex];
this.startLowerPositions[intIndex] = objLowerControl.getAbsolutePosition().x;
this.startLowerSizes[intIndex] = eval(objLowerControl.control.style.width.replace(/px/, ""));
};
if (this.resizeMinimum != null)
this.resizeMinimumX = this.getAbsolutePosition().x - (this.offsetLeft - this.resizeMinimum);
else
this.resizeMinimumX = null;
if (this.resizeMaximum != null)
this.resizeMaximumX = this.getAbsolutePosition().x - (this.offsetLeft - this.resizeMaximum);
else
this.resizeMaximumX = null;
};
return qcodo.terminateEvent(objEvent);
};
objWrapper.handleMouseMove = function(objEvent, objHandle) {
if (this.resizeDirectionVertical) {
var intNewY = qcodo.page.y - this.offsetY;
if (this.resizeMinimumY != null)
intNewY = Math.max(intNewY, this.resizeMinimumY);
if (this.resizeMaximumY != null)
intNewY = Math.min(intNewY, this.resizeMaximumY);
var intDeltaY = intNewY - this.startDragY + this.offsetY;
// Update ResizeHandle's Position
this.setAbsolutePosition(this.getAbsolutePosition().x, intNewY);
// Resize Upper Controls
for (var intIndex = 0; intIndex < this.resizeUpperControls.length; intIndex++) {
var objUpperControl = this.resizeUpperControls[intIndex];
objUpperControl.updateStyle("height", this.startUpperSizes[intIndex] + intDeltaY + "px");
};
// Reposition Lower Controls
for (var intIndex = 0; intIndex < this.resizeLowerControls.length; intIndex++) {
var objLowerControl = this.resizeLowerControls[intIndex];
objLowerControl.setAbsolutePosition(
objLowerControl.getAbsolutePosition().x,
this.startLowerPositions[intIndex] + intDeltaY);
objLowerControl.updateStyle("height", this.startLowerSizes[intIndex] - intDeltaY + "px");
};
} else {
var intNewX = qcodo.page.x - this.offsetX;
if (this.resizeMinimumX != null)
intNewX = Math.max(intNewX, this.resizeMinimumX);
if (this.resizeMaximumX != null)
intNewX = Math.min(intNewX, this.resizeMaximumX);
var intDeltaX = intNewX - this.startDragX + this.offsetX;
// Update ResizeHandle's Position
this.setAbsolutePosition(intNewX, this.getAbsolutePosition().y);
// Resize Upper Controls
for (var intIndex = 0; intIndex < this.resizeUpperControls.length; intIndex++) {
var objUpperControl = this.resizeUpperControls[intIndex];
objUpperControl.updateStyle("width", this.startUpperSizes[intIndex] + intDeltaX + "px");
};
// Reposition Lower Controls
for (var intIndex = 0; intIndex < this.resizeLowerControls.length; intIndex++) {
var objLowerControl = this.resizeLowerControls[intIndex];
objLowerControl.setAbsolutePosition(
this.startLowerPositions[intIndex] + intDeltaX,
objLowerControl.getAbsolutePosition().y);
objLowerControl.updateStyle("width", this.startLowerSizes[intIndex] - intDeltaX + "px");
};
};
// Update Handle Position
this.updateHandle(false);
return qcodo.terminateEvent(objEvent);
};
objWrapper.handleMouseUp = function(objEvent, objHandle) {
// See if we've even resized at all
var blnResized = true;
if (this.resizeDirectionVertical) {
if (this.startDragY == qcodo.page.y)
blnResized = false;
} else {
if (this.startDragX == qcodo.page.x)
blnResized = false;
};
if (blnResized) {
this.updateHandle(true);
// Setup OnResize (if applicable)
if (this.control.getAttribute("onqcodoresize")) {
this.control.qcodoresize = function(strOnResizeCommand) {
eval(strOnResizeCommand);
};
this.control.qcodoresize(this.control.getAttribute("onqcodoresize"));
};
return qcodo.terminateEvent(objEvent);
} else {
// If we haven't resized at all, go ahead and run the control's onclick method
// (if applicable) or just propogate the click up
if (this.control.onclick)
return this.control.onclick(objEvent);
else
return true;
};
};
objWrapper.setUpperControl = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
var objWrapper = objControl.wrapper;
this.resizeUpperControls[this.resizeUpperControls.length] = objWrapper;
};
objWrapper.setLowerControl = function(mixControl) {
var objControl; if (!(objControl = qcodo.getControl(mixControl))) return;
var objWrapper = objControl.wrapper;
this.resizeLowerControls[this.resizeLowerControls.length] = objWrapper;
};
objWrapper.resizeMinimum = null;
objWrapper.resizeMaximum = null;
objWrapper.setResizeMinimum = function(intMinimum) {
this.resizeMinimum = intMinimum;
};
objWrapper.setResizeMaximum = function(intMaximum) {
this.resizeMaximum = intMaximum;
};
// Wrapper Shortcuts
objWrapper.setUC = objWrapper.setUpperControl;
objWrapper.setLC = objWrapper.setLowerControl;
objWrapper.setReMi = objWrapper.setResizeMinimum;
objWrapper.setReMa = objWrapper.setResizeMaximum;
} else {
objWrapper.updateHandle();
};
};
//////////////////
// Qcodo Shortcuts
//////////////////
qc.regCRH = qcodo.registerControlResizeHandle;
// This function hides the toggle menu if it is being displayed
function clickWindow(toggleMenuId) {
var objToggleMenu = document.getElementById(toggleMenuId);
if (objToggleMenu.parentNode.style.display != 'none') {
qc.getW(toggleMenuId).toggleDisplay('hide');
}
}
// This function repositions the toggle menu when the window is resized
function resizeWindow(toggleMenuId, toggleButtonId) {
var objToggleMenu = document.getElementById(toggleMenuId);
if (objToggleMenu.parentNode.style.display != 'none') {
setPosition(toggleButtonId, toggleMenuId);
}
}
// This function is run when the ColumnToggleButton is clicked
// Positions and Displays the column toggle menu
function toggleColumnToggleDisplay(e, toggleMenuId, toggleButtonId) {
// Set the position of the toggle menu based on the location of the menu button
setPosition(toggleButtonId, toggleMenuId);
// Display/Hide the column toggle menu
qc.getW(toggleMenuId).toggleDisplay();
var objToggleMenu = document.getElementById(toggleMenuId);
// Set the onresize and onclick event handlers only when the menu is being displayed to avoid unnecessarily running the function
if (objToggleMenu.parentNode.style.display != 'none') {
function r() {
resizeWindow(toggleMenuId, toggleButtonId);
}
window.onresize = r;
function c() {
clickWindow(toggleMenuId);
}
window.document.onclick = c;
}
// Set event handlers to null when menu is not being displayed
else {
window.onresize = null;
window.document.onclick = null;
}
// Stop bubbling up and propagation down in events so that functions don't get run more than once
// This was specifically because setPosition was getting run from the window.onClick() event and from clicking on the button
if (!e) { var e = window.event; }
e.cancelBubble = true;
if (e.stopPropagation) { e.stopPropagation(); }
}
// Based on the position of the button (strLabelControlId), this positions the column toggle menu (strPanelControlId)
function setPosition(strLabelControlId, strPanelControlId) {
var objLabel = document.getElementById(strLabelControlId);
var arrCurrentLabelPosition = findPosition(objLabel.offsetParent);
var objToggleMenu = document.getElementById(strPanelControlId);
var strMenuWidth = objToggleMenu.offsetWidth;
// The menu width will be 0 when it is first rendered as display: none. This uses it's style parameters to calculate what it's width will be
// This was necessary in order to be able to set the position of the menu before it was displayed, to avoid a scrollbar flicker.
if (strMenuWidth==0) {
strMenuWidth = getWidth(objToggleMenu);
}
objToggleMenu.style.position = 'absolute';
objToggleMenu.style.left = (arrCurrentLabelPosition[0] + objLabel.offsetParent.offsetWidth - strMenuWidth) + 'px';
objToggleMenu.style.top = (arrCurrentLabelPosition[1] + objLabel.offsetParent.offsetHeight) + 'px';
}
// This function finds the absolute position of and element in pixels by drilling down through all parent elements and summing all left and top offsets.
function findPosition(obj) {
var current_top = 0;
var current_left = 0;
if (obj.offsetParent) {
current_left = obj.offsetLeft;
current_top = obj.offsetTop;
while (obj = obj.offsetParent) {
current_left += obj.offsetLeft;
current_top += obj.offsetTop;
}
}
return [current_left,current_top];
}
function getWidth(obj) {
var strWidth = 0;
var intWidth = parseInt(obj.style.width);
var intPaddingLeft = parseInt(obj.style.paddingLeft);
var intPaddingRight = parseInt(obj.style.paddingRight);
var intBorderLeftWidth = parseInt(obj.style.borderLeftWidth);
var intBorderRightWidth = parseInt(obj.style.borderRightWidth);
strWidth += (!isNaN(intWidth)) ? intWidth : 0;
strWidth += (!isNaN(intPaddingLeft)) ? intPaddingLeft : 0;
strWidth += (!isNaN(intPaddingRight)) ? intPaddingRight : 0;
strWidth += (!isNaN(intBorderLeftWidth)) ? intBorderLeftWidth : 0;
strWidth += (!isNaN(intBorderRightWidth)) ? intBorderRightWidth : 0;
return strWidth;
}
function __resetListBox(strFormId, strControlId) {
var objListBox = document.forms[strFormId].elements[strControlId];
objListBox.selectedIndex = -1;
if (objListBox.onchange)
objListBox.onchange();
}; function Qcodo__DateTimePicker_Change(strControlId, objListbox) {
var objMonth = document.getElementById(strControlId + "_lstMonth");
var objDay = document.getElementById(strControlId + "_lstDay");
var objYear = document.getElementById(strControlId + "_lstYear");
if (objListbox.options[objListbox.selectedIndex].value == "") {
objMonth.selectedIndex = 0;
objYear.selectedIndex = 0;
while(objDay.options.length)
objDay.options[objDay.options.length - 1] = null;
objDay.options[0] = new Option("--", "");
objDay.selectedIndex = 0;
} else {
if ((objListbox == objMonth) || ((objListbox == objYear) && (objMonth.options[objMonth.selectedIndex].value == 2))) {
var intCurrentDay = objDay.options[objDay.selectedIndex].value;
var intCurrentMaxDay = objDay.options[objDay.options.length - 1].value;
// Calculate new Max Day
var intNewMaxDay = 0;
var intSelectedMonth = objMonth.options[objMonth.selectedIndex].value;
var intSelectedYear = new Number(objYear.options[objYear.selectedIndex].value);
if (!intSelectedYear)
intSelectedYear = 2000;
switch (intSelectedMonth) {
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":
intNewMaxDay = 31;
break;
case "4":
case "6":
case "9":
case "11":
intNewMaxDay = 30;
break;
case "2":
if ((intSelectedYear % 4) != 0)
intNewMaxDay = 28;
else if ((intSelectedYear % 1000) == 0)
intNewMaxDay = 29;
else if ((intSelectedYear % 100) == 0)
intNewMaxDay = 28;
else
intNewMaxDay = 29;
break;
};
if (intNewMaxDay != intCurrentMaxDay) {
// Redo the Days Dropdown
var blnRequired = true;
if (objDay.options[0].value == "")
blnRequired = false;
while (objDay.options.length)
objDay.options[objDay.options.length - 1] = null;
if (!blnRequired)
objDay.options[0] = new Option("--", "");
for (var intDay = 1; intDay <= intNewMaxDay; intDay++) {
objDay.options[objDay.options.length] = new Option(intDay, intDay);
};
intCurrentDay = Math.min(intCurrentDay, intNewMaxDay);
if (blnRequired)
objDay.options[intCurrentDay - 1].selected = true;
else
objDay.options[intCurrentDay].selected = true;
};
};
};
}; | heshuai64/einv2 | js/_core/_tracmor.src.js | JavaScript | gpl-2.0 | 90,784 |
<?php
/**
* Aliases for special pages
*
* @file
* @ingroup Extensions
*/
$specialPageAliases = [];
/** English (English) */
$specialPageAliases['en'] = [
'PrivateDomains' => [ 'PrivateDomains' ],
];
/** Serbian Cyrillic (српски (ћирилица)) */
$specialPageAliases['sr-ec'] = [
'PrivateDomains' => [ 'ПриватниДомени' ],
];
/** Serbian Latin (srpski (latinica)) */
$specialPageAliases['sr-el'] = [
'PrivateDomains' => [ 'PrivatniDomeni' ],
];
| wikimedia/mediawiki-extensions-PrivateDomains | PrivateDomains.alias.php | PHP | gpl-2.0 | 480 |
include ../../../Makefile.inc
CLC_ROOT = ../../../inc
all: exe_src exe_src_m2s exe_bin amd_compile m2c_compile run_m2s run_native check_result
exe_src:
@-$(CC) $(CC_FLAG) *src.c -o exe_src $(CC_INC) $(CC_LIB) > relational_greater_than_long4long4.exe_src.log 2>&1
exe_src_m2s:
@-$(CC) $(CC_FLAG) -m32 *src.c -o exe_src_m2s $(CC_INC) $(M2S_LIB) > relational_greater_than_long4long4.exe_src_m2s.log 2>&1
exe_bin:
@-$(CC) $(CC_FLAG) *bin.c -o exe_bin $(CC_INC) $(CC_LIB) > relational_greater_than_long4long4.exe_bin.log 2>&1
amd_compile:
@-$(AMD_CC) --amd --amd-dump-all --amd-device 11 relational_greater_than_long4long4.cl > relational_greater_than_long4long4.amdcc.log 2>&1
@-rm -rf /tmp/*.clp && rm -rf /tmp/*_amd_files
m2c_compile:
@-python compile.py
run_m2s:
@-M2S_OPENCL_BINARY=./relational_greater_than_long4long4.opt.bin $(M2S) --si-sim functional ./exe_src_m2s > m2s.log 2>&1
run_native:
@-./exe_src > native.log 2>&1
check_result:
@-diff exe_src.result exe_src_m2s.result > check.log 2>&1
clean:
rm -rf exe_src exe_src_m2s exe_bin *.ll *.log *files *bin *.s *.bc *.result
| xianggong/m2c_unit_test | test/operator/relational_greater_than_long4long4/Makefile | Makefile | gpl-2.0 | 1,101 |
/* Cabal - Legacy Game Implementations
*
* Cabal is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
// Based on the ScummVM (GPLv2+) file of the same name
#include "common/scummsys.h"
#include "common/rect.h"
#include "common/endian.h"
#include "common/stream.h"
#include "common/substream.h"
#include "common/system.h"
#include "common/textconsole.h"
#include "common/types.h"
#include "common/util.h"
#include "video/coktel_decoder.h"
#include "image/codecs/indeo3.h"
#ifdef VIDEO_COKTELDECODER_H
#include "audio/audiostream.h"
#include "audio/decoders/pcm.h"
#include "audio/decoders/adpcm_intern.h"
#include "common/memstream.h"
static const uint32 kVideoCodecIndeo3 = MKTAG('i','v','3','2');
namespace Video {
CoktelDecoder::State::State() : flags(0), speechId(0) {
}
CoktelDecoder::CoktelDecoder(Audio::Mixer *mixer, Audio::Mixer::SoundType soundType) :
_mixer(mixer), _soundType(soundType), _width(0), _height(0), _x(0), _y(0),
_defaultX(0), _defaultY(0), _features(0), _frameCount(0), _paletteDirty(false),
_ownSurface(true), _frameRate(12), _hasSound(false), _soundEnabled(false),
_soundStage(kSoundNone), _audioStream(0), _startTime(0), _pauseStartTime(0),
_isPaused(false) {
assert(_mixer);
memset(_palette, 0, 768);
}
CoktelDecoder::~CoktelDecoder() {
}
bool CoktelDecoder::evaluateSeekFrame(int32 &frame, int whence) const {
if (!isVideoLoaded())
// Nothing to do
return false;
// Find the frame to which to seek
if (whence == SEEK_CUR)
frame += _curFrame;
else if (whence == SEEK_END)
frame = _frameCount - frame - 1;
else if (whence == SEEK_SET)
frame--;
else
return false;
if ((frame < -1) || (frame >= ((int32) _frameCount)))
// Out of range
return false;
return true;
}
void CoktelDecoder::setSurfaceMemory(void *mem, uint16 width, uint16 height, uint8 bpp) {
freeSurface();
if (!hasVideo())
return;
// Sanity checks
assert((width > 0) && (height > 0));
assert(bpp == getPixelFormat().bytesPerPixel);
// Create a surface over this memory
// TODO: Check whether it is fine to assume we want the setup PixelFormat.
_surface.init(width, height, width * bpp, mem, getPixelFormat());
_ownSurface = false;
}
void CoktelDecoder::setSurfaceMemory() {
freeSurface();
createSurface();
_ownSurface = true;
}
const Graphics::Surface *CoktelDecoder::getSurface() const {
if (!isVideoLoaded())
return 0;
return &_surface;
}
bool CoktelDecoder::hasSurface() {
return _surface.getPixels();
}
void CoktelDecoder::createSurface() {
if (hasSurface())
return;
if (!hasVideo())
return;
if ((_width > 0) && (_height > 0))
_surface.create(_width, _height, getPixelFormat());
_ownSurface = true;
}
void CoktelDecoder::freeSurface() {
if (!_ownSurface) {
_surface.w = 0;
_surface.h = 0;
_surface.pitch = 0;
_surface.setPixels(0);
_surface.format = Graphics::PixelFormat();
} else
_surface.free();
_ownSurface = true;
}
void CoktelDecoder::setXY(uint16 x, uint16 y) {
_x = x;
_y = y;
}
void CoktelDecoder::setXY() {
setXY(_defaultX, _defaultY);
}
void CoktelDecoder::setFrameRate(Common::Rational frameRate) {
_frameRate = frameRate;
}
uint16 CoktelDecoder::getDefaultX() const {
return _defaultX;
}
uint16 CoktelDecoder::getDefaultY() const {
return _defaultY;
}
const Common::List<Common::Rect> &CoktelDecoder::getDirtyRects() const {
return _dirtyRects;
}
bool CoktelDecoder::hasPalette() const {
return (_features & kFeaturesPalette) != 0;
}
bool CoktelDecoder::hasVideo() const {
return true;
}
bool CoktelDecoder::hasSound() const {
return _hasSound;
}
bool CoktelDecoder::isSoundEnabled() const {
return _soundEnabled;
}
bool CoktelDecoder::isSoundPlaying() const {
return _audioStream && _mixer->isSoundHandleActive(_audioHandle);
}
void CoktelDecoder::enableSound() {
if (!hasSound() || isSoundEnabled())
return;
// Sanity check
if (_mixer->getOutputRate() == 0)
return;
// Only possible on the first frame
if (_curFrame > -1)
return;
_soundEnabled = true;
}
void CoktelDecoder::disableSound() {
if (_audioStream) {
if ((_soundStage == kSoundPlaying) || (_soundStage == kSoundFinished)) {
_audioStream->finish();
_mixer->stopHandle(_audioHandle);
}
delete _audioStream;
}
_soundEnabled = false;
_soundStage = kSoundNone;
_audioStream = 0;
}
void CoktelDecoder::finishSound() {
if (!_audioStream)
return;
_audioStream->finish();
_soundStage = kSoundFinished;
}
void CoktelDecoder::colorModeChanged() {
}
bool CoktelDecoder::getFrameCoords(int16 frame, int16 &x, int16 &y, int16 &width, int16 &height) {
return false;
}
bool CoktelDecoder::hasEmbeddedFiles() const {
return false;
}
bool CoktelDecoder::hasEmbeddedFile(const Common::String &fileName) const {
return false;
}
Common::SeekableReadStream *CoktelDecoder::getEmbeddedFile(const Common::String &fileName) const {
return 0;
}
int32 CoktelDecoder::getSubtitleIndex() const {
return -1;
}
bool CoktelDecoder::isPaletted() const {
return true;
}
int CoktelDecoder::getCurFrame() const {
return _curFrame;
}
void CoktelDecoder::close() {
disableSound();
freeSurface();
_x = 0;
_y = 0;
_defaultX = 0;
_defaultY = 0;
_features = 0;
_curFrame = -1;
_frameCount = 0;
_startTime = 0;
_hasSound = false;
_isPaused = false;
}
Audio::Mixer::SoundType CoktelDecoder::getSoundType() const {
return _soundType;
}
Audio::AudioStream *CoktelDecoder::getAudioStream() const {
return _audioStream;
}
uint16 CoktelDecoder::getWidth() const {
return _width;
}
uint16 CoktelDecoder::getHeight() const {
return _height;
}
uint32 CoktelDecoder::getFrameCount() const {
return _frameCount;
}
const byte *CoktelDecoder::getPalette() {
_paletteDirty = false;
return _palette;
}
bool CoktelDecoder::hasDirtyPalette() const {
return (_features & kFeaturesPalette) && _paletteDirty;
}
uint32 CoktelDecoder::deLZ77(byte *dest, const byte *src, uint32 srcSize, uint32 destSize) {
uint32 frameLength = READ_LE_UINT32(src);
if (frameLength > destSize) {
warning("CoktelDecoder::deLZ77(): Uncompressed size bigger than buffer size (%d > %d)", frameLength, destSize);
return 0;
}
assert(srcSize >= 4);
uint32 realSize = frameLength;
src += 4;
srcSize -= 4;
uint16 bufPos1;
bool mode;
if ((READ_LE_UINT16(src) == 0x1234) && (READ_LE_UINT16(src + 2) == 0x5678)) {
assert(srcSize >= 4);
src += 4;
srcSize -= 4;
bufPos1 = 273;
mode = 1; // 123Ch (cmp al, 12h)
} else {
bufPos1 = 4078;
mode = 0; // 275h (jnz +2)
}
byte buf[4370];
memset(buf, 32, bufPos1);
uint8 chunkCount = 1;
uint8 chunkBitField = 0;
while (frameLength > 0) {
chunkCount--;
if (chunkCount == 0) {
chunkCount = 8;
chunkBitField = *src++;
}
if (chunkBitField % 2) {
assert(srcSize >= 1);
chunkBitField >>= 1;
buf[bufPos1] = *src;
*dest++ = *src++;
bufPos1 = (bufPos1 + 1) % 4096;
frameLength--;
srcSize--;
continue;
}
chunkBitField >>= 1;
assert(srcSize >= 2);
uint16 tmp = READ_LE_UINT16(src);
uint16 chunkLength = ((tmp & 0xF00) >> 8) + 3;
src += 2;
srcSize -= 2;
if ((mode && ((chunkLength & 0xFF) == 0x12)) ||
(!mode && (chunkLength == 0))) {
assert(srcSize >= 1);
chunkLength = *src++ + 0x12;
srcSize--;
}
uint16 bufPos2 = (tmp & 0xFF) + ((tmp >> 4) & 0x0F00);
if (((tmp + chunkLength) >= 4096) ||
((chunkLength + bufPos1) >= 4096)) {
for (int i = 0; i < chunkLength; i++, dest++) {
*dest = buf[bufPos2];
buf[bufPos1] = buf[bufPos2];
bufPos1 = (bufPos1 + 1) % 4096;
bufPos2 = (bufPos2 + 1) % 4096;
}
} else if (((tmp + chunkLength) < bufPos1) ||
((chunkLength + bufPos1) < bufPos2)) {
memcpy(dest, buf + bufPos2, chunkLength);
memmove(buf + bufPos1, buf + bufPos2, chunkLength);
dest += chunkLength;
bufPos1 += chunkLength;
bufPos2 += chunkLength;
} else {
for (int i = 0; i < chunkLength; i++, dest++, bufPos1++, bufPos2++) {
*dest = buf[bufPos2];
buf[bufPos1] = buf[bufPos2];
}
}
frameLength -= chunkLength;
}
return realSize;
}
void CoktelDecoder::deRLE(byte *&destPtr, const byte *&srcPtr, int16 destLen, int16 srcLen) {
srcPtr++;
if (srcLen & 1) {
byte data = *srcPtr++;
if (destLen > 0) {
*destPtr++ = data;
destLen--;
}
}
srcLen >>= 1;
while (srcLen > 0) {
uint8 tmp = *srcPtr++;
if (tmp & 0x80) { // Verbatim copy
tmp &= 0x7F;
int16 copyCount = MAX<int16>(0, MIN<int16>(destLen, tmp * 2));
memcpy(destPtr, srcPtr, copyCount);
srcPtr += tmp * 2;
destPtr += copyCount;
destLen -= copyCount;
} else { // 2 bytes tmp times
for (int i = 0; (i < tmp) && (destLen > 0); i++) {
for (int j = 0; j < 2; j++) {
if (destLen <= 0)
break;
*destPtr++ = srcPtr[j];
destLen--;
}
}
srcPtr += 2;
}
srcLen -= tmp;
}
}
// A whole, completely filled block
void CoktelDecoder::renderBlockWhole(Graphics::Surface &dstSurf, const byte *src, Common::Rect &rect) {
Common::Rect srcRect = rect;
rect.clip(dstSurf.w, dstSurf.h);
byte *dst = (byte *)dstSurf.getBasePtr(rect.left, rect.top);
for (int i = 0; i < rect.height(); i++) {
memcpy(dst, src, rect.width() * dstSurf.format.bytesPerPixel);
src += srcRect.width() * dstSurf.format.bytesPerPixel;
dst += dstSurf.pitch;
}
}
// A quarter-wide whole, completely filled block
void CoktelDecoder::renderBlockWhole4X(Graphics::Surface &dstSurf, const byte *src, Common::Rect &rect) {
Common::Rect srcRect = rect;
rect.clip(dstSurf.w, dstSurf.h);
byte *dst = (byte *)dstSurf.getBasePtr(rect.left, rect.top);
for (int i = 0; i < rect.height(); i++) {
byte *dstRow = dst;
const byte *srcRow = src;
int16 count = rect.width();
while (count >= 0) {
memset(dstRow, *srcRow, MIN<int16>(count, 4));
count -= 4;
dstRow += 4;
srcRow += 1;
}
src += srcRect.width() / 4;
dst += dstSurf.pitch;
}
}
// A half-high whole, completely filled block
void CoktelDecoder::renderBlockWhole2Y(Graphics::Surface &dstSurf, const byte *src, Common::Rect &rect) {
Common::Rect srcRect = rect;
rect.clip(dstSurf.w, dstSurf.h);
int16 height = rect.height();
byte *dst = (byte *)dstSurf.getBasePtr(rect.left, rect.top);
while (height > 1) {
memcpy(dst , src, rect.width());
memcpy(dst + dstSurf.pitch, src, rect.width());
height -= 2;
src += srcRect.width();
dst += 2 * dstSurf.pitch;
}
if (height == 1)
memcpy(dst, src, rect.width());
}
// A sparse block
void CoktelDecoder::renderBlockSparse(Graphics::Surface &dstSurf, const byte *src, Common::Rect &rect) {
Common::Rect srcRect = rect;
rect.clip(dstSurf.w, dstSurf.h);
byte *dst = (byte *)dstSurf.getBasePtr(rect.left, rect.top);
for (int i = 0; i < rect.height(); i++) {
byte *dstRow = dst;
int16 pixWritten = 0;
while (pixWritten < srcRect.width()) {
int16 pixCount = *src++;
if (pixCount & 0x80) { // Data
int16 copyCount;
pixCount = MIN((pixCount & 0x7F) + 1, srcRect.width() - pixWritten);
copyCount = CLIP<int16>(rect.width() - pixWritten, 0, pixCount);
memcpy(dstRow, src, copyCount);
pixWritten += pixCount;
dstRow += pixCount;
src += pixCount;
} else { // "Hole"
pixWritten += pixCount + 1;
dstRow += pixCount + 1;
}
}
dst += dstSurf.pitch;
}
}
// A half-high sparse block
void CoktelDecoder::renderBlockSparse2Y(Graphics::Surface &dstSurf, const byte *src, Common::Rect &rect) {
warning("renderBlockSparse2Y");
Common::Rect srcRect = rect;
rect.clip(dstSurf.w, dstSurf.h);
byte *dst = (byte *)dstSurf.getBasePtr(rect.left, rect.top);
for (int i = 0; i < rect.height(); i += 2) {
byte *dstRow = dst;
int16 pixWritten = 0;
while (pixWritten < srcRect.width()) {
int16 pixCount = *src++;
if (pixCount & 0x80) { // Data
pixCount = MIN((pixCount & 0x7F) + 1, srcRect.width() - pixWritten);
memcpy(dstRow , src, pixCount);
memcpy(dstRow + dstSurf.pitch, src, pixCount);
pixWritten += pixCount;
dstRow += pixCount;
src += pixCount;
} else { // "Hole"
pixWritten += pixCount + 1;
dstRow += pixCount + 1;
}
}
dst += dstSurf.pitch;
}
}
void CoktelDecoder::renderBlockRLE(Graphics::Surface &dstSurf, const byte *src, Common::Rect &rect) {
Common::Rect srcRect = rect;
rect.clip(dstSurf.w, dstSurf.h);
byte *dst = (byte *)dstSurf.getBasePtr(rect.left, rect.top);
for (int i = 0; i < rect.height(); i++) {
byte *dstRow = dst;
int16 pixWritten = 0;
while (pixWritten < srcRect.width()) {
int16 pixCount = *src++;
if (pixCount & 0x80) {
int16 copyCount;
pixCount = MIN((pixCount & 0x7F) + 1, srcRect.width() - pixWritten);
copyCount = CLIP<int16>(rect.width() - pixWritten, 0, pixCount);
if (*src != 0xFF) { // Normal copy
memcpy(dstRow, src, copyCount);
dstRow += copyCount;
src += pixCount;
} else
deRLE(dstRow, src, copyCount, pixCount);
pixWritten += pixCount;
} else { // "Hole"
int16 copyCount = CLIP<int16>(rect.width() - pixWritten, 0, pixCount + 1);
dstRow += copyCount;
pixWritten += pixCount + 1;
}
}
dst += dstSurf.pitch;
}
}
Common::Rational CoktelDecoder::getFrameRate() const {
return _frameRate;
}
uint32 CoktelDecoder::getTimeToNextFrame() const {
if (endOfVideo() || _curFrame < 0)
return 0;
uint32 elapsedTime = g_system->getMillis() - _startTime;
uint32 nextFrameStartTime = (Common::Rational((_curFrame + 1) * 1000) / getFrameRate()).toInt();
if (nextFrameStartTime <= elapsedTime)
return 0;
return nextFrameStartTime - elapsedTime;
}
uint32 CoktelDecoder::getStaticTimeToNextFrame() const {
return (1000 / _frameRate).toInt();
}
void CoktelDecoder::pauseVideo(bool pause) {
if (_isPaused != pause) {
if (_isPaused) {
// Add the time we were paused to the initial starting time
_startTime += g_system->getMillis() - _pauseStartTime;
} else {
// Store the time we paused for use later
_pauseStartTime = g_system->getMillis();
}
_isPaused = pause;
}
}
inline void CoktelDecoder::unsignedToSigned(byte *buffer, int length) {
while (length-- > 0) *buffer++ ^= 0x80;
}
bool CoktelDecoder::endOfVideo() const {
return !isVideoLoaded() || (getCurFrame() >= (int32)getFrameCount() - 1);
}
PreIMDDecoder::PreIMDDecoder(uint16 width, uint16 height,
Audio::Mixer *mixer, Audio::Mixer::SoundType soundType) : CoktelDecoder(mixer, soundType),
_stream(0), _videoBuffer(0), _videoBufferSize(0) {
_width = width;
_height = height;
}
PreIMDDecoder::~PreIMDDecoder() {
close();
}
bool PreIMDDecoder::reloadStream(Common::SeekableReadStream *stream) {
if (!_stream)
return false;
if (!stream->seek(_stream->pos())) {
close();
return false;
}
delete _stream;
_stream = stream;
return true;
}
bool PreIMDDecoder::seek(int32 frame, int whence, bool restart) {
if (!evaluateSeekFrame(frame, whence))
return false;
if (frame == _curFrame)
// Nothing to do
return true;
// Run through the frames
_curFrame = -1;
_stream->seek(2);
while (_curFrame != frame) {
uint16 frameSize = _stream->readUint16LE();
_stream->skip(frameSize + 2);
_curFrame++;
}
return true;
}
bool PreIMDDecoder::loadStream(Common::SeekableReadStream *stream) {
// Since PreIMDs don't have any width and height values stored,
// we need them to be specified in the constructor
assert((_width > 0) && (_height > 0));
close();
_stream = stream;
_stream->seek(0);
_frameCount = _stream->readUint16LE();
_videoBufferSize = _width * _height;
_videoBuffer = new byte[_videoBufferSize];
memset(_videoBuffer, 0, _videoBufferSize);
return true;
}
void PreIMDDecoder::close() {
CoktelDecoder::close();
delete _stream;
delete[] _videoBuffer;
_stream = 0;
_videoBuffer = 0;
_videoBufferSize = 0;
}
bool PreIMDDecoder::isVideoLoaded() const {
return _stream != 0;
}
const Graphics::Surface *PreIMDDecoder::decodeNextFrame() {
if (!isVideoLoaded() || endOfVideo())
return 0;
createSurface();
processFrame();
renderFrame();
if (_curFrame == 0)
_startTime = g_system->getMillis();
return &_surface;
}
void PreIMDDecoder::processFrame() {
_curFrame++;
uint16 frameSize = _stream->readUint16LE();
if (_stream->eos() || (frameSize == 0))
return;
uint32 nextFramePos = _stream->pos() + frameSize + 2;
byte cmd;
cmd = _stream->readByte();
frameSize--;
if (cmd == 0) {
// Palette. Ignored by Fascination, though.
// NOTE: If we ever find another game using this format,
// palettes may need to be evaluated.
_stream->skip(768);
frameSize -= 769;
cmd = _stream->readByte();
}
if (cmd != 2) {
// Partial frame data
uint32 fSize = frameSize;
uint32 vidSize = _videoBufferSize;
byte *vidBuffer = _videoBuffer;
while ((fSize > 0) && (vidSize > 0)) {
uint32 n = _stream->readByte();
fSize--;
if ((n & 0x80) != 0) {
// Data
n = MIN<uint32>((n & 0x7F) + 1, MIN(fSize, vidSize));
_stream->read(vidBuffer, n);
vidBuffer += n;
vidSize -= n;
fSize -= n;
} else {
// Skip
n = MIN<uint32>(n + 1, vidSize);
vidBuffer += n;
vidSize -= n;
}
}
} else {
// Full direct frame
uint32 vidSize = MIN<uint32>(_videoBufferSize, frameSize);
_stream->read(_videoBuffer, vidSize);
}
_stream->seek(nextFramePos);
}
// Just a simple blit
void PreIMDDecoder::renderFrame() {
_dirtyRects.clear();
uint16 w = CLIP<int32>(_surface.w - _x, 0, _width);
uint16 h = CLIP<int32>(_surface.h - _y, 0, _height);
const byte *src = _videoBuffer;
byte *dst = (byte *)_surface.getBasePtr(_x, _y);
uint32 frameDataSize = _videoBufferSize;
while (h-- > 0) {
uint32 n = MIN<uint32>(w, frameDataSize);
memcpy(dst, src, n);
src += _width;
dst += _surface.pitch;
frameDataSize -= n;
}
_dirtyRects.push_back(Common::Rect(_x, _y, _x + _width, _y + _height));
}
Graphics::PixelFormat PreIMDDecoder::getPixelFormat() const {
return Graphics::PixelFormat::createFormatCLUT8();
}
IMDDecoder::IMDDecoder(Audio::Mixer *mixer, Audio::Mixer::SoundType soundType) : CoktelDecoder(mixer, soundType),
_stream(0), _version(0), _stdX(-1), _stdY(-1), _stdWidth(-1), _stdHeight(-1),
_flags(0), _firstFramePos(0), _framePos(0), _frameCoords(0), _videoBufferSize(0),
_soundFlags(0), _soundFreq(0), _soundSliceSize(0), _soundSlicesCount(0) {
_videoBuffer [0] = 0;
_videoBuffer [1] = 0;
_videoBufferLen[0] = 0;
_videoBufferLen[1] = 0;
}
IMDDecoder::~IMDDecoder() {
close();
}
bool IMDDecoder::reloadStream(Common::SeekableReadStream *stream) {
if (!_stream)
return false;
if (!stream->seek(_stream->pos())) {
close();
return false;
}
delete _stream;
_stream = stream;
return true;
}
bool IMDDecoder::seek(int32 frame, int whence, bool restart) {
if (!evaluateSeekFrame(frame, whence))
return false;
if (frame == _curFrame)
// Nothing to do
return true;
// Try every possible way to find a file offset to that frame
uint32 framePos = 0;
if (frame == -1) {
// First frame, we know that position
framePos = _firstFramePos;
} else if (frame == 0) {
// Second frame, can be calculated from the first frame's position
framePos = _firstFramePos;
_stream->seek(framePos);
framePos += _stream->readUint16LE() + 4;
} else if (_framePos) {
// If we have an array of frame positions, use that
framePos = _framePos[frame + 1];
} else if (restart && (_soundStage == kSoundNone)) {
// If we are asked to restart the video if necessary and have no
// audio to worry about, restart the video and run through the frames
_curFrame = 0;
_stream->seek(_firstFramePos);
for (int i = ((frame > _curFrame) ? _curFrame : 0); i <= frame; i++)
processFrame();
return true;
} else {
// Not possible
warning("IMDDecoder::seek(): Frame %d is not directly accessible", frame + 1);
return false;
}
// Seek
_stream->seek(framePos);
_curFrame = frame;
return true;
}
void IMDDecoder::setXY(uint16 x, uint16 y) {
// Adjusting the standard coordinates
if (_stdX != -1) {
if (x != 0xFFFF)
_stdX = _stdX - _x + x;
if (y != 0xFFFF)
_stdY = _stdY - _y + y;
}
// Going through the coordinate table as well
if (_frameCoords) {
for (uint32 i = 0; i < _frameCount; i++) {
if (_frameCoords[i].left != -1) {
if (x != 0xFFFF) {
_frameCoords[i].left = _frameCoords[i].left - _x + x;
_frameCoords[i].right = _frameCoords[i].right - _x + x;
}
if (y != 0xFFFF) {
_frameCoords[i].top = _frameCoords[i].top - _y + y;
_frameCoords[i].bottom = _frameCoords[i].bottom - _y + y;
}
}
}
}
if (x != 0xFFFF)
_x = x;
if (y != 0xFFFF)
_y = y;
}
bool IMDDecoder::loadStream(Common::SeekableReadStream *stream) {
close();
_stream = stream;
uint16 handle;
handle = _stream->readUint16LE();
_version = _stream->readByte();
// Version checking
if ((handle != 0) || (_version < 2)) {
warning("IMDDecoder::loadStream(): Version incorrect (%d, 0x%X)", handle, _version);
close();
return false;
}
// Rest header
_features = _stream->readByte();
_frameCount = _stream->readUint16LE();
_defaultX = _stream->readSint16LE();
_defaultY = _stream->readSint16LE();
_width = _stream->readSint16LE();
_height = _stream->readSint16LE();
_flags = _stream->readUint16LE();
_firstFramePos = _stream->readUint16LE();
_x = _defaultX;
_y = _defaultY;
// IMDs always have video
_features |= kFeaturesVideo;
// IMDs always have palettes
_features |= kFeaturesPalette;
// Palette
for (int i = 0; i < 768; i++)
_palette[i] = _stream->readByte() << 2;
_paletteDirty = true;
if (!loadCoordinates()) {
close();
return false;
}
uint32 framePosPos, frameCoordsPos;
if (!loadFrameTableOffsets(framePosPos, frameCoordsPos)) {
close();
return false;
}
if (!assessAudioProperties()) {
close();
return false;
}
if (!assessVideoProperties()) {
close();
return false;
}
if (!loadFrameTables(framePosPos, frameCoordsPos)) {
close();
return false;
}
// Seek to the first frame
_stream->seek(_firstFramePos);
return true;
}
bool IMDDecoder::loadCoordinates() {
// Standard coordinates
if (_version >= 3) {
uint16 count = _stream->readUint16LE();
if (count > 1) {
warning("IMDDecoder::loadCoordinates(): More than one standard coordinate quad found (%d)", count);
return false;
}
if (count != 0) {
_stdX = _stream->readSint16LE();
_stdY = _stream->readSint16LE();
_stdWidth = _stream->readSint16LE();
_stdHeight = _stream->readSint16LE();
_features |= kFeaturesStdCoords;
} else
_stdX = _stdY = _stdWidth = _stdHeight = -1;
} else
_stdX = _stdY = _stdWidth = _stdHeight = -1;
return true;
}
bool IMDDecoder::loadFrameTableOffsets(uint32 &framePosPos, uint32 &frameCoordsPos) {
framePosPos = 0;
frameCoordsPos = 0;
// Frame positions
if (_version >= 4) {
framePosPos = _stream->readUint32LE();
if (framePosPos != 0) {
_framePos = new uint32[_frameCount];
_features |= kFeaturesFramePos;
}
}
// Frame coordinates
if (_features & kFeaturesFrameCoords)
frameCoordsPos = _stream->readUint32LE();
return true;
}
bool IMDDecoder::assessVideoProperties() {
uint32 suggestedVideoBufferSize = 0;
// Sizes of the frame data and extra video buffer
if (_features & kFeaturesDataSize) {
uint32 size1, size2;
size1 = _stream->readUint16LE();
if (size1 == 0) {
size1 = _stream->readUint32LE();
size2 = _stream->readUint32LE();
} else
size2 = _stream->readUint16LE();
suggestedVideoBufferSize = MAX(size1, size2);
}
_videoBufferSize = _width * _height + 1000;
if (suggestedVideoBufferSize > _videoBufferSize) {
warning("Suggested video buffer size greater than what should be needed (%d, %d, %dx%d",
suggestedVideoBufferSize, _videoBufferSize, _width, _height);
_videoBufferSize = suggestedVideoBufferSize;
}
for (int i = 0; i < 2; i++) {
_videoBuffer[i] = new byte[_videoBufferSize];
memset(_videoBuffer[i], 0, _videoBufferSize);
}
return true;
}
bool IMDDecoder::assessAudioProperties() {
if (_features & kFeaturesSound) {
_soundFreq = _stream->readSint16LE();
_soundSliceSize = _stream->readSint16LE();
_soundSlicesCount = _stream->readSint16LE();
if (_soundFreq < 0)
_soundFreq = -_soundFreq;
if (_soundSlicesCount < 0)
_soundSlicesCount = -_soundSlicesCount - 1;
if (_soundSlicesCount > 40) {
warning("IMDDecoder::assessAudioProperties(): More than 40 sound slices found (%d)", _soundSlicesCount);
return false;
}
_frameRate = Common::Rational(_soundFreq, _soundSliceSize);
_hasSound = true;
_soundEnabled = true;
_soundStage = kSoundLoaded;
_audioStream = Audio::makeQueuingAudioStream(_soundFreq, 1);
}
return true;
}
bool IMDDecoder::loadFrameTables(uint32 framePosPos, uint32 frameCoordsPos) {
// Positions table
if (_framePos) {
_stream->seek(framePosPos);
for (uint32 i = 0; i < _frameCount; i++)
_framePos[i] = _stream->readUint32LE();
}
// Coordinates table
if (_features & kFeaturesFrameCoords) {
_stream->seek(frameCoordsPos);
_frameCoords = new Coord[_frameCount];
assert(_frameCoords);
for (uint32 i = 0; i < _frameCount; i++) {
_frameCoords[i].left = _stream->readSint16LE();
_frameCoords[i].top = _stream->readSint16LE();
_frameCoords[i].right = _stream->readSint16LE();
_frameCoords[i].bottom = _stream->readSint16LE();
}
}
return true;
}
void IMDDecoder::close() {
CoktelDecoder::close();
delete _stream;
delete[] _framePos;
delete[] _frameCoords;
delete[] _videoBuffer[0];
delete[] _videoBuffer[1];
_stream = 0;
_version = 0;
_stdX = -1;
_stdY = -1;
_stdWidth = -1;
_stdHeight = -1;
_flags = 0;
_firstFramePos = 0;
_framePos = 0;
_frameCoords = 0;
_videoBufferSize = 0;
_videoBuffer [0] = 0;
_videoBuffer [1] = 0;
_videoBufferLen[0] = 0;
_videoBufferLen[1] = 0;
_soundFlags = 0;
_soundFreq = 0;
_soundSliceSize = 0;
_soundSlicesCount = 0;
_hasSound = false;
_soundEnabled = false;
_soundStage = kSoundNone;
}
bool IMDDecoder::isVideoLoaded() const {
return _stream != 0;
}
const Graphics::Surface *IMDDecoder::decodeNextFrame() {
if (!isVideoLoaded() || endOfVideo())
return 0;
createSurface();
processFrame();
if (_curFrame == 0)
_startTime = g_system->getMillis();
return &_surface;
}
void IMDDecoder::processFrame() {
_curFrame++;
_dirtyRects.clear();
uint32 cmd = 0;
bool hasNextCmd = false;
bool startSound = false;
do {
cmd = _stream->readUint16LE();
if ((cmd & kCommandBreakMask) == kCommandBreak) {
// Flow control
if (cmd == kCommandBreak) {
_stream->skip(2);
cmd = _stream->readUint16LE();
}
// Break
if (cmd == kCommandBreakSkip0) {
continue;
} else if (cmd == kCommandBreakSkip16) {
cmd = _stream->readUint16LE();
_stream->skip(cmd);
continue;
} else if (cmd == kCommandBreakSkip32) {
cmd = _stream->readUint32LE();
_stream->skip(cmd);
continue;
}
}
// Audio
if (cmd == kCommandNextSound) {
nextSoundSlice(hasNextCmd);
cmd = _stream->readUint16LE();
} else if (cmd == kCommandStartSound) {
startSound = initialSoundSlice(hasNextCmd);
cmd = _stream->readUint16LE();
} else
emptySoundSlice(hasNextCmd);
// Set palette
if (cmd == kCommandPalette) {
_stream->skip(2);
_paletteDirty = true;
for (int i = 0; i < 768; i++)
_palette[i] = _stream->readByte() << 2;
cmd = _stream->readUint16LE();
}
hasNextCmd = false;
if (cmd == kCommandJump) {
// Jump to frame
int16 frame = _stream->readSint16LE();
if (_framePos) {
_curFrame = frame - 1;
_stream->seek(_framePos[frame]);
hasNextCmd = true;
}
} else if (cmd == kCommandVideoData) {
_videoBufferLen[0] = _stream->readUint32LE() + 2;
_stream->read(_videoBuffer[0], _videoBufferLen[0]);
Common::Rect rect = calcFrameCoords(_curFrame);
if (renderFrame(rect))
_dirtyRects.push_back(rect);
} else if (cmd != 0) {
_videoBufferLen[0] = cmd + 2;
_stream->read(_videoBuffer[0], _videoBufferLen[0]);
Common::Rect rect = calcFrameCoords(_curFrame);
if (renderFrame(rect))
_dirtyRects.push_back(rect);
}
} while (hasNextCmd);
// Start the audio stream if necessary
if (startSound && _soundEnabled) {
_mixer->playStream(_soundType, &_audioHandle, _audioStream,
-1, Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::NO);
_soundStage = kSoundPlaying;
}
// End the audio stream if necessary
if ((_curFrame >= (int32)(_frameCount - 1)) && (_soundStage == kSoundPlaying)) {
_audioStream->finish();
_soundStage = kSoundFinished;
}
}
Common::Rect IMDDecoder::calcFrameCoords(uint32 frame) {
Common::Rect rect;
if (frame == 0) {
// First frame is always a full "keyframe"
rect.left = _x;
rect.top = _y;
rect.right = _x + _width;
rect.bottom = _y + _height;
} else if (_frameCoords && ((_frameCoords[frame].left != -1))) {
// We have frame coordinates for that frame
rect.left = _frameCoords[frame].left;
rect.top = _frameCoords[frame].top;
rect.right = _frameCoords[frame].right + 1;
rect.bottom = _frameCoords[frame].bottom + 1;
} else if (_stdX != -1) {
// We have standard coordinates
rect.left = _stdX;
rect.top = _stdY;
rect.right = _stdX + _stdWidth;
rect.bottom = _stdY + _stdHeight;
} else {
// Otherwise, it must be a full "keyframe"
rect.left = _x;
rect.top = _y;
rect.right = _x + _width;
rect.bottom = _y + _height;
}
return rect;
}
bool IMDDecoder::renderFrame(Common::Rect &rect) {
if (!rect.isValidRect())
// Invalid rendering area
return false;
// Clip the rendering area to the video's visible area
rect.clip(Common::Rect(_x, _y, _x + _width, _y + _height));
if (!rect.isValidRect() || rect.isEmpty())
// Result is empty => nothing to do
return false;
byte *dataPtr = _videoBuffer[0];
uint32 dataSize = _videoBufferLen[0] - 1;
uint8 type = *dataPtr++;
if (type & 0x10) {
// Palette data
// One byte index
int index = *dataPtr++;
int count = MIN((255 - index) * 3, 48);
for (int i = 0; i < count; i++)
_palette[index * 3 + i] = dataPtr[i] << 2;
dataPtr += 48;
dataSize -= 49;
type ^= 0x10;
_paletteDirty = true;
}
if (type & 0x80) {
// Frame data is compressed
type &= 0x7F;
if ((type == 2) && (rect.width() == _surface.w) && (_x == 0)) {
// Directly uncompress onto the video surface
const int offsetX = rect.left * _surface.format.bytesPerPixel;
const int offsetY = (_y + rect.top) * _surface.pitch;
const int offset = offsetX + offsetY;
if (deLZ77((byte *)_surface.getPixels() + offset, dataPtr, dataSize,
_surface.w * _surface.h * _surface.format.bytesPerPixel - offset))
return true;
}
_videoBufferLen[1] = deLZ77(_videoBuffer[1], dataPtr, dataSize, _videoBufferSize);
dataPtr = _videoBuffer[1];
dataSize = _videoBufferLen[1];
}
// Evaluate the block type
if (type == 0x01)
renderBlockSparse (_surface, dataPtr, rect);
else if (type == 0x02)
renderBlockWhole (_surface, dataPtr, rect);
else if (type == 0x42)
renderBlockWhole4X (_surface, dataPtr, rect);
else if ((type & 0x0F) == 0x02)
renderBlockWhole2Y (_surface, dataPtr, rect);
else
renderBlockSparse2Y(_surface, dataPtr, rect);
return true;
}
void IMDDecoder::nextSoundSlice(bool hasNextCmd) {
if (hasNextCmd || !_soundEnabled || !_audioStream) {
// Skip sound
_stream->skip(_soundSliceSize);
return;
}
// Read, convert, queue
byte *soundBuf = (byte *)malloc(_soundSliceSize);
_stream->read(soundBuf, _soundSliceSize);
unsignedToSigned(soundBuf, _soundSliceSize);
_audioStream->queueBuffer(soundBuf, _soundSliceSize, DisposeAfterUse::YES, 0);
}
bool IMDDecoder::initialSoundSlice(bool hasNextCmd) {
int dataLength = _soundSliceSize * _soundSlicesCount;
if (hasNextCmd || !_soundEnabled) {
// Skip sound
_stream->skip(dataLength);
return false;
}
if (!_audioStream || (_soundStage == kSoundFinished)) {
delete _audioStream;
_audioStream = Audio::makeQueuingAudioStream(_soundFreq, 1);
_soundStage = kSoundLoaded;
}
// Read, convert, queue
byte *soundBuf = (byte *)malloc(dataLength);
_stream->read(soundBuf, dataLength);
unsignedToSigned(soundBuf, dataLength);
_audioStream->queueBuffer(soundBuf, dataLength, DisposeAfterUse::YES, 0);
return _soundStage == kSoundLoaded;
}
void IMDDecoder::emptySoundSlice(bool hasNextCmd) {
if (hasNextCmd || !_soundEnabled || !_audioStream)
return;
// Create an empty sound buffer and queue it
byte *soundBuf = (byte *)malloc(_soundSliceSize);
memset(soundBuf, 0, _soundSliceSize);
_audioStream->queueBuffer(soundBuf, _soundSliceSize, DisposeAfterUse::YES, 0);
}
Graphics::PixelFormat IMDDecoder::getPixelFormat() const {
return Graphics::PixelFormat::createFormatCLUT8();
}
VMDDecoder::File::File() {
offset = 0;
size = 0;
realSize = 0;
}
VMDDecoder::Part::Part() {
type = kPartTypeSeparator;
field_1 = 0;
field_E = 0;
size = 0;
left = 0;
top = 0;
right = 0;
bottom = 0;
id = 0;
flags = 0;
}
VMDDecoder::Frame::Frame() {
parts = 0;
offset = 0;
}
VMDDecoder::Frame::~Frame() {
delete[] parts;
}
VMDDecoder::VMDDecoder(Audio::Mixer *mixer, Audio::Mixer::SoundType soundType) : CoktelDecoder(mixer, soundType),
_stream(0), _version(0), _flags(0), _frameInfoOffset(0), _partsPerFrame(0), _frames(0),
_soundFlags(0), _soundFreq(0), _soundSliceSize(0), _soundSlicesCount(0),
_soundBytesPerSample(0), _soundStereo(0), _soundHeaderSize(0), _soundDataSize(0),
_soundLastFilledFrame(0), _audioFormat(kAudioFormat8bitRaw),
_hasVideo(false), _videoCodec(0), _blitMode(0), _bytesPerPixel(0),
_firstFramePos(0), _videoBufferSize(0), _externalCodec(false), _codec(0),
_subtitle(-1), _isPaletted(true), _autoStartSound(true) {
_videoBuffer [0] = 0;
_videoBuffer [1] = 0;
_videoBuffer [2] = 0;
_videoBufferLen[0] = 0;
_videoBufferLen[1] = 0;
_videoBufferLen[2] = 0;
}
VMDDecoder::~VMDDecoder() {
close();
}
bool VMDDecoder::reloadStream(Common::SeekableReadStream *stream) {
if (!_stream)
return false;
if (!stream->seek(_stream->pos())) {
close();
return false;
}
delete _stream;
_stream = stream;
return true;
}
bool VMDDecoder::seek(int32 frame, int whence, bool restart) {
if (!evaluateSeekFrame(frame, whence))
return false;
if (frame == _curFrame)
// Nothing to do
return true;
// Restart sound
if (_hasSound && (frame == -1) &&
((_soundStage == kSoundNone) || (_soundStage == kSoundFinished))) {
delete _audioStream;
_soundStage = kSoundLoaded;
_audioStream = Audio::makeQueuingAudioStream(_soundFreq, _soundStereo ? 2 : 1);
}
_subtitle = -1;
if ((_blitMode > 0) && (_flags & 0x4000)) {
if (_curFrame > frame) {
_stream->seek(_frames[0].offset);
_curFrame = -1;
}
while (frame > _curFrame)
decodeNextFrame();
return true;
}
// Seek
_stream->seek(_frames[frame + 1].offset);
_curFrame = frame;
_startTime = g_system->getMillis() - ((frame + 2) * getStaticTimeToNextFrame());
return true;
}
void VMDDecoder::setXY(uint16 x, uint16 y) {
uint16 curX = _x;
uint16 setX = x;
if ((x != 0xFFFF) && (_blitMode == 1)) {
curX *= _bytesPerPixel;
setX *= _bytesPerPixel;
}
for (uint32 i = 0; i < _frameCount; i++) {
for (int j = 0; j < _partsPerFrame; j++) {
if (_frames[i].parts[j].type == kPartTypeVideo) {
if (x != 0xFFFF) {
_frames[i].parts[j].left = _frames[i].parts[j].left - curX + setX;
_frames[i].parts[j].right = _frames[i].parts[j].right - curX + setX;
}
if (y != 0xFFFF) {
_frames[i].parts[j].top = _frames[i].parts[j].top - _y + y;
_frames[i].parts[j].bottom = _frames[i].parts[j].bottom - _y + y;
}
}
}
}
if (x != 0xFFFF)
_x = x;
if (y != 0xFFFF)
_y = y;
}
bool VMDDecoder::openExternalCodec() {
delete _codec;
_codec = 0;
if (_externalCodec) {
if (_videoCodec == kVideoCodecIndeo3) {
_isPaletted = false;
_codec = new Image::Indeo3Decoder(_width, _height);
} else {
warning("VMDDecoder::openExternalCodec(): Unknown video codec FourCC \"%s\"",
tag2str(_videoCodec));
return false;
}
}
return true;
}
void VMDDecoder::colorModeChanged() {
openExternalCodec();
}
bool VMDDecoder::loadStream(Common::SeekableReadStream *stream) {
close();
_stream = stream;
_stream->seek(0);
uint16 headerLength;
uint16 handle;
headerLength = _stream->readUint16LE();
handle = _stream->readUint16LE();
_version = _stream->readUint16LE();
// Version checking
if (headerLength == 50) {
// Newer version, used in Addy 5 upwards
warning("VMDDecoder::loadStream(): TODO: Addy 5 videos");
} else if (headerLength == 814) {
// Old version
_features |= kFeaturesPalette;
} else {
warning("VMDDecoder::loadStream(): Version incorrect (%d, %d, %d)", headerLength, handle, _version);
close();
return false;
}
_frameCount = _stream->readUint16LE();
_defaultX = _stream->readSint16LE();
_defaultY = _stream->readSint16LE();
_width = _stream->readSint16LE();
_height = _stream->readSint16LE();
_x = _defaultX;
_y = _defaultY;
if ((_width != 0) && (_height != 0)) {
_hasVideo = true;
_features |= kFeaturesVideo;
} else
_hasVideo = false;
_bytesPerPixel = 1;
if (_version & 4)
_bytesPerPixel = handle + 1;
if (_bytesPerPixel > 3) {
warning("VMDDecoder::loadStream(): Requested %d bytes per pixel (%d, %d, %d)",
_bytesPerPixel, headerLength, handle, _version);
close();
return false;
}
_flags = _stream->readUint16LE();
_partsPerFrame = _stream->readUint16LE();
_firstFramePos = _stream->readUint32LE();
_videoCodec = _stream->readUint32BE();
if (_features & kFeaturesPalette) {
for (int i = 0; i < 768; i++)
_palette[i] = _stream->readByte() << 2;
_paletteDirty = true;
}
uint32 videoBufferSize1 = _stream->readUint32LE();
uint32 videoBufferSize2 = _stream->readUint32LE();
_videoBufferSize = MAX(videoBufferSize1, videoBufferSize2);
if (_hasVideo) {
if (!assessVideoProperties()) {
close();
return false;
}
}
_soundFreq = _stream->readSint16LE();
_soundSliceSize = _stream->readSint16LE();
_soundSlicesCount = _stream->readSint16LE();
_soundFlags = _stream->readUint16LE();
_hasSound = (_soundFreq != 0);
if (_hasSound) {
if (!assessAudioProperties()) {
close();
return false;
}
} else
_frameRate = 12;
_frameInfoOffset = _stream->readUint32LE();
int numFiles;
if (!readFrameTable(numFiles)) {
close();
return false;
}
_stream->seek(_firstFramePos);
if (numFiles == 0)
return true;
_files.reserve(numFiles);
if (!readFiles()) {
close();
return false;
}
_stream->seek(_firstFramePos);
return true;
}
bool VMDDecoder::assessVideoProperties() {
_isPaletted = true;
if ((_version & 2) && !(_version & 8)) {
_externalCodec = true;
_videoBufferSize = 0;
} else
_externalCodec = false;
if (!openExternalCodec())
return false;
if (_externalCodec)
_blitMode = 0;
else if (_bytesPerPixel == 1)
_blitMode = 0;
else if ((_bytesPerPixel == 2) || (_bytesPerPixel == 3)) {
int n = (_flags & 0x80) ? 2 : 3;
_blitMode = _bytesPerPixel - 1;
_bytesPerPixel = n;
_isPaletted = false;
}
if (_blitMode == 1) {
_width /= _bytesPerPixel;
_defaultX /= _bytesPerPixel;
_x /= _bytesPerPixel;
}
if (_hasVideo) {
uint32 suggestedVideoBufferSize = _videoBufferSize;
_videoBufferSize = _width * _height * _bytesPerPixel + 1000;
if ((suggestedVideoBufferSize > _videoBufferSize) && (suggestedVideoBufferSize < 2097152)) {
warning("Suggested video buffer size greater than what should be needed (%d, %d, %dx%d",
suggestedVideoBufferSize, _videoBufferSize, _width, _height);
_videoBufferSize = suggestedVideoBufferSize;
}
for (int i = 0; i < 3; i++) {
_videoBuffer[i] = new byte[_videoBufferSize];
memset(_videoBuffer[i], 0, _videoBufferSize);
_8bppSurface[i].init(_width * _bytesPerPixel, _height, _width * _bytesPerPixel,
_videoBuffer[i], Graphics::PixelFormat::createFormatCLUT8());
}
}
return true;
}
bool VMDDecoder::assessAudioProperties() {
bool supportedFormat = true;
_features |= kFeaturesSound;
_soundStereo = (_soundFlags & 0x8000) ? 1 : ((_soundFlags & 0x200) ? 2 : 0);
if (_soundSliceSize < 0) {
_soundBytesPerSample = 2;
_soundSliceSize = -_soundSliceSize;
if (_soundFlags & 0x10) {
_audioFormat = kAudioFormat16bitADPCM;
_soundHeaderSize = 3;
_soundDataSize = _soundSliceSize >> 1;
if (_soundStereo > 0)
supportedFormat = false;
} else {
_audioFormat = kAudioFormat16bitDPCM;
_soundHeaderSize = 1;
_soundDataSize = _soundSliceSize;
if (_soundStereo == 1) {
supportedFormat = false;
} else if (_soundStereo == 2) {
_soundDataSize = 2 * _soundDataSize + 2;
_soundHeaderSize = 4;
}
}
} else {
_soundBytesPerSample = 1;
_audioFormat = kAudioFormat8bitRaw;
_soundHeaderSize = 0;
_soundDataSize = _soundSliceSize;
if (_soundStereo > 0)
supportedFormat = false;
}
if (!supportedFormat) {
warning("VMDDecoder::assessAudioProperties(): Unsupported audio format: %d bits, encoding %d, stereo %d",
_soundBytesPerSample * 8, _audioFormat, _soundStereo);
return false;
}
_frameRate = Common::Rational(_soundFreq, _soundSliceSize);
_hasSound = true;
_soundEnabled = true;
_soundStage = kSoundLoaded;
_audioStream = Audio::makeQueuingAudioStream(_soundFreq, _soundStereo ? 2 : 1);
return true;
}
bool VMDDecoder::readFrameTable(int &numFiles) {
numFiles = 0;
_stream->seek(_frameInfoOffset);
_frames = new Frame[_frameCount];
for (uint16 i = 0; i < _frameCount; i++) {
_frames[i].parts = new Part[_partsPerFrame];
_stream->skip(2); // Unknown
_frames[i].offset = _stream->readUint32LE();
}
_soundLastFilledFrame = 0;
for (uint16 i = 0; i < _frameCount; i++) {
bool separator = false;
for (uint16 j = 0; j < _partsPerFrame; j++) {
_frames[i].parts[j].type = (PartType) _stream->readByte();
_frames[i].parts[j].field_1 = _stream->readByte();
_frames[i].parts[j].size = _stream->readUint32LE();
if (_frames[i].parts[j].type == kPartTypeAudio) {
_frames[i].parts[j].flags = _stream->readByte();
_stream->skip(9); // Unknown
if (_frames[i].parts[j].flags != 3)
_soundLastFilledFrame = i;
} else if (_frames[i].parts[j].type == kPartTypeVideo) {
_frames[i].parts[j].left = _stream->readUint16LE();
_frames[i].parts[j].top = _stream->readUint16LE();
_frames[i].parts[j].right = _stream->readUint16LE();
_frames[i].parts[j].bottom = _stream->readUint16LE();
_frames[i].parts[j].field_E = _stream->readByte();
_frames[i].parts[j].flags = _stream->readByte();
} else if (_frames[i].parts[j].type == kPartTypeSubtitle) {
_frames[i].parts[j].id = _stream->readUint16LE();
// Speech text file name
_stream->skip(8);
} else if (_frames[i].parts[j].type == kPartTypeFile) {
if (!separator)
numFiles++;
_stream->skip(10);
} else if (_frames[i].parts[j].type == kPartTypeSeparator) {
separator = true;
_stream->skip(10);
} else {
// Unknown type
_stream->skip(10);
}
}
}
return true;
}
bool VMDDecoder::readFiles() {
uint32 ssize = _stream->size();
for (uint16 i = 0; i < _frameCount; i++) {
_stream->seek(_frames[i].offset);
for (uint16 j = 0; j < _partsPerFrame; j++) {
if (_frames[i].parts[j].type == kPartTypeSeparator)
break;
if (_frames[i].parts[j].type == kPartTypeFile) {
File file;
file.offset = _stream->pos() + 20;
file.size = _frames[i].parts[j].size;
file.realSize = _stream->readUint32LE();
char name[16];
_stream->read(name, 16);
name[15] = '\0';
file.name = name;
_stream->skip(_frames[i].parts[j].size - 20);
if ((((uint32) file.realSize) >= ssize) || (file.name == ""))
continue;
_files.push_back(file);
} else
_stream->skip(_frames[i].parts[j].size);
}
}
return true;
}
void VMDDecoder::close() {
CoktelDecoder::close();
delete _stream;
delete[] _frames;
delete[] _videoBuffer[0];
delete[] _videoBuffer[1];
delete[] _videoBuffer[2];
delete _codec;
_files.clear();
_stream = 0;
_version = 0;
_flags = 0;
_frameInfoOffset = 0;
_partsPerFrame = 0;
_frames = 0;
_soundFlags = 0;
_soundFreq = 0;
_soundSliceSize = 0;
_soundSlicesCount = 0;
_soundBytesPerSample = 0;
_soundStereo = 0;
_soundHeaderSize = 0;
_soundDataSize = 0;
_soundLastFilledFrame = 0;
_audioFormat = kAudioFormat8bitRaw;
_hasVideo = false;
_videoCodec = 0;
_blitMode = 0;
_bytesPerPixel = 0;
_firstFramePos = 0;
_videoBufferSize = 0;
_videoBuffer [0] = 0;
_videoBuffer [1] = 0;
_videoBuffer [2] = 0;
_videoBufferLen[0] = 0;
_videoBufferLen[1] = 0;
_videoBufferLen[2] = 0;
_externalCodec = false;
_codec = 0;
_isPaletted = true;
}
bool VMDDecoder::isVideoLoaded() const {
return _stream != 0;
}
const Graphics::Surface *VMDDecoder::decodeNextFrame() {
if (!isVideoLoaded() || endOfVideo())
return 0;
createSurface();
processFrame();
if (_curFrame == 0)
_startTime = g_system->getMillis();
return &_surface;
}
void VMDDecoder::processFrame() {
_curFrame++;
_dirtyRects.clear();
_subtitle = -1;
bool startSound = false;
for (uint16 i = 0; i < _partsPerFrame; i++) {
uint32 pos = _stream->pos();
Part &part = _frames[_curFrame].parts[i];
if (part.type == kPartTypeAudio) {
if (part.flags == 1) {
// Next sound slice data
if (_soundEnabled) {
filledSoundSlice(part.size);
if (_soundStage == kSoundLoaded)
startSound = true;
} else
_stream->skip(part.size);
} else if (part.flags == 2) {
// Initial sound data (all slices)
if (_soundEnabled) {
uint32 mask = _stream->readUint32LE();
filledSoundSlices(part.size - 4, mask);
if (_soundStage == kSoundLoaded)
startSound = true;
} else
_stream->skip(part.size);
} else if (part.flags == 3) {
// Empty sound slice
if (_soundEnabled) {
if ((uint32)_curFrame < _soundLastFilledFrame)
emptySoundSlice(_soundDataSize * _soundBytesPerSample);
if (_soundStage == kSoundLoaded)
startSound = true;
}
_stream->skip(part.size);
} else if (part.flags == 4) {
warning("VMDDecoder::processFrame(): TODO: Addy 5 sound type 4 (%d)", part.size);
disableSound();
_stream->skip(part.size);
} else {
warning("VMDDecoder::processFrame(): Unknown sound type %d", part.flags);
_stream->skip(part.size);
}
_stream->seek(pos + part.size);
} else if ((part.type == kPartTypeVideo) && !_hasVideo) {
warning("VMDDecoder::processFrame(): Header claims there's no video, but video found (%d)", part.size);
_stream->skip(part.size);
} else if ((part.type == kPartTypeVideo) && _hasVideo) {
uint32 size = part.size;
// New palette
if (part.flags & 2) {
uint8 index = _stream->readByte();
uint8 count = _stream->readByte();
for (int j = 0; j < ((count + 1) * 3); j++)
_palette[index * 3 + j] = _stream->readByte() << 2;
_stream->skip((255 - count) * 3);
_paletteDirty = true;
size -= (768 + 2);
}
_stream->read(_videoBuffer[0], size);
_videoBufferLen[0] = size;
Common::Rect rect(part.left, part.top, part.right + 1, part.bottom + 1);
if (renderFrame(rect))
_dirtyRects.push_back(rect);
} else if (part.type == kPartTypeSeparator) {
// Ignore
} else if (part.type == kPartTypeFile) {
// Ignore
_stream->skip(part.size);
} else if (part.type == kPartType4) {
// Unknown, ignore
_stream->skip(part.size);
} else if (part.type == kPartTypeSubtitle) {
_subtitle = part.id;
_stream->skip(part.size);
} else {
warning("VMDDecoder::processFrame(): Unknown frame part type %d, size %d (%d of %d)",
part.type, part.size, i + 1, _partsPerFrame);
}
}
if (startSound && _soundEnabled) {
if (_hasSound && _audioStream) {
if (_autoStartSound)
_mixer->playStream(_soundType, &_audioHandle, _audioStream,
-1, Audio::Mixer::kMaxChannelVolume, 0, DisposeAfterUse::NO);
_soundStage = kSoundPlaying;
} else
_soundStage = kSoundNone;
}
if (((uint32)_curFrame == (_frameCount - 1)) && (_soundStage == 2)) {
_audioStream->finish();
_soundStage = kSoundFinished;
}
}
bool VMDDecoder::renderFrame(Common::Rect &rect) {
Common::Rect realRect, fakeRect;
if (!getRenderRects(rect, realRect, fakeRect))
return false;
if (_externalCodec) {
if (!_codec)
return false;
Common::MemoryReadStream frameStream(_videoBuffer[0], _videoBufferLen[0]);
const Graphics::Surface *codecSurf = _codec->decodeFrame(frameStream);
if (!codecSurf)
return false;
rect = Common::Rect(_x, _y, _x + codecSurf->w, _y + codecSurf->h);
rect.clip(Common::Rect(_x, _y, _x + _width, _y + _height));
renderBlockWhole(_surface, (const byte *)codecSurf->getPixels(), rect);
return true;
}
uint8 srcBuffer = 0;
byte *dataPtr = _videoBuffer[srcBuffer];
uint32 dataSize = _videoBufferLen[srcBuffer] - 1;
uint8 type = *dataPtr++;
if (type & 0x80) {
// Frame data is compressed
type &= 0x7F;
if ((type == 2) && (rect.width() == _surface.w) && (_x == 0) && (_blitMode == 0)) {
// Directly uncompress onto the video surface
const int offsetX = rect.left * _surface.format.bytesPerPixel;
const int offsetY = (_y + rect.top) * _surface.pitch;
const int offset = offsetX + offsetY;
if (deLZ77((byte *)_surface.getPixels() + offset, dataPtr, dataSize,
_surface.w * _surface.h * _surface.format.bytesPerPixel - offset))
return true;
}
srcBuffer = 1;
_videoBufferLen[srcBuffer] =
deLZ77(_videoBuffer[srcBuffer], dataPtr, dataSize, _videoBufferSize);
dataPtr = _videoBuffer[srcBuffer];
dataSize = _videoBufferLen[srcBuffer];
}
Common::Rect *blockRect = &fakeRect;
Graphics::Surface *surface = &_surface;
if (_blitMode == 0) {
*blockRect = Common::Rect(blockRect->left + _x, blockRect->top + _y,
blockRect->right + _x, blockRect->bottom + _y);
} else {
surface = &_8bppSurface[2];
}
// Evaluate the block type
if (type == 0x01)
renderBlockSparse (*surface, dataPtr, *blockRect);
else if (type == 0x02)
renderBlockWhole (*surface, dataPtr, *blockRect);
else if (type == 0x03)
renderBlockRLE (*surface, dataPtr, *blockRect);
else if (type == 0x42)
renderBlockWhole4X (*surface, dataPtr, *blockRect);
else if ((type & 0x0F) == 0x02)
renderBlockWhole2Y (*surface, dataPtr, *blockRect);
else
renderBlockSparse2Y(*surface, dataPtr, *blockRect);
if (_blitMode > 0) {
if (_bytesPerPixel == 2)
blit16(*surface, *blockRect);
else if (_bytesPerPixel == 3)
blit24(*surface, *blockRect);
*blockRect = Common::Rect(blockRect->left + _x, blockRect->top + _y,
blockRect->right + _x, blockRect->bottom + _y);
}
rect = *blockRect;
return true;
}
bool VMDDecoder::getRenderRects(const Common::Rect &rect,
Common::Rect &realRect, Common::Rect &fakeRect) {
realRect = rect;
fakeRect = rect;
if (_blitMode == 0) {
realRect = Common::Rect(realRect.left - _x, realRect.top - _y,
realRect.right - _x, realRect.bottom - _y);
fakeRect = Common::Rect(fakeRect.left - _x, fakeRect.top - _y,
fakeRect.right - _x, fakeRect.bottom - _y);
} else if (_blitMode == 1) {
realRect = Common::Rect(rect.left / _bytesPerPixel, rect.top,
rect.right / _bytesPerPixel, rect.bottom);
realRect = Common::Rect(realRect.left - _x, realRect.top - _y,
realRect.right - _x, realRect.bottom - _y);
fakeRect = Common::Rect(fakeRect.left - _x * _bytesPerPixel, fakeRect.top - _y,
fakeRect.right - _x * _bytesPerPixel, fakeRect.bottom - _y);
} else if (_blitMode == 2) {
fakeRect = Common::Rect(rect.left * _bytesPerPixel, rect.top,
rect.right * _bytesPerPixel, rect.bottom);
realRect = Common::Rect(realRect.left - _x, realRect.top - _y,
realRect.right - _x, realRect.bottom - _y);
fakeRect = Common::Rect(fakeRect.left - _x * _bytesPerPixel, fakeRect.top - _y,
fakeRect.right - _x * _bytesPerPixel, fakeRect.bottom - _y);
}
realRect.clip(Common::Rect(_surface.w, _surface.h));
fakeRect.clip(Common::Rect(_surface.w * _bytesPerPixel, _surface.h));
if (!realRect.isValidRect() || realRect.isEmpty())
return false;
if (!fakeRect.isValidRect() || realRect.isEmpty())
return false;
return true;
}
void VMDDecoder::blit16(const Graphics::Surface &srcSurf, Common::Rect &rect) {
rect = Common::Rect(rect.left / 2, rect.top, rect.right / 2, rect.bottom);
Common::Rect srcRect = rect;
rect.clip(_surface.w, _surface.h);
Graphics::PixelFormat pixelFormat = getPixelFormat();
// We cannot use getBasePtr here because srcSurf.format.bytesPerPixel is
// different from _bytesPerPixel.
const byte *src = (const byte *)srcSurf.getPixels() +
(srcRect.top * srcSurf.pitch) + srcRect.left * _bytesPerPixel;
byte *dst = (byte *)_surface.getBasePtr(_x + rect.left, _y + rect.top);
for (int i = 0; i < rect.height(); i++) {
const byte *srcRow = src;
byte *dstRow = dst;
for (int j = 0; j < rect.width(); j++, srcRow += 2, dstRow += _surface.format.bytesPerPixel) {
uint16 data = READ_LE_UINT16(srcRow);
byte r = ((data & 0x7C00) >> 10) << 3;
byte g = ((data & 0x03E0) >> 5) << 3;
byte b = ((data & 0x001F) >> 0) << 3;
uint32 c = pixelFormat.RGBToColor(r, g, b);
if ((r == 0) && (g == 0) && (b == 0))
c = 0;
if (_surface.format.bytesPerPixel == 2)
*((uint16 *)dstRow) = (uint16) c;
else if (_surface.format.bytesPerPixel == 4)
*((uint32 *)dstRow) = (uint32) c;
}
src += srcSurf .pitch;
dst += _surface.pitch;
}
}
void VMDDecoder::blit24(const Graphics::Surface &srcSurf, Common::Rect &rect) {
rect = Common::Rect(rect.left / 3, rect.top, rect.right / 3, rect.bottom);
Common::Rect srcRect = rect;
rect.clip(_surface.w, _surface.h);
Graphics::PixelFormat pixelFormat = getPixelFormat();
// We cannot use getBasePtr here because srcSurf.format.bytesPerPixel is
// different from _bytesPerPixel.
const byte *src = (const byte *)srcSurf.getPixels() +
(srcRect.top * srcSurf.pitch) + srcRect.left * _bytesPerPixel;
byte *dst = (byte *)_surface.getBasePtr(_x + rect.left, _y + rect.top);
for (int i = 0; i < rect.height(); i++) {
const byte *srcRow = src;
byte *dstRow = dst;
for (int j = 0; j < rect.width(); j++, srcRow += 3, dstRow += _surface.format.bytesPerPixel) {
byte r = srcRow[2];
byte g = srcRow[1];
byte b = srcRow[0];
uint32 c = pixelFormat.RGBToColor(r, g, b);
if ((r == 0) && (g == 0) && (b == 0))
c = 0;
if (_surface.format.bytesPerPixel == 2)
*((uint16 *)dstRow) = (uint16) c;
else if (_surface.format.bytesPerPixel == 4)
*((uint32 *)dstRow) = (uint32) c;
}
src += srcSurf .pitch;
dst += _surface.pitch;
}
}
void VMDDecoder::emptySoundSlice(uint32 size) {
byte *soundBuf = (byte *)malloc(size);
if (soundBuf) {
uint32 flags = 0;
memset(soundBuf, 0, size);
flags |= (_soundBytesPerSample == 2) ? Audio::FLAG_16BITS : 0;
flags |= (_soundStereo > 0) ? Audio::FLAG_STEREO : 0;
_audioStream->queueBuffer(soundBuf, size, DisposeAfterUse::YES, flags);
}
}
void VMDDecoder::filledSoundSlice(uint32 size) {
if (!_audioStream) {
_stream->skip(size);
return;
}
Common::SeekableReadStream *data = _stream->readStream(size);
Audio::AudioStream *sliceStream = 0;
if (_audioFormat == kAudioFormat8bitRaw)
sliceStream = create8bitRaw(data);
else if (_audioFormat == kAudioFormat16bitDPCM)
sliceStream = create16bitDPCM(data);
else if (_audioFormat == kAudioFormat16bitADPCM)
sliceStream = create16bitADPCM(data);
if (sliceStream)
_audioStream->queueAudioStream(sliceStream);
}
void VMDDecoder::filledSoundSlices(uint32 size, uint32 mask) {
bool fillInfo[32];
uint8 max;
uint8 n = evaluateMask(mask, fillInfo, max);
int32 extraSize;
extraSize = size - n * _soundDataSize;
if (_soundSlicesCount > 32)
extraSize -= (_soundSlicesCount - 32) * _soundDataSize;
if (n > 0)
extraSize /= n;
for (uint8 i = 0; i < max; i++)
if (fillInfo[i])
filledSoundSlice(_soundDataSize + extraSize);
else
emptySoundSlice(_soundDataSize * _soundBytesPerSample);
if (_soundSlicesCount > 32)
filledSoundSlice((_soundSlicesCount - 32) * _soundDataSize + _soundHeaderSize);
}
uint8 VMDDecoder::evaluateMask(uint32 mask, bool *fillInfo, uint8 &max) {
max = MIN<int>(_soundSlicesCount - 1, 31);
uint8 n = 0;
for (int i = 0; i < max; i++) {
if (!(mask & 1)) {
n++;
*fillInfo++ = true;
} else
*fillInfo++ = false;
mask >>= 1;
}
return n;
}
Audio::AudioStream *VMDDecoder::create8bitRaw(Common::SeekableReadStream *stream) {
int flags = Audio::FLAG_UNSIGNED;
if (_soundStereo != 0)
flags |= Audio::FLAG_STEREO;
return Audio::makePCMStream(stream, _soundFreq, flags, DisposeAfterUse::YES);
}
class DPCMStream : public Audio::AudioStream {
public:
DPCMStream(Common::SeekableReadStream *stream, int rate, int channels) {
_stream = stream;
_rate = rate;
_channels = channels;
}
~DPCMStream() {
delete _stream;
}
int readBuffer(int16 *buffer, const int numSamples);
uint getChannels() const { return _channels; }
int getRate() const { return _rate; }
bool endOfData() const { return _stream->pos() >= _stream->size() || _stream->eos() || _stream->err(); }
private:
Common::SeekableReadStream *_stream;
int _channels;
int _rate;
int _buffer[2];
};
int DPCMStream::readBuffer(int16 *buffer, const int numSamples) {
static const uint16 tableDPCM[128] = {
0x0000, 0x0008, 0x0010, 0x0020, 0x0030, 0x0040, 0x0050, 0x0060, 0x0070, 0x0080,
0x0090, 0x00A0, 0x00B0, 0x00C0, 0x00D0, 0x00E0, 0x00F0, 0x0100, 0x0110, 0x0120,
0x0130, 0x0140, 0x0150, 0x0160, 0x0170, 0x0180, 0x0190, 0x01A0, 0x01B0, 0x01C0,
0x01D0, 0x01E0, 0x01F0, 0x0200, 0x0208, 0x0210, 0x0218, 0x0220, 0x0228, 0x0230,
0x0238, 0x0240, 0x0248, 0x0250, 0x0258, 0x0260, 0x0268, 0x0270, 0x0278, 0x0280,
0x0288, 0x0290, 0x0298, 0x02A0, 0x02A8, 0x02B0, 0x02B8, 0x02C0, 0x02C8, 0x02D0,
0x02D8, 0x02E0, 0x02E8, 0x02F0, 0x02F8, 0x0300, 0x0308, 0x0310, 0x0318, 0x0320,
0x0328, 0x0330, 0x0338, 0x0340, 0x0348, 0x0350, 0x0358, 0x0360, 0x0368, 0x0370,
0x0378, 0x0380, 0x0388, 0x0390, 0x0398, 0x03A0, 0x03A8, 0x03B0, 0x03B8, 0x03C0,
0x03C8, 0x03D0, 0x03D8, 0x03E0, 0x03E8, 0x03F0, 0x03F8, 0x0400, 0x0440, 0x0480,
0x04C0, 0x0500, 0x0540, 0x0580, 0x05C0, 0x0600, 0x0640, 0x0680, 0x06C0, 0x0700,
0x0740, 0x0780, 0x07C0, 0x0800, 0x0900, 0x0A00, 0x0B00, 0x0C00, 0x0D00, 0x0E00,
0x0F00, 0x1000, 0x1400, 0x1800, 0x1C00, 0x2000, 0x3000, 0x4000
};
assert((numSamples % _channels) == 0);
int samples = 0;
// Our starting position
if (_stream->pos() == 0) {
for (int i = 0; i < _channels; i++)
*buffer++ = _buffer[i] = _stream->readSint16LE();
samples += _channels;
}
while (!endOfData() && samples < numSamples) {
for (int i = 0; i < _channels; i++) {
byte data = _stream->readByte();
if (data & 0x80)
_buffer[i] -= tableDPCM[data & 0x7f];
else
_buffer[i] += tableDPCM[data];
*buffer++ = _buffer[i] = CLIP<int32>(_buffer[i], -32768, 32767);
}
samples += _channels;
}
return samples;
}
Audio::AudioStream *VMDDecoder::create16bitDPCM(Common::SeekableReadStream *stream) {
return new DPCMStream(stream, _soundFreq, (_soundStereo == 0) ? 1 : 2);
}
class VMD_ADPCMStream : public Audio::DVI_ADPCMStream {
public:
VMD_ADPCMStream(Common::SeekableReadStream *stream, DisposeAfterUse::Flag disposeAfterUse,
int rate, int channels) : Audio::DVI_ADPCMStream(new Common::SeekableSubReadStream(stream, 3, stream->size(), disposeAfterUse), DisposeAfterUse::YES, rate, channels, 0) {
// FIXME: Using the same predictor/index for two channels probably won't work
// properly However, we have no samples of this, so an assert is here for now.
// Also, since the DPCM stereo has a second predictor, I'm lead to believe
// all VMD with ADPCM are mono unless they changed the code in a later
// revision.
assert(channels == 1);
stream->seek(0);
_startPredictorValue = stream->readSint16LE();
_startIndexValue = stream->readByte();
reset();
}
protected:
virtual void reset() {
Audio::DVI_ADPCMStream::reset();
_status.ima_ch[0].last = _startPredictorValue;
_status.ima_ch[0].stepIndex = _startIndexValue;
}
private:
int32 _startPredictorValue;
int32 _startIndexValue;
};
Audio::AudioStream *VMDDecoder::create16bitADPCM(Common::SeekableReadStream *stream) {
return new VMD_ADPCMStream(stream, DisposeAfterUse::YES, _soundFreq, (_soundStereo == 0) ? 1 : 2);
}
Graphics::PixelFormat VMDDecoder::getPixelFormat() const {
if (_externalCodec) {
if (_codec)
return _codec->getPixelFormat();
// If we don't have the needed codec, just assume it's in the
// current screen format
return g_system->getScreenFormat();
}
if (_blitMode > 0)
return g_system->getScreenFormat();
return Graphics::PixelFormat::createFormatCLUT8();
}
bool VMDDecoder::getPartCoords(int16 frame, PartType type, int16 &x, int16 &y, int16 &width, int16 &height) {
if (frame >= ((int32) _frameCount))
return false;
Frame &f = _frames[frame];
// Look for a part matching the requested type, stopping at a separator
Part *part = 0;
for (int i = 0; i < _partsPerFrame; i++) {
Part &p = f.parts[i];
if ((p.type == kPartTypeSeparator) || (p.type == type)) {
part = &p;
break;
}
}
if (!part)
return false;
x = part->left;
y = part->top;
width = part->right - part->left + 1;
height = part->bottom - part->top + 1;
return true;
}
bool VMDDecoder::getFrameCoords(int16 frame, int16 &x, int16 &y, int16 &width, int16 &height) {
return getPartCoords(frame, kPartTypeVideo, x, y, width, height);
}
bool VMDDecoder::hasEmbeddedFiles() const {
return !_files.empty();
}
bool VMDDecoder::hasEmbeddedFile(const Common::String &fileName) const {
for (Common::Array<File>::const_iterator file = _files.begin(); file != _files.end(); ++file)
if (!file->name.compareToIgnoreCase(fileName))
return true;
return false;
}
Common::SeekableReadStream *VMDDecoder::getEmbeddedFile(const Common::String &fileName) const {
const File *file = 0;
for (Common::Array<File>::const_iterator it = _files.begin(); it != _files.end(); ++it)
if (!it->name.compareToIgnoreCase(fileName)) {
file = &*it;
break;
}
if (!file)
return 0;
if ((file->size - 20) != file->realSize) {
warning("VMDDecoder::getEmbeddedFile(): Sizes for \"%s\" differ! (%d, %d)",
fileName.c_str(), (file->size - 20), file->realSize);
return 0;
}
if (!_stream->seek(file->offset)) {
warning("VMDDecoder::getEmbeddedFile(): Can't seek to offset %d to (file \"%s\")",
file->offset, fileName.c_str());
return 0;
}
byte *data = (byte *) malloc(file->realSize);
if (_stream->read(data, file->realSize) != file->realSize) {
free(data);
warning("VMDDecoder::getEmbeddedFile(): Couldn't read %d bytes (file \"%s\")",
file->realSize, fileName.c_str());
return 0;
}
Common::MemoryReadStream *stream =
new Common::MemoryReadStream(data, file->realSize, DisposeAfterUse::YES);
return stream;
}
int32 VMDDecoder::getSubtitleIndex() const {
return _subtitle;
}
bool VMDDecoder::hasVideo() const {
return _hasVideo;
}
bool VMDDecoder::isPaletted() const {
return _isPaletted;
}
void VMDDecoder::setAutoStartSound(bool autoStartSound) {
_autoStartSound = autoStartSound;
}
AdvancedVMDDecoder::AdvancedVMDDecoder(Audio::Mixer::SoundType soundType) {
_decoder = new VMDDecoder(g_system->getMixer(), soundType);
_decoder->setAutoStartSound(false);
}
AdvancedVMDDecoder::~AdvancedVMDDecoder() {
close();
delete _decoder;
}
bool AdvancedVMDDecoder::loadStream(Common::SeekableReadStream *stream) {
close();
if (!_decoder->loadStream(stream))
return false;
if (_decoder->hasVideo()) {
_videoTrack = new VMDVideoTrack(_decoder);
addTrack(_videoTrack);
}
if (_decoder->hasSound()) {
_audioTrack = new VMDAudioTrack(_decoder);
addTrack(_audioTrack);
}
return true;
}
void AdvancedVMDDecoder::close() {
VideoDecoder::close();
_decoder->close();
}
AdvancedVMDDecoder::VMDVideoTrack::VMDVideoTrack(VMDDecoder *decoder) : _decoder(decoder) {
}
uint16 AdvancedVMDDecoder::VMDVideoTrack::getWidth() const {
return _decoder->getWidth();
}
uint16 AdvancedVMDDecoder::VMDVideoTrack::getHeight() const {
return _decoder->getHeight();
}
Graphics::PixelFormat AdvancedVMDDecoder::VMDVideoTrack::getPixelFormat() const {
return _decoder->getPixelFormat();
}
int AdvancedVMDDecoder::VMDVideoTrack::getCurFrame() const {
return _decoder->getCurFrame();
}
int AdvancedVMDDecoder::VMDVideoTrack::getFrameCount() const {
return _decoder->getFrameCount();
}
const Graphics::Surface *AdvancedVMDDecoder::VMDVideoTrack::decodeNextFrame() {
return _decoder->decodeNextFrame();
}
const byte *AdvancedVMDDecoder::VMDVideoTrack::getPalette() const {
return _decoder->getPalette();
}
bool AdvancedVMDDecoder::VMDVideoTrack::hasDirtyPalette() const {
return _decoder->hasDirtyPalette();
}
Common::Rational AdvancedVMDDecoder::VMDVideoTrack::getFrameRate() const {
return _decoder->getFrameRate();
}
AdvancedVMDDecoder::VMDAudioTrack::VMDAudioTrack(VMDDecoder *decoder) : _decoder(decoder) {
}
Audio::Mixer::SoundType AdvancedVMDDecoder::VMDAudioTrack::getSoundType() const {
return _decoder->getSoundType();
}
Audio::AudioStream *AdvancedVMDDecoder::VMDAudioTrack::getAudioStream() const {
return _decoder->getAudioStream();
}
} // End of namespace Video
#endif // VIDEO_COKTELDECODER_H
| clone2727/cabal | video/coktel_decoder.cpp | C++ | gpl-2.0 | 67,288 |
/**
* @package AcyMailing for Joomla!
* @version 4.4.1
* @author acyba.com
* @copyright (C) 2009-2013 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
@import url("component_default.css");
#acyarchivelisting .inputbox, #acyuserinfo .inputbox{
color:#666 !important;
border:1px solid #ddd !important;
margin-right: 10px!important;
padding: 4px 10px !important;
background-image: linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
background-image: -o-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
background-image: -moz-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
background-image: -webkit-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
background-image: -ms-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#ebebeb',GradientType=0 ) !important;
}
#acyarchivelisting .inputbox:hover, #acyuserinfo .inputbox:hover{
border:1px solid #ddd !important;
border-bottom:1px solid #999 !important;
box-shadow: 0 0 3px 2px #eee!important;
-moz-box-shadow: 0 0 3px 2px #eee !important;
-webkit-box-shadow: 0 0 3px 2px #eee !important;
}
#acyarchivelisting .inputbox:focus, #acyuserinfo .inputbox:focus{
border:1px solid #bbb !important;
background-color:#f5f5f5 !important;
box-shadow: 0 0 3px 2px #eee!important;
-moz-box-shadow: 0 0 3px 2px #eee !important;
-webkit-box-shadow: 0 0 3px 2px #eee !important;}
#acyarchivelisting .button, #acymodifyform .button, #unsubbutton_div .button{
color:#666 !important;
border:1px solid #ddd !important;
padding: 3px !important;
text-shadow:1px 1px 1px #fff !important;
margin-right:5px !important;
background-color:#CCC !important;
background-image: linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
background-image: -o-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
background-image: -moz-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
background-image: -webkit-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
background-image: -ms-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%) !important;
background: -ms-linear-gradient(top, ellipse cover, #e3eff3 0%,#5a99ab 100%);
background: radial-gradient(top, ellipse cover, #e3eff3 0%,#5a99ab 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#ebebeb',GradientType=0 ) !important;
}
#acyarchivelisting .button:hover, #acymodifyform .button:hover, #unsubbutton_div .button:hover {
color:#000 !important;
background-color:#f5f5f5 !important;
background-image: linear-gradient(bottom, rgb(255,255,255) 57%, rgb(238,237,237) 86%) !important;
background-image: -o-linear-gradient(bottom, rgb(255,255,255) 57%, rgb(238,237,237) 86%) !important;
background-image: -moz-linear-gradient(bottom, rgb(255,255,255) 57%, rgb(238,237,237) 86%) !important;
background-image: -webkit-linear-gradient(bottom, rgb(255,255,255) 57%, rgb(238,237,237) 86%) !important;
background-image: -ms-linear-gradient(bottom, rgb(255,255,255) 57%, rgb(238,237,237) 86%) !important;
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ebebeb', endColorstr='#ffffff',GradientType=0 ) !important;
box-shadow: 0 0 3px 2px #eee !important;
-moz-box-shadow: 0 0 3px 2px #eee !important;
-webkit-box-shadow: 0 0 3px 2px #eee !important;
}
#acyarchivelisting table{
border:0px !important;}
#acyarchivelisting .contentheading{
color:#000;
font-size:16px;
font-weight:bold;
border-bottom:1px solid #000;
padding-bottom:4px;
}
#acyarchivelisting .contentpane form{
background-color: #FFFFFF;
border-style: solid;
border-color:#ccc;
border-width: 1px;
padding: 10px;
}
#acyarchivelisting .contentpane .contentdescription{
color:#666;
font-weight:bold;
padding-top:10px;
padding-bottom:10px;
}
#acyarchivelisting .acynewbutton a:hover, #acyarchivelisting .acynewbutton a:focus{
background-color:transparent;
color:#cf5402;
}
#acyarchivelisting .sectiontableheader{
color:#333;
padding-top:25px;}
#acyarchivelisting .contentpane thead{
border-bottom:1px solid #ccc;
height:30px;
}
#acyarchivelisting .contentpane tbody{
color:#333;
}
#acyarchivelisting .sectiontableheader a{
color:#333;
text-decoration:none;
background-color:transparent;
font-weight:bold;
font-size:12px;
}
#acyarchivelisting .sectiontableheader a:hover{
background-color:transparent;
color:#666;
}
#acyarchivelisting .contentpane tbody .sectiontableentry1{
text-align:center;
height:30px;
background-color:#eeeded;
border-bottom:1px solid #fff;
}
#acyarchivelisting .contentpane tbody .sectiontableentry1:hover{
text-align:center;
height:30px;
background-color:#e6e6e6;
}
#acyarchivelisting .contentpane tbody .sectiontableentry1 a{
text-decoration:none;
color:#666;
background-color:transparent;
}
#acyarchivelisting .contentpane tbody .sectiontableentry1 a:hover{
color:#000;
background-color:transparent;
text-decoration:underline;
}
#acyarchivelisting .contentpane tbody .sectiontableentry2{
text-align:center;
height:30px;
background-color:#f5f5f5;
border-bottom:1px solid #fff;
}
#acyarchivelisting .contentpane tbody .sectiontableentry2:hover{
text-align:center;
height:30px;
background-color:#e6e6e6;
}
#acyarchivelisting .contentpane tbody .sectiontableentry2 a{
text-decoration:none;
color:#666;
background-color:transparent;
}
#acyarchivelisting .contentpane tbody .sectiontableentry2 a:hover{
color:#000;
background-color:transparent;
text-decoration:underline;
}
#acylistslisting .componentheading{
color:#000;
font-weight:bold;
border-bottom:1px solid #000;
margin-bottom:10px;
font-weight:bold;
font-size:16px;
padding-bottom:4px;
}
#acylistslisting .list_name a{
background-color: transparent;
color:#666;
cursor: pointer;
font-size: 12px;
font-weight: bold;
text-decoration: none;
}
#acylistslisting .list_name a:hover, #acylistslisting .list_name a:focus {
text-decoration:underline;
background-color:transparent;
color:#666;
}
#acylistslisting .list_description{
color:#333;
padding:0px;
}
#acylistslisting p{
line-height: 15px;
margin: 3px 0;}
div.acymailing_list:hover{
background-color :#f5f5f5;
}
#acylistslisting .contentpane thead td{
padding-top:20px;
}
#acylistslisting div.acymailing_list{
border:none;
border-bottom:1px solid #ccc;
margin: 0px;
padding-top: 10px;
}
#acyusersubscription th{
color:#666;
padding: 4px 5px;
background-image: linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%);
background-image: -o-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%);
background-image: -moz-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%);
background-image: -webkit-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%);
background-image: -ms-linear-gradient(bottom, rgb(235,235,235) 21%, rgb(255,255,255) 58%);
border:1px solid #ccc;}
#acyusersubscription tr{
border-bottom:1px solid #ccc !important;}
#acyusersubscription .acystatus{
padding-top:20px;
padding-bottom: 25px;
}
#acymodifyform .adminform{
color:#666;
text-align:left;
}
#acymodifyform fieldset{
padding:0px;
}
#acyuserinfo{
background-color:#fff;
border:1px solid #ccc;
}
#acyuserinfo #trname td{
padding-top:10px;}
#acyuserinfo #trplus td{
padding-bottom:10px;}
#acyuserinfo select{
border:1px solid #dcc2b2;}
#acyuserinfo .key{
color:#666;
font-weight:bold;
font-size:11px;
padding-left:20px;
}
#acyusersubscription{
background-color:#FFF;
border:1px solid #ccc;
}
#acymodifyform legend{
color:#000;
font-size:16px;
font-weight:bold;
padding:0px;
border-bottom:1px solid #000;
margin-bottom:20px;
padding-bottom:4px;
}
#acyuserinfo input{
margin:0 5px;
}
#acyusersubscription .list_name{
border-bottom: 1px solid #dddddd;
color: #666;
font-size: 12px;
font-weight: bold;
margin: 0px;
padding-top: 20px;
text-align: left;
}
#acyusersubscription .list_description{
text-align:left;
font-size:12px;
color:#333;
padding:0px;
padding-top:5px;
}
#acymodifyform .acymodifybutton{
text-align:center;
}
#unsubpage{
padding: 20px 20px 40px;
font-size:11px;
border:1px solid #ccc;}
#unsubpage .unsubsurvey, #unsubpage .unsubintro{
padding:0px;}
#unsubpage input{
margin-right:5px;}
#unsubpage .unsubintro{
font-weight:bold;
color:#000;
font-size:12px;
padding:0px;
border-bottom: 1px solid #000;
padding-bottom:4px;
margin-bottom:10px;}
#unsubpage .unsuboptions{
padding:0px;}
#unsubpage .unsubsurveytext{
border-bottom: 1px solid #000;
color: #000;
display: block;
font-size: 12px;
font-weight: bold;
margin-bottom: 10px;
margin-top: 30px;
padding-bottom: 4px;
}
#unsubpage .unsuboptions div{
font-size: 11px;
margin-top: 6px;
font-weight:normal;
}
#unsubpage .unsubsurvey div{
font-size: 11px;
margin-top: 6px;
font-weight:normal;
}
#unsubpage .unsubsurvey textarea{
margin-top:15px;
border:1px solid #ccc;
width:100%;
margin-bottom: 10px;
background-color::#fff;
}
#unsubpage .unsubsurvey textarea:hover{
border:1px solid #aaa;
border-right:1px solid #999;
border-bottom:1px solid #999;
}
#unsubpage .input{
padding-right:10px;
}
#unsubbutton_div{
text-align:center;
}
#acyarchiveview{
border:1px solid #ccc;
padding:10px;}
#acyarchiveview .contentheading{
font-weight:bold;
color:#000;
font-size:16px;}
#acyuserinfo .invalid{
border:1px solid #999 !important;}
| pirke05/procut | media/com_acymailing/css/component_default_square_black.css | CSS | gpl-2.0 | 10,210 |
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2017 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
class PluginFooBar {
} | eltharin/glpi | tests/fixtures/pluginfoobar.php | PHP | gpl-2.0 | 1,186 |
/* [kernel/drivers/input/misc/simple_remote.c]
*
* Copyright (C) [2010] Sony Ericsson Mobile Communications AB.
*
* Authors: Takashi Shiina <takashi.shiina@sonyericsson.com>
* Tadashi Kubo <tadashi.kubo@sonyericsson.com>
* Joachim Holst <joachim.holst@sonyericsson.com>
* Torbjorn Eklund <torbjorn.eklund@sonyericsson.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*/
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <linux/workqueue.h>
#include <linux/err.h>
#include <linux/switch.h>
#include <linux/input.h>
#include <linux/delay.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/mutex.h>
#include <linux/kernel.h>
#include <asm/atomic.h>
#include <linux/ctype.h>
#include <linux/timer.h>
#include <linux/kernel.h>
#include <linux/simple_remote.h>
#define SIMPLE_REMOTE_APPKEY BTN_3
#define DETECTION_DELAY 200
#define DETECTION_CYCLES 20
#define MAX_NODEV_CYCLES 10
#define MIN_NUM_OMTP_DETECTIONS 3
#define MIN_NUM_HEADPHONE_DETECTIONS 5
#define DETECT_WORK_DELAY \
(jiffies + msecs_to_jiffies(DETECTION_DELAY))
static irqreturn_t simple_remote_button_irq_handler(int irq, void *dev_id);
static irqreturn_t simple_remote_detect_irq_handler(int irq, void *dev_id);
enum dev_state {
NO_DEVICE = 0,
DEVICE_HEADSET,
DEVICE_HEADPHONE,
DEVICE_UNSUPPORTED = 0xFE00,
DEVICE_UNKNOWN = 0xFF00,
};
static int simple_remote_acc_min[] = {
0, /* DEVICE_HEADPHONE */
200, /* DEVICE_HEADSET */
};
static int simple_remote_acc_max[] = {
200, /* DEVICE_HEADPHONE */
1599, /* DEVICE_HEADSET */
};
static int simple_remote_btn_min[] = {
0, /* BTN_0 */
100, /* BTN_1 */
300, /* BTN_2 */
500, /* BTN_3 */
};
static int simple_remote_btn_max[] = {
99, /* BTN_0 */
199, /* BTN_1 */
399, /* BTN_2 */
699, /* BTN_3 */
};
static int simple_remote_btn_trig_level[] = {
460, /* Default trig level */
};
static int simple_remote_trig_period_freq[] = {
512, /* Default trig period frequency*/
};
static int simple_remote_trig_period_time[] = {
16, /* Default trig period time*/
};
static int simple_remote_trig_hysteresis_freq[] = {
512, /* Default trig hysteresis freq*/
};
static int simple_remote_trig_hysteresis_time[] = {
16, /* Default trig hysteresis time*/
};
static ssize_t simple_remote_attrs_show_property(struct device *dev,
struct device_attribute *attr,
char *buf);
static ssize_t simple_remote_attrs_store_property(struct device *dev,
struct device_attribute *attr,
const char *buf,
size_t count);
#define SIMPLE_REMOTE_ATTR(_name) \
{\
.attr = { .name = _name,\
.mode = (S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH),\
},\
.show = simple_remote_attrs_show_property,\
.store = simple_remote_attrs_store_property,\
}
#define SIMPLE_REMOTE_ACC_MIN_VALS_NAME "accessory_min_vals"
#define SIMPLE_REMOTE_ACC_MAX_VALS_NAME "accessory_max_vals"
#define SIMPLE_REMOTE_BTN_MIN_VALS_NAME "button_min_vals"
#define SIMPLE_REMOTE_BTN_MAX_VALS_NAME "button_max_vals"
#define SIMPLE_REMOTE_TRIG_LVL_NAME "btn_trig_level"
#define SIMPLE_REMOTE_TRIG_PRD_F_NAME "btn_trig_period_freq"
#define SIMPLE_REMOTE_TRIG_PRD_T_NAME "btn_trig_period_time"
#define SIMPLE_REMOTE_TRIG_HST_F_NAME "btn_trig_hyst_freq"
#define SIMPLE_REMOTE_TRIG_HST_T_NAME "btn_trig_hyst_time"
static struct device_attribute simple_remote_attrs[] = {
SIMPLE_REMOTE_ATTR(SIMPLE_REMOTE_ACC_MIN_VALS_NAME),
SIMPLE_REMOTE_ATTR(SIMPLE_REMOTE_ACC_MAX_VALS_NAME),
SIMPLE_REMOTE_ATTR(SIMPLE_REMOTE_BTN_MIN_VALS_NAME),
SIMPLE_REMOTE_ATTR(SIMPLE_REMOTE_BTN_MAX_VALS_NAME),
SIMPLE_REMOTE_ATTR(SIMPLE_REMOTE_TRIG_LVL_NAME),
SIMPLE_REMOTE_ATTR(SIMPLE_REMOTE_TRIG_PRD_F_NAME),
SIMPLE_REMOTE_ATTR(SIMPLE_REMOTE_TRIG_PRD_T_NAME),
SIMPLE_REMOTE_ATTR(SIMPLE_REMOTE_TRIG_HST_F_NAME),
SIMPLE_REMOTE_ATTR(SIMPLE_REMOTE_TRIG_HST_T_NAME),
};
struct simple_remote_driver {
struct switch_dev swdev;
struct input_dev *indev;
struct input_dev *indev_appkey;
atomic_t detection_in_progress;
atomic_t detect_cycle;
atomic_t initialized;
u8 pressed_button;
u8 nodetect_cycles;
u8 num_omtp_detections;
u8 num_headphone_detections;
enum dev_state current_accessory_state;
struct work_struct plug_det_work;
struct work_struct btn_det_work;
struct mutex simple_remote_mutex;
struct timer_list plug_det_timer;
enum dev_state new_accessory_state;
int client_counter;
struct device *dev;
struct simple_remote_pf_interface *interface;
};
static int simple_remote_attrs_set_data_buffer(char *buf, const int *array,
int array_len)
{
int j;
int buf_pos = 0;
for (j = 0; j < array_len; j++) {
buf_pos += snprintf(&buf[buf_pos], PAGE_SIZE - buf_pos,
"%d ", array[j]);
if (buf_pos >= PAGE_SIZE) {
pr_err("*** %s - Error! len (%d) > PAGE_SIZE\n",
__func__, buf_pos);
return -E2BIG;
}
}
buf[buf_pos - 1] = '\n';
return buf_pos;
}
static ssize_t simple_remote_attrs_show_property(struct device *dev,
struct device_attribute *attr,
char *buf) {
int retval = -EIO;
int val = -1;
struct simple_remote_driver *jack = dev_get_drvdata(dev);
mutex_lock(&jack->simple_remote_mutex);
if (!strcmp(SIMPLE_REMOTE_ACC_MIN_VALS_NAME, attr->attr.name)) {
retval = simple_remote_attrs_set_data_buffer(
buf, simple_remote_acc_min,
ARRAY_SIZE(simple_remote_acc_min));
goto done;
}
if (!strcmp(SIMPLE_REMOTE_ACC_MAX_VALS_NAME, attr->attr.name)) {
retval = simple_remote_attrs_set_data_buffer(
buf, simple_remote_acc_max,
ARRAY_SIZE(simple_remote_acc_max));
goto done;
}
if (!strcmp(SIMPLE_REMOTE_BTN_MIN_VALS_NAME, attr->attr.name)) {
retval = simple_remote_attrs_set_data_buffer(
buf, simple_remote_btn_min,
ARRAY_SIZE(simple_remote_btn_min));
goto done;
}
if (!strcmp(SIMPLE_REMOTE_BTN_MAX_VALS_NAME, attr->attr.name)) {
retval = simple_remote_attrs_set_data_buffer(
buf, simple_remote_btn_max,
ARRAY_SIZE(simple_remote_btn_max));
goto done;
}
if (!strcmp(SIMPLE_REMOTE_TRIG_LVL_NAME, attr->attr.name))
retval = jack->interface->get_trig_level(&val);
else if (!strcmp(SIMPLE_REMOTE_TRIG_PRD_F_NAME, attr->attr.name))
retval = jack->interface->get_period_freq(&val);
else if (!strcmp(SIMPLE_REMOTE_TRIG_PRD_T_NAME, attr->attr.name))
retval = jack->interface->get_period_time(&val);
else if (!strcmp(SIMPLE_REMOTE_TRIG_HST_F_NAME, attr->attr.name))
retval = jack->interface->get_hysteresis_freq(&val);
else if (!strcmp(SIMPLE_REMOTE_TRIG_HST_T_NAME, attr->attr.name))
retval = jack->interface->get_hysteresis_time(&val);
if (!retval)
retval = scnprintf(buf, PAGE_SIZE, "%d\n", val);
done:
mutex_unlock(&jack->simple_remote_mutex);
return retval;
}
static void simple_remote_attrs_update_data(const char *buf, size_t count,
int *array, int array_len)
{
char tmp_buf[10];
int i, stepper;
int value_count = 0;
long conversion = 0;
char *q = (char *)buf;
do {
i = strcspn(q, " \t,\r\n");
for (stepper = 0; stepper < i && stepper < sizeof(tmp_buf) - 1;
stepper++) {
/* First char could be - sign.
Store it anyway */
if (0 == stepper)
tmp_buf[stepper] = q[stepper];
else if (isdigit(q[stepper]))
tmp_buf[stepper] = q[stepper];
else
return;
}
tmp_buf[stepper] = '\0';
if (strict_strtol(tmp_buf, 10, &conversion))
return;
/* Making sure that we get values that are in range */
if (conversion <= SHRT_MAX && conversion >= SHRT_MIN) {
array[value_count] = (short)conversion;
} else {
pr_err("%s - Value out of range. Aborting"
" change!\n", __func__);
return;
}
value_count++;
q += i+1;
count -= (i + 1);
} while (count > 0 && value_count < array_len);
}
static ssize_t simple_remote_attrs_store_property(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
long val;
struct simple_remote_driver *jack = dev_get_drvdata(dev);
mutex_lock(&jack->simple_remote_mutex);
strict_strtol(buf, 10, &val);
if (!strcmp(SIMPLE_REMOTE_ACC_MIN_VALS_NAME, attr->attr.name)) {
simple_remote_attrs_update_data(
buf, count, simple_remote_acc_min,
ARRAY_SIZE(simple_remote_acc_min));
} else if (!strcmp(SIMPLE_REMOTE_ACC_MAX_VALS_NAME, attr->attr.name)) {
simple_remote_attrs_update_data(
buf, count, simple_remote_acc_max,
ARRAY_SIZE(simple_remote_acc_max));
} else if (!strcmp(SIMPLE_REMOTE_BTN_MIN_VALS_NAME, attr->attr.name)) {
simple_remote_attrs_update_data(
buf, count, simple_remote_btn_min,
ARRAY_SIZE(simple_remote_btn_min));
} else if (!strcmp(SIMPLE_REMOTE_BTN_MAX_VALS_NAME, attr->attr.name)) {
simple_remote_attrs_update_data(
buf, count, simple_remote_btn_max,
ARRAY_SIZE(simple_remote_btn_max));
} else if (!strcmp(SIMPLE_REMOTE_TRIG_LVL_NAME, attr->attr.name))
jack->interface->set_trig_level(val);
else if (!strcmp(SIMPLE_REMOTE_TRIG_PRD_F_NAME, attr->attr.name))
jack->interface->set_period_freq(val);
else if (!strcmp(SIMPLE_REMOTE_TRIG_PRD_T_NAME, attr->attr.name))
jack->interface->set_period_time(val);
else if (!strcmp(SIMPLE_REMOTE_TRIG_HST_F_NAME, attr->attr.name))
jack->interface->set_hysteresis_freq(val);
else if (!strcmp(SIMPLE_REMOTE_TRIG_HST_T_NAME, attr->attr.name))
jack->interface->set_hysteresis_time(val);
mutex_unlock(&jack->simple_remote_mutex);
return count;
}
static int create_sysfs_interfaces(struct device *dev)
{
int i;
for (i = 0; i < ARRAY_SIZE(simple_remote_attrs); i++)
if (device_create_file(dev, simple_remote_attrs + i))
goto error;
return 0;
error:
for (i = i - 1; i >= 0; i--)
device_remove_file(dev, simple_remote_attrs + i);
dev_err(dev, "Unable to create sysfs interfaces\n");
return -EIO;
}
static void remove_sysfs_interfaces(struct device *dev)
{
int i;
for (i = 0; i < ARRAY_SIZE(simple_remote_attrs); i++)
device_remove_file(dev, simple_remote_attrs + i);
}
static u8 simple_remote_attrs_parse_button_value(
struct simple_remote_driver *jack, unsigned int adc_value)
{
int i;
u8 button = BTN_9 - BTN_0;
mutex_lock(&jack->simple_remote_mutex);
for (i = 0; i < ARRAY_SIZE(simple_remote_btn_max); i++) {
if (adc_value <= simple_remote_btn_max[i] &&
adc_value >= simple_remote_btn_min[i]) {
button = i;
break;
}
}
mutex_unlock(&jack->simple_remote_mutex);
return button;
}
static enum dev_state simple_remote_attrs_parse_accessory_type(
struct simple_remote_driver *jack, unsigned int adc_value,
u8 gpio_state)
{
if (gpio_state) {
jack->nodetect_cycles++;
dev_dbg(jack->dev, "NO_DEVICE\n");
return NO_DEVICE;
}
jack->nodetect_cycles = 0;
if (adc_value <= simple_remote_acc_max[0]
&& adc_value >= simple_remote_acc_min[0]) {
dev_dbg(jack->dev, "DEVICE_HEADPHONE\n");
return DEVICE_HEADPHONE;
} else if (adc_value <= simple_remote_acc_max[1]
&& adc_value >= simple_remote_acc_min[1]) {
dev_dbg(jack->dev, "DEVICE_HEADSET");
return DEVICE_HEADSET;
}
return DEVICE_UNKNOWN;
}
static void report_button_id(struct simple_remote_driver *jack,
u8 pressed)
{
unsigned int pressed_button;
dev_dbg(jack->dev, "Reporting button event. Button = 0x%x, "
"event = %d\n", jack->pressed_button, pressed);
pressed_button = BTN_0 + jack->pressed_button;
/* Report all button presses to both input devices. The
input device will filter the button press, and only
let through registered buttons. */
input_report_key(jack->indev, pressed_button, pressed);
input_sync(jack->indev);
input_report_key(jack->indev_appkey, pressed_button, pressed);
input_sync(jack->indev_appkey);
}
static ssize_t simple_remote_print_name(struct switch_dev *sdev, char *buf)
{
struct simple_remote_driver *jack =
container_of(sdev, struct simple_remote_driver, swdev);
switch (switch_get_state(&jack->swdev)) {
case DEVICE_UNKNOWN:
dev_info(jack->dev, "Device Unknown\n");
return snprintf(buf, PAGE_SIZE, "Device Unknown\n");
case DEVICE_UNSUPPORTED:
dev_info(jack->dev, "Device unsupported\n");
return snprintf(buf, PAGE_SIZE, "Unsupported\n");
case NO_DEVICE:
dev_info(jack->dev, "No Device\n");
return snprintf(buf, PAGE_SIZE, "No Device\n");
case DEVICE_HEADSET:
dev_info(jack->dev, "Headset\n");
return snprintf(buf, PAGE_SIZE, "Headset\n");
case DEVICE_HEADPHONE:
dev_info(jack->dev, "Headphone\n");
return snprintf(buf, PAGE_SIZE, "Headphone\n");
}
return -EINVAL;
}
static void simple_remote_report_accessory_type(
struct simple_remote_driver *jack)
{
dev_vdbg(jack->dev, "current_accessory_state = %d, new_accessory_state "
"= %d\n", jack->current_accessory_state,
jack->new_accessory_state);
if (jack->current_accessory_state != jack->new_accessory_state) {
if (DEVICE_HEADSET == jack->current_accessory_state) {
jack->interface->enable_mic_bias(0);
report_button_id(jack, 0);
jack->interface->unregister_hssd_button_interrupt(jack);
}
if (jack->current_accessory_state == DEVICE_HEADPHONE ||
jack->current_accessory_state == DEVICE_HEADSET)
switch_set_state(&jack->swdev, NO_DEVICE);
dev_dbg(jack->dev, "Accessory : ");
switch (jack->new_accessory_state) {
case DEVICE_UNKNOWN:
dev_dbg(jack->dev, "DEVICE_UNKNOWN\n");
break;
case DEVICE_UNSUPPORTED:
dev_dbg(jack->dev, "UNSUPPORTED\n");
break;
case DEVICE_HEADPHONE:
dev_dbg(jack->dev, "DEVICE_HEADPHONE\n");
break;
case NO_DEVICE:
dev_dbg(jack->dev, "NO_DEVICE\n");
break;
case DEVICE_HEADSET:
dev_dbg(jack->dev, "DEVICE_HEADSET\n");
msleep(100);
jack->interface->enable_mic_bias(1);
jack->interface->register_hssd_button_interrupt(
simple_remote_button_irq_handler, jack);
break;
default:
break;
}
switch_set_state(&jack->swdev, jack->new_accessory_state);
jack->current_accessory_state = jack->new_accessory_state;
}
}
static int simple_remote_open(struct input_dev *dev)
{
int err = 0;
struct simple_remote_driver *jack = input_get_drvdata(dev);
mutex_lock(&jack->simple_remote_mutex);
if (!jack->client_counter) {
dev_dbg(jack->dev, "Starting interrupt handling.");
err = jack->interface->register_plug_detect_interrupt
(&simple_remote_detect_irq_handler, jack);
if (!err) {
/* This will force an initial detection to
make sure that we always have a correct
headset state and detect headsets inserted
before the phone has been booted.*/
mod_timer(&jack->plug_det_timer, DETECT_WORK_DELAY);
} else if (err == -EALREADY) {
dev_info(jack->dev, "Plug detect interrupt "
"is already registered\n");
goto exit;
} else {
dev_err(jack->dev, "Failed to "
"register plug detect interrupt\n");
goto exit;
}
}
jack->client_counter++;
exit:
mutex_unlock(&jack->simple_remote_mutex);
return err;
}
static void simple_remote_close(struct input_dev *dev)
{
struct simple_remote_driver *jack = input_get_drvdata(dev);
mutex_lock(&jack->simple_remote_mutex);
if (1 == jack->client_counter) {
dev_dbg(jack->dev, "Stopping button interrupt handling.");
jack->interface->unregister_hssd_button_interrupt(jack);
jack->interface->enable_mic_bias(0);
jack->interface->unregister_plug_detect_interrupt(jack);
}
if (jack->client_counter > 0)
jack->client_counter--;
mutex_unlock(&jack->simple_remote_mutex);
}
/*
* Plug detection is performed here and this function is only called after
* the IRQ has been silent DETECTION_DELAY time (ms). This is done in order to
* avoid gitter in the IRQ line. The functionlity should be quite clear
* if the plug_detect interrupt handler is analyzed. Besides being quite fast,
* this detection scheme will make sure that we will not have false detections.
* If a HEADPHONE or UNKNOWN accessory is detected, we will continue to to call
* the detection functionality for DETECTION_DELAY * DETECTION_CYCLES because
* some accessories may generate a different accessory type than the actually
* are in some circumstances.
*/
static void simple_remote_plug_det_work(struct work_struct *work)
{
u8 getgpiovalue;
unsigned int adc_value = 2000;
unsigned int alt_adc_val = 2000;
enum dev_state state;
struct simple_remote_driver *jack =
container_of(work, struct simple_remote_driver, plug_det_work);
dev_vdbg(jack->dev, "%s - Called\n", __func__);
jack->interface->get_current_plug_status(&getgpiovalue);
if (!getgpiovalue) {
jack->interface->enable_mic_bias(1);
jack->interface->read_hs_adc(&adc_value);
dev_dbg(jack->dev, "%s - adc_value = %d\n", __func__,
adc_value);
jack->interface->enable_mic_bias(0);
}
jack->new_accessory_state =
simple_remote_attrs_parse_accessory_type(
jack, adc_value, getgpiovalue);
/* performing CTIA detection */
if (!getgpiovalue && jack->new_accessory_state == DEVICE_HEADSET) {
dev_dbg(jack->dev,
"%s - Headset detected. Checking for unsupported\n",
__func__);
jack->interface->enable_mic_bias(1);
if (0 > jack->interface->enable_alternate_adc_mode(1))
dev_warn(jack->dev,
"%s - Alternate ADC mode did not engage "
"correctly. Unsupported headset may not be"
"correctly detected!\n", __func__);
jack->interface->read_hs_adc(&alt_adc_val);
dev_dbg(jack->dev, "%s - alt_adc_val = %d\n", __func__,
alt_adc_val);
jack->interface->enable_mic_bias(0);
jack->interface->enable_alternate_adc_mode(0);
state = simple_remote_attrs_parse_accessory_type(
jack, alt_adc_val, getgpiovalue);
if (DEVICE_HEADPHONE == state) {
dev_info(jack->dev,
"%s - CTIA headset detected", __func__);
if (jack->interface->enable_alternate_headset_mode(1)) {
jack->new_accessory_state = DEVICE_UNSUPPORTED;
jack->num_omtp_detections = 0;
}
} else {
jack->num_omtp_detections++;
}
}
if (jack->new_accessory_state == DEVICE_HEADPHONE)
jack->num_headphone_detections++;
else
jack->num_headphone_detections = 0;
/*
* Avoid the conflict between audio path changing and alternate
* ADC reading.
* Accessory state report to the upper layer is deferred until OMTP
* detection cycle finishes when the accessory state is DEVICE_HEADSET.
*/
if (!(jack->new_accessory_state == DEVICE_HEADPHONE ||
jack->new_accessory_state == DEVICE_HEADSET) ||
jack->num_headphone_detections >= MIN_NUM_HEADPHONE_DETECTIONS ||
jack->num_omtp_detections >= MIN_NUM_OMTP_DETECTIONS)
simple_remote_report_accessory_type(jack);
dev_vdbg(jack->dev, "%s - used detection cycles = %d\n", __func__,
atomic_read(&jack->detect_cycle));
/* Restart detection cycle if required */
if (DETECTION_CYCLES > atomic_read(&jack->detect_cycle) &&
jack->num_omtp_detections < MIN_NUM_OMTP_DETECTIONS &&
MAX_NODEV_CYCLES > jack->nodetect_cycles) {
dev_vdbg(jack->dev, "%s - Restarting delayed work\n", __func__);
mod_timer(&jack->plug_det_timer, DETECT_WORK_DELAY);
atomic_inc(&jack->detect_cycle);
} else {
jack->nodetect_cycles = 0;
atomic_set(&jack->detection_in_progress, 0);
jack->num_omtp_detections = 0;
jack->num_headphone_detections = 0;
}
}
void simple_remote_plug_detect_tmr_func(unsigned long func_data)
{
struct simple_remote_driver *jack =
(struct simple_remote_driver *)func_data;
dev_vdbg(jack->dev, "called\n");
schedule_work(&jack->plug_det_work);
}
static irqreturn_t simple_remote_detect_irq_handler(int irq, void *dev_id)
{
struct simple_remote_driver *jack = dev_id;
dev_vdbg(jack->dev, "%s - Called\n", __func__);
atomic_set(&jack->detection_in_progress, 1);
atomic_set(&jack->detect_cycle, 0);
mod_timer(&jack->plug_det_timer, DETECT_WORK_DELAY);
return IRQ_HANDLED;
}
static void simple_remote_btn_det_work(struct work_struct *work)
{
unsigned int adc_value;
u8 button;
struct simple_remote_driver *jack =
container_of(work, struct simple_remote_driver, btn_det_work);
/* Avoid sending button events if detection is in progress
* This may happen if plug is removed while detection work
* is in progress. */
if (atomic_read(&jack->detection_in_progress) > 0) {
dev_info(jack->dev, "%s - Detection in progress. Ignoring"
" button event\n", __func__);
return;
}
atomic_set(&jack->detection_in_progress, 1);
jack->interface->read_hs_adc(&adc_value);
dev_dbg(jack->dev, "%s - ADC VAlue = %u\n", __func__, adc_value);
button = simple_remote_attrs_parse_button_value(jack, adc_value);
if (button < ARRAY_SIZE(simple_remote_btn_max))
jack->pressed_button = button;
report_button_id(jack, button < ARRAY_SIZE(simple_remote_btn_max));
atomic_set(&jack->detection_in_progress, 0);
}
static irqreturn_t simple_remote_button_irq_handler(int irq, void *data)
{
struct simple_remote_driver *jack = data;
if (atomic_read(&jack->initialized)) {
dev_dbg(jack->dev, "Received a Button interrupt\n");
schedule_work(&jack->btn_det_work);
} else {
dev_dbg(jack->dev, "Received button IRQ before initialized "
"system. Discarding\n");
}
return IRQ_HANDLED;
}
static int initialize_hardware(struct simple_remote_driver *jack)
{
int err = jack->interface->set_period_freq(
simple_remote_trig_period_freq[0]);
err |= jack->interface->set_period_time(
simple_remote_trig_period_time[0]);
err |= jack->interface->set_hysteresis_freq(
simple_remote_trig_hysteresis_freq[0]);
err |= jack->interface->set_hysteresis_time(
simple_remote_trig_hysteresis_time[0]);
err |= jack->interface->set_trig_level(
simple_remote_btn_trig_level[0]);
return err;
}
static int simple_remote_probe(struct platform_device *pdev)
{
int ret = 0;
int size;
void *v;
struct simple_remote_driver *jack;
dev_info(&pdev->dev, "**** Registering (headset) driver\n");
jack = kzalloc(sizeof(struct simple_remote_driver), GFP_KERNEL);
if (!jack)
return -ENOMEM;
mutex_init(&jack->simple_remote_mutex);
if (!pdev->dev.platform_data)
goto err_switch_dev_register;
size = sizeof(*jack->interface) / sizeof(void *);
v = (void *)pdev->dev.platform_data;
for (; size > 0; size--)
if (v++ == NULL)
goto err_switch_dev_register;
jack->interface = pdev->dev.platform_data;
jack->dev = &pdev->dev;
jack->plug_det_timer.function = simple_remote_plug_detect_tmr_func;
jack->plug_det_timer.data = (unsigned long)jack;
init_timer(&jack->plug_det_timer);
/* Set flags */
jack->current_accessory_state = NO_DEVICE;
jack->pressed_button = 0xFF;
/* Initialize work queue for Simple Remote Driver */
INIT_WORK(&jack->plug_det_work,
simple_remote_plug_det_work);
INIT_WORK(&jack->btn_det_work,
simple_remote_btn_det_work);
/* device name */
jack->swdev.name = "h2w";
/* print function name */
jack->swdev.print_name = simple_remote_print_name;
ret = switch_dev_register(&jack->swdev);
if (ret < 0) {
dev_err(jack->dev, "switch_dev_register failed\n");
goto err_switch_dev_register;
}
ret = create_sysfs_interfaces(&pdev->dev);
if (ret) {
dev_err(jack->dev,
"create_sysfs_interfaces for input failed\n");
goto err_switch_dev_register;
}
if (initialize_hardware(jack))
dev_err(jack->dev, "Failed to set default values in HW "
"components.");
/* Create input device for normal key events. */
jack->indev = input_allocate_device();
if (!jack->indev) {
ret = -ENOMEM;
dev_err(jack->dev, "Failed to allocate input device\n");
goto err_allocate_input_dev;
}
jack->indev->name = SIMPLE_REMOTE_NAME;
jack->indev->evbit[0] = BIT_MASK(EV_KEY);
jack->indev->keybit[BIT_WORD(KEY_MEDIA)] |= BIT_MASK(KEY_MEDIA);
jack->indev->keybit[BIT_WORD(BTN_MISC)] |= BIT_MASK(BTN_0) |
BIT_MASK(BTN_1) | BIT_MASK(BTN_2);
jack->indev->open = simple_remote_open;
jack->indev->close = simple_remote_close;
input_set_drvdata(jack->indev, jack);
platform_set_drvdata(pdev, jack);
ret = input_register_device(jack->indev);
if (ret) {
dev_err(jack->dev, "input_register_device for input device "
"failed\n");
input_free_device(jack->indev);
goto err_register_input_dev;
}
/* Create input device for application key events. */
jack->indev_appkey = input_allocate_device();
if (!jack->indev_appkey) {
ret = -ENOMEM;
dev_err(jack->dev, "Failed to allocate application key input "
"device\n");
goto err_allocate_input_appkey_dev;
}
jack->indev_appkey->name = SIMPLE_REMOTE_APPKEY_NAME;
jack->indev_appkey->evbit[0] = BIT_MASK(EV_KEY);
jack->indev_appkey->keybit[BIT_WORD(BTN_MISC)] |=
BIT_MASK(SIMPLE_REMOTE_APPKEY);
jack->indev_appkey->open = simple_remote_open;
jack->indev_appkey->close = simple_remote_close;
input_set_drvdata(jack->indev_appkey, jack);
ret = input_register_device(jack->indev_appkey);
if (ret) {
dev_err(jack->dev, "input_register_device for application key "
"input device failed\n");
goto err_register_input_appkey_dev;
}
dev_info(jack->dev, "***** Successfully registered\n");
atomic_set(&jack->initialized, 1);
return ret;
err_register_input_appkey_dev:
input_free_device(jack->indev_appkey);
err_allocate_input_appkey_dev:
input_unregister_device(jack->indev);
err_register_input_dev:
err_allocate_input_dev:
err_switch_dev_register:
dev_err(&pdev->dev, "***** Failed to initialize\n");
kzfree(jack);
return ret;
}
static int simple_remote_remove(struct platform_device *pdev)
{
struct simple_remote_driver *jack = platform_get_drvdata(pdev);
if (switch_get_state(&jack->swdev)) {
jack->interface->unregister_hssd_button_interrupt(jack);
jack->interface->enable_mic_bias(0);
switch_set_state(&jack->swdev, NO_DEVICE);
}
jack->interface->unregister_plug_detect_interrupt(jack);
remove_sysfs_interfaces(&pdev->dev);
input_unregister_device(jack->indev_appkey);
input_unregister_device(jack->indev);
switch_dev_unregister(&jack->swdev);
kzfree(jack);
return 0;
}
int simlple_remote_suspend(struct platform_device *pdev, pm_message_t state)
{
struct simple_remote_driver *jack = dev_get_drvdata(&pdev->dev);
dev_dbg(jack->dev, "%s - Suspend state = 0x%X\n", __func__,
state.event);
if (atomic_read(&jack->detection_in_progress)) {
dev_dbg(jack->dev, "%s - Plug detection in progress. "
"Not allowing suspend\n", __func__);
return -EAGAIN;
}
dev_dbg(jack->dev, "%s - No plug or button detection in progress. "
"Allowing suspend\n", __func__);
return 0;
}
static struct platform_driver simple_remote = {
.probe = simple_remote_probe,
.remove = simple_remote_remove,
.suspend = simlple_remote_suspend,
.driver = {
.name = SIMPLE_REMOTE_NAME,
.owner = THIS_MODULE,
},
};
static int __init simple_remote_init(void)
{
return platform_driver_register(&simple_remote);
}
static void __exit simple_remote_exit(void)
{
platform_driver_unregister(&simple_remote);
}
module_init(simple_remote_init);
module_exit(simple_remote_exit);
MODULE_AUTHOR("Joachim Holst");
MODULE_DESCRIPTION("3.5mm audio jack driver");
MODULE_LICENSE("GPL");
| adrientetar/semc-msm-3.4 | drivers/input/misc/simple_remote.c | C | gpl-2.0 | 27,050 |
/*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Definitions for inet_sock
*
* Authors: Many, reorganised here by
* Arnaldo Carvalho de Melo <acme@mandriva.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.
*/
#ifndef _INET_SOCK_H
#define _INET_SOCK_H
#include <linux/bitops.h>
#include <linux/kmemcheck.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/jhash.h>
#include <linux/netdevice.h>
#include <net/flow.h>
#include <net/sock.h>
#include <net/request_sock.h>
#include <net/netns/hash.h>
#include <net/tcp_states.h>
#include <net/l3mdev.h>
/** struct ip_options - IP Options
*
* @faddr - Saved first hop address
* @nexthop - Saved nexthop address in LSRR and SSRR
* @is_strictroute - Strict source route
* @srr_is_hit - Packet destination addr was our one
* @is_changed - IP checksum more not valid
* @rr_needaddr - Need to record addr of outgoing dev
* @ts_needtime - Need to record timestamp
* @ts_needaddr - Need to record addr of outgoing dev
*/
struct ip_options {
__be32 faddr;
__be32 nexthop;
unsigned char optlen;
unsigned char srr;
unsigned char rr;
unsigned char ts;
unsigned char is_strictroute:1,
srr_is_hit:1,
is_changed:1,
rr_needaddr:1,
ts_needtime:1,
ts_needaddr:1;
unsigned char router_alert;
unsigned char cipso;
unsigned char __pad2;
unsigned char __data[0];
};
struct ip_options_rcu {
struct rcu_head rcu;
struct ip_options opt;
};
struct ip_options_data {
struct ip_options_rcu opt;
char data[40];
};
struct inet_request_sock {
struct request_sock req;
#define ir_loc_addr req.__req_common.skc_rcv_saddr
#define ir_rmt_addr req.__req_common.skc_daddr
#define ir_num req.__req_common.skc_num
#define ir_rmt_port req.__req_common.skc_dport
#define ir_v6_rmt_addr req.__req_common.skc_v6_daddr
#define ir_v6_loc_addr req.__req_common.skc_v6_rcv_saddr
#define ir_iif req.__req_common.skc_bound_dev_if
#define ir_cookie req.__req_common.skc_cookie
#define ireq_net req.__req_common.skc_net
#define ireq_state req.__req_common.skc_state
#define ireq_family req.__req_common.skc_family
kmemcheck_bitfield_begin(flags);
u16 snd_wscale : 4,
rcv_wscale : 4,
tstamp_ok : 1,
sack_ok : 1,
wscale_ok : 1,
ecn_ok : 1,
acked : 1,
no_srccheck: 1;
kmemcheck_bitfield_end(flags);
u32 ir_mark;
union {
struct ip_options_rcu *opt;
#if IS_ENABLED(CONFIG_IPV6)
struct {
struct ipv6_txoptions *ipv6_opt;
struct sk_buff *pktopts;
};
#endif
};
};
static inline struct inet_request_sock *inet_rsk(const struct request_sock *sk)
{
return (struct inet_request_sock *)sk;
}
static inline u32 inet_request_mark(const struct sock *sk, struct sk_buff *skb)
{
if (!sk->sk_mark && sock_net(sk)->ipv4.sysctl_tcp_fwmark_accept)
return skb->mark;
return sk->sk_mark;
}
static inline int inet_request_bound_dev_if(const struct sock *sk,
struct sk_buff *skb)
{
#ifdef CONFIG_NET_L3_MASTER_DEV
struct net *net = sock_net(sk);
if (!sk->sk_bound_dev_if && net->ipv4.sysctl_tcp_l3mdev_accept)
return l3mdev_master_ifindex_by_index(net, skb->skb_iif);
#endif
return sk->sk_bound_dev_if;
}
struct inet_cork {
unsigned int flags;
__be32 addr;
struct ip_options *opt;
unsigned int fragsize;
int length; /* Total length of all frames */
struct dst_entry *dst;
u8 tx_flags;
__u8 ttl;
__s16 tos;
char priority;
};
struct inet_cork_full {
struct inet_cork base;
struct flowi fl;
};
struct ip_mc_socklist;
struct ipv6_pinfo;
struct rtable;
/** struct inet_sock - representation of INET sockets
*
* @sk - ancestor class
* @pinet6 - pointer to IPv6 control block
* @inet_daddr - Foreign IPv4 addr
* @inet_rcv_saddr - Bound local IPv4 addr
* @inet_dport - Destination port
* @inet_num - Local port
* @inet_saddr - Sending source
* @uc_ttl - Unicast TTL
* @inet_sport - Source port
* @inet_id - ID counter for DF pkts
* @tos - TOS
* @mc_ttl - Multicasting TTL
* @is_icsk - is this an inet_connection_sock?
* @uc_index - Unicast outgoing device index
* @mc_index - Multicast device index
* @mc_list - Group array
* @cork - info to build ip hdr on each ip frag while socket is corked
*/
struct inet_sock {
/* sk and pinet6 has to be the first two members of inet_sock */
struct sock sk;
#if IS_ENABLED(CONFIG_IPV6)
struct ipv6_pinfo *pinet6;
#endif
/* Socket demultiplex comparisons on incoming packets. */
#define inet_daddr sk.__sk_common.skc_daddr
#define inet_rcv_saddr sk.__sk_common.skc_rcv_saddr
#define inet_dport sk.__sk_common.skc_dport
#define inet_num sk.__sk_common.skc_num //Ö÷»ú×Ö½ÚÐò±íʾµÄÔ´¶Ë¿ÚºÅ
__be32 inet_saddr;
__s16 uc_ttl;
__u16 cmsg_flags;
__be16 inet_sport; //ÍøÂç×Ö×Ö½ÚÐò±íʾµÄ¶Ë¿ÚºÅ
__u16 inet_id;
struct ip_options_rcu __rcu *inet_opt;
int rx_dst_ifindex;
__u8 tos;
__u8 min_ttl;
__u8 mc_ttl;
__u8 pmtudisc;
__u8 recverr:1,
is_icsk:1,
freebind:1,
hdrincl:1,
mc_loop:1,
transparent:1,
mc_all:1,
nodefrag:1;
__u8 bind_address_no_port:1;
__u8 rcv_tos;
__u8 convert_csum;
int uc_index;
int mc_index;
__be32 mc_addr;
struct ip_mc_socklist __rcu *mc_list;
struct inet_cork_full cork;
};
#define IPCORK_OPT 1 /* ip-options has been held in ipcork.opt */
#define IPCORK_ALLFRAG 2 /* always fragment (for ipv6 for now) */
/* cmsg flags for inet */
#define IP_CMSG_PKTINFO BIT(0)
#define IP_CMSG_TTL BIT(1)
#define IP_CMSG_TOS BIT(2)
#define IP_CMSG_RECVOPTS BIT(3)
#define IP_CMSG_RETOPTS BIT(4)
#define IP_CMSG_PASSSEC BIT(5)
#define IP_CMSG_ORIGDSTADDR BIT(6)
#define IP_CMSG_CHECKSUM BIT(7)
/**
* sk_to_full_sk - Access to a full socket
* @sk: pointer to a socket
*
* SYNACK messages might be attached to request sockets.
* Some places want to reach the listener in this case.
*/
static inline struct sock *sk_to_full_sk(struct sock *sk)
{
#ifdef CONFIG_INET
if (sk && sk->sk_state == TCP_NEW_SYN_RECV)
sk = inet_reqsk(sk)->rsk_listener;
#endif
return sk;
}
/* sk_to_full_sk() variant with a const argument */
static inline const struct sock *sk_const_to_full_sk(const struct sock *sk)
{
#ifdef CONFIG_INET
if (sk && sk->sk_state == TCP_NEW_SYN_RECV)
sk = ((const struct request_sock *)sk)->rsk_listener;
#endif
return sk;
}
static inline struct sock *skb_to_full_sk(const struct sk_buff *skb)
{
return sk_to_full_sk(skb->sk);
}
static inline struct inet_sock *inet_sk(const struct sock *sk)
{
return (struct inet_sock *)sk;
}
static inline void __inet_sk_copy_descendant(struct sock *sk_to,
const struct sock *sk_from,
const int ancestor_size)
{
memcpy(inet_sk(sk_to) + 1, inet_sk(sk_from) + 1,
sk_from->sk_prot->obj_size - ancestor_size);
}
#if !(IS_ENABLED(CONFIG_IPV6))
static inline void inet_sk_copy_descendant(struct sock *sk_to,
const struct sock *sk_from)
{
__inet_sk_copy_descendant(sk_to, sk_from, sizeof(struct inet_sock));
}
#endif
int inet_sk_rebuild_header(struct sock *sk);
static inline unsigned int __inet_ehashfn(const __be32 laddr,
const __u16 lport,
const __be32 faddr,
const __be16 fport,
u32 initval)
{
return jhash_3words((__force __u32) laddr,
(__force __u32) faddr,
((__u32) lport) << 16 | (__force __u32)fport,
initval);
}
struct request_sock *inet_reqsk_alloc(const struct request_sock_ops *ops,
struct sock *sk_listener,
bool attach_listener);
static inline __u8 inet_sk_flowi_flags(const struct sock *sk)
{
__u8 flags = 0;
if (inet_sk(sk)->transparent || inet_sk(sk)->hdrincl)
flags |= FLOWI_FLAG_ANYSRC;
return flags;
}
static inline void inet_inc_convert_csum(struct sock *sk)
{
inet_sk(sk)->convert_csum++;
}
static inline void inet_dec_convert_csum(struct sock *sk)
{
if (inet_sk(sk)->convert_csum > 0)
inet_sk(sk)->convert_csum--;
}
static inline bool inet_get_convert_csum(struct sock *sk)
{
return !!inet_sk(sk)->convert_csum;
}
#endif /* _INET_SOCK_H */
| zzpu/linux-stack | include/net/inet_sock.h | C | gpl-2.0 | 8,390 |
/*
* cros_ec_sensors - Driver for Chrome OS Embedded Controller sensors.
*
* Copyright (C) 2015 Google, Inc
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This driver uses the cros-ec interface to communicate with the Chrome OS
* EC about accelerometer data. Accelerometer access is presented through
* iio sysfs.
*/
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/iio/buffer.h>
#include <linux/iio/iio.h>
#include <linux/iio/kfifo_buf.h>
#include <linux/iio/trigger.h>
#include <linux/iio/triggered_buffer.h>
#include <linux/iio/trigger_consumer.h>
#include <linux/kernel.h>
#include <linux/mfd/cros_ec.h>
#include <linux/mfd/cros_ec_commands.h>
#include <linux/mfd/cros_ec_dev.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/platform_device.h>
#include "cros_ec_sensors_core.h"
#define MAX_CHANNELS (MAX_AXIS + 1)
/* State data for ec_sensors iio driver. */
struct cros_ec_sensors_state {
/* Shared by all sensors */
struct cros_ec_sensors_core_state core;
struct iio_chan_spec channels[MAX_CHANNELS];
};
static int cros_ec_sensors_read(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2, long mask)
{
struct cros_ec_sensors_state *st = iio_priv(indio_dev);
s16 data = 0;
s64 val64;
int i;
int ret = IIO_VAL_INT;
int idx = chan->scan_index;
mutex_lock(&st->core.cmd_lock);
switch (mask) {
case IIO_CHAN_INFO_RAW:
if (st->core.read_ec_sensors_data(indio_dev,
1 << idx, &data) < 0)
ret = -EIO;
*val = data;
break;
case IIO_CHAN_INFO_CALIBBIAS:
st->core.param.cmd = MOTIONSENSE_CMD_SENSOR_OFFSET;
st->core.param.sensor_offset.flags = 0;
if (cros_ec_motion_send_host_cmd(&st->core, 0)) {
ret = -EIO;
break;
}
/* Save values */
for (i = X; i < MAX_AXIS; i++)
st->core.calib[i].offset =
st->core.resp->sensor_offset.offset[i];
*val = st->core.calib[idx].offset;
break;
case IIO_CHAN_INFO_SCALE:
st->core.param.cmd = MOTIONSENSE_CMD_SENSOR_RANGE;
st->core.param.sensor_range.data =
EC_MOTION_SENSE_NO_VALUE;
if (cros_ec_motion_send_host_cmd(&st->core, 0)) {
ret = -EIO;
break;
}
val64 = st->core.resp->sensor_range.ret;
switch (st->core.type) {
case MOTIONSENSE_TYPE_ACCEL:
/*
* EC returns data in g, iio exepects m/s^2.
* Do not use IIO_G_TO_M_S_2 to avoid precision loss.
*/
*val = div_s64(val64 * 980665, 10);
*val2 = 10000 << (CROS_EC_SENSOR_BITS - 1);
ret = IIO_VAL_FRACTIONAL;
break;
case MOTIONSENSE_TYPE_GYRO:
/* EC returns date in dps, iio expects rad/s.
* Do not use IIO_DEGREE_TO_RAD to avoid precision
* loss. Round to the nearest integer.
*/
*val = div_s64(val64 * 314159 + 9000000ULL, 1000);
*val2 = 18000 << (CROS_EC_SENSOR_BITS - 1);
ret = IIO_VAL_FRACTIONAL;
break;
case MOTIONSENSE_TYPE_MAG:
/*
* EC returns date in 16LSB / uT,
* iio expects Gauss
*/
*val = val64;
*val2 = 100 << (CROS_EC_SENSOR_BITS - 1);
ret = IIO_VAL_FRACTIONAL;
break;
default:
ret = -EINVAL;
}
break;
default:
ret = cros_ec_sensors_core_read(
&st->core, chan, val, val2, mask);
break;
}
mutex_unlock(&st->core.cmd_lock);
return ret;
}
static int cros_ec_sensors_write(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val, int val2, long mask)
{
struct cros_ec_sensors_state *st = iio_priv(indio_dev);
int i;
int ret = 0;
int idx = chan->scan_index;
mutex_lock(&st->core.cmd_lock);
switch (mask) {
case IIO_CHAN_INFO_CALIBBIAS:
st->core.calib[idx].offset = val;
/* Send to EC for each axis, even if not complete */
st->core.param.cmd = MOTIONSENSE_CMD_SENSOR_OFFSET;
st->core.param.sensor_offset.flags =
MOTION_SENSE_SET_OFFSET;
for (i = X; i < MAX_AXIS; i++)
st->core.param.sensor_offset.offset[i] =
st->core.calib[i].offset;
st->core.param.sensor_offset.temp =
EC_MOTION_SENSE_INVALID_CALIB_TEMP;
if (cros_ec_motion_send_host_cmd(&st->core, 0))
ret = -EIO;
break;
case IIO_CHAN_INFO_SCALE:
if (st->core.type == MOTIONSENSE_TYPE_MAG) {
ret = -EINVAL;
break;
}
st->core.param.cmd = MOTIONSENSE_CMD_SENSOR_RANGE;
st->core.param.sensor_range.data = val;
/* Always roundup, so caller gets at least what it asks for. */
st->core.param.sensor_range.roundup = 1;
if (cros_ec_motion_send_host_cmd(&st->core, 0))
ret = -EIO;
break;
default:
ret = cros_ec_sensors_core_write(
&st->core, chan, val, val2, mask);
break;
}
mutex_unlock(&st->core.cmd_lock);
return ret;
}
static const struct iio_info ec_sensors_info = {
.read_raw = &cros_ec_sensors_read,
.write_raw = &cros_ec_sensors_write,
.driver_module = THIS_MODULE,
};
static int cros_ec_sensors_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct cros_ec_dev *ec_dev = dev_get_drvdata(dev->parent);
struct cros_ec_device *ec_device;
struct iio_dev *indio_dev;
struct cros_ec_sensors_state *state;
struct iio_chan_spec *channel;
int ret, i;
if (!ec_dev || !ec_dev->ec_dev) {
dev_warn(&pdev->dev, "No CROS EC device found.\n");
return -EINVAL;
}
ec_device = ec_dev->ec_dev;
indio_dev = devm_iio_device_alloc(&pdev->dev, sizeof(*state));
if (!indio_dev)
return -ENOMEM;
ret = cros_ec_sensors_core_init(pdev, indio_dev, true);
if (ret)
return ret;
indio_dev->info = &ec_sensors_info;
state = iio_priv(indio_dev);
for (channel = state->channels, i = X; i < MAX_AXIS; i++, channel++) {
/* common part */
channel->info_mask_separate =
BIT(IIO_CHAN_INFO_RAW) |
BIT(IIO_CHAN_INFO_CALIBBIAS);
channel->info_mask_shared_by_all =
BIT(IIO_CHAN_INFO_SCALE) |
BIT(IIO_CHAN_INFO_FREQUENCY) |
BIT(IIO_CHAN_INFO_SAMP_FREQ);
channel->scan_type.realbits = CROS_EC_SENSOR_BITS;
channel->scan_type.storagebits = CROS_EC_SENSOR_BITS;
channel->scan_type.shift = 0;
channel->scan_index = i;
channel->ext_info = cros_ec_sensors_ext_info;
channel->modified = 1;
channel->channel2 = IIO_MOD_X + i;
channel->scan_type.sign = 's';
state->core.calib[i].offset = 0;
/* sensor specific */
switch (state->core.type) {
case MOTIONSENSE_TYPE_ACCEL:
channel->type = IIO_ACCEL;
break;
case MOTIONSENSE_TYPE_GYRO:
channel->type = IIO_ANGL_VEL;
break;
case MOTIONSENSE_TYPE_MAG:
channel->type = IIO_MAGN;
break;
default:
dev_warn(&pdev->dev, "unknown\n");
}
}
/* Timestamp */
channel->type = IIO_TIMESTAMP;
channel->channel = -1;
channel->scan_index = MAX_AXIS;
channel->scan_type.sign = 's';
channel->scan_type.realbits = 64;
channel->scan_type.storagebits = 64;
indio_dev->channels = state->channels;
indio_dev->num_channels = MAX_CHANNELS;
/* There is only enough room for accel and gyro in the io space */
if ((state->core.ec->cmd_read_u8 != NULL) &&
(state->core.type != MOTIONSENSE_TYPE_MAG))
state->core.read_ec_sensors_data = cros_ec_sensors_read_lpc;
else
state->core.read_ec_sensors_data = cros_ec_sensors_read_cmd;
ret = iio_triggered_buffer_setup(indio_dev, NULL,
cros_ec_sensors_capture, NULL);
if (ret)
return ret;
ret = iio_device_register(indio_dev);
return ret;
}
static int cros_ec_sensors_remove(struct platform_device *pdev)
{
struct iio_dev *indio_dev = platform_get_drvdata(pdev);
iio_device_unregister(indio_dev);
iio_triggered_buffer_cleanup(indio_dev);
return 0;
}
static const struct platform_device_id cros_ec_sensors_ids[] = {
{
.name = "cros-ec-accel",
},
{
.name = "cros-ec-gyro",
},
{
.name = "cros-ec-mag",
},
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(platform, cros_ec_sensors_ids);
static struct platform_driver cros_ec_sensors_platform_driver = {
.driver = {
.name = "cros-ec-sensors",
.pm = &cros_ec_sensors_pm_ops,
},
.probe = cros_ec_sensors_probe,
.remove = cros_ec_sensors_remove,
.id_table = cros_ec_sensors_ids,
};
module_platform_driver(cros_ec_sensors_platform_driver);
MODULE_DESCRIPTION("ChromeOS EC 3-axis sensors driver");
MODULE_LICENSE("GPL v2");
| kendling/android_kernel_google_dragon | drivers/iio/common/cros_ec_sensors/cros_ec_sensors.c | C | gpl-2.0 | 8,444 |
<?php
namespace IXP\Http\Controllers;
/*
* Copyright (C) 2009 - 2021 Internet Neutral Exchange Association Company Limited By Guarantee.
* All Rights Reserved.
*
* This file is part of IXP Manager.
*
* IXP Manager 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 v2.0 of the License.
*
* IXP Manager 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 v2.0
* along with IXP Manager. If not, see:
*
* http://www.gnu.org/licenses/gpl-2.0.html
*/
use Former, Redirect;
use Illuminate\Http\{
RedirectResponse
};
use Illuminate\Support\Facades\View as FacadeView;
use Illuminate\View\View;
use IXP\Http\Requests\StoreRouter;
use IXP\Models\{
Router,
Vlan
};
use IXP\Utils\View\Alert\{
Alert,
Container as AlertContainer
};
/**
* Router Controller
*
* @author Barry O'Donovan <barry@islandbridgenetworks.ie>
* @author Yann Robin <yann@islandbridgenetworks.ie>
* @category IXP
* @package IXP\Http\Controllers
* @copyright Copyright (C) 2009 - 2021 Internet Neutral Exchange Association Company Limited By Guarantee
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU GPL V2.0
*/
class RouterController extends Controller
{
/**
* Display all the routers
*
* @return View
*/
public function list(): View
{
return view( 'router/index' )->with([
'routers' => Router::with( 'vlan' )->get()
]);
}
/**
* Status page for routers
*
* @return View
*/
public function status(): View
{
$routers = $routersWithApi = [];
$lgEnabled = !config('ixp_fe.frontend.disabled.lg' );
if( $lgEnabled ) {
$routers = Router::all();
// Get routers with API
$routersWithApi = Router::whereNotNull( 'api' )
->where( 'api_type', '!=', 0 )->get()
->pluck( 'handle' )->toArray();
}
return view( 'router/status' )->with([
'routers' => $routers,
'routersWithApi' => $routersWithApi,
'lgEnabled' => $lgEnabled,
]);
}
/**
* Display the form to create a router
*
* @return View
*/
public function create(): View
{
return view( 'router/edit' )->with([
'rt' => false,
'vlans' => Vlan::publicOnly()->orderBy( 'number' )->get()
]);
}
/**
* Create a router
*
* @param StoreRouter $r instance of the current HTTP request
*
* @return RedirectResponse
*
* @throws
*/
public function store( StoreRouter $r ): RedirectResponse
{
if( !FacadeView::exists( $r->template ) ) {
AlertContainer::push( 'The template you entered cannot be found. Please check the help message for more information.', Alert::DANGER );
return Redirect::to( route( 'router@create' ) )->withInput( $r->all() );
}
Router::create( $r->all() );
AlertContainer::push( 'Router created.', Alert::SUCCESS );
return Redirect::to( route( "router@list" ) );
}
/**
* Display the form to edit a router
*
* @param Router $router router that need to be edited
*
* @return View
*/
public function edit( Router $router ): View
{
Former::populate([
'handle' => request()->old( 'handle', $router->handle ),
'vlan_id' => request()->old( 'vlan_id', $router->vlan_id ),
'protocol' => request()->old( 'protocol', $router->protocol ),
'type' => request()->old( 'type', $router->type ),
'name' => request()->old( 'name', $router->name ),
'shortname' => request()->old( 'shortname', $router->shortname ),
'router_id' => request()->old( 'router_id', $router->router_id ),
'peering_ip' => request()->old( 'peering_ip', $router->peering_ip ),
'asn' => request()->old( 'asn', $router->asn ),
'software' => request()->old( 'software', $router->software ),
'software_version' => request()->old( 'software_version', $router->software_version ),
'operating_system' => request()->old( 'operating_system', $router->operating_system ),
'operating_system_version' => request()->old( 'operating_system_version', $router->operating_system_version ),
'mgmt_host' => request()->old( 'mgmt_host', $router->mgmt_host ),
'api_type' => request()->old( 'api_type', $router->api_type ),
'api' => request()->old( 'api', $router->api ),
'lg_access' => request()->old( 'lg_access', $router->lg_access ),
'quarantine' => request()->old( 'quarantine', $router->quarantine ),
'bgp_lc' => request()->old( 'bgp_lc', $router->bgp_lc ),
'rpki' => request()->old( 'rpki', $router->rpki ),
'rfc1997_passthru' => request()->old( 'rfc1997_passthru', $router->rfc1997_passthru ),
'skip_md5' => request()->old( 'skip_md5', $router->skip_md5 ),
'template' => request()->old( 'template', $router->template ),
]);
return view( 'router/edit' )->with([
'rt' => $router,
'vlans' => Vlan::publicOnly()->orderBy( 'number' )->get(),
]);
}
/**
* Update a router (set all the data needed)
*
* @param StoreRouter $r instance of the current HTTP request
* @param Router $router
*
* @return RedirectResponse
*
* @throws
*/
public function update( StoreRouter $r, Router $router ): RedirectResponse
{
$router->update( $r->all() );
AlertContainer::push( 'Router updated.', Alert::SUCCESS );
return Redirect::to( route( "router@list" ) );
}
/**
* Display the details of a router
*
* @param Router $router router that need to be displayed
*
* @return View
*/
public function view( Router $router ): View
{
return view( 'router/view' )->with([
'rt' => $router->load( 'vlan' )
]);
}
/**
* Delete a router
*
* @param Router $router
*
* @return redirectresponse
*
* @throws
*/
public function delete( Router $router): RedirectResponse
{
$router->delete();
AlertContainer::push( 'Router deleted.', Alert::SUCCESS );
return Redirect::to( route( "router@list" ) );
}
} | inex/IXP-Manager | app/Http/Controllers/RouterController.php | PHP | gpl-2.0 | 7,677 |
# -*- coding: UTF-8 -*-
"""
Copyright (C) 2014 smokdpi
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import re
from t0mm0.common.net import Net
from lib import jsunpack
from urlresolver import common
from urlresolver.plugnplay.interfaces import UrlResolver
from urlresolver.plugnplay.interfaces import PluginSettings
from urlresolver.plugnplay import Plugin
class UsersCloudResolver(Plugin, UrlResolver, PluginSettings):
implements = [UrlResolver, PluginSettings]
name = "userscloud"
domains = ["userscloud.com"]
pattern = '(?://|\.)(userscloud\.com)/(?:embed-)?([0-9a-zA-Z/]+)'
def __init__(self):
p = self.get_setting('priority') or 100
self.priority = int(p)
self.net = Net()
self.user_agent = common.IE_USER_AGENT
self.net.set_user_agent(self.user_agent)
self.headers = {'User-Agent': self.user_agent}
def get_media_url(self, host, media_id):
web_url = self.get_url(host, media_id)
stream_url = None
self.headers['Referer'] = web_url
html = self.net.http_GET(web_url, headers=self.headers).content
r = re.search('>(eval\(function\(p,a,c,k,e,d\).+?)</script>', html, re.DOTALL)
if r:
js_data = jsunpack.unpack(r.group(1))
stream_url = re.findall('<param\s+name="src"\s*value="([^"]+)', js_data)
stream_url += re.findall('file\s*:\s*[\'|\"](.+?)[\'|\"]', js_data)
stream_url = [i for i in stream_url if not i.endswith('.srt')]
if stream_url:
return stream_url[0]
raise UrlResolver.ResolverError('File not found')
def get_url(self, host, media_id):
return 'https://%s/%s' % (host, media_id)
def get_host_and_id(self, url):
r = re.search(self.pattern, url)
if r:
return r.groups()
else:
return False
def valid_url(self, url, host):
return re.search(self.pattern, url) or self.name in host
| igor-rangel7l/igorrangelteste.repository | script.module.urlresolver/lib/urlresolver/plugins/userscloud.py | Python | gpl-2.0 | 2,595 |
# -*- coding: utf-8 -*-
'''
test_qgsatlascomposition.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
'''
import qgis # NOQA
import os
import glob
import shutil
import tempfile
from qgis.testing import start_app, unittest
from utilities import unitTestDataPath
from qgis.PyQt.QtCore import QFileInfo, QRectF, qWarning
from qgis.core import (
QgsCategorizedSymbolRenderer,
QgsComposerLabel,
QgsComposerLegend,
QgsComposerMap,
QgsComposition,
QgsCoordinateReferenceSystem,
QgsFeature,
QgsFillSymbol,
QgsFontUtils,
QgsGeometry,
QgsMarkerSymbol,
QgsPointXY,
QgsProject,
QgsRectangle,
QgsRendererCategory,
QgsSingleSymbolRenderer,
QgsVectorLayer,
)
from qgscompositionchecker import QgsCompositionChecker
start_app()
class TestQgsAtlasComposition(unittest.TestCase):
def testCase(self):
self.TEST_DATA_DIR = unitTestDataPath()
tmppath = tempfile.mkdtemp()
for file in glob.glob(os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr")
QgsProject.instance().addMapLayers([mVectorLayer])
self.layers = [mVectorLayer]
# create composition with composer map
# select epsg:2154
crs = QgsCoordinateReferenceSystem()
crs.createFromSrid(2154)
QgsProject.instance().setCrs(crs)
self.mComposition = QgsComposition(QgsProject.instance())
self.mComposition.setPaperSize(297, 210)
# fix the renderer, fill with green
props = {"color": "0,127,0"}
fillSymbol = QgsFillSymbol.createSimple(props)
renderer = QgsSingleSymbolRenderer(fillSymbol)
mVectorLayer.setRenderer(renderer)
# the atlas map
self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
self.mAtlasMap.setFrameEnabled(True)
self.mAtlasMap.setLayers([mVectorLayer])
self.mComposition.addComposerMap(self.mAtlasMap)
# the atlas
self.mAtlas = self.mComposition.atlasComposition()
self.mAtlas.setCoverageLayer(mVectorLayer)
self.mAtlas.setEnabled(True)
self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)
# an overview
self.mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
self.mOverview.setFrameEnabled(True)
self.mOverview.overview().setFrameMap(self.mAtlasMap.id())
self.mOverview.setLayers([mVectorLayer])
self.mComposition.addComposerMap(self.mOverview)
nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
self.mOverview.setNewExtent(nextent)
# set the fill symbol of the overview map
props2 = {"color": "127,0,0,127"}
fillSymbol2 = QgsFillSymbol.createSimple(props2)
self.mOverview.overview().setFrameSymbol(fillSymbol2)
# header label
self.mLabel1 = QgsComposerLabel(self.mComposition)
self.mComposition.addComposerLabel(self.mLabel1)
self.mLabel1.setText("[% \"NAME_1\" %] area")
self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
self.mLabel1.adjustSizeToText()
self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))
qWarning(
"header label font: %s exactMatch:%s" % (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))
# feature number label
self.mLabel2 = QgsComposerLabel(self.mComposition)
self.mComposition.addComposerLabel(self.mLabel2)
self.mLabel2.setText("# [%@atlas_featurenumber || ' / ' || @atlas_totalfeatures%]")
self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
self.mLabel2.adjustSizeToText()
self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))
qWarning("feature number label font: %s exactMatch:%s" % (
self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))
self.filename_test()
self.autoscale_render_test()
self.fixedscale_render_test()
self.predefinedscales_render_test()
self.hidden_render_test()
self.legend_test()
self.rotation_test()
shutil.rmtree(tmppath, True)
def filename_test(self):
self.mAtlas.setFilenamePattern("'output_' || @atlas_featurenumber")
self.mAtlas.beginRender()
for i in range(0, self.mAtlas.numFeatures()):
self.mAtlas.prepareForFeature(i)
expected = "output_%d" % (i + 1)
self.assertEqual(self.mAtlas.currentFilename(), expected)
self.mAtlas.endRender()
def autoscale_render_test(self):
self.mAtlasMap.setAtlasDriven(True)
self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
self.mAtlasMap.setAtlasMargin(0.10)
self.mAtlas.beginRender()
for i in range(0, 2):
self.mAtlas.prepareForFeature(i)
self.mLabel1.adjustSizeToText()
checker = QgsCompositionChecker('atlas_autoscale%d' % (i + 1), self.mComposition)
checker.setControlPathPrefix("atlas")
myTestResult, myMessage = checker.testComposition(0, 200)
assert myTestResult
self.mAtlas.endRender()
self.mAtlasMap.setAtlasDriven(False)
self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
self.mAtlasMap.setAtlasMargin(0)
def fixedscale_render_test(self):
self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
self.mAtlasMap.setAtlasDriven(True)
self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
self.mAtlas.beginRender()
for i in range(0, 2):
self.mAtlas.prepareForFeature(i)
self.mLabel1.adjustSizeToText()
checker = QgsCompositionChecker('atlas_fixedscale%d' % (i + 1), self.mComposition)
checker.setControlPathPrefix("atlas")
myTestResult, myMessage = checker.testComposition(0, 200)
assert myTestResult
self.mAtlas.endRender()
def predefinedscales_render_test(self):
self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
self.mAtlasMap.setAtlasDriven(True)
self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Predefined)
scales = [1800000, 5000000]
self.mAtlas.setPredefinedScales(scales)
for i, s in enumerate(self.mAtlas.predefinedScales()):
assert s == scales[i]
self.mAtlas.beginRender()
for i in range(0, 2):
self.mAtlas.prepareForFeature(i)
self.mLabel1.adjustSizeToText()
checker = QgsCompositionChecker('atlas_predefinedscales%d' % (i + 1), self.mComposition)
checker.setControlPathPrefix("atlas")
myTestResult, myMessage = checker.testComposition(0, 200)
assert myTestResult
self.mAtlas.endRender()
def hidden_render_test(self):
self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
self.mAtlas.setHideCoverage(True)
self.mAtlas.beginRender()
for i in range(0, 2):
self.mAtlas.prepareForFeature(i)
self.mLabel1.adjustSizeToText()
checker = QgsCompositionChecker('atlas_hiding%d' % (i + 1), self.mComposition)
checker.setControlPathPrefix("atlas")
myTestResult, myMessage = checker.testComposition(0, 200)
assert myTestResult
self.mAtlas.endRender()
self.mAtlas.setHideCoverage(False)
def sorting_render_test(self):
self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
self.mAtlas.setHideCoverage(False)
self.mAtlas.setSortFeatures(True)
self.mAtlas.setSortKeyAttributeIndex(4) # departement name
self.mAtlas.setSortAscending(False)
self.mAtlas.beginRender()
for i in range(0, 2):
self.mAtlas.prepareForFeature(i)
self.mLabel1.adjustSizeToText()
checker = QgsCompositionChecker('atlas_sorting%d' % (i + 1), self.mComposition)
checker.setControlPathPrefix("atlas")
myTestResult, myMessage = checker.testComposition(0, 200)
assert myTestResult
self.mAtlas.endRender()
def filtering_render_test(self):
self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
self.mAtlas.setHideCoverage(False)
self.mAtlas.setSortFeatures(False)
self.mAtlas.setFilterFeatures(True)
self.mAtlas.setFeatureFilter("substr(NAME_1,1,1)='P'") # select only 'Pays de la loire'
self.mAtlas.beginRender()
for i in range(0, 1):
self.mAtlas.prepareForFeature(i)
self.mLabel1.adjustSizeToText()
checker = QgsCompositionChecker('atlas_filtering%d' % (i + 1), self.mComposition)
checker.setControlPathPrefix("atlas")
myTestResult, myMessage = checker.testComposition(0, 200)
assert myTestResult
self.mAtlas.endRender()
def legend_test(self):
self.mAtlasMap.setAtlasDriven(True)
self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
self.mAtlasMap.setAtlasMargin(0.10)
# add a point layer
ptLayer = QgsVectorLayer("Point?crs=epsg:4326&field=attr:int(1)&field=label:string(20)", "points", "memory")
pr = ptLayer.dataProvider()
f1 = QgsFeature(1)
f1.initAttributes(2)
f1.setAttribute(0, 1)
f1.setAttribute(1, "Test label 1")
f1.setGeometry(QgsGeometry.fromPoint(QgsPointXY(-0.638, 48.954)))
f2 = QgsFeature(2)
f2.initAttributes(2)
f2.setAttribute(0, 2)
f2.setAttribute(1, "Test label 2")
f2.setGeometry(QgsGeometry.fromPoint(QgsPointXY(-1.682, 48.550)))
pr.addFeatures([f1, f2])
# categorized symbology
r = QgsCategorizedSymbolRenderer("attr", [QgsRendererCategory(1, QgsMarkerSymbol.createSimple({"color": "255,0,0"}), "red"),
QgsRendererCategory(2, QgsMarkerSymbol.createSimple({"color": "0,0,255"}), "blue")])
ptLayer.setRenderer(r)
QgsProject.instance().addMapLayer(ptLayer)
# add the point layer to the map settings
layers = self.layers
layers = [ptLayer] + layers
self.mAtlasMap.setLayers(layers)
self.mOverview.setLayers(layers)
# add a legend
legend = QgsComposerLegend(self.mComposition)
legend.moveBy(200, 100)
# sets the legend filter parameter
legend.setComposerMap(self.mAtlasMap)
legend.setLegendFilterOutAtlas(True)
self.mComposition.addComposerLegend(legend)
self.mAtlas.beginRender()
self.mAtlas.prepareForFeature(0)
self.mLabel1.adjustSizeToText()
checker = QgsCompositionChecker('atlas_legend', self.mComposition)
myTestResult, myMessage = checker.testComposition()
assert myTestResult
self.mAtlas.endRender()
# restore state
self.mAtlasMap.setLayers([layers[1]])
self.mComposition.removeComposerItem(legend)
QgsProject.instance().removeMapLayer(ptLayer.id())
def rotation_test(self):
# We will create a polygon layer with a rotated rectangle.
# Then we will make it the object layer for the atlas,
# rotate the map and test that the bounding rectangle
# is smaller than the bounds without rotation.
polygonLayer = QgsVectorLayer('Polygon', 'test_polygon', 'memory')
poly = QgsFeature(polygonLayer.pendingFields())
points = [(10, 15), (15, 10), (45, 40), (40, 45)]
poly.setGeometry(QgsGeometry.fromPolygon([[QgsPointXY(x[0], x[1]) for x in points]]))
polygonLayer.dataProvider().addFeatures([poly])
QgsProject.instance().addMapLayer(polygonLayer)
# Recreating the composer locally
composition = QgsComposition(QgsProject.instance())
composition.setPaperSize(297, 210)
# the atlas map
atlasMap = QgsComposerMap(composition, 20, 20, 130, 130)
atlasMap.setFrameEnabled(True)
atlasMap.setLayers([polygonLayer])
atlasMap.setNewExtent(QgsRectangle(0, 0, 100, 50))
composition.addComposerMap(atlasMap)
# the atlas
atlas = composition.atlasComposition()
atlas.setCoverageLayer(polygonLayer)
atlas.setEnabled(True)
composition.setAtlasMode(QgsComposition.ExportAtlas)
atlasMap.setAtlasDriven(True)
atlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
atlasMap.setAtlasMargin(0.0)
# Testing
atlasMap.setMapRotation(0.0)
atlas.firstFeature()
nonRotatedExtent = QgsRectangle(atlasMap.currentMapExtent())
atlasMap.setMapRotation(45.0)
atlas.firstFeature()
rotatedExtent = QgsRectangle(atlasMap.currentMapExtent())
assert rotatedExtent.width() < nonRotatedExtent.width() * 0.9
assert rotatedExtent.height() < nonRotatedExtent.height() * 0.9
QgsProject.instance().removeMapLayer(polygonLayer)
if __name__ == '__main__':
unittest.main()
| GeoCat/QGIS | tests/src/python/test_qgsatlascomposition.py | Python | gpl-2.0 | 14,506 |
/***************************************************************************
file : CarControl.h
copyright : (C) 2007 Daniele Loiacono
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef CARCONTROL_H_
#define CARCONTROL_H_
#include <string>
class CarControl {
public:
CarControl(std::string sensors);
CarControl(float accel, float brake, int gear, float steer, float clutch, int focus = 0, int meta = 0);
std::string toString();
float getAccel();
void setAccel (float accel);
float getBrake();
void setBrake (float brake);
int getGear();
void setGear(int gear);
float getSteer();
void setSteer(float steer);
int getMeta();
void setMeta(int gear);
float getClutch();
void setClutch(float clutch);
int getFocus();
void setFocus(int focus);
const static int META_RESTART = 1;
private:
float accel;
float brake;
int gear;
float steer;
float clutch;
int meta;
int focus;
};
#endif
| xythobuz/ki_light_torcs | src/CarControl.h | C | gpl-2.0 | 1,671 |
package tp.pr2.mv;
/**
* Clase que representa la pila de operandos.
* @author Adrian Garcia y Omar Gaytan
*
*/
public class OperandStack {
private int maxSize = 100;
private Integer[] stack;
private int top = -1;
private int numElements = 0;
/**
* Constructor sin parametros
*/
public OperandStack(){
this.stack = new Integer[maxSize];
}
/**
* Devuelve el número de elementos en la pila
* @return numElements
*/
public int getNumElem(){
return this.numElements;
}
/**
* Comprueba si la pila esta vacía
* @return aux
*/
public boolean isEmpty(){
boolean aux = true;
if(top >= 0) aux = false;
return aux;
}
/**
* Inserta un valor en la cima de la pila.
* @param value
* @return aux
*/
public boolean push(int value){
boolean aux = false;
if(top < maxSize -1){
stack[++top] = value;
aux = true;
this.numElements++;
}
return aux;
}
/**
* Disminuye la cima de la pila.
*/
public int pop() {
Integer n = this.stack[top];
top--;
this.numElements--;
return n;
}
/**
* Devuelve la cima de la pila.
* @return i
*/
public int top(){
int i = 0;
if(!this.isEmpty()){
i = stack[top] ;
}
return i;
}
/**
* Devuelve el contenido de la pila en forma de string.
*/
public String toString(){
String s = "";
if(!this.isEmpty()){
for(int i =0;i<=top;i++){
s = s + " " + stack[i];
}
}else{
s = s + " <vacia>";
}
return s;
}
/**
* Duplica el tamaño de la pila(llamada por cpu cuando se supera el tamaño).
*/
public void reSize() {
int[] aux = new int[maxSize];
for(int i=0;i<maxSize;i++){
aux[i] = stack[i];
}
maxSize = maxSize*2;
stack = new Integer[maxSize];
for(int i=0;i<maxSize/2;i++){
stack[i] = aux[i];
}
}
} | mizadri/java_tp | 2pr/src/tp/pr2/mv/OperandStack.java | Java | gpl-2.0 | 2,424 |
// MELFAS HEX Studio v0.6 [2009.10.12]
const uint16_t MELFAS_binary_nLength = 0x2CF4; // 11.2 KBytes ( 11508 )
const uint8_t MELFAS_binary[] = {
// Model name : M340K
// Module revision : R15
// Firmware version : V09
0x02, 0x22, 0xD6, 0x02, 0x00, 0x1E, 0xD2, 0xD8, 0xC2, 0xDB, 0xC2, 0xDA, 0x53, 0x8E, 0xE0, 0x43,
0x8E, 0xE0, 0x22, 0x02, 0x00, 0x60, 0x43, 0xE8, 0x20, 0x22, 0xFF, 0x02, 0x28, 0x32, 0xC0, 0xE0,
0xC0, 0xF0, 0xC0, 0x83, 0xC0, 0x82, 0xC0, 0xD0, 0x75, 0xD0, 0x00, 0xC0, 0x00, 0xC0, 0x01, 0xC0,
0x02, 0xC0, 0x03, 0xC0, 0x04, 0xC0, 0x05, 0xC0, 0x06, 0xC0, 0x07, 0xC2, 0xA8, 0x12, 0x00, 0x86,
0x7F, 0x01, 0x12, 0x2C, 0xD4, 0xD0, 0x07, 0xD0, 0x06, 0xD0, 0x05, 0xD0, 0x04, 0xD0, 0x03, 0xD0,
0x02, 0xD0, 0x01, 0xD0, 0x00, 0xD0, 0xD0, 0xD0, 0x82, 0xD0, 0x83, 0xD0, 0xF0, 0xD0, 0xE0, 0x32,
0xC2, 0xAA, 0x32, 0x02, 0x2C, 0x51, 0x53, 0xE8, 0xDF, 0x22, 0xFF, 0x02, 0x18, 0x5F, 0x90, 0x01,
0x89, 0xE0, 0x6F, 0x60, 0x0A, 0xEF, 0xF0, 0x25, 0xE0, 0x24, 0x02, 0xFF, 0x12, 0x2C, 0x8A, 0x22,
0x4D, 0x33, 0x34, 0x30, 0x4B, 0x00, 0x12, 0x28, 0xE4, 0x12, 0x00, 0x06, 0xD2, 0xD9, 0x12, 0x2C,
0xEC, 0xD2, 0xAF, 0x02, 0x2A, 0x91, 0x52, 0x31, 0x35, 0x00, 0xFF, 0x56, 0x30, 0x39, 0x00, 0xE7,
0x09, 0xF6, 0x08, 0xDF, 0xFA, 0x80, 0x46, 0xE7, 0x09, 0xF2, 0x08, 0xDF, 0xFA, 0x80, 0x3E, 0x88,
0x82, 0x8C, 0x83, 0xE7, 0x09, 0xF0, 0xA3, 0xDF, 0xFA, 0x80, 0x32, 0xE3, 0x09, 0xF6, 0x08, 0xDF,
0xFA, 0x80, 0x78, 0xE3, 0x09, 0xF2, 0x08, 0xDF, 0xFA, 0x80, 0x70, 0x88, 0x82, 0x8C, 0x83, 0xE3,
0x09, 0xF0, 0xA3, 0xDF, 0xFA, 0x80, 0x64, 0x89, 0x82, 0x8A, 0x83, 0xE0, 0xA3, 0xF6, 0x08, 0xDF,
0xFA, 0x80, 0x58, 0x89, 0x82, 0x8A, 0x83, 0xE0, 0xA3, 0xF2, 0x08, 0xDF, 0xFA, 0x80, 0x4C, 0x80,
0xD2, 0x80, 0xFA, 0x80, 0xC6, 0x80, 0xD4, 0x80, 0x69, 0x80, 0xF2, 0x80, 0x33, 0x80, 0x10, 0x80,
0xA6, 0x80, 0xEA, 0x80, 0x9A, 0x80, 0xA8, 0x80, 0xDA, 0x80, 0xE2, 0x80, 0xCA, 0x80, 0x33, 0x89,
0x82, 0x8A, 0x83, 0xEC, 0xFA, 0xE4, 0x93, 0xA3, 0xC8, 0xC5, 0x82, 0xC8, 0xCC, 0xC5, 0x83, 0xCC,
0xF0, 0xA3, 0xC8, 0xC5, 0x82, 0xC8, 0xCC, 0xC5, 0x83, 0xCC, 0xDF, 0xE9, 0xDE, 0xE7, 0x80, 0x0D,
0x89, 0x82, 0x8A, 0x83, 0xE4, 0x93, 0xA3, 0xF6, 0x08, 0xDF, 0xF9, 0xEC, 0xFA, 0xA9, 0xF0, 0xED,
0xFB, 0x22, 0x89, 0x82, 0x8A, 0x83, 0xEC, 0xFA, 0xE0, 0xA3, 0xC8, 0xC5, 0x82, 0xC8, 0xCC, 0xC5,
0x83, 0xCC, 0xF0, 0xA3, 0xC8, 0xC5, 0x82, 0xC8, 0xCC, 0xC5, 0x83, 0xCC, 0xDF, 0xEA, 0xDE, 0xE8,
0x80, 0xDB, 0x89, 0x82, 0x8A, 0x83, 0xE4, 0x93, 0xA3, 0xF2, 0x08, 0xDF, 0xF9, 0x80, 0xCC, 0x88,
0xF0, 0xEF, 0x60, 0x01, 0x0E, 0x4E, 0x60, 0xC3, 0x88, 0xF0, 0xED, 0x24, 0x02, 0xB4, 0x04, 0x00,
0x50, 0xB9, 0xF5, 0x82, 0xEB, 0x24, 0x02, 0xB4, 0x04, 0x00, 0x50, 0xAF, 0x23, 0x23, 0x45, 0x82,
0x23, 0x90, 0x00, 0xEF, 0x73, 0xC2, 0xD5, 0x30, 0xF7, 0x07, 0xB2, 0xD5, 0x63, 0xF0, 0xFF, 0x05,
0xF0, 0x30, 0xE7, 0x0C, 0xB2, 0xD5, 0xF4, 0x04, 0x84, 0x63, 0xF0, 0xFF, 0x05, 0xF0, 0x80, 0x01,
0x84, 0x30, 0xD5, 0x02, 0xF4, 0x04, 0x22, 0xBB, 0x01, 0x06, 0x89, 0x82, 0x8A, 0x83, 0xE0, 0x22,
0x50, 0x02, 0xE7, 0x22, 0xBB, 0xFE, 0x02, 0xE3, 0x22, 0x89, 0x82, 0x8A, 0x83, 0xE4, 0x93, 0x22,
0xBB, 0x01, 0x0C, 0xE5, 0x82, 0x29, 0xF5, 0x82, 0xE5, 0x83, 0x3A, 0xF5, 0x83, 0xE0, 0x22, 0x50,
0x06, 0xE9, 0x25, 0x82, 0xF8, 0xE6, 0x22, 0xBB, 0xFE, 0x06, 0xE9, 0x25, 0x82, 0xF8, 0xE2, 0x22,
0xE5, 0x82, 0x29, 0xF5, 0x82, 0xE5, 0x83, 0x3A, 0xF5, 0x83, 0xE4, 0x93, 0x22, 0xBB, 0x01, 0x06,
0x89, 0x82, 0x8A, 0x83, 0xF0, 0x22, 0x50, 0x02, 0xF7, 0x22, 0xBB, 0xFE, 0x01, 0xF3, 0x22, 0xF8,
0xBB, 0x01, 0x0D, 0xE5, 0x82, 0x29, 0xF5, 0x82, 0xE5, 0x83, 0x3A, 0xF5, 0x83, 0xE8, 0xF0, 0x22,
0x50, 0x06, 0xE9, 0x25, 0x82, 0xC8, 0xF6, 0x22, 0xBB, 0xFE, 0x05, 0xE9, 0x25, 0x82, 0xC8, 0xF2,
0x22, 0xEF, 0x8D, 0xF0, 0xA4, 0xA8, 0xF0, 0xCF, 0x8C, 0xF0, 0xA4, 0x28, 0xCE, 0x8D, 0xF0, 0xA4,
0x2E, 0xFE, 0x22, 0xBC, 0x00, 0x0B, 0xBE, 0x00, 0x29, 0xEF, 0x8D, 0xF0, 0x84, 0xFF, 0xAD, 0xF0,
0x22, 0xE4, 0xCC, 0xF8, 0x75, 0xF0, 0x08, 0xEF, 0x2F, 0xFF, 0xEE, 0x33, 0xFE, 0xEC, 0x33, 0xFC,
0xEE, 0x9D, 0xEC, 0x98, 0x40, 0x05, 0xFC, 0xEE, 0x9D, 0xFE, 0x0F, 0xD5, 0xF0, 0xE9, 0xE4, 0xCE,
0xFD, 0x22, 0xED, 0xF8, 0xF5, 0xF0, 0xEE, 0x84, 0x20, 0xD2, 0x1C, 0xFE, 0xAD, 0xF0, 0x75, 0xF0,
0x08, 0xEF, 0x2F, 0xFF, 0xED, 0x33, 0xFD, 0x40, 0x07, 0x98, 0x50, 0x06, 0xD5, 0xF0, 0xF2, 0x22,
0xC3, 0x98, 0xFD, 0x0F, 0xD5, 0xF0, 0xEA, 0x22, 0xC2, 0xD5, 0xEC, 0x30, 0xE7, 0x09, 0xB2, 0xD5,
0xE4, 0xC3, 0x9D, 0xFD, 0xE4, 0x9C, 0xFC, 0xEE, 0x30, 0xE7, 0x15, 0xB2, 0xD5, 0xE4, 0xC3, 0x9F,
0xFF, 0xE4, 0x9E, 0xFE, 0x12, 0x02, 0x43, 0xC3, 0xE4, 0x9D, 0xFD, 0xE4, 0x9C, 0xFC, 0x80, 0x03,
0x12, 0x02, 0x43, 0x30, 0xD5, 0x07, 0xC3, 0xE4, 0x9F, 0xFF, 0xE4, 0x9E, 0xFE, 0x22, 0xC5, 0xF0,
0xF8, 0xA3, 0xE0, 0x28, 0xF0, 0xC5, 0xF0, 0xF8, 0xE5, 0x82, 0x15, 0x82, 0x70, 0x02, 0x15, 0x83,
0xE0, 0x38, 0xF0, 0x22, 0xBB, 0x01, 0x0A, 0x89, 0x82, 0x8A, 0x83, 0xE0, 0xF5, 0xF0, 0xA3, 0xE0,
0x22, 0x50, 0x06, 0x87, 0xF0, 0x09, 0xE7, 0x19, 0x22, 0xBB, 0xFE, 0x07, 0xE3, 0xF5, 0xF0, 0x09,
0xE3, 0x19, 0x22, 0x89, 0x82, 0x8A, 0x83, 0xE4, 0x93, 0xF5, 0xF0, 0x74, 0x01, 0x93, 0x22, 0xBB,
0x01, 0x10, 0xE5, 0x82, 0x29, 0xF5, 0x82, 0xE5, 0x83, 0x3A, 0xF5, 0x83, 0xE0, 0xF5, 0xF0, 0xA3,
0xE0, 0x22, 0x50, 0x09, 0xE9, 0x25, 0x82, 0xF8, 0x86, 0xF0, 0x08, 0xE6, 0x22, 0xBB, 0xFE, 0x0A,
0xE9, 0x25, 0x82, 0xF8, 0xE2, 0xF5, 0xF0, 0x08, 0xE2, 0x22, 0xE5, 0x83, 0x2A, 0xF5, 0x83, 0xE9,
0x93, 0xF5, 0xF0, 0xA3, 0xE9, 0x93, 0x22, 0xBB, 0x01, 0x0A, 0x89, 0x82, 0x8A, 0x83, 0xF0, 0xE5,
0xF0, 0xA3, 0xF0, 0x22, 0x50, 0x06, 0xF7, 0x09, 0xA7, 0xF0, 0x19, 0x22, 0xBB, 0xFE, 0x06, 0xF3,
0xE5, 0xF0, 0x09, 0xF3, 0x19, 0x22, 0xF8, 0xBB, 0x01, 0x11, 0xE5, 0x82, 0x29, 0xF5, 0x82, 0xE5,
0x83, 0x3A, 0xF5, 0x83, 0xE8, 0xF0, 0xE5, 0xF0, 0xA3, 0xF0, 0x22, 0x50, 0x09, 0xE9, 0x25, 0x82,
0xC8, 0xF6, 0x08, 0xA6, 0xF0, 0x22, 0xBB, 0xFE, 0x09, 0xE9, 0x25, 0x82, 0xC8, 0xF2, 0xE5, 0xF0,
0x08, 0xF2, 0x22, 0xEF, 0x2B, 0xFF, 0xEE, 0x3A, 0xFE, 0xED, 0x39, 0xFD, 0xEC, 0x38, 0xFC, 0x22,
0xC3, 0xEF, 0x9B, 0xFF, 0xEE, 0x9A, 0xFE, 0xED, 0x99, 0xFD, 0xEC, 0x98, 0xFC, 0x22, 0x75, 0xF0,
0x08, 0x75, 0x82, 0x00, 0xEF, 0x2F, 0xFF, 0xEE, 0x33, 0xFE, 0xCD, 0x33, 0xCD, 0xCC, 0x33, 0xCC,
0xC5, 0x82, 0x33, 0xC5, 0x82, 0x9B, 0xED, 0x9A, 0xEC, 0x99, 0xE5, 0x82, 0x98, 0x40, 0x0C, 0xF5,
0x82, 0xEE, 0x9B, 0xFE, 0xED, 0x9A, 0xFD, 0xEC, 0x99, 0xFC, 0x0F, 0xD5, 0xF0, 0xD6, 0xE4, 0xCE,
0xFB, 0xE4, 0xCD, 0xFA, 0xE4, 0xCC, 0xF9, 0xA8, 0x82, 0x22, 0xB8, 0x00, 0xC1, 0xB9, 0x00, 0x59,
0xBA, 0x00, 0x2D, 0xEC, 0x8B, 0xF0, 0x84, 0xCF, 0xCE, 0xCD, 0xFC, 0xE5, 0xF0, 0xCB, 0xF9, 0x78,
0x18, 0xEF, 0x2F, 0xFF, 0xEE, 0x33, 0xFE, 0xED, 0x33, 0xFD, 0xEC, 0x33, 0xFC, 0xEB, 0x33, 0xFB,
0x10, 0xD7, 0x03, 0x99, 0x40, 0x04, 0xEB, 0x99, 0xFB, 0x0F, 0xD8, 0xE5, 0xE4, 0xF9, 0xFA, 0x22,
0x78, 0x18, 0xEF, 0x2F, 0xFF, 0xEE, 0x33, 0xFE, 0xED, 0x33, 0xFD, 0xEC, 0x33, 0xFC, 0xC9, 0x33,
0xC9, 0x10, 0xD7, 0x05, 0x9B, 0xE9, 0x9A, 0x40, 0x07, 0xEC, 0x9B, 0xFC, 0xE9, 0x9A, 0xF9, 0x0F,
0xD8, 0xE0, 0xE4, 0xC9, 0xFA, 0xE4, 0xCC, 0xFB, 0x22, 0x75, 0xF0, 0x10, 0xEF, 0x2F, 0xFF, 0xEE,
0x33, 0xFE, 0xED, 0x33, 0xFD, 0xCC, 0x33, 0xCC, 0xC8, 0x33, 0xC8, 0x10, 0xD7, 0x07, 0x9B, 0xEC,
0x9A, 0xE8, 0x99, 0x40, 0x0A, 0xED, 0x9B, 0xFD, 0xEC, 0x9A, 0xFC, 0xE8, 0x99, 0xF8, 0x0F, 0xD5,
0xF0, 0xDA, 0xE4, 0xCD, 0xFB, 0xE4, 0xCC, 0xFA, 0xE4, 0xC8, 0xF9, 0x22, 0xEB, 0x9F, 0xF5, 0xF0,
0xEA, 0x9E, 0x42, 0xF0, 0xE9, 0x9D, 0x42, 0xF0, 0xE8, 0x9C, 0x45, 0xF0, 0x22, 0xE0, 0xFC, 0xA3,
0xE0, 0xFD, 0xA3, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF, 0x22, 0xE0, 0xF8, 0xA3, 0xE0, 0xF9, 0xA3, 0xE0,
0xFA, 0xA3, 0xE0, 0xFB, 0x22, 0xEC, 0xF0, 0xA3, 0xED, 0xF0, 0xA3, 0xEE, 0xF0, 0xA3, 0xEF, 0xF0,
0x22, 0xA8, 0x82, 0x85, 0x83, 0xF0, 0xD0, 0x83, 0xD0, 0x82, 0x12, 0x04, 0xC8, 0x12, 0x04, 0xC8,
0x12, 0x04, 0xC8, 0x12, 0x04, 0xC8, 0xE4, 0x73, 0xE4, 0x93, 0xA3, 0xC5, 0x83, 0xC5, 0xF0, 0xC5,
0x83, 0xC8, 0xC5, 0x82, 0xC8, 0xF0, 0xA3, 0xC5, 0x83, 0xC5, 0xF0, 0xC5, 0x83, 0xC8, 0xC5, 0x82,
0xC8, 0x22, 0xA4, 0x25, 0x82, 0xF5, 0x82, 0xE5, 0xF0, 0x35, 0x83, 0xF5, 0x83, 0x22, 0xE0, 0xFB,
0xA3, 0xE0, 0xFA, 0xA3, 0xE0, 0xF9, 0x22, 0xF8, 0xE0, 0xFB, 0xA3, 0xA3, 0xE0, 0xF9, 0x25, 0xF0,
0xF0, 0xE5, 0x82, 0x15, 0x82, 0x70, 0x02, 0x15, 0x83, 0xE0, 0xFA, 0x38, 0xF0, 0x22, 0xEB, 0xF0,
0xA3, 0xEA, 0xF0, 0xA3, 0xE9, 0xF0, 0x22, 0xD0, 0x83, 0xD0, 0x82, 0xF8, 0xE4, 0x93, 0x70, 0x12,
0x74, 0x01, 0x93, 0x70, 0x0D, 0xA3, 0xA3, 0x93, 0xF8, 0x74, 0x01, 0x93, 0xF5, 0x82, 0x88, 0x83,
0xE4, 0x73, 0x74, 0x02, 0x93, 0x68, 0x60, 0xEF, 0xA3, 0xA3, 0xA3, 0x80, 0xDF, 0x8F, 0x23, 0x8B,
0x24, 0x8A, 0x25, 0x89, 0x26, 0x75, 0x2F, 0x09, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0xEF, 0x78, 0x02,
0xC3, 0x33, 0xCE, 0x33, 0xCE, 0xD8, 0xF9, 0x24, 0xC0, 0xF5, 0x82, 0x74, 0x00, 0x3E, 0xF5, 0x83,
0xC0, 0x83, 0xC0, 0x82, 0x12, 0x04, 0x8D, 0xC0, 0x04, 0xC0, 0x05, 0xC0, 0x06, 0xC0, 0x07, 0xAF,
0x23, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90, 0x00, 0x70, 0x75, 0xF0, 0x28, 0xEF, 0x12, 0x04, 0xE2,
0xEE, 0x75, 0xF0, 0x28, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xC0, 0x83, 0xC0, 0x82, 0x90, 0x00, 0xD3,
0xE0, 0xD0, 0x82, 0xD0, 0x83, 0x25, 0x82, 0xF5, 0x82, 0xE4, 0x35, 0x83, 0xF5, 0x83, 0xE0, 0xFF,
0xE4, 0xF8, 0xF9, 0xFA, 0xAB, 0x07, 0xD0, 0x07, 0xD0, 0x06, 0xD0, 0x05, 0xD0, 0x04, 0x12, 0x03,
0xA0, 0xD0, 0x82, 0xD0, 0x83, 0x12, 0x04, 0xA5, 0xE5, 0x23, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0xED,
0xAE, 0x04, 0x78, 0x02, 0xC3, 0x33, 0xCE, 0x33, 0xCE, 0xD8, 0xF9, 0x24, 0xC0, 0xF5, 0x82, 0x74,
0x00, 0x3E, 0xF5, 0x83, 0xC0, 0x83, 0xC0, 0x82, 0x12, 0x04, 0x99, 0x90, 0x00, 0xD3, 0xE0, 0x24,
0x42, 0x75, 0xF0, 0x28, 0x84, 0xAF, 0xF0, 0x90, 0x00, 0x70, 0x75, 0xF0, 0x28, 0xED, 0x12, 0x04,
0xE2, 0xEC, 0x75, 0xF0, 0x28, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE5, 0x82, 0x2F, 0xF5, 0x82, 0xE4,
0x35, 0x83, 0xF5, 0x83, 0xE0, 0xFF, 0xE4, 0xFC, 0xFD, 0xFE, 0x12, 0x03, 0x93, 0xD0, 0x82, 0xD0,
0x83, 0x12, 0x04, 0xA5, 0xAB, 0x24, 0xAA, 0x25, 0xA9, 0x26, 0xAF, 0x23, 0xEF, 0x33, 0x95, 0xE0,
0xFE, 0x8F, 0x82, 0xF5, 0x83, 0x12, 0x01, 0xD0, 0xFD, 0x90, 0x00, 0x70, 0x75, 0xF0, 0x28, 0xEF,
0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x28, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xC0, 0x83, 0xC0, 0x82,
0x90, 0x00, 0xD3, 0xE0, 0xD0, 0x82, 0xD0, 0x83, 0x25, 0x82, 0xF5, 0x82, 0xE4, 0x35, 0x83, 0xF5,
0x83, 0xED, 0xF0, 0xE4, 0xF5, 0x2D, 0x75, 0x2E, 0xFF, 0xFB, 0xFA, 0x90, 0x00, 0xD3, 0xE0, 0xC3,
0x9B, 0xFF, 0xE4, 0x9A, 0xCF, 0x24, 0x28, 0xCF, 0x34, 0x00, 0xFE, 0x7C, 0x00, 0x7D, 0x28, 0x12,
0x02, 0x98, 0xAF, 0x23, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90, 0x00, 0x70, 0x75, 0xF0, 0x28, 0xEF,
0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x28, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE5, 0x82, 0x2D, 0xF5,
0x82, 0xE5, 0x83, 0x3C, 0xF5, 0x83, 0xE0, 0xFF, 0xE5, 0x2D, 0xC3, 0x9F, 0x50, 0x02, 0x8F, 0x2D,
0xE5, 0x2E, 0xD3, 0x9F, 0x40, 0x02, 0x8F, 0x2E, 0x0B, 0xBB, 0x00, 0x01, 0x0A, 0xEB, 0x64, 0x07,
0x4A, 0x70, 0xA8, 0xC3, 0xE5, 0x2D, 0x95, 0x2E, 0xC3, 0x95, 0x2F, 0x40, 0x03, 0x02, 0x08, 0x78,
0xAF, 0x23, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0xEF, 0x78, 0x02, 0xC3, 0x33, 0xCE, 0x33, 0xCE, 0xD8,
0xF9, 0x24, 0xC0, 0xF5, 0x82, 0x74, 0x00, 0x3E, 0xF5, 0x83, 0x12, 0x04, 0x8D, 0xE4, 0x7B, 0x1A,
0xFA, 0xF9, 0xF8, 0x12, 0x03, 0xEA, 0x8E, 0x29, 0x8F, 0x2A, 0xE4, 0xF5, 0x2B, 0xF5, 0x2C, 0xFA,
0xFB, 0x90, 0x00, 0xD3, 0xE0, 0xC3, 0x9B, 0xFF, 0xE4, 0x9A, 0xCF, 0x24, 0x28, 0xCF, 0x34, 0x00,
0xFE, 0x7C, 0x00, 0x7D, 0x28, 0x12, 0x02, 0x98, 0xAF, 0x23, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90,
0x00, 0x70, 0x75, 0xF0, 0x28, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x28, 0xA4, 0x25, 0x83,
0xF5, 0x83, 0xE5, 0x82, 0x2D, 0xF5, 0x82, 0xE5, 0x83, 0x3C, 0xF5, 0x83, 0xE0, 0x25, 0x2C, 0xF5,
0x2C, 0xE4, 0x35, 0x2B, 0xF5, 0x2B, 0x0B, 0xBB, 0x00, 0x01, 0x0A, 0xEB, 0x64, 0x07, 0x4A, 0x70,
0xB0, 0xAE, 0x2B, 0xAF, 0x2C, 0x7C, 0x00, 0x7D, 0x07, 0x12, 0x02, 0x98, 0x8E, 0x2B, 0x8F, 0x2C,
0xE4, 0xF5, 0x27, 0xF5, 0x28, 0xFA, 0x7B, 0x01, 0x90, 0x00, 0xD3, 0xE0, 0x2B, 0xFF, 0xE4, 0x3A,
0xCF, 0x24, 0x28, 0xCF, 0x34, 0x00, 0xFE, 0x7C, 0x00, 0x7D, 0x28, 0x12, 0x02, 0x98, 0xAF, 0x23,
0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90, 0x00, 0x70, 0x75, 0xF0, 0x28, 0xEF, 0x12, 0x04, 0xE2, 0xEE,
0x75, 0xF0, 0x28, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE5, 0x82, 0x2D, 0xF5, 0x82, 0xE5, 0x83, 0x3C,
0xF5, 0x83, 0xE0, 0xC3, 0x95, 0x2C, 0xE5, 0x2B, 0x64, 0x80, 0xF8, 0x74, 0x80, 0x98, 0x50, 0x08,
0x05, 0x28, 0xE5, 0x28, 0x70, 0x02, 0x05, 0x27, 0x0B, 0xBB, 0x00, 0x01, 0x0A, 0xEB, 0x64, 0x1B,
0x4A, 0x70, 0xA5, 0xC3, 0xE5, 0x2A, 0x95, 0x2C, 0xFF, 0xE5, 0x29, 0x95, 0x2B, 0xFE, 0xC3, 0xEF,
0x94, 0x03, 0xEE, 0x64, 0x80, 0x94, 0x80, 0x50, 0x03, 0x02, 0x08, 0x78, 0xE5, 0x28, 0x94, 0x0A,
0xE5, 0x27, 0x64, 0x80, 0x94, 0x80, 0x40, 0x03, 0x02, 0x08, 0x78, 0xE5, 0x23, 0xFD, 0x33, 0x95,
0xE0, 0xFC, 0x74, 0xC9, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xE5, 0x2C, 0xF0, 0x74,
0xC9, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xE0, 0x75, 0xF0, 0x1A, 0xA4, 0xFF, 0xAE,
0xF0, 0xE4, 0xFC, 0xFD, 0xC0, 0x04, 0xC0, 0x05, 0xC0, 0x06, 0xC0, 0x07, 0xAF, 0x23, 0xEF, 0x33,
0x95, 0xE0, 0xFE, 0xEF, 0x78, 0x02, 0xC3, 0x33, 0xCE, 0x33, 0xCE, 0xD8, 0xF9, 0x24, 0xC0, 0xF5,
0x82, 0x74, 0x00, 0x3E, 0xF5, 0x83, 0xD0, 0x07, 0xD0, 0x06, 0xD0, 0x05, 0xD0, 0x04, 0x12, 0x04,
0xA5, 0xE4, 0xFA, 0xFB, 0xAF, 0x23, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x74, 0xC9, 0x2F, 0xF5, 0x82,
0x74, 0x00, 0x3E, 0xF5, 0x83, 0xE0, 0xFF, 0xAD, 0x23, 0xED, 0x33, 0x95, 0xE0, 0xFC, 0x90, 0x00,
0x70, 0x75, 0xF0, 0x28, 0xED, 0x12, 0x04, 0xE2, 0xEC, 0x75, 0xF0, 0x28, 0xA4, 0x25, 0x83, 0xF5,
0x83, 0xE5, 0x82, 0x2B, 0xF5, 0x82, 0xE4, 0x35, 0x83, 0xF5, 0x83, 0xEF, 0xF0, 0x0B, 0xBB, 0x00,
0x01, 0x0A, 0xEB, 0x64, 0x28, 0x4A, 0x70, 0xBC, 0xE4, 0xF5, 0x2D, 0x75, 0x2E, 0xFF, 0xFA, 0xFB,
0x90, 0x00, 0xD3, 0xE0, 0xC3, 0x9B, 0xFF, 0xE4, 0x9A, 0xCF, 0x24, 0x28, 0xCF, 0x34, 0x00, 0xFE,
0x7C, 0x00, 0x7D, 0x28, 0x12, 0x02, 0x98, 0xAF, 0x23, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90, 0x00,
0x70, 0x75, 0xF0, 0x28, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x28, 0xA4, 0x25, 0x83, 0xF5,
0x83, 0xE5, 0x82, 0x2D, 0xF5, 0x82, 0xE5, 0x83, 0x3C, 0xF5, 0x83, 0xE0, 0xFF, 0xE5, 0x2D, 0xC3,
0x9F, 0x50, 0x02, 0x8F, 0x2D, 0xE5, 0x2E, 0xD3, 0x9F, 0x40, 0x02, 0x8F, 0x2E, 0x0B, 0xBB, 0x00,
0x01, 0x0A, 0xEB, 0x64, 0x0A, 0x4A, 0x70, 0xA8, 0xC3, 0xE5, 0x2D, 0x95, 0x2E, 0xC3, 0x95, 0x2F,
0x50, 0x37, 0xAF, 0x23, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x74, 0xC9, 0x2F, 0xF5, 0x82, 0x74, 0x00,
0x3E, 0xF5, 0x83, 0xE0, 0x24, 0x0A, 0xFD, 0xE4, 0x33, 0xFC, 0xC3, 0xE5, 0x2D, 0x9D, 0xEC, 0x64,
0x80, 0xF8, 0x74, 0x80, 0x98, 0x50, 0x0F, 0x74, 0xC9, 0x2F, 0xF5, 0x82, 0x74, 0x00, 0x3E, 0xF5,
0x83, 0xE5, 0x2D, 0xF0, 0x80, 0x03, 0x7F, 0x01, 0x22, 0xAF, 0x23, 0x12, 0x2C, 0x30, 0xE5, 0x23,
0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x74, 0xC9, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xE0,
0xFE, 0xEF, 0xD3, 0x9E, 0x50, 0x1B, 0xAF, 0x23, 0x12, 0x2C, 0x1E, 0xE5, 0x23, 0xFD, 0x33, 0x95,
0xE0, 0xFC, 0x74, 0xC9, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xE0, 0xD3, 0x9F, 0x40,
0x0A, 0xAF, 0x23, 0x12, 0x0D, 0x5E, 0xEF, 0x70, 0x02, 0xFF, 0x22, 0x7F, 0x01, 0x22, 0x00, 0xFF,
0x00, 0xFC, 0x00, 0xF9, 0x00, 0xF6, 0x00, 0xF3, 0x00, 0xF0, 0x00, 0xEE, 0x00, 0xEB, 0x00, 0xE8,
0x00, 0xE5, 0x00, 0xE3, 0x00, 0xE0, 0x00, 0xDD, 0x00, 0xDB, 0x00, 0xD8, 0x00, 0xD6, 0x00, 0xD3,
0x00, 0xD1, 0x00, 0xCE, 0x00, 0xCC, 0x00, 0xCA, 0x00, 0xC7, 0x00, 0xC5, 0x00, 0xC3, 0x00, 0xC0,
0x00, 0xBE, 0x00, 0xBC, 0x00, 0xBA, 0x00, 0xB7, 0x00, 0xB5, 0x00, 0xB3, 0x00, 0xB1, 0x00, 0xAF,
0x00, 0xAD, 0x00, 0xAB, 0x00, 0xA9, 0x00, 0xA7, 0x00, 0xA5, 0x00, 0xA3, 0x00, 0xA1, 0x00, 0x9F,
0x00, 0x9D, 0x00, 0x9C, 0x00, 0x9A, 0x00, 0x98, 0x00, 0x96, 0x00, 0x94, 0x00, 0x93, 0x00, 0x91,
0x00, 0x8F, 0x00, 0x8E, 0x00, 0x8C, 0x00, 0x8A, 0x00, 0x89, 0x00, 0x87, 0x00, 0x86, 0x00, 0x84,
0x00, 0x82, 0x00, 0x81, 0x00, 0x7F, 0x00, 0x7E, 0x00, 0x7C, 0x00, 0x7B, 0x00, 0x7A, 0x00, 0x78,
0x00, 0x77, 0x00, 0x75, 0x00, 0x74, 0x00, 0x73, 0x00, 0x71, 0x00, 0x70, 0x00, 0x6F, 0x00, 0x6D,
0x00, 0x6C, 0x00, 0x6B, 0x00, 0x6A, 0x00, 0x68, 0x00, 0x67, 0x00, 0x66, 0x00, 0x65, 0x00, 0x63,
0x00, 0x62, 0x00, 0x61, 0x00, 0x60, 0x00, 0x5F, 0x00, 0x5E, 0x00, 0x5D, 0x00, 0x5C, 0x00, 0x5B,
0x00, 0x5A, 0x00, 0x58, 0x00, 0x57, 0x00, 0x56, 0x00, 0x55, 0x00, 0x54, 0x00, 0x53, 0x00, 0x52,
0x00, 0x51, 0x00, 0x51, 0x00, 0x50, 0x00, 0x4F, 0x00, 0x4E, 0x00, 0x4D, 0x00, 0x4C, 0x00, 0x4B,
0x00, 0x4A, 0x00, 0x49, 0x00, 0x48, 0x00, 0x48, 0x00, 0x47, 0x00, 0x46, 0x00, 0x45, 0x00, 0x44,
0x00, 0x43, 0x00, 0x43, 0x00, 0x42, 0x00, 0x41, 0x00, 0x40, 0x00, 0x40, 0x00, 0x3F, 0x00, 0x3E,
0x00, 0x3D, 0x00, 0x3D, 0x00, 0x3C, 0x00, 0x3B, 0x00, 0x3B, 0x00, 0x3A, 0x00, 0x39, 0x00, 0x39,
0x00, 0x38, 0x00, 0x37, 0x00, 0x37, 0x00, 0x36, 0x00, 0x35, 0x00, 0x35, 0x00, 0x34, 0x00, 0x33,
0x00, 0x33, 0x00, 0x32, 0x00, 0x32, 0x00, 0x31, 0x00, 0x31, 0x00, 0x30, 0x00, 0x2F, 0x00, 0x2F,
0x00, 0x2E, 0x00, 0x2E, 0x00, 0x2D, 0x00, 0x2D, 0x00, 0x2C, 0x00, 0x2C, 0x00, 0x2B, 0x00, 0x2B,
0x00, 0x2A, 0x00, 0x2A, 0x00, 0x29, 0x00, 0x29, 0x00, 0x28, 0x00, 0x28, 0x00, 0x27, 0x00, 0x27,
0x00, 0x26, 0x00, 0x26, 0x00, 0x25, 0x00, 0x25, 0x00, 0x25, 0x00, 0x24, 0x00, 0x24, 0x00, 0x23,
0x00, 0x23, 0x00, 0x23, 0x00, 0x22, 0x00, 0x22, 0x00, 0x21, 0x00, 0x21, 0x00, 0x21, 0x00, 0x20,
0x00, 0x20, 0x00, 0x1F, 0x00, 0x1F, 0x00, 0x1F, 0x00, 0x1E, 0x00, 0x1E, 0x00, 0x1E, 0x00, 0x1D,
0x00, 0x1D, 0x00, 0x1D, 0x00, 0x1C, 0x00, 0x1C, 0x00, 0x1C, 0x00, 0x1B, 0x00, 0x1B, 0x00, 0x1B,
0x00, 0x1A, 0x00, 0x1A, 0x00, 0x1A, 0x00, 0x19, 0x00, 0x19, 0x00, 0x19, 0x00, 0x19, 0x00, 0x18,
0x00, 0x18, 0x00, 0x18, 0x00, 0x17, 0x00, 0x17, 0x00, 0x17, 0x00, 0x17, 0x00, 0x16, 0x00, 0x16,
0x00, 0x16, 0x00, 0x16, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x14, 0x00, 0x14,
0x00, 0x14, 0x00, 0x14, 0x00, 0x13, 0x00, 0x13, 0x00, 0x13, 0x00, 0x13, 0x00, 0x13, 0x00, 0x12,
0x00, 0x12, 0x00, 0x12, 0x00, 0x12, 0x00, 0x11, 0x00, 0x11, 0x00, 0x11, 0x00, 0x11, 0x00, 0x11,
0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x0F, 0x00, 0x0F,
0x00, 0x0F, 0x00, 0x0F, 0x00, 0x0F, 0x00, 0x0E, 0x00, 0x0E, 0x00, 0x0E, 0x00, 0x0E, 0x00, 0x0E,
0x00, 0x0E, 0x00, 0x0D, 0x00, 0x0D, 0x00, 0x0D, 0x00, 0x0D, 0x00, 0x0D, 0x00, 0x0D, 0x00, 0x03,
0x06, 0x09, 0x0C, 0x0F, 0x11, 0x14, 0x17, 0x1A, 0x1C, 0x1F, 0x22, 0x24, 0x27, 0x29, 0x2C, 0x2E,
0x31, 0x33, 0x35, 0x38, 0x3A, 0x3C, 0x3F, 0x41, 0x43, 0x45, 0x48, 0x4A, 0x4C, 0x4E, 0x50, 0x52,
0x54, 0x56, 0x58, 0x5A, 0x5C, 0x5E, 0x60, 0x62, 0x63, 0x65, 0x67, 0x69, 0x6B, 0x6C, 0x6E, 0x70,
0x71, 0x73, 0x75, 0x76, 0x78, 0x79, 0x7B, 0x7D, 0x7E, 0x80, 0x81, 0x83, 0x84, 0x85, 0x87, 0x88,
0x8A, 0x8B, 0x8C, 0x8E, 0x8F, 0x90, 0x92, 0x93, 0x94, 0x95, 0x97, 0x98, 0x99, 0x9A, 0x9C, 0x9D,
0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE,
0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC,
0xBC, 0xBD, 0xBE, 0xBF, 0xBF, 0xC0, 0xC1, 0xC2, 0xC2, 0xC3, 0xC4, 0xC4, 0xC5, 0xC6, 0xC6, 0xC7,
0xC8, 0xC8, 0xC9, 0xCA, 0xCA, 0xCB, 0xCC, 0xCC, 0xCD, 0xCD, 0xCE, 0xCE, 0xCF, 0xD0, 0xD0, 0xD1,
0xD1, 0xD2, 0xD2, 0xD3, 0xD3, 0xD4, 0xD4, 0xD5, 0xD5, 0xD6, 0xD6, 0xD7, 0xD7, 0xD8, 0xD8, 0xD9,
0xD9, 0xDA, 0xDA, 0xDA, 0xDB, 0xDB, 0xDC, 0xDC, 0xDC, 0xDD, 0xDD, 0xDE, 0xDE, 0xDE, 0xDF, 0xDF,
0xE0, 0xE0, 0xE0, 0xE1, 0xE1, 0xE1, 0xE2, 0xE2, 0xE2, 0xE3, 0xE3, 0xE3, 0xE4, 0xE4, 0xE4, 0xE5,
0xE5, 0xE5, 0xE6, 0xE6, 0xE6, 0xE6, 0xE7, 0xE7, 0xE7, 0xE8, 0xE8, 0xE8, 0xE8, 0xE9, 0xE9, 0xE9,
0xE9, 0xEA, 0xEA, 0xEA, 0xEA, 0xEB, 0xEB, 0xEB, 0xEB, 0xEC, 0xEC, 0xEC, 0xEC, 0xEC, 0xED, 0xED,
0xED, 0xED, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0xEF, 0xEF, 0xEF, 0xEF, 0xEF, 0xEF, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0x00, 0x03,
0x06, 0x09, 0x0C, 0x0F, 0x11, 0x14, 0x17, 0x1A, 0x1C, 0x1F, 0x22, 0x24, 0x27, 0x29, 0x2C, 0x2E,
0x31, 0x33, 0x35, 0x38, 0x3A, 0x3C, 0x3F, 0x41, 0x43, 0x45, 0x48, 0x4A, 0x4C, 0x4E, 0x50, 0x52,
0x54, 0x56, 0x58, 0x5A, 0x5C, 0x5E, 0x60, 0x62, 0x63, 0x65, 0x67, 0x69, 0x6B, 0x6C, 0x6E, 0x70,
0x71, 0x73, 0x75, 0x76, 0x78, 0x79, 0x7B, 0x7D, 0x7E, 0x80, 0x81, 0x83, 0x84, 0x85, 0x87, 0x88,
0x8A, 0x8B, 0x8C, 0x8E, 0x8F, 0x90, 0x92, 0x93, 0x94, 0x95, 0x97, 0x98, 0x99, 0x9A, 0x9C, 0x9D,
0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE,
0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC,
0xBC, 0xBD, 0xBE, 0xBF, 0xBF, 0xC0, 0xC1, 0xC2, 0xC2, 0xC3, 0xC4, 0xC4, 0xC5, 0xC6, 0xC6, 0xC7,
0xC8, 0xC8, 0xC9, 0xCA, 0xCA, 0xCB, 0xCC, 0xCC, 0xCD, 0xCD, 0xCE, 0xCE, 0xCF, 0xD0, 0xD0, 0xD1,
0xD1, 0xD2, 0xD2, 0xD3, 0xD3, 0xD4, 0xD4, 0xD5, 0xD5, 0xD6, 0xD6, 0xD7, 0xD7, 0xD8, 0xD8, 0xD9,
0xD9, 0xDA, 0xDA, 0xDA, 0xDB, 0xDB, 0xDC, 0xDC, 0xDC, 0xDD, 0xDD, 0xDE, 0xDE, 0xDE, 0xDF, 0xDF,
0xE0, 0xE0, 0xE0, 0xE1, 0xE1, 0xE1, 0xE2, 0xE2, 0xE2, 0xE3, 0xE3, 0xE3, 0xE4, 0xE4, 0xE4, 0xE5,
0xE5, 0xE5, 0xE6, 0xE6, 0xE6, 0xE6, 0xE7, 0xE7, 0xE7, 0xE8, 0xE8, 0xE8, 0xE8, 0xE9, 0xE9, 0xE9,
0xE9, 0xEA, 0xEA, 0xEA, 0xEA, 0xEB, 0xEB, 0xEB, 0xEB, 0xEC, 0xEC, 0xEC, 0xEC, 0xEC, 0xED, 0xED,
0xED, 0xED, 0xEE, 0xEE, 0xEE, 0xEE, 0xEE, 0xEF, 0xEF, 0xEF, 0xEF, 0xEF, 0xEF, 0xF0, 0xF0, 0xF0,
0xF0, 0xF0, 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, 0xF1, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0x90, 0x01,
0x1A, 0xEF, 0xF0, 0x90, 0x01, 0x1C, 0x74, 0x01, 0xF0, 0x12, 0x2C, 0x1E, 0x7E, 0x00, 0xC0, 0x06,
0xC0, 0x07, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C, 0x30, 0xEF, 0xFD, 0xD0, 0xE0, 0x2D, 0xFF,
0xD0, 0xE0, 0x34, 0x00, 0xA2, 0xE7, 0x13, 0xFE, 0xEF, 0x13, 0xFF, 0x90, 0x01, 0x1F, 0xEE, 0xF0,
0xA3, 0xEF, 0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C, 0x30, 0xC3, 0x90, 0x01, 0x20, 0xE0,
0x9F, 0xFF, 0x90, 0x01, 0x1F, 0xE0, 0x94, 0x00, 0xFE, 0xEF, 0x78, 0x02, 0xC3, 0x33, 0xCE, 0x33,
0xCE, 0xD8, 0xF9, 0xFF, 0x7C, 0x00, 0x7D, 0x0A, 0x12, 0x02, 0x98, 0x90, 0x01, 0x20, 0xE0, 0xC3,
0x9F, 0x90, 0x01, 0x1D, 0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C, 0x1E, 0x90, 0x01, 0x1F,
0xE0, 0xFC, 0xA3, 0xE0, 0xFD, 0xC3, 0xEF, 0x9D, 0xFF, 0xE4, 0x9C, 0xFE, 0xEF, 0x78, 0x02, 0xC3,
0x33, 0xCE, 0x33, 0xCE, 0xD8, 0xF9, 0xFF, 0x7C, 0x00, 0x7D, 0x0A, 0x12, 0x02, 0x98, 0x90, 0x01,
0x20, 0x02, 0x11, 0x1E, 0x90, 0x01, 0x1A, 0xE0, 0xFB, 0xE4, 0xFD, 0x7F, 0xFF, 0x12, 0x29, 0x1C,
0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x7D, 0x1B, 0x12, 0x24, 0xDD, 0x12, 0x2B, 0xA3, 0x90, 0x01, 0x1A,
0xE0, 0xFB, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x74, 0x6E, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5,
0x83, 0xEF, 0xF0, 0x74, 0x6E, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xE0, 0xFF, 0x74,
0xAB, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83, 0xE0, 0xFE, 0xC3, 0xEF, 0x9E, 0xFD, 0x12,
0x29, 0x1C, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x7D, 0x1B, 0x12, 0x24, 0xDD, 0x90, 0x01, 0x1A, 0xE0,
0xFD, 0x12, 0x2A, 0xB7, 0x90, 0x01, 0x1D, 0xE0, 0xFE, 0xEF, 0xC3, 0x9E, 0x50, 0x7A, 0x90, 0x01,
0x1D, 0xE0, 0xD3, 0x9F, 0x50, 0x0A, 0xA3, 0xE0, 0xFE, 0xEF, 0x9E, 0x50, 0x03, 0x02, 0x0F, 0x69,
0x90, 0x01, 0x1A, 0xE0, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x74, 0x6E, 0x2D, 0xF5, 0x82, 0x74, 0x00,
0x3C, 0xF5, 0x83, 0xE0, 0xC3, 0x94, 0xFF, 0x40, 0x03, 0x02, 0x10, 0x6E, 0x74, 0x6E, 0x2D, 0xF5,
0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xE0, 0x04, 0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xF9, 0xFD, 0x33,
0x95, 0xE0, 0xFC, 0x74, 0x6E, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xE0, 0xFF, 0x74,
0xAB, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83, 0xE0, 0xFE, 0xC3, 0xEF, 0x9E, 0xFD, 0xAB,
0x01, 0x12, 0x29, 0x1C, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x7D, 0x1B, 0x12, 0x24, 0xDD, 0x90, 0x01,
0x1A, 0xE0, 0xFD, 0x12, 0x2A, 0xB7, 0x80, 0x86, 0x90, 0x01, 0x1E, 0xE0, 0xFE, 0xEF, 0xD3, 0x9E,
0x50, 0x03, 0x02, 0x0F, 0x69, 0x90, 0x01, 0x1D, 0xE0, 0xD3, 0x9F, 0x50, 0x07, 0xA3, 0xE0, 0xFE,
0xEF, 0x9E, 0x40, 0x75, 0x90, 0x01, 0x1A, 0xE0, 0xFE, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x74, 0xAB,
0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83, 0xE0, 0xFB, 0x74, 0x6E, 0x2D, 0xF5, 0x82, 0x74,
0x00, 0x3C, 0xF5, 0x83, 0xE0, 0xD3, 0x9B, 0x50, 0x03, 0x02, 0x10, 0x6E, 0xEE, 0x33, 0x95, 0xE0,
0xFC, 0x74, 0x6E, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xE0, 0x14, 0xF0, 0x90, 0x01,
0x1A, 0xE0, 0xF9, 0x74, 0x6E, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xE0, 0xFF, 0x74,
0xAB, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83, 0xE0, 0xFE, 0xC3, 0xEF, 0x9E, 0xFD, 0xAB,
0x01, 0x12, 0x29, 0x1C, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x7D, 0x1B, 0x12, 0x24, 0xDD, 0x90, 0x01,
0x1A, 0xE0, 0xFD, 0x12, 0x2A, 0xB7, 0x02, 0x0E, 0xE5, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C,
0x1E, 0x90, 0x01, 0x1A, 0xE0, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x74, 0xC9, 0x2D, 0xF5, 0x82, 0x74,
0x00, 0x3C, 0xF5, 0x83, 0xEF, 0xF0, 0xE4, 0x90, 0x01, 0x1B, 0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xFF,
0x12, 0x2C, 0x1E, 0x90, 0x01, 0x1A, 0xE0, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x90, 0x00, 0x70, 0x75,
0xF0, 0x28, 0xED, 0x12, 0x04, 0xE2, 0xEC, 0x75, 0xF0, 0x28, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xC0,
0x83, 0xC0, 0x82, 0x90, 0x01, 0x1B, 0xE0, 0xD0, 0x82, 0xD0, 0x83, 0x25, 0x82, 0xF5, 0x82, 0xE4,
0x35, 0x83, 0xF5, 0x83, 0xEF, 0xF0, 0x90, 0x01, 0x1B, 0xE0, 0x04, 0xF0, 0xE0, 0xC3, 0x94, 0x28,
0x40, 0xB9, 0xE4, 0x90, 0x01, 0x1B, 0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C, 0x1E, 0x90,
0x01, 0x1A, 0xE0, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x90, 0x00, 0xCD, 0x75, 0xF0, 0x03, 0xED, 0x12,
0x04, 0xE2, 0xEC, 0x75, 0xF0, 0x03, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xC0, 0x83, 0xC0, 0x82, 0x90,
0x01, 0x1B, 0xE0, 0xD0, 0x82, 0xD0, 0x83, 0x25, 0x82, 0xF5, 0x82, 0xE4, 0x35, 0x83, 0xF5, 0x83,
0xEF, 0xF0, 0x90, 0x01, 0x1B, 0xE0, 0x04, 0xF0, 0xE0, 0xC3, 0x94, 0x03, 0x40, 0xB9, 0xE4, 0x90,
0x00, 0xC8, 0xF0, 0x90, 0x00, 0xD3, 0x74, 0x27, 0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C,
0x1E, 0xEF, 0x75, 0xF0, 0x1A, 0xA4, 0xFF, 0xAE, 0xF0, 0xE4, 0xFC, 0xFD, 0xC0, 0x04, 0xC0, 0x05,
0xC0, 0x06, 0xC0, 0x07, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x33, 0x95, 0xE0, 0xFE, 0xEF, 0x78, 0x02,
0xC3, 0x33, 0xCE, 0x33, 0xCE, 0xD8, 0xF9, 0x24, 0xC0, 0xF5, 0x82, 0x74, 0x00, 0x3E, 0xF5, 0x83,
0xD0, 0x07, 0xD0, 0x06, 0xD0, 0x05, 0xD0, 0x04, 0x12, 0x04, 0xA5, 0x7F, 0x01, 0x22, 0x90, 0x01,
0x1C, 0xE0, 0x64, 0x01, 0x70, 0x52, 0x74, 0x02, 0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C,
0x30, 0xC3, 0x90, 0x01, 0x20, 0xE0, 0x9F, 0xFF, 0x90, 0x01, 0x1F, 0xE0, 0x94, 0x00, 0xFE, 0x7C,
0x00, 0x7D, 0x07, 0x12, 0x02, 0x31, 0x7D, 0x0A, 0x12, 0x02, 0x98, 0xA3, 0xE0, 0xC3, 0x9F, 0x90,
0x01, 0x1D, 0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C, 0x1E, 0x90, 0x01, 0x1F, 0xE0, 0xFC,
0xA3, 0xE0, 0xFD, 0xC3, 0xEF, 0x9D, 0xFF, 0xE4, 0x9C, 0xFE, 0x7C, 0x00, 0x7D, 0x07, 0x12, 0x02,
0x31, 0x7D, 0x0A, 0x12, 0x02, 0x98, 0x80, 0x56, 0x90, 0x01, 0x1C, 0xE0, 0x64, 0x02, 0x70, 0x57,
0x74, 0x03, 0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C, 0x30, 0xC3, 0x90, 0x01, 0x20, 0xE0,
0x9F, 0xFF, 0x90, 0x01, 0x1F, 0xE0, 0x94, 0x00, 0xFE, 0x7C, 0x00, 0x7D, 0x09, 0x12, 0x02, 0x31,
0x0D, 0x12, 0x02, 0x98, 0xA3, 0xE0, 0xC3, 0x9F, 0x90, 0x01, 0x1D, 0xF0, 0x90, 0x01, 0x1A, 0xE0,
0xFF, 0x12, 0x2C, 0x1E, 0x90, 0x01, 0x1F, 0xE0, 0xFC, 0xA3, 0xE0, 0xFD, 0xC3, 0xEF, 0x9D, 0xFF,
0xE4, 0x9C, 0xFE, 0x7C, 0x00, 0x7D, 0x09, 0x12, 0x02, 0x31, 0x0D, 0x12, 0x02, 0x98, 0xE0, 0x2F,
0x90, 0x01, 0x1E, 0xF0, 0x02, 0x0D, 0xF4, 0x90, 0x01, 0x1C, 0xE0, 0xB4, 0x03, 0x22, 0x74, 0x04,
0xF0, 0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C, 0x1E, 0xEF, 0x24, 0x0C, 0x90, 0x01, 0x1E, 0xF0,
0x90, 0x01, 0x1A, 0xE0, 0xFF, 0x12, 0x2C, 0x30, 0x90, 0x01, 0x1D, 0xEF, 0xF0, 0x02, 0x0D, 0xF4,
0x7F, 0x00, 0x22, 0x8B, 0x23, 0x8A, 0x24, 0x89, 0x25, 0x8D, 0x26, 0xE4, 0xF5, 0x28, 0xE4, 0xF5,
0x27, 0xAD, 0x27, 0xED, 0x33, 0x95, 0xE0, 0xFC, 0xC3, 0xED, 0x95, 0x26, 0x74, 0x80, 0xF8, 0x6C,
0x98, 0x50, 0x3D, 0x12, 0x2C, 0xA6, 0xE4, 0xFD, 0xFF, 0x12, 0x1E, 0x7C, 0xE5, 0x27, 0xFD, 0x33,
0x95, 0xE0, 0xFC, 0x74, 0x36, 0x2D, 0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xEF, 0xF0, 0xE4,
0xFD, 0x7F, 0x01, 0x12, 0x1E, 0x7C, 0xE5, 0x27, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x74, 0x51, 0x2D,
0xF5, 0x82, 0x74, 0x00, 0x3C, 0xF5, 0x83, 0xEF, 0xF0, 0x12, 0x2C, 0xAE, 0x05, 0x27, 0x80, 0xB1,
0xE4, 0xF5, 0x27, 0xAF, 0x27, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90, 0x00, 0x36, 0x75, 0xF0, 0x1B,
0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x08,
0x90, 0x00, 0x37, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25,
0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x09, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90, 0x00, 0x38, 0x75, 0xF0,
0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5,
0x0A, 0x90, 0x00, 0x39, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4,
0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x0B, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90, 0x00, 0x3A, 0x75,
0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0,
0xF5, 0x0C, 0x90, 0x00, 0x3B, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B,
0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x0D, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90, 0x00, 0x3C,
0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25, 0x83, 0xF5, 0x83,
0xE0, 0xF5, 0x0E, 0x90, 0x00, 0x3D, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0,
0x1B, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x0F, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90, 0x00,
0x3E, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25, 0x83, 0xF5,
0x83, 0xE0, 0xF5, 0x10, 0x90, 0x00, 0x3F, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75,
0xF0, 0x1B, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x11, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x90,
0x00, 0x40, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25, 0x83,
0xF5, 0x83, 0xE0, 0xF5, 0x12, 0x90, 0x00, 0x41, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE,
0x75, 0xF0, 0x1B, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x13, 0xEF, 0x33, 0x95, 0xE0, 0xFE,
0x90, 0x00, 0x42, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25,
0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x14, 0x90, 0x00, 0x43, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2,
0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x15, 0xEF, 0x33, 0x95, 0xE0,
0xFE, 0x90, 0x00, 0x44, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4,
0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x16, 0x90, 0x00, 0x45, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04,
0xE2, 0xEE, 0x75, 0xF0, 0x1B, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x17, 0xEF, 0x33, 0x95,
0xE0, 0xFE, 0x90, 0x00, 0x46, 0x75, 0xF0, 0x1B, 0xEF, 0x12, 0x04, 0xE2, 0xEE, 0x75, 0xF0, 0x1B,
0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE0, 0xF5, 0x18, 0x7C, 0x00, 0x78, 0x08, 0xE8, 0x2C, 0xF8, 0xF9,
0xE6, 0xFA, 0xEC, 0xFB, 0x0B, 0x08, 0xE6, 0x9A, 0x40, 0x0B, 0xE6, 0xCA, 0xF6, 0xE8, 0xFD, 0xE9,
0xF8, 0xEA, 0xF6, 0xED, 0xF8, 0x0B, 0xBB, 0x11, 0xEC, 0x0C, 0xBC, 0x09, 0xDD, 0xAD, 0x27, 0xAF,
0x10, 0x12, 0x2A, 0xB7, 0xAB, 0x23, 0xAA, 0x24, 0xA9, 0x25, 0xE5, 0x27, 0xFD, 0x33, 0x95, 0xE0,
0x8D, 0x82, 0xF5, 0x83, 0xEF, 0x12, 0x02, 0x0F, 0x05, 0x27, 0xC3, 0xE5, 0x27, 0x64, 0x80, 0x94,
0x82, 0x50, 0x03, 0x02, 0x11, 0xB3, 0xC3, 0xE5, 0x28, 0x64, 0x80, 0x94, 0x86, 0x50, 0x35, 0xE4,
0xF5, 0x27, 0xC3, 0xE5, 0x27, 0x64, 0x80, 0x94, 0x82, 0x50, 0x29, 0xAF, 0x27, 0x12, 0x2C, 0x30,
0xEF, 0x24, 0xEC, 0xFF, 0xAB, 0x23, 0xAA, 0x24, 0xA9, 0x25, 0xE5, 0x27, 0xFD, 0x33, 0x95, 0xE0,
0x8D, 0x82, 0xF5, 0x83, 0x12, 0x01, 0xD0, 0xC3, 0x9F, 0x50, 0x05, 0x05, 0x28, 0x02, 0x11, 0x5E,
0x05, 0x27, 0x80, 0xCE, 0x22, 0x90, 0x01, 0x16, 0x12, 0x05, 0x0E, 0x90, 0x01, 0x19, 0xEC, 0xF0,
0xA3, 0xED, 0xF0, 0xE4, 0xA3, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x1B, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF,
0xC3, 0x94, 0x02, 0xEE, 0x64, 0x80, 0x94, 0x80, 0x40, 0x03, 0x02, 0x16, 0x49, 0xE4, 0xA3, 0xF0,
0x90, 0x01, 0x19, 0xE0, 0xF4, 0x70, 0x03, 0xA3, 0xE0, 0xF4, 0x70, 0x30, 0x90, 0x01, 0x77, 0xE0,
0xFD, 0x90, 0x01, 0x76, 0xE0, 0x2D, 0xFD, 0xE4, 0x33, 0xFC, 0xEF, 0x25, 0xE0, 0xFF, 0xEE, 0x33,
0xFE, 0x74, 0x56, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0, 0xC3, 0x9D, 0xEC, 0x64,
0x80, 0xF8, 0x74, 0x80, 0x98, 0x40, 0x03, 0x02, 0x15, 0x24, 0x80, 0x48, 0x90, 0x01, 0x1A, 0xE0,
0x24, 0x33, 0xF8, 0xE6, 0xFF, 0x33, 0x95, 0xE0, 0xFE, 0xA3, 0xE0, 0xFC, 0xA3, 0xE0, 0xFD, 0x6F,
0x70, 0x02, 0xEC, 0x6E, 0x60, 0x3E, 0x90, 0x01, 0x77, 0xE0, 0xFF, 0x90, 0x01, 0x76, 0xE0, 0x2F,
0xFB, 0xE4, 0x33, 0xFA, 0xED, 0x25, 0xE0, 0xFF, 0xEC, 0x33, 0xFE, 0x74, 0x56, 0x2F, 0xF5, 0x82,
0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0, 0xC3, 0x9B, 0xEA, 0x64, 0x80, 0xF8, 0x74, 0x80, 0x98, 0x40,
0x03, 0x02, 0x15, 0x24, 0x74, 0x56, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0, 0x04,
0xF0, 0x02, 0x15, 0x24, 0x90, 0x01, 0x78, 0xE0, 0xFF, 0x90, 0x01, 0x75, 0xE0, 0x2F, 0xFF, 0xE4,
0x33, 0xFE, 0x90, 0x01, 0x53, 0xE0, 0x24, 0x7A, 0xF5, 0x82, 0xE4, 0x34, 0x01, 0xF5, 0x83, 0xE0,
0x7C, 0x00, 0x2F, 0xFD, 0xEC, 0x3E, 0xFC, 0x90, 0x01, 0x1C, 0xE0, 0x25, 0xE0, 0xFF, 0x90, 0x01,
0x1B, 0xE0, 0x33, 0xFE, 0x74, 0x55, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0, 0xC3,
0x9D, 0xEC, 0x64, 0x80, 0xF8, 0x74, 0x80, 0x98, 0x50, 0x0F, 0x74, 0x55, 0x2F, 0xF5, 0x82, 0x74,
0x01, 0x3E, 0xF5, 0x83, 0xE0, 0x04, 0xF0, 0x80, 0x25, 0x90, 0x01, 0x78, 0xE0, 0xFF, 0x90, 0x01,
0x75, 0xE0, 0x2F, 0x04, 0xFD, 0x90, 0x01, 0x1C, 0xE0, 0x25, 0xE0, 0xFF, 0x90, 0x01, 0x1B, 0xE0,
0x33, 0xFE, 0x74, 0x55, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xED, 0xF0, 0x90, 0x01,
0x1D, 0x74, 0x01, 0xF0, 0x90, 0x01, 0x1D, 0xE0, 0x60, 0x38, 0x90, 0x01, 0x1C, 0xE0, 0x25, 0xE0,
0xFF, 0x90, 0x01, 0x1B, 0xE0, 0x33, 0xFE, 0x74, 0x55, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5,
0x83, 0xE0, 0xFF, 0x90, 0x01, 0x75, 0xE0, 0xFE, 0xEF, 0x6E, 0x70, 0x6F, 0x90, 0x01, 0x16, 0x12,
0x04, 0xEE, 0x90, 0x00, 0x02, 0xE4, 0x12, 0x02, 0x0F, 0xE4, 0x75, 0xF0, 0x01, 0x12, 0x03, 0x47,
0x80, 0x59, 0x90, 0x01, 0x1C, 0xE0, 0x25, 0xE0, 0xFF, 0x90, 0x01, 0x1B, 0xE0, 0x33, 0xFE, 0x74,
0x56, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0, 0xFF, 0x90, 0x01, 0x76, 0xE0, 0xFE,
0xEF, 0xB5, 0x06, 0x37, 0x90, 0x01, 0x16, 0x12, 0x04, 0xEE, 0x90, 0x00, 0x02, 0x74, 0xFF, 0x12,
0x02, 0x0F, 0xE4, 0x75, 0xF0, 0x02, 0x12, 0x03, 0x47, 0x90, 0x01, 0x1C, 0xE0, 0xFF, 0x90, 0x01,
0x16, 0x12, 0x04, 0xEE, 0x90, 0x00, 0x05, 0xEF, 0x12, 0x02, 0x0F, 0x90, 0x00, 0x13, 0xE4, 0xF5,
0xF0, 0x12, 0x03, 0x66, 0xE4, 0x90, 0x01, 0x52, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x1D, 0xE0, 0x60,
0x2C, 0x90, 0x01, 0x1C, 0xE0, 0x25, 0xE0, 0xFF, 0x90, 0x01, 0x1B, 0xE0, 0x33, 0xFE, 0x74, 0x55,
0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0, 0xFD, 0x90, 0x01, 0x75, 0xE0, 0xFC, 0xED,
0xC3, 0x9C, 0x40, 0x38, 0x74, 0x56, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x80, 0x2A, 0x90, 0x01, 0x1C,
0xE0, 0x25, 0xE0, 0xFF, 0x90, 0x01, 0x1B, 0xE0, 0x33, 0xFE, 0x74, 0x56, 0x2F, 0xF5, 0x82, 0x74,
0x01, 0x3E, 0xF5, 0x83, 0xE0, 0xFD, 0x90, 0x01, 0x76, 0xE0, 0xFC, 0xED, 0xC3, 0x9C, 0x40, 0x0C,
0x74, 0x55, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE4, 0xF0, 0x90, 0x01, 0x16, 0x12,
0x04, 0xEE, 0x12, 0x02, 0xE4, 0x45, 0xF0, 0x60, 0x13, 0x78, 0x59, 0x7C, 0x01, 0x7D, 0x01, 0x90,
0x01, 0x16, 0x12, 0x04, 0xEE, 0x7E, 0x00, 0x7F, 0x19, 0x12, 0x01, 0x6F, 0x90, 0x01, 0x1B, 0xE4,
0x75, 0xF0, 0x01, 0x12, 0x02, 0xCE, 0x02, 0x13, 0xF8, 0x22, 0x90, 0x01, 0x1A, 0x12, 0x05, 0x0E,
0xD2, 0xD8, 0x7B, 0x01, 0x7A, 0x01, 0x79, 0x1E, 0x7D, 0x11, 0x12, 0x11, 0x53, 0xD2, 0xD8, 0x7B,
0x01, 0x7A, 0x01, 0x79, 0x20, 0x7D, 0x11, 0x12, 0x11, 0x53, 0xD2, 0xD8, 0x7B, 0x01, 0x7A, 0x01,
0x79, 0x22, 0x7D, 0x11, 0x12, 0x11, 0x53, 0xE4, 0x90, 0x01, 0x1D, 0xF0, 0xD2, 0xD8, 0x90, 0x01,
0x1D, 0xE0, 0xFF, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x74, 0x1E, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C,
0xF5, 0x83, 0xE0, 0xFB, 0x90, 0x01, 0x24, 0xE4, 0xF0, 0xA3, 0xEB, 0xF0, 0x74, 0x20, 0x2D, 0xF5,
0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83, 0xE0, 0xFD, 0x90, 0x01, 0x24, 0xE4, 0x8D, 0xF0, 0x12, 0x02,
0xCE, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x74, 0x22, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83,
0xE0, 0xFF, 0x90, 0x01, 0x24, 0xE4, 0x8F, 0xF0, 0x12, 0x02, 0xCE, 0x90, 0x01, 0x24, 0xE0, 0xFE,
0xA3, 0xE0, 0xFF, 0x7C, 0x00, 0x7D, 0x03, 0x12, 0x02, 0x43, 0x90, 0x01, 0x1A, 0x12, 0x04, 0xEE,
0x90, 0x01, 0x1D, 0xE0, 0xFD, 0x33, 0x95, 0xE0, 0x8D, 0x82, 0xF5, 0x83, 0xEF, 0x12, 0x02, 0x0F,
0x90, 0x01, 0x1D, 0xE0, 0x04, 0xF0, 0xE0, 0x64, 0x02, 0x70, 0x81, 0xD2, 0xD8, 0xE4, 0x90, 0x01,
0x1D, 0xF0, 0x90, 0x01, 0x1D, 0xE0, 0xFF, 0xC3, 0x64, 0x80, 0x94, 0x82, 0x50, 0x4B, 0x90, 0x01,
0x1A, 0x12, 0x04, 0xEE, 0xEF, 0x33, 0x95, 0xE0, 0x8F, 0x82, 0xF5, 0x83, 0x12, 0x01, 0xD0, 0xFF,
0x90, 0x00, 0xC8, 0xE0, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x90, 0x01, 0x1D, 0xE0, 0xFB, 0x33, 0x95,
0xE0, 0xFA, 0x90, 0x00, 0xCD, 0x75, 0xF0, 0x03, 0xEB, 0x12, 0x04, 0xE2, 0xEA, 0x75, 0xF0, 0x03,
0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE5, 0x82, 0x2D, 0xF5, 0x82, 0xE5, 0x83, 0x3C, 0xF5, 0x83, 0xEF,
0xF0, 0x90, 0x01, 0x1D, 0xE0, 0x04, 0xF0, 0x80, 0xA9, 0x90, 0x00, 0xC8, 0xE0, 0x24, 0x04, 0xFF,
0x75, 0xF0, 0x03, 0x12, 0x01, 0x95, 0xAF, 0xF0, 0x90, 0x00, 0xC8, 0xEF, 0xF0, 0xE4, 0x90, 0x01,
0x1D, 0xF0, 0xD2, 0xD8, 0xE4, 0xFF, 0xEF, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x90, 0x01, 0x1D, 0xE0,
0xFB, 0x33, 0x95, 0xE0, 0xFA, 0x90, 0x00, 0xCD, 0x75, 0xF0, 0x03, 0xEB, 0x12, 0x04, 0xE2, 0xEA,
0x75, 0xF0, 0x03, 0xA4, 0x25, 0x83, 0xF5, 0x83, 0xE5, 0x82, 0x2D, 0xF5, 0x82, 0xE5, 0x83, 0x3C,
0xF5, 0x83, 0xE0, 0xFE, 0xEF, 0x33, 0x95, 0xE0, 0xFC, 0x74, 0x26, 0x2D, 0xF5, 0x82, 0x74, 0x01,
0x3C, 0xF5, 0x83, 0xEE, 0xF0, 0x0F, 0xEF, 0xB4, 0x03, 0xBC, 0xD2, 0xD8, 0xE4, 0xFF, 0xEF, 0x04,
0xFE, 0xC3, 0xEE, 0x64, 0x80, 0x94, 0x83, 0x50, 0x66, 0xEE, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x74,
0x26, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83, 0xE0, 0xFD, 0xEF, 0xFB, 0x33, 0x95, 0xE0,
0xFA, 0x74, 0x26, 0x2B, 0xF5, 0x82, 0x74, 0x01, 0x3A, 0xF5, 0x83, 0xE0, 0xC3, 0x9D, 0x50, 0x3C,
0x74, 0x26, 0x2B, 0xF5, 0x82, 0x74, 0x01, 0x3A, 0xF5, 0x83, 0xE0, 0xF9, 0xEE, 0xFD, 0x33, 0x95,
0xE0, 0xFC, 0x74, 0x26, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83, 0xE0, 0xFD, 0x74, 0x26,
0x2B, 0xF5, 0x82, 0x74, 0x01, 0x3A, 0xF5, 0x83, 0xED, 0xF0, 0xEE, 0xFB, 0x33, 0x95, 0xE0, 0xFA,
0x74, 0x26, 0x2B, 0xF5, 0x82, 0x74, 0x01, 0x3A, 0xF5, 0x83, 0xE9, 0xF0, 0x0E, 0x80, 0x92, 0x0F,
0xEF, 0x64, 0x02, 0x70, 0x89, 0x90, 0x01, 0x27, 0xE0, 0xFF, 0x90, 0x01, 0x1A, 0x12, 0x04, 0xEE,
0x90, 0x01, 0x1D, 0xE0, 0xFD, 0x33, 0x95, 0xE0, 0x8D, 0x82, 0xF5, 0x83, 0xEF, 0x12, 0x02, 0x0F,
0x90, 0x01, 0x1D, 0xE0, 0x04, 0xF0, 0xE0, 0x64, 0x02, 0x60, 0x03, 0x02, 0x17, 0x72, 0x22, 0xC0,
0xE0, 0xC0, 0xF0, 0xC0, 0x83, 0xC0, 0x82, 0xC0, 0xD0, 0x75, 0xD0, 0x00, 0xC0, 0x00, 0xC0, 0x01,
0xC0, 0x02, 0xC0, 0x03, 0xC0, 0x04, 0xC0, 0x05, 0xC0, 0x06, 0xC0, 0x07, 0xC2, 0xAF, 0x53, 0xE8,
0xDF, 0xC2, 0xB7, 0x7B, 0x01, 0x7A, 0x01, 0x79, 0x8B, 0x90, 0x01, 0x9D, 0x12, 0x05, 0x0E, 0x90,
0x00, 0xF1, 0x74, 0x01, 0xF0, 0xD2, 0xD8, 0x20, 0xB3, 0x03, 0x02, 0x19, 0x23, 0x30, 0xB5, 0x03,
0x02, 0x19, 0x23, 0x30, 0xB4, 0x5C, 0x90, 0x01, 0x9A, 0xE0, 0xB4, 0x05, 0x07, 0x90, 0x01, 0xA3,
0xE4, 0xF0, 0x80, 0x2F, 0x90, 0x01, 0x9A, 0xE0, 0xB4, 0x06, 0x08, 0x90, 0x01, 0xA3, 0x74, 0x01,
0xF0, 0x80, 0x20, 0x90, 0x01, 0x9A, 0xE0, 0xB4, 0x07, 0x08, 0x90, 0x01, 0xA3, 0x74, 0x02, 0xF0,
0x80, 0x11, 0x90, 0x01, 0x9A, 0xE0, 0x90, 0x01, 0xA3, 0xB4, 0x08, 0x05, 0x74, 0x03, 0xF0, 0x80,
0x02, 0xE4, 0xF0, 0x90, 0x01, 0x9D, 0x12, 0x04, 0xEE, 0x90, 0x01, 0xA3, 0xE0, 0xF5, 0x82, 0x75,
0x83, 0x00, 0x12, 0x01, 0xD0, 0xF5, 0xB4, 0x43, 0xB1, 0x20, 0x90, 0x01, 0x99, 0x74, 0x03, 0xF0,
0x80, 0x72, 0x90, 0x01, 0xA4, 0xE4, 0xF0, 0x90, 0x01, 0x9A, 0xF0, 0xA3, 0xF0, 0xA3, 0xF0, 0x7B,
0x01, 0x7A, 0x01, 0x79, 0x9A, 0x90, 0x01, 0xA0, 0x12, 0x05, 0x0E, 0x90, 0x01, 0x99, 0x74, 0x02,
0xF0, 0x80, 0x51, 0x90, 0x01, 0x99, 0xE0, 0xFF, 0xB4, 0x03, 0x22, 0x20, 0xB5, 0x1A, 0x90, 0x01,
0xA3, 0xE0, 0x04, 0xF0, 0x90, 0x01, 0x9D, 0x12, 0x04, 0xEE, 0x90, 0x01, 0xA3, 0xE0, 0xF5, 0x82,
0x75, 0x83, 0x00, 0x12, 0x01, 0xD0, 0xF5, 0xB4, 0x43, 0xB1, 0x20, 0x80, 0x27, 0xEF, 0xB4, 0x02,
0x23, 0x43, 0xB1, 0x20, 0x20, 0xB3, 0x1D, 0x20, 0xB5, 0x1A, 0x90, 0x01, 0xA0, 0x12, 0x04, 0xEE,
0x90, 0x01, 0xA4, 0xE0, 0xF5, 0x82, 0x75, 0x83, 0x00, 0xE5, 0xB4, 0x12, 0x02, 0x0F, 0x90, 0x01,
0xA4, 0xE0, 0x04, 0xF0, 0x43, 0xB1, 0x20, 0x90, 0x01, 0x99, 0xE0, 0x64, 0x02, 0x70, 0x22, 0x90,
0x01, 0x98, 0xE0, 0x60, 0x13, 0x30, 0xB2, 0x10, 0x7B, 0x01, 0x7A, 0x01, 0x79, 0x9A, 0x90, 0x01,
0xA4, 0xE0, 0xFD, 0x12, 0x26, 0x1D, 0x80, 0x09, 0x7B, 0x01, 0x7A, 0x01, 0x79, 0x9A, 0x12, 0x1C,
0x6D, 0x43, 0x9E, 0x04, 0x43, 0xE8, 0x20, 0xD2, 0xAF, 0xD0, 0x07, 0xD0, 0x06, 0xD0, 0x05, 0xD0,
0x04, 0xD0, 0x03, 0xD0, 0x02, 0xD0, 0x01, 0xD0, 0x00, 0xD0, 0xD0, 0xD0, 0x82, 0xD0, 0x83, 0xD0,
0xF0, 0xD0, 0xE0, 0x32, 0x90, 0x01, 0x1A, 0x12, 0x05, 0x0E, 0x74, 0xFF, 0x90, 0x01, 0x28, 0xF0,
0xA3, 0xF0, 0xE4, 0x90, 0x01, 0x2E, 0xF0, 0x90, 0x01, 0x26, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x26,
0xE0, 0xFE, 0xA3, 0xE0, 0xFF, 0xC3, 0x94, 0x02, 0xEE, 0x64, 0x80, 0x94, 0x80, 0x50, 0x29, 0x90,
0x01, 0x20, 0x12, 0x04, 0xEE, 0x8F, 0x82, 0x8E, 0x83, 0x12, 0x01, 0xD0, 0xFF, 0x90, 0x01, 0x27,
0xE0, 0x24, 0x2F, 0xF5, 0x82, 0xE4, 0x34, 0x01, 0xF5, 0x83, 0xEF, 0xF0, 0x90, 0x01, 0x26, 0xE4,
0x75, 0xF0, 0x01, 0x12, 0x02, 0xCE, 0x80, 0xC5, 0xE4, 0x90, 0x01, 0x2C, 0xF0, 0xA3, 0xF0, 0x90,
0x01, 0x2A, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x23, 0x12, 0x04, 0xEE, 0x90, 0x00, 0x13, 0x12, 0x03,
0x0F, 0xFF, 0x90, 0x01, 0x20, 0x12, 0x04, 0xEE, 0x8F, 0x82, 0x85, 0xF0, 0x83, 0x12, 0x01, 0xD0,
0xFF, 0x90, 0x01, 0x88, 0xE0, 0xFD, 0x90, 0x01, 0xDF, 0xE0, 0x2D, 0xFD, 0x90, 0x01, 0xDE, 0xE0,
0x34, 0x00, 0xFC, 0xD3, 0xEF, 0x9D, 0xE4, 0x9C, 0x40, 0x21, 0x90, 0x01, 0x23, 0x12, 0x04, 0xEE,
0x90, 0x00, 0x13, 0x12, 0x03, 0x0F, 0xFF, 0xAE, 0xF0, 0xF4, 0x70, 0x02, 0xEE, 0xF4, 0x60, 0x0B,
0x90, 0x01, 0x28, 0xEE, 0xF0, 0xA3, 0xEF, 0xF0, 0x02, 0x1A, 0xFD, 0xE4, 0x90, 0x01, 0x26, 0xF0,
0xA3, 0xF0, 0x90, 0x01, 0x27, 0xE0, 0x24, 0x2F, 0xF5, 0x82, 0xE4, 0x34, 0x01, 0xF5, 0x83, 0xE0,
0xFF, 0x7E, 0x00, 0x90, 0x01, 0x2A, 0xEE, 0x8F, 0xF0, 0x12, 0x02, 0xCE, 0xC3, 0x90, 0x01, 0x2D,
0xE0, 0x9F, 0x90, 0x01, 0x2C, 0xE0, 0x9E, 0x50, 0x12, 0xEE, 0xF0, 0xA3, 0xEF, 0xF0, 0x90, 0x01,
0x26, 0xE0, 0xFF, 0xA3, 0xE0, 0xA3, 0xCF, 0xF0, 0xA3, 0xEF, 0xF0, 0x90, 0x01, 0x26, 0xE4, 0x75,
0xF0, 0x01, 0x12, 0x02, 0xCE, 0x90, 0x01, 0x26, 0xE0, 0x70, 0x04, 0xA3, 0xE0, 0x64, 0x02, 0x70,
0xB1, 0x90, 0x01, 0x88, 0xE0, 0xFF, 0x90, 0x01, 0xDF, 0xE0, 0x2F, 0xFF, 0x90, 0x01, 0xDE, 0xE0,
0x34, 0x00, 0xFE, 0xC3, 0x90, 0x01, 0x2D, 0xE0, 0x9F, 0x90, 0x01, 0x2C, 0xE0, 0x9E, 0x50, 0x0D,
0x74, 0xFF, 0x90, 0x01, 0x28, 0xF0, 0xA3, 0xF0, 0xE4, 0xA3, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x28,
0xE0, 0xFE, 0xA3, 0xE0, 0xFF, 0x90, 0x01, 0x1A, 0x12, 0x04, 0xEE, 0xEE, 0x8F, 0xF0, 0x12, 0x03,
0x47, 0x90, 0x01, 0x2A, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF, 0x90, 0x01, 0x1D, 0x12, 0x04, 0xEE, 0xEE,
0x8F, 0xF0, 0x02, 0x03, 0x47, 0x4D, 0x01, 0x8B, 0x00, 0x09, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x01, 0x98, 0x00, 0x41, 0x01, 0x88, 0x00, 0x41, 0x01, 0x89,
0x00, 0x41, 0x01, 0x8A, 0x01, 0x41, 0x01, 0x99, 0x00, 0x41, 0x01, 0xA3, 0x00, 0x41, 0x01, 0xA4,
0x00, 0x43, 0x01, 0x9A, 0x00, 0x00, 0x00, 0x41, 0x01, 0xC2, 0x02, 0x41, 0x01, 0xC3, 0x02, 0x41,
0x01, 0xC4, 0x01, 0x41, 0x01, 0xC5, 0x01, 0x42, 0x01, 0xBF, 0x00, 0x00, 0x41, 0x01, 0xC1, 0x00,
0x41, 0x01, 0xDA, 0x00, 0x41, 0x01, 0xD8, 0xFF, 0x41, 0x01, 0xD9, 0xFF, 0x42, 0x01, 0x4F, 0xFF,
0xFF, 0x59, 0x01, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x01, 0x51,
0x00, 0x41, 0x01, 0x33, 0x00, 0x41, 0x01, 0x32, 0x01, 0x41, 0x01, 0x31, 0x0F, 0x44, 0x01, 0x55,
0x00, 0x00, 0x00, 0x00, 0x41, 0x01, 0x54, 0x32, 0x41, 0x00, 0xC8, 0x00, 0x41, 0x00, 0xD4, 0x01,
0x41, 0x00, 0xF1, 0x00, 0x44, 0x00, 0xED, 0x01, 0x00, 0x00, 0x02, 0x54, 0x00, 0xD5, 0x00, 0x02,
0x1C, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x01, 0x40, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x41, 0x01, 0x72, 0x00, 0x41, 0x01, 0x85, 0x00, 0x44, 0x01, 0x81, 0x00, 0x01, 0x00,
0x02, 0x4E, 0x01, 0x73, 0x01, 0x01, 0x05, 0x04, 0x0C, 0x25, 0x25, 0x25, 0x02, 0x02, 0x02, 0x02,
0x25, 0x25, 0x02, 0x33, 0x00, 0x01, 0x02, 0x35, 0x04, 0x07, 0x42, 0x01, 0xA9, 0x05, 0x06, 0x42,
0x01, 0xAB, 0x0B, 0x0F, 0x42, 0x01, 0xA7, 0x32, 0x32, 0x42, 0x01, 0xA5, 0x0C, 0x0C, 0x42, 0x01,
0xAD, 0x0A, 0x0A, 0x42, 0x01, 0xDE, 0x00, 0x14, 0x60, 0x36, 0x00, 0x00, 0x04, 0x08, 0x00, 0x00,
0x08, 0x02, 0x02, 0x08, 0x10, 0xEA, 0x08, 0x11, 0xEC, 0x08, 0x12, 0xA2, 0x08, 0x13, 0xEE, 0x08,
0x14, 0xA3, 0x08, 0x15, 0xF4, 0x08, 0x16, 0xA2, 0x08, 0x17, 0xF6, 0x08, 0x18, 0xA0, 0x08, 0x19,
0xF8, 0x08, 0x1A, 0xA8, 0x08, 0x1B, 0xFA, 0x08, 0x1C, 0xA8, 0x08, 0x1D, 0xFC, 0x08, 0x1E, 0xA8,
0x08, 0x1F, 0x42, 0x01, 0xD6, 0xCD, 0xC4, 0x42, 0x01, 0xD4, 0xAB, 0xAB, 0x00, 0x90, 0x01, 0x06,
0x12, 0x05, 0x0E, 0x12, 0x01, 0xB7, 0x90, 0x01, 0x09, 0xF0, 0x12, 0x05, 0x17, 0x1C, 0xC9, 0x01,
0x1C, 0xD4, 0x02, 0x1D, 0x2E, 0x03, 0x1D, 0x32, 0x04, 0x1D, 0x37, 0x07, 0x1D, 0x69, 0x0A, 0x1D,
0x6C, 0x0B, 0x1D, 0x70, 0x0C, 0x1C, 0xE0, 0x12, 0x1C, 0xF8, 0x13, 0x1D, 0x10, 0x14, 0x1D, 0x3E,
0x15, 0x1D, 0x52, 0x16, 0x1D, 0x7E, 0x55, 0x1D, 0x74, 0xA0, 0x1D, 0x74, 0xA1, 0x1D, 0x74, 0xA2,
0x1D, 0x74, 0xA3, 0x1D, 0x74, 0xA4, 0x1D, 0x74, 0xA5, 0x1D, 0x74, 0xA6, 0x1D, 0x74, 0xA7, 0x1D,
0x74, 0xA8, 0x1D, 0x74, 0xA9, 0x00, 0x00, 0x1D, 0x8A, 0x7F, 0x01, 0x12, 0x2C, 0xD4, 0xE4, 0x90,
0x01, 0x8A, 0xF0, 0x22, 0xE4, 0xFF, 0x12, 0x2C, 0xD4, 0x90, 0x01, 0x8A, 0x74, 0x01, 0xF0, 0x22,
0x90, 0x01, 0x31, 0xE0, 0xC3, 0x94, 0x0F, 0x40, 0x03, 0x02, 0x1D, 0x8A, 0x7F, 0x14, 0x12, 0x2C,
0xD4, 0x90, 0x01, 0x31, 0xE0, 0x04, 0xF0, 0x22, 0x90, 0x01, 0x31, 0xE0, 0xD3, 0x94, 0x00, 0x50,
0x03, 0x02, 0x1D, 0x8A, 0x7F, 0x14, 0x12, 0x2C, 0xD4, 0x90, 0x01, 0x31, 0xE0, 0x14, 0xF0, 0x22,
0x90, 0x01, 0x06, 0x12, 0x04, 0xEE, 0x90, 0x00, 0x01, 0x12, 0x01, 0xD0, 0x90, 0x01, 0x31, 0xF0,
0xD3, 0x94, 0x00, 0x40, 0x65, 0xE0, 0x94, 0x0F, 0x50, 0x60, 0x7F, 0x14, 0x80, 0x06, 0x7F, 0x04,
0x80, 0x02, 0x7F, 0x08, 0x02, 0x2C, 0xD4, 0x90, 0x01, 0x54, 0x74, 0xFF, 0xF0, 0x22, 0x90, 0x01,
0x06, 0x12, 0x04, 0xEE, 0x90, 0x00, 0x01, 0x12, 0x01, 0xD0, 0x90, 0x01, 0x88, 0xF0, 0x7F, 0x05,
0x80, 0x07, 0xE4, 0x90, 0x01, 0x88, 0xF0, 0x7F, 0x03, 0x12, 0x2C, 0x8A, 0x12, 0x2B, 0x14, 0xEF,
0x25, 0xE0, 0xFF, 0x90, 0x01, 0x97, 0xEF, 0xF0, 0x22, 0xE4, 0x80, 0x0E, 0x7F, 0x02, 0x80, 0x0B,
0x7F, 0x04, 0x80, 0x07, 0x90, 0x01, 0x09, 0xE0, 0x24, 0x60, 0xFF, 0x02, 0x00, 0x6E, 0x90, 0x01,
0x98, 0x74, 0x01, 0xF0, 0x90, 0x01, 0x8B, 0x74, 0xAA, 0xF0, 0x22, 0x90, 0x01, 0x1A, 0x12, 0x05,
0x0E, 0xE4, 0x90, 0x01, 0x1D, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x1D, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF,
0xC3, 0x94, 0x02, 0xEE, 0x64, 0x80, 0x94, 0x80, 0x50, 0x76, 0x90, 0x01, 0x1A, 0x12, 0x04, 0xEE,
0x8F, 0x82, 0x8E, 0x83, 0x12, 0x01, 0xD0, 0xFF, 0x90, 0x01, 0x1E, 0xE0, 0xF9, 0x24, 0xC9, 0xF5,
0x82, 0xE4, 0x34, 0x00, 0xF5, 0x83, 0xE0, 0xFD, 0xC3, 0xEF, 0x9D, 0xFD, 0xE4, 0x94, 0x00, 0xFC,
0x90, 0x01, 0x1E, 0xE0, 0x25, 0xE0, 0xFF, 0x90, 0x01, 0x1D, 0xE0, 0x33, 0xFE, 0x74, 0x1F, 0x2F,
0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xEC, 0xF0, 0xA3, 0xED, 0xF0, 0x74, 0x1F, 0x2F, 0xF5,
0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF, 0xC3, 0xEE, 0x64, 0x80, 0x94,
0x80, 0x50, 0x04, 0x7F, 0x00, 0x80, 0x00, 0x74, 0xCB, 0x29, 0xF5, 0x82, 0xE4, 0x34, 0x00, 0xF5,
0x83, 0xEF, 0xF0, 0x90, 0x01, 0x1D, 0xE4, 0x75, 0xF0, 0x01, 0x12, 0x02, 0xCE, 0x02, 0x1D, 0x98,
0xC2, 0xAF, 0xE4, 0x90, 0x01, 0x1D, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x1E, 0xE0, 0xFF, 0x24, 0xCB,
0xF5, 0x82, 0xE4, 0x34, 0x00, 0xF5, 0x83, 0xE0, 0x25, 0xE0, 0xFE, 0x74, 0x8E, 0x2F, 0xF5, 0x82,
0xE4, 0x34, 0x01, 0xF5, 0x83, 0xEE, 0xF0, 0x90, 0x01, 0x1E, 0xE0, 0xFF, 0x24, 0xC9, 0xF5, 0x82,
0xE4, 0x34, 0x00, 0xF5, 0x83, 0xE0, 0xFE, 0x74, 0x95, 0x2F, 0xF5, 0x82, 0xE4, 0x34, 0x01, 0xF5,
0x83, 0xEE, 0xF0, 0x90, 0x01, 0x1D, 0xE4, 0x75, 0xF0, 0x01, 0x12, 0x02, 0xCE, 0x90, 0x01, 0x1D,
0xE0, 0x70, 0x04, 0xA3, 0xE0, 0x64, 0x02, 0x70, 0xB0, 0xD2, 0xAF, 0x22, 0x8D, 0x32, 0xEF, 0xFD,
0x33, 0x95, 0xE0, 0xFC, 0x74, 0xA5, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83, 0xE0, 0xC4,
0x54, 0xF0, 0x44, 0x0F, 0x90, 0x08, 0x02, 0xF0, 0x74, 0xAD, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C,
0xF5, 0x83, 0xE0, 0xFE, 0xC3, 0x74, 0xF4, 0x9E, 0x90, 0x08, 0x14, 0xF0, 0xE0, 0x14, 0x90, 0x08,
0x12, 0xF0, 0x74, 0x35, 0x2F, 0xF8, 0xE6, 0xC4, 0x54, 0xF0, 0x90, 0x08, 0x00, 0xF0, 0xE0, 0x44,
0x0A, 0xF0, 0xE4, 0x90, 0x00, 0xF1, 0xF0, 0x90, 0x08, 0x03, 0x74, 0xFC, 0xF0, 0x90, 0x08, 0x00,
0xE0, 0x44, 0x01, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x08, 0x03, 0x74, 0xFE, 0xF0,
0x90, 0x08, 0x00, 0xE0, 0x20, 0xE0, 0xF9, 0x90, 0x00, 0xF1, 0xE0, 0x70, 0x95, 0x90, 0x08, 0x00,
0xE0, 0x54, 0xF7, 0xF0, 0xA3, 0xE0, 0xFF, 0x22, 0x90, 0x00, 0xF4, 0xE0, 0xFF, 0xC4, 0x13, 0x13,
0x13, 0x54, 0x01, 0x30, 0xE0, 0x13, 0x90, 0x00, 0x02, 0x12, 0x01, 0xD0, 0xFE, 0xF4, 0x60, 0x09,
0xEE, 0x60, 0x06, 0x90, 0x01, 0x85, 0x74, 0x01, 0xF0, 0xEF, 0x13, 0x13, 0x54, 0x3F, 0x30, 0xE0,
0x63, 0x90, 0x01, 0x85, 0xE0, 0x70, 0x5D, 0x90, 0x00, 0x05, 0x12, 0x01, 0xD0, 0xFF, 0xC3, 0x64,
0x80, 0x94, 0x84, 0x50, 0x4F, 0x12, 0x02, 0xE4, 0x30, 0xE1, 0x1D, 0xEF, 0x33, 0x95, 0xE0, 0xFE,
0xEF, 0x25, 0xE0, 0xFF, 0xEE, 0x33, 0xFE, 0x74, 0x81, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5,
0x83, 0xA3, 0xE0, 0xFF, 0x7D, 0x02, 0x80, 0x27, 0x12, 0x02, 0xE4, 0x30, 0xE0, 0x26, 0x90, 0x00,
0x05, 0x12, 0x01, 0xD0, 0xFF, 0x33, 0x95, 0xE0, 0xFE, 0xEF, 0x25, 0xE0, 0xFF, 0xEE, 0x33, 0xFE,
0x74, 0x81, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xA3, 0xE0, 0xFF, 0x7D, 0x01, 0x7C,
0x00, 0x12, 0x2A, 0xF6, 0x90, 0x00, 0x02, 0x12, 0x01, 0xD0, 0xB4, 0xFF, 0x12, 0x90, 0x00, 0xF4,
0xE0, 0xC4, 0x13, 0x13, 0x13, 0x54, 0x01, 0x20, 0xE0, 0x05, 0xE4, 0x90, 0x01, 0x85, 0xF0, 0x22,
0x90, 0x01, 0x12, 0xEC, 0xF0, 0xA3, 0xED, 0xF0, 0xE4, 0xF5, 0xF0, 0x12, 0x03, 0x47, 0x90, 0x00,
0x13, 0xEC, 0x8D, 0xF0, 0x12, 0x03, 0x66, 0xBC, 0xFF, 0x07, 0xBD, 0xFF, 0x04, 0x7F, 0xFF, 0x80,
0x09, 0x90, 0x01, 0x13, 0xE0, 0x24, 0x33, 0xF8, 0xE6, 0xFF, 0x90, 0x00, 0x05, 0xEF, 0x12, 0x02,
0x0F, 0x90, 0x01, 0x14, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF, 0x90, 0x00, 0x11, 0xEE, 0x8F, 0xF0, 0x12,
0x03, 0x66, 0x90, 0x00, 0x02, 0x74, 0xFF, 0x12, 0x02, 0x0F, 0x90, 0x00, 0x06, 0xE4, 0xF5, 0xF0,
0x12, 0x03, 0x66, 0x90, 0x00, 0x08, 0xE4, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x00, 0x0A, 0xE4,
0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x00, 0x0E, 0xE4, 0x12, 0x02, 0x0F, 0x90, 0x00, 0x0F, 0xE4,
0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x00, 0x0C, 0x74, 0xFF, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90,
0x00, 0x17, 0xE4, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x01, 0x54, 0xE0, 0xFD, 0xC3, 0xEF, 0x9D,
0xEE, 0x94, 0x00, 0x50, 0x0B, 0x90, 0x01, 0x12, 0xE0, 0xFC, 0xA3, 0xE0, 0xFD, 0x12, 0x13, 0xE5,
0x22, 0x90, 0x01, 0x0F, 0x12, 0x05, 0x0E, 0xE4, 0x90, 0x01, 0x19, 0xF0, 0x7B, 0x01, 0x7A, 0x00,
0x79, 0x6C, 0x12, 0x16, 0x4A, 0x90, 0x00, 0xD3, 0xE0, 0x24, 0x29, 0x75, 0xF0, 0x28, 0x84, 0xE5,
0xF0, 0xF0, 0xE4, 0x90, 0x01, 0x18, 0xF0, 0x90, 0x01, 0x18, 0xE0, 0xFF, 0xC3, 0x64, 0x80, 0x94,
0x82, 0x50, 0x16, 0x7B, 0x01, 0x7A, 0x00, 0x79, 0x6C, 0x12, 0x05, 0x3D, 0x90, 0x01, 0x19, 0xEF,
0xF0, 0x90, 0x01, 0x18, 0xE0, 0x04, 0xF0, 0x80, 0xDE, 0x7B, 0x01, 0x7A, 0x00, 0x79, 0x6C, 0x12,
0x1D, 0x8B, 0x90, 0x01, 0x19, 0xE0, 0x60, 0x2D, 0x90, 0x01, 0x12, 0x12, 0x04, 0xEE, 0x90, 0x01,
0x1D, 0x12, 0x05, 0x0E, 0x7B, 0x01, 0x7A, 0x00, 0x79, 0xCB, 0x90, 0x01, 0x20, 0x12, 0x05, 0x0E,
0x90, 0x01, 0x15, 0x12, 0x04, 0xEE, 0x90, 0x01, 0x23, 0x12, 0x05, 0x0E, 0x90, 0x01, 0x0F, 0x12,
0x04, 0xEE, 0x02, 0x19, 0xC4, 0x7B, 0x00, 0x7A, 0xFF, 0x79, 0xFF, 0x90, 0x01, 0x0F, 0x12, 0x05,
0x0E, 0x7A, 0x00, 0x79, 0x00, 0x90, 0x01, 0x12, 0x12, 0x05, 0x0E, 0x22, 0xED, 0x64, 0x80, 0x4C,
0x70, 0x03, 0x8F, 0x80, 0x22, 0xED, 0x64, 0x90, 0x4C, 0x70, 0x03, 0x8F, 0x90, 0x22, 0xED, 0x64,
0x95, 0x4C, 0x70, 0x03, 0x8F, 0x95, 0x22, 0xED, 0x64, 0x96, 0x4C, 0x70, 0x03, 0x8F, 0x96, 0x22,
0xED, 0x64, 0x9D, 0x4C, 0x70, 0x03, 0x8F, 0x9D, 0x22, 0xED, 0x64, 0x9E, 0x4C, 0x70, 0x03, 0x8F,
0x9E, 0x22, 0xED, 0x64, 0xA5, 0x4C, 0x70, 0x03, 0x8F, 0xA5, 0x22, 0xED, 0x64, 0xA6, 0x4C, 0x70,
0x03, 0x8F, 0xA6, 0x22, 0xED, 0x64, 0xD2, 0x4C, 0x70, 0x03, 0x8F, 0xD2, 0x22, 0xED, 0x64, 0xD4,
0x4C, 0x70, 0x03, 0x8F, 0xD4, 0x22, 0xED, 0x64, 0xD6, 0x4C, 0x70, 0x03, 0x8F, 0xD6, 0x22, 0xED,
0x64, 0xDC, 0x4C, 0x70, 0x03, 0x8F, 0xDC, 0x22, 0xED, 0x64, 0xDD, 0x4C, 0x70, 0x03, 0x8F, 0xDD,
0x22, 0xED, 0x64, 0xDE, 0x4C, 0x70, 0x03, 0x8F, 0xDE, 0x22, 0xED, 0x64, 0xDF, 0x4C, 0x70, 0x03,
0x8F, 0xDF, 0x22, 0xC3, 0xED, 0x94, 0xF9, 0xEC, 0x94, 0x00, 0x40, 0x06, 0x8D, 0x82, 0x8C, 0x83,
0xEF, 0xF0, 0x22, 0x12, 0x2C, 0xE0, 0x90, 0x01, 0xE0, 0xEF, 0xF0, 0x12, 0x2C, 0xDA, 0xEF, 0x60,
0x5F, 0x90, 0x01, 0xC1, 0xE0, 0x70, 0x0B, 0x90, 0x01, 0xBF, 0xF0, 0xA3, 0xF0, 0xA3, 0x04, 0xF0,
0x80, 0x4E, 0x90, 0x01, 0xBF, 0xE4, 0x75, 0xF0, 0x01, 0x12, 0x02, 0xCE, 0xD3, 0x90, 0x01, 0xC0,
0xE0, 0x94, 0x0C, 0x90, 0x01, 0xBF, 0xE0, 0x94, 0x00, 0x40, 0x35, 0xE4, 0xF0, 0xA3, 0xF0, 0xA3,
0xF0, 0x90, 0x01, 0xE0, 0xE0, 0x70, 0x04, 0x7F, 0x04, 0x80, 0x1F, 0x90, 0x01, 0xE0, 0xE0, 0xB4,
0x01, 0x04, 0x7F, 0x08, 0x80, 0x14, 0x90, 0x01, 0xE0, 0xE0, 0xB4, 0x02, 0x04, 0x7F, 0x0C, 0x80,
0x09, 0x90, 0x01, 0xE0, 0xE0, 0xB4, 0x03, 0x05, 0x7F, 0x10, 0x12, 0x2C, 0xD4, 0x12, 0x2C, 0x5D,
0x90, 0x01, 0xC4, 0xE0, 0x60, 0x1D, 0x90, 0x01, 0xC2, 0xE0, 0x60, 0x04, 0xE0, 0xB4, 0x01, 0x09,
0xE4, 0xF5, 0x8A, 0xF5, 0x8C, 0xD2, 0x8C, 0x80, 0x0A, 0x90, 0x01, 0xC2, 0xE0, 0xB4, 0x03, 0x03,
0xE4, 0xF5, 0x8A, 0xD2, 0xD8, 0xC2, 0x8D, 0x22, 0x90, 0x01, 0x0D, 0xEE, 0xF0, 0xA3, 0xEF, 0xF0,
0xD3, 0x94, 0xF8, 0xEE, 0x94, 0x00, 0x50, 0x70, 0x90, 0x01, 0x0D, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF,
0xEE, 0x70, 0x62, 0xEF, 0x12, 0x05, 0x17, 0x22, 0x98, 0x80, 0x22, 0x9B, 0x90, 0x22, 0x9E, 0x95,
0x22, 0xA1, 0x96, 0x22, 0xA4, 0x9D, 0x22, 0xA7, 0x9E, 0x22, 0xAA, 0xA5, 0x22, 0xAD, 0xA6, 0x22,
0xB0, 0xD2, 0x22, 0xB3, 0xD4, 0x22, 0xB6, 0xD6, 0x22, 0xB9, 0xDC, 0x22, 0xBC, 0xDD, 0x22, 0xBF,
0xDE, 0x22, 0xC2, 0xDF, 0x00, 0x00, 0x22, 0xC5, 0xAF, 0x80, 0x22, 0xAF, 0x90, 0x22, 0xAF, 0x95,
0x22, 0xAF, 0x96, 0x22, 0xAF, 0x9D, 0x22, 0xAF, 0x9E, 0x22, 0xAF, 0xA5, 0x22, 0xAF, 0xA6, 0x22,
0xAF, 0xD2, 0x22, 0xAF, 0xD4, 0x22, 0xAF, 0xD6, 0x22, 0xAF, 0xDC, 0x22, 0xAF, 0xDD, 0x22, 0xAF,
0xDE, 0x22, 0xAF, 0xDF, 0x22, 0x7F, 0x00, 0x22, 0x90, 0x01, 0x0D, 0xE0, 0xFE, 0xA3, 0xE0, 0xF5,
0x82, 0x8E, 0x83, 0xE0, 0xFF, 0x22, 0x78, 0x7F, 0xE4, 0xF6, 0xD8, 0xFD, 0x75, 0x81, 0x36, 0x02,
0x23, 0x1D, 0x02, 0x2A, 0x69, 0xE4, 0x93, 0xA3, 0xF8, 0xE4, 0x93, 0xA3, 0x40, 0x03, 0xF6, 0x80,
0x01, 0xF2, 0x08, 0xDF, 0xF4, 0x80, 0x29, 0xE4, 0x93, 0xA3, 0xF8, 0x54, 0x07, 0x24, 0x0C, 0xC8,
0xC3, 0x33, 0xC4, 0x54, 0x0F, 0x44, 0x20, 0xC8, 0x83, 0x40, 0x04, 0xF4, 0x56, 0x80, 0x01, 0x46,
0xF6, 0xDF, 0xE4, 0x80, 0x0B, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x90, 0x1B, 0x25,
0xE4, 0x7E, 0x01, 0x93, 0x60, 0xBC, 0xA3, 0xFF, 0x54, 0x3F, 0x30, 0xE5, 0x09, 0x54, 0x1F, 0xFE,
0xE4, 0x93, 0xA3, 0x60, 0x01, 0x0E, 0xCF, 0x54, 0xC0, 0x25, 0xE0, 0x60, 0xA8, 0x40, 0xB8, 0xE4,
0x93, 0xA3, 0xFA, 0xE4, 0x93, 0xA3, 0xF8, 0xE4, 0x93, 0xA3, 0xC8, 0xC5, 0x82, 0xC8, 0xCA, 0xC5,
0x83, 0xCA, 0xF0, 0xA3, 0xC8, 0xC5, 0x82, 0xC8, 0xCA, 0xC5, 0x83, 0xCA, 0xDF, 0xE9, 0xDE, 0xE7,
0x80, 0xBE, 0x75, 0x80, 0xFF, 0x75, 0x85, 0x02, 0x75, 0x86, 0x03, 0x75, 0x87, 0x10, 0xE4, 0xF5,
0x88, 0xF5, 0x89, 0xF5, 0x8A, 0xF5, 0x8B, 0xF5, 0x8C, 0xF5, 0x8D, 0x75, 0x8E, 0xE0, 0x75, 0x8F,
0xFF, 0x75, 0x90, 0xFF, 0x75, 0x91, 0x01, 0x75, 0x95, 0xFF, 0x75, 0x96, 0xFF, 0xF5, 0x9C, 0x75,
0x9D, 0xFF, 0x75, 0x9E, 0xFF, 0x75, 0xA5, 0xFF, 0x75, 0xA6, 0xFF, 0xF5, 0xA8, 0xF5, 0xB0, 0x75,
0xB1, 0x20, 0xF5, 0xB2, 0xF5, 0xB3, 0xF5, 0xB4, 0xF5, 0xB5, 0xF5, 0xB7, 0xF5, 0xB8, 0x75, 0xC6,
0x0F, 0xF5, 0xC7, 0xF5, 0xC8, 0xF5, 0xC9, 0xF5, 0xCA, 0xF5, 0xCB, 0xF5, 0xCC, 0xF5, 0xCD, 0xF5,
0xD0, 0xF5, 0xD2, 0xF5, 0xD4, 0xF5, 0xD6, 0x75, 0xD8, 0x50, 0xF5, 0xDC, 0xF5, 0xDD, 0xF5, 0xDE,
0xF5, 0xDF, 0xF5, 0xE8, 0xF5, 0xEA, 0xF5, 0xEB, 0xF5, 0xEC, 0xF5, 0xED, 0xF5, 0xEE, 0xF5, 0xF4,
0xF5, 0xF3, 0xF5, 0xF2, 0xF5, 0xF7, 0xF5, 0xF8, 0x7F, 0x01, 0x22, 0x90, 0x01, 0x10, 0x12, 0x05,
0x0E, 0xE4, 0x90, 0x01, 0x13, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x13, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF,
0xC3, 0x94, 0x02, 0xEE, 0x64, 0x80, 0x94, 0x80, 0x50, 0x63, 0x90, 0x01, 0x78, 0xE0, 0xFD, 0x90,
0x01, 0x75, 0xE0, 0x2D, 0xFD, 0xE4, 0x33, 0xFC, 0xEF, 0x25, 0xE0, 0xFF, 0xEE, 0x33, 0xFE, 0x74,
0x55, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0, 0xC3, 0x9D, 0xEC, 0x64, 0x80, 0xF8,
0x74, 0x80, 0x98, 0x40, 0x2C, 0x90, 0x01, 0x10, 0x12, 0x04, 0xEE, 0x12, 0x02, 0xE4, 0x44, 0x02,
0xFF, 0xE5, 0xF0, 0x8F, 0xF0, 0x12, 0x03, 0x47, 0x90, 0x01, 0x10, 0x12, 0x04, 0xEE, 0x90, 0x00,
0x13, 0xE4, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x01, 0x14, 0xE0, 0x90, 0x00, 0x05, 0x12, 0x02,
0x0F, 0x90, 0x01, 0x13, 0xE4, 0x75, 0xF0, 0x01, 0x12, 0x02, 0xCE, 0x80, 0x8B, 0x22, 0x90, 0x01,
0x32, 0xE0, 0x60, 0x05, 0xE4, 0xF0, 0x12, 0x2A, 0x91, 0x90, 0x01, 0x98, 0xE0, 0x70, 0x5D, 0x7B,
0x01, 0x7A, 0x01, 0x79, 0x4D, 0x90, 0x01, 0x12, 0x12, 0x05, 0x0E, 0x7A, 0x01, 0x79, 0x34, 0x90,
0x01, 0x15, 0x12, 0x05, 0x0E, 0x7A, 0x01, 0x79, 0x4F, 0x12, 0x20, 0x81, 0x7B, 0x01, 0x7A, 0x01,
0x79, 0x34, 0x90, 0x01, 0x4F, 0xE0, 0xFC, 0xA3, 0xE0, 0xFD, 0x90, 0x01, 0x4D, 0xE0, 0xFF, 0xA3,
0xE0, 0x90, 0x01, 0x14, 0xCF, 0xF0, 0xA3, 0xEF, 0xF0, 0x12, 0x1F, 0xE0, 0x7B, 0x01, 0x7A, 0x01,
0x79, 0x34, 0x12, 0x1F, 0x38, 0x90, 0x01, 0x33, 0xE0, 0xFF, 0x90, 0x01, 0x51, 0xE0, 0x6F, 0x60,
0x0B, 0x90, 0x01, 0x33, 0xE0, 0x90, 0x01, 0x51, 0xF0, 0x12, 0x29, 0x54, 0x22, 0xAB, 0x07, 0xAA,
0x05, 0x74, 0x35, 0x2B, 0xF8, 0xE6, 0xFF, 0x74, 0x01, 0xA8, 0x07, 0x08, 0x80, 0x02, 0xC3, 0x33,
0xD8, 0xFC, 0xF9, 0xE4, 0xF5, 0x30, 0xF5, 0x31, 0xEA, 0xFF, 0xC3, 0xE5, 0x31, 0x9F, 0x74, 0x80,
0xF8, 0x65, 0x30, 0x98, 0x50, 0x1E, 0x12, 0x2C, 0xA6, 0xAF, 0x03, 0xAD, 0x01, 0x12, 0x1E, 0x7C,
0x74, 0x08, 0x25, 0x31, 0xF8, 0xA6, 0x07, 0x12, 0x2C, 0xAE, 0x05, 0x31, 0xE5, 0x31, 0x70, 0xD8,
0x05, 0x30, 0x80, 0xD4, 0x7C, 0x00, 0x78, 0x08, 0xE8, 0x2C, 0xF8, 0xF9, 0xE6, 0xFA, 0xEC, 0xFB,
0x0B, 0x08, 0xE6, 0x9A, 0x40, 0x0B, 0xE6, 0xCA, 0xF6, 0xE8, 0xFD, 0xE9, 0xF8, 0xEA, 0xF6, 0xED,
0xF8, 0x0B, 0xBB, 0x1B, 0xEC, 0x0C, 0xBC, 0x0E, 0xDD, 0xAF, 0x15, 0x22, 0xE4, 0xF5, 0xF0, 0x12,
0x03, 0x47, 0x90, 0x00, 0x06, 0xE4, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x00, 0x08, 0xE4, 0xF5,
0xF0, 0x12, 0x03, 0x66, 0x90, 0x00, 0x13, 0x74, 0xFF, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x00,
0x05, 0x74, 0xFF, 0x12, 0x02, 0x0F, 0x90, 0x00, 0x11, 0xE4, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90,
0x00, 0x0A, 0xE4, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x00, 0x0E, 0xE4, 0x12, 0x02, 0x0F, 0x90,
0x00, 0x0F, 0xE4, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x00, 0x0C, 0x74, 0xFF, 0xF5, 0xF0, 0x12,
0x03, 0x66, 0x90, 0x00, 0x17, 0xE4, 0xF5, 0xF0, 0x12, 0x03, 0x66, 0x90, 0x00, 0x02, 0x74, 0xFF,
0x12, 0x02, 0x0F, 0x12, 0x23, 0xEB, 0x02, 0x26, 0x73, 0x90, 0x01, 0x31, 0xE0, 0xC4, 0x54, 0xF0,
0xFE, 0xE0, 0xFD, 0xEF, 0x12, 0x05, 0x17, 0x25, 0xF2, 0x00, 0x25, 0xFB, 0x01, 0x26, 0x02, 0x02,
0x26, 0x02, 0x03, 0x26, 0x02, 0x04, 0x26, 0x0A, 0x05, 0x26, 0x06, 0x06, 0x26, 0x06, 0x07, 0x26,
0x06, 0x08, 0x26, 0x0F, 0x09, 0x25, 0xFB, 0x12, 0x25, 0xF2, 0x13, 0x26, 0x14, 0x14, 0x00, 0x00,
0x26, 0x1C, 0xEE, 0xF4, 0x52, 0xDE, 0xED, 0xF4, 0x52, 0xDF, 0x22, 0xEE, 0x42, 0xDE, 0xED, 0x42,
0xDF, 0x22, 0xEE, 0x42, 0xDD, 0x22, 0xED, 0x42, 0xDE, 0x22, 0xEE, 0xF4, 0x52, 0xDD, 0x22, 0xED,
0xF4, 0x52, 0xDE, 0x22, 0xAF, 0x06, 0x8F, 0xDE, 0xAF, 0x05, 0x8F, 0xDF, 0x22, 0x90, 0x01, 0x06,
0x12, 0x05, 0x0E, 0x90, 0x01, 0x09, 0xED, 0xF0, 0xE4, 0xA3, 0xF0, 0xA3, 0xF0, 0xA3, 0xF0, 0x12,
0x02, 0xE4, 0xFF, 0x90, 0x01, 0x0B, 0xE5, 0xF0, 0xF0, 0xA3, 0xEF, 0xF0, 0xBD, 0x02, 0x02, 0x80,
0x21, 0x90, 0x01, 0x09, 0xE0, 0xB4, 0x03, 0x2A, 0x90, 0x01, 0x06, 0x12, 0x04, 0xEE, 0x90, 0x00,
0x02, 0x12, 0x01, 0xD0, 0xFF, 0x90, 0x01, 0x0A, 0xF0, 0xA3, 0xE0, 0xFC, 0xA3, 0xE0, 0xFD, 0x12,
0x21, 0x1C, 0x90, 0x01, 0x0B, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF, 0x12, 0x22, 0x48, 0x90, 0x01, 0x8B,
0xEF, 0xF0, 0x22, 0xE4, 0xFD, 0xFC, 0xED, 0x25, 0xE0, 0xFF, 0xEC, 0x33, 0xFE, 0x74, 0x55, 0x2F,
0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE4, 0xF0, 0x90, 0x01, 0x77, 0xE0, 0xFF, 0x90, 0x01,
0x76, 0xE0, 0x2F, 0xFB, 0xED, 0x25, 0xE0, 0xFF, 0xEC, 0x33, 0xFE, 0x74, 0x56, 0x2F, 0xF5, 0x82,
0x74, 0x01, 0x3E, 0xF5, 0x83, 0xEB, 0xF0, 0x0D, 0xBD, 0x00, 0x01, 0x0C, 0xED, 0x64, 0x02, 0x4C,
0x70, 0xC4, 0xE4, 0x90, 0x01, 0x52, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x59, 0xF0, 0xA3, 0xF0, 0x74,
0xFF, 0x90, 0x01, 0x6C, 0xF0, 0xA3, 0xF0, 0x22, 0x78, 0x11, 0x7C, 0x01, 0x7D, 0x01, 0x7B, 0xFF,
0x7A, 0x2C, 0x79, 0xF2, 0x7E, 0x00, 0x7F, 0x01, 0x12, 0x01, 0x6F, 0xE4, 0x90, 0x01, 0x10, 0xF0,
0x90, 0x01, 0x10, 0xE0, 0xFF, 0xC3, 0x64, 0x80, 0x94, 0x82, 0x50, 0x22, 0x7B, 0x01, 0x7A, 0x01,
0x79, 0x11, 0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x74, 0xA9, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5,
0x83, 0xE0, 0xFD, 0x12, 0x29, 0x86, 0x90, 0x01, 0x10, 0xE0, 0x04, 0xF0, 0x80, 0xD2, 0x90, 0x01,
0x11, 0xE0, 0xFF, 0x7D, 0xD6, 0x7C, 0x00, 0x02, 0x21, 0x1C, 0x90, 0x01, 0xC6, 0xEF, 0xF0, 0xA3,
0x12, 0x05, 0x0E, 0xE4, 0xFF, 0xFE, 0xD3, 0x90, 0x01, 0xCB, 0xE0, 0x9F, 0xEE, 0x64, 0x80, 0xF8,
0x90, 0x01, 0xCA, 0xE0, 0x64, 0x80, 0x98, 0x40, 0x1C, 0x90, 0x01, 0xC7, 0x12, 0x04, 0xEE, 0x8F,
0x82, 0x8E, 0x83, 0x12, 0x01, 0xD0, 0xFD, 0x90, 0x01, 0xC6, 0xE0, 0x6D, 0x60, 0x07, 0x0F, 0xBF,
0x00, 0x01, 0x0E, 0x80, 0xD1, 0x90, 0x01, 0xCA, 0xE0, 0xB5, 0x06, 0x08, 0xA3, 0xE0, 0xB5, 0x07,
0x03, 0x7F, 0x00, 0x22, 0x7F, 0x01, 0x22, 0xEF, 0x12, 0x05, 0x17, 0x27, 0x93, 0x00, 0x27, 0x98,
0x01, 0x27, 0x9D, 0x02, 0x27, 0x9D, 0x03, 0x27, 0x9D, 0x04, 0x27, 0xA3, 0x05, 0x27, 0xA1, 0x06,
0x27, 0xA1, 0x07, 0x27, 0xA1, 0x08, 0x27, 0xAA, 0x09, 0x27, 0x98, 0x12, 0x27, 0x93, 0x13, 0x00,
0x00, 0x27, 0xB0, 0x53, 0x80, 0xFE, 0x80, 0x15, 0x43, 0x80, 0x01, 0x80, 0x09, 0x43, 0x80, 0x01,
0x22, 0x80, 0x03, 0x53, 0x80, 0xFE, 0x43, 0x80, 0x04, 0x22, 0x43, 0x80, 0x01, 0x53, 0x80, 0xFB,
0x22, 0x90, 0x01, 0xAF, 0x12, 0x04, 0xA5, 0x90, 0x01, 0xB3, 0x12, 0x04, 0xB1, 0x00, 0x00, 0x00,
0x00, 0x90, 0x01, 0xAF, 0x12, 0x04, 0x8D, 0x90, 0x01, 0xB3, 0x12, 0x04, 0x99, 0xC3, 0x12, 0x04,
0x7C, 0x50, 0x1E, 0x12, 0x2C, 0xEF, 0x90, 0x01, 0xB3, 0x12, 0x04, 0x8D, 0xEF, 0x24, 0x01, 0xFF,
0xE4, 0x3E, 0xFE, 0xE4, 0x3D, 0xFD, 0xE4, 0x3C, 0xFC, 0x90, 0x01, 0xB3, 0x12, 0x04, 0xA5, 0x80,
0xD0, 0x22, 0x90, 0x01, 0xB7, 0x12, 0x05, 0x0E, 0xE4, 0xFF, 0xFE, 0xD3, 0x90, 0x01, 0xBE, 0xE0,
0x9F, 0xEE, 0x64, 0x80, 0xF8, 0x90, 0x01, 0xBD, 0xE0, 0x64, 0x80, 0x98, 0x40, 0x23, 0x90, 0x01,
0xBA, 0xE4, 0x75, 0xF0, 0x01, 0x12, 0x04, 0xF7, 0x12, 0x01, 0xB7, 0xFD, 0x90, 0x01, 0xB7, 0xE4,
0x75, 0xF0, 0x01, 0x12, 0x04, 0xF7, 0xED, 0x12, 0x01, 0xFD, 0x0F, 0xBF, 0x00, 0x01, 0x0E, 0x80,
0xCA, 0x22, 0xC0, 0xE0, 0xC0, 0x83, 0xC0, 0x82, 0xC0, 0xD0, 0x90, 0x01, 0xC4, 0xE0, 0x60, 0x0C,
0x90, 0x01, 0xC2, 0xE0, 0xB4, 0x03, 0x05, 0x75, 0x8C, 0x00, 0x80, 0x18, 0x90, 0x01, 0xC5, 0xE0,
0x60, 0x12, 0x90, 0x01, 0xC3, 0xE0, 0x60, 0x04, 0xE0, 0xB4, 0x01, 0x08, 0x75, 0x8A, 0x00, 0x75,
0x8C, 0x00, 0xD2, 0x8E, 0xC2, 0x8F, 0xD0, 0xD0, 0xD0, 0x82, 0xD0, 0x83, 0xD0, 0xE0, 0x32, 0xE4,
0x90, 0x01, 0x10, 0xF0, 0x90, 0x01, 0x10, 0xE0, 0xFE, 0x75, 0xF0, 0x03, 0xA4, 0x24, 0x00, 0xF5,
0x82, 0xE4, 0x34, 0x00, 0xF5, 0x83, 0xE0, 0xFF, 0xEE, 0x75, 0xF0, 0x03, 0xA4, 0x24, 0x01, 0xF5,
0x82, 0xE4, 0x34, 0x00, 0xF5, 0x83, 0xE0, 0xFC, 0xA3, 0xE0, 0xFD, 0x12, 0x21, 0x1C, 0x90, 0x01,
0x10, 0xE0, 0x04, 0xF0, 0xE0, 0xC3, 0x94, 0x12, 0x40, 0xCA, 0x22, 0x90, 0x01, 0xCC, 0xEF, 0xF0,
0xA3, 0xED, 0xF0, 0xE4, 0xA3, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0xCC, 0xE0, 0xFF, 0xA3, 0xE0, 0xFD,
0x90, 0x01, 0xCF, 0xE0, 0xFB, 0x12, 0x29, 0x1C, 0x90, 0x01, 0xCE, 0xE4, 0x75, 0xF0, 0x01, 0x12,
0x02, 0xCE, 0xC3, 0x90, 0x01, 0xCF, 0xE0, 0x94, 0x02, 0x90, 0x01, 0xCE, 0xE0, 0x64, 0x80, 0x94,
0x80, 0x40, 0xD5, 0x22, 0x43, 0x85, 0x01, 0x75, 0xC6, 0x04, 0x7D, 0xD4, 0x7C, 0x00, 0x7F, 0xFF,
0x12, 0x21, 0x1C, 0x7D, 0xD6, 0x7C, 0x00, 0x7F, 0xFF, 0x12, 0x21, 0x1C, 0x7D, 0x00, 0x7C, 0x08,
0x7F, 0x04, 0x12, 0x21, 0x1C, 0xE4, 0xF5, 0x95, 0xF5, 0x9D, 0x75, 0xA5, 0xFF, 0xF5, 0x80, 0xF5,
0x96, 0x75, 0x9E, 0xFF, 0x75, 0xA6, 0xFF, 0xF5, 0x90, 0x7F, 0x01, 0x22, 0x90, 0x01, 0x21, 0xED,
0xF0, 0xA3, 0xEB, 0xF0, 0xE0, 0x24, 0x35, 0xF8, 0xE6, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0xED, 0x24,
0x20, 0xFD, 0xEC, 0x34, 0x08, 0xFC, 0x12, 0x21, 0x1C, 0x90, 0x01, 0x21, 0xE0, 0xFF, 0xA3, 0xE0,
0x24, 0x35, 0xF8, 0xE6, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0xED, 0x24, 0x30, 0xFD, 0xEC, 0x34, 0x08,
0xFC, 0x02, 0x21, 0x1C, 0xE4, 0x90, 0x01, 0x10, 0xF0, 0xA3, 0xF0, 0x90, 0x01, 0x11, 0xE0, 0xFF,
0x12, 0x0D, 0x5E, 0xEF, 0x70, 0x02, 0xFF, 0x22, 0x90, 0x01, 0x10, 0xE4, 0x75, 0xF0, 0x01, 0x12,
0x02, 0xCE, 0xC3, 0x90, 0x01, 0x11, 0xE0, 0x94, 0x02, 0x90, 0x01, 0x10, 0xE0, 0x64, 0x80, 0x94,
0x80, 0x40, 0xD8, 0x7F, 0x01, 0x22, 0xED, 0x75, 0xF0, 0x08, 0x12, 0x01, 0x95, 0xFF, 0x33, 0x95,
0xE0, 0xFE, 0xE9, 0x2F, 0xF9, 0xEA, 0x3E, 0xFA, 0x12, 0x01, 0xB7, 0xFF, 0xAE, 0x05, 0xEE, 0x75,
0xF0, 0x08, 0x12, 0x01, 0x95, 0xAE, 0xF0, 0x74, 0x01, 0xA8, 0x06, 0x08, 0x80, 0x02, 0xC3, 0x33,
0xD8, 0xFC, 0x4F, 0x02, 0x01, 0xFD, 0xED, 0x75, 0xF0, 0x08, 0x12, 0x01, 0x95, 0xFF, 0x33, 0x95,
0xE0, 0xFE, 0xE9, 0x2F, 0xF9, 0xEA, 0x3E, 0xFA, 0x12, 0x01, 0xB7, 0xFF, 0xAE, 0x05, 0xEE, 0x75,
0xF0, 0x08, 0x12, 0x01, 0x95, 0xAE, 0xF0, 0x74, 0x01, 0xA8, 0x06, 0x08, 0x80, 0x02, 0xC3, 0x33,
0xD8, 0xFC, 0x4F, 0x02, 0x01, 0xFD, 0x90, 0x01, 0xDB, 0x12, 0x05, 0x0E, 0xE4, 0xFF, 0xFE, 0x74,
0xCB, 0x2F, 0xF5, 0x82, 0xE4, 0x34, 0x00, 0xF5, 0x83, 0xE0, 0xFD, 0x90, 0x01, 0xDB, 0x12, 0x04,
0xEE, 0x8F, 0x82, 0x8E, 0x83, 0xED, 0x12, 0x02, 0x0F, 0x0F, 0xBF, 0x00, 0x01, 0x0E, 0xEF, 0x64,
0x02, 0x4E, 0x70, 0xDB, 0x22, 0xE4, 0x90, 0x01, 0x0F, 0xF0, 0x90, 0x00, 0xD5, 0xF0, 0x7B, 0x01,
0x7A, 0x01, 0x79, 0x34, 0x12, 0x25, 0x4C, 0x12, 0x2C, 0x9D, 0x90, 0x00, 0xF3, 0xE0, 0x30, 0xE1,
0x08, 0x12, 0x29, 0x54, 0x90, 0x01, 0x0F, 0xEF, 0xF0, 0x90, 0x01, 0x0F, 0xE0, 0xFF, 0x22, 0x90,
0x01, 0xD0, 0x12, 0x05, 0x0E, 0x90, 0x01, 0xD3, 0xED, 0xF0, 0xFB, 0xE4, 0xFD, 0x7F, 0xFF, 0x12,
0x29, 0x1C, 0x90, 0x01, 0xD3, 0xE0, 0xFF, 0x7D, 0x1B, 0x12, 0x24, 0xDD, 0x12, 0x2B, 0xA3, 0x90,
0x01, 0xD0, 0x12, 0x04, 0xEE, 0xEF, 0x02, 0x01, 0xFD, 0x12, 0x23, 0x62, 0x12, 0x00, 0x86, 0x12,
0x2B, 0x14, 0xEF, 0x25, 0xE0, 0xFF, 0xEE, 0x33, 0x90, 0x01, 0x97, 0xEF, 0xF0, 0x12, 0x2A, 0x15,
0xEF, 0x60, 0xFA, 0x12, 0x2B, 0xE3, 0x90, 0x01, 0x98, 0xE0, 0x70, 0xF7, 0x12, 0x24, 0x6E, 0x80,
0xF2, 0x78, 0xF2, 0x7C, 0x00, 0x7D, 0x01, 0x7B, 0x01, 0x7A, 0x00, 0x79, 0xD5, 0x7E, 0x00, 0x7F,
0x14, 0x12, 0x01, 0x6F, 0x78, 0xE9, 0x7C, 0x00, 0x7D, 0x01, 0x7B, 0x01, 0x7A, 0x00, 0x79, 0xED,
0x7E, 0x00, 0x7F, 0x04, 0x02, 0x01, 0x6F, 0xAC, 0x07, 0xAF, 0x05, 0xEF, 0x7F, 0x00, 0xFE, 0xEF,
0x24, 0x5E, 0xF5, 0x82, 0x74, 0x0B, 0x3E, 0xF5, 0x83, 0xE5, 0x82, 0x2C, 0xF5, 0x82, 0xE4, 0x35,
0x83, 0xF5, 0x83, 0xE4, 0x93, 0xFF, 0x22, 0x78, 0x10, 0x7C, 0x01, 0x7D, 0x01, 0x7B, 0xFF, 0x7A,
0x2C, 0x79, 0xF3, 0x7E, 0x00, 0x7F, 0x01, 0x12, 0x01, 0x6F, 0x90, 0x01, 0x10, 0xE0, 0xFF, 0x7D,
0xD4, 0x7C, 0x00, 0x02, 0x21, 0x1C, 0xED, 0x64, 0x01, 0x4C, 0x70, 0x07, 0x90, 0x01, 0x8B, 0xEF,
0xF0, 0x80, 0x0D, 0xED, 0x64, 0x02, 0x4C, 0x70, 0x07, 0xEF, 0x44, 0x08, 0x90, 0x01, 0x8B, 0xF0,
0x53, 0x9E, 0xFB, 0x22, 0x90, 0x01, 0x88, 0xE0, 0xFF, 0x60, 0x0E, 0x90, 0x01, 0xDF, 0xE0, 0x2F,
0xFF, 0x90, 0x01, 0xDE, 0xE0, 0x34, 0x00, 0xFE, 0x22, 0x90, 0x01, 0xDE, 0xE0, 0xFE, 0xA3, 0xE0,
0xFF, 0x22, 0x90, 0x00, 0xFF, 0xE0, 0x14, 0x60, 0x0A, 0x04, 0x70, 0x13, 0x90, 0x08, 0x03, 0x74,
0xFE, 0xF0, 0x22, 0x90, 0x01, 0x00, 0xE0, 0x25, 0xE0, 0x25, 0xE0, 0x90, 0x08, 0x03, 0xF0, 0x22,
0x90, 0x01, 0xC3, 0xEF, 0xF0, 0x90, 0x01, 0xC5, 0xED, 0xF0, 0x53, 0x89, 0xCF, 0xEF, 0x54, 0x03,
0xC4, 0x54, 0xF0, 0x42, 0x89, 0xE4, 0xF5, 0x8B, 0xF5, 0x8D, 0xD2, 0xAB, 0x22, 0xAD, 0x07, 0xAC,
0x06, 0x7F, 0x01, 0x7E, 0x00, 0xED, 0x1D, 0xAA, 0x04, 0x70, 0x01, 0x1C, 0x4A, 0x60, 0x09, 0xEF,
0x25, 0xE0, 0xFF, 0xEE, 0x33, 0xFE, 0x80, 0xED, 0x22, 0x90, 0x01, 0xC2, 0xEF, 0xF0, 0x90, 0x01,
0xC4, 0xED, 0xF0, 0x53, 0x89, 0xFC, 0xEF, 0x54, 0x03, 0x42, 0x89, 0xE4, 0xF5, 0x8A, 0xF5, 0x8C,
0xD2, 0xA9, 0x22, 0xEF, 0x25, 0xE0, 0xFF, 0xE4, 0x33, 0xFE, 0x74, 0x5E, 0x2F, 0xF5, 0x82, 0x74,
0x09, 0x3E, 0xF5, 0x83, 0x74, 0x01, 0x93, 0xFF, 0x22, 0xAE, 0x05, 0xEF, 0xFD, 0x33, 0x95, 0xE0,
0xFC, 0x74, 0xD6, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83, 0xEE, 0xF0, 0x22, 0xAE, 0x05,
0xEF, 0xFD, 0x33, 0x95, 0xE0, 0xFC, 0x74, 0xD4, 0x2D, 0xF5, 0x82, 0x74, 0x01, 0x3C, 0xF5, 0x83,
0xEE, 0xF0, 0x22, 0x90, 0x01, 0xD9, 0xE0, 0xFF, 0x74, 0xFF, 0xF0, 0xD3, 0xEF, 0x64, 0x80, 0x94,
0x7F, 0x40, 0x03, 0x12, 0x2B, 0xF7, 0x22, 0xEF, 0x60, 0x03, 0xB4, 0x01, 0x0B, 0x90, 0x01, 0x32,
0x74, 0x01, 0xF0, 0x90, 0x00, 0xD5, 0xEF, 0xF0, 0x02, 0x25, 0xB9, 0x53, 0xE8, 0xDF, 0x53, 0xB2,
0xF7, 0x75, 0xB3, 0x40, 0x43, 0xB1, 0x03, 0x43, 0xB1, 0x20, 0x43, 0xE8, 0x20, 0x22, 0xEF, 0x33,
0x95, 0xE0, 0xFE, 0x74, 0xD6, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0, 0xFF, 0x22,
0xEF, 0x33, 0x95, 0xE0, 0xFE, 0x74, 0xD4, 0x2F, 0xF5, 0x82, 0x74, 0x01, 0x3E, 0xF5, 0x83, 0xE0,
0xFF, 0x22, 0x90, 0x01, 0x32, 0x74, 0x01, 0xF0, 0x90, 0x00, 0xE7, 0xEE, 0xF0, 0xA3, 0xEF, 0xF0,
0x22, 0xC2, 0xEC, 0xD2, 0xD9, 0x75, 0xC6, 0x15, 0xD2, 0xD8, 0xC2, 0xDB, 0x32, 0xE4, 0x90, 0x01,
0xDA, 0xF0, 0x90, 0x01, 0xD8, 0x74, 0xFF, 0xF0, 0x22, 0x90, 0x01, 0x32, 0x74, 0x01, 0xF0, 0x90,
0x00, 0xE3, 0xEF, 0xF0, 0x22, 0x90, 0x01, 0xDA, 0xEF, 0xF0, 0x90, 0x01, 0xD8, 0xED, 0xF0, 0x22,
0xE4, 0xF5, 0xDC, 0xF5, 0xDD, 0xF5, 0xDE, 0xF5, 0xDF, 0x22, 0x90, 0x01, 0x75, 0xE0, 0x6F, 0x60,
0x02, 0xEF, 0xF0, 0x22, 0x90, 0x00, 0xE7, 0xE0, 0xFE, 0xA3, 0xE0, 0xFF, 0x22, 0x12, 0x28, 0x6F,
0x12, 0x2B, 0x32, 0x02, 0x2C, 0xE6, 0x90, 0x08, 0x00, 0xE0, 0x54, 0xFB, 0xF0, 0x22, 0x90, 0x08,
0x00, 0xE0, 0x44, 0x04, 0xF0, 0x22, 0x90, 0x01, 0x89, 0xE0, 0xFF, 0x22, 0xEF, 0x24, 0xFF, 0x92,
0x8C, 0x22, 0xEF, 0x24, 0xFF, 0x92, 0x8E, 0x22, 0xEF, 0x24, 0xFF, 0x92, 0xD9, 0x22, 0xEF, 0x24,
0xFF, 0x92, 0xEC, 0x22, 0x90, 0x01, 0xD9, 0xEF, 0xF0, 0x22, 0x90, 0x01, 0xDA, 0xE0, 0xFF, 0x22,
0x90, 0x01, 0xD8, 0xE0, 0xFF, 0x22, 0x12, 0x26, 0xC8, 0x02, 0x2A, 0xD7, 0x02, 0x2C, 0x0B, 0x00,
0x00, 0x22, 0xFF, 0xFF,
};
| ikotpk/android_kernel_samsung_vastoskt | drivers/input/keyboard/M340K_R15_V09_bin.c | C | gpl-2.0 | 70,724 |
FROM puckiq/woodmoney-laravel
| PuckIQ/woodmoney-web | Dockerfile | Dockerfile | gpl-2.0 | 30 |
# encoding: utf-8
#
# CMS.rb
#
# Copyright 2014 Guillermo Valdés Lozano <guivaloz@movimientolibre.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
##
# Si gusta, puede descomentar el cambio al directorio donde va a tener este sitio web.
# Dir.chdir('/home/usuario/Documentos/GitHub/cms')
##
# Cargar los archivos con las clases necesarias
require './src/Imprenta.rb'
require './src/Menu.rb'
require './src/MenuPrincipal.rb'
require './src/MenuSecundario.rb'
require './src/MenuSecundarioContando.rb'
require './src/Multipagina.rb'
require './src/Plantilla.rb'
require './src/Publicacion.rb'
##
# CMS es una extensión de Imprenta.
#
# Haga las modificaciones necesarias para personalizar su sitio web.
class CMS < Imprenta
##
# Inicializar
def initialize
super
# Modifique estas propiedades
@sitio_titulo = "CMS de Movimiento Libre"
@sitio_descripcion = "Administrador de contenidos programado con Ruby para crear un sitio web con páginas estáticas."
@sitio_url = "http://cms.movimientolibre.com" # No use diagonal al final
@autor_por_defecto = "guivaloz" # El autor por defecto para las publicaciones que no lo tengan definido
@publicaciones_directorios = %w{ contacto documentacion licencias } # Los directorios que contenen las publicaciones
@publicaciones_etiquetas = { 'documentacion' => 'Documentación' } # Si hay que usar una etiqueta diferente para el directorio
@publicaciones_por_pagina_maximo = 8 # Por defecto se ponen 5 publicaciones por página, aquí lo cambiamos a 8
# Prepare el menu principal
@menu_principal = MenuPrincipal.new
@menu_principal.sitio_titulo = @sitio_titulo
@menu_principal.agregar('Documentación', 'documentacion/index.html')
@menu_principal.agregar('Licencias', 'licencias/index.html')
@menu_principal.agregar('Contacto', 'contacto/index.html')
@menu_principal.agregar_derecha('GitHub', 'https://github.com/MovimientoLibre/cms')
@menu_principal.agregar_derecha('RSS', 'rss.xml')
# Preparar plantilla
@plantilla = Plantilla.new
@plantilla.sitio_titulo = @sitio_titulo
@plantilla.sitio_url = @sitio_url
@plantilla.encabezado = <<FINAL
<div class="jumbotron">
<h1>#@sitio_titulo</h1>
<p>#@sitio_descripcion</p>
</div>
FINAL
@plantilla.pie = <<FINAL
<p>
Copyright (c) 2006-2014 Guillermo Valdés Lozano. Se otorga permiso para copiar, distribuir y/o modificar este documento.<br>
El programa está protegido por la licencia <a href="http://cms.movimientolibre.com/licencias/gpl-2.html">GPL versión 2</a>.<br>
La documentación está protegida por la licencia <a href="http://cms.movimientolibre.com/licencias/gfdl.html">GFDL</a>.
</p>
FINAL
end
##
# Construir sitio
def construir
# Construir
puts "Alimentándose..."
puts alimentarse
puts clasificar_autores
puts clasificar_categorias
puts preparar_menu_ultimas_publicaciones
# Preparar plantilla para archivos que NO estarán en la raíz
@plantilla.contenido_secundario = leer_archivo('inc/descargar.html') + @menu_categorias.to_html + @menu_autores.to_html + @menu_ultimas_publicaciones.to_html
@plantilla.menu_principal = @menu_principal.to_html
# Crear archivos que NO estarán en la raíz
puts "Creando publicaciones..."
paginas_publicaciones.each { |archivo, contenido| puts crear_archivo(archivo, contenido) }
puts "Creando páginas de los directorios..."
paginas_directorios.each { |archivo, contenido| puts crear_archivo(archivo, contenido) }
puts "Creando páginas de los autores..."
paginas_autores.each { |archivo, contenido| puts crear_archivo(archivo, contenido) }
puts "Creando páginas de las categorías..."
paginas_categorias.each { |archivo, contenido| puts crear_archivo(archivo, contenido) }
# Preparar la plantilla para archivos que SI van a estar en la raíz
@plantilla.contenido_secundario = leer_archivo('inc/descargar.html') + @menu_categorias.to_html(true) + @menu_autores.to_html(true) + @menu_ultimas_publicaciones.to_html(true)
@plantilla.menu_principal = @menu_principal.to_html(true)
# Crear archivos para la raíz
puts "Creando páginas iniciales..."
paginas_iniciales.each { |archivo, contenido| puts crear_archivo(archivo, contenido) }
puts "Creando sindicalización..."
puts crear_archivo('rss.xml', sindicalizacion)
end
end
##
# Ejecutar construir
cms = CMS.new
cms.construir
puts "Su sitio web está listo :-)"
| MovimientoLibre/cms | CMS.rb | Ruby | gpl-2.0 | 5,725 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_18) on Tue Nov 02 13:16:53 CET 2010 -->
<TITLE>
com.redhat.rhn.common.security.user
</TITLE>
<META NAME="date" CONTENT="2010-11-02">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../../com/redhat/rhn/common/security/user/package-summary.html" target="classFrame">com.redhat.rhn.common.security.user</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Exceptions</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="StateChangeException.html" title="class in com.redhat.rhn.common.security.user" target="classFrame">StateChangeException</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| colloquium/spacewalk | documentation/javadoc/com/redhat/rhn/common/security/user/package-frame.html | HTML | gpl-2.0 | 965 |
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
local talkState = {}
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
function creatureSayCallback(cid, type, msg)
if(not npcHandler:isFocused(cid)) then
return false
end
local talkUser = NPCHANDLER_CONVBEHAVIOR == CONVERSATION_DEFAULT and 0 or cid
if(msgcontains(msg, 'administrate')) then
if(getPlayerStorageValue(cid,2202) < 0) then
selfSay('Do you want to hire a {Bree Mercenaries Officer}?', cid)
talkState[talkUser] = 1
elseif(getPlayerStorageValue(cid,2202) == 0) then
selfSay('You cant hire any more officers.', cid)
end
elseif(msgcontains(msg, 'bree mercenaries officer')) then
if(talkState[talkUser] == 1) then
selfSay('For 30000 gp you can hire a bree mercenaries officer. He will help you to hire bree mercenary infantry, {ok}?.', cid)
talkState[talkUser] = 2
end
elseif(msgcontains(msg, 'ok')) then
if(talkState[talkUser] == 2) then
if(getPlayerStorageValue(cid,2202) < 0) then
if(doPlayerRemoveMoney(cid, 30000)) then
selfSay('Its done my lord.', cid)
setPlayerStorageValue(cid,2202,0)
x=Position(573, 952, 6)
doCreateNpc("Bree Mercenaries Officer",x)
talkState[talkUser] = 0
selfSay('Anything else?', cid)
else
selfSay('You need more gold.', cid)
end
end
end
elseif(msgcontains(msg, 'no') and isInArray({1}, talkState[talkUser])) then
selfSay('Ok. I understand.', cid)
talkState[talkUser] = 0
end
return true
end
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| troopizer/ot-server | data/npc/scripts/barrackswarden.lua | Lua | gpl-2.0 | 1,927 |
#ifndef __LOG_H
#define __LOG_H
class Log {
public:
Log() {
Serial.begin(57600);
Serial3.begin(57600);
}
void waitSerial() {
Serial.println("Enter key to start");
Serial3.println("Enter key to start");
while (!Serial.available() && !Serial3.available());
while ((Serial.available() && Serial.read()) || (Serial3.available() && Serial3.read()));
// delay(10000);
}
void print(const char* s) {
Serial.print(s);
Serial3.print(s);
}
void print(double s) {
Serial.print(s);
Serial3.print(s);
}
void print(float s) {
Serial.print(s);
Serial3.print(s);
}
void print(int s) {
Serial.print(s);
Serial3.print(s);
}
void print(long s) {
Serial.print(s);
Serial3.print(s);
}
void print(unsigned int s) {
Serial.print(s);
Serial3.print(s);
}
void print(unsigned long s) {
Serial.print(s);
Serial3.print(s);
}
void println(const char* s) {
Serial.println(s);
Serial3.println(s);
}
void println(double s) {
Serial.println(s);
Serial3.println(s);
}
};
#endif
| mwimble/ArduinoConroller | ArduinoConroller/ControllerWithTimer/Log.h | C | gpl-2.0 | 1,102 |
a, b = map(int,raw_input().split())
i=0
while(i<a):
j=0
c=[]
if(i%2==0):
while(j<b):
c.append('#')
j=j+1
print (''.join(c))
else:
k = int(i/2)
if (k%2==0):
while(j<(b-1)):
c.append(".")
j=j+1
c.append("#")
print (''.join(c))
else:
c.append('#')
while(j<(b-1)):
c.append(".")
j=j+1
print (''.join(c))
i=i+1
| Sarthak30/Codeforces | fox_and_snake.py | Python | gpl-2.0 | 361 |
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main(void)
{
int n,k;
cin>>n>>k;
vector<pair<int,int>> v;
for(int i=0;i<n;++i)
{
int temp;
cin>>temp;
v.push_back(make_pair(temp%10,temp));
}
sort(v.rbegin(),v.rend());
int flag=0;
while(flag==0)
{
int cnt=0;
for(int i=0;i<n;++i)
{
int a=v[i].first;
int b=v[i].second;
if(b==100)
{
cnt++;
continue;
}
if(k>=(10-a))
{
v[i].second+=10-a;
k-=(10-a);
v[i].first=0;
}
else
{
flag=2;
break;
}
}
if(cnt==n)
flag=1;
}
int ans=0;
for(int i=0;i<n;++i)
ans+=(v[i].second)/10;
cout<<ans;
return 0;
}
| Sarthak30/Codeforces | Developing Skills.cpp | C++ | gpl-2.0 | 1,007 |
/****************************************************************************************
* Copyright (c) 2014 Houssam Salem <houssam.salem.au@gmail.com> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package website.openeng.anki.tests;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.Suppress;
import website.openeng.anki.BackupManager;
import website.openeng.anki.exception.APIVersionException;
import website.openeng.libanki.Collection;
import website.openeng.libanki.Note;
import website.openeng.libanki.Media;
import website.openeng.anki.tests.Shared;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import website.openeng.utils.*;
/**
* Unit tests for {@link Media}.
*/
public class MediaTest extends AndroidTestCase {
public void testAdd() throws IOException, APIVersionException {
// open new empty collection
Collection d = Shared.getEmptyCol(getContext());
File dir = Shared.getTestDir(getContext());
BackupManager.removeDir(dir);
dir.mkdirs();
File path = new File(dir, "foo.jpg");
FileOutputStream os;
os = new FileOutputStream(path, false);
os.write("hello".getBytes());
os.close();
// new file, should preserve name
String r = d.getMedia().addFile(path);
assertEquals("foo.jpg", r);
// adding the same file again should not create a duplicate
assertEquals("foo.jpg", d.getMedia().addFile(path));
// but if it has a different md5, it should
os = new FileOutputStream(path, false);
os.write("world".getBytes());
os.close();
assertEquals("foo (1).jpg", d.getMedia().addFile(path));
}
public void testStrings() throws IOException {
Collection d = Shared.getEmptyCol(getContext());
Long mid = d.getModels().getModels().entrySet().iterator().next().getKey();
List<String> expected;
List<String> actual;
expected = Arrays.asList();
actual = d.getMedia().filesInStr(mid, "aoeu");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg");
actual = d.getMedia().filesInStr(mid, "aoeu<img src='foo.jpg'>ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg", "bar.jpg");
actual = d.getMedia().filesInStr(mid, "aoeu<img src='foo.jpg'><img src=\"bar.jpg\">ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg");
actual = d.getMedia().filesInStr(mid, "aoeu<img src=foo.jpg style=bar>ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("one", "two");
actual = d.getMedia().filesInStr(mid, "<img src=one><img src=two>");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg");
actual = d.getMedia().filesInStr(mid, "aoeu<img src=\"foo.jpg\">ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg", "fo");
actual = d.getMedia().filesInStr(mid, "aoeu<img src=\"foo.jpg\"><img class=yo src=fo>ao");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.mp3");
actual = d.getMedia().filesInStr(mid, "aou[sound:foo.mp3]aou");
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
assertEquals("aoeu", d.getMedia().strip("aoeu"));
assertEquals("aoeuaoeu", d.getMedia().strip("aoeu[sound:foo.mp3]aoeu"));
assertEquals("aoeu", d.getMedia().strip("a<img src=yo>oeu"));
assertEquals("aoeu", d.getMedia().escapeImages("aoeu"));
assertEquals("<img src='http://foo.com'>", d.getMedia().escapeImages("<img src='http://foo.com'>"));
assertEquals("<img src=\"foo%20bar.jpg\">", d.getMedia().escapeImages("<img src=\"foo bar.jpg\">"));
}
public void testDeckIntegration() throws IOException, APIVersionException {
Collection d = Shared.getEmptyCol(getContext());
// create a media dir
d.getMedia().dir();
// Put a file into it
File file = new File(Shared.getTestDir(getContext()), "fake.png");
file.createNewFile();
d.getMedia().addFile(file);
// add a note which references it
Note f = d.newNote();
f.setitem("Front", "one");
f.setitem("Back", "<img src='fake.png'>");
d.addNote(f);
// and one which references a non-existent file
f = d.newNote();
f.setitem("Front", "one");
f.setitem("Back", "<img src='fake2.png'>");
d.addNote(f);
// and add another file which isn't used
FileOutputStream os;
os = new FileOutputStream(new File(d.getMedia().dir(), "foo.jpg"), false);
os.write("test".getBytes());
os.close();
// check media
List<List<String>> ret = d.getMedia().check();
List<String> expected;
List<String> actual;
expected = Arrays.asList("fake2.png");
actual = ret.get(0);
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
expected = Arrays.asList("foo.jpg");
actual = ret.get(1);
actual.retainAll(expected);
assertEquals(expected.size(), actual.size());
}
@Suppress
private List<String> added(Collection d) {
return d.getMedia().getDb().queryColumn(String.class, "select fname from media where csum is not null", 0);
}
@Suppress
private List<String> removed(Collection d) {
return d.getMedia().getDb().queryColumn(String.class, "select fname from media where csum is null", 0);
}
public void testChanges() throws IOException, APIVersionException {
Collection d = Shared.getEmptyCol(getContext());
assertTrue(d.getMedia()._changed() != null);
assertTrue(added(d).size() == 0);
assertTrue(removed(d).size() == 0);
// add a file
File dir = Shared.getTestDir(getContext());
File path = new File(dir, "foo.jpg");
FileOutputStream os;
os = new FileOutputStream(path, false);
os.write("hello".getBytes());
os.close();
path = new File(d.getMedia().dir(), d.getMedia().addFile(path));
// should have been logged
d.getMedia().findChanges();
assertTrue(added(d).size() > 0);
assertTrue(removed(d).size() == 0);
// if we modify it, the cache won't notice
os = new FileOutputStream(path, true);
os.write("world".getBytes());
os.close();
assertTrue(added(d).size() == 1);
assertTrue(removed(d).size() == 0);
// but if we add another file, it will
path = new File(path.getAbsolutePath()+"2");
os = new FileOutputStream(path, true);
os.write("yo".getBytes());
os.close();
d.getMedia().findChanges(true);
assertTrue(added(d).size() == 2);
assertTrue(removed(d).size() == 0);
// deletions should get noticed too
path.delete();
d.getMedia().findChanges(true);
assertTrue(added(d).size() == 1);
assertTrue(removed(d).size() == 1);
}
public void testIllegal() throws IOException {
Collection d = Shared.getEmptyCol(getContext());
String aString = "a:b|cd\\e/f\0g*h";
String good = "abcdefgh";
assertTrue(d.getMedia().stripIllegal(aString).equals(good));
for (int i = 0; i < aString.length(); i++) {
char c = aString.charAt(i);
boolean bad = d.getMedia().hasIllegal("something" + c + "morestring");
if (bad) {
assertTrue(good.indexOf(c) == -1);
} else {
assertTrue(good.indexOf(c) != -1);
}
}
}
}
| mikeAopeneng/joyo-kanji | KanjiDroid/src/androidTest/java/com.ichi2.anki.tests/MediaTest.java | Java | gpl-2.0 | 9,354 |
<html>
<head>
<title>RunUO Documentation - Class Overview - Ettin</title>
</head>
<body bgcolor="white" style="font-family: Courier New" text="#000000" link="#000000" vlink="#000000" alink="#808080">
<h4><a href="../namespaces/Server.Mobiles.html">Back to Server.Mobiles</a></h4>
<h2>Ettin : <!-- DBG-1 --><a href="BaseCreature.html">BaseCreature</a>, <!-- DBG-2.2 --><a href="IHued.html">IHued</a>, <!-- DBG-2.1 --><font color="blue">IComparable</font><<a href="Mobile.html">Mobile</a>>, <!-- DBG-2.2 --><a href="ISerializable.html">ISerializable</a>, <!-- DBG-2.2 --><a href="ISpawnable.html">ISpawnable</a>, <!-- DBG-2.2 --><a href="IEntity.html">IEntity</a>, <!-- DBG-2.2 --><a href="IPoint3D.html">IPoint3D</a>, <!-- DBG-2.2 --><a href="IPoint2D.html">IPoint2D</a>, <!-- DBG-2.1 --><font color="blue">IComparable</font>, <!-- DBG-2.1 --><font color="blue">IComparable</font><<a href="IEntity.html">IEntity</a>>, <!-- DBG-2.2 --><a href="IHonorTarget.html">IHonorTarget</a></h2>
(<font color="blue">ctor</font>) Ettin()<br>
(<font color="blue">ctor</font>) Ettin( <!-- DBG-0 --><a href="Serial.html">Serial</a> serial )<br>
<font color="blue">bool</font> CanRummageCorpses( <font color="blue">get</font>; )<br>
<font color="blue">int</font> Meat( <font color="blue">get</font>; )<br>
<font color="blue">int</font> TreasureMapLevel( <font color="blue">get</font>; )<br>
<font color="blue">virtual</font> <font color="blue">void</font> Deserialize( <!-- DBG-0 --><a href="GenericReader.html">GenericReader</a> reader )<br>
<font color="blue">virtual</font> <font color="blue">void</font> GenerateLoot()<br>
<font color="blue">virtual</font> <font color="blue">void</font> Serialize( <!-- DBG-0 --><a href="GenericWriter.html">GenericWriter</a> writer )<br>
</body>
</html>
| alucardxlx/matts-uo-server | docs/types/Ettin.html | HTML | gpl-2.0 | 1,882 |
# Jigglypuff
Enabling Secure Keyless Acoustic Communication for Smartphones

## How to Use
===
When you start the application, there are two buttons. First for sender and another for receiver.
## Main Class && Methods
===
### Main Part:
**SenderActivity**: Keep input value, encode that value.
encodeMessage: Encodes the message and plays the sound signal using FSK.
**ReceiverActivity**: Start the receiver to receive the sound signal from mic. The data received is stored in a buffer and then will appear on the screen
**AudioReceiver**: Receive the data/message.
messageReceived: Check the message is received, if not then send last message.
###FSK Modulation/Demodulation:
When app starts a thread object that continuously records sound.
**ArduinoService**: sound acquisition
AudioRecordingRun(): loop that records sound
write(int): encodes the integer and plays the sound signal.
**FSKDecoder**: Thread object that demodulates the sound signal.
**FSKModule**: Utility static methods related to FSK modulation/demodulation.
encode(int): encodes the number into a sound signal
decodeSound(double): decodes the sound signal into an integer
**ErrorDetection**: Before transmission the number(between 0 and 31) is added with a checksum. Then at the reception, the message is decoded and if checksum check:
fails: an ARQ (Automatic Request Query) code is sent, then the sender repeats the last message sent.
agrees: an ACK (Acknowledgment) code is sent (if not received the sender tries to the send the last message again).
## Proposal
===
### 1. Demonstrate encode function by transferring text to voice frequency (9,000~10,000 Hz).(1 week)
In this process, we use two major techniques to implement transition, **FSK** and **ECC**.
Frequency shift keying (FSK) is a frequency modulation scheme in which digital information is transmitted through discrete frequency changes of a carrier wave. Normally, the transmitted audio alternates between two tones: one , the "mark", represents a binary one, the other, the "space", represents a binary zero.
Error correction code (ECC) is a systematic way of building codes that could detect and correct multiple random symbols. It viewed as cyclic BCH codes, where encoding symbols are derived from the coefficients of a polynomial constructed by multiplying p(x) with a cyclic generator polynomial, which gives rise to efficient decoding algorithms.
### 2. Demonstrate decode function by transferring voice frequency to text.(1 week)
### 3. Do the test on smart phones. To see if we can get the right text by choosing a specific voice frequency (handled by FSK).(1 week)
### 4. Testing if we can use FSK algorithm to transfer any text information to the voice frequency, and vice versa.(2 weeks)
### 5. By adding the white noise, our group implement security function and test the correctness.(4 weeks)
The applications of **accelerometer and distance detector** determine:
1. the receiver generates jamming signal;
2. sender sends information to receiver;
3. after receiver gets the mixed signal, it will remove the jamming signal.
## Team Member
====
Chen Si
Wang Jun
Tu Yujin
| quake0day/Jigglypuff | README.md | Markdown | gpl-2.0 | 3,291 |
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/power_supply.h>
#include <linux/workqueue.h>
#include <linux/reboot.h>
#include <asm/unaligned.h>
#include <mach/gpio.h>
#include <mach/iomux.h>
#include <mach/board.h>
#include <asm/uaccess.h>
#include <linux/power_supply.h>
#if 0
#define DBG(x...) printk(KERN_INFO x)
#else
#define DBG(x...)
#endif
//#define RK29_PLAY_ON_PIN RK29_PIN6_PA7
//#define MAX_PRE_CNT 2
//#define DET_CNT 5
#define PWR_ON_THRESHD 5 //power on threshd of capacity
//unsigned int pre_cnt = 0; //for long press counter
//int charge_disp_mode = 0;
static int pwr_on_thrsd = 5; //power on capcity threshold
int charger_in_logo = 0;
//extern int boot_mode_init(char * s);
static int __init pwr_on_thrsd_setup(char *str)
{
pwr_on_thrsd = simple_strtol(str,NULL,10);
printk(KERN_INFO "power on threshold:%d",pwr_on_thrsd);
return 0;
}
__setup("pwr_on_thrsd=", pwr_on_thrsd_setup);
static int usb_status;
static int ac_status;
static int __rk_get_system_battery_status(struct device *dev, void *data)
{
union power_supply_propval val_status = {POWER_SUPPLY_STATUS_DISCHARGING};
struct power_supply *psy = dev_get_drvdata(dev);
psy->get_property(psy, POWER_SUPPLY_PROP_ONLINE, &val_status);
if (val_status.intval != 0) {
if (psy->type == POWER_SUPPLY_TYPE_USB)
usb_status = POWER_SUPPLY_TYPE_USB;
if (psy->type == POWER_SUPPLY_TYPE_MAINS)
ac_status = POWER_SUPPLY_TYPE_MAINS;
}
return 0;
}
// POWER_SUPPLY_TYPE_BATTERY --- discharge
// POWER_SUPPLY_TYPE_USB --- usb_charging
// POWER_SUPPLY_TYPE_MAINS --- AC_charging
int rk_get_system_battery_status(void)
{
class_for_each_device(power_supply_class, NULL, NULL, __rk_get_system_battery_status);
if (ac_status == POWER_SUPPLY_TYPE_MAINS) {
return POWER_SUPPLY_TYPE_MAINS;
} else if (usb_status == POWER_SUPPLY_TYPE_USB) {
return POWER_SUPPLY_TYPE_USB;
}
return POWER_SUPPLY_TYPE_BATTERY;
}
EXPORT_SYMBOL(rk_get_system_battery_status);
static union power_supply_propval battery_capacity = { 100 };
static int __rk_get_system_battery_capacity(struct device *dev, void *data)
{
struct power_supply *psy = dev_get_drvdata(dev);
psy->get_property(psy, POWER_SUPPLY_PROP_CAPACITY, &battery_capacity);
return 0;
}
int rk_get_system_battery_capacity(void)
{
class_for_each_device(power_supply_class, NULL, NULL, __rk_get_system_battery_capacity);
return battery_capacity.intval;
}
EXPORT_SYMBOL(rk_get_system_battery_capacity);
#ifdef CONFIG_POWER_ON_CHARGER_DISPLAY
//int charger_mode=0; //1:charge,0:not charge
static void add_bootmode_charger_to_cmdline(void)
{
char *pmode=" androidboot.mode=charger";
//int off = strlen(saved_command_line);
char *new_command_line = kzalloc(strlen(saved_command_line) + strlen(pmode) + 1, GFP_KERNEL);
sprintf(new_command_line, "%s%s", saved_command_line, pmode);
saved_command_line = new_command_line;
//strcpy(saved_command_line+off,pmode);
//int off = strlen(boot_command_line);
//strcpy(boot_command_line+off,pmode);
printk("Kernel command line: %s\n", saved_command_line);
}
//display charger logo in kernel CAPACITY
static int __init start_charge_logo_display(void)
{
union power_supply_propval val_status = {POWER_SUPPLY_STATUS_DISCHARGING};
union power_supply_propval val_capacity ={ 100} ;
printk("start_charge_logo_display\n");
charger_in_logo = 0;
if(board_boot_mode() == BOOT_MODE_RECOVERY) //recovery mode
{
printk("recovery mode \n");
return 0;
}
if (rk_get_system_battery_status() != POWER_SUPPLY_TYPE_BATTERY)
val_status.intval = POWER_SUPPLY_STATUS_CHARGING;
val_capacity.intval = rk_get_system_battery_capacity();
// low power and discharging
#if 1
if((val_capacity.intval < pwr_on_thrsd )&&(val_status.intval != POWER_SUPPLY_STATUS_CHARGING))
{
printk("low power\n");
add_bootmode_charger_to_cmdline();
charger_in_logo = 1;
//kernel_power_off();
//while(1);
return 0;
}
#endif
//low power and charging
#if 0
if((val_capacity.intval < pwr_on_thrsd )&&(val_status.intval == POWER_SUPPLY_STATUS_CHARGING))
{
while((val_capacity.intval < pwr_on_thrsd ))
{
list_for_each_entry(psy, &rk_psy_head, rk_psy_node)
{
psy->get_property(psy,POWER_SUPPLY_PROP_CAPACITY,&val_capacity);
}
//printk("charging ... \n");
}
}
#endif
if(val_status.intval == POWER_SUPPLY_STATUS_CHARGING)
{
if ((board_boot_mode() == BOOT_MODE_NORMAL) ||(board_boot_mode() == BOOT_MODE_CHARGE)/* || (val_capacity.intval <= pwr_on_thrsd)*/) //do not enter power on charge mode when soft reset
{
add_bootmode_charger_to_cmdline();
//boot_mode_init("charge");
printk("power in charge mode\n");
charger_in_logo = 1;
}
}
return 0;
}
subsys_initcall_sync(start_charge_logo_display);
//module_init(start_charge_logo_display);
#endif
| lehmanju/kernel_lenovo_lifetab_e10312 | drivers/power/rk29_charger_display.c | C | gpl-2.0 | 4,932 |
<?php
include 'logincheck.php';
include 'html/header.php';
if(isset($_POST['invite']))
{ $invite = strtolower($_POST['invite']); }
else
{ echo '<h1>No Invite Code Entered</h1>'; exit; }
$row = mysql_fetch_array(mysql_query("SELECT Count(id) FROM users WHERE Invite = '$invite'"));
$count = $row['Count(id)'];
/* when you remove the invite feature, please update the GotBanners plugin page on Gotchance.com */
switch($invite)
{
case "brandon": if($count >= 1000) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "garcya": if($count >= 1000) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "andaka": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "maelkool": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "maisblogs": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "ollieparsley": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "techjuicer": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "webjuice": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "siteguide": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "makeuseof": if($count >= 2500) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "webappers": if($count >= 1001) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "techcrunch": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "mashable": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "centernetworks": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "readwriteweb": if($count >= 300) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "gotchance": if($count >= 1000) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "johnchow": if($count >= 200) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "bloggingexperiment": if($count >= 200) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "johntp": if($count >= 1000) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "shoemoney": if($count >= 200) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "problogger": if($count >= 1000) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "netbusinessblog": if($count >= 200) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "carlocab": if($count >= 250) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "techfold": if($count >= 250) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "jeffro2pt0": if($count >= 200) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
case "darin": if($count >= 250) { echo '<h1>Invite Code Expired</h1>'; exit; } break;
default: echo '<h1>Invalid Invite Code</h1>'; exit; break;
}
echo '<script language="javascript" src="html/register.js"></script>';
?>
<h1>Register</h1>
<div id="fullarea">
<form name="regform" id="regform" onsubmit="register('<?php echo $invite; ?>');" >
<table width="100%" border="0" cellpadding="5" cellspacing="0" style="font-size: 18px;">
<tr>
<td align="right">Name </td>
<td><input name="name" type="text" id="name" class="bigbox" /></td>
</tr>
<tr>
<td align="right">Email Address </td>
<td><input name="email" type="text" id="email" class="bigbox" /></td>
</tr>
<tr>
<td align="right">Username </td>
<td><input name="username" type="text" id="username" class="bigbox" /></td>
</tr>
<tr>
<td align="right">Password </td>
<td><input name="password" type="password" id="password" class="bigbox" /></td>
</tr>
<tr>
<td align="right">Confirm Password </td>
<td><input name="confirm" type="password" id="confirm" class="bigbox" /></td>
</tr>
<tr>
<td colspan="2" align="center">
<div id="regarea" style="font-size: 15px; margin-bottom: 10px;"></div>
<input type="button" value="Register" name="reg" onclick="register('<?php echo $invite; ?>');" style="font-size: 18px;" />
</td>
</tr>
</table>
</form>
</div>
<?php
include 'html/footer.php';
?> | fevangelou/rotatee | register.php | PHP | gpl-2.0 | 4,069 |
# program template for Spaceship
import simplegui
import math
import random
# globals for user interface
WIDTH = 800
HEIGHT = 600
score = 0
lives = 3
time = 0
game_mode = 0 # 0 = splash screen, 1 = game mode, 2 = game over
ANGULAR_ACCEL_SCALAR = math.pi / 800.0
ANGULAR_FRICTION = 0.95
LINEAR_ACCEL_SCALAR = 0.25
LINEAR_FRICTION = 0.99
RANDOM_VEL_MAX = 4.0
RANDOM_VEL_MIN = 0.5
RANDOM_ANG_MAX = math.pi / 100.0
BULLET_VEL = 10
SMALL_ROCK_SPEED = 3
class ImageInfo:
def __init__(self, center, size, radius = 0, lifespan = None, animated = False):
self.center = center
self.size = size
self.radius = radius
if lifespan:
self.lifespan = lifespan
else:
self.lifespan = float('inf')
self.animated = animated
def get_center(self):
return self.center
def get_size(self):
return self.size
def get_radius(self):
return self.radius
def get_lifespan(self):
return self.lifespan
def get_animated(self):
return self.animated
# art assets created by Kim Lathrop, may be freely re-used in non-commercial projects, please credit Kim
# debris images - debris1_brown.png, debris2_brown.png, debris3_brown.png, debris4_brown.png
# debris1_blue.png, debris2_blue.png, debris3_blue.png, debris4_blue.png, debris_blend.png
debris_info = ImageInfo([320, 240], [640, 480])
debris_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png")
# nebula images - nebula_brown.png, nebula_blue.png
nebula_info = ImageInfo([400, 300], [800, 600])
nebula_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.f2014.png")
# splash image
splash_info = ImageInfo([200, 150], [400, 300])
splash_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/splash.png")
# ship image
ship_info = ImageInfo([45, 45], [90, 90], 35)
ship_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png")
# missile image - shot1.png, shot2.png, shot3.png
missile_info = ImageInfo([5,5], [10, 10], 3, 75)
missile_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot2.png")
# asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.png
asteroid_info = ImageInfo([45, 45], [90, 90], 40)
asteroid_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png")
# animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.png
explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True)
explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png")
# sound assets purchased from sounddogs.com, please do not redistribute
soundtrack = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.mp3")
missile_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.mp3")
missile_sound.set_volume(.5)
ship_thrust_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.mp3")
explosion_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.mp3")
## CC 3.0 sound file by Jesus Lastra, http://opengameart.org/content/8-bit-pickup-1
extra_life_sound = simplegui.load_sound("http://mwales.net/junk/SFX_Pickup_44.mp3")
# helper functions to handle transformations
def angle_to_vector(ang):
return [math.cos(ang), math.sin(ang)]
def vector_to_angle(v):
return math.atan2(v[0],v[1])
def vector_scale(vec, scale):
return [vec[0] * scale, vec[1] * scale]
def vector_add(vec1, vec2):
return [vec1[0] + vec2[0], vec1[1] + vec2[1]]
def dist(p,q):
return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2)
def smallRockExplode(rockInstance):
# Return an explosion sprite
explodeObj = Sprite(rockInstance.get_position(),
(0,0),
random.random() * 2 * math.pi,
0,
explosion_image,
explosion_info,
explosion_sound,
relSize = 0.3)
return explodeObj
def rockExplode(rockInstance, deathBullet):
# Return an explosion sprite
explodeObj = Sprite(rockInstance.get_position(),
(0,0),
random.random() * 2 * math.pi,
0,
explosion_image,
explosion_info,
explosion_sound)
# Create 4 smaller rocks that explode away based on angle bullet came in at
bulletAngle = vector_to_angle(deathBullet.get_velocity())
smallRockAngle = bulletAngle + 45.0 / 360.0 * math.pi * 2.0
for i in range(0,4):
smallRockAngle += math.pi / 2.0
smallRockVel = angle_to_vector(smallRockAngle)
smallRockVel = vector_scale(smallRockVel, SMALL_ROCK_SPEED)
smallRockVel = vector_add(smallRockVel, rockInstance.get_velocity())
randomAngVel = random.random() * RANDOM_ANG_MAX * 4.0 - RANDOM_ANG_MAX
smallRock = Sprite(rockInstance.get_position(),
smallRockVel,
random.random() * 2 * math.pi,
randomAngVel,
asteroid_image,
asteroid_info,
relSize = 0.5)
smallRockList.append(smallRock)
return explodeObj
# Ship class
class Ship:
def __init__(self, pos, vel, angle, image, info, bulletTimer):
self.pos = [pos[0],pos[1]]
self.vel = [vel[0],vel[1]]
self.thrust = False
self.angle = angle
self.angle_vel = 0
self.angle_acc = 0
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.radius = info.get_radius()
self.bullet_timer = bulletTimer
self.spawn_bullets = False
self.bullets = []
self.bullet_type = 0
self.weapon_name = {}
self.weapon_name[0] = "Speed Shot"
self.weapon_name[1] = "Spread Shot"
self.weapon_name[2] = "Power Shot"
def get_weapon_name(self):
return self.weapon_name[self.bullet_type]
def draw(self,canvas):
if self.thrust:
canvas.draw_image(self.image,
(self.image_center[0] + self.image_size[0], self.image_center[1]),
self.image_size,
self.pos,
self.image_size,
self.angle)
else:
canvas.draw_image(self.image,
self.image_center,
self.image_size,
self.pos,
self.image_size,
self.angle)
for singleBullets in self.bullets:
singleBullets.draw(canvas)
def update(self):
self.pos = vector_add(self.pos, self.vel)
# Position should wrap around the screen
self.pos = [self.pos[0] % WIDTH, self.pos[1] % HEIGHT]
# Handle ship thrust
if self.thrust:
accel = angle_to_vector(self.angle)
accel = vector_scale(accel, LINEAR_ACCEL_SCALAR)
self.vel = vector_add(self.vel, accel)
# Friction against motion
self.vel = vector_scale(self.vel, LINEAR_FRICTION)
self.angle = self.angle + self.angle_vel
self.angle_vel = self.angle_vel + self.angle_acc
self.angle_vel = self.angle_vel * ANGULAR_FRICTION
oldBullets = []
for singleBullets in self.bullets:
if singleBullets.update():
oldBullets.append(singleBullets)
for bulletToDelete in oldBullets:
self.bullets.remove(bulletToDelete)
def process_collisions(self, rockList, smallRockList, explosionList):
global score, lives, extra_life_sound
# Don't change containers while looping through them
shipExplodes = False
rockListCopy = rockList
bulletListCopy = self.bullets
for singleRock in rockListCopy:
for singleBullet in bulletListCopy:
# Collisions of bullets and rocks
if singleBullet.collide(singleRock):
# delete the bullet
self.bullets.remove(singleBullet)
# delete and explode the rock
if singleRock in rockList:
rockList.remove(singleRock)
explosionList.append(rockExplode(singleRock, singleBullet))
print "Rock goes boom"
# increase score , 1-up consideration
self.scorePoint()
# Collisions of rock and ship
if singleRock.collide(self):
#print "Ship goes boom"
shipExplodes = True
smallRockListCopy = smallRockList
bulletListCopy = self.bullets
for singleSmallRock in smallRockListCopy:
for singleBullet in bulletListCopy:
if singleBullet.collide(singleSmallRock):
# delete the bullet
self.bullets.remove(singleBullet)
# delete and explode the rock
if singleSmallRock in smallRockList:
smallRockList.remove(singleSmallRock)
explosionList.append(smallRockExplode(singleSmallRock))
print "Small Rock goes boom"
# increase score , 1-up consideration
self.scorePoint()
# Collisions of rock and ship
if singleSmallRock.collide(self):
#print "Ship goes boom"
shipExplodes = True
if shipExplodes:
self.attemptRespawn(rockList, explosionList)
def scorePoint(self):
global lives, score
score += 1
if ((score % 100) == 0):
print "1-up"
lives += 1
extra_life_sound.rewind()
extra_life_sound.play()
def attemptRespawn(self, rockList, explosionList):
global lives
lives -= 1
if (lives == 0):
game_over()
return
# Find a safe spot to respawn
bestLocation = []
bestLocationClosestRock = 0
for respawnX in range( int(WIDTH / 10), int(WIDTH * .9), 10):
for respawnY in range( int(HEIGHT / 10), int(HEIGHT * .9), 10):
closestRock = WIDTH * HEIGHT
potentialLocation = [respawnX, respawnY]
# Determine at this location how close closest rock is
for singleRock in rockList:
distFromRock = dist(potentialLocation, singleRock.get_position())
if (distFromRock < closestRock):
closestRock = distFromRock
for singleRock in smallRockList:
distFromRock = dist(potentialLocation, singleRock.get_position())
if (distFromRock < closestRock):
closestRock = distFromRock
# If the closest rock is farther away than other locations, use this location
if (closestRock > bestLocationClosestRock):
bestLocationClosestRock = closestRock
bestLocation = potentialLocation
# Move ship to new location
shipExplosion = Sprite(self.pos,
(0,0),
random.random() * 2 * math.pi,
0,
explosion_image,
explosion_info,
explosion_sound,
relSize = 3.0)
explosionList.append(shipExplosion)
self.pos = bestLocation
self.vel = [0,0]
self.angle_vel = 0
# Just pass in -1 to rotate right, +1 to rotate left
def rotate(self, angularAcceleration):
self.angle_acc = angularAcceleration * ANGULAR_ACCEL_SCALAR
#print "Alpha =" + str(self.angle_acc)
# Just pass in True to thrust, False to not thrust
def setThrust(self, thrustBool):
global ship_thrust_sound
self.thrust = thrustBool
if thrustBool:
ship_thrust_sound.rewind()
ship_thrust_sound.play()
else:
ship_thrust_sound.pause()
def startShooting(self):
self.spawn_bullets = True;
self.bullet_timer.start()
self.spawn_bullet()
def stopShooting(self):
self.spawn_bullets = False
self.bullet_timer.stop()
def change_bullet_type(self):
self.bullet_type = (self.bullet_type + 1) % 3
def set_bullet_type(self, bulletType):
self.bullet_type = bulletType % 3
def get_bullet_type(self):
return self.bullet_type
def spawn_bullet(self):
if (self.bullet_type == 0):
# speed shot
self.make_bullet()
elif (self.bullet_type == 1):
# spread
self.make_bullet(relSpeed=0.5)
self.make_bullet(relAngle=-math.pi * 2 * 30.0 / 360.0,
relSpeed=0.5)
self.make_bullet(relAngle=math.pi * 2 * 30.0 / 360.0,
relSpeed=0.5)
else:
# big bullet
self.make_bullet(relSpeed=0.25,
relSize=3.0,
relLifetime=5.0)
curDirection = angle_to_vector(self.angle)
recoil = vector_scale(curDirection, -1.0)
self.vel = vector_add(self.vel, recoil)
def make_bullet(self, relAngle=0, relSpeed=1.0, relSize=1.0, relLifetime=1.0):
global missle_sound
bulletPos = angle_to_vector(self.angle)
bulletPos = vector_scale(bulletPos, self.image_size[0] / 2)
bulletPos = vector_add(self.pos, bulletPos)
bulletVel = angle_to_vector(self.angle + relAngle)
bulletVel = vector_scale(bulletVel, BULLET_VEL * relSpeed)
bulletVel = vector_add(bulletVel, self.vel)
bulletObj = Sprite(bulletPos,
bulletVel,
self.angle,
0,
missile_image,
missile_info,
missile_sound,
relSize,
relLifetime)
self.bullets.append(bulletObj)
def get_position(self):
return self.pos
def reset(self):
self.pos = [WIDTH / 2, HEIGHT / 2]
self.vel = [0,0]
self.angle = 0
self.bullets = []
def get_radius(self):
return self.radius
def get_velocity(self):
return self.vel
# Sprite class
class Sprite:
def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None, relSize=1.0, relLifetime=1.0):
self.pos = [pos[0],pos[1]]
self.vel = [vel[0],vel[1]]
self.angle = ang
self.angle_vel = ang_vel
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.draw_size = vector_scale(self.image_size, relSize)
self.radius = info.get_radius() * relSize
self.lifespan = info.get_lifespan() * relLifetime
self.animated = info.get_animated()
self.age = 0
if sound:
sound.rewind()
sound.play()
def draw(self, canvas):
if self.animated:
frameCenter = vector_add(self.image_center, [self.image_size[0] * self.age,0])
canvas.draw_image(self.image,
frameCenter,
self.image_size,
self.pos,
self.draw_size,
self.angle)
else:
canvas.draw_image(self.image,
self.image_center,
self.image_size,
self.pos,
self.draw_size,
self.angle)
def update(self):
pass
self.pos = vector_add(self.pos, self.vel)
# Position should wrap around the screen
self.pos = [self.pos[0] % WIDTH, self.pos[1] % HEIGHT]
self.angle = self.angle + self.angle_vel
# Age out?
self.age += 1
return (self.age > self.lifespan)
def collide(self, otherObject):
currentDistOfCenters = dist(otherObject.get_position(),
self.pos)
minSafeDistance = (otherObject.get_radius() + \
self.radius) * 0.9
return (currentDistOfCenters < minSafeDistance)
def get_position(self):
return self.pos
def get_radius(self):
return self.radius
def get_velocity(self):
return self.vel
def process_sprites(canvas):
global explodeList
# draw ship and sprites
my_ship.draw(canvas)
for singleRock in rockList:
singleRock.draw(canvas)
for smallRock in smallRockList:
smallRock.draw(canvas)
# update ship and sprites
my_ship.update()
for singleRock in rockList:
singleRock.update()
for smallRock in smallRockList:
smallRock.update()
# update explosions
splodeCopy = explodeList
for singleSplosion in splodeCopy:
singleSplosion.draw(canvas)
if singleSplosion.update():
explodeList.remove(singleSplosion)
my_ship.process_collisions(rockList, smallRockList, explodeList)
def draw(canvas):
global time
# animiate background
time += 1
wtime = (time / 4) % WIDTH
center = debris_info.get_center()
size = debris_info.get_size()
canvas.draw_image(nebula_image, nebula_info.get_center(), nebula_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT])
canvas.draw_image(debris_image, center, size, (wtime - WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))
canvas.draw_image(debris_image, center, size, (wtime + WIDTH / 2, HEIGHT / 2), (WIDTH, HEIGHT))
if game_mode == 1:
process_sprites(canvas)
if ( (game_mode == 1) or (game_mode == 2) ):
canvas.draw_text("Score: " + str(score),
(WIDTH - 250,60),
30,
'White')
canvas.draw_text("Lives: " + str(lives),
(150,60),
30,
'White')
canvas.draw_text("Weapon: " + my_ship.get_weapon_name(),
(WIDTH-400, HEIGHT - 50),
25,
'White',
'monospace')
if game_mode == 0:
canvas.draw_image(splash_image,
splash_info.get_center(),
splash_info.get_size(),
[WIDTH / 2, HEIGHT / 2],
splash_info.get_size())
# timer handler that spawns a rock
def rock_spawner(recurseDepth = 10):
global rockList
if (len(rockList) > 12):
print "Too many rocks"
return
randomX = random.choice(range(0, WIDTH))
randomY = random.choice(range(0, HEIGHT))
#print "Rock + " + str(recurseDepth) + " dist = " + str(dist(my_ship.get_position(), [randomX, randomY]))
if (dist(my_ship.get_position(), [randomX, randomY]) < 150):
print "too close for a rock"
if recurseDepth == 0:
return
else:
rock_spawner(recurseDepth - 1)
return
randomVel = angle_to_vector(random.random() * math.pi * 2.0)
randomVel = vector_scale(randomVel, random.random() * (RANDOM_VEL_MAX - RANDOM_VEL_MIN) + RANDOM_VEL_MIN)
randomAngVel = random.random() * RANDOM_ANG_MAX * 2.0 - RANDOM_ANG_MAX
#print "Spawn rock: [" + str(randomX) + "," + str(randomY) + "] v=" + \
# str(randomVel) + " Alpha=" + str(randomAngVel)
spawnRock = Sprite([randomX, randomY],
randomVel,
random.random() * math.pi * 2.0,
randomAngVel,
asteroid_image,
asteroid_info)
rockList.append(spawnRock)
def bullet_spawner():
global my_ship
my_ship.spawn_bullet()
def key_down_handler(key):
global my_ship, game_mode
if (game_mode == 1):
if ( (key == simplegui.KEY_MAP['left']) or (key == simplegui.KEY_MAP['a']) ):
my_ship.rotate(-1)
elif ( (key == simplegui.KEY_MAP['right']) or (key == simplegui.KEY_MAP['d']) ):
my_ship.rotate(1)
elif ( (key == simplegui.KEY_MAP['up']) or (key == simplegui.KEY_MAP['w']) ):
my_ship.setThrust(True)
elif ( (key == simplegui.KEY_MAP['down']) or (key == simplegui.KEY_MAP['s']) ):
pass
elif (key == simplegui.KEY_MAP['space']):
my_ship.startShooting()
elif (key == simplegui.KEY_MAP['1']):
pass
elif (key == simplegui.KEY_MAP['2']):
pass
elif (key == simplegui.KEY_MAP['3']):
pass
elif (game_mode == 0):
if (key == simplegui.KEY_MAP['space']):
start_game()
else:
if (key == simplegui.KEY_MAP['space']):
game_mode = 0
def key_up_handler(key):
global my_ship
if ( (key == simplegui.KEY_MAP['left']) or (key == simplegui.KEY_MAP['a']) ):
my_ship.rotate(0)
elif ( (key == simplegui.KEY_MAP['right']) or (key == simplegui.KEY_MAP['d']) ):
my_ship.rotate(0)
elif ( (key == simplegui.KEY_MAP['up']) or (key == simplegui.KEY_MAP['w']) ):
my_ship.setThrust(False)
elif ( (key == simplegui.KEY_MAP['down']) or (key == simplegui.KEY_MAP['s']) ):
my_ship.change_bullet_type()
elif (key == simplegui.KEY_MAP['space']):
my_ship.stopShooting()
elif (key == simplegui.KEY_MAP['1']):
my_ship.set_bullet_type(0)
elif (key == simplegui.KEY_MAP['2']):
my_ship.set_bullet_type(1)
elif (key == simplegui.KEY_MAP['3']):
my_ship.set_bullet_type(2)
def game_over():
global my_ship, rockList, smallRockList, timer, game_mode, soundtrack
rockList = []
smallRockList = []
timer.stop()
game_mode = 2
soundtrack.pause()
def start_game():
global timer, game_mode, lives, score, soundtrack
my_ship.reset()
timer.start()
game_mode = 1
lives = 3
score = 0
soundtrack.rewind()
soundtrack.play()
def mouse_handler(position):
if (game_mode == 0):
start_game()
# initialize frame
frame = simplegui.create_frame("Asteroids", WIDTH, HEIGHT)
frame.set_keydown_handler(key_down_handler)
frame.set_keyup_handler(key_up_handler)
frame.set_mouseclick_handler(mouse_handler)
frame.add_label("A/D or Left/Right to rotate")
frame.add_label("W or Up to thrust")
frame.add_label("S or Down to change weapon")
frame.add_label("1,2,3 are weapon hot key")
# initialize ship and two sprites
bulletSpawnerTimer = simplegui.create_timer(200, bullet_spawner)
my_ship = Ship([WIDTH / 2, HEIGHT / 2], [0, 0], math.pi, ship_image, ship_info, bulletSpawnerTimer)
rockList = []
smallRockList = []
explodeList = []
# register handlers
frame.set_draw_handler(draw)
timer = simplegui.create_timer(1000.0, rock_spawner)
# get things rolling
frame.start()
| mwales/education | InteractivePython/asteroids.py | Python | gpl-2.0 | 25,069 |
#!/bin/bash
SKIP_EXISTING=FALSE
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
if [[ -z $1 ]]; then
FILES="${DIR}/../images/themes/qfield/nodpi/$1*.svg"
else
FILES=$1
fi
if [[ -z $2 ]]; then
DESTINATION_PATH=${DIR}/../images/themes/qfield
else
DESTINATION_PATH=${DIR}/../android/res
PREFIX="drawable-"
fi
for f in $FILES
do
filename=$(basename "$f")
filename="${filename%.*}"
echo $filename
for size in "mdpi" "hdpi" "xhdpi" "xxhdpi" "xxxhdpi"
do
case $size in
mdpi)
res=24
;;
hdpi)
res=36
;;
xhdpi)
res=48
;;
xxhdpi)
res=72
;;
xxxhdpi)
res=96
;;
esac
DEST_FILE=${DESTINATION_PATH}/${PREFIX}${size}/$filename.png
if [[ ! -f ${DEST_FILE} ]] || [[ ${SKIP_EXISTING} != TRUE ]]; then
inkscape -z -o ${DEST_FILE} -w $res -h $res $f
else
echo " skipping"
fi
done
done
| opengisch/QField | scripts/create-images.sh | Shell | gpl-2.0 | 954 |
angular.module('NetPlanningApp').controller('AppCtrl', function($mdSidenav, $mdDialog, $mdToast, $scope, $location, $localStorage, $translate, amMoment, settings, DataService) {
'use strict';
var vm = this;
vm.$storage = $localStorage;
vm.DataService = DataService;
vm.username = '';
vm.password = '';
vm.errorMessage = null;
vm.$localStorage = $localStorage;
vm.availableLanguages = {
'en': 'English',
'it': 'Italiano',
'fr': 'French'
};
$localStorage.$default({
language: settings.defaultLanguage
});
$scope.$watch(function() {
return $localStorage.language;
}, function(val) {
$translate.use(val);
amMoment.changeLocale(val);
});
vm.update = function() {
var errorMessage = '<md-icon md-svg-src="images/ic_settings_48px.svg" class="md-warn" aria-label="settings"></md-icon>';
errorMessage += $translate.instant('ERROR_LOADING_DATA');
DataService.loadItems(true).catch(function() {
$mdToast.show({
templateUrl: 'partials/toast-error.html',
position: 'top right',
hideDelay: 800
});
});
};
vm.login = function() {
vm.errorMessage = null;
DataService.login(vm.username, vm.password).then(function() {
DataService.loadItems(false);
}).catch(function(reason) {
vm.errorMessage = reason.status > -1 ? reason.data.message : $translate.instant('NETWORK_ERROR');
}).finally(function() {
vm.username = '';
vm.password = '';
});
};
vm.logout = function() {
var title = $translate.instant('LOGOUT').capitalize();
var content = $translate.instant('ARE_YOU_SURE_YOU_WANT_TO_LOGOUT').capitalize() + ' ?';
var btnOk = $translate.instant('OK');
var btnCancel = $translate.instant('CANCEL');
var dialog = $mdDialog
.confirm()
.title(title)
.textContent(content)
.ariaLabel('Logout')
.ok(btnOk)
.cancel(btnCancel);
$mdDialog
.show(dialog)
.then(DataService.logout);
};
vm.toggleSidenav = function(menuId) {
$mdSidenav(menuId).toggle();
};
vm.navigateAndToggleSidenav = function(location, menuId) {
$mdSidenav(menuId).toggle();
$location.path(location);
};
});
| tabman83/netplanning-material-client | app/scripts/controllers/app.js | JavaScript | gpl-2.0 | 2,087 |
/* @override
http://clotheachild.net/wp-content/themes/reverie/css/colorbox.css */
/*
Colorbox Core Style:
The following CSS is consistent between example themes and should not be altered.
*/
#colorbox, #cboxOverlay, #cboxWrapper{position:absolute; top:0; left:0; z-index:9999; overflow:hidden;}
#cboxWrapper {max-width:none;}
#cboxOverlay{position:fixed; width:100%; height:100%;}
#cboxMiddleLeft, #cboxBottomLeft{clear:left;}
#cboxContent{position:relative;}
#cboxLoadedContent{overflow:auto; -webkit-overflow-scrolling: touch;}
#cboxTitle{margin:0; font-weight: bold; font-size: 16px;
}
#cboxLoadingOverlay, #cboxLoadingGraphic{position:absolute; top:0; left:0; width:100%; height:100%;}
#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{cursor:pointer;}
.cboxPhoto{float:left; margin:auto; border:0; display:block; max-width:none; -ms-interpolation-mode:bicubic;}
.cboxIframe{width:100%; height:100%; display:block; border:0; padding:0; margin:0;}
#colorbox, #cboxContent, #cboxLoadedContent{box-sizing:content-box; -moz-box-sizing:content-box; -webkit-box-sizing:content-box;}
/*
User Style:
Change the following styles to modify the appearance of Colorbox. They are
ordered & tabbed in a way that represents the nesting of the generated HTML.
*/
#cboxOverlay{background:#000; opacity: 0.9; filter: alpha(opacity = 90);}
#colorbox{outline:0;}
#cboxContent{margin-top:20px;background:#000;}
.cboxIframe{background:#fff;}
#cboxError{padding:50px; border:1px solid #ccc;}
#cboxLoadedContent{border:5px solid #000; background:#fff;}
#cboxTitle{position:absolute; top:-20px; left:0; color:#ccc;}
#cboxCurrent{position:absolute; top:-20px; right:0px; color:#ccc;}
#cboxLoadingGraphic{background:url(images/loading.gif) no-repeat center center;}
/* these elements are buttons, and may need to have additional styles reset to avoid unwanted base styles */
#cboxPrevious, #cboxNext, #cboxSlideshow, #cboxClose {border:0; padding:0; margin:0; overflow:visible; width:auto; background:none; }
/* avoid outlines on :active (mouseclick), but preserve outlines on :focus (tabbed navigating) */
#cboxPrevious:active, #cboxNext:active, #cboxSlideshow:active, #cboxClose:active {outline:0;}
#cboxSlideshow{position:absolute; top:-20px; right:90px; color:#fff;}
#cboxPrevious{position:absolute; top:50%; left:5px; margin-top:-32px; background:url(images/controls.png) no-repeat top left; width:28px; height:65px; text-indent:-9999px;}
#cboxPrevious:hover{background-position:bottom left;}
#cboxNext{position:absolute; top:50%; right:5px; margin-top:-32px; background:url(images/controls.png) no-repeat top right; width:28px; height:65px; text-indent:-9999px;}
#cboxNext:hover{background-position:bottom right;}
#cboxClose{position:absolute; top:5px; right:5px; display:block; background:url(images/controls.png) no-repeat top center; width:38px; height:19px; text-indent:-9999px;}
#cboxClose:hover{background-position:bottom center;}
| revivemarketing/clothe-a-child | wp-content/themes/reverie/css/colorbox.css | CSS | gpl-2.0 | 3,109 |
namespace UFIDA.U9.Cust.ChuangYeRenBillImportBP.ShipmentRelationBP
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.IO;
using UFSoft.UBF.Util.Context;
using UFSoft.UBF;
using UFSoft.UBF.Exceptions;
using UFSoft.UBF.Service.Base ;
[System.ServiceModel.ServiceContractAttribute(Namespace = "http://www.UFIDA.org", Name="UFIDA.U9.Cust.ChuangYeRenBillImportBP.ShipmentRelationBP.IDeleteReceivementProcessBP")]
public interface IDeleteReceivementProcessBP
{
[ServiceKnownType(typeof(ApplicationContext))]
[ServiceKnownType(typeof(PlatformContext))]
[ServiceKnownType(typeof(ThreadContext))]
[ServiceKnownType(typeof( UFSoft.UBF.Business.BusinessException))]
[ServiceKnownType(typeof( UFSoft.UBF.Business.EntityNotExistException))]
[ServiceKnownType(typeof( UFSoft.UBF.Business.AttributeInValidException))]
[ServiceKnownType(typeof(UFSoft.UBF.Business.AttrsContainerException))]
[ServiceKnownType(typeof(UFSoft.UBF.Exceptions.MessageBase))]
[FaultContract(typeof(UFSoft.UBF.Service.ServiceLostException))]
[FaultContract(typeof(UFSoft.UBF.Service.ServiceException))]
[FaultContract(typeof(UFSoft.UBF.Service.ServiceExceptionDetail))]
[FaultContract(typeof(ExceptionBase))]
[FaultContract(typeof(Exception))]
[OperationContract()]
PublicDataTransObj.PublicReturnDTOData Do(IContext context ,out IList<MessageBase> outMessages ,System.Int64 relationU9Id);
}
[UFSoft.UBF.Service.ServiceImplement]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class DeleteReceivementProcessBPStub : OperationStubBase, IDeleteReceivementProcessBP
{
#region IDeleteReceivementProcessBP Members
//[OperationBehavior]
public PublicDataTransObj.PublicReturnDTOData Do(IContext context ,out IList<MessageBase> outMessages, System.Int64 relationU9Id)
{
ICommonDataContract commonData = CommonDataContractFactory.GetCommonData(context, out outMessages);
return DoEx(commonData, relationU9Id);
}
//[OperationBehavior]
public PublicDataTransObj.PublicReturnDTOData DoEx(ICommonDataContract commonData, System.Int64 relationU9Id)
{
this.CommonData = commonData ;
try
{
BeforeInvoke("UFIDA.U9.Cust.ChuangYeRenBillImportBP.ShipmentRelationBP.DeleteReceivementProcessBP");
DeleteReceivementProcessBP objectRef = new DeleteReceivementProcessBP();
objectRef.RelationU9Id = relationU9Id;
//处理返回类型.
PublicDataTransObj.PublicReturnDTO result = objectRef.Do();
if (result == null)
return null ;
PublicDataTransObj.PublicReturnDTOData resultdata = result.ToEntityData();
DoSerializeKey(resultdata, "UFIDA.U9.Cust.ChuangYeRenBillImportBP.ShipmentRelationBP.DeleteReceivementProcessBP");
return resultdata;
}
catch (System.Exception e)
{
DealException(e);
throw;
}
finally
{
FinallyInvoke("UFIDA.U9.Cust.ChuangYeRenBillImportBP.ShipmentRelationBP.DeleteReceivementProcessBP");
}
}
#endregion
}
}
| amazingbow/yonyou | 创业人/ChuangYeRen_Code/ChuangYeRenBillImportBP/BpImplement/ShipmentRelationBP/DeleteReceivementProcessBPStub.cs | C# | gpl-2.0 | 3,268 |
/*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2010, Ralink Technology, Inc.
*
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
*************************************************************************/
#include "rt_config.h"
/**
* md5_mac:
* @key: pointer to the key used for MAC generation
* @key_len: length of the key in bytes
* @data: pointer to the data area for which the MAC is generated
* @data_len: length of the data in bytes
* @mac: pointer to the buffer holding space for the MAC; the buffer should
* have space for 128-bit (16 bytes) MD5 hash value
*
* md5_mac() determines the message authentication code by using secure hash
* MD5(key | data | key).
*/
void md5_mac(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac)
{
MD5_CTX context;
MD5Init(&context);
MD5Update(&context, key, key_len);
MD5Update(&context, data, data_len);
MD5Update(&context, key, key_len);
MD5Final(mac, &context);
}
/**
* hmac_md5:
* @key: pointer to the key used for MAC generation
* @key_len: length of the key in bytes
* @data: pointer to the data area for which the MAC is generated
* @data_len: length of the data in bytes
* @mac: pointer to the buffer holding space for the MAC; the buffer should
* have space for 128-bit (16 bytes) MD5 hash value
*
* hmac_md5() determines the message authentication code using HMAC-MD5.
* This implementation is based on the sample code presented in RFC 2104.
*/
void hmac_md5(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac)
{
MD5_CTX context;
u8 k_ipad[65]; /* inner padding - key XORd with ipad */
u8 k_opad[65]; /* outer padding - key XORd with opad */
u8 tk[16];
int i;
//assert(key != NULL && data != NULL && mac != NULL);
/* if key is longer than 64 bytes reset it to key = MD5(key) */
if (key_len > 64) {
MD5_CTX ttcontext;
MD5Init(&ttcontext);
MD5Update(&ttcontext, key, key_len);
MD5Final(tk, &ttcontext);
//key=(PUCHAR)ttcontext.buf;
key = tk;
key_len = 16;
}
/* the HMAC_MD5 transform looks like:
*
* MD5(K XOR opad, MD5(K XOR ipad, text))
*
* where K is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* and text is the data being protected */
/* start out by storing key in pads */
NdisZeroMemory(k_ipad, sizeof(k_ipad));
NdisZeroMemory(k_opad, sizeof(k_opad));
//assert(key_len < sizeof(k_ipad));
NdisMoveMemory(k_ipad, key, key_len);
NdisMoveMemory(k_opad, key, key_len);
/* XOR key with ipad and opad values */
for (i = 0; i < 64; i++) {
k_ipad[i] ^= 0x36;
k_opad[i] ^= 0x5c;
}
/* perform inner MD5 */
MD5Init(&context); /* init context for 1st pass */
MD5Update(&context, k_ipad, 64); /* start with inner pad */
MD5Update(&context, data, data_len); /* then text of datagram */
MD5Final(mac, &context); /* finish up 1st pass */
/* perform outer MD5 */
MD5Init(&context); /* init context for 2nd pass */
MD5Update(&context, k_opad, 64); /* start with outer pad */
MD5Update(&context, mac, 16); /* then results of 1st hash */
MD5Final(mac, &context); /* finish up 2nd pass */
}
#ifndef RT_BIG_ENDIAN
#define byteReverse(buf, len) /* Nothing */
#else
void byteReverse(unsigned char *buf, unsigned longs);
void byteReverse(unsigned char *buf, unsigned longs)
{
do {
*(ULONG *)buf = SWAP32(*(ULONG *)buf);
buf += 4;
} while (--longs);
}
#endif
/* ========================== MD5 implementation =========================== */
// four base functions for MD5
#define MD5_F1(x, y, z) (((x) & (y)) | ((~x) & (z)))
#define MD5_F2(x, y, z) (((x) & (z)) | ((y) & (~z)))
#define MD5_F3(x, y, z) ((x) ^ (y) ^ (z))
#define MD5_F4(x, y, z) ((y) ^ ((x) | (~z)))
#define CYCLIC_LEFT_SHIFT(w, s) (((w) << (s)) | ((w) >> (32-(s))))
#define MD5Step(f, w, x, y, z, data, t, s) \
( w += f(x, y, z) + data + t, w = (CYCLIC_LEFT_SHIFT(w, s)) & 0xffffffff, w += x )
/*
* Function Description:
* Initiate MD5 Context satisfied in RFC 1321
*
* Arguments:
* pCtx Pointer to MD5 context
*
* Return Value:
* None
*/
VOID MD5Init(MD5_CTX *pCtx)
{
pCtx->Buf[0]=0x67452301;
pCtx->Buf[1]=0xefcdab89;
pCtx->Buf[2]=0x98badcfe;
pCtx->Buf[3]=0x10325476;
pCtx->LenInBitCount[0]=0;
pCtx->LenInBitCount[1]=0;
}
/*
* Function Description:
* Update MD5 Context, allow of an arrary of octets as the next portion
* of the message
*
* Arguments:
* pCtx Pointer to MD5 context
* pData Pointer to input data
* LenInBytes The length of input data (unit: byte)
*
* Return Value:
* None
*
* Note:
* Called after MD5Init or MD5Update(itself)
*/
VOID MD5Update(MD5_CTX *pCtx, UCHAR *pData, ULONG LenInBytes)
{
ULONG TfTimes;
ULONG temp;
unsigned int i;
temp = pCtx->LenInBitCount[0];
pCtx->LenInBitCount[0] = (ULONG) (pCtx->LenInBitCount[0] + (LenInBytes << 3));
if (pCtx->LenInBitCount[0] < temp)
pCtx->LenInBitCount[1]++; //carry in
pCtx->LenInBitCount[1] += LenInBytes >> 29;
// mod 64 bytes
temp = (temp >> 3) & 0x3f;
// process lacks of 64-byte data
if (temp)
{
UCHAR *pAds = (UCHAR *) pCtx->Input + temp;
if ((temp+LenInBytes) < 64)
{
NdisMoveMemory(pAds, (UCHAR *)pData, LenInBytes);
return;
}
NdisMoveMemory(pAds, (UCHAR *)pData, 64-temp);
byteReverse(pCtx->Input, 16);
MD5Transform(pCtx->Buf, (ULONG *)pCtx->Input);
pData += 64-temp;
LenInBytes -= 64-temp;
} // end of if (temp)
TfTimes = (LenInBytes >> 6);
for (i=TfTimes; i>0; i--)
{
NdisMoveMemory(pCtx->Input, (UCHAR *)pData, 64);
byteReverse(pCtx->Input, 16);
MD5Transform(pCtx->Buf, (ULONG *)pCtx->Input);
pData += 64;
LenInBytes -= 64;
} // end of for
// buffering lacks of 64-byte data
if(LenInBytes)
NdisMoveMemory(pCtx->Input, (UCHAR *)pData, LenInBytes);
}
/*
* Function Description:
* Append padding bits and length of original message in the tail
* The message digest has to be completed in the end
*
* Arguments:
* Digest Output of Digest-Message for MD5
* pCtx Pointer to MD5 context
*
* Return Value:
* None
*
* Note:
* Called after MD5Update
*/
VOID MD5Final(UCHAR Digest[16], MD5_CTX *pCtx)
{
UCHAR Remainder;
UCHAR PadLenInBytes;
UCHAR *pAppend=0;
unsigned int i;
Remainder = (UCHAR)((pCtx->LenInBitCount[0] >> 3) & 0x3f);
PadLenInBytes = (Remainder < 56) ? (56-Remainder) : (120-Remainder);
pAppend = (UCHAR *)pCtx->Input + Remainder;
// padding bits without crossing block(64-byte based) boundary
if (Remainder < 56)
{
*pAppend = 0x80;
PadLenInBytes --;
NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, PadLenInBytes);
// add data-length field, from low to high
for (i=0; i<4; i++)
{
pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[0] >> (i << 3)) & 0xff);
pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[1] >> (i << 3)) & 0xff);
}
byteReverse(pCtx->Input, 16);
MD5Transform(pCtx->Buf, (ULONG *)pCtx->Input);
} // end of if
// padding bits with crossing block(64-byte based) boundary
else
{
// the first block ===
*pAppend = 0x80;
PadLenInBytes --;
NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, (64-Remainder-1));
PadLenInBytes -= (64 - Remainder - 1);
byteReverse(pCtx->Input, 16);
MD5Transform(pCtx->Buf, (ULONG *)pCtx->Input);
// the second block ===
NdisZeroMemory((UCHAR *)pCtx->Input, PadLenInBytes);
// add data-length field
for (i=0; i<4; i++)
{
pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[0] >> (i << 3)) & 0xff);
pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[1] >> (i << 3)) & 0xff);
}
byteReverse(pCtx->Input, 16);
MD5Transform(pCtx->Buf, (ULONG *)pCtx->Input);
} // end of else
NdisMoveMemory((UCHAR *)Digest, (ULONG *)pCtx->Buf, 16); // output
byteReverse((UCHAR *)Digest, 4);
NdisZeroMemory(pCtx, sizeof(*pCtx)); // memory free
}
/*
* Function Description:
* The central algorithm of MD5, consists of four rounds and sixteen
* steps per round
*
* Arguments:
* Buf Buffers of four states (output: 16 bytes)
* Mes Input data (input: 64 bytes)
*
* Return Value:
* None
*
* Note:
* Called by MD5Update or MD5Final
*/
VOID MD5Transform(ULONG Buf[4], ULONG Mes[16])
{
ULONG Reg[4], Temp;
unsigned int i;
static UCHAR LShiftVal[16] =
{
7, 12, 17, 22,
5, 9 , 14, 20,
4, 11, 16, 23,
6, 10, 15, 21,
};
// [equal to 4294967296*abs(sin(index))]
static ULONG MD5Table[64] =
{
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
};
for (i=0; i<4; i++)
Reg[i]=Buf[i];
// 64 steps in MD5 algorithm
for (i=0; i<16; i++)
{
MD5Step(MD5_F1, Reg[0], Reg[1], Reg[2], Reg[3], Mes[i],
MD5Table[i], LShiftVal[i & 0x3]);
// one-word right shift
Temp = Reg[3];
Reg[3] = Reg[2];
Reg[2] = Reg[1];
Reg[1] = Reg[0];
Reg[0] = Temp;
}
for (i=16; i<32; i++)
{
MD5Step(MD5_F2, Reg[0], Reg[1], Reg[2], Reg[3], Mes[(5*(i & 0xf)+1) & 0xf],
MD5Table[i], LShiftVal[(0x1 << 2)+(i & 0x3)]);
// one-word right shift
Temp = Reg[3];
Reg[3] = Reg[2];
Reg[2] = Reg[1];
Reg[1] = Reg[0];
Reg[0] = Temp;
}
for (i=32; i<48; i++)
{
MD5Step(MD5_F3, Reg[0], Reg[1], Reg[2], Reg[3], Mes[(3*(i & 0xf)+5) & 0xf],
MD5Table[i], LShiftVal[(0x1 << 3)+(i & 0x3)]);
// one-word right shift
Temp = Reg[3];
Reg[3] = Reg[2];
Reg[2] = Reg[1];
Reg[1] = Reg[0];
Reg[0] = Temp;
}
for (i=48; i<64; i++)
{
MD5Step(MD5_F4, Reg[0], Reg[1], Reg[2], Reg[3], Mes[(7*(i & 0xf)) & 0xf],
MD5Table[i], LShiftVal[(0x3 << 2)+(i & 0x3)]);
// one-word right shift
Temp = Reg[3];
Reg[3] = Reg[2];
Reg[2] = Reg[1];
Reg[1] = Reg[0];
Reg[0] = Temp;
}
// (temporary)output
for (i=0; i<4; i++)
Buf[i] += Reg[i];
}
/* ========================= SHA-1 implementation ========================== */
// four base functions for SHA-1
#define SHA1_F1(b, c, d) (((b) & (c)) | ((~b) & (d)))
#define SHA1_F2(b, c, d) ((b) ^ (c) ^ (d))
#define SHA1_F3(b, c, d) (((b) & (c)) | ((b) & (d)) | ((c) & (d)))
#define SHA1Step(f, a, b, c, d, e, w, k) \
( e += ( f(b, c, d) + w + k + CYCLIC_LEFT_SHIFT(a, 5)) & 0xffffffff, \
b = CYCLIC_LEFT_SHIFT(b, 30) )
//Initiate SHA-1 Context satisfied in RFC 3174
VOID SHAInit(SHA_CTX *pCtx)
{
pCtx->Buf[0]=0x67452301;
pCtx->Buf[1]=0xefcdab89;
pCtx->Buf[2]=0x98badcfe;
pCtx->Buf[3]=0x10325476;
pCtx->Buf[4]=0xc3d2e1f0;
pCtx->LenInBitCount[0]=0;
pCtx->LenInBitCount[1]=0;
}
/*
* Function Description:
* Update SHA-1 Context, allow of an arrary of octets as the next
* portion of the message
*
* Arguments:
* pCtx Pointer to SHA-1 context
* pData Pointer to input data
* LenInBytes The length of input data (unit: byte)
*
* Return Value:
* error indicate more than pow(2,64) bits of data
*
* Note:
* Called after SHAInit or SHAUpdate(itself)
*/
UCHAR SHAUpdate(SHA_CTX *pCtx, UCHAR *pData, ULONG LenInBytes)
{
ULONG TfTimes;
ULONG temp1,temp2;
unsigned int i;
UCHAR err=1;
temp1 = pCtx->LenInBitCount[0];
temp2 = pCtx->LenInBitCount[1];
pCtx->LenInBitCount[0] = (ULONG) (pCtx->LenInBitCount[0] + (LenInBytes << 3));
if (pCtx->LenInBitCount[0] < temp1)
pCtx->LenInBitCount[1]++; //carry in
pCtx->LenInBitCount[1] = (ULONG) (pCtx->LenInBitCount[1] +(LenInBytes >> 29));
if (pCtx->LenInBitCount[1] < temp2)
return (err); //check total length of original data
// mod 64 bytes
temp1 = (temp1 >> 3) & 0x3f;
// process lacks of 64-byte data
if (temp1)
{
UCHAR *pAds = (UCHAR *) pCtx->Input + temp1;
if ((temp1+LenInBytes) < 64)
{
NdisMoveMemory(pAds, (UCHAR *)pData, LenInBytes);
return (0);
}
NdisMoveMemory(pAds, (UCHAR *)pData, 64-temp1);
byteReverse((UCHAR *)pCtx->Input, 16);
NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
SHATransform(pCtx->Buf, (ULONG *)pCtx->Input);
pData += 64-temp1;
LenInBytes -= 64-temp1;
} // end of if (temp1)
TfTimes = (LenInBytes >> 6);
for (i=TfTimes; i>0; i--)
{
NdisMoveMemory(pCtx->Input, (UCHAR *)pData, 64);
byteReverse((UCHAR *)pCtx->Input, 16);
NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
SHATransform(pCtx->Buf, (ULONG *)pCtx->Input);
pData += 64;
LenInBytes -= 64;
} // end of for
// buffering lacks of 64-byte data
if(LenInBytes)
NdisMoveMemory(pCtx->Input, (UCHAR *)pData, LenInBytes);
return (0);
}
// Append padding bits and length of original message in the tail
// The message digest has to be completed in the end
VOID SHAFinal(SHA_CTX *pCtx, UCHAR Digest[20])
{
UCHAR Remainder;
UCHAR PadLenInBytes;
UCHAR *pAppend=0;
unsigned int i;
Remainder = (UCHAR)((pCtx->LenInBitCount[0] >> 3) & 0x3f);
pAppend = (UCHAR *)pCtx->Input + Remainder;
PadLenInBytes = (Remainder < 56) ? (56-Remainder) : (120-Remainder);
// padding bits without crossing block(64-byte based) boundary
if (Remainder < 56)
{
*pAppend = 0x80;
PadLenInBytes --;
NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, PadLenInBytes);
// add data-length field, from high to low
for (i=0; i<4; i++)
{
pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[1] >> ((3-i) << 3)) & 0xff);
pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[0] >> ((3-i) << 3)) & 0xff);
}
byteReverse((UCHAR *)pCtx->Input, 16);
NdisZeroMemory((UCHAR *)pCtx->Input + 64, 14);
SHATransform(pCtx->Buf, (ULONG *)pCtx->Input);
} // end of if
// padding bits with crossing block(64-byte based) boundary
else
{
// the first block ===
*pAppend = 0x80;
PadLenInBytes --;
NdisZeroMemory((UCHAR *)pCtx->Input + Remainder+1, (64-Remainder-1));
PadLenInBytes -= (64 - Remainder - 1);
byteReverse((UCHAR *)pCtx->Input, 16);
NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
SHATransform(pCtx->Buf, (ULONG *)pCtx->Input);
// the second block ===
NdisZeroMemory((UCHAR *)pCtx->Input, PadLenInBytes);
// add data-length field
for (i=0; i<4; i++)
{
pCtx->Input[56+i] = (UCHAR)((pCtx->LenInBitCount[1] >> ((3-i) << 3)) & 0xff);
pCtx->Input[60+i] = (UCHAR)((pCtx->LenInBitCount[0] >> ((3-i) << 3)) & 0xff);
}
byteReverse((UCHAR *)pCtx->Input, 16);
NdisZeroMemory((UCHAR *)pCtx->Input + 64, 16);
SHATransform(pCtx->Buf, (ULONG *)pCtx->Input);
} // end of else
//Output, bytereverse
for (i=0; i<20; i++)
{
Digest [i] = (UCHAR)(pCtx->Buf[i>>2] >> 8*(3-(i & 0x3)));
}
NdisZeroMemory(pCtx, sizeof(*pCtx)); // memory free
}
// The central algorithm of SHA-1, consists of four rounds and
// twenty steps per round
VOID SHATransform(ULONG Buf[5], ULONG Mes[20])
{
ULONG Reg[5],Temp;
unsigned int i;
ULONG W[80];
static ULONG SHA1Table[4] = { 0x5a827999, 0x6ed9eba1,
0x8f1bbcdc, 0xca62c1d6 };
Reg[0]=Buf[0];
Reg[1]=Buf[1];
Reg[2]=Buf[2];
Reg[3]=Buf[3];
Reg[4]=Buf[4];
//the first octet of a word is stored in the 0th element, bytereverse
for(i = 0; i < 16; i++)
{
W[i] = (Mes[i] >> 24) & 0xff;
W[i] |= (Mes[i] >> 8 ) & 0xff00;
W[i] |= (Mes[i] << 8 ) & 0xff0000;
W[i] |= (Mes[i] << 24) & 0xff000000;
}
for (i = 0; i < 64; i++)
W[16+i] = CYCLIC_LEFT_SHIFT(W[i] ^ W[2+i] ^ W[8+i] ^ W[13+i], 1);
// 80 steps in SHA-1 algorithm
for (i=0; i<80; i++)
{
if (i<20)
SHA1Step(SHA1_F1, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
W[i], SHA1Table[0]);
else if (i>=20 && i<40)
SHA1Step(SHA1_F2, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
W[i], SHA1Table[1]);
else if (i>=40 && i<60)
SHA1Step(SHA1_F3, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
W[i], SHA1Table[2]);
else
SHA1Step(SHA1_F2, Reg[0], Reg[1], Reg[2], Reg[3], Reg[4],
W[i], SHA1Table[3]);
// one-word right shift
Temp = Reg[4];
Reg[4] = Reg[3];
Reg[3] = Reg[2];
Reg[2] = Reg[1];
Reg[1] = Reg[0];
Reg[0] = Temp;
} // end of for-loop
// (temporary)output
for (i=0; i<5; i++)
Buf[i] += Reg[i];
}
/*
========================================================================
Routine Description:
SHA1 function
Arguments:
Return Value:
Note:
========================================================================
*/
VOID HMAC_SHA1(
IN UCHAR *text,
IN UINT text_len,
IN UCHAR *key,
IN UINT key_len,
IN UCHAR *digest)
{
SHA_CTX context;
UCHAR k_ipad[65]; /* inner padding - key XORd with ipad */
UCHAR k_opad[65]; /* outer padding - key XORd with opad */
INT i;
// if key is longer than 64 bytes reset it to key=SHA1(key)
if (key_len > 64)
{
SHA_CTX tctx;
SHAInit(&tctx);
SHAUpdate(&tctx, key, key_len);
SHAFinal(&tctx, key);
key_len = 20;
}
NdisZeroMemory(k_ipad, sizeof(k_ipad));
NdisZeroMemory(k_opad, sizeof(k_opad));
NdisMoveMemory(k_ipad, key, key_len);
NdisMoveMemory(k_opad, key, key_len);
// XOR key with ipad and opad values
for (i = 0; i < 64; i++)
{
k_ipad[i] ^= 0x36;
k_opad[i] ^= 0x5c;
}
// perform inner SHA1
SHAInit(&context); /* init context for 1st pass */
SHAUpdate(&context, k_ipad, 64); /* start with inner pad */
SHAUpdate(&context, text, text_len); /* then text of datagram */
SHAFinal(&context, digest); /* finish up 1st pass */
//perform outer SHA1
SHAInit(&context); /* init context for 2nd pass */
SHAUpdate(&context, k_opad, 64); /* start with outer pad */
SHAUpdate(&context, digest, 20); /* then results of 1st hash */
SHAFinal(&context, digest); /* finish up 2nd pass */
}
/* End of crypt_md5.c */
| mtorromeo/rt3562sta-linux | common/crypt_md5.c | C | gpl-2.0 | 21,485 |
"""
AUTHOR: Peter Collins, 2005.
This software is Copyright (C) 2004-2008 Bristol University
and is released under the GNU General Public License version 2.
MODULE: RunHill
PURPOSE:
A sample setup and configuration for the normalization algorithms.
NOTES:
See RunConfig.py for configuration options
"""
import sys
import RunConfig
degree = 6
if len(sys.argv)>1:
degree = int(sys.argv[1])
# pull things into the global context for profile
# from RunConfig import run_nf
# degree 6 runs in about 2m, 8 in 20m, 10 in 2h
config = { "tolerance" : 5.0e-14 , "degree" : degree , "system" : "Hill" ,
"do_stream" : False ,
"compute_diagonalisation" : True ,
"run_normal_form_python" : False ,
"run_normal_form_cpp" : True }
RunConfig.NfConfig(config).run_examp()
# Now do a python run if degree is < 7
config["compute_diagonalisation"] = False
config["run_normal_form_python"] = True
config["run_normal_form_cpp"] = False
if degree < 7:
RunConfig.NfConfig(config).run_examp()
| Peter-Collins/NormalForm | src/config-run/RunHill.py | Python | gpl-2.0 | 1,029 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DNQ.VirtualizedItemsSource
{
/// <summary> Interface that represents the result of a re-caching operation. </summary>
/// <typeparam name="T"> Generic type parameter for the type of data items. </typeparam>
internal interface IOperationResult<T>
{
Exception Exception
{
get;
}
DNQ.VirtualizedItemsSource.Operation<T> Operation
{
get;
}
T[] ResultSet
{
get;
}
IBounds NewBounds
{
get;
}
bool MustRefresh
{
get;
}
}
}
| DonaqLLC/dnq.virtualizeditemssource | IOperationResult.cs | C# | gpl-2.0 | 725 |
# herramienta_para_autodiagnostico_ADEADA
La Herramienta de Autodiagnóstico es una aplicación informática destinada a obtener un diagnóstico de la situación de cada empresa asociada en cuanto a gestión.
| Esleelkartea/herramienta_para_autodiagnostico_ADEADA | README.md | Markdown | gpl-2.0 | 209 |
/*
* Copyright (C) 2013-2016 Parallel and Reconfigurable Computing Group, University of Auckland.
*
* Authors: <http://homepages.engineering.auckland.ac.nz/~parallel/ParallelIT/People.html>
*
* This file is part of Pyjama, a Java implementation of OpenMP-like directive-based
* parallelisation compiler and its runtime routines.
*
* Pyjama 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 3 of the License, or
* (at your option) any later version.
*
* Pyjama 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 Pyjama. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Xing Fan
* @version 1.0
*/
package pj.parser.ast.visitor;
import pj.parser.ast.*;
import pj.parser.ast.body.*;
import pj.parser.ast.expr.*;
import pj.parser.ast.omp.*;
import pj.parser.ast.stmt.*;
import pj.parser.ast.symbolscope.SymbolTable;
import pj.parser.ast.type.*;
import pj.parser.ast.visitor.constructwrappers.*;
import pj.parser.ast.visitor.dataclausehandler.DataClausesHandler;
import pj.parser.ast.visitor.dataclausehandler.DataClauseHandlerUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
public class PyjamaToJavaVisitor implements VoidVisitor<SourcePrinter> {
protected File file;
protected String compilationFileName;
protected final static String PYJAMA_FILE_EXTENSION = ".pj";
static protected int nextOpenMPRegionUniqueID = 0;
static protected int nextTargetBlockID = 0;
static protected int nextTaskBlockID = 0;
static protected int nextWorkShareID = 0;
static protected int nextGuiCodeID = 0;
protected static final String prefixTaskNameForParallelRegion = "_OMP_ParallelRegion_";
protected static final String prefixTaskNameForTargetTaskRegion = "_OMP_TargetTaskRegion_";
protected static final String prefixTaskNameForTaskRegion = "_OMP_TaskRegion_";
protected static final String prefixTaskNameForWorkShare = "_OMP_WorkShare_";
protected static final String prefixTaskNameForGuiCode = "_OMP_GuiCode_";
//this hashmap stores the id of each generated region, in order to avoid id mismatch for same OpenMP construct.
static HashMap<OpenMPStatement, Integer> OpenMPStatementIDPairing = new HashMap<OpenMPStatement, Integer>();
//this hashmap stores the virtual targets with their name_as names. A name may pair multiple target blocks.
static HashMap<String, HashSet<TargetTaskCodeClassBuilder>> nameAsTargetBlocks = new HashMap<String, HashSet<TargetTaskCodeClassBuilder>>();
protected Stack<Boolean> stateMachineVisitingMode = new Stack<Boolean>();
protected SourcePrinter CodePrinter = new SourcePrinter();
protected SourcePrinter PrinterForAuxiliaryClasses = new SourcePrinter();
protected SourcePrinter PrinterForAsyncMethodStateMachineBuilder = new SourcePrinter();
protected SourcePrinter PrinterForAsyncTargetTaskStateMachineBuilder = new SourcePrinter();
//keep track of current method whether is static, used for the generate of parallel region class, and work share method
public boolean currentMethodIsStatic = false;
//keep track of current method or constructor's statements, this statements may used in freeguithread visitor
protected List<Statement> currentMethodOrConstructorStmts = null;
//keep track of current type of declaration of variables 2014.7.14
protected Type currentVarDeclarationType = null;
//if current var declaration is in foreach header, do not give initial value 2014.7.4 => 2014.10.27
protected boolean needNotVarInit = false;
//keep track of current worksharing block's private variables, including firstprivate, lastprivate, and reduction
/* 2015.6.29
* currentPrivateVariableInOMPWorksharingBlock: contain all variable name inside current //#omp for or //#omp sections
* need to be renamed. This is used in NameExpr visitor.
*/
protected HashMap<String,String> currentPrivateVariableInOMPWorksharingBlock = new HashMap<String,String>();
private SymbolTable symbolTable = null;
public PyjamaToJavaVisitor(SymbolTable symbolTable) {
this.symbolTable = symbolTable;
}
public PyjamaToJavaVisitor(SymbolTable symbolTable, Stack<Boolean> visitingMode) {
this.symbolTable = symbolTable;
this.stateMachineVisitingMode = visitingMode;
}
public SymbolTable getSymbolTable() {
return symbolTable;
}
public Stack<Boolean> getVisitingModeTrack() {
return this.stateMachineVisitingMode;
}
//OpenMP add BEGIN*******************************************************************************OpenMP add BEGIN//
public void visit(Node n, SourcePrinter printer){
throw new RuntimeException("Node: This abstract class should not appear.");
}
//------------------------------------------------------
public void visit(OmpParallelConstruct n, SourcePrinter printer){
//get current OmpParallelConstruct's scopeinfo from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
n.processAllReachableVariablesIfNecessary();
int uniqueOpenMPRegionID = -1;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueOpenMPRegionID = nextOpenMPRegionUniqueID++;
OpenMPStatementIDPairing.put(n, uniqueOpenMPRegionID);
} else {
uniqueOpenMPRegionID = OpenMPStatementIDPairing.get(n);
}
ParallelRegionClassBuilder currentPRClass = ParallelRegionClassBuilder.create(n, this.currentMethodIsStatic, this, this.currentMethodOrConstructorStmts);
currentPRClass.className = prefixTaskNameForParallelRegion + uniqueOpenMPRegionID;
printer.printLn("/*OpenMP Parallel region (#" + uniqueOpenMPRegionID + ") -- START */");
this.PrinterForAuxiliaryClasses.printLn(currentPRClass.getSource());
String previous_icv = "icv_previous_" + currentPRClass.className;
String new_icv = "icv_" + currentPRClass.className;
String thread_number = "_threadNum_" + currentPRClass.className;
printer.printLn("InternalControlVariables " + previous_icv + " = PjRuntime.getCurrentThreadICV();");
printer.printLn("InternalControlVariables " + new_icv + " = PjRuntime.inheritICV(" + previous_icv + ");");
if (null != n.getNumThreadsExpression()) {
String numThreadsClause = n.getNumThreadsExpression().getNumExpression().toString();
printer.printLn("int " + thread_number + " = " + numThreadsClause + ";");
} else {
printer.printLn("int " + thread_number + " = " + new_icv + ".nthreads_var.get("+ new_icv + ".levels_var);");
}
printer.printLn(currentPRClass.className + " " + currentPRClass.className + "_in = new "+ currentPRClass.className + "(" + thread_number + "," + new_icv + ");");
DataClausesHandler.processDataClausesBeforePRClassInvocation(currentPRClass, printer);
printer.printLn(currentPRClass.className + "_in" + ".runParallelCode();");
if (!n.isFreegui()) {
// if directive is normal parallel directive, recovery data from PRClass
DataClausesHandler.processDataClausesAfterPRClassInvocation(currentPRClass, printer);
printer.printLn("PjRuntime.recoverParentICV(" + previous_icv + ");");
printer.printLn("RuntimeException OMP_ee_" + uniqueOpenMPRegionID + " = (RuntimeException) " + currentPRClass.className + "_in.OMP_CurrentParallelRegionExceptionSlot.get();");
printer.printLn("if (OMP_ee_" + uniqueOpenMPRegionID + " != null) {throw OMP_ee_" + uniqueOpenMPRegionID + ";}");
} else if (n.isFreegui()) {
// if directive is freeguithread property, return after region, following code is invoked in region.
printer.printLn("if (PjRuntime.getCurrentThreadICV() != null) {", -1);
printer.indent();
DataClausesHandler.processDataClausesAfterPRClassInvocation(currentPRClass, printer);
printer.printLn("PjRuntime.recoverParentICV(" + previous_icv + ");");
printer.printLn("return;", -1);
printer.unindent();
printer.printLn("}", -1);
}
printer.printLn("/*OpenMP Parallel region (#" + uniqueOpenMPRegionID + ") -- END */");
}
public void visit(OmpParallelForConstruct n, SourcePrinter printer){
throw new RuntimeException("//#omp parallel for: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpParallelSectionsConstruct n, SourcePrinter printer){
throw new RuntimeException("//#omp parallel sections: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpForConstruct n, SourcePrinter printer){
//get current OmpParallelConstruct's scopeinfo from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
int uniqueWorkShareRegionID = -1;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueWorkShareRegionID = nextOpenMPRegionUniqueID++;
OpenMPStatementIDPairing.put(n, uniqueWorkShareRegionID);
} else {
uniqueWorkShareRegionID = OpenMPStatementIDPairing.get(n);
}
WorkShareBlockBuilder currentWSBlock = new WorkShareBlockBuilder(n, this, uniqueWorkShareRegionID);
printer.printLn("/*OpenMP Work Share region (#" + uniqueWorkShareRegionID + ") -- START */");
//Print Work Share Region
printer.printLn(currentWSBlock.getSource());
printer.printLn("PjRuntime.setBarrier();");
printer.printLn("PjRuntime.reset_OMP_orderCursor();");
printer.printLn("/*OpenMP Work Share region (#" + uniqueWorkShareRegionID + ") -- END */");
}
public void visit(OmpSectionsConstruct n, SourcePrinter printer){
throw new RuntimeException("//#omp sections: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpSingleConstruct n, SourcePrinter printer){
throw new RuntimeException("//#omp single: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpMasterConstruct n, SourcePrinter printer){
printer.printLn("if (0 == Pyjama.omp_get_thread_num()) {");
printer.indent();
n.getStatement().accept(this, printer);
printer.unindent();
printer.printLn("}");
}
public void visit(OmpCriticalConstruct n, SourcePrinter printer){
printer.printLn("PjRuntime.OMP_lock.lock();");
printer.printLn("try {");
printer.indent();
n.getStatement().accept(this, printer);
printer.unindent();
printer.printLn("} finally {");
printer.printLn("PjRuntime.OMP_lock.unlock();");
printer.unindent();
printer.printLn("}");
}
public void visit(OmpOrderedConstruct n, SourcePrinter printer){
printer.printLn("while (PjRuntime.get_OMP_orderCursor().get() < OMP_local_iterator) {}");
n.getStatement().accept(this, printer);
printer.printLn();
printer.printLn("PjRuntime.get_OMP_orderCursor().incrementAndGet();");
}
public void visit(OmpAtomicConstruct n, SourcePrinter printer){
// throw new RuntimeException("//#omp atomic: This should have been normalised.");
// --------------------------- Normalised --------------------//
printer.printLn("PjRuntime.OMP_lock.lock();");
printer.printLn("try {");
printer.indent();
n.getStatement().accept(this, printer);
printer.unindent();
printer.printLn("} finally {");
printer.printLn("PjRuntime.OMP_lock.unlock();");
printer.unindent();
printer.printLn("}");
}
public void visit(OmpTaskConstruct n, SourcePrinter printer) {
//get current OmpTaskConstruct's scope info from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
n.processAllReachableVariablesIfNecessary();
int uniqueTaskBlockID = -1;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueTaskBlockID = nextTaskBlockID++;
OpenMPStatementIDPairing.put(n, uniqueTaskBlockID);
} else {
uniqueTaskBlockID = OpenMPStatementIDPairing.get(n);
}
TaskCodeClassBuilder currentTClass = TaskCodeClassBuilder.create(n, this.currentMethodIsStatic, this, prefixTaskNameForTaskRegion + uniqueTaskBlockID);
printer.printLn("/*OpenMP Task block (#" + uniqueTaskBlockID + ") -- START */");
printer.printLn(currentTClass.className + " " + currentTClass.className + "_in = new "+ currentTClass.className + "();");
DataClausesHandler.processDataClausesBeforeTaskClassInvocation(currentTClass, printer);
printer.printLn("PjRuntime.submitOmpTask(" + currentTClass.className + "_in);");
DataClausesHandler.processDataClausesAfterTaskClassInvocation(currentTClass, printer);
printer.printLn("/*OpenMP Task block (#" + uniqueTaskBlockID + ") -- END */");
this.PrinterForAuxiliaryClasses.printLn(currentTClass.getSource());
}
public void visit(OmpBarrierDirective n, SourcePrinter printer){
printer.printLn("PjRuntime.setBarrier();");
}
public void visit(OmpFlushDirective n, SourcePrinter printer){
printer.printLn("PjRuntime.flushMemory();");
}
public void visit(OmpFreeguiConstruct n, SourcePrinter printer){
throw new RuntimeException("OmpFreeguiConstruct should be normalised as OmpParallelConstruct with freegui property");
}
public void visit(OmpGuiConstruct n, SourcePrinter printer){
//get current OmpParallelConstruct's scopeinfo from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
int uniqueGuiCodeID = nextGuiCodeID++;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueGuiCodeID = nextOpenMPRegionUniqueID++;
OpenMPStatementIDPairing.put(n, uniqueGuiCodeID);
} else {
uniqueGuiCodeID = OpenMPStatementIDPairing.get(n);
}
GuiCodeClassBuilder currentGuiCode = new GuiCodeClassBuilder(n, this);
currentGuiCode.guiName = prefixTaskNameForGuiCode + uniqueGuiCodeID;
printer.printLn("//#BEGIN GUI execution block");
printer.printLn("if (SwingUtilities.isEventDispatchThread()) {");
printer.indent();
n.getStatement().accept(this, printer);
printer.unindent();
printer.printLn("}");
printer.printLn("else {");
printer.indent();
printer.printLn(currentGuiCode.getSource());
printer.printLn("}");
printer.printLn("//#END GUI execution block");
}
public void visit(OmpCopyprivateDataClause n, SourcePrinter arg) {
throw new RuntimeException("copyprivate Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpDataClause n, SourcePrinter arg) {
throw new RuntimeException("OpenMPStatement: This abstract class should not appear.");
}
public void visit(OmpDefaultDataClause n, SourcePrinter arg) {
throw new RuntimeException("default Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpIfClause n, SourcePrinter arg) {
throw new RuntimeException("if Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpLastprivateDataClause n, SourcePrinter arg) {
throw new RuntimeException("lastprivate Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpNumthreadsClause n, SourcePrinter arg) {
throw new RuntimeException("num_threads Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpPrivateDataClause n, SourcePrinter arg) {
throw new RuntimeException("private Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpReductionDataClause n, SourcePrinter arg) {
throw new RuntimeException("reduction Clause should not be visited by PyjamaToJavaVisitor.");
}
@Override
public void visit(OmpReductionOperator n, SourcePrinter arg) {
throw new RuntimeException("reduction Operator should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpScheduleClause n, SourcePrinter arg) {
throw new RuntimeException("schedule Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpSectionConstruct n, SourcePrinter arg) {
throw new RuntimeException("//#omp section: This should have been normalised.");
// --------------------------- Normalised --------------------//
}
public void visit(OmpSharedDataClause n, SourcePrinter arg) {
throw new RuntimeException("shared Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OpenMPStatement n, SourcePrinter arg) {
throw new RuntimeException("OpenMPStatement: This abstract class should not appear.");
}
public void visit(OmpNeglectExceptionClause n, SourcePrinter arg) {
throw new RuntimeException("neglect_exception Clause should not be visited by PyjamaToJavaVisitor.");
}
public void visit(OmpCancellationPointDirective n, SourcePrinter printer) {
if (n.getRegion() == OmpCancellationPointDirective.Region.Parallel) {
printer.printLn("PjRuntime.checkParallelCancellationPoint();");
} else if (n.getRegion() == OmpCancellationPointDirective.Region.For) {
printer.printLn("PjRuntime.checkWorksharingCancellationPoint();");
} else if (n.getRegion() == OmpCancellationPointDirective.Region.Sections) {
printer.printLn("PjRuntime.checkWorksharingCancellationPoint();");
} else if (n.getRegion() == OmpCancellationPointDirective.Region.Taskgroup) {
throw new RuntimeException("Pyjama does not support omp task yet!");
} else if (n.getRegion() == OmpCancellationPointDirective.Region.CurrentTask) {
//omp cancellation point task
printer.printLn("PjRuntime.checkTaskCancellation();");
}
}
public void visit(OmpCancelDirective n, SourcePrinter printer) {
if (n.getRegion() == OmpCancelDirective.Region.Parallel) {
if (n.getThreadAffiliate() == OmpCancelDirective.ThreadAffiliate.Global) {
printer.print("throw new pj.pr.exceptions.OmpParallelRegionGlobalCancellationException(");
if (null != n.getException()) {
printer.print(n.getException());
}
printer.printLn(");");
} else if (n.getThreadAffiliate() == OmpCancelDirective.ThreadAffiliate.Local) {
printer.printLn("throw new pj.pr.exceptions.OmpParallelRegionLocalCancellationException(");
if (null != n.getException()) {
printer.print(n.getException());
}
printer.printLn(");");
}
} else if (n.getRegion() == OmpCancelDirective.Region.For || n.getRegion() == OmpCancelDirective.Region.Sections){
if (n.getThreadAffiliate() == OmpCancelDirective.ThreadAffiliate.Global) {
printer.printLn("throw new pj.pr.exceptions.OmpWorksharingGlobalCancellationException(");
if (null != n.getException()) {
printer.print(n.getException());
}
printer.printLn(");");
} else if (n.getThreadAffiliate() == OmpCancelDirective.ThreadAffiliate.Local) {
printer.printLn("throw new pj.pr.exceptions.OmpWorksharingLocalCancellationException(");
if (null != n.getException()) {
printer.print(n.getException());
}
printer.printLn(");");
}
} else if (n.getRegion() == OmpCancelDirective.Region.Taskgroup) {
throw new RuntimeException("Pyjama does not support omp task yet!");
}
}
public void visit(OmpTargetConstruct n, SourcePrinter printer) {
//return if current visiting is in a state-machine building mode.
boolean stateMachineBuildingMode = this.stateMachineVisitingMode.peek();
//if current target block contains await, the indicate the compiler, the inside visiting should also visited by a state machine builder.
if (n.containAwait()) {
this.stateMachineVisitingMode.push(true);
} else {
this.stateMachineVisitingMode.push(false);
}
//get current OmpTargetConstruct's scope info from symbolTable
n.scope = this.symbolTable.getScopeOfNode(n);
n.processAllReachableVariablesIfNecessary();
int uniqueTargetBlockID = -1;
if (OpenMPStatementIDPairing.get(n) == null) {
uniqueTargetBlockID = nextTargetBlockID++;
OpenMPStatementIDPairing.put(n, uniqueTargetBlockID);
} else {
uniqueTargetBlockID = OpenMPStatementIDPairing.get(n);
}
TargetTaskCodeClassBuilder currentTTClass = TargetTaskCodeClassBuilder.create(n, this.currentMethodIsStatic, this,
prefixTaskNameForTargetTaskRegion + uniqueTargetBlockID, n.containAwait());
printer.printLn("/*OpenMP Target region (#" + uniqueTargetBlockID + ") -- START */");
if (stateMachineBuildingMode) {
printer.printLn(currentTTClass.className + "_in = new "+ currentTTClass.className + "();");
} else {
printer.printLn(currentTTClass.className + " " + currentTTClass.className + "_in = new "+ currentTTClass.className + "();");
}
DataClausesHandler.processDataClausesBeforeTTClassInvocation(currentTTClass, printer);
this.PrinterForAsyncMethodStateMachineBuilder.printLn("private " + currentTTClass.className + " " + currentTTClass.className + "_in;");
this.PrinterForAsyncTargetTaskStateMachineBuilder.printLn("private " + currentTTClass.className + " " + currentTTClass.className + "_in;");
printer.printLn("if (PjRuntime.currentThreadIsTheTarget(\"" + n.getTargetName() + "\")) {");
printer.indent();
/*
* If current thread is already the target, we needn't submit the target task.
* Instead, we execute the target task in current thread.
*/
printer.printLn(currentTTClass.className + "_in.run();");
DataClausesHandler.processDataClausesAfterTTClassInvocation(currentTTClass, printer);
printer.unindent();
printer.printLn("} else {");
printer.indent();
//If this is a state machine building mode, we set completion call back function of current target task.
if (n.isAwait() && stateMachineBuildingMode) {
printer.printLn(currentTTClass.className + "_in.setOnCompleteCall(this, PjRuntime.getVirtualTargetOfCurrentThread());");
}
printer.printLn("PjRuntime.submitTargetTask(Thread.currentThread(), \"" + n.getTargetName() + "\", " + currentTTClass.className + "_in);");
if (n.isSync()) {
/*
* If default policy is applied, the encountering thread waits until the target block is finished.
*/
printer.printLn("PjRuntime.waitTaskTillFinish(" + currentTTClass.className + "_in);");
DataClausesHandler.processDataClausesAfterTTClassInvocation(currentTTClass, printer);
} else if (n.isAwait()) {
/*
* If await is applied, the current thread gives up current function execution, backs when target
* block is finished. For current implementation, we simply adopt an IHP (Irrelevant Handling Processing).
*/
if (!stateMachineBuildingMode) {
/*
* In normal method mode, we simply use IHP, essentially it will do a busy waiting in current implementation.
*/
printer.printLn("PjRuntime.IrrelevantHandlingProcessing(" + currentTTClass.className + "_in);");
} else if (stateMachineBuildingMode){
printer.printLn("if (false == PjRuntime.checkFinish(" + currentTTClass.className + "_in)) {");
printer.indent();
printer.printLn("this.OMP_state++;");
printer.printLn("return null;");
printer.unindent();
printer.printLn("}");
}
} else if (n.isNoWait()) {
/*
* We safely do nothing because we need not care about nowait the finish of the target block.
*/
}
printer.unindent();
printer.printLn("}");
if (n.isTaskAs()) {
storeTargetClassNameByTaskName(n.getTaskName(), currentTTClass);
printer.printLn("PjRuntime.storeTargetHandlerByName(" + currentTTClass.className + "_in, \"" + n.getTaskName() + "\");");
}
if (n.isAwait() && stateMachineBuildingMode) {
printer.printLn("this.OMP_state++;");
}
printer.printLn("/*OpenMP Target region (#" + uniqueTargetBlockID + ") -- END */");
//---Print Auxilary class
this.PrinterForAuxiliaryClasses.printLn(currentTTClass.getSource());
//---pop visiting mode.
this.stateMachineVisitingMode.pop();
}
public void visit(OmpTaskwaitDirective n, SourcePrinter printer) {
if (null != n.getIfClause()) {
printer.print("if(");
n.getIfClause().getIfExpression().accept(this, printer);
printer.printLn("){");
printer.indent();
}
if (null == n.getTaskName()) {
//If taskwait directive is not followed with a task name, this is wait for the tasks in the default parallel region.
printer.printLn("PjRuntime.taskWait();");
} else {
//If taskwait directive is followed with a task name, only wait tasks with this specific name, these tasks must be virtual task.
printer.printLn("PjRuntime.waitTargetBlocksWithTaskNameUntilFinish(\"" + n.getTaskName() + "\");");
}
if (null != n.getIfClause()) {
printer.unindent();
printer.printLn("}");
}
}
@Override
public void visit(OmpTaskcancelDirective n, SourcePrinter printer) {
if (null != n.getIfClause()) {
printer.print("if(");
n.getIfClause().getIfExpression().accept(this, printer);
printer.printLn("){");
printer.indent();
}
if (null == n.getTaskName()) {
//If taskwait directive is not followed with a task name, this is wait for the tasks in the default parallel region.
printer.printLn("PjRuntime.taskCancel();");
} else {
//If taskwait directive is followed with a task name, only wait tasks with this specific name, these tasks must be virtual task.
printer.printLn("PjRuntime.setCancellationFlagToTaskName(\""+ n.getTaskName() + "\");");
}
if (null != n.getIfClause()) {
printer.unindent();
printer.printLn("}");
}
}
@Override
public void visit(OmpAsyncCallConstruct n, SourcePrinter printer) {
/* For an async function, the prototype of this function still call the await block synchronously;
* So, directly visit this block. The states are used in state machine class.
*/
n.getBody().accept(this, this.CodePrinter);
/* The states should be generated in favor of state machine class building. However, this type of
* visiting is implemented by AsyncFunctionCallSubstitutionVisitor visitor.
*/
}
@Override
public void visit(OmpFunctionCallDeclaration n, SourcePrinter printer) {
throw new RuntimeException("OmpFunctionCallDeclaration should not be visited by PyjamaToJavaVisitor.");
}
//OpenMP add END*********************************************************************************OpenMP add END//
public void visit(CompilationUnit n, SourcePrinter printer) {
//print the compiler information at the beginning of the file.
this.CodePrinter.printLn("//Pyjama compiler version:" + pj.Version.getCompilerVersion());
if (n.getPackage() != null) {
n.getPackage().accept(this, this.CodePrinter);
}
if (n.getImports() != null) {
for (ImportDeclaration i : n.getImports()) {
i.accept(this, this.CodePrinter);
}
this.CodePrinter.printLn();
}
this.CodePrinter.printLn(this.printRuntimeImports());
if (n.getTypes() != null) {
for (Iterator<TypeDeclaration> i = n.getTypes().iterator(); i.hasNext();) {
i.next().accept(this, this.CodePrinter);
this.CodePrinter.printLn();
if (i.hasNext()) {
this.CodePrinter.printLn();
}
}
}
}
public void visit(PackageDeclaration n, SourcePrinter printer) {
printAnnotations(n.getAnnotations(), printer);
printer.print("package ");
n.getName().accept(this, printer);
printer.printLn(";");
printer.printLn();
}
public void visit(NameExpr n, SourcePrinter printer) {
/*Xing added at 2014.8.3: Renaming variable which has private property
* (firstprivate, lastprivate, reduction) for worksharing methods.
* conversion i => OMP_WoRkShArInG_PRIVATE_i;
*/
if (currentPrivateVariableInOMPWorksharingBlock.keySet().contains(n.toString())) {
printer.print(currentPrivateVariableInOMPWorksharingBlock.get(n.toString()));
} else {
printer.print(n.getName());
}
}
public void visit(QualifiedNameExpr n, SourcePrinter printer) {
n.getQualifier().accept(this, printer);
printer.print(".");
printer.print(n.getName());
}
public void visit(ImportDeclaration n, SourcePrinter printer) {
printer.print("import ");
if (n.isStatic()) {
printer.print("static ");
}
n.getName().accept(this, printer);
if (n.isAsterisk()) {
printer.print(".*");
}
printer.printLn(";");
}
public void visit(ClassOrInterfaceDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
if (n.isInterface()) {
printer.print("interface ");
} else {
printer.print("class ");
}
printer.print(n.getName());
printTypeParameters(n.getTypeParameters(), printer);
if (n.getExtends() != null) {
printer.print(" extends ");
for (Iterator<ClassOrInterfaceType> i = n.getExtends().iterator(); i.hasNext();) {
ClassOrInterfaceType c = i.next();
c.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
if (n.getImplements() != null) {
printer.print(" implements ");
for (Iterator<ClassOrInterfaceType> i = n.getImplements().iterator(); i.hasNext();) {
ClassOrInterfaceType c = i.next();
c.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.printLn(" {");
printer.indent();
if (n.getMembers() != null) {
printMembers(n.getMembers(), printer);
}
printer.unindent();
printer.print("}");
}
public void visit(EmptyTypeDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printer.print(";");
}
public void visit(JavadocComment n, SourcePrinter printer) {
printer.print("/**");
printer.print(n.getContent());
printer.printLn("*/");
}
public void visit(ClassOrInterfaceType n, SourcePrinter printer) {
if (n.getScope() != null) {
n.getScope().accept(this, printer);
printer.print(".");
}
printer.print(n.getName());
printTypeArgs(n.getTypeArgs(), printer);
}
public void visit(TypeParameter n, SourcePrinter printer) {
printer.print(n.getName());
if (n.getTypeBound() != null) {
printer.print(" extends ");
for (Iterator<ClassOrInterfaceType> i = n.getTypeBound().iterator(); i.hasNext();) {
ClassOrInterfaceType c = i.next();
c.accept(this, printer);
if (i.hasNext()) {
printer.print(" & ");
}
}
}
}
public void visit(PrimitiveType n, SourcePrinter printer) {
switch (n.getType()) {
case Boolean:
printer.print("boolean");
break;
case Byte:
printer.print("byte");
break;
case Char:
printer.print("char");
break;
case Double:
printer.print("double");
break;
case Float:
printer.print("float");
break;
case Int:
printer.print("int");
break;
case Long:
printer.print("long");
break;
case Short:
printer.print("short");
break;
}
}
public void visit(ReferenceType n, SourcePrinter printer) {
n.getType().accept(this, printer);
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
}
public void visit(WildcardType n, SourcePrinter printer) {
printer.print("?");
if (n.getExtends() != null) {
printer.print(" extends ");
n.getExtends().accept(this, printer);
}
if (n.getSuper() != null) {
printer.print(" super ");
n.getSuper().accept(this, printer);
}
}
public void visit(FieldDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
n.getType().accept(this, printer);
//Xing add code at 2014.7.29 BEGIN
/*this code snippet intends force initialize variables in declaration expression.
* The goal is solving uninitalization problem for parallel code generation.
*/
currentVarDeclarationType = n.getType();
//Xing add code at 2014.7.29 END
printer.print(" ");
for (Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext();) {
VariableDeclarator var = i.next();
var.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
printer.print(";");
}
public void visit(VariableDeclarator n, SourcePrinter printer) {
n.getId().accept(this, printer);
if (n.getInit() != null) {
printer.print(" = ");
n.getInit().accept(this, printer);
} else if (!this.needNotVarInit){
printer.print(" = ");
printer.print(DataClauseHandlerUtils.getDefaultValuesForPrimitiveType(currentVarDeclarationType.toString()));
}
}
public void visit(VariableDeclaratorId n, SourcePrinter printer) {
printer.print(n.getName());
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
}
public void visit(ArrayInitializerExpr n, SourcePrinter printer) {
printer.print("{");
if (n.getValues() != null) {
printer.print(" ");
for (Iterator<Expression> i = n.getValues().iterator(); i.hasNext();) {
Expression expr = i.next();
expr.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
printer.print(" ");
}
printer.print("}");
}
public void visit(VoidType n, SourcePrinter printer) {
printer.print("void");
}
public void visit(ArrayAccessExpr n, SourcePrinter printer) {
n.getName().accept(this, printer);
printer.print("[");
n.getIndex().accept(this, printer);
printer.print("]");
}
public void visit(ArrayCreationExpr n, SourcePrinter printer) {
printer.print("new ");
n.getType().accept(this, printer);
if (n.getDimensions() != null) {
for (Expression dim : n.getDimensions()) {
printer.print("[");
dim.accept(this, printer);
printer.print("]");
}
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
} else {
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
printer.print(" ");
n.getInitializer().accept(this, printer);
}
}
public void visit(AssignExpr n, SourcePrinter printer) {
n.getTarget().accept(this, printer);
printer.print(" ");
switch (n.getOperator()) {
case assign:
printer.print("=");
break;
case and:
printer.print("&=");
break;
case or:
printer.print("|=");
break;
case xor:
printer.print("^=");
break;
case plus:
printer.print("+=");
break;
case minus:
printer.print("-=");
break;
case rem:
printer.print("%=");
break;
case slash:
printer.print("/=");
break;
case star:
printer.print("*=");
break;
case lShift:
printer.print("<<=");
break;
case rSignedShift:
printer.print(">>=");
break;
case rUnsignedShift:
printer.print(">>>=");
break;
}
printer.print(" ");
n.getValue().accept(this, printer);
}
public void visit(BinaryExpr n, SourcePrinter printer) {
n.getLeft().accept(this, printer);
printer.print(" ");
switch (n.getOperator()) {
case or:
printer.print("||");
break;
case and:
printer.print("&&");
break;
case binOr:
printer.print("|");
break;
case binAnd:
printer.print("&");
break;
case xor:
printer.print("^");
break;
case equals:
printer.print("==");
break;
case notEquals:
printer.print("!=");
break;
case less:
printer.print("<");
break;
case greater:
printer.print(">");
break;
case lessEquals:
printer.print("<=");
break;
case greaterEquals:
printer.print(">=");
break;
case lShift:
printer.print("<<");
break;
case rSignedShift:
printer.print(">>");
break;
case rUnsignedShift:
printer.print(">>>");
break;
case plus:
printer.print("+");
break;
case minus:
printer.print("-");
break;
case times:
printer.print("*");
break;
case divide:
printer.print("/");
break;
case remainder:
printer.print("%");
break;
}
printer.print(" ");
n.getRight().accept(this, printer);
}
public void visit(CastExpr n, SourcePrinter printer) {
printer.print("(");
n.getType().accept(this, printer);
printer.print(") ");
n.getExpr().accept(this, printer);
}
public void visit(ClassExpr n, SourcePrinter printer) {
n.getType().accept(this, printer);
printer.print(".class");
}
public void visit(ConditionalExpr n, SourcePrinter printer) {
n.getCondition().accept(this, printer);
printer.print(" ? ");
n.getThenExpr().accept(this, printer);
printer.print(" : ");
n.getElseExpr().accept(this, printer);
}
public void visit(EnclosedExpr n, SourcePrinter printer) {
printer.print("(");
n.getInner().accept(this, printer);
printer.print(")");
}
public void visit(FieldAccessExpr n, SourcePrinter printer) {
n.getScope().accept(this, printer);
printer.print(".");
printer.print(n.getField());
}
public void visit(InstanceOfExpr n, SourcePrinter printer) {
n.getExpr().accept(this, printer);
printer.print(" instanceof ");
n.getType().accept(this, printer);
}
public void visit(CharLiteralExpr n, SourcePrinter printer) {
printer.print("'");
printer.print(n.getValue());
printer.print("'");
}
public void visit(DoubleLiteralExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(IntegerLiteralExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(LongLiteralExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(IntegerLiteralMinValueExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(LongLiteralMinValueExpr n, SourcePrinter printer) {
printer.print(n.getValue());
}
public void visit(StringLiteralExpr n, SourcePrinter printer) {
printer.print("\"");
printer.print(n.getValue());
printer.print("\"");
}
public void visit(BooleanLiteralExpr n, SourcePrinter printer) {
printer.print(String.valueOf(n.getValue()));
}
public void visit(NullLiteralExpr n, SourcePrinter printer) {
printer.print("null");
}
public void visit(ThisExpr n, SourcePrinter printer) {
if (n.getClassExpr() != null) {
n.getClassExpr().accept(this, printer);
printer.print(".");
}
printer.print("this");
}
public void visit(SuperExpr n, SourcePrinter printer) {
if (n.getClassExpr() != null) {
n.getClassExpr().accept(this, printer);
printer.print(".");
}
printer.print("super");
}
public void visit(MethodCallExpr n, SourcePrinter printer) {
if (n.getScope() != null) {
n.getScope().accept(this, printer);
printer.print(".");
}
printTypeArgs(n.getTypeArgs(), printer);
printer.print(n.getName());
printArguments(n.getArgs(), printer);
}
public void visit(ObjectCreationExpr n, SourcePrinter printer) {
if (n.getScope() != null) {
n.getScope().accept(this, printer);
printer.print(".");
}
printer.print("new ");
printTypeArgs(n.getTypeArgs(), printer);
n.getType().accept(this, printer);
printArguments(n.getArgs(), printer);
if (n.getAnonymousClassBody() != null) {
printer.printLn(" {");
printer.indent();
printMembers(n.getAnonymousClassBody(), printer);
printer.unindent();
printer.print("}");
}
}
public void visit(UnaryExpr n, SourcePrinter printer) {
switch (n.getOperator()) {
case positive:
printer.print("+");
break;
case negative:
printer.print("-");
break;
case inverse:
printer.print("~");
break;
case not:
printer.print("!");
break;
case preIncrement:
printer.print("++");
break;
case preDecrement:
printer.print("--");
break;
default:
break;
}
n.getExpr().accept(this, printer);
switch (n.getOperator()) {
case posIncrement:
printer.print("++");
break;
case posDecrement:
printer.print("--");
break;
default:
break;
}
}
public void visit(ConstructorDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
//Xing added to keep track of current constructor's statements
this.currentMethodOrConstructorStmts = new ArrayList<Statement>();
this.currentMethodOrConstructorStmts = n.getBlock().getStmts();
//Xing added
printTypeParameters(n.getTypeParameters(), printer);
if (n.getTypeParameters() != null) {
printer.print(" ");
}
printer.print(n.getName());
printer.print("(");
if (n.getParameters() != null) {
for (Iterator<Parameter> i = n.getParameters().iterator(); i.hasNext();) {
Parameter p = i.next();
p.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(")");
if (n.getThrows() != null) {
printer.print(" throws ");
for (Iterator<NameExpr> i = n.getThrows().iterator(); i.hasNext();) {
NameExpr name = i.next();
name.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(" ");
n.getBlock().accept(this, printer);
//Xing added
this.currentMethodOrConstructorStmts = null;
//Xing added
}
public void visit(MethodDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
this.currentMethodOrConstructorStmts = new ArrayList<Statement>();
if (n.getBody() != null) {
/*
* We do null pointer check because it is possible current method
* does not have body (e.g. abstract method); or current method
* does not have any statement (e.g.empty method).
*/
if (n.getBody().getStmts() != null) {
this.currentMethodOrConstructorStmts = n.getBody().getStmts();
}
}
//Xing added for checking current method is static or not
if (ModifierSet.isStatic(n.getModifiers())) {
this.currentMethodIsStatic = true;
}
else {
this.currentMethodIsStatic = false;
}
//Xing added for checking if current method should be annotated as an async method.
if (!n.isAsyncMethod() && n.containAwait()) {
throw new RuntimeException("Pyjama parsing error: Using the await block within a non-async method(" + n.getBeginLine() + ":" + n.getBeginColumn() + ").");
}
this.stateMachineVisitingMode.push(false);
printTypeParameters(n.getTypeParameters(), printer);
if (n.getTypeParameters() != null) {
printer.print(" ");
}
n.getType().accept(this, printer);
printer.print(" ");
printer.print(n.getName());
printer.print("(");
if (n.getParameters() != null) {
for (Iterator<Parameter> i = n.getParameters().iterator(); i.hasNext();) {
Parameter p = i.next();
p.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(")");
for (int i = 0; i < n.getArrayCount(); i++) {
printer.print("[]");
}
if (n.getThrows() != null) {
printer.print(" throws ");
for (Iterator<NameExpr> i = n.getThrows().iterator(); i.hasNext();) {
NameExpr name = i.next();
name.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
if (n.getBody() == null) {
printer.print(";");
} else {
printer.print(" ");
printer.print("{");
n.getBody().accept(this, printer);
printer.printLn();
printer.print("}");
}
this.stateMachineVisitingMode.pop();
/*Xing added to print Auxiliary parallel region classes
*if current method has PR regions or the current method is async.
*/
if (n.isAsyncMethod()) {
this.stateMachineVisitingMode.push(true);
StateMachineClassBuilder stateMachineMethodBuilder = new AsyncMethodStateMachineClassBuilder(n, this.currentMethodIsStatic, this, this.PrinterForAsyncMethodStateMachineBuilder.getSource());
this.PrinterForAuxiliaryClasses.printLn(stateMachineMethodBuilder.getSource());
this.PrinterForAsyncMethodStateMachineBuilder.clear();
this.stateMachineVisitingMode.pop();
}
printer.printLn(this.PrinterForAuxiliaryClasses.getSource());
this.PrinterForAuxiliaryClasses.clear();
// reset flag to default, for next method visiting
this.currentMethodOrConstructorStmts = null;
///Xing added end
}
public void visit(Parameter n, SourcePrinter printer) {
printAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
n.getType().accept(this, printer);
if (n.isVarArgs()) {
printer.print("...");
}
printer.print(" ");
n.getId().accept(this, printer);
}
public void visit(ExplicitConstructorInvocationStmt n, SourcePrinter printer) {
if (n.isThis()) {
printTypeArgs(n.getTypeArgs(), printer);
printer.print("this");
} else {
if (n.getExpr() != null) {
n.getExpr().accept(this, printer);
printer.print(".");
}
printTypeArgs(n.getTypeArgs(), printer);
printer.print("super");
}
printArguments(n.getArgs(), printer);
printer.print(";");
}
public void visit(VariableDeclarationExpr n, SourcePrinter printer) {
printAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
n.getType().accept(this, printer);
//Xing add code at 2014.7.29 BEGIN
/*this code snippet intends force initialize variables in declaration expression.
* The goal is solving uninitalization problem for parallel code generation.
*/
/*
* This cause another bugs: foreach loop local variable needn't to be initialised:
* however, this visitor will convert for(int i: list) => for(int i=0: list)
*/
currentVarDeclarationType = n.getType();
//Xing add code at 2014.7.29 END
printer.print(" ");
for (Iterator<VariableDeclarator> i = n.getVars().iterator(); i.hasNext();) {
VariableDeclarator v = i.next();
v.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
public void visit(TypeDeclarationStmt n, SourcePrinter printer) {
n.getTypeDeclaration().accept(this, printer);
}
public void visit(AssertStmt n, SourcePrinter printer) {
printer.print("assert ");
n.getCheck().accept(this, printer);
if (n.getMessage() != null) {
printer.print(" : ");
n.getMessage().accept(this, printer);
}
printer.print(";");
}
public void visit(BlockStmt n, SourcePrinter printer) {
printer.printLn("{");
if (n.getStmts() != null) {
printer.indent();
for (Statement s : n.getStmts()) {
s.accept(this, printer);
printer.printLn();
}
printer.unindent();
}
printer.print("}");
}
public void visit(LabeledStmt n, SourcePrinter printer) {
printer.print(n.getLabel());
printer.print(": ");
n.getStmt().accept(this, printer);
}
public void visit(EmptyStmt n, SourcePrinter printer) {
printer.print(";");
}
public void visit(ExpressionStmt n, SourcePrinter printer) {
n.getExpression().accept(this, printer);
printer.print(";");
}
public void visit(SwitchStmt n, SourcePrinter printer) {
printer.print("switch(");
n.getSelector().accept(this, printer);
printer.printLn(") {");
if (n.getEntries() != null) {
printer.indent();
for (SwitchEntryStmt e : n.getEntries()) {
e.accept(this, printer);
}
printer.unindent();
}
printer.print("}");
}
public void visit(SwitchEntryStmt n, SourcePrinter printer) {
if (n.getLabel() != null) {
printer.print("case ");
n.getLabel().accept(this, printer);
printer.print(":");
} else {
printer.print("default:");
}
printer.printLn();
printer.indent();
if (n.getStmts() != null) {
for (Statement s : n.getStmts()) {
s.accept(this, printer);
printer.printLn();
}
}
printer.unindent();
}
public void visit(BreakStmt n, SourcePrinter printer) {
printer.print("break");
if (n.getId() != null) {
printer.print(" ");
printer.print(n.getId());
}
printer.print(";");
}
public void visit(ReturnStmt n, SourcePrinter printer) {
printer.print("return");
if (n.getExpr() != null) {
printer.print(" ");
n.getExpr().accept(this, printer);
}
printer.print(";");
}
public void visit(EnumDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
printer.print("enum ");
printer.print(n.getName());
if (n.getImplements() != null) {
printer.print(" implements ");
for (Iterator<ClassOrInterfaceType> i = n.getImplements().iterator(); i.hasNext();) {
ClassOrInterfaceType c = i.next();
c.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.printLn(" {");
printer.indent();
if (n.getEntries() != null) {
printer.printLn();
for (Iterator<EnumConstantDeclaration> i = n.getEntries().iterator(); i.hasNext();) {
EnumConstantDeclaration e = i.next();
e.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
if (n.getMembers() != null) {
printer.printLn(";");
printMembers(n.getMembers(), printer);
} else {
if (n.getEntries() != null) {
printer.printLn();
}
}
printer.unindent();
printer.print("}");
}
public void visit(EnumConstantDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printer.print(n.getName());
if (n.getArgs() != null) {
printArguments(n.getArgs(), printer);
}
if (n.getClassBody() != null) {
printer.printLn(" {");
printer.indent();
printMembers(n.getClassBody(), printer);
printer.unindent();
printer.printLn("}");
}
}
public void visit(EmptyMemberDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printer.print(";");
}
public void visit(InitializerDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
if (n.isStatic()) {
printer.print("static ");
}
n.getBlock().accept(this, printer);
}
public void visit(IfStmt n, SourcePrinter printer) {
printer.print("if (");
n.getCondition().accept(this, printer);
printer.print(") ");
n.getThenStmt().accept(this, printer);
if (n.getElseStmt() != null) {
printer.print(" else ");
n.getElseStmt().accept(this, printer);
}
}
public void visit(WhileStmt n, SourcePrinter printer) {
printer.print("while (");
n.getCondition().accept(this, printer);
printer.print(") ");
n.getBody().accept(this, printer);
}
public void visit(ContinueStmt n, SourcePrinter printer) {
printer.print("continue");
if (n.getId() != null) {
printer.print(" ");
printer.print(n.getId());
}
printer.print(";");
}
public void visit(DoStmt n, SourcePrinter printer) {
printer.print("do ");
n.getBody().accept(this, printer);
printer.print(" while (");
n.getCondition().accept(this, printer);
printer.print(");");
}
public void visit(ForeachStmt n, SourcePrinter printer) {
printer.print("for (");
//Xing added at 2014.10.27, fix init bug at foreach loop
this.needNotVarInit = true;
n.getVariable().accept(this, printer);
this.needNotVarInit = false;
printer.print(" : ");
n.getIterable().accept(this, printer);
printer.print(") ");
n.getBody().accept(this, printer);
}
public void visit(ForStmt n, SourcePrinter printer) {
printer.print("for (");
if (n.getInit() != null) {
for (Iterator<Expression> i = n.getInit().iterator(); i.hasNext();) {
Expression e = i.next();
e.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print("; ");
if (n.getCompare() != null) {
n.getCompare().accept(this, printer);
}
printer.print("; ");
if (n.getUpdate() != null) {
for (Iterator<Expression> i = n.getUpdate().iterator(); i.hasNext();) {
Expression e = i.next();
e.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(") ");
n.getBody().accept(this, printer);
}
public void visit(ThrowStmt n, SourcePrinter printer) {
printer.print("throw ");
n.getExpr().accept(this, printer);
printer.print(";");
}
public void visit(SynchronizedStmt n, SourcePrinter printer) {
printer.print("synchronized (");
n.getExpr().accept(this, printer);
printer.print(") ");
n.getBlock().accept(this, printer);
}
public void visit(TryStmt n, SourcePrinter printer) {
printer.print("try ");
n.getTryBlock().accept(this, printer);
if (n.getCatchs() != null) {
for (CatchClause c : n.getCatchs()) {
c.accept(this, printer);
}
}
if (n.getFinallyBlock() != null) {
printer.print(" finally ");
n.getFinallyBlock().accept(this, printer);
}
}
public void visit(CatchClause n, SourcePrinter printer) {
printer.print(" catch (");
n.getExcept().accept(this, printer);
printer.print(") ");
n.getCatchBlock().accept(this, printer);
}
public void visit(AnnotationDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
printer.print("@interface ");
printer.print(n.getName());
printer.printLn(" {");
printer.indent();
if (n.getMembers() != null) {
printMembers(n.getMembers(), printer);
}
printer.unindent();
printer.print("}");
}
public void visit(AnnotationMemberDeclaration n, SourcePrinter printer) {
printJavadoc(n.getJavaDoc(), printer);
printMemberAnnotations(n.getAnnotations(), printer);
printModifiers(n.getModifiers(), printer);
n.getType().accept(this, printer);
printer.print(" ");
printer.print(n.getName());
printer.print("()");
if (n.getDefaultValue() != null) {
printer.print(" default ");
n.getDefaultValue().accept(this, printer);
}
printer.print(";");
}
public void visit(MarkerAnnotationExpr n, SourcePrinter printer) {
printer.print("@");
n.getName().accept(this, printer);
}
public void visit(SingleMemberAnnotationExpr n, SourcePrinter printer) {
printer.print("@");
n.getName().accept(this, printer);
printer.print("(");
n.getMemberValue().accept(this, printer);
printer.print(")");
}
public void visit(NormalAnnotationExpr n, SourcePrinter printer) {
printer.print("@");
n.getName().accept(this, printer);
printer.print("(");
if (n.getPairs() != null) {
for (Iterator<MemberValuePair> i = n.getPairs().iterator(); i.hasNext();) {
MemberValuePair m = i.next();
m.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(")");
}
public void visit(MemberValuePair n, SourcePrinter printer) {
printer.print(n.getName());
printer.print(" = ");
n.getValue().accept(this, printer);
}
public void visit(LineComment n, SourcePrinter printer) {
printer.print("//");
printer.printLn(n.getContent());
}
public void visit(BlockComment n, SourcePrinter printer) {
printer.print("/*");
printer.print(n.getContent());
printer.printLn("*/");
}
////////////////////PRIVATE METHODS BEGIN///////////////////////////////
private void printModifiers(int modifiers, SourcePrinter printer) {
if (ModifierSet.isPrivate(modifiers)) {
printer.print("private ");
}
if (ModifierSet.isProtected(modifiers)) {
printer.print("protected ");
}
if (ModifierSet.isPublic(modifiers)) {
printer.print("public ");
}
if (ModifierSet.isAbstract(modifiers)) {
printer.print("abstract ");
}
if (ModifierSet.isStatic(modifiers)) {
printer.print("static ");
}
if (ModifierSet.isFinal(modifiers)) {
printer.print("final ");
}
if (ModifierSet.isNative(modifiers)) {
printer.print("native ");
}
if (ModifierSet.isStrictfp(modifiers)) {
printer.print("strictfp ");
}
if (ModifierSet.isSynchronized(modifiers)) {
printer.print("synchronized ");
}
if (ModifierSet.isTransient(modifiers)) {
printer.print("transient ");
}
if (ModifierSet.isVolatile(modifiers)) {
printer.print("volatile ");
}
}
private void printMembers(List<BodyDeclaration> members, SourcePrinter printer) {
for (BodyDeclaration member : members) {
printer.printLn();
member.accept(this, printer);
printer.printLn();
}
}
private void printMemberAnnotations(List<AnnotationExpr> annotations, SourcePrinter printer) {
if (annotations != null) {
for (AnnotationExpr a : annotations) {
a.accept(this, printer);
printer.printLn();
}
}
}
private void printAnnotations(List<AnnotationExpr> annotations, SourcePrinter printer) {
if (annotations != null) {
for (AnnotationExpr a : annotations) {
a.accept(this, printer);
printer.print(" ");
}
}
}
private void printTypeArgs(List<pj.parser.ast.type.Type> args, SourcePrinter printer) {
if (args != null) {
printer.print("<");
for (Iterator<pj.parser.ast.type.Type> i = args.iterator(); i.hasNext();) {
pj.parser.ast.type.Type t = i.next();
t.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
printer.print(">");
}
}
private void printTypeParameters(List<TypeParameter> args, SourcePrinter printer) {
if (args != null) {
printer.print("<");
for (Iterator<TypeParameter> i = args.iterator(); i.hasNext();) {
TypeParameter t = i.next();
t.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
printer.print(">");
}
}
private void printArguments(List<Expression> args, SourcePrinter printer) {
printer.print("(");
if (args != null) {
for (Iterator<Expression> i = args.iterator(); i.hasNext();) {
Expression e = i.next();
e.accept(this, printer);
if (i.hasNext()) {
printer.print(", ");
}
}
}
printer.print(")");
}
private void printJavadoc(JavadocComment javadoc, SourcePrinter printer) {
if (javadoc != null) {
javadoc.accept(this, printer);
}
}
private String printRuntimeImports(){
SourcePrinter printer = new SourcePrinter();
printer.printLn("import pj.pr.*;");
printer.printLn("import pj.PjRuntime;");
printer.printLn("import pj.Pyjama;");
printer.printLn("import pi.*;");
printer.printLn("import java.util.concurrent.*;");
printer.printLn("import java.util.concurrent.atomic.AtomicBoolean;");
printer.printLn("import java.util.concurrent.atomic.AtomicInteger;");
printer.printLn("import java.util.concurrent.atomic.AtomicReference;");
printer.printLn("import java.util.concurrent.locks.ReentrantLock;");
printer.printLn("import java.lang.reflect.InvocationTargetException;");
printer.printLn("import pj.pr.exceptions.*;");
return printer.getSource();
}
//---OpenMP Target construct visiting helper methods
private void storeTargetClassNameByTaskName(String taskName, TargetTaskCodeClassBuilder targetClassBuilder) {
HashSet<TargetTaskCodeClassBuilder> targetBuilders = nameAsTargetBlocks.get(taskName);
if (null == targetBuilders) {
targetBuilders = new HashSet<TargetTaskCodeClassBuilder>();
nameAsTargetBlocks.put(taskName, targetBuilders);
}
targetBuilders.add(targetClassBuilder);
}
private HashSet<TargetTaskCodeClassBuilder> getTargetClassBuilders(String taskName) {
HashSet<TargetTaskCodeClassBuilder> targetBuilders = nameAsTargetBlocks.get(taskName);
if (null != targetBuilders) {
return targetBuilders;
} else {
//return empty list.
return new HashSet<TargetTaskCodeClassBuilder>();
}
}
////////////////////PRIVATE METHODS END////////////////////
public PyjamaToJavaVisitor(File file) {
this.file = file;
this.compilationFileName = this.file.getName().substring(0,
this.file.getName().indexOf(PYJAMA_FILE_EXTENSION));
}
public SourcePrinter getPriter() {
return this.CodePrinter;
}
public String getSource() {
return CodePrinter.getSource();
}
public String getAuxiliaryClassesSource() {
return this.PrinterForAuxiliaryClasses.getSource();
}
public void appendAuxiliaryClassesSource(String source) {
this.PrinterForAuxiliaryClasses.printLn(source);
}
public SourcePrinter getPrinterForAsyncTargetTaskStateMachineBuilder() {
return this.PrinterForAsyncTargetTaskStateMachineBuilder;
}
/********************************************************************************************************************************/
} | ParallelAndReconfigurableComputing/Pyjama | src/pj/parser/ast/visitor/PyjamaToJavaVisitor.java | Java | gpl-2.0 | 69,061 |
/* Copyright (C) 2003-2010 Jesper K. Pedersen <blackie@kde.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; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef IMAGEDB_H
#define IMAGEDB_H
#include "DB/ImageInfoPtr.h"
#include "DB/ImageInfoList.h"
#include "DB/MediaCount.h"
#include <DB/FileNameList.h>
class QProgressBar;
namespace DB
{
class CategoryCollection;
class Category;
class MD5Map;
class MemberMap;
class ImageDateCollection;
class IdList;
class Id;
class ImageSearchInfo;
class FileName;
class ImageDB :public QObject {
Q_OBJECT
public:
static ImageDB* instance();
static void setupXMLDB( const QString& configFile );
static void deleteInstance();
DB::FileNameSet imagesWithMD5Changed();
public slots:
void setDateRange( const ImageDate&, bool includeFuzzyCounts );
void clearDateRange();
virtual void slotRescan();
void slotRecalcCheckSums(const DB::FileNameList& selection);
virtual MediaCount count( const ImageSearchInfo& info );
virtual void slotReread( const DB::FileNameList& list, DB::ExifMode mode);
protected:
ImageDate _selectionRange;
bool _includeFuzzyCounts;
ImageInfoList _clipboard;
private:
static void connectSlots();
static ImageDB* _instance;
protected:
ImageDB();
public:
static QString NONE();
DB::FileNameList currentScope(bool requireOnDisk) const;
virtual DB::FileName findFirstItemInRange(
const FileNameList& images,
const ImageDate& range,
bool includeRanges) const;
public: // Methods that must be overridden
virtual uint totalCount() const = 0;
virtual DB::FileNameList search(const ImageSearchInfo&, bool requireOnDisk=false) const = 0;
virtual void renameCategory( const QString& oldName, const QString newName ) = 0;
virtual QMap<QString,uint> classify( const ImageSearchInfo& info, const QString & category, MediaType typemask ) = 0;
virtual FileNameList images() = 0;
virtual void addImages( const ImageInfoList& images ) = 0;
/** @short Update file name stored in the DB */
virtual void renameImage( const ImageInfoPtr info, const DB::FileName& newName ) = 0;
virtual void addToBlockList(const DB::FileNameList& list) = 0;
virtual bool isBlocking( const DB::FileName& fileName ) = 0;
virtual void deleteList(const DB::FileNameList& list) = 0;
virtual ImageInfoPtr info( const DB::FileName& fileName ) const = 0;
virtual MemberMap& memberMap() = 0;
virtual void save( const QString& fileName, bool isAutoSave ) = 0;
virtual MD5Map* md5Map() = 0;
virtual void sortAndMergeBackIn(const DB::FileNameList& list) = 0;
virtual CategoryCollection* categoryCollection() = 0;
virtual KSharedPtr<ImageDateCollection> rangeCollection() = 0;
/**
* Reorder the items in the database by placing all the items given in
* cutList directly before or after the given item.
* If the parameter "after" determines where to place it.
*/
virtual void reorder(const DB::FileName& item, const DB::FileNameList& cutList, bool after) = 0;
/** @short Create a stack of images/videos/whatever
*
* If the specified images already belong to different stacks, then no
* change happens and the function returns false.
*
* If some of them are in one stack and others aren't stacked at all, then
* the unstacked will be added to the existing stack and we return true.
*
* If none of them are stacked, then a new stack is created and we return
* true.
*
* All images which previously weren't in the stack are added in order they
* are present in the provided list and after all items that are already in
* the stack. The order of images which were already in the stack is not
* changed.
* */
virtual bool stack(const DB::FileNameList& items) = 0;
/** @short Remove all images from whichever stacks they might be in
*
* We might destroy some stacks in the process if they become empty or just
* containing one image.
*
* This function doesn't touch the order of images at all.
* */
virtual void unstack(const DB::FileNameList& images) = 0;
/** @short Return a list of images which are in the same stack as the one specified.
*
* Returns an empty list when the image is not stacked.
*
* They are returned sorted according to their stackOrder.
* */
virtual DB::FileNameList getStackFor(const DB::FileName& referenceId) const = 0;
virtual void copyData( const DB::FileName& from, const DB::FileName& to) = 0;
protected slots:
virtual void lockDB( bool lock, bool exclude ) = 0;
void markDirty();
signals:
void totalChanged( uint );
void dirty();
void imagesDeleted( const DB::FileNameList& );
};
}
#endif /* IMAGEDB_H */
// vi:expandtab:tabstop=4 shiftwidth=4:
| Df458/kphotoalbum-multitags-branch | DB/ImageDB.h | C | gpl-2.0 | 5,535 |
/***************************************************************************\
* Copyright (C) 2006 by Nestal Wan *
* me@nestal.net *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; version 2. *
* *
* 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. *
\***************************************************************************/
/** \file FontDescriptor.cc
\brief implementation of the FontDescriptor class
\date Jan 16, 2010
\author Nestal Wan
*/
#include "FontDescriptor.hh"
#include "FontException.hh"
#include "FontSubsetInfo.hh"
#include "subset/Sfnt.hh"
#include "core/Array.hh"
#include "core/Dictionary.hh"
#include "file/File.hh"
#include "file/DictReader.hh"
#include "stream/Stream.hh"
#include "util/CArray.hh"
#include "util/Debug.hh"
// freetype headers
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_TRUETYPE_IDS_H
#include FT_TRUETYPE_TABLES_H
#include <boost/format.hpp>
#include <iostream>
#include <iterator>
#include <fstream>
namespace pdf {
const Name FontDescriptor::m_stretch_names[] =
{
"padding", ///< to match the OS/2 table in truetype font enum
"UltraCondensed", ///< usWidthClass: 1
"ExtraCondensed", ///< usWidthClass: 2
"Condensed", ///< usWidthClass: 3
"SemiCondensed", ///< usWidthClass: 4
"Normal", ///< usWidthClass: 5
"SemiExpanded", ///< usWidthClass: 6
"Expanded", ///< usWidthClass: 7
"ExtraExpanded", ///< usWidthClass: 8
"UltraExpanded", ///< usWidthClass: 9
} ;
/** \internal constructor
*/
FontDescriptor::FontDescriptor( )
: m_stretch( font::normal_width )
, m_weight( 400 ) // 400 means normal
, m_flags( 0 )
{
m_ascent = m_descent = m_leading = m_cap_height = m_x_height =
m_stemv = m_stemh = m_avg_width = m_max_width = m_miss_width = 0 ;
m_length1 = m_length2 = m_length3 = 0 ;
}
FontDescriptor::FontDescriptor( DictReader& self )
: m_stretch( font::normal_width )
, m_weight( 400 ) // 400 means normal
, m_flags( 0 )
{
m_ascent = m_descent = m_leading = m_cap_height = m_x_height =
m_stemv = m_stemh = m_avg_width = m_max_width = m_miss_width = 0 ;
m_length1 = m_length2 = m_length3 = 0 ;
Read( self ) ;
}
FontDescriptor::FontDescriptor( FT_Face face, std::vector<unsigned char>& prog )
: m_stretch( font::normal_width )
, m_weight( 400 ) // 400 means normal
, m_flags( GetFlag( face ) )
{
m_ascent = m_descent = m_leading = m_cap_height = m_x_height =
m_stemv = m_stemh = m_avg_width = m_max_width = m_miss_width = 0 ;
m_length1 = m_length2 = m_length3 = 0 ;
PDF_ASSERT( face != 0 ) ;
m_length1 = m_length2 = m_length3 = 0 ;
TT_OS2 *os2 = reinterpret_cast<TT_OS2*>(
FT_Get_Sfnt_Table( face, ft_sfnt_os2 ) ) ;
TT_Postscript *post = reinterpret_cast<TT_Postscript*>(
FT_Get_Sfnt_Table( face, ft_sfnt_post ) ) ;
const char *psname = FT_Get_Postscript_Name( face ) ;
m_psname = psname ? psname : "" ;
m_ascent = FontUnit(face->ascender, face) ;
m_descent = FontUnit(face->descender, face) ;
m_leading = 0 ; // TODO: see other implementation
m_stemv = 70.0 ; // TODO: verify?
if ( os2 != 0 )
{
// prefer to use OS/2 table if present
m_ascent = FontUnit(os2->sTypoAscender, face) ;
m_descent = FontUnit(os2->sTypoDescender, face) ;
m_cap_height = FontUnit( os2->version == 0x0002
? os2->sCapHeight
: os2->sTypoAscender,
face ) ; // arbitrary
// optional
m_x_height = FontUnit(os2->version == 0x0002
? os2->sxHeight
: 0.0,
face ) ;
m_avg_width = FontUnit(os2->xAvgCharWidth != 0
? os2->xAvgCharWidth
: 0.0,
face ) ;
// I don't know how to get this one
m_stemv = (os2->usWeightClass/65.0) * (os2->usWeightClass/65.0)+ 50;
// we define the Width enum to suit the usWidthClass field
m_stretch = static_cast<font::Width>( os2->usWidthClass ) ;
}
double x_min = FontUnit( face->bbox.xMin, face ) ;
double x_max = FontUnit( face->bbox.xMax, face ) ;
double y_min = FontUnit( face->bbox.yMin, face ) ;
double y_max = FontUnit( face->bbox.yMax, face ) ;
m_bbox = Rect( x_min, y_min, x_max, y_max ) ;
m_italic_angle = (post != 0 ? FontUnit(post->italicAngle, face) : 0.0) ;
m_leading = 0.0 ;
// steal the buffer. if we don't steal it, then it will be destroyed later.
// then the FT_Face will become invalid.
m_font_file.swap( prog ) ;
font::Type type = font::GetType( face ) ;
if ( type == font::type1 )
{
InitType1Lengths( ) ;
}
}
void FontDescriptor::InitType1Lengths( )
{
unsigned char eexec[] = "eexec" ;
std::size_t eexec_len = Count( eexec ) - 1 ;
std::vector<unsigned char>::const_iterator len1 =
std::search(
m_font_file.begin(),
m_font_file.end(),
eexec,
eexec + eexec_len ) ;
if ( len1 != m_font_file.end() )
m_length1 = len1 - m_font_file.begin() + eexec_len ;
unsigned char cleartomark[] = "cleartomark" ;
std::size_t cleartomark_len = Count( cleartomark ) - 1 ;
std::vector<unsigned char>::const_iterator len2 =
std::search(
m_font_file.begin(),
m_font_file.end(),
cleartomark,
cleartomark + cleartomark_len ) ;
if ( m_length1 > 0 && len2 != m_font_file.end() )
{
m_length2 = len2 - m_font_file.begin( ) - 520 - m_length1 ;
m_length3 = 520 ;
}
}
std::bitset<32> FontDescriptor::GetFlag( FT_FaceRec_ *face )
{
// TODO: use some real flags
std::bitset<32> r ;
r[nonsymbolic] = 1 ;
return r ;
}
/// Read the font descriptor from file.
void FontDescriptor::Read( DictReader& reader )
{
// font file can be in FontFile, FontFile2 or 3, depending on font type
Stream prog ;
// type1 font program is embbeded in the "FontFile" stream.
if ( reader.Detach( "FontFile", prog ) )
{
Dictionary prog_dict = prog.Self() ;
DictReader prog_reader( prog_dict, reader.GetFile() ) ;
// it has has 3 different lengths
if ( !prog_reader.Detach( "Length1", m_length1 ) ||
!prog_reader.Detach( "Length2", m_length2 ) ||
!prog_reader.Detach( "Length3", m_length3 ) )
throw FontException()
<< expt::ErrMsg( "missing length for type 1 font" ) ;
}
// truetype font program is embbeded in the "FontFile2" stream
else if ( reader.Detach( "FontFile2", prog ) )
{
}
// CFF and open type are in "FontFile3"
else if ( reader.Detach( "FontFile3", prog ) )
{
}
prog.CopyData( m_font_file ) ;
// optional font family name. normally empty for embedded font
reader.Detach( "FontFamily", m_family ) ;
Name stretch ;
if ( reader.Detach( "FontStretch", stretch ) )
m_stretch = static_cast<font::Width>(std::find(
Begin(m_stretch_names),
End(m_stretch_names),
stretch ) - Begin(m_stretch_names) ) ;
reader.Detach( "FontWeight", m_weight ) ;
int flags ;
if ( reader.Detach( "Flags", flags ) )
m_flags = flags ;
reader.Detach( "FontBBox", m_bbox ) ;
reader.Detach( "ItalicAngle", m_italic_angle ) ;
reader.Detach( "Ascent", m_ascent ) ;
reader.Detach( "Descent", m_descent ) ;
reader.Detach( "Leading", m_leading ) ;
reader.Detach( "CapHeight", m_cap_height ) ;
reader.Detach( "XHeight", m_x_height ) ;
reader.Detach( "StemV", m_stemv ) ;
reader.Detach( "StemH", m_stemh ) ;
reader.Detach( "AvgWidth", m_avg_width ) ;
reader.Detach( "MaxWidth", m_max_width ) ;
reader.Detach( "MissingWidth", m_miss_width ) ;
Name psname ;
if ( reader.Detach( "FontName", psname) )
m_psname = psname.Str() ;
}
Stream FontDescriptor::WriteTrueTypeFont(
FT_FaceRec_ *face,
const std::vector<long>& glyphs ) const
{
PDF_ASSERT( FT_IS_SFNT( face ) ) ;
std::size_t size = m_font_file.size() ;
Stream s( Stream::deflate ) ;
// write the whole font
if ( glyphs.empty() )
s.Append( &m_font_file[0], m_font_file.size() ) ;
// write font subset
else
{
Sfnt sfnt( face ) ;
std::vector<uchar> subset = sfnt.CreateSubset(
&glyphs[0], glyphs.size() ) ;
s.Append( &subset[0], subset.size() ) ;
size = subset.size( ) ;
}
s.Flush( ) ;
// Length1 indicates original uncompressed size
Dictionary& sdict = s.Self() ;
sdict.insert( std::make_pair( "Length1", size ) ) ;
return s ;
}
Ref FontDescriptor::Write(
File *file,
const std::vector<long>& glyphs,
FT_FaceRec_ *face ) const
{
PDF_ASSERT( file != 0 ) ;
Dictionary self ;
if ( !m_psname.empty() )
self.insert( "FontName", Name(m_psname) ) ;
if ( !m_family.empty() )
self.insert( "Family", m_family ) ;
self.insert( "Ascent", m_ascent ) ;
self.insert( "Descent", m_descent ) ;
self.insert( "CapHeight", m_cap_height ) ;
self.insert( "StemV", m_stemv ) ;
self.insert( "Flags", static_cast<int>( m_flags.to_ulong() ) ) ;
self.insert( "Type", Name("FontDescriptor") ) ;
self.insert( "ItalicAngle", 0 ) ;
if ( m_x_height != 0.0 )
self.insert( "XHeight", m_x_height ) ;
self.insert( "FontBBox", m_bbox ) ;
if ( !m_font_file.empty() )
{
font::Type type = font::GetType( face ) ;
if ( type == font::truetype )
{
Stream ttf = WriteTrueTypeFont( face, glyphs ) ;
self.insert( "FontFile2", file->WriteObj( ttf ) ) ;
}
else
{
Stream s( Stream::deflate ) ;
s.Append( &m_font_file[0], m_font_file.size() ) ;
s.Flush( ) ;
Name prog_key ;
Dictionary& sdict = s.Self() ;
if ( type == font::type1 )
{
sdict.insert( std::make_pair( "Length1", m_length1 ) ) ;
sdict.insert( std::make_pair( "Length2", m_length2 ) ) ;
sdict.insert( std::make_pair( "Length3", m_length3 ) ) ;
prog_key = "FontFile" ;
}
else if ( type == font::opentype_cff )
{
sdict.insert( std::make_pair( "Subtype", Name("OpenType") ) ) ;
prog_key = "FontFile3" ;
}
else if ( type == font::type2 )
{
sdict.insert( std::make_pair( "Subtype", Name("Type1C") ) ) ;
prog_key = "FontFile3" ;
}
else
throw Unsupported( )
<< expt::ErrMsg( "unsupported font type" )
<< expt::Index( type ) ;
self.insert( prog_key, file->WriteObj( s ) ) ;
}
}
if ( m_stretch >= font::ultra_condensed &&
m_stretch <= font::ultra_expanded )
self.insert( "Stretch", m_stretch_names[m_stretch] ) ;
return file->WriteObj( self ) ;
}
const std::vector<unsigned char>& FontDescriptor::FontFile( ) const
{
return m_font_file ;
}
std::string FontDescriptor::Family( ) const
{
return m_family ;
}
double FontDescriptor::FontUnit( double val, FT_Face face )
{
PDF_ASSERT( face != 0 ) ;
return val * 1000.0 / face->units_per_EM ;
}
bool FontDescriptor::IsSymbolic() const
{
return m_flags[symbolic] ;
}
} // end of namespace
| match41/sumpdf | libpdfdoc/src/font/FontDescriptor.cc | C++ | gpl-2.0 | 11,466 |
using System.Collections.Generic;
using System.Diagnostics;
using System;
namespace SenseNet.Tools.EventLogCreator
{
internal class EventLogDeployer
{
private string _machineName = ".";
private int _logSizeInMegaBytes = 15;
public int LogSizeInMegaBytes
{
get
{
return this._logSizeInMegaBytes;
}
set
{
this._logSizeInMegaBytes = value;
}
}
string _logName;
public string LogName
{
get
{
return this._logName;
}
}
IEnumerable<string> _sources;
public IEnumerable<string> Sources
{
get
{
return this._sources;
}
}
public EventLogDeployer(string logName, IEnumerable<string> sources)
{
_logName = logName;
_sources = sources;
}
public EventLogDeployer(string logName, IEnumerable<string> sources, string machineName) : this(logName, sources)
{
_machineName = machineName;
}
private void DeleteSource(string source)
{
string sourceBelongsToLog = EventLog.LogNameFromSourceName(source, _machineName);
if (sourceBelongsToLog != _logName)
{
Console.WriteLine("Skipping '{0}' - it belongs to log '{1}' rather than '{2}'.", source, sourceBelongsToLog, _logName);
return;
}
EventLog.DeleteEventSource(source, _machineName);
}
public void Delete()
{
string builtInSourceName = string.Concat(_logName, "Instrumentation");
bool sourcesContainedBuildIn = false;
// create sources
foreach (string source in _sources)
{
DeleteSource(source);
if (source == builtInSourceName)
sourcesContainedBuildIn = true;
}
if (!sourcesContainedBuildIn)
{
DeleteSource(builtInSourceName);
}
if (EventLog.Exists(_logName, _machineName))
{
EventLog.Delete(_logName, _machineName);
}
}
private void CreateSource(string source)
{
string sourceBelongsToLog = EventLog.LogNameFromSourceName(source, _machineName);
if (sourceBelongsToLog != string.Empty)
{
Console.WriteLine("Skipping '{0}' - source belongs to log '{1}' already.", source, sourceBelongsToLog);
return;
}
EventLog.CreateEventSource(source, _logName, _machineName);
}
public void Create()
{
string builtInSourceName = string.Concat(_logName, "Instrumentation");
bool sourcesContainedBuildIn = false;
// create sources
foreach (string source in _sources)
{
CreateSource(source);
if (source == builtInSourceName)
sourcesContainedBuildIn = true;
}
if (!sourcesContainedBuildIn)
{
CreateSource(builtInSourceName);
}
using (EventLog eventLog = new EventLog(_logName, _machineName, builtInSourceName))
{
eventLog.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 14);
eventLog.MaximumKilobytes = _logSizeInMegaBytes * 1024;
eventLog.WriteEntry("Log created.", EventLogEntryType.Information);
eventLog.Dispose();
}
}
}
} | vlslavik/SenseNet | Source/SenseNet/Tools/EventLogCreator/EventLogDeployer.cs | C# | gpl-2.0 | 2,859 |
/*
* This file is part of the Chelsio T4 Ethernet driver for Linux.
*
* Copyright (c) 2009-2010 Chelsio Communications, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef _T4FW_INTERFACE_H_
#define _T4FW_INTERFACE_H_
enum fw_retval {
FW_SUCCESS = 0, /* completed sucessfully */
FW_EPERM = 1, /* operation not permitted */
FW_ENOENT = 2, /* no such file or directory */
FW_EIO = 5, /* input/output error; hw bad */
FW_ENOEXEC = 8, /* exec format error; inv microcode */
FW_EAGAIN = 11, /* try again */
FW_ENOMEM = 12, /* out of memory */
FW_EFAULT = 14, /* bad address; fw bad */
FW_EBUSY = 16, /* resource busy */
FW_EEXIST = 17, /* file exists */
FW_EINVAL = 22, /* invalid argument */
FW_ENOSPC = 28, /* no space left on device */
FW_ENOSYS = 38, /* functionality not implemented */
FW_EPROTO = 71, /* protocol error */
FW_EADDRINUSE = 98, /* address already in use */
FW_EADDRNOTAVAIL = 99, /* cannot assigned requested address */
FW_ENETDOWN = 100, /* network is down */
FW_ENETUNREACH = 101, /* network is unreachable */
FW_ENOBUFS = 105, /* no buffer space available */
FW_ETIMEDOUT = 110, /* timeout */
FW_EINPROGRESS = 115, /* fw internal */
FW_SCSI_ABORT_REQUESTED = 128, /* */
FW_SCSI_ABORT_TIMEDOUT = 129, /* */
FW_SCSI_ABORTED = 130, /* */
FW_SCSI_CLOSE_REQUESTED = 131, /* */
FW_ERR_LINK_DOWN = 132, /* */
FW_RDEV_NOT_READY = 133, /* */
FW_ERR_RDEV_LOST = 134, /* */
FW_ERR_RDEV_LOGO = 135, /* */
FW_FCOE_NO_XCHG = 136, /* */
FW_SCSI_RSP_ERR = 137, /* */
FW_ERR_RDEV_IMPL_LOGO = 138, /* */
FW_SCSI_UNDER_FLOW_ERR = 139, /* */
FW_SCSI_OVER_FLOW_ERR = 140, /* */
FW_SCSI_DDP_ERR = 141, /* DDP error*/
FW_SCSI_TASK_ERR = 142, /* No SCSI tasks available */
};
#define FW_T4VF_SGE_BASE_ADDR 0x0000
#define FW_T4VF_MPS_BASE_ADDR 0x0100
#define FW_T4VF_PL_BASE_ADDR 0x0200
#define FW_T4VF_MBDATA_BASE_ADDR 0x0240
#define FW_T4VF_CIM_BASE_ADDR 0x0300
enum fw_wr_opcodes {
FW_FILTER_WR = 0x02,
FW_ULPTX_WR = 0x04,
FW_TP_WR = 0x05,
FW_ETH_TX_PKT_WR = 0x08,
FW_OFLD_CONNECTION_WR = 0x2f,
FW_FLOWC_WR = 0x0a,
FW_OFLD_TX_DATA_WR = 0x0b,
FW_CMD_WR = 0x10,
FW_ETH_TX_PKT_VM_WR = 0x11,
FW_RI_RES_WR = 0x0c,
FW_RI_INIT_WR = 0x0d,
FW_RI_RDMA_WRITE_WR = 0x14,
FW_RI_SEND_WR = 0x15,
FW_RI_RDMA_READ_WR = 0x16,
FW_RI_RECV_WR = 0x17,
FW_RI_BIND_MW_WR = 0x18,
FW_RI_FR_NSMR_WR = 0x19,
FW_RI_INV_LSTAG_WR = 0x1a,
FW_LASTC2E_WR = 0x40
};
struct fw_wr_hdr {
__be32 hi;
__be32 lo;
};
#define FW_WR_OP(x) ((x) << 24)
#define FW_WR_OP_GET(x) (((x) >> 24) & 0xff)
#define FW_WR_ATOMIC(x) ((x) << 23)
#define FW_WR_FLUSH(x) ((x) << 22)
#define FW_WR_COMPL(x) ((x) << 21)
#define FW_WR_IMMDLEN_MASK 0xff
#define FW_WR_IMMDLEN(x) ((x) << 0)
#define FW_WR_EQUIQ (1U << 31)
#define FW_WR_EQUEQ (1U << 30)
#define FW_WR_FLOWID(x) ((x) << 8)
#define FW_WR_LEN16(x) ((x) << 0)
#define HW_TPL_FR_MT_PR_IV_P_FC 0X32B
#define HW_TPL_FR_MT_PR_OV_P_FC 0X327
/* filter wr reply code in cookie in CPL_SET_TCB_RPL */
enum fw_filter_wr_cookie {
FW_FILTER_WR_SUCCESS,
FW_FILTER_WR_FLT_ADDED,
FW_FILTER_WR_FLT_DELETED,
FW_FILTER_WR_SMT_TBL_FULL,
FW_FILTER_WR_EINVAL,
};
struct fw_filter_wr {
__be32 op_pkd;
__be32 len16_pkd;
__be64 r3;
__be32 tid_to_iq;
__be32 del_filter_to_l2tix;
__be16 ethtype;
__be16 ethtypem;
__u8 frag_to_ovlan_vldm;
__u8 smac_sel;
__be16 rx_chan_rx_rpl_iq;
__be32 maci_to_matchtypem;
__u8 ptcl;
__u8 ptclm;
__u8 ttyp;
__u8 ttypm;
__be16 ivlan;
__be16 ivlanm;
__be16 ovlan;
__be16 ovlanm;
__u8 lip[16];
__u8 lipm[16];
__u8 fip[16];
__u8 fipm[16];
__be16 lp;
__be16 lpm;
__be16 fp;
__be16 fpm;
__be16 r7;
__u8 sma[6];
};
#define S_FW_FILTER_WR_TID 12
#define M_FW_FILTER_WR_TID 0xfffff
#define V_FW_FILTER_WR_TID(x) ((x) << S_FW_FILTER_WR_TID)
#define G_FW_FILTER_WR_TID(x) \
(((x) >> S_FW_FILTER_WR_TID) & M_FW_FILTER_WR_TID)
#define S_FW_FILTER_WR_RQTYPE 11
#define M_FW_FILTER_WR_RQTYPE 0x1
#define V_FW_FILTER_WR_RQTYPE(x) ((x) << S_FW_FILTER_WR_RQTYPE)
#define G_FW_FILTER_WR_RQTYPE(x) \
(((x) >> S_FW_FILTER_WR_RQTYPE) & M_FW_FILTER_WR_RQTYPE)
#define F_FW_FILTER_WR_RQTYPE V_FW_FILTER_WR_RQTYPE(1U)
#define S_FW_FILTER_WR_NOREPLY 10
#define M_FW_FILTER_WR_NOREPLY 0x1
#define V_FW_FILTER_WR_NOREPLY(x) ((x) << S_FW_FILTER_WR_NOREPLY)
#define G_FW_FILTER_WR_NOREPLY(x) \
(((x) >> S_FW_FILTER_WR_NOREPLY) & M_FW_FILTER_WR_NOREPLY)
#define F_FW_FILTER_WR_NOREPLY V_FW_FILTER_WR_NOREPLY(1U)
#define S_FW_FILTER_WR_IQ 0
#define M_FW_FILTER_WR_IQ 0x3ff
#define V_FW_FILTER_WR_IQ(x) ((x) << S_FW_FILTER_WR_IQ)
#define G_FW_FILTER_WR_IQ(x) \
(((x) >> S_FW_FILTER_WR_IQ) & M_FW_FILTER_WR_IQ)
#define S_FW_FILTER_WR_DEL_FILTER 31
#define M_FW_FILTER_WR_DEL_FILTER 0x1
#define V_FW_FILTER_WR_DEL_FILTER(x) ((x) << S_FW_FILTER_WR_DEL_FILTER)
#define G_FW_FILTER_WR_DEL_FILTER(x) \
(((x) >> S_FW_FILTER_WR_DEL_FILTER) & M_FW_FILTER_WR_DEL_FILTER)
#define F_FW_FILTER_WR_DEL_FILTER V_FW_FILTER_WR_DEL_FILTER(1U)
#define S_FW_FILTER_WR_RPTTID 25
#define M_FW_FILTER_WR_RPTTID 0x1
#define V_FW_FILTER_WR_RPTTID(x) ((x) << S_FW_FILTER_WR_RPTTID)
#define G_FW_FILTER_WR_RPTTID(x) \
(((x) >> S_FW_FILTER_WR_RPTTID) & M_FW_FILTER_WR_RPTTID)
#define F_FW_FILTER_WR_RPTTID V_FW_FILTER_WR_RPTTID(1U)
#define S_FW_FILTER_WR_DROP 24
#define M_FW_FILTER_WR_DROP 0x1
#define V_FW_FILTER_WR_DROP(x) ((x) << S_FW_FILTER_WR_DROP)
#define G_FW_FILTER_WR_DROP(x) \
(((x) >> S_FW_FILTER_WR_DROP) & M_FW_FILTER_WR_DROP)
#define F_FW_FILTER_WR_DROP V_FW_FILTER_WR_DROP(1U)
#define S_FW_FILTER_WR_DIRSTEER 23
#define M_FW_FILTER_WR_DIRSTEER 0x1
#define V_FW_FILTER_WR_DIRSTEER(x) ((x) << S_FW_FILTER_WR_DIRSTEER)
#define G_FW_FILTER_WR_DIRSTEER(x) \
(((x) >> S_FW_FILTER_WR_DIRSTEER) & M_FW_FILTER_WR_DIRSTEER)
#define F_FW_FILTER_WR_DIRSTEER V_FW_FILTER_WR_DIRSTEER(1U)
#define S_FW_FILTER_WR_MASKHASH 22
#define M_FW_FILTER_WR_MASKHASH 0x1
#define V_FW_FILTER_WR_MASKHASH(x) ((x) << S_FW_FILTER_WR_MASKHASH)
#define G_FW_FILTER_WR_MASKHASH(x) \
(((x) >> S_FW_FILTER_WR_MASKHASH) & M_FW_FILTER_WR_MASKHASH)
#define F_FW_FILTER_WR_MASKHASH V_FW_FILTER_WR_MASKHASH(1U)
#define S_FW_FILTER_WR_DIRSTEERHASH 21
#define M_FW_FILTER_WR_DIRSTEERHASH 0x1
#define V_FW_FILTER_WR_DIRSTEERHASH(x) ((x) << S_FW_FILTER_WR_DIRSTEERHASH)
#define G_FW_FILTER_WR_DIRSTEERHASH(x) \
(((x) >> S_FW_FILTER_WR_DIRSTEERHASH) & M_FW_FILTER_WR_DIRSTEERHASH)
#define F_FW_FILTER_WR_DIRSTEERHASH V_FW_FILTER_WR_DIRSTEERHASH(1U)
#define S_FW_FILTER_WR_LPBK 20
#define M_FW_FILTER_WR_LPBK 0x1
#define V_FW_FILTER_WR_LPBK(x) ((x) << S_FW_FILTER_WR_LPBK)
#define G_FW_FILTER_WR_LPBK(x) \
(((x) >> S_FW_FILTER_WR_LPBK) & M_FW_FILTER_WR_LPBK)
#define F_FW_FILTER_WR_LPBK V_FW_FILTER_WR_LPBK(1U)
#define S_FW_FILTER_WR_DMAC 19
#define M_FW_FILTER_WR_DMAC 0x1
#define V_FW_FILTER_WR_DMAC(x) ((x) << S_FW_FILTER_WR_DMAC)
#define G_FW_FILTER_WR_DMAC(x) \
(((x) >> S_FW_FILTER_WR_DMAC) & M_FW_FILTER_WR_DMAC)
#define F_FW_FILTER_WR_DMAC V_FW_FILTER_WR_DMAC(1U)
#define S_FW_FILTER_WR_SMAC 18
#define M_FW_FILTER_WR_SMAC 0x1
#define V_FW_FILTER_WR_SMAC(x) ((x) << S_FW_FILTER_WR_SMAC)
#define G_FW_FILTER_WR_SMAC(x) \
(((x) >> S_FW_FILTER_WR_SMAC) & M_FW_FILTER_WR_SMAC)
#define F_FW_FILTER_WR_SMAC V_FW_FILTER_WR_SMAC(1U)
#define S_FW_FILTER_WR_INSVLAN 17
#define M_FW_FILTER_WR_INSVLAN 0x1
#define V_FW_FILTER_WR_INSVLAN(x) ((x) << S_FW_FILTER_WR_INSVLAN)
#define G_FW_FILTER_WR_INSVLAN(x) \
(((x) >> S_FW_FILTER_WR_INSVLAN) & M_FW_FILTER_WR_INSVLAN)
#define F_FW_FILTER_WR_INSVLAN V_FW_FILTER_WR_INSVLAN(1U)
#define S_FW_FILTER_WR_RMVLAN 16
#define M_FW_FILTER_WR_RMVLAN 0x1
#define V_FW_FILTER_WR_RMVLAN(x) ((x) << S_FW_FILTER_WR_RMVLAN)
#define G_FW_FILTER_WR_RMVLAN(x) \
(((x) >> S_FW_FILTER_WR_RMVLAN) & M_FW_FILTER_WR_RMVLAN)
#define F_FW_FILTER_WR_RMVLAN V_FW_FILTER_WR_RMVLAN(1U)
#define S_FW_FILTER_WR_HITCNTS 15
#define M_FW_FILTER_WR_HITCNTS 0x1
#define V_FW_FILTER_WR_HITCNTS(x) ((x) << S_FW_FILTER_WR_HITCNTS)
#define G_FW_FILTER_WR_HITCNTS(x) \
(((x) >> S_FW_FILTER_WR_HITCNTS) & M_FW_FILTER_WR_HITCNTS)
#define F_FW_FILTER_WR_HITCNTS V_FW_FILTER_WR_HITCNTS(1U)
#define S_FW_FILTER_WR_TXCHAN 13
#define M_FW_FILTER_WR_TXCHAN 0x3
#define V_FW_FILTER_WR_TXCHAN(x) ((x) << S_FW_FILTER_WR_TXCHAN)
#define G_FW_FILTER_WR_TXCHAN(x) \
(((x) >> S_FW_FILTER_WR_TXCHAN) & M_FW_FILTER_WR_TXCHAN)
#define S_FW_FILTER_WR_PRIO 12
#define M_FW_FILTER_WR_PRIO 0x1
#define V_FW_FILTER_WR_PRIO(x) ((x) << S_FW_FILTER_WR_PRIO)
#define G_FW_FILTER_WR_PRIO(x) \
(((x) >> S_FW_FILTER_WR_PRIO) & M_FW_FILTER_WR_PRIO)
#define F_FW_FILTER_WR_PRIO V_FW_FILTER_WR_PRIO(1U)
#define S_FW_FILTER_WR_L2TIX 0
#define M_FW_FILTER_WR_L2TIX 0xfff
#define V_FW_FILTER_WR_L2TIX(x) ((x) << S_FW_FILTER_WR_L2TIX)
#define G_FW_FILTER_WR_L2TIX(x) \
(((x) >> S_FW_FILTER_WR_L2TIX) & M_FW_FILTER_WR_L2TIX)
#define S_FW_FILTER_WR_FRAG 7
#define M_FW_FILTER_WR_FRAG 0x1
#define V_FW_FILTER_WR_FRAG(x) ((x) << S_FW_FILTER_WR_FRAG)
#define G_FW_FILTER_WR_FRAG(x) \
(((x) >> S_FW_FILTER_WR_FRAG) & M_FW_FILTER_WR_FRAG)
#define F_FW_FILTER_WR_FRAG V_FW_FILTER_WR_FRAG(1U)
#define S_FW_FILTER_WR_FRAGM 6
#define M_FW_FILTER_WR_FRAGM 0x1
#define V_FW_FILTER_WR_FRAGM(x) ((x) << S_FW_FILTER_WR_FRAGM)
#define G_FW_FILTER_WR_FRAGM(x) \
(((x) >> S_FW_FILTER_WR_FRAGM) & M_FW_FILTER_WR_FRAGM)
#define F_FW_FILTER_WR_FRAGM V_FW_FILTER_WR_FRAGM(1U)
#define S_FW_FILTER_WR_IVLAN_VLD 5
#define M_FW_FILTER_WR_IVLAN_VLD 0x1
#define V_FW_FILTER_WR_IVLAN_VLD(x) ((x) << S_FW_FILTER_WR_IVLAN_VLD)
#define G_FW_FILTER_WR_IVLAN_VLD(x) \
(((x) >> S_FW_FILTER_WR_IVLAN_VLD) & M_FW_FILTER_WR_IVLAN_VLD)
#define F_FW_FILTER_WR_IVLAN_VLD V_FW_FILTER_WR_IVLAN_VLD(1U)
#define S_FW_FILTER_WR_OVLAN_VLD 4
#define M_FW_FILTER_WR_OVLAN_VLD 0x1
#define V_FW_FILTER_WR_OVLAN_VLD(x) ((x) << S_FW_FILTER_WR_OVLAN_VLD)
#define G_FW_FILTER_WR_OVLAN_VLD(x) \
(((x) >> S_FW_FILTER_WR_OVLAN_VLD) & M_FW_FILTER_WR_OVLAN_VLD)
#define F_FW_FILTER_WR_OVLAN_VLD V_FW_FILTER_WR_OVLAN_VLD(1U)
#define S_FW_FILTER_WR_IVLAN_VLDM 3
#define M_FW_FILTER_WR_IVLAN_VLDM 0x1
#define V_FW_FILTER_WR_IVLAN_VLDM(x) ((x) << S_FW_FILTER_WR_IVLAN_VLDM)
#define G_FW_FILTER_WR_IVLAN_VLDM(x) \
(((x) >> S_FW_FILTER_WR_IVLAN_VLDM) & M_FW_FILTER_WR_IVLAN_VLDM)
#define F_FW_FILTER_WR_IVLAN_VLDM V_FW_FILTER_WR_IVLAN_VLDM(1U)
#define S_FW_FILTER_WR_OVLAN_VLDM 2
#define M_FW_FILTER_WR_OVLAN_VLDM 0x1
#define V_FW_FILTER_WR_OVLAN_VLDM(x) ((x) << S_FW_FILTER_WR_OVLAN_VLDM)
#define G_FW_FILTER_WR_OVLAN_VLDM(x) \
(((x) >> S_FW_FILTER_WR_OVLAN_VLDM) & M_FW_FILTER_WR_OVLAN_VLDM)
#define F_FW_FILTER_WR_OVLAN_VLDM V_FW_FILTER_WR_OVLAN_VLDM(1U)
#define S_FW_FILTER_WR_RX_CHAN 15
#define M_FW_FILTER_WR_RX_CHAN 0x1
#define V_FW_FILTER_WR_RX_CHAN(x) ((x) << S_FW_FILTER_WR_RX_CHAN)
#define G_FW_FILTER_WR_RX_CHAN(x) \
(((x) >> S_FW_FILTER_WR_RX_CHAN) & M_FW_FILTER_WR_RX_CHAN)
#define F_FW_FILTER_WR_RX_CHAN V_FW_FILTER_WR_RX_CHAN(1U)
#define S_FW_FILTER_WR_RX_RPL_IQ 0
#define M_FW_FILTER_WR_RX_RPL_IQ 0x3ff
#define V_FW_FILTER_WR_RX_RPL_IQ(x) ((x) << S_FW_FILTER_WR_RX_RPL_IQ)
#define G_FW_FILTER_WR_RX_RPL_IQ(x) \
(((x) >> S_FW_FILTER_WR_RX_RPL_IQ) & M_FW_FILTER_WR_RX_RPL_IQ)
#define S_FW_FILTER_WR_MACI 23
#define M_FW_FILTER_WR_MACI 0x1ff
#define V_FW_FILTER_WR_MACI(x) ((x) << S_FW_FILTER_WR_MACI)
#define G_FW_FILTER_WR_MACI(x) \
(((x) >> S_FW_FILTER_WR_MACI) & M_FW_FILTER_WR_MACI)
#define S_FW_FILTER_WR_MACIM 14
#define M_FW_FILTER_WR_MACIM 0x1ff
#define V_FW_FILTER_WR_MACIM(x) ((x) << S_FW_FILTER_WR_MACIM)
#define G_FW_FILTER_WR_MACIM(x) \
(((x) >> S_FW_FILTER_WR_MACIM) & M_FW_FILTER_WR_MACIM)
#define S_FW_FILTER_WR_FCOE 13
#define M_FW_FILTER_WR_FCOE 0x1
#define V_FW_FILTER_WR_FCOE(x) ((x) << S_FW_FILTER_WR_FCOE)
#define G_FW_FILTER_WR_FCOE(x) \
(((x) >> S_FW_FILTER_WR_FCOE) & M_FW_FILTER_WR_FCOE)
#define F_FW_FILTER_WR_FCOE V_FW_FILTER_WR_FCOE(1U)
#define S_FW_FILTER_WR_FCOEM 12
#define M_FW_FILTER_WR_FCOEM 0x1
#define V_FW_FILTER_WR_FCOEM(x) ((x) << S_FW_FILTER_WR_FCOEM)
#define G_FW_FILTER_WR_FCOEM(x) \
(((x) >> S_FW_FILTER_WR_FCOEM) & M_FW_FILTER_WR_FCOEM)
#define F_FW_FILTER_WR_FCOEM V_FW_FILTER_WR_FCOEM(1U)
#define S_FW_FILTER_WR_PORT 9
#define M_FW_FILTER_WR_PORT 0x7
#define V_FW_FILTER_WR_PORT(x) ((x) << S_FW_FILTER_WR_PORT)
#define G_FW_FILTER_WR_PORT(x) \
(((x) >> S_FW_FILTER_WR_PORT) & M_FW_FILTER_WR_PORT)
#define S_FW_FILTER_WR_PORTM 6
#define M_FW_FILTER_WR_PORTM 0x7
#define V_FW_FILTER_WR_PORTM(x) ((x) << S_FW_FILTER_WR_PORTM)
#define G_FW_FILTER_WR_PORTM(x) \
(((x) >> S_FW_FILTER_WR_PORTM) & M_FW_FILTER_WR_PORTM)
#define S_FW_FILTER_WR_MATCHTYPE 3
#define M_FW_FILTER_WR_MATCHTYPE 0x7
#define V_FW_FILTER_WR_MATCHTYPE(x) ((x) << S_FW_FILTER_WR_MATCHTYPE)
#define G_FW_FILTER_WR_MATCHTYPE(x) \
(((x) >> S_FW_FILTER_WR_MATCHTYPE) & M_FW_FILTER_WR_MATCHTYPE)
#define S_FW_FILTER_WR_MATCHTYPEM 0
#define M_FW_FILTER_WR_MATCHTYPEM 0x7
#define V_FW_FILTER_WR_MATCHTYPEM(x) ((x) << S_FW_FILTER_WR_MATCHTYPEM)
#define G_FW_FILTER_WR_MATCHTYPEM(x) \
(((x) >> S_FW_FILTER_WR_MATCHTYPEM) & M_FW_FILTER_WR_MATCHTYPEM)
struct fw_ulptx_wr {
__be32 op_to_compl;
__be32 flowid_len16;
u64 cookie;
};
struct fw_tp_wr {
__be32 op_to_immdlen;
__be32 flowid_len16;
u64 cookie;
};
struct fw_eth_tx_pkt_wr {
__be32 op_immdlen;
__be32 equiq_to_len16;
__be64 r3;
};
struct fw_ofld_connection_wr {
__be32 op_compl;
__be32 len16_pkd;
__u64 cookie;
__be64 r2;
__be64 r3;
struct fw_ofld_connection_le {
__be32 version_cpl;
__be32 filter;
__be32 r1;
__be16 lport;
__be16 pport;
union fw_ofld_connection_leip {
struct fw_ofld_connection_le_ipv4 {
__be32 pip;
__be32 lip;
__be64 r0;
__be64 r1;
__be64 r2;
} ipv4;
struct fw_ofld_connection_le_ipv6 {
__be64 pip_hi;
__be64 pip_lo;
__be64 lip_hi;
__be64 lip_lo;
} ipv6;
} u;
} le;
struct fw_ofld_connection_tcb {
__be32 t_state_to_astid;
__be16 cplrxdataack_cplpassacceptrpl;
__be16 rcv_adv;
__be32 rcv_nxt;
__be32 tx_max;
__be64 opt0;
__be32 opt2;
__be32 r1;
__be64 r2;
__be64 r3;
} tcb;
};
#define S_FW_OFLD_CONNECTION_WR_VERSION 31
#define M_FW_OFLD_CONNECTION_WR_VERSION 0x1
#define V_FW_OFLD_CONNECTION_WR_VERSION(x) \
((x) << S_FW_OFLD_CONNECTION_WR_VERSION)
#define G_FW_OFLD_CONNECTION_WR_VERSION(x) \
(((x) >> S_FW_OFLD_CONNECTION_WR_VERSION) & \
M_FW_OFLD_CONNECTION_WR_VERSION)
#define F_FW_OFLD_CONNECTION_WR_VERSION \
V_FW_OFLD_CONNECTION_WR_VERSION(1U)
#define S_FW_OFLD_CONNECTION_WR_CPL 30
#define M_FW_OFLD_CONNECTION_WR_CPL 0x1
#define V_FW_OFLD_CONNECTION_WR_CPL(x) ((x) << S_FW_OFLD_CONNECTION_WR_CPL)
#define G_FW_OFLD_CONNECTION_WR_CPL(x) \
(((x) >> S_FW_OFLD_CONNECTION_WR_CPL) & M_FW_OFLD_CONNECTION_WR_CPL)
#define F_FW_OFLD_CONNECTION_WR_CPL V_FW_OFLD_CONNECTION_WR_CPL(1U)
#define S_FW_OFLD_CONNECTION_WR_T_STATE 28
#define M_FW_OFLD_CONNECTION_WR_T_STATE 0xf
#define V_FW_OFLD_CONNECTION_WR_T_STATE(x) \
((x) << S_FW_OFLD_CONNECTION_WR_T_STATE)
#define G_FW_OFLD_CONNECTION_WR_T_STATE(x) \
(((x) >> S_FW_OFLD_CONNECTION_WR_T_STATE) & \
M_FW_OFLD_CONNECTION_WR_T_STATE)
#define S_FW_OFLD_CONNECTION_WR_RCV_SCALE 24
#define M_FW_OFLD_CONNECTION_WR_RCV_SCALE 0xf
#define V_FW_OFLD_CONNECTION_WR_RCV_SCALE(x) \
((x) << S_FW_OFLD_CONNECTION_WR_RCV_SCALE)
#define G_FW_OFLD_CONNECTION_WR_RCV_SCALE(x) \
(((x) >> S_FW_OFLD_CONNECTION_WR_RCV_SCALE) & \
M_FW_OFLD_CONNECTION_WR_RCV_SCALE)
#define S_FW_OFLD_CONNECTION_WR_ASTID 0
#define M_FW_OFLD_CONNECTION_WR_ASTID 0xffffff
#define V_FW_OFLD_CONNECTION_WR_ASTID(x) \
((x) << S_FW_OFLD_CONNECTION_WR_ASTID)
#define G_FW_OFLD_CONNECTION_WR_ASTID(x) \
(((x) >> S_FW_OFLD_CONNECTION_WR_ASTID) & M_FW_OFLD_CONNECTION_WR_ASTID)
#define S_FW_OFLD_CONNECTION_WR_CPLRXDATAACK 15
#define M_FW_OFLD_CONNECTION_WR_CPLRXDATAACK 0x1
#define V_FW_OFLD_CONNECTION_WR_CPLRXDATAACK(x) \
((x) << S_FW_OFLD_CONNECTION_WR_CPLRXDATAACK)
#define G_FW_OFLD_CONNECTION_WR_CPLRXDATAACK(x) \
(((x) >> S_FW_OFLD_CONNECTION_WR_CPLRXDATAACK) & \
M_FW_OFLD_CONNECTION_WR_CPLRXDATAACK)
#define F_FW_OFLD_CONNECTION_WR_CPLRXDATAACK \
V_FW_OFLD_CONNECTION_WR_CPLRXDATAACK(1U)
#define S_FW_OFLD_CONNECTION_WR_CPLPASSACCEPTRPL 14
#define M_FW_OFLD_CONNECTION_WR_CPLPASSACCEPTRPL 0x1
#define V_FW_OFLD_CONNECTION_WR_CPLPASSACCEPTRPL(x) \
((x) << S_FW_OFLD_CONNECTION_WR_CPLPASSACCEPTRPL)
#define G_FW_OFLD_CONNECTION_WR_CPLPASSACCEPTRPL(x) \
(((x) >> S_FW_OFLD_CONNECTION_WR_CPLPASSACCEPTRPL) & \
M_FW_OFLD_CONNECTION_WR_CPLPASSACCEPTRPL)
#define F_FW_OFLD_CONNECTION_WR_CPLPASSACCEPTRPL \
V_FW_OFLD_CONNECTION_WR_CPLPASSACCEPTRPL(1U)
enum fw_flowc_mnem {
FW_FLOWC_MNEM_PFNVFN, /* PFN [15:8] VFN [7:0] */
FW_FLOWC_MNEM_CH,
FW_FLOWC_MNEM_PORT,
FW_FLOWC_MNEM_IQID,
FW_FLOWC_MNEM_SNDNXT,
FW_FLOWC_MNEM_RCVNXT,
FW_FLOWC_MNEM_SNDBUF,
FW_FLOWC_MNEM_MSS,
};
struct fw_flowc_mnemval {
u8 mnemonic;
u8 r4[3];
__be32 val;
};
struct fw_flowc_wr {
__be32 op_to_nparams;
#define FW_FLOWC_WR_NPARAMS(x) ((x) << 0)
__be32 flowid_len16;
struct fw_flowc_mnemval mnemval[0];
};
struct fw_ofld_tx_data_wr {
__be32 op_to_immdlen;
__be32 flowid_len16;
__be32 plen;
__be32 tunnel_to_proxy;
#define FW_OFLD_TX_DATA_WR_TUNNEL(x) ((x) << 19)
#define FW_OFLD_TX_DATA_WR_SAVE(x) ((x) << 18)
#define FW_OFLD_TX_DATA_WR_FLUSH(x) ((x) << 17)
#define FW_OFLD_TX_DATA_WR_URGENT(x) ((x) << 16)
#define FW_OFLD_TX_DATA_WR_MORE(x) ((x) << 15)
#define FW_OFLD_TX_DATA_WR_SHOVE(x) ((x) << 14)
#define FW_OFLD_TX_DATA_WR_ULPMODE(x) ((x) << 10)
#define FW_OFLD_TX_DATA_WR_ULPSUBMODE(x) ((x) << 6)
};
struct fw_cmd_wr {
__be32 op_dma;
#define FW_CMD_WR_DMA (1U << 17)
__be32 len16_pkd;
__be64 cookie_daddr;
};
struct fw_eth_tx_pkt_vm_wr {
__be32 op_immdlen;
__be32 equiq_to_len16;
__be32 r3[2];
u8 ethmacdst[6];
u8 ethmacsrc[6];
__be16 ethtype;
__be16 vlantci;
};
#define FW_CMD_MAX_TIMEOUT 10000
/*
* If a host driver does a HELLO and discovers that there's already a MASTER
* selected, we may have to wait for that MASTER to finish issuing RESET,
* configuration and INITIALIZE commands. Also, there's a possibility that
* our own HELLO may get lost if it happens right as the MASTER is issuign a
* RESET command, so we need to be willing to make a few retries of our HELLO.
*/
#define FW_CMD_HELLO_TIMEOUT (3 * FW_CMD_MAX_TIMEOUT)
#define FW_CMD_HELLO_RETRIES 3
enum fw_cmd_opcodes {
FW_LDST_CMD = 0x01,
FW_RESET_CMD = 0x03,
FW_HELLO_CMD = 0x04,
FW_BYE_CMD = 0x05,
FW_INITIALIZE_CMD = 0x06,
FW_CAPS_CONFIG_CMD = 0x07,
FW_PARAMS_CMD = 0x08,
FW_PFVF_CMD = 0x09,
FW_IQ_CMD = 0x10,
FW_EQ_MNGT_CMD = 0x11,
FW_EQ_ETH_CMD = 0x12,
FW_EQ_CTRL_CMD = 0x13,
FW_EQ_OFLD_CMD = 0x21,
FW_VI_CMD = 0x14,
FW_VI_MAC_CMD = 0x15,
FW_VI_RXMODE_CMD = 0x16,
FW_VI_ENABLE_CMD = 0x17,
FW_ACL_MAC_CMD = 0x18,
FW_ACL_VLAN_CMD = 0x19,
FW_VI_STATS_CMD = 0x1a,
FW_PORT_CMD = 0x1b,
FW_PORT_STATS_CMD = 0x1c,
FW_PORT_LB_STATS_CMD = 0x1d,
FW_PORT_TRACE_CMD = 0x1e,
FW_PORT_TRACE_MMAP_CMD = 0x1f,
FW_RSS_IND_TBL_CMD = 0x20,
FW_RSS_GLB_CONFIG_CMD = 0x22,
FW_RSS_VI_CONFIG_CMD = 0x23,
FW_CLIP_CMD = 0x28,
FW_LASTC2E_CMD = 0x40,
FW_ERROR_CMD = 0x80,
FW_DEBUG_CMD = 0x81,
};
enum fw_cmd_cap {
FW_CMD_CAP_PF = 0x01,
FW_CMD_CAP_DMAQ = 0x02,
FW_CMD_CAP_PORT = 0x04,
FW_CMD_CAP_PORTPROMISC = 0x08,
FW_CMD_CAP_PORTSTATS = 0x10,
FW_CMD_CAP_VF = 0x80,
};
/*
* Generic command header flit0
*/
struct fw_cmd_hdr {
__be32 hi;
__be32 lo;
};
#define FW_CMD_OP(x) ((x) << 24)
#define FW_CMD_OP_GET(x) (((x) >> 24) & 0xff)
#define FW_CMD_REQUEST (1U << 23)
#define FW_CMD_REQUEST_GET(x) (((x) >> 23) & 0x1)
#define FW_CMD_READ (1U << 22)
#define FW_CMD_WRITE (1U << 21)
#define FW_CMD_EXEC (1U << 20)
#define FW_CMD_RAMASK(x) ((x) << 20)
#define FW_CMD_RETVAL(x) ((x) << 8)
#define FW_CMD_RETVAL_GET(x) (((x) >> 8) & 0xff)
#define FW_CMD_LEN16(x) ((x) << 0)
#define FW_LEN16(fw_struct) FW_CMD_LEN16(sizeof(fw_struct) / 16)
enum fw_ldst_addrspc {
FW_LDST_ADDRSPC_FIRMWARE = 0x0001,
FW_LDST_ADDRSPC_SGE_EGRC = 0x0008,
FW_LDST_ADDRSPC_SGE_INGC = 0x0009,
FW_LDST_ADDRSPC_SGE_FLMC = 0x000a,
FW_LDST_ADDRSPC_SGE_CONMC = 0x000b,
FW_LDST_ADDRSPC_TP_PIO = 0x0010,
FW_LDST_ADDRSPC_TP_TM_PIO = 0x0011,
FW_LDST_ADDRSPC_TP_MIB = 0x0012,
FW_LDST_ADDRSPC_MDIO = 0x0018,
FW_LDST_ADDRSPC_MPS = 0x0020,
FW_LDST_ADDRSPC_FUNC = 0x0028,
FW_LDST_ADDRSPC_FUNC_PCIE = 0x0029,
};
enum fw_ldst_mps_fid {
FW_LDST_MPS_ATRB,
FW_LDST_MPS_RPLC
};
enum fw_ldst_func_access_ctl {
FW_LDST_FUNC_ACC_CTL_VIID,
FW_LDST_FUNC_ACC_CTL_FID
};
enum fw_ldst_func_mod_index {
FW_LDST_FUNC_MPS
};
struct fw_ldst_cmd {
__be32 op_to_addrspace;
#define FW_LDST_CMD_ADDRSPACE(x) ((x) << 0)
__be32 cycles_to_len16;
union fw_ldst {
struct fw_ldst_addrval {
__be32 addr;
__be32 val;
} addrval;
struct fw_ldst_idctxt {
__be32 physid;
__be32 msg_pkd;
__be32 ctxt_data7;
__be32 ctxt_data6;
__be32 ctxt_data5;
__be32 ctxt_data4;
__be32 ctxt_data3;
__be32 ctxt_data2;
__be32 ctxt_data1;
__be32 ctxt_data0;
} idctxt;
struct fw_ldst_mdio {
__be16 paddr_mmd;
__be16 raddr;
__be16 vctl;
__be16 rval;
} mdio;
struct fw_ldst_mps {
__be16 fid_ctl;
__be16 rplcpf_pkd;
__be32 rplc127_96;
__be32 rplc95_64;
__be32 rplc63_32;
__be32 rplc31_0;
__be32 atrb;
__be16 vlan[16];
} mps;
struct fw_ldst_func {
u8 access_ctl;
u8 mod_index;
__be16 ctl_id;
__be32 offset;
__be64 data0;
__be64 data1;
} func;
struct fw_ldst_pcie {
u8 ctrl_to_fn;
u8 bnum;
u8 r;
u8 ext_r;
u8 select_naccess;
u8 pcie_fn;
__be16 nset_pkd;
__be32 data[12];
} pcie;
} u;
};
#define FW_LDST_CMD_MSG(x) ((x) << 31)
#define FW_LDST_CMD_PADDR(x) ((x) << 8)
#define FW_LDST_CMD_MMD(x) ((x) << 0)
#define FW_LDST_CMD_FID(x) ((x) << 15)
#define FW_LDST_CMD_CTL(x) ((x) << 0)
#define FW_LDST_CMD_RPLCPF(x) ((x) << 0)
#define FW_LDST_CMD_LC (1U << 4)
#define FW_LDST_CMD_NACCESS(x) ((x) << 0)
#define FW_LDST_CMD_FN(x) ((x) << 0)
struct fw_reset_cmd {
__be32 op_to_write;
__be32 retval_len16;
__be32 val;
__be32 halt_pkd;
};
#define FW_RESET_CMD_HALT_SHIFT 31
#define FW_RESET_CMD_HALT_MASK 0x1
#define FW_RESET_CMD_HALT(x) ((x) << FW_RESET_CMD_HALT_SHIFT)
#define FW_RESET_CMD_HALT_GET(x) \
(((x) >> FW_RESET_CMD_HALT_SHIFT) & FW_RESET_CMD_HALT_MASK)
enum fw_hellow_cmd {
fw_hello_cmd_stage_os = 0x0
};
struct fw_hello_cmd {
__be32 op_to_write;
__be32 retval_len16;
__be32 err_to_clearinit;
#define FW_HELLO_CMD_ERR (1U << 31)
#define FW_HELLO_CMD_INIT (1U << 30)
#define FW_HELLO_CMD_MASTERDIS(x) ((x) << 29)
#define FW_HELLO_CMD_MASTERFORCE(x) ((x) << 28)
#define FW_HELLO_CMD_MBMASTER_MASK 0xfU
#define FW_HELLO_CMD_MBMASTER_SHIFT 24
#define FW_HELLO_CMD_MBMASTER(x) ((x) << FW_HELLO_CMD_MBMASTER_SHIFT)
#define FW_HELLO_CMD_MBMASTER_GET(x) \
(((x) >> FW_HELLO_CMD_MBMASTER_SHIFT) & FW_HELLO_CMD_MBMASTER_MASK)
#define FW_HELLO_CMD_MBASYNCNOTINT(x) ((x) << 23)
#define FW_HELLO_CMD_MBASYNCNOT(x) ((x) << 20)
#define FW_HELLO_CMD_STAGE(x) ((x) << 17)
#define FW_HELLO_CMD_CLEARINIT (1U << 16)
__be32 fwrev;
};
struct fw_bye_cmd {
__be32 op_to_write;
__be32 retval_len16;
__be64 r3;
};
struct fw_initialize_cmd {
__be32 op_to_write;
__be32 retval_len16;
__be64 r3;
};
enum fw_caps_config_hm {
FW_CAPS_CONFIG_HM_PCIE = 0x00000001,
FW_CAPS_CONFIG_HM_PL = 0x00000002,
FW_CAPS_CONFIG_HM_SGE = 0x00000004,
FW_CAPS_CONFIG_HM_CIM = 0x00000008,
FW_CAPS_CONFIG_HM_ULPTX = 0x00000010,
FW_CAPS_CONFIG_HM_TP = 0x00000020,
FW_CAPS_CONFIG_HM_ULPRX = 0x00000040,
FW_CAPS_CONFIG_HM_PMRX = 0x00000080,
FW_CAPS_CONFIG_HM_PMTX = 0x00000100,
FW_CAPS_CONFIG_HM_MC = 0x00000200,
FW_CAPS_CONFIG_HM_LE = 0x00000400,
FW_CAPS_CONFIG_HM_MPS = 0x00000800,
FW_CAPS_CONFIG_HM_XGMAC = 0x00001000,
FW_CAPS_CONFIG_HM_CPLSWITCH = 0x00002000,
FW_CAPS_CONFIG_HM_T4DBG = 0x00004000,
FW_CAPS_CONFIG_HM_MI = 0x00008000,
FW_CAPS_CONFIG_HM_I2CM = 0x00010000,
FW_CAPS_CONFIG_HM_NCSI = 0x00020000,
FW_CAPS_CONFIG_HM_SMB = 0x00040000,
FW_CAPS_CONFIG_HM_MA = 0x00080000,
FW_CAPS_CONFIG_HM_EDRAM = 0x00100000,
FW_CAPS_CONFIG_HM_PMU = 0x00200000,
FW_CAPS_CONFIG_HM_UART = 0x00400000,
FW_CAPS_CONFIG_HM_SF = 0x00800000,
};
enum fw_caps_config_nbm {
FW_CAPS_CONFIG_NBM_IPMI = 0x00000001,
FW_CAPS_CONFIG_NBM_NCSI = 0x00000002,
};
enum fw_caps_config_link {
FW_CAPS_CONFIG_LINK_PPP = 0x00000001,
FW_CAPS_CONFIG_LINK_QFC = 0x00000002,
FW_CAPS_CONFIG_LINK_DCBX = 0x00000004,
};
enum fw_caps_config_switch {
FW_CAPS_CONFIG_SWITCH_INGRESS = 0x00000001,
FW_CAPS_CONFIG_SWITCH_EGRESS = 0x00000002,
};
enum fw_caps_config_nic {
FW_CAPS_CONFIG_NIC = 0x00000001,
FW_CAPS_CONFIG_NIC_VM = 0x00000002,
};
enum fw_caps_config_ofld {
FW_CAPS_CONFIG_OFLD = 0x00000001,
};
enum fw_caps_config_rdma {
FW_CAPS_CONFIG_RDMA_RDDP = 0x00000001,
FW_CAPS_CONFIG_RDMA_RDMAC = 0x00000002,
};
enum fw_caps_config_iscsi {
FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU = 0x00000001,
FW_CAPS_CONFIG_ISCSI_TARGET_PDU = 0x00000002,
FW_CAPS_CONFIG_ISCSI_INITIATOR_CNXOFLD = 0x00000004,
FW_CAPS_CONFIG_ISCSI_TARGET_CNXOFLD = 0x00000008,
};
enum fw_caps_config_fcoe {
FW_CAPS_CONFIG_FCOE_INITIATOR = 0x00000001,
FW_CAPS_CONFIG_FCOE_TARGET = 0x00000002,
FW_CAPS_CONFIG_FCOE_CTRL_OFLD = 0x00000004,
};
enum fw_memtype_cf {
FW_MEMTYPE_CF_EDC0 = 0x0,
FW_MEMTYPE_CF_EDC1 = 0x1,
FW_MEMTYPE_CF_EXTMEM = 0x2,
FW_MEMTYPE_CF_FLASH = 0x4,
FW_MEMTYPE_CF_INTERNAL = 0x5,
};
struct fw_caps_config_cmd {
__be32 op_to_write;
__be32 cfvalid_to_len16;
__be32 r2;
__be32 hwmbitmap;
__be16 nbmcaps;
__be16 linkcaps;
__be16 switchcaps;
__be16 r3;
__be16 niccaps;
__be16 ofldcaps;
__be16 rdmacaps;
__be16 r4;
__be16 iscsicaps;
__be16 fcoecaps;
__be32 cfcsum;
__be32 finiver;
__be32 finicsum;
};
#define FW_CAPS_CONFIG_CMD_CFVALID (1U << 27)
#define FW_CAPS_CONFIG_CMD_MEMTYPE_CF(x) ((x) << 24)
#define FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(x) ((x) << 16)
/*
* params command mnemonics
*/
enum fw_params_mnem {
FW_PARAMS_MNEM_DEV = 1, /* device params */
FW_PARAMS_MNEM_PFVF = 2, /* function params */
FW_PARAMS_MNEM_REG = 3, /* limited register access */
FW_PARAMS_MNEM_DMAQ = 4, /* dma queue params */
FW_PARAMS_MNEM_LAST
};
/*
* device parameters
*/
enum fw_params_param_dev {
FW_PARAMS_PARAM_DEV_CCLK = 0x00, /* chip core clock in khz */
FW_PARAMS_PARAM_DEV_PORTVEC = 0x01, /* the port vector */
FW_PARAMS_PARAM_DEV_NTID = 0x02, /* reads the number of TIDs
* allocated by the device's
* Lookup Engine
*/
FW_PARAMS_PARAM_DEV_FLOWC_BUFFIFO_SZ = 0x03,
FW_PARAMS_PARAM_DEV_INTVER_NIC = 0x04,
FW_PARAMS_PARAM_DEV_INTVER_VNIC = 0x05,
FW_PARAMS_PARAM_DEV_INTVER_OFLD = 0x06,
FW_PARAMS_PARAM_DEV_INTVER_RI = 0x07,
FW_PARAMS_PARAM_DEV_INTVER_ISCSIPDU = 0x08,
FW_PARAMS_PARAM_DEV_INTVER_ISCSI = 0x09,
FW_PARAMS_PARAM_DEV_INTVER_FCOE = 0x0A,
FW_PARAMS_PARAM_DEV_FWREV = 0x0B,
FW_PARAMS_PARAM_DEV_TPREV = 0x0C,
FW_PARAMS_PARAM_DEV_CF = 0x0D,
FW_PARAMS_PARAM_DEV_ULPTX_MEMWRITE_DSGL = 0x17,
};
/*
* physical and virtual function parameters
*/
enum fw_params_param_pfvf {
FW_PARAMS_PARAM_PFVF_RWXCAPS = 0x00,
FW_PARAMS_PARAM_PFVF_ROUTE_START = 0x01,
FW_PARAMS_PARAM_PFVF_ROUTE_END = 0x02,
FW_PARAMS_PARAM_PFVF_CLIP_START = 0x03,
FW_PARAMS_PARAM_PFVF_CLIP_END = 0x04,
FW_PARAMS_PARAM_PFVF_FILTER_START = 0x05,
FW_PARAMS_PARAM_PFVF_FILTER_END = 0x06,
FW_PARAMS_PARAM_PFVF_SERVER_START = 0x07,
FW_PARAMS_PARAM_PFVF_SERVER_END = 0x08,
FW_PARAMS_PARAM_PFVF_TDDP_START = 0x09,
FW_PARAMS_PARAM_PFVF_TDDP_END = 0x0A,
FW_PARAMS_PARAM_PFVF_ISCSI_START = 0x0B,
FW_PARAMS_PARAM_PFVF_ISCSI_END = 0x0C,
FW_PARAMS_PARAM_PFVF_STAG_START = 0x0D,
FW_PARAMS_PARAM_PFVF_STAG_END = 0x0E,
FW_PARAMS_PARAM_PFVF_RQ_START = 0x1F,
FW_PARAMS_PARAM_PFVF_RQ_END = 0x10,
FW_PARAMS_PARAM_PFVF_PBL_START = 0x11,
FW_PARAMS_PARAM_PFVF_PBL_END = 0x12,
FW_PARAMS_PARAM_PFVF_L2T_START = 0x13,
FW_PARAMS_PARAM_PFVF_L2T_END = 0x14,
FW_PARAMS_PARAM_PFVF_SQRQ_START = 0x15,
FW_PARAMS_PARAM_PFVF_SQRQ_END = 0x16,
FW_PARAMS_PARAM_PFVF_CQ_START = 0x17,
FW_PARAMS_PARAM_PFVF_CQ_END = 0x18,
FW_PARAMS_PARAM_PFVF_SCHEDCLASS_ETH = 0x20,
FW_PARAMS_PARAM_PFVF_VIID = 0x24,
FW_PARAMS_PARAM_PFVF_CPMASK = 0x25,
FW_PARAMS_PARAM_PFVF_OCQ_START = 0x26,
FW_PARAMS_PARAM_PFVF_OCQ_END = 0x27,
FW_PARAMS_PARAM_PFVF_CONM_MAP = 0x28,
FW_PARAMS_PARAM_PFVF_IQFLINT_START = 0x29,
FW_PARAMS_PARAM_PFVF_IQFLINT_END = 0x2A,
FW_PARAMS_PARAM_PFVF_EQ_START = 0x2B,
FW_PARAMS_PARAM_PFVF_EQ_END = 0x2C,
FW_PARAMS_PARAM_PFVF_ACTIVE_FILTER_START = 0x2D,
FW_PARAMS_PARAM_PFVF_ACTIVE_FILTER_END = 0x2E,
FW_PARAMS_PARAM_PFVF_ETHOFLD_END = 0x30,
FW_PARAMS_PARAM_PFVF_CPLFW4MSG_ENCAP = 0x31
};
/*
* dma queue parameters
*/
enum fw_params_param_dmaq {
FW_PARAMS_PARAM_DMAQ_IQ_DCAEN_DCACPU = 0x00,
FW_PARAMS_PARAM_DMAQ_IQ_INTCNTTHRESH = 0x01,
FW_PARAMS_PARAM_DMAQ_EQ_CMPLIQID_MNGT = 0x10,
FW_PARAMS_PARAM_DMAQ_EQ_CMPLIQID_CTRL = 0x11,
FW_PARAMS_PARAM_DMAQ_EQ_SCHEDCLASS_ETH = 0x12,
};
#define FW_PARAMS_MNEM(x) ((x) << 24)
#define FW_PARAMS_PARAM_X(x) ((x) << 16)
#define FW_PARAMS_PARAM_Y_SHIFT 8
#define FW_PARAMS_PARAM_Y_MASK 0xffU
#define FW_PARAMS_PARAM_Y(x) ((x) << FW_PARAMS_PARAM_Y_SHIFT)
#define FW_PARAMS_PARAM_Y_GET(x) (((x) >> FW_PARAMS_PARAM_Y_SHIFT) &\
FW_PARAMS_PARAM_Y_MASK)
#define FW_PARAMS_PARAM_Z_SHIFT 0
#define FW_PARAMS_PARAM_Z_MASK 0xffu
#define FW_PARAMS_PARAM_Z(x) ((x) << FW_PARAMS_PARAM_Z_SHIFT)
#define FW_PARAMS_PARAM_Z_GET(x) (((x) >> FW_PARAMS_PARAM_Z_SHIFT) &\
FW_PARAMS_PARAM_Z_MASK)
#define FW_PARAMS_PARAM_XYZ(x) ((x) << 0)
#define FW_PARAMS_PARAM_YZ(x) ((x) << 0)
struct fw_params_cmd {
__be32 op_to_vfn;
__be32 retval_len16;
struct fw_params_param {
__be32 mnem;
__be32 val;
} param[7];
};
#define FW_PARAMS_CMD_PFN(x) ((x) << 8)
#define FW_PARAMS_CMD_VFN(x) ((x) << 0)
struct fw_pfvf_cmd {
__be32 op_to_vfn;
__be32 retval_len16;
__be32 niqflint_niq;
__be32 type_to_neq;
__be32 tc_to_nexactf;
__be32 r_caps_to_nethctrl;
__be16 nricq;
__be16 nriqp;
__be32 r4;
};
#define FW_PFVF_CMD_PFN(x) ((x) << 8)
#define FW_PFVF_CMD_VFN(x) ((x) << 0)
#define FW_PFVF_CMD_NIQFLINT(x) ((x) << 20)
#define FW_PFVF_CMD_NIQFLINT_GET(x) (((x) >> 20) & 0xfff)
#define FW_PFVF_CMD_NIQ(x) ((x) << 0)
#define FW_PFVF_CMD_NIQ_GET(x) (((x) >> 0) & 0xfffff)
#define FW_PFVF_CMD_TYPE (1 << 31)
#define FW_PFVF_CMD_TYPE_GET(x) (((x) >> 31) & 0x1)
#define FW_PFVF_CMD_CMASK(x) ((x) << 24)
#define FW_PFVF_CMD_CMASK_MASK 0xf
#define FW_PFVF_CMD_CMASK_GET(x) (((x) >> 24) & FW_PFVF_CMD_CMASK_MASK)
#define FW_PFVF_CMD_PMASK(x) ((x) << 20)
#define FW_PFVF_CMD_PMASK_MASK 0xf
#define FW_PFVF_CMD_PMASK_GET(x) (((x) >> 20) & FW_PFVF_CMD_PMASK_MASK)
#define FW_PFVF_CMD_NEQ(x) ((x) << 0)
#define FW_PFVF_CMD_NEQ_GET(x) (((x) >> 0) & 0xfffff)
#define FW_PFVF_CMD_TC(x) ((x) << 24)
#define FW_PFVF_CMD_TC_GET(x) (((x) >> 24) & 0xff)
#define FW_PFVF_CMD_NVI(x) ((x) << 16)
#define FW_PFVF_CMD_NVI_GET(x) (((x) >> 16) & 0xff)
#define FW_PFVF_CMD_NEXACTF(x) ((x) << 0)
#define FW_PFVF_CMD_NEXACTF_GET(x) (((x) >> 0) & 0xffff)
#define FW_PFVF_CMD_R_CAPS(x) ((x) << 24)
#define FW_PFVF_CMD_R_CAPS_GET(x) (((x) >> 24) & 0xff)
#define FW_PFVF_CMD_WX_CAPS(x) ((x) << 16)
#define FW_PFVF_CMD_WX_CAPS_GET(x) (((x) >> 16) & 0xff)
#define FW_PFVF_CMD_NETHCTRL(x) ((x) << 0)
#define FW_PFVF_CMD_NETHCTRL_GET(x) (((x) >> 0) & 0xffff)
enum fw_iq_type {
FW_IQ_TYPE_FL_INT_CAP,
FW_IQ_TYPE_NO_FL_INT_CAP
};
struct fw_iq_cmd {
__be32 op_to_vfn;
__be32 alloc_to_len16;
__be16 physiqid;
__be16 iqid;
__be16 fl0id;
__be16 fl1id;
__be32 type_to_iqandstindex;
__be16 iqdroprss_to_iqesize;
__be16 iqsize;
__be64 iqaddr;
__be32 iqns_to_fl0congen;
__be16 fl0dcaen_to_fl0cidxfthresh;
__be16 fl0size;
__be64 fl0addr;
__be32 fl1cngchmap_to_fl1congen;
__be16 fl1dcaen_to_fl1cidxfthresh;
__be16 fl1size;
__be64 fl1addr;
};
#define FW_IQ_CMD_PFN(x) ((x) << 8)
#define FW_IQ_CMD_VFN(x) ((x) << 0)
#define FW_IQ_CMD_ALLOC (1U << 31)
#define FW_IQ_CMD_FREE (1U << 30)
#define FW_IQ_CMD_MODIFY (1U << 29)
#define FW_IQ_CMD_IQSTART(x) ((x) << 28)
#define FW_IQ_CMD_IQSTOP(x) ((x) << 27)
#define FW_IQ_CMD_TYPE(x) ((x) << 29)
#define FW_IQ_CMD_IQASYNCH(x) ((x) << 28)
#define FW_IQ_CMD_VIID(x) ((x) << 16)
#define FW_IQ_CMD_IQANDST(x) ((x) << 15)
#define FW_IQ_CMD_IQANUS(x) ((x) << 14)
#define FW_IQ_CMD_IQANUD(x) ((x) << 12)
#define FW_IQ_CMD_IQANDSTINDEX(x) ((x) << 0)
#define FW_IQ_CMD_IQDROPRSS (1U << 15)
#define FW_IQ_CMD_IQGTSMODE (1U << 14)
#define FW_IQ_CMD_IQPCIECH(x) ((x) << 12)
#define FW_IQ_CMD_IQDCAEN(x) ((x) << 11)
#define FW_IQ_CMD_IQDCACPU(x) ((x) << 6)
#define FW_IQ_CMD_IQINTCNTTHRESH(x) ((x) << 4)
#define FW_IQ_CMD_IQO (1U << 3)
#define FW_IQ_CMD_IQCPRIO(x) ((x) << 2)
#define FW_IQ_CMD_IQESIZE(x) ((x) << 0)
#define FW_IQ_CMD_IQNS(x) ((x) << 31)
#define FW_IQ_CMD_IQRO(x) ((x) << 30)
#define FW_IQ_CMD_IQFLINTIQHSEN(x) ((x) << 28)
#define FW_IQ_CMD_IQFLINTCONGEN(x) ((x) << 27)
#define FW_IQ_CMD_IQFLINTISCSIC(x) ((x) << 26)
#define FW_IQ_CMD_FL0CNGCHMAP(x) ((x) << 20)
#define FW_IQ_CMD_FL0CACHELOCK(x) ((x) << 15)
#define FW_IQ_CMD_FL0DBP(x) ((x) << 14)
#define FW_IQ_CMD_FL0DATANS(x) ((x) << 13)
#define FW_IQ_CMD_FL0DATARO(x) ((x) << 12)
#define FW_IQ_CMD_FL0CONGCIF(x) ((x) << 11)
#define FW_IQ_CMD_FL0ONCHIP(x) ((x) << 10)
#define FW_IQ_CMD_FL0STATUSPGNS(x) ((x) << 9)
#define FW_IQ_CMD_FL0STATUSPGRO(x) ((x) << 8)
#define FW_IQ_CMD_FL0FETCHNS(x) ((x) << 7)
#define FW_IQ_CMD_FL0FETCHRO(x) ((x) << 6)
#define FW_IQ_CMD_FL0HOSTFCMODE(x) ((x) << 4)
#define FW_IQ_CMD_FL0CPRIO(x) ((x) << 3)
#define FW_IQ_CMD_FL0PADEN(x) ((x) << 2)
#define FW_IQ_CMD_FL0PACKEN(x) ((x) << 1)
#define FW_IQ_CMD_FL0CONGEN (1U << 0)
#define FW_IQ_CMD_FL0DCAEN(x) ((x) << 15)
#define FW_IQ_CMD_FL0DCACPU(x) ((x) << 10)
#define FW_IQ_CMD_FL0FBMIN(x) ((x) << 7)
#define FW_IQ_CMD_FL0FBMAX(x) ((x) << 4)
#define FW_IQ_CMD_FL0CIDXFTHRESHO (1U << 3)
#define FW_IQ_CMD_FL0CIDXFTHRESH(x) ((x) << 0)
#define FW_IQ_CMD_FL1CNGCHMAP(x) ((x) << 20)
#define FW_IQ_CMD_FL1CACHELOCK(x) ((x) << 15)
#define FW_IQ_CMD_FL1DBP(x) ((x) << 14)
#define FW_IQ_CMD_FL1DATANS(x) ((x) << 13)
#define FW_IQ_CMD_FL1DATARO(x) ((x) << 12)
#define FW_IQ_CMD_FL1CONGCIF(x) ((x) << 11)
#define FW_IQ_CMD_FL1ONCHIP(x) ((x) << 10)
#define FW_IQ_CMD_FL1STATUSPGNS(x) ((x) << 9)
#define FW_IQ_CMD_FL1STATUSPGRO(x) ((x) << 8)
#define FW_IQ_CMD_FL1FETCHNS(x) ((x) << 7)
#define FW_IQ_CMD_FL1FETCHRO(x) ((x) << 6)
#define FW_IQ_CMD_FL1HOSTFCMODE(x) ((x) << 4)
#define FW_IQ_CMD_FL1CPRIO(x) ((x) << 3)
#define FW_IQ_CMD_FL1PADEN (1U << 2)
#define FW_IQ_CMD_FL1PACKEN (1U << 1)
#define FW_IQ_CMD_FL1CONGEN (1U << 0)
#define FW_IQ_CMD_FL1DCAEN(x) ((x) << 15)
#define FW_IQ_CMD_FL1DCACPU(x) ((x) << 10)
#define FW_IQ_CMD_FL1FBMIN(x) ((x) << 7)
#define FW_IQ_CMD_FL1FBMAX(x) ((x) << 4)
#define FW_IQ_CMD_FL1CIDXFTHRESHO (1U << 3)
#define FW_IQ_CMD_FL1CIDXFTHRESH(x) ((x) << 0)
struct fw_eq_eth_cmd {
__be32 op_to_vfn;
__be32 alloc_to_len16;
__be32 eqid_pkd;
__be32 physeqid_pkd;
__be32 fetchszm_to_iqid;
__be32 dcaen_to_eqsize;
__be64 eqaddr;
__be32 viid_pkd;
__be32 r8_lo;
__be64 r9;
};
#define FW_EQ_ETH_CMD_PFN(x) ((x) << 8)
#define FW_EQ_ETH_CMD_VFN(x) ((x) << 0)
#define FW_EQ_ETH_CMD_ALLOC (1U << 31)
#define FW_EQ_ETH_CMD_FREE (1U << 30)
#define FW_EQ_ETH_CMD_MODIFY (1U << 29)
#define FW_EQ_ETH_CMD_EQSTART (1U << 28)
#define FW_EQ_ETH_CMD_EQSTOP (1U << 27)
#define FW_EQ_ETH_CMD_EQID(x) ((x) << 0)
#define FW_EQ_ETH_CMD_EQID_GET(x) (((x) >> 0) & 0xfffff)
#define FW_EQ_ETH_CMD_PHYSEQID(x) ((x) << 0)
#define FW_EQ_ETH_CMD_PHYSEQID_GET(x) (((x) >> 0) & 0xfffff)
#define FW_EQ_ETH_CMD_FETCHSZM(x) ((x) << 26)
#define FW_EQ_ETH_CMD_STATUSPGNS(x) ((x) << 25)
#define FW_EQ_ETH_CMD_STATUSPGRO(x) ((x) << 24)
#define FW_EQ_ETH_CMD_FETCHNS(x) ((x) << 23)
#define FW_EQ_ETH_CMD_FETCHRO(x) ((x) << 22)
#define FW_EQ_ETH_CMD_HOSTFCMODE(x) ((x) << 20)
#define FW_EQ_ETH_CMD_CPRIO(x) ((x) << 19)
#define FW_EQ_ETH_CMD_ONCHIP(x) ((x) << 18)
#define FW_EQ_ETH_CMD_PCIECHN(x) ((x) << 16)
#define FW_EQ_ETH_CMD_IQID(x) ((x) << 0)
#define FW_EQ_ETH_CMD_DCAEN(x) ((x) << 31)
#define FW_EQ_ETH_CMD_DCACPU(x) ((x) << 26)
#define FW_EQ_ETH_CMD_FBMIN(x) ((x) << 23)
#define FW_EQ_ETH_CMD_FBMAX(x) ((x) << 20)
#define FW_EQ_ETH_CMD_CIDXFTHRESHO(x) ((x) << 19)
#define FW_EQ_ETH_CMD_CIDXFTHRESH(x) ((x) << 16)
#define FW_EQ_ETH_CMD_EQSIZE(x) ((x) << 0)
#define FW_EQ_ETH_CMD_AUTOEQUEQE (1U << 30)
#define FW_EQ_ETH_CMD_VIID(x) ((x) << 16)
struct fw_eq_ctrl_cmd {
__be32 op_to_vfn;
__be32 alloc_to_len16;
__be32 cmpliqid_eqid;
__be32 physeqid_pkd;
__be32 fetchszm_to_iqid;
__be32 dcaen_to_eqsize;
__be64 eqaddr;
};
#define FW_EQ_CTRL_CMD_PFN(x) ((x) << 8)
#define FW_EQ_CTRL_CMD_VFN(x) ((x) << 0)
#define FW_EQ_CTRL_CMD_ALLOC (1U << 31)
#define FW_EQ_CTRL_CMD_FREE (1U << 30)
#define FW_EQ_CTRL_CMD_MODIFY (1U << 29)
#define FW_EQ_CTRL_CMD_EQSTART (1U << 28)
#define FW_EQ_CTRL_CMD_EQSTOP (1U << 27)
#define FW_EQ_CTRL_CMD_CMPLIQID(x) ((x) << 20)
#define FW_EQ_CTRL_CMD_EQID(x) ((x) << 0)
#define FW_EQ_CTRL_CMD_EQID_GET(x) (((x) >> 0) & 0xfffff)
#define FW_EQ_CTRL_CMD_PHYSEQID_GET(x) (((x) >> 0) & 0xfffff)
#define FW_EQ_CTRL_CMD_FETCHSZM (1U << 26)
#define FW_EQ_CTRL_CMD_STATUSPGNS (1U << 25)
#define FW_EQ_CTRL_CMD_STATUSPGRO (1U << 24)
#define FW_EQ_CTRL_CMD_FETCHNS (1U << 23)
#define FW_EQ_CTRL_CMD_FETCHRO (1U << 22)
#define FW_EQ_CTRL_CMD_HOSTFCMODE(x) ((x) << 20)
#define FW_EQ_CTRL_CMD_CPRIO(x) ((x) << 19)
#define FW_EQ_CTRL_CMD_ONCHIP(x) ((x) << 18)
#define FW_EQ_CTRL_CMD_PCIECHN(x) ((x) << 16)
#define FW_EQ_CTRL_CMD_IQID(x) ((x) << 0)
#define FW_EQ_CTRL_CMD_DCAEN(x) ((x) << 31)
#define FW_EQ_CTRL_CMD_DCACPU(x) ((x) << 26)
#define FW_EQ_CTRL_CMD_FBMIN(x) ((x) << 23)
#define FW_EQ_CTRL_CMD_FBMAX(x) ((x) << 20)
#define FW_EQ_CTRL_CMD_CIDXFTHRESHO(x) ((x) << 19)
#define FW_EQ_CTRL_CMD_CIDXFTHRESH(x) ((x) << 16)
#define FW_EQ_CTRL_CMD_EQSIZE(x) ((x) << 0)
struct fw_eq_ofld_cmd {
__be32 op_to_vfn;
__be32 alloc_to_len16;
__be32 eqid_pkd;
__be32 physeqid_pkd;
__be32 fetchszm_to_iqid;
__be32 dcaen_to_eqsize;
__be64 eqaddr;
};
#define FW_EQ_OFLD_CMD_PFN(x) ((x) << 8)
#define FW_EQ_OFLD_CMD_VFN(x) ((x) << 0)
#define FW_EQ_OFLD_CMD_ALLOC (1U << 31)
#define FW_EQ_OFLD_CMD_FREE (1U << 30)
#define FW_EQ_OFLD_CMD_MODIFY (1U << 29)
#define FW_EQ_OFLD_CMD_EQSTART (1U << 28)
#define FW_EQ_OFLD_CMD_EQSTOP (1U << 27)
#define FW_EQ_OFLD_CMD_EQID(x) ((x) << 0)
#define FW_EQ_OFLD_CMD_EQID_GET(x) (((x) >> 0) & 0xfffff)
#define FW_EQ_OFLD_CMD_PHYSEQID_GET(x) (((x) >> 0) & 0xfffff)
#define FW_EQ_OFLD_CMD_FETCHSZM(x) ((x) << 26)
#define FW_EQ_OFLD_CMD_STATUSPGNS(x) ((x) << 25)
#define FW_EQ_OFLD_CMD_STATUSPGRO(x) ((x) << 24)
#define FW_EQ_OFLD_CMD_FETCHNS(x) ((x) << 23)
#define FW_EQ_OFLD_CMD_FETCHRO(x) ((x) << 22)
#define FW_EQ_OFLD_CMD_HOSTFCMODE(x) ((x) << 20)
#define FW_EQ_OFLD_CMD_CPRIO(x) ((x) << 19)
#define FW_EQ_OFLD_CMD_ONCHIP(x) ((x) << 18)
#define FW_EQ_OFLD_CMD_PCIECHN(x) ((x) << 16)
#define FW_EQ_OFLD_CMD_IQID(x) ((x) << 0)
#define FW_EQ_OFLD_CMD_DCAEN(x) ((x) << 31)
#define FW_EQ_OFLD_CMD_DCACPU(x) ((x) << 26)
#define FW_EQ_OFLD_CMD_FBMIN(x) ((x) << 23)
#define FW_EQ_OFLD_CMD_FBMAX(x) ((x) << 20)
#define FW_EQ_OFLD_CMD_CIDXFTHRESHO(x) ((x) << 19)
#define FW_EQ_OFLD_CMD_CIDXFTHRESH(x) ((x) << 16)
#define FW_EQ_OFLD_CMD_EQSIZE(x) ((x) << 0)
/*
* Macros for VIID parsing:
* VIID - [10:8] PFN, [7] VI Valid, [6:0] VI number
*/
#define FW_VIID_PFN_GET(x) (((x) >> 8) & 0x7)
#define FW_VIID_VIVLD_GET(x) (((x) >> 7) & 0x1)
#define FW_VIID_VIN_GET(x) (((x) >> 0) & 0x7F)
struct fw_vi_cmd {
__be32 op_to_vfn;
__be32 alloc_to_len16;
__be16 type_viid;
u8 mac[6];
u8 portid_pkd;
u8 nmac;
u8 nmac0[6];
__be16 rsssize_pkd;
u8 nmac1[6];
__be16 idsiiq_pkd;
u8 nmac2[6];
__be16 idseiq_pkd;
u8 nmac3[6];
__be64 r9;
__be64 r10;
};
#define FW_VI_CMD_PFN(x) ((x) << 8)
#define FW_VI_CMD_VFN(x) ((x) << 0)
#define FW_VI_CMD_ALLOC (1U << 31)
#define FW_VI_CMD_FREE (1U << 30)
#define FW_VI_CMD_VIID(x) ((x) << 0)
#define FW_VI_CMD_VIID_GET(x) ((x) & 0xfff)
#define FW_VI_CMD_PORTID(x) ((x) << 4)
#define FW_VI_CMD_PORTID_GET(x) (((x) >> 4) & 0xf)
#define FW_VI_CMD_RSSSIZE_GET(x) (((x) >> 0) & 0x7ff)
/* Special VI_MAC command index ids */
#define FW_VI_MAC_ADD_MAC 0x3FF
#define FW_VI_MAC_ADD_PERSIST_MAC 0x3FE
#define FW_VI_MAC_MAC_BASED_FREE 0x3FD
#define FW_CLS_TCAM_NUM_ENTRIES 336
enum fw_vi_mac_smac {
FW_VI_MAC_MPS_TCAM_ENTRY,
FW_VI_MAC_MPS_TCAM_ONLY,
FW_VI_MAC_SMT_ONLY,
FW_VI_MAC_SMT_AND_MPSTCAM
};
enum fw_vi_mac_result {
FW_VI_MAC_R_SUCCESS,
FW_VI_MAC_R_F_NONEXISTENT_NOMEM,
FW_VI_MAC_R_SMAC_FAIL,
FW_VI_MAC_R_F_ACL_CHECK
};
struct fw_vi_mac_cmd {
__be32 op_to_viid;
__be32 freemacs_to_len16;
union fw_vi_mac {
struct fw_vi_mac_exact {
__be16 valid_to_idx;
u8 macaddr[6];
} exact[7];
struct fw_vi_mac_hash {
__be64 hashvec;
} hash;
} u;
};
#define FW_VI_MAC_CMD_VIID(x) ((x) << 0)
#define FW_VI_MAC_CMD_FREEMACS(x) ((x) << 31)
#define FW_VI_MAC_CMD_HASHVECEN (1U << 23)
#define FW_VI_MAC_CMD_HASHUNIEN(x) ((x) << 22)
#define FW_VI_MAC_CMD_VALID (1U << 15)
#define FW_VI_MAC_CMD_PRIO(x) ((x) << 12)
#define FW_VI_MAC_CMD_SMAC_RESULT(x) ((x) << 10)
#define FW_VI_MAC_CMD_SMAC_RESULT_GET(x) (((x) >> 10) & 0x3)
#define FW_VI_MAC_CMD_IDX(x) ((x) << 0)
#define FW_VI_MAC_CMD_IDX_GET(x) (((x) >> 0) & 0x3ff)
#define FW_RXMODE_MTU_NO_CHG 65535
struct fw_vi_rxmode_cmd {
__be32 op_to_viid;
__be32 retval_len16;
__be32 mtu_to_vlanexen;
__be32 r4_lo;
};
#define FW_VI_RXMODE_CMD_VIID(x) ((x) << 0)
#define FW_VI_RXMODE_CMD_MTU_MASK 0xffff
#define FW_VI_RXMODE_CMD_MTU(x) ((x) << 16)
#define FW_VI_RXMODE_CMD_PROMISCEN_MASK 0x3
#define FW_VI_RXMODE_CMD_PROMISCEN(x) ((x) << 14)
#define FW_VI_RXMODE_CMD_ALLMULTIEN_MASK 0x3
#define FW_VI_RXMODE_CMD_ALLMULTIEN(x) ((x) << 12)
#define FW_VI_RXMODE_CMD_BROADCASTEN_MASK 0x3
#define FW_VI_RXMODE_CMD_BROADCASTEN(x) ((x) << 10)
#define FW_VI_RXMODE_CMD_VLANEXEN_MASK 0x3
#define FW_VI_RXMODE_CMD_VLANEXEN(x) ((x) << 8)
struct fw_vi_enable_cmd {
__be32 op_to_viid;
__be32 ien_to_len16;
__be16 blinkdur;
__be16 r3;
__be32 r4;
};
#define FW_VI_ENABLE_CMD_VIID(x) ((x) << 0)
#define FW_VI_ENABLE_CMD_IEN(x) ((x) << 31)
#define FW_VI_ENABLE_CMD_EEN(x) ((x) << 30)
#define FW_VI_ENABLE_CMD_LED (1U << 29)
/* VI VF stats offset definitions */
#define VI_VF_NUM_STATS 16
enum fw_vi_stats_vf_index {
FW_VI_VF_STAT_TX_BCAST_BYTES_IX,
FW_VI_VF_STAT_TX_BCAST_FRAMES_IX,
FW_VI_VF_STAT_TX_MCAST_BYTES_IX,
FW_VI_VF_STAT_TX_MCAST_FRAMES_IX,
FW_VI_VF_STAT_TX_UCAST_BYTES_IX,
FW_VI_VF_STAT_TX_UCAST_FRAMES_IX,
FW_VI_VF_STAT_TX_DROP_FRAMES_IX,
FW_VI_VF_STAT_TX_OFLD_BYTES_IX,
FW_VI_VF_STAT_TX_OFLD_FRAMES_IX,
FW_VI_VF_STAT_RX_BCAST_BYTES_IX,
FW_VI_VF_STAT_RX_BCAST_FRAMES_IX,
FW_VI_VF_STAT_RX_MCAST_BYTES_IX,
FW_VI_VF_STAT_RX_MCAST_FRAMES_IX,
FW_VI_VF_STAT_RX_UCAST_BYTES_IX,
FW_VI_VF_STAT_RX_UCAST_FRAMES_IX,
FW_VI_VF_STAT_RX_ERR_FRAMES_IX
};
/* VI PF stats offset definitions */
#define VI_PF_NUM_STATS 17
enum fw_vi_stats_pf_index {
FW_VI_PF_STAT_TX_BCAST_BYTES_IX,
FW_VI_PF_STAT_TX_BCAST_FRAMES_IX,
FW_VI_PF_STAT_TX_MCAST_BYTES_IX,
FW_VI_PF_STAT_TX_MCAST_FRAMES_IX,
FW_VI_PF_STAT_TX_UCAST_BYTES_IX,
FW_VI_PF_STAT_TX_UCAST_FRAMES_IX,
FW_VI_PF_STAT_TX_OFLD_BYTES_IX,
FW_VI_PF_STAT_TX_OFLD_FRAMES_IX,
FW_VI_PF_STAT_RX_BYTES_IX,
FW_VI_PF_STAT_RX_FRAMES_IX,
FW_VI_PF_STAT_RX_BCAST_BYTES_IX,
FW_VI_PF_STAT_RX_BCAST_FRAMES_IX,
FW_VI_PF_STAT_RX_MCAST_BYTES_IX,
FW_VI_PF_STAT_RX_MCAST_FRAMES_IX,
FW_VI_PF_STAT_RX_UCAST_BYTES_IX,
FW_VI_PF_STAT_RX_UCAST_FRAMES_IX,
FW_VI_PF_STAT_RX_ERR_FRAMES_IX
};
struct fw_vi_stats_cmd {
__be32 op_to_viid;
__be32 retval_len16;
union fw_vi_stats {
struct fw_vi_stats_ctl {
__be16 nstats_ix;
__be16 r6;
__be32 r7;
__be64 stat0;
__be64 stat1;
__be64 stat2;
__be64 stat3;
__be64 stat4;
__be64 stat5;
} ctl;
struct fw_vi_stats_pf {
__be64 tx_bcast_bytes;
__be64 tx_bcast_frames;
__be64 tx_mcast_bytes;
__be64 tx_mcast_frames;
__be64 tx_ucast_bytes;
__be64 tx_ucast_frames;
__be64 tx_offload_bytes;
__be64 tx_offload_frames;
__be64 rx_pf_bytes;
__be64 rx_pf_frames;
__be64 rx_bcast_bytes;
__be64 rx_bcast_frames;
__be64 rx_mcast_bytes;
__be64 rx_mcast_frames;
__be64 rx_ucast_bytes;
__be64 rx_ucast_frames;
__be64 rx_err_frames;
} pf;
struct fw_vi_stats_vf {
__be64 tx_bcast_bytes;
__be64 tx_bcast_frames;
__be64 tx_mcast_bytes;
__be64 tx_mcast_frames;
__be64 tx_ucast_bytes;
__be64 tx_ucast_frames;
__be64 tx_drop_frames;
__be64 tx_offload_bytes;
__be64 tx_offload_frames;
__be64 rx_bcast_bytes;
__be64 rx_bcast_frames;
__be64 rx_mcast_bytes;
__be64 rx_mcast_frames;
__be64 rx_ucast_bytes;
__be64 rx_ucast_frames;
__be64 rx_err_frames;
} vf;
} u;
};
#define FW_VI_STATS_CMD_VIID(x) ((x) << 0)
#define FW_VI_STATS_CMD_NSTATS(x) ((x) << 12)
#define FW_VI_STATS_CMD_IX(x) ((x) << 0)
struct fw_acl_mac_cmd {
__be32 op_to_vfn;
__be32 en_to_len16;
u8 nmac;
u8 r3[7];
__be16 r4;
u8 macaddr0[6];
__be16 r5;
u8 macaddr1[6];
__be16 r6;
u8 macaddr2[6];
__be16 r7;
u8 macaddr3[6];
};
#define FW_ACL_MAC_CMD_PFN(x) ((x) << 8)
#define FW_ACL_MAC_CMD_VFN(x) ((x) << 0)
#define FW_ACL_MAC_CMD_EN(x) ((x) << 31)
struct fw_acl_vlan_cmd {
__be32 op_to_vfn;
__be32 en_to_len16;
u8 nvlan;
u8 dropnovlan_fm;
u8 r3_lo[6];
__be16 vlanid[16];
};
#define FW_ACL_VLAN_CMD_PFN(x) ((x) << 8)
#define FW_ACL_VLAN_CMD_VFN(x) ((x) << 0)
#define FW_ACL_VLAN_CMD_EN(x) ((x) << 31)
#define FW_ACL_VLAN_CMD_DROPNOVLAN(x) ((x) << 7)
#define FW_ACL_VLAN_CMD_FM(x) ((x) << 6)
enum fw_port_cap {
FW_PORT_CAP_SPEED_100M = 0x0001,
FW_PORT_CAP_SPEED_1G = 0x0002,
FW_PORT_CAP_SPEED_2_5G = 0x0004,
FW_PORT_CAP_SPEED_10G = 0x0008,
FW_PORT_CAP_SPEED_40G = 0x0010,
FW_PORT_CAP_SPEED_100G = 0x0020,
FW_PORT_CAP_FC_RX = 0x0040,
FW_PORT_CAP_FC_TX = 0x0080,
FW_PORT_CAP_ANEG = 0x0100,
FW_PORT_CAP_MDI_0 = 0x0200,
FW_PORT_CAP_MDI_1 = 0x0400,
FW_PORT_CAP_BEAN = 0x0800,
FW_PORT_CAP_PMA_LPBK = 0x1000,
FW_PORT_CAP_PCS_LPBK = 0x2000,
FW_PORT_CAP_PHYXS_LPBK = 0x4000,
FW_PORT_CAP_FAR_END_LPBK = 0x8000,
};
enum fw_port_mdi {
FW_PORT_MDI_UNCHANGED,
FW_PORT_MDI_AUTO,
FW_PORT_MDI_F_STRAIGHT,
FW_PORT_MDI_F_CROSSOVER
};
#define FW_PORT_MDI(x) ((x) << 9)
enum fw_port_action {
FW_PORT_ACTION_L1_CFG = 0x0001,
FW_PORT_ACTION_L2_CFG = 0x0002,
FW_PORT_ACTION_GET_PORT_INFO = 0x0003,
FW_PORT_ACTION_L2_PPP_CFG = 0x0004,
FW_PORT_ACTION_L2_DCB_CFG = 0x0005,
FW_PORT_ACTION_LOW_PWR_TO_NORMAL = 0x0010,
FW_PORT_ACTION_L1_LOW_PWR_EN = 0x0011,
FW_PORT_ACTION_L2_WOL_MODE_EN = 0x0012,
FW_PORT_ACTION_LPBK_TO_NORMAL = 0x0020,
FW_PORT_ACTION_L1_LPBK = 0x0021,
FW_PORT_ACTION_L1_PMA_LPBK = 0x0022,
FW_PORT_ACTION_L1_PCS_LPBK = 0x0023,
FW_PORT_ACTION_L1_PHYXS_CSIDE_LPBK = 0x0024,
FW_PORT_ACTION_L1_PHYXS_ESIDE_LPBK = 0x0025,
FW_PORT_ACTION_PHY_RESET = 0x0040,
FW_PORT_ACTION_PMA_RESET = 0x0041,
FW_PORT_ACTION_PCS_RESET = 0x0042,
FW_PORT_ACTION_PHYXS_RESET = 0x0043,
FW_PORT_ACTION_DTEXS_REEST = 0x0044,
FW_PORT_ACTION_AN_RESET = 0x0045
};
enum fw_port_l2cfg_ctlbf {
FW_PORT_L2_CTLBF_OVLAN0 = 0x01,
FW_PORT_L2_CTLBF_OVLAN1 = 0x02,
FW_PORT_L2_CTLBF_OVLAN2 = 0x04,
FW_PORT_L2_CTLBF_OVLAN3 = 0x08,
FW_PORT_L2_CTLBF_IVLAN = 0x10,
FW_PORT_L2_CTLBF_TXIPG = 0x20
};
enum fw_port_dcb_cfg {
FW_PORT_DCB_CFG_PG = 0x01,
FW_PORT_DCB_CFG_PFC = 0x02,
FW_PORT_DCB_CFG_APPL = 0x04
};
enum fw_port_dcb_cfg_rc {
FW_PORT_DCB_CFG_SUCCESS = 0x0,
FW_PORT_DCB_CFG_ERROR = 0x1
};
enum fw_port_dcb_type {
FW_PORT_DCB_TYPE_PGID = 0x00,
FW_PORT_DCB_TYPE_PGRATE = 0x01,
FW_PORT_DCB_TYPE_PRIORATE = 0x02,
FW_PORT_DCB_TYPE_PFC = 0x03,
FW_PORT_DCB_TYPE_APP_ID = 0x04,
};
struct fw_port_cmd {
__be32 op_to_portid;
__be32 action_to_len16;
union fw_port {
struct fw_port_l1cfg {
__be32 rcap;
__be32 r;
} l1cfg;
struct fw_port_l2cfg {
__be16 ctlbf_to_ivlan0;
__be16 ivlantype;
__be32 txipg_pkd;
__be16 ovlan0mask;
__be16 ovlan0type;
__be16 ovlan1mask;
__be16 ovlan1type;
__be16 ovlan2mask;
__be16 ovlan2type;
__be16 ovlan3mask;
__be16 ovlan3type;
} l2cfg;
struct fw_port_info {
__be32 lstatus_to_modtype;
__be16 pcap;
__be16 acap;
__be16 mtu;
__u8 cbllen;
__u8 r9;
__be32 r10;
__be64 r11;
} info;
struct fw_port_ppp {
__be32 pppen_to_ncsich;
__be32 r11;
} ppp;
struct fw_port_dcb {
__be16 cfg;
u8 up_map;
u8 sf_cfgrc;
__be16 prot_ix;
u8 pe7_to_pe0;
u8 numTCPFCs;
__be32 pgid0_to_pgid7;
__be32 numTCs_oui;
u8 pgpc[8];
} dcb;
} u;
};
#define FW_PORT_CMD_READ (1U << 22)
#define FW_PORT_CMD_PORTID(x) ((x) << 0)
#define FW_PORT_CMD_PORTID_GET(x) (((x) >> 0) & 0xf)
#define FW_PORT_CMD_ACTION(x) ((x) << 16)
#define FW_PORT_CMD_ACTION_GET(x) (((x) >> 16) & 0xffff)
#define FW_PORT_CMD_CTLBF(x) ((x) << 10)
#define FW_PORT_CMD_OVLAN3(x) ((x) << 7)
#define FW_PORT_CMD_OVLAN2(x) ((x) << 6)
#define FW_PORT_CMD_OVLAN1(x) ((x) << 5)
#define FW_PORT_CMD_OVLAN0(x) ((x) << 4)
#define FW_PORT_CMD_IVLAN0(x) ((x) << 3)
#define FW_PORT_CMD_TXIPG(x) ((x) << 19)
#define FW_PORT_CMD_LSTATUS (1U << 31)
#define FW_PORT_CMD_LSTATUS_GET(x) (((x) >> 31) & 0x1)
#define FW_PORT_CMD_LSPEED(x) ((x) << 24)
#define FW_PORT_CMD_LSPEED_GET(x) (((x) >> 24) & 0x3f)
#define FW_PORT_CMD_TXPAUSE (1U << 23)
#define FW_PORT_CMD_RXPAUSE (1U << 22)
#define FW_PORT_CMD_MDIOCAP (1U << 21)
#define FW_PORT_CMD_MDIOADDR_GET(x) (((x) >> 16) & 0x1f)
#define FW_PORT_CMD_LPTXPAUSE (1U << 15)
#define FW_PORT_CMD_LPRXPAUSE (1U << 14)
#define FW_PORT_CMD_PTYPE_MASK 0x1f
#define FW_PORT_CMD_PTYPE_GET(x) (((x) >> 8) & FW_PORT_CMD_PTYPE_MASK)
#define FW_PORT_CMD_MODTYPE_MASK 0x1f
#define FW_PORT_CMD_MODTYPE_GET(x) (((x) >> 0) & FW_PORT_CMD_MODTYPE_MASK)
#define FW_PORT_CMD_PPPEN(x) ((x) << 31)
#define FW_PORT_CMD_TPSRC(x) ((x) << 28)
#define FW_PORT_CMD_NCSISRC(x) ((x) << 24)
#define FW_PORT_CMD_CH0(x) ((x) << 20)
#define FW_PORT_CMD_CH1(x) ((x) << 16)
#define FW_PORT_CMD_CH2(x) ((x) << 12)
#define FW_PORT_CMD_CH3(x) ((x) << 8)
#define FW_PORT_CMD_NCSICH(x) ((x) << 4)
enum fw_port_type {
FW_PORT_TYPE_FIBER_XFI,
FW_PORT_TYPE_FIBER_XAUI,
FW_PORT_TYPE_BT_SGMII,
FW_PORT_TYPE_BT_XFI,
FW_PORT_TYPE_BT_XAUI,
FW_PORT_TYPE_KX4,
FW_PORT_TYPE_CX4,
FW_PORT_TYPE_KX,
FW_PORT_TYPE_KR,
FW_PORT_TYPE_SFP,
FW_PORT_TYPE_BP_AP,
FW_PORT_TYPE_BP4_AP,
FW_PORT_TYPE_QSFP_10G,
FW_PORT_TYPE_QSFP,
FW_PORT_TYPE_BP40_BA,
FW_PORT_TYPE_NONE = FW_PORT_CMD_PTYPE_MASK
};
enum fw_port_module_type {
FW_PORT_MOD_TYPE_NA,
FW_PORT_MOD_TYPE_LR,
FW_PORT_MOD_TYPE_SR,
FW_PORT_MOD_TYPE_ER,
FW_PORT_MOD_TYPE_TWINAX_PASSIVE,
FW_PORT_MOD_TYPE_TWINAX_ACTIVE,
FW_PORT_MOD_TYPE_LRM,
FW_PORT_MOD_TYPE_ERROR = FW_PORT_CMD_MODTYPE_MASK - 3,
FW_PORT_MOD_TYPE_UNKNOWN = FW_PORT_CMD_MODTYPE_MASK - 2,
FW_PORT_MOD_TYPE_NOTSUPPORTED = FW_PORT_CMD_MODTYPE_MASK - 1,
FW_PORT_MOD_TYPE_NONE = FW_PORT_CMD_MODTYPE_MASK
};
enum fw_port_mod_sub_type {
FW_PORT_MOD_SUB_TYPE_NA,
FW_PORT_MOD_SUB_TYPE_MV88E114X = 0x1,
FW_PORT_MOD_SUB_TYPE_TN8022 = 0x2,
FW_PORT_MOD_SUB_TYPE_AQ1202 = 0x3,
FW_PORT_MOD_SUB_TYPE_88x3120 = 0x4,
FW_PORT_MOD_SUB_TYPE_BCM84834 = 0x5,
FW_PORT_MOD_SUB_TYPE_BT_VSC8634 = 0x8,
/* The following will never been in the VPD. They are TWINAX cable
* lengths decoded from SFP+ module i2c PROMs. These should
* almost certainly go somewhere else ...
*/
FW_PORT_MOD_SUB_TYPE_TWINAX_1 = 0x9,
FW_PORT_MOD_SUB_TYPE_TWINAX_3 = 0xA,
FW_PORT_MOD_SUB_TYPE_TWINAX_5 = 0xB,
FW_PORT_MOD_SUB_TYPE_TWINAX_7 = 0xC,
};
/* port stats */
#define FW_NUM_PORT_STATS 50
#define FW_NUM_PORT_TX_STATS 23
#define FW_NUM_PORT_RX_STATS 27
enum fw_port_stats_tx_index {
FW_STAT_TX_PORT_BYTES_IX,
FW_STAT_TX_PORT_FRAMES_IX,
FW_STAT_TX_PORT_BCAST_IX,
FW_STAT_TX_PORT_MCAST_IX,
FW_STAT_TX_PORT_UCAST_IX,
FW_STAT_TX_PORT_ERROR_IX,
FW_STAT_TX_PORT_64B_IX,
FW_STAT_TX_PORT_65B_127B_IX,
FW_STAT_TX_PORT_128B_255B_IX,
FW_STAT_TX_PORT_256B_511B_IX,
FW_STAT_TX_PORT_512B_1023B_IX,
FW_STAT_TX_PORT_1024B_1518B_IX,
FW_STAT_TX_PORT_1519B_MAX_IX,
FW_STAT_TX_PORT_DROP_IX,
FW_STAT_TX_PORT_PAUSE_IX,
FW_STAT_TX_PORT_PPP0_IX,
FW_STAT_TX_PORT_PPP1_IX,
FW_STAT_TX_PORT_PPP2_IX,
FW_STAT_TX_PORT_PPP3_IX,
FW_STAT_TX_PORT_PPP4_IX,
FW_STAT_TX_PORT_PPP5_IX,
FW_STAT_TX_PORT_PPP6_IX,
FW_STAT_TX_PORT_PPP7_IX
};
enum fw_port_stat_rx_index {
FW_STAT_RX_PORT_BYTES_IX,
FW_STAT_RX_PORT_FRAMES_IX,
FW_STAT_RX_PORT_BCAST_IX,
FW_STAT_RX_PORT_MCAST_IX,
FW_STAT_RX_PORT_UCAST_IX,
FW_STAT_RX_PORT_MTU_ERROR_IX,
FW_STAT_RX_PORT_MTU_CRC_ERROR_IX,
FW_STAT_RX_PORT_CRC_ERROR_IX,
FW_STAT_RX_PORT_LEN_ERROR_IX,
FW_STAT_RX_PORT_SYM_ERROR_IX,
FW_STAT_RX_PORT_64B_IX,
FW_STAT_RX_PORT_65B_127B_IX,
FW_STAT_RX_PORT_128B_255B_IX,
FW_STAT_RX_PORT_256B_511B_IX,
FW_STAT_RX_PORT_512B_1023B_IX,
FW_STAT_RX_PORT_1024B_1518B_IX,
FW_STAT_RX_PORT_1519B_MAX_IX,
FW_STAT_RX_PORT_PAUSE_IX,
FW_STAT_RX_PORT_PPP0_IX,
FW_STAT_RX_PORT_PPP1_IX,
FW_STAT_RX_PORT_PPP2_IX,
FW_STAT_RX_PORT_PPP3_IX,
FW_STAT_RX_PORT_PPP4_IX,
FW_STAT_RX_PORT_PPP5_IX,
FW_STAT_RX_PORT_PPP6_IX,
FW_STAT_RX_PORT_PPP7_IX,
FW_STAT_RX_PORT_LESS_64B_IX
};
struct fw_port_stats_cmd {
__be32 op_to_portid;
__be32 retval_len16;
union fw_port_stats {
struct fw_port_stats_ctl {
u8 nstats_bg_bm;
u8 tx_ix;
__be16 r6;
__be32 r7;
__be64 stat0;
__be64 stat1;
__be64 stat2;
__be64 stat3;
__be64 stat4;
__be64 stat5;
} ctl;
struct fw_port_stats_all {
__be64 tx_bytes;
__be64 tx_frames;
__be64 tx_bcast;
__be64 tx_mcast;
__be64 tx_ucast;
__be64 tx_error;
__be64 tx_64b;
__be64 tx_65b_127b;
__be64 tx_128b_255b;
__be64 tx_256b_511b;
__be64 tx_512b_1023b;
__be64 tx_1024b_1518b;
__be64 tx_1519b_max;
__be64 tx_drop;
__be64 tx_pause;
__be64 tx_ppp0;
__be64 tx_ppp1;
__be64 tx_ppp2;
__be64 tx_ppp3;
__be64 tx_ppp4;
__be64 tx_ppp5;
__be64 tx_ppp6;
__be64 tx_ppp7;
__be64 rx_bytes;
__be64 rx_frames;
__be64 rx_bcast;
__be64 rx_mcast;
__be64 rx_ucast;
__be64 rx_mtu_error;
__be64 rx_mtu_crc_error;
__be64 rx_crc_error;
__be64 rx_len_error;
__be64 rx_sym_error;
__be64 rx_64b;
__be64 rx_65b_127b;
__be64 rx_128b_255b;
__be64 rx_256b_511b;
__be64 rx_512b_1023b;
__be64 rx_1024b_1518b;
__be64 rx_1519b_max;
__be64 rx_pause;
__be64 rx_ppp0;
__be64 rx_ppp1;
__be64 rx_ppp2;
__be64 rx_ppp3;
__be64 rx_ppp4;
__be64 rx_ppp5;
__be64 rx_ppp6;
__be64 rx_ppp7;
__be64 rx_less_64b;
__be64 rx_bg_drop;
__be64 rx_bg_trunc;
} all;
} u;
};
#define FW_PORT_STATS_CMD_NSTATS(x) ((x) << 4)
#define FW_PORT_STATS_CMD_BG_BM(x) ((x) << 0)
#define FW_PORT_STATS_CMD_TX(x) ((x) << 7)
#define FW_PORT_STATS_CMD_IX(x) ((x) << 0)
/* port loopback stats */
#define FW_NUM_LB_STATS 16
enum fw_port_lb_stats_index {
FW_STAT_LB_PORT_BYTES_IX,
FW_STAT_LB_PORT_FRAMES_IX,
FW_STAT_LB_PORT_BCAST_IX,
FW_STAT_LB_PORT_MCAST_IX,
FW_STAT_LB_PORT_UCAST_IX,
FW_STAT_LB_PORT_ERROR_IX,
FW_STAT_LB_PORT_64B_IX,
FW_STAT_LB_PORT_65B_127B_IX,
FW_STAT_LB_PORT_128B_255B_IX,
FW_STAT_LB_PORT_256B_511B_IX,
FW_STAT_LB_PORT_512B_1023B_IX,
FW_STAT_LB_PORT_1024B_1518B_IX,
FW_STAT_LB_PORT_1519B_MAX_IX,
FW_STAT_LB_PORT_DROP_FRAMES_IX
};
struct fw_port_lb_stats_cmd {
__be32 op_to_lbport;
__be32 retval_len16;
union fw_port_lb_stats {
struct fw_port_lb_stats_ctl {
u8 nstats_bg_bm;
u8 ix_pkd;
__be16 r6;
__be32 r7;
__be64 stat0;
__be64 stat1;
__be64 stat2;
__be64 stat3;
__be64 stat4;
__be64 stat5;
} ctl;
struct fw_port_lb_stats_all {
__be64 tx_bytes;
__be64 tx_frames;
__be64 tx_bcast;
__be64 tx_mcast;
__be64 tx_ucast;
__be64 tx_error;
__be64 tx_64b;
__be64 tx_65b_127b;
__be64 tx_128b_255b;
__be64 tx_256b_511b;
__be64 tx_512b_1023b;
__be64 tx_1024b_1518b;
__be64 tx_1519b_max;
__be64 rx_lb_drop;
__be64 rx_lb_trunc;
} all;
} u;
};
#define FW_PORT_LB_STATS_CMD_LBPORT(x) ((x) << 0)
#define FW_PORT_LB_STATS_CMD_NSTATS(x) ((x) << 4)
#define FW_PORT_LB_STATS_CMD_BG_BM(x) ((x) << 0)
#define FW_PORT_LB_STATS_CMD_IX(x) ((x) << 0)
struct fw_rss_ind_tbl_cmd {
__be32 op_to_viid;
#define FW_RSS_IND_TBL_CMD_VIID(x) ((x) << 0)
__be32 retval_len16;
__be16 niqid;
__be16 startidx;
__be32 r3;
__be32 iq0_to_iq2;
#define FW_RSS_IND_TBL_CMD_IQ0(x) ((x) << 20)
#define FW_RSS_IND_TBL_CMD_IQ1(x) ((x) << 10)
#define FW_RSS_IND_TBL_CMD_IQ2(x) ((x) << 0)
__be32 iq3_to_iq5;
__be32 iq6_to_iq8;
__be32 iq9_to_iq11;
__be32 iq12_to_iq14;
__be32 iq15_to_iq17;
__be32 iq18_to_iq20;
__be32 iq21_to_iq23;
__be32 iq24_to_iq26;
__be32 iq27_to_iq29;
__be32 iq30_iq31;
__be32 r15_lo;
};
struct fw_rss_glb_config_cmd {
__be32 op_to_write;
__be32 retval_len16;
union fw_rss_glb_config {
struct fw_rss_glb_config_manual {
__be32 mode_pkd;
__be32 r3;
__be64 r4;
__be64 r5;
} manual;
struct fw_rss_glb_config_basicvirtual {
__be32 mode_pkd;
__be32 synmapen_to_hashtoeplitz;
#define FW_RSS_GLB_CONFIG_CMD_SYNMAPEN (1U << 8)
#define FW_RSS_GLB_CONFIG_CMD_SYN4TUPENIPV6 (1U << 7)
#define FW_RSS_GLB_CONFIG_CMD_SYN2TUPENIPV6 (1U << 6)
#define FW_RSS_GLB_CONFIG_CMD_SYN4TUPENIPV4 (1U << 5)
#define FW_RSS_GLB_CONFIG_CMD_SYN2TUPENIPV4 (1U << 4)
#define FW_RSS_GLB_CONFIG_CMD_OFDMAPEN (1U << 3)
#define FW_RSS_GLB_CONFIG_CMD_TNLMAPEN (1U << 2)
#define FW_RSS_GLB_CONFIG_CMD_TNLALLLKP (1U << 1)
#define FW_RSS_GLB_CONFIG_CMD_HASHTOEPLITZ (1U << 0)
__be64 r8;
__be64 r9;
} basicvirtual;
} u;
};
#define FW_RSS_GLB_CONFIG_CMD_MODE(x) ((x) << 28)
#define FW_RSS_GLB_CONFIG_CMD_MODE_GET(x) (((x) >> 28) & 0xf)
#define FW_RSS_GLB_CONFIG_CMD_MODE_MANUAL 0
#define FW_RSS_GLB_CONFIG_CMD_MODE_BASICVIRTUAL 1
struct fw_rss_vi_config_cmd {
__be32 op_to_viid;
#define FW_RSS_VI_CONFIG_CMD_VIID(x) ((x) << 0)
__be32 retval_len16;
union fw_rss_vi_config {
struct fw_rss_vi_config_manual {
__be64 r3;
__be64 r4;
__be64 r5;
} manual;
struct fw_rss_vi_config_basicvirtual {
__be32 r6;
__be32 defaultq_to_udpen;
#define FW_RSS_VI_CONFIG_CMD_DEFAULTQ(x) ((x) << 16)
#define FW_RSS_VI_CONFIG_CMD_DEFAULTQ_GET(x) (((x) >> 16) & 0x3ff)
#define FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN (1U << 4)
#define FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN (1U << 3)
#define FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN (1U << 2)
#define FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN (1U << 1)
#define FW_RSS_VI_CONFIG_CMD_UDPEN (1U << 0)
__be64 r9;
__be64 r10;
} basicvirtual;
} u;
};
struct fw_clip_cmd {
__be32 op_to_write;
__be32 alloc_to_len16;
__be64 ip_hi;
__be64 ip_lo;
__be32 r4[2];
};
#define S_FW_CLIP_CMD_ALLOC 31
#define M_FW_CLIP_CMD_ALLOC 0x1
#define V_FW_CLIP_CMD_ALLOC(x) ((x) << S_FW_CLIP_CMD_ALLOC)
#define G_FW_CLIP_CMD_ALLOC(x) \
(((x) >> S_FW_CLIP_CMD_ALLOC) & M_FW_CLIP_CMD_ALLOC)
#define F_FW_CLIP_CMD_ALLOC V_FW_CLIP_CMD_ALLOC(1U)
#define S_FW_CLIP_CMD_FREE 30
#define M_FW_CLIP_CMD_FREE 0x1
#define V_FW_CLIP_CMD_FREE(x) ((x) << S_FW_CLIP_CMD_FREE)
#define G_FW_CLIP_CMD_FREE(x) \
(((x) >> S_FW_CLIP_CMD_FREE) & M_FW_CLIP_CMD_FREE)
#define F_FW_CLIP_CMD_FREE V_FW_CLIP_CMD_FREE(1U)
enum fw_error_type {
FW_ERROR_TYPE_EXCEPTION = 0x0,
FW_ERROR_TYPE_HWMODULE = 0x1,
FW_ERROR_TYPE_WR = 0x2,
FW_ERROR_TYPE_ACL = 0x3,
};
struct fw_error_cmd {
__be32 op_to_type;
__be32 len16_pkd;
union fw_error {
struct fw_error_exception {
__be32 info[6];
} exception;
struct fw_error_hwmodule {
__be32 regaddr;
__be32 regval;
} hwmodule;
struct fw_error_wr {
__be16 cidx;
__be16 pfn_vfn;
__be32 eqid;
u8 wrhdr[16];
} wr;
struct fw_error_acl {
__be16 cidx;
__be16 pfn_vfn;
__be32 eqid;
__be16 mv_pkd;
u8 val[6];
__be64 r4;
} acl;
} u;
};
struct fw_debug_cmd {
__be32 op_type;
#define FW_DEBUG_CMD_TYPE_GET(x) ((x) & 0xff)
__be32 len16_pkd;
union fw_debug {
struct fw_debug_assert {
__be32 fcid;
__be32 line;
__be32 x;
__be32 y;
u8 filename_0_7[8];
u8 filename_8_15[8];
__be64 r3;
} assert;
struct fw_debug_prt {
__be16 dprtstridx;
__be16 r3[3];
__be32 dprtstrparam0;
__be32 dprtstrparam1;
__be32 dprtstrparam2;
__be32 dprtstrparam3;
} prt;
} u;
};
#define FW_PCIE_FW_ERR (1U << 31)
#define FW_PCIE_FW_INIT (1U << 30)
#define FW_PCIE_FW_HALT (1U << 29)
#define FW_PCIE_FW_MASTER_VLD (1U << 15)
#define FW_PCIE_FW_MASTER_MASK 0x7
#define FW_PCIE_FW_MASTER_SHIFT 12
#define FW_PCIE_FW_MASTER(x) ((x) << FW_PCIE_FW_MASTER_SHIFT)
#define FW_PCIE_FW_MASTER_GET(x) (((x) >> FW_PCIE_FW_MASTER_SHIFT) & \
FW_PCIE_FW_MASTER_MASK)
struct fw_hdr {
u8 ver;
u8 chip; /* terminator chip type */
__be16 len512; /* bin length in units of 512-bytes */
__be32 fw_ver; /* firmware version */
__be32 tp_microcode_ver;
u8 intfver_nic;
u8 intfver_vnic;
u8 intfver_ofld;
u8 intfver_ri;
u8 intfver_iscsipdu;
u8 intfver_iscsi;
u8 intfver_fcoepdu;
u8 intfver_fcoe;
__u32 reserved2;
__u32 reserved3;
__u32 reserved4;
__be32 flags;
__be32 reserved6[23];
};
enum fw_hdr_chip {
FW_HDR_CHIP_T4,
FW_HDR_CHIP_T5
};
#define FW_HDR_FW_VER_MAJOR_GET(x) (((x) >> 24) & 0xff)
#define FW_HDR_FW_VER_MINOR_GET(x) (((x) >> 16) & 0xff)
#define FW_HDR_FW_VER_MICRO_GET(x) (((x) >> 8) & 0xff)
#define FW_HDR_FW_VER_BUILD_GET(x) (((x) >> 0) & 0xff)
enum fw_hdr_intfver {
FW_HDR_INTFVER_NIC = 0x00,
FW_HDR_INTFVER_VNIC = 0x00,
FW_HDR_INTFVER_OFLD = 0x00,
FW_HDR_INTFVER_RI = 0x00,
FW_HDR_INTFVER_ISCSIPDU = 0x00,
FW_HDR_INTFVER_ISCSI = 0x00,
FW_HDR_INTFVER_FCOEPDU = 0x00,
FW_HDR_INTFVER_FCOE = 0x00,
};
enum fw_hdr_flags {
FW_HDR_FLAGS_RESET_HALT = 0x00000001,
};
#endif /* _T4FW_INTERFACE_H_ */
| GuoqingJiang/SLE12-clustermd | drivers/net/ethernet/chelsio/cxgb4/t4fw_api.h | C | gpl-2.0 | 64,924 |
/*
* Copyright (C) 2011-2012 BlizzLikeCore <http://blizzlike.servegame.com/>
* Please, read the credits 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 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Isle_of_Queldanas
SD%Complete: 100
SDComment: Quest support: 11524, 11525, 11532, 11533, 11542, 11543, 11541
SDCategory: Isle Of Quel'Danas
EndScriptData */
/* ContentData
npc_converted_sentry
npc_greengill_slave
EndContentData */
#include "ScriptPCH.h"
/*######
## npc_converted_sentry
######*/
enum eConv
{
SAY_CONVERTED_1 = -1000188,
SAY_CONVERTED_2 = -1000189,
SPELL_CONVERT_CREDIT = 45009
};
struct npc_converted_sentryAI : public ScriptedAI
{
npc_converted_sentryAI(Creature *c) : ScriptedAI(c) {}
bool Credit;
uint32 Timer;
void Reset()
{
Credit = false;
Timer = 2500;
}
void MoveInLineOfSight(Unit * /*who*/) {}
void EnterCombat(Unit* /*who*/) {}
void UpdateAI(const uint32 diff)
{
if (!Credit)
{
if (Timer <= diff)
{
uint32 i = urand(1,2);
if (i == 1)
DoScriptText(SAY_CONVERTED_1, me);
else
DoScriptText(SAY_CONVERTED_2, me);
DoCast(me, SPELL_CONVERT_CREDIT);
if (me->isPet())
CAST_PET(me)->SetDuration(7500);
Credit = true;
} else Timer -= diff;
}
}
};
CreatureAI* GetAI_npc_converted_sentry(Creature* pCreature)
{
return new npc_converted_sentryAI (pCreature);
}
/*######
## npc_greengill_slave
######*/
#define ENRAGE 45111
#define ORB 45109
#define QUESTG 11541
#define DM 25060
struct npc_greengill_slaveAI : public ScriptedAI
{
npc_greengill_slaveAI(Creature* c) : ScriptedAI(c) {}
uint64 PlayerGUID;
void EnterCombat(Unit* /*who*/){}
void Reset()
{
PlayerGUID = 0;
}
void SpellHit(Unit* caster, const SpellEntry* spell)
{
if (!caster)
return;
if (caster->GetTypeId() == TYPEID_PLAYER && spell->Id == ORB && !me->HasAura(ENRAGE, 0))
{
PlayerGUID = caster->GetGUID();
if (PlayerGUID)
{
Player* plr = Unit::GetPlayer(*me, PlayerGUID);
if (plr && plr->GetQuestStatus(QUESTG) == QUEST_STATUS_INCOMPLETE)
plr->KilledMonsterCredit(25086, me->GetGUID());
}
DoCast(me, ENRAGE);
Unit* Myrmidon = me->FindNearestCreature(DM, 70);
if (Myrmidon)
{
me->AddThreat(Myrmidon, 100000.0f);
AttackStart(Myrmidon);
}
}
}
void UpdateAI(const uint32 /*diff*/)
{
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_npc_greengill_slaveAI(Creature* pCreature)
{
return new npc_greengill_slaveAI(pCreature);
}
void AddSC_isle_of_queldanas()
{
Script *newscript;
newscript = new Script;
newscript->Name = "npc_converted_sentry";
newscript->GetAI = &GetAI_npc_converted_sentry;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "npc_greengill_slave";
newscript->GetAI = &GetAI_npc_greengill_slaveAI;
newscript->RegisterSelf();
}
| Amara1231/blizzlikecore | src/scripts/EasternKingdoms/isle_of_queldanas.cpp | C++ | gpl-2.0 | 3,896 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Deployer.App {
using Gadgeteer;
using GTM = Gadgeteer.Modules;
public partial class Program : Gadgeteer.Program {
/// <summary>The LED Strip module (not connected).</summary>
private Gadgeteer.Modules.GHIElectronics.LEDStrip ledStrip;
/// <summary>The Button module (not connected).</summary>
private Gadgeteer.Modules.GHIElectronics.Button button;
/// <summary>The Character Display module using socket 2 of the mainboard.</summary>
private Gadgeteer.Modules.GHIElectronics.CharacterDisplay characterDisplay;
/// <summary>The Breakout TB10 module using socket 1 of the mainboard.</summary>
private Gadgeteer.Modules.GHIElectronics.BreakoutTB10 breakoutTB10;
/// <summary>The Tunes module using socket 3 of the mainboard.</summary>
private Gadgeteer.Modules.GHIElectronics.Tunes tunes;
/// <summary>This property provides access to the Mainboard API. This is normally not necessary for an end user program.</summary>
protected new static GHIElectronics.Gadgeteer.FEZCerbuinoNet Mainboard {
get {
return ((GHIElectronics.Gadgeteer.FEZCerbuinoNet)(Gadgeteer.Program.Mainboard));
}
set {
Gadgeteer.Program.Mainboard = value;
}
}
/// <summary>This method runs automatically when the device is powered, and calls ProgramStarted.</summary>
public static void Main() {
// Important to initialize the Mainboard first
Program.Mainboard = new GHIElectronics.Gadgeteer.FEZCerbuinoNet();
Program p = new Program();
p.InitializeModules();
p.ProgramStarted();
// Starts Dispatcher
p.Run();
}
private void InitializeModules() {
Microsoft.SPOT.Debug.Print("The module \'ledStrip\' was not connected in the designer and will be null.");
Microsoft.SPOT.Debug.Print("The module \'button\' was not connected in the designer and will be null.");
this.characterDisplay = new GTM.GHIElectronics.CharacterDisplay(2);
this.breakoutTB10 = new GTM.GHIElectronics.BreakoutTB10(1);
this.tunes = new GTM.GHIElectronics.Tunes(3);
}
}
}
| DevOpsGear/DeployerOfCodes | Deployer.App/Program.generated.cs | C# | gpl-2.0 | 2,778 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Twitch_Downloader.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("mkv")]
public string VideoContainer {
get {
return ((string)(this["VideoContainer"]));
}
set {
this["VideoContainer"] = value;
}
}
}
}
| bcartfall/twitch-downloader | source/Twitch_Downloader/Properties/Settings.Designer.cs | C# | gpl-2.0 | 1,514 |
using Sogyo.CQRS.Library.Infrastructure.Bus.Messages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImageHoster.CQRS.Commands
{
public class DeleteGroup : Command
{
public Guid Id { get; set; }
public Guid GroupId { get; set; }
public Guid UserId { get; set; }
}
}
| ElizaReiGWCD/ImageCandy | ImageHoster.CQRS/Commands/DeleteGroup.cs | C# | gpl-2.0 | 401 |
/*
* This file is part of nzbget. See <http://nzbget.net>.
*
* Copyright (C) 2012-2016 Andrey Prygunkov <hugbug@users.sourceforge.net>
*
* 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 "nzbget.h"
#include "UrlCoordinator.h"
#include "Options.h"
#include "WebDownloader.h"
#include "Util.h"
#include "FileSystem.h"
#include "NzbFile.h"
#include "Scanner.h"
#include "DiskState.h"
#include "QueueScript.h"
void UrlDownloader::ProcessHeader(const char* line)
{
WebDownloader::ProcessHeader(line);
if (!strncmp(line, "X-DNZB-Category:", 16))
{
m_category = Util::Trim(CString(line + 16));
debug("Category: %s", *m_category);
}
else if (!strncmp(line, "X-DNZB-", 7))
{
CString modLine = line;
char* value = strchr(modLine, ':');
if (value)
{
*value = '\0';
value++;
while (*value == ' ') value++;
Util::Trim(value);
debug("X-DNZB: %s", *modLine);
debug("Value: %s", value);
BString<100> paramName("*DNZB:%s", modLine + 7);
CString paramValue = WebUtil::Latin1ToUtf8(value);
m_nzbInfo->GetParameters()->SetParameter(paramName, paramValue);
}
}
}
UrlCoordinator::~UrlCoordinator()
{
debug("Destroying UrlCoordinator");
for (UrlDownloader* urlDownloader : m_activeDownloads)
{
delete urlDownloader;
}
m_activeDownloads.clear();
debug("UrlCoordinator destroyed");
}
void UrlCoordinator::Run()
{
debug("Entering UrlCoordinator-loop");
while (!DownloadQueue::IsLoaded())
{
usleep(20 * 1000);
}
int resetCounter = 0;
while (!IsStopped())
{
bool downloadStarted = false;
if (!g_Options->GetPauseDownload() || g_Options->GetUrlForce())
{
// start download for next URL
GuardedDownloadQueue downloadQueue = DownloadQueue::Guard();
if ((int)m_activeDownloads.size() < g_Options->GetUrlConnections())
{
NzbInfo* nzbInfo = GetNextUrl(downloadQueue);
bool hasMoreUrls = nzbInfo != nullptr;
bool urlDownloadsRunning = !m_activeDownloads.empty();
m_hasMoreJobs = hasMoreUrls || urlDownloadsRunning;
if (hasMoreUrls && !IsStopped())
{
StartUrlDownload(nzbInfo);
downloadStarted = true;
}
}
}
int sleepInterval = downloadStarted ? 0 : 100;
usleep(sleepInterval * 1000);
resetCounter += sleepInterval;
if (resetCounter >= 1000)
{
// this code should not be called too often, once per second is OK
ResetHangingDownloads();
resetCounter = 0;
}
}
WaitJobs();
debug("Exiting UrlCoordinator-loop");
}
void UrlCoordinator::WaitJobs()
{
// waiting for downloads
debug("UrlCoordinator: waiting for Downloads to complete");
while (true)
{
{
GuardedDownloadQueue guard = DownloadQueue::Guard();
if (m_activeDownloads.empty())
{
break;
}
}
usleep(100 * 1000);
ResetHangingDownloads();
}
debug("UrlCoordinator: Downloads are completed");
}
void UrlCoordinator::Stop()
{
Thread::Stop();
debug("Stopping UrlDownloads");
GuardedDownloadQueue guard = DownloadQueue::Guard();
for (UrlDownloader* urlDownloader : m_activeDownloads)
{
urlDownloader->Stop();
}
debug("UrlDownloads are notified");
}
void UrlCoordinator::ResetHangingDownloads()
{
if (g_Options->GetUrlTimeout() == 0)
{
return;
}
GuardedDownloadQueue guard = DownloadQueue::Guard();
time_t tm = Util::CurrentTime();
for (UrlDownloader* urlDownloader: m_activeDownloads)
{
if (tm - urlDownloader->GetLastUpdateTime() > g_Options->GetUrlTimeout() + 10 &&
urlDownloader->GetStatus() == UrlDownloader::adRunning)
{
error("Cancelling hanging url download %s", urlDownloader->GetInfoName());
urlDownloader->Stop();
}
}
}
void UrlCoordinator::LogDebugInfo()
{
info(" ---------- UrlCoordinator");
GuardedDownloadQueue guard = DownloadQueue::Guard();
info(" Active Downloads: %i", (int)m_activeDownloads.size());
for (UrlDownloader* urlDownloader : m_activeDownloads)
{
urlDownloader->LogDebugInfo();
}
}
/*
* Returns next URL for download.
*/
NzbInfo* UrlCoordinator::GetNextUrl(DownloadQueue* downloadQueue)
{
bool pauseDownload = g_Options->GetPauseDownload();
NzbInfo* nzbInfo = nullptr;
for (NzbInfo* nzbInfo1 : downloadQueue->GetQueue())
{
if (nzbInfo1->GetKind() == NzbInfo::nkUrl &&
nzbInfo1->GetUrlStatus() == NzbInfo::lsNone &&
nzbInfo1->GetDeleteStatus() == NzbInfo::dsNone &&
(!pauseDownload || g_Options->GetUrlForce()) &&
(!nzbInfo || nzbInfo1->GetPriority() > nzbInfo->GetPriority()))
{
nzbInfo = nzbInfo1;
}
}
return nzbInfo;
}
void UrlCoordinator::StartUrlDownload(NzbInfo* nzbInfo)
{
debug("Starting new UrlDownloader");
UrlDownloader* urlDownloader = new UrlDownloader();
urlDownloader->SetAutoDestroy(true);
urlDownloader->Attach(this);
urlDownloader->SetNzbInfo(nzbInfo);
urlDownloader->SetUrl(nzbInfo->GetUrl());
urlDownloader->SetForce(g_Options->GetUrlForce());
urlDownloader->SetInfoName(nzbInfo->MakeNiceUrlName(nzbInfo->GetUrl(), nzbInfo->GetFilename()));
urlDownloader->SetOutputFilename(BString<1024>("%s%curl-%i.tmp",
g_Options->GetTempDir(), PATH_SEPARATOR, nzbInfo->GetId()));
nzbInfo->SetActiveDownloads(1);
nzbInfo->SetUrlStatus(NzbInfo::lsRunning);
m_activeDownloads.push_back(urlDownloader);
urlDownloader->Start();
}
void UrlCoordinator::Update(Subject* caller, void* aspect)
{
debug("Notification from UrlDownloader received");
UrlDownloader* urlDownloader = (UrlDownloader*) caller;
if ((urlDownloader->GetStatus() == WebDownloader::adFinished) ||
(urlDownloader->GetStatus() == WebDownloader::adFailed) ||
(urlDownloader->GetStatus() == WebDownloader::adRetry))
{
UrlCompleted(urlDownloader);
}
}
void UrlCoordinator::UrlCompleted(UrlDownloader* urlDownloader)
{
debug("URL downloaded");
NzbInfo* nzbInfo = urlDownloader->GetNzbInfo();
const char* origname;
if (urlDownloader->GetOriginalFilename())
{
origname = urlDownloader->GetOriginalFilename();
}
else
{
origname = FileSystem::BaseFileName(nzbInfo->GetUrl());
// TODO: decode URL escaping
}
CString filename = FileSystem::MakeValidFilename(origname);
debug("Filename: [%s]", *filename);
bool retry;
{
GuardedDownloadQueue downloadQueue = DownloadQueue::Guard();
// remove downloader from downloader list
m_activeDownloads.erase(std::find(m_activeDownloads.begin(), m_activeDownloads.end(), urlDownloader));
nzbInfo->SetActiveDownloads(0);
retry = urlDownloader->GetStatus() == WebDownloader::adRetry && !nzbInfo->GetDeleting();
if (nzbInfo->GetDeleting())
{
nzbInfo->SetDeleteStatus(NzbInfo::dsManual);
nzbInfo->SetUrlStatus(NzbInfo::lsNone);
nzbInfo->SetDeleting(false);
}
else if (urlDownloader->GetStatus() == WebDownloader::adFinished)
{
nzbInfo->SetUrlStatus(NzbInfo::lsFinished);
}
else if (urlDownloader->GetStatus() == WebDownloader::adFailed)
{
nzbInfo->SetUrlStatus(NzbInfo::lsFailed);
}
else if (urlDownloader->GetStatus() == WebDownloader::adRetry)
{
nzbInfo->SetUrlStatus(NzbInfo::lsNone);
}
if (!retry)
{
DownloadQueue::Aspect aspect = {DownloadQueue::eaUrlCompleted, downloadQueue, nzbInfo, nullptr};
downloadQueue->Notify(&aspect);
}
}
if (retry)
{
return;
}
if (nzbInfo->GetUrlStatus() == NzbInfo::lsFinished)
{
// add nzb-file to download queue
Scanner::EAddStatus addStatus = g_Scanner->AddExternalFile(
!Util::EmptyStr(nzbInfo->GetFilename()) ? nzbInfo->GetFilename() : *filename,
!Util::EmptyStr(nzbInfo->GetCategory()) ? nzbInfo->GetCategory() : urlDownloader->GetCategory(),
nzbInfo->GetPriority(), nzbInfo->GetDupeKey(), nzbInfo->GetDupeScore(), nzbInfo->GetDupeMode(),
nzbInfo->GetParameters(), false, nzbInfo->GetAddUrlPaused(), nzbInfo,
urlDownloader->GetOutputFilename(), nullptr, 0, nullptr);
if (addStatus == Scanner::asSuccess)
{
// if scanner has successfully added nzb-file to queue, our pNZBInfo is
// already removed from queue and destroyed
return;
}
nzbInfo->SetUrlStatus(addStatus == Scanner::asFailed ? NzbInfo::lsScanFailed : NzbInfo::lsScanSkipped);
}
// the rest of function is only for failed URLs or for failed scans
g_QueueScriptCoordinator->EnqueueScript(nzbInfo, QueueScriptCoordinator::qeUrlCompleted);
std::unique_ptr<NzbInfo> oldNzbInfo;
{
GuardedDownloadQueue downloadQueue = DownloadQueue::Guard();
// delete URL from queue
oldNzbInfo = downloadQueue->GetQueue()->Remove(nzbInfo);
// add failed URL to history
if (g_Options->GetKeepHistory() > 0 &&
nzbInfo->GetUrlStatus() != NzbInfo::lsFinished &&
!nzbInfo->GetAvoidHistory())
{
std::unique_ptr<HistoryInfo> historyInfo = std::make_unique<HistoryInfo>(std::move(oldNzbInfo));
historyInfo->SetTime(Util::CurrentTime());
downloadQueue->GetHistory()->Add(std::move(historyInfo), true);
downloadQueue->HistoryChanged();
}
downloadQueue->Save();
}
if (oldNzbInfo)
{
g_DiskState->DiscardFiles(oldNzbInfo.get());
}
}
bool UrlCoordinator::DeleteQueueEntry(DownloadQueue* downloadQueue, NzbInfo* nzbInfo, bool avoidHistory)
{
if (nzbInfo->GetActiveDownloads() > 0)
{
info("Deleting active URL %s", nzbInfo->GetName());
nzbInfo->SetDeleting(true);
nzbInfo->SetAvoidHistory(avoidHistory);
for (UrlDownloader* urlDownloader : m_activeDownloads)
{
if (urlDownloader->GetNzbInfo() == nzbInfo)
{
urlDownloader->Stop();
return true;
}
}
}
info("Deleting URL %s", nzbInfo->GetName());
nzbInfo->SetDeleteStatus(NzbInfo::dsManual);
nzbInfo->SetUrlStatus(NzbInfo::lsNone);
std::unique_ptr<NzbInfo> oldNzbInfo = downloadQueue->GetQueue()->Remove(nzbInfo);
if (g_Options->GetKeepHistory() > 0 && !avoidHistory)
{
std::unique_ptr<HistoryInfo> historyInfo = std::make_unique<HistoryInfo>(std::move(oldNzbInfo));
historyInfo->SetTime(Util::CurrentTime());
downloadQueue->GetHistory()->Add(std::move(historyInfo), true);
downloadQueue->HistoryChanged();
}
else
{
g_DiskState->DiscardFiles(oldNzbInfo.get());
}
return true;
}
| ta264/nzbget | daemon/queue/UrlCoordinator.cpp | C++ | gpl-2.0 | 10,514 |
/* @(#)scsi-unixware.c 1.36 04/01/15 Copyright 1998 J. Schilling, Santa Cruz Operation */
#ifndef lint
static char __sccsid[] =
"@(#)scsi-unixware.c 1.36 04/01/15 Copyright 1998 J. Schilling, Santa Cruz Operation";
#endif
/*
* Interface for the SCO UnixWare SCSI implementation.
*
* Warning: you may change this source, but if you do that
* you need to change the _scg_version and _scg_auth* string below.
* You may not return "schily" for an SCG_AUTHOR request anymore.
* Choose your name instead of "schily" and make clear that the version
* string is related to a modified source.
*
* Copyright (c) 1998 J. Schilling, Santa Cruz Operation
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; see the file COPYING. If not, write to the Free Software
* Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#undef sense
#undef SC_PARITY
#undef scb
#include <sys/sysmacros.h> /* XXX Falsch, richtig -> sys/mkdev.h */
#include <sys/scsi.h>
#include <sys/sdi_edt.h>
#include <sys/sdi.h>
/*
* Warning: you may change this source, but if you do that
* you need to change the _scg_version and _scg_auth* string below.
* You may not return "schily" for an SCG_AUTHOR request anymore.
* Choose your name instead of "schily" and make clear that the version
* string is related to a modified source.
*/
LOCAL char _scg_trans_version[] = "scsi-unixware.c-1.36"; /* The version for this transport*/
/* Max. number of scg scsibusses. The real limit would be */
/* MAX_HBA * MAX_BUS (which would be 32 * 8 on UnixWare 2.1/7.x), */
/* but given that we will hardly see such a beast, lets take 32 */
#define MAX_SCG 32
/* maximum defines for UnixWare 2.x/7.x from <sys/sdi_edt.h> */
#define MAX_TGT MAX_EXTCS /* Max # of target id's */
#define MAX_LUN MAX_EXLUS /* Max # of lun's */
#define MAX_DMA (32*1024)
#ifdef __WHAT_TODO__
#define MAX_DMA (16*1024) /* On UnixWare 2.1.x w/ AHA2940 HBA */
/* the max DMA size is 16KB. */
#endif
#define MAXLINE 80
#define MAXPATH 256
#define DEV_DIR "/tmp"
#define DEV_NAME "scg.s%1dt%1dl%1d"
#define SCAN_HBA "%d:%d,%d,%d:%7s : %n"
#define SCAN_DEV "%d,%d,%d:%7s : %n"
#define PRIM_HBA "/dev/hba/hba1"
#define SCSI_CFG "LC_ALL=C /etc/scsi/pdiconfig -l"
#define SCAN_ALL "LIBSCG_SCAN_ALL"
#define SDI_VALID 0x01 /* Entry may be used (non disk) */
#define SDI_ATAPI 0x02 /* Connected via IDE HBA */
#define SDI_INITIATOR 0x04 /* This is the initiator target ID */
typedef struct scg2sdi {
short open;
short flags;
short fd;
char hba;
char bus;
char tgt;
char lun;
dev_t node;
dev_t major;
dev_t minor;
/*#define SCG_DEBUG*/
#ifdef SCG_DEBUG
char type[20];
char vend[40];
char devn[32];
#endif
} scg2sdi_t;
LOCAL scg2sdi_t sdidevs [MAX_SCG][MAX_TGT][MAX_LUN];
LOCAL BOOL sdiinit = FALSE;
struct scg_local {
short scgfiles[MAX_SCG][MAX_TGT][MAX_LUN];
};
#define scglocal(p) ((struct scg_local *)((p)->local))
LOCAL int unixware_init __PR((SCSI *scgp));
LOCAL int do_scg_cmd __PR((SCSI *scgp, struct scg_cmd *sp));
LOCAL int do_scg_sense __PR((SCSI *scgp, struct scg_cmd *sp));
LOCAL FILE *xpopen __PR((char *cmd, char *type));
LOCAL int xpclose __PR((FILE *f));
/*
* -------------------------------------------------------------------------
* SCO UnixWare 2.1.x / UnixWare 7 provides a scsi pass-through mechanism,
* which can be used to access any configured scsi device.
*
* NOTE: The libscg UnixWare passthrough routines have changed with
* cdrecord-1.8 to enable the -scanbus, -load, -eject option
* regardless of the status of media and the addressing
* scheme is now the same as used on many other platforms like
* Solaris, Linux etc.
*
* ===============================================================
* RUN 'cdrecord -scanbus' TO SEE THE DEVICE ADDRESSES YOU CAN USE
* ===============================================================
*/
/*
* Return version information for the low level SCSI transport code.
* This has been introduced to make it easier to trace down problems
* in applications.
*
*/
LOCAL char *
scgo_version(scgp, what)
SCSI *scgp;
int what;
{
if (scgp != (SCSI *)0) {
switch (what) {
case SCG_VERSION:
return (_scg_trans_version);
/*
* If you changed this source, you are not allowed to
* return "schily" for the SCG_AUTHOR request.
*/
case SCG_AUTHOR:
return (_scg_auth_schily);
case SCG_SCCS_ID:
return (__sccsid);
}
}
return ((char *)0);
}
LOCAL int
scgo_help(scgp, f)
SCSI *scgp;
FILE *f;
{
__scg_help(f, "SDI_SEND", "Generic SCSI",
"", "bus,target,lun", "1,2,0", TRUE, FALSE);
return (0);
}
/*
* ---------------------------------------------------------------
* This routine is introduced to create all device nodes necessary
* to access any detected scsi device. It parses the output of
* /etc/scsi/pdiconfig -l and creates passthru device node for each
* found scsi device apart from the listed hba's.
*
*/
LOCAL int
unixware_init(scgp)
SCSI *scgp;
{
FILE *cmd;
int hba = 0, bus = 0, scg = 0, tgt = 0, lun = 0;
int nscg = -1, lhba = -1, lbus = 0;
int atapi, fd, nopen = 0, pos = 0, len = 0;
int s, t, l;
int scan_disks;
char lines[MAXLINE];
char class[MAXLINE];
char ident[MAXLINE];
char devnm[MAXPATH];
char dname[MAXPATH];
struct stat stbuf;
dev_t ptdev, major, minor, node;
char **evsave;
extern char **environ;
/* Check for validity of primary hostbus adapter node */
if (stat(PRIM_HBA, &stbuf) < 0) {
if (scgp->errstr)
js_snprintf(scgp->errstr, SCSI_ERRSTR_SIZE,
"Can not stat() primary hba (%s)",
PRIM_HBA);
return (-1);
}
if (!S_ISCHR(stbuf.st_mode)) {
if (scgp->errstr)
js_snprintf(scgp->errstr, SCSI_ERRSTR_SIZE,
"Primary hba (%s) not a character device",
PRIM_HBA);
return (-1);
}
major = getmajor(stbuf.st_rdev);
/*
* Check whether we want to scan all devices
*/
if (getenv(SCAN_ALL) != NULL) {
scan_disks = 1;
} else {
scan_disks = 0;
}
/* read pdiconfig output and get all attached scsi devices ! */
evsave = environ;
environ = 0;
if ((cmd = xpopen(SCSI_CFG, "r")) == NULL) {
if (scgp->errstr)
js_snprintf(scgp->errstr, SCSI_ERRSTR_SIZE,
"Error popen() for \"%s\"",
SCSI_CFG);
environ = evsave;
return (-1);
}
environ = evsave;
for (;;) {
if (fgets(lines, MAXLINE, cmd) == NULL)
break;
memset(class, '\0', sizeof (class));
memset(ident, '\0', sizeof (ident));
if (lines[0] == ' ') {
sscanf(lines, SCAN_DEV, &bus, &tgt, &lun, class, &pos);
hba = lhba;
} else {
sscanf(lines, SCAN_HBA, &hba, &bus, &tgt, &lun, class, &pos);
nscg++;
lhba = hba;
atapi = 0;
}
/* We can't sscanf() the ident string of the device */
/* as it may contain characters sscanf() will */
/* recognize as a delimiter. So do a strcpy() instead ! */
len = strlen(lines) - pos - 1; /* don't copy the '\n' */
strncpy(ident, &lines[pos], len);
if (scgp->debug > 0) {
js_fprintf((FILE *)scgp->errfile,
"SDI -> %d:%d,%d,%d: %-7s : %s\n",
hba, bus, tgt, lun, class, ident);
}
if (bus != lbus) {
nscg++;
lbus = bus;
}
scg = nscg;
/* check whether we have a HBA or a SCSI device, don't */
/* let HBA's be valid device for cdrecord, but mark */
/* them as a controller (initiator = 1). */
/* Don't detect disks, opening a mounted disk can hang */
/* the disk subsystem !!! So unless we set an */
/* environment variable LIBSCG_SCAN_ALL, we will ignore */
/* disks */
if (strstr(class, "HBA") == NULL) {
if (strstr(class, "DISK") != NULL) {
if (scan_disks)
sdidevs[scg][tgt][lun].flags |= SDI_VALID;
else
sdidevs[scg][tgt][lun].flags &= ~SDI_VALID;
} else {
sdidevs[scg][tgt][lun].flags |= SDI_VALID;
}
} else {
sdidevs[scg][tgt][lun].flags |= SDI_INITIATOR;
}
/* There is no real flag that shows a HBA as an ATAPI */
/* controller, so as we know the driver is called 'ide' */
/* we can check the ident string for the occurence of it*/
if (strstr(ident, "(ide,") != NULL) {
atapi = 1;
}
/*
* Fill the sdidevs array with all we know now.
* Do not overwrite fields that may contain old state like
* sdidevs[scg][tgt][lun].open
*/
if (atapi)
sdidevs[scg][tgt][lun].flags |= SDI_ATAPI;
else
sdidevs[scg][tgt][lun].flags &= ~SDI_ATAPI;
sdidevs[scg][tgt][lun].hba = hba;
sdidevs[scg][tgt][lun].bus = bus;
sdidevs[scg][tgt][lun].tgt = tgt;
sdidevs[scg][tgt][lun].lun = lun;
#ifdef SCG_DEBUG
strcpy(sdidevs[scg][tgt][lun].type, class);
strcpy(sdidevs[scg][tgt][lun].vend, ident);
js_snprintf(sdidevs[scg][tgt][lun].devn,
sizeof (sdidevs[scg][tgt][lun].devn),
DEV_NAME, scg, tgt, lun);
#endif
js_snprintf(devnm, sizeof (devnm),
DEV_NAME, scg, tgt, lun);
minor = SDI_MINOR(hba, tgt, lun, bus);
node = makedevice(major, minor);
sdidevs[scg][tgt][lun].major = major;
sdidevs[scg][tgt][lun].minor = minor;
sdidevs[scg][tgt][lun].node = node;
if (scgp->debug > 0) {
js_fprintf((FILE *)scgp->errfile,
"h = %d; b = %d, s = %d, t = %d, l = %d, a = %d, ma = %d, mi = %2d, dev = '%s', id = '%s'\n",
hba, bus, scg, tgt, lun,
(sdidevs[scg][tgt][lun].flags & SDI_ATAPI) != 0,
sdidevs[scg][tgt][lun].major,
sdidevs[scg][tgt][lun].minor,
devnm,
ident);
}
}
if (xpclose(cmd) == -1) {
if (scgp->errstr)
js_snprintf(scgp->errstr, SCSI_ERRSTR_SIZE,
"Error pclose() for \"%s\"",
SCSI_CFG);
return (-1);
}
/* create all temporary device nodes */
for (s = 0; s < MAX_SCG; s++) {
for (t = 0; t < MAX_TGT; t++) {
for (l = 0; l < MAX_LUN; l++) {
if ((sdidevs[s][t][l].flags & SDI_VALID) == 0) {
if (sdidevs[s][t][l].fd >= 0) {
close(sdidevs[s][t][l].fd);
}
sdidevs[s][t][l].fd = -1;
sdidevs[s][t][l].open = 0;
continue;
}
/* Make pass-through interface device node */
js_snprintf(devnm,
sizeof (devnm),
DEV_NAME, s, t, l);
js_snprintf(dname, sizeof (dname),
"%s/%s", DEV_DIR, devnm);
ptdev = sdidevs[s][t][l].node;
if (mknod(dname, S_IFCHR | 0700, ptdev) < 0) {
if (errno == EEXIST) {
unlink(dname);
if (mknod(dname, S_IFCHR | 0700, ptdev) < 0) {
if (scgp->errstr)
js_snprintf(scgp->errstr, SCSI_ERRSTR_SIZE,
"mknod() error for \"%s\"", dname);
return (-1);
}
} else {
if (scgp->errstr)
js_snprintf(scgp->errstr, SCSI_ERRSTR_SIZE,
"mknod() error for \"%s\"", dname);
return (-1);
}
}
/* Open pass-through device node */
if ((fd = open(dname, O_RDONLY)) < 0) {
if (errno == EBUSY && sdidevs[s][t][l].open > 0) {
/*
* Device has already been opened, just
* return the saved file desc.
*/
fd = sdidevs[s][t][l].fd;
} else {
if (scgp->errstr)
js_snprintf(scgp->errstr, SCSI_ERRSTR_SIZE,
"can not open pass-through %s", dname);
return (-1);
}
}
/*
* If for whatever reason we may open a pass through
* device more than once, this will waste fs's as we
* do not check for sdidevs[s][t][l].fd == -1.
*/
sdidevs[s][t][l].fd = fd;
sdidevs[s][t][l].open++;
nopen++;
scglocal(scgp)->scgfiles[s][t][l] = (short) fd;
if (scgp->debug > 0) {
js_fprintf((FILE *)scgp->errfile,
"s = %d, t = %d, l = %d, dev = %s, fd = %d\n",
s, t, l,
devnm,
sdidevs[s][t][l].fd);
}
}
}
}
return (nopen);
}
LOCAL int
scgo_open(scgp, device)
SCSI *scgp;
char *device;
{
int busno = scg_scsibus(scgp);
int tgt = scg_target(scgp);
int tlun = scg_lun(scgp);
int b, t, l;
if (busno >= MAX_SCG || tgt >= MAX_TGT || tlun >= MAX_LUN) {
errno = EINVAL;
if (scgp->errstr)
js_snprintf(scgp->errstr, SCSI_ERRSTR_SIZE,
"Illegal value for busno, target or lun '%d,%d,%d'",
busno, tgt, tlun);
return (-1);
}
if (scgp->local == NULL) {
scgp->local = malloc(sizeof (struct scg_local));
if (scgp->local == NULL)
return (0);
for (b = 0; b < MAX_SCG; b++) {
for (t = 0; t < MAX_TGT; t++) {
for (l = 0; l < MAX_LUN; l++)
scglocal(scgp)->scgfiles[b][t][l] = (short)-1;
}
}
}
if (!sdiinit) {
sdiinit = TRUE;
memset(sdidevs, 0, sizeof (sdidevs)); /* init tmp_structure */
for (b = 0; b < MAX_SCG; b++) {
for (t = 0; t < MAX_TGT; t++) {
for (l = 0; l < MAX_LUN; l++) {
sdidevs[b][t][l].flags = 0;
sdidevs[b][t][l].fd = -1;
sdidevs[b][t][l].open = 0;
}
}
}
}
if (*device != '\0') { /* we don't allow old dev usage */
errno = EINVAL;
if (scgp->errstr)
js_snprintf(scgp->errstr, SCSI_ERRSTR_SIZE,
"Open by 'devname' no longer supported on this OS");
return (-1);
} else { /* this is the new stuff */
/* it will do the initialisation */
/* and return the number of */
/* detected devices to be used */
/* with the new addressing */
/* scheme. */
return (unixware_init(scgp));
}
}
LOCAL int
scgo_close(scgp)
SCSI *scgp;
{
register int f;
register int b;
register int t;
register int l;
if (scgp->local == NULL)
return (-1);
for (b = 0; b < MAX_SCG; b++) {
for (t = 0; t < MAX_TGT; t++) {
for (l = 0; l < MAX_LUN; l++) {
f = scglocal(scgp)->scgfiles[b][t][l];
if (f >= 0) {
if (sdidevs[b][t][l].open > 0)
sdidevs[b][t][l].open--;
if (sdidevs[b][t][l].open <= 0) {
if (sdidevs[b][t][l].fd >= 0)
close(sdidevs[b][t][l].fd);
sdidevs[b][t][l].fd = -1;
sdidevs[b][t][l].flags &= ~SDI_VALID;
}
}
scglocal(scgp)->scgfiles[b][t][l] = (short)-1;
}
}
}
return (0);
}
LOCAL long
scgo_maxdma(scgp, amt)
SCSI *scgp;
long amt;
{
return (MAX_DMA);
}
LOCAL void *
scgo_getbuf(scgp, amt)
SCSI *scgp;
long amt;
{
if (scgp->debug > 0) {
js_fprintf((FILE *)scgp->errfile,
"scgo_getbuf: %ld bytes\n", amt);
}
scgp->bufbase = (void *) valloc((size_t)(amt));
return (scgp->bufbase);
}
LOCAL void
scgo_freebuf(scgp)
SCSI *scgp;
{
if (scgp->bufbase)
free(scgp->bufbase);
scgp->bufbase = NULL;
}
LOCAL BOOL
scgo_havebus(scgp, busno)
SCSI *scgp;
int busno;
{
register int t;
register int l;
if (busno < 0 || busno >= MAX_SCG)
return (FALSE);
if (scgp->local == NULL)
return (FALSE);
for (t = 0; t < MAX_TGT; t++) {
for (l = 0; l < MAX_LUN; l++)
if (scglocal(scgp)->scgfiles[busno][t][l] >= 0)
return (TRUE);
}
return (FALSE);
}
LOCAL int
scgo_fileno(scgp, busno, tgt, tlun)
SCSI *scgp;
int busno;
int tgt;
int tlun;
{
if (busno < 0 || busno >= MAX_SCG ||
tgt < 0 || tgt >= MAX_TGT ||
tlun < 0 || tlun >= MAX_LUN)
return (-1);
if (scgp->local == NULL)
return (-1);
return ((int)scglocal(scgp)->scgfiles[busno][tgt][tlun]);
}
LOCAL int
scgo_initiator_id(scgp)
SCSI *scgp;
{
register int t;
register int l;
register int busno;
busno = scg_scsibus(scgp);
if (busno < 0 || busno >= MAX_SCG)
return (FALSE);
for (t = 0; t < MAX_TGT; t++) {
for (l = 0; l < MAX_LUN; l++)
if ((sdidevs[busno][t][l].flags & SDI_INITIATOR) != 0) {
if (scgp->debug > 0) {
js_fprintf((FILE *)scgp->errfile,
"scgo_initiator_id: id = %d\n", t);
}
return (t);
}
}
return (-1);
}
LOCAL int
scgo_isatapi(scgp)
SCSI *scgp;
{
/* if the new address method is used we know if this is ATAPI */
return ((sdidevs[scg_scsibus(scgp)][scg_target(scgp)][scg_lun(scgp)].flags & SDI_ATAPI) != 0);
}
LOCAL int
scgo_reset(scgp, what)
SCSI *scgp;
int what;
{
int f = scgp->fd;
errno = EINVAL;
#if defined(SDI_TRESET) || defined(SDI_BRESET)
if (what == SCG_RESET_NOP) {
errno = 0;
return (0);
}
#ifdef SDI_TRESET
if (what == SCG_RESET_TGT) {
errno = 0;
if (ioctl(f, SDI_TRESET, 0) >= 0)
return (0);
}
#endif
#ifdef SDI_BRESET
if (what == SCG_RESET_BUS) {
errno = 0;
if (ioctl(f, SDI_BRESET, 0) >= 0)
return (0);
}
#endif
#endif /* defined(SDI_TRESET) || defined(SDI_BRESET) */
return (-1);
}
LOCAL int
do_scg_cmd(scgp, sp)
SCSI *scgp;
struct scg_cmd *sp;
{
int ret;
int i;
struct sb scsi_cmd;
struct scb *scbp;
memset(&scsi_cmd, 0, sizeof (scsi_cmd));
scsi_cmd.sb_type = ISCB_TYPE;
scbp = &scsi_cmd.SCB;
scbp->sc_cmdpt = (caddr_t) sp->cdb.cmd_cdb;
scbp->sc_cmdsz = sp->cdb_len;
scbp->sc_datapt = sp->addr;
scbp->sc_datasz = sp->size;
if (!(sp->flags & SCG_RECV_DATA) && (sp->size > 0))
scbp->sc_mode = SCB_WRITE;
else
scbp->sc_mode = SCB_READ;
scbp->sc_time = sp->timeout;
sp->error = SCG_NO_ERROR;
errno = 0;
for (;;) {
if ((ret = ioctl(scgp->fd, SDI_SEND, &scsi_cmd)) < 0) {
if (errno == EAGAIN) {
sleep(1);
errno = 0;
continue;
}
sp->ux_errno = errno;
if (errno == 0)
sp->ux_errno = EIO;
sp->error = SCG_RETRYABLE;
#ifdef __needed__
if (errno == ENOTTY || errno == EINVAL ||
errno == EACCES) {
return (-1);
}
#endif
return (ret);
}
break;
}
sp->ux_errno = errno;
sp->resid = scbp->sc_resid;
memset(&sp->u_scb.Scb, 0, sizeof (sp->u_scb.Scb));
sp->u_scb.cmd_scb[0] = scbp->sc_status;
if (sp->u_scb.cmd_scb[0] & 0x02) {
if (sp->ux_errno == 0)
sp->ux_errno = EIO;
}
switch (scbp->sc_comp_code) {
case SDI_ASW : /* Job completed normally */
case SDI_LINKF0 : /* Linked command done without flag */
case SDI_LINKF1 : /* Linked command done with flag */
sp->error = SCG_NO_ERROR;
break;
case SDI_CKSTAT : /* Check the status byte */
sp->error = SCG_NO_ERROR;
break;
case SDI_NOALLOC : /* This block is not allocated */
case SDI_NOTEQ : /* Addressed device not present */
case SDI_OOS : /* Device is out of service */
case SDI_NOSELE : /* The SCSI bus select failed */
case SDI_SBRESC : /* SCSI bus reservation conflict */
sp->error = SCG_FATAL;
if (sp->ux_errno == 0)
sp->ux_errno = EIO;
break;
case SDI_QFLUSH : /* Job was flushed */
case SDI_ABORT : /* Command was aborted */
case SDI_RESET : /* Reset was detected on the bus */
case SDI_CRESET : /* Reset was caused by this unit */
case SDI_V2PERR : /* vtop failed */
case SDI_HAERR : /* Host adapter error */
case SDI_MEMERR : /* Memory fault */
case SDI_SBUSER : /* SCSI bus error */
case SDI_SCBERR : /* SCB error */
case SDI_MISMAT : /* parameter mismatch */
case SDI_PROGRES : /* Job in progress */
case SDI_UNUSED : /* Job not in use */
case SDI_ONEIC : /* More than one immediate request */
case SDI_SFBERR : /* SFB error */
case SDI_TCERR : /* Target protocol error detected */
default:
sp->error = SCG_RETRYABLE;
if (sp->ux_errno == 0)
sp->ux_errno = EIO;
break;
case SDI_TIME : /* Job timed out */
case SDI_TIME_NOABORT : /* Job timed out, but could not be aborted */
sp->error = SCG_TIMEOUT;
if (sp->ux_errno == 0)
sp->ux_errno = EIO;
break;
}
return (0);
}
LOCAL int
do_scg_sense(scgp, sp)
SCSI *scgp;
struct scg_cmd *sp;
{
int ret;
struct scg_cmd s_cmd;
memset((caddr_t)&s_cmd, 0, sizeof (s_cmd));
s_cmd.addr = (caddr_t) sp->u_sense.cmd_sense;
s_cmd.size = sp->sense_len;
s_cmd.flags = SCG_RECV_DATA|SCG_DISRE_ENA;
s_cmd.cdb_len = SC_G0_CDBLEN;
s_cmd.sense_len = CCS_SENSE_LEN;
s_cmd.cdb.g0_cdb.cmd = SC_REQUEST_SENSE;
s_cmd.cdb.g0_cdb.lun = sp->cdb.g0_cdb.lun;
s_cmd.cdb.g0_cdb.count = sp->sense_len;
ret = do_scg_cmd(scgp, &s_cmd);
if (ret < 0)
return (ret);
sp->sense_count = sp->sense_len - s_cmd.resid;
return (ret);
}
LOCAL int
scgo_send(scgp)
SCSI *scgp;
{
struct scg_cmd *sp = scgp->scmd;
int ret;
if (scgp->fd < 0) {
sp->error = SCG_FATAL;
return (0);
}
ret = do_scg_cmd(scgp, sp);
if (ret < 0)
return (ret);
if (sp->u_scb.cmd_scb[0] & S_CKCON)
ret = do_scg_sense(scgp, sp);
return (ret);
}
#define sense u_sense.Sense
#undef SC_PARITY
#define SC_PARITY 0x09
#define scb u_scb.Scb
/*--------------------------------------------------------------------------*/
#include <unixstd.h>
#include <waitdefs.h>
/*
* Simplified version of popen()
* This version of popen() is not usable more than once at a time.
* Needed because /etc/scsi/pdiconfig will not work if euid != uid
*/
LOCAL pid_t po_pid;
LOCAL FILE *
xpopen(cmd, type)
char *cmd;
char *type;
{
FILE *ret;
FILE *pp[2];
if (po_pid != 0)
return ((FILE *)NULL);
if (*type != 'r')
return ((FILE *)NULL);
if (fpipe(pp) == 0)
return ((FILE *)NULL);
if ((po_pid = fork()) == 0) {
setuid(0);
fclose(pp[0]);
(void) fexecl("/bin/sh", stdin, pp[1], stderr,
"sh", "-c", cmd, (char *)0);
_exit(1);
}
fclose(pp[1]);
if (po_pid == (pid_t)-1) {
fclose(pp[0]);
return ((FILE *)NULL);
}
return (pp[0]);
}
LOCAL int
xpclose(f)
FILE *f;
{
int ret = 0;
if (po_pid == 0)
return (-1);
fclose(f);
if (waitpid(po_pid, &ret, 0) < 0)
ret = -1;
po_pid = 0;
return (ret);
}
| Distrotech/cdrdao | scsilib/libscg/scsi-unixware.c | C | gpl-2.0 | 21,446 |
from Plugins.Plugin import PluginDescriptor
from Screens.PluginBrowser import *
from Screens.Ipkg import Ipkg
from Screens.HarddiskSetup import HarddiskSetup
from Components.ProgressBar import ProgressBar
from Components.SelectionList import SelectionList
from Screens.NetworkSetup import *
from enigma import *
from Screens.Standby import *
from Screens.LogManager import *
from Screens.MessageBox import MessageBox
from Plugins.SystemPlugins.SoftwareManager.Flash_online import FlashOnline
from Components.ActionMap import ActionMap, NumberActionMap, HelpableActionMap
from Screens.Screen import Screen
from Screens.TaskView import JobView
from Components.Task import Task, Job, job_manager, Condition
from GlobalActions import globalActionMap
from Screens.ChoiceBox import ChoiceBox
from Tools.BoundFunction import boundFunction
from Tools.LoadPixmap import LoadPixmap
from Tools.Directories import resolveFilename, SCOPE_CURRENT_SKIN, SCOPE_PLUGINS
from Components.MenuList import MenuList
from Components.FileList import FileList
from Components.Label import Label
from Components.ScrollLabel import ScrollLabel
from Components.Pixmap import Pixmap
from Components.config import ConfigSubsection, ConfigInteger, ConfigText, getConfigListEntry, ConfigSelection, ConfigIP, ConfigYesNo, ConfigSequence, ConfigNumber, NoSave, ConfigEnableDisable, configfile
from Components.ConfigList import ConfigListScreen, ConfigList
from Components.Sources.StaticText import StaticText
from Components.Sources.Progress import Progress
from Components.Button import Button
from Components.ActionMap import ActionMap
from Components.SystemInfo import SystemInfo
from Screens.VirtualKeyBoard import VirtualKeyBoard
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
from OPENDROID.OscamSmartcard import *
from enigma import eConsoleAppContainer
from Tools.Directories import fileExists
from Tools.Downloader import downloadWithProgress
from boxbranding import getBoxType, getMachineName, getMachineBrand, getBrandOEM
from enigma import getDesktop
from Screens.InputBox import PinInput
import string
from random import Random
import os
import sys
import re, string
font = 'Regular;16'
import ServiceReference
import time
import datetime
inOPD_panel = None
config.softcam = ConfigSubsection()
config.softcam.actCam = ConfigText(visible_width=200)
config.softcam.actCam2 = ConfigText(visible_width=200)
config.softcam.waittime = ConfigSelection([('0',_("dont wait")),('1',_("1 second")), ('5',_("5 seconds")),('10',_("10 seconds")),('15',_("15 seconds")),('20',_("20 seconds")),('30',_("30 seconds"))], default='15')
if os.path.isfile('/usr/lib/enigma2/python/Plugins/Extensions/MultiQuickButton/plugin.pyo') is True:
try:
from Plugins.Extensions.MultiQuickButton.plugin import *
except:
pass
from OPENDROID.BluePanel import *
from OPENDROID.CronManager import *
from OPENDROID.ScriptRunner import *
from OPENDROID.MountManager import *
from OPENDROID.SwapManager import Swap, SwapAutostart
from OPENDROID.SoftwarePanel import SoftwarePanel
from Plugins.SystemPlugins.SoftwareManager.BackupRestore import BackupScreen, RestoreScreen, BackupSelection, getBackupPath, getBackupFilename
import gettext
def _(txt):
t = gettext.dgettext("OPD_panel", txt)
if t == txt:
print "[OPD_panel] fallback to default translation for", txt
t = gettext.gettext(txt)
return t
def command(comandline, strip=1):
comandline = comandline + " >/tmp/command.txt"
os.system(comandline)
text = ""
if os.path.exists("/tmp/command.txt") is True:
file = open("/tmp/command.txt", "r")
if strip == 1:
for line in file:
text = text + line.strip() + '\n'
else:
for line in file:
text = text + line
if text[-1:] != '\n': text = text + "\n"
file.close()
# if one or last line then remove linefeed
if text[-1:] == '\n': text = text[:-1]
comandline = text
os.system("rm /tmp/command.txt")
return comandline
boxversion = getBoxType()
machinename = getMachineName()
machinebrand = getMachineBrand()
OEMname = getBrandOEM()
OPD_panel_Version = 'OPD PANEL V1.4 (By OPD-Team)'
print "[OPD_panel] machinebrand: %s" % (machinebrand)
print "[OPD_panel] machinename: %s" % (machinename)
print "[OPD_panel] oem name: %s" % (OEMname)
print "[OPD_panel] boxtype: %s" % (boxversion)
panel = open("/tmp/OPD_panel.ver", "w")
panel.write(OPD_panel_Version + '\n')
panel.write("Machinebrand: %s " % (machinebrand)+ '\n')
panel.write("Machinename: %s " % (machinename)+ '\n')
panel.write("oem name: %s " % (OEMname)+ '\n')
panel.write("Boxtype: %s " % (boxversion)+ '\n')
panel.close()
ExitSave = "[Exit] = " +_("Cancel") +" [Ok] =" +_("Save")
class ConfigPORT(ConfigSequence):
def __init__(self, default):
ConfigSequence.__init__(self, seperator = ".", limits = [(1,65535)], default = default)
def main(session, **kwargs):
session.open(OPD_panel)
def Apanel(menuid, **kwargs):
if menuid == "mainmenu":
return [(_("OPD_panel"), main, "OPD_panel", 3)]
else:
return []
def Plugins(**kwargs):
return [
PluginDescriptor(name='OPD_panel', description='OPD_panel GUI 16/5/2016', where=PluginDescriptor.WHERE_MENU, fnc=Apanel),
PluginDescriptor(where=[PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc=camstart),
PluginDescriptor(where=[PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc=SwapAutostart),
PluginDescriptor(name='OPD_panel', description='OPD_panel GUI 16/5/2016', where=PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=main)]
MENU_SKIN = '<screen position="center,center" size="950,470" title="OPD Panel - Main Menu" >\n\t<ePixmap pixmap="/usr/lib/enigma2/python/OPENDROID/icons/redlogo.png" position="0,380" size="950,84" alphatest="on" zPosition="1"/>\n\t<ePixmap pixmap="/usr/lib/enigma2/python/OPENDROID/icons/opendroid_info.png" position="510,11" size="550,354" alphatest="on" zPosition="1"/>\n\t\t<widget source="global.CurrentTime" render="Label" position="450, 340" size="500,24" font="Regular;20" foregroundColor="#FFFFFF" halign="right" transparent="1" zPosition="5">\n\t\t<convert type="ClockToText">>Format%H:%M:%S</convert>\n\t</widget>\n\t<eLabel backgroundColor="#56C856" position="0,330" size="950,1" zPosition="0" />\n <widget name="Mlist" position="70,110" size="705,260" itemHeight="50" scrollbarMode="showOnDemand" transparent="1" zPosition="0" />\n\t<widget name="label1" position="10,340" size="490,25" font="Regular;20" transparent="1" foregroundColor="#f2e000" halign="left" />\n</screen>'
CONFIG_SKIN = '<screen position="center,center" size="600,440" title="PANEL Config" >\n\t<widget name="config" position="10,10" size="580,377" enableWrapAround="1" scrollbarMode="showOnDemand" />\n\t<widget name="labelExitsave" position="90,410" size="420,25" halign="center" font="Regular;20" transparent="1" foregroundColor="#f2e000" />\n</screen>'
INFO_SKIN = '<screen name="OPD_panel" position="center,center" size="730,400" title="OPD_panel" >\n\t<widget name="label2" position="0,10" size="730,25" font="Regular;20" transparent="1" halign="center" foregroundColor="#f2e000" />\n\t<widget name="label1" position="10,45" size="710,350" font="Console;20" zPosition="1" backgroundColor="#251e1f20" transparent="1" />\n</screen>'
INFO_SKIN2 = '<screen name="OPD_panel" position="center,center" size="530,400" title="OPD_panel" backgroundColor="#251e1f20">\n\t<widget name="label1" position="10,50" size="510,340" font="Regular;15" zPosition="1" backgroundColor="#251e1f20" transparent="1" />\n</screen>'
class PanelList(MenuList):
if (getDesktop(0).size().width() == 1920):
def __init__(self, list, font0 = 38, font1 = 28, itemHeight = 60, enableWrapAround = True):
MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)
self.l.setFont(0, gFont("Regular", font0))
self.l.setFont(1, gFont("Regular", font1))
self.l.setItemHeight(itemHeight)
else:
def __init__(self, list, font0 = 24, font1 = 16, itemHeight = 50, enableWrapAround = True):
MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent)
self.l.setFont(0, gFont("Regular", font0))
self.l.setFont(1, gFont("Regular", font1))
self.l.setItemHeight(itemHeight)
def MenuEntryItem(entry):
if (getDesktop(0).size().width() == 1920):
res = [entry]
res.append(MultiContentEntryPixmapAlphaTest(pos=(0, 10), size=(60, 60), png=entry[0]))
res.append(MultiContentEntryText(pos=(110, 5), size=(690, 50), font=0, text=entry[1]))
return res
else:
res = [entry]
res.append(MultiContentEntryPixmapAlphaTest(pos=(0, 5), size=(100, 40), png=entry[0]))
res.append(MultiContentEntryText(pos=(110, 10), size=(440, 40), font=0, text=entry[1]))
return res
from Screens.PiPSetup import PiPSetup
from Screens.InfoBarGenerics import InfoBarPiP
def InfoEntryComponent(file):
png = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, 'icons/' + file + '.png'))
if png == None:
png = LoadPixmap('/usr/lib/enigma2/python/OPENDROID/icons/' + file + '.png')
if png == None:
png = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, 'icons/default.png'))
if png == None:
png = LoadPixmap('/usr/lib/enigma2/python/OPENDROID/icons/default.png')
res = png
return res
class OPD_panel(Screen, InfoBarPiP):
servicelist = None
def __init__(self, session, services = None):
global menu
global inOPD_panel
global pluginlist
global INFOCONF
Screen.__init__(self, session)
self.session = session
self.skin = MENU_SKIN
self.onShown.append(self.setWindowTitle)
self.service = None
INFOCONF = 0
pluginlist = 'False'
try:
print '[OPD_panel] SHOW'
OPD_panel = self
except:
print '[OPD_Panel] Error Hide'
if services is not None:
self.servicelist = services
else:
self.servicelist = None
self.list = []
self['actions'] = ActionMap(['OkCancelActions', 'DirectionActions', 'ColorActions'], {'cancel': self.Exit,
'upUp': self.up,
'downUp': self.down,
'ok': self.ok}, 1)
self['label1'] = Label(OPD_panel_Version)
self.Mlist = []
self.Mlist.append(MenuEntryItem((InfoEntryComponent('ImageFlash'), _('Image-Flasher'), 'ImageFlash')))
self.Mlist.append(MenuEntryItem((InfoEntryComponent('LogManager'), _('Log-Manager'), 'LogManager')))
self.Mlist.append(MenuEntryItem((InfoEntryComponent('SoftwareManager'), _('Software-Manager'), 'software-manager')))
self.Mlist.append(MenuEntryItem((InfoEntryComponent('services'), _('services'), 'services')))
self.Mlist.append(MenuEntryItem((InfoEntryComponent('Infos'), _('Infos'), 'Infos')))
self.Mlist.append(MenuEntryItem((InfoEntryComponent('Infobar_Setup'), _('Infobar_Setup'), 'Infobar_Setup')))
self.onChangedEntry = []
self["Mlist"] = PanelList([])
self["Mlist"].l.setList(self.Mlist)
menu = 0
self['Mlist'].onSelectionChanged.append(self.selectionChanged)
def getCurrentEntry(self):
if self['Mlist'].l.getCurrentSelection():
selection = self['Mlist'].l.getCurrentSelection()[0]
if selection[0] is not None:
return selection[0]
return
def selectionChanged(self):
item = self.getCurrentEntry()
def setWindowTitle(self):
self.setTitle(_('OPD-Main Menu'))
def up(self):
pass
def down(self):
pass
def left(self):
pass
def right(self):
pass
def Red(self):
self.showExtensionSelection1(Parameter='run')
def Green(self):
pass
def yellow(self):
pass
def blue(self):
pass
def Exit(self):
global menu
global inOPD_panel
if menu == 0:
try:
self.service = self.session.nav.getCurrentlyPlayingServiceReference()
service = self.service.toCompareString()
servicename = ServiceReference.ServiceReference(service).getServiceName().replace('\xc2\x87', '').replace('\xc2\x86', '').ljust(16)
print '[OPD_panel] HIDE'
inOPD_panel = None
except:
print '[OPD_panel] Error Hide'
self.close()
elif menu == 1:
self['Mlist'].moveToIndex(0)
self['Mlist'].l.setList(self.oldmlist)
menu = 0
self['label1'].setText(OPD_panel_Version)
elif menu == 2:
self['Mlist'].moveToIndex(0)
self['Mlist'].l.setList(self.oldmlist1)
menu = 1
self['label1'].setText('Infos')
return
def ok(self):
menu = self['Mlist'].l.getCurrentSelection()[0][2]
print '[OPD_panel] MenuItem: ' + menu
if menu == 'services':
self.services()
elif menu == 'Pluginbrowser':
self.session.open(PluginBrowser)
elif menu == 'Infos':
self.Infos()
elif menu == 'Service_Team':
self.session.open(Info, 'Service_Team')
elif menu == 'Info':
self.session.open(Info, 'SystemInfo')
elif menu == 'ImageVersion':
self.session.open(Info, 'ImageVersion')
elif menu == 'FreeSpace':
self.session.open(Info, 'FreeSpace')
elif menu == 'Network':
self.session.open(Info, 'Network')
elif menu == 'Mounts':
self.session.open(Info, 'Mounts')
elif menu == 'Kernel':
self.session.open(Info, 'Kernel')
elif menu == 'Ram':
self.session.open(Info, 'Free')
elif menu == 'Cpu':
self.session.open(Info, 'Cpu')
elif menu == 'Top':
self.session.open(Info, 'Top')
elif menu == 'MemInfo':
self.session.open(Info, 'MemInfo')
elif menu == 'Module':
self.session.open(Info, 'Module')
elif menu == 'Mtd':
self.session.open(Info, 'Mtd')
elif menu == 'Partitions':
self.session.open(Info, 'Partitions')
elif menu == 'Swap':
self.session.open(Info, 'Swap')
elif menu == 'SystemInfo':
self.System()
elif menu == 'CronManager':
self.session.open(CronManager)
elif menu == 'Infobar_Setup':
from OPENDROID.GreenPanel import InfoBarSetup
self.session.open(InfoBarSetup)
elif menu == 'Decoding_Setup':
from OPENDROID.GreenPanel import DecodingSetup
self.session.open(DecodingSetup)
elif menu == 'JobManager':
self.session.open(ScriptRunner)
elif menu == 'software-manager':
self.Software_Manager()
elif menu == 'software-update':
self.session.open(SoftwarePanel)
elif menu == 'backup-settings':
self.session.openWithCallback(self.backupDone, BackupScreen, runBackup=True)
elif menu == 'restore-settings':
self.backuppath = getBackupPath()
self.backupfile = getBackupFilename()
self.fullbackupfilename = self.backuppath + '/' + self.backupfile
if os_path.exists(self.fullbackupfilename):
self.session.openWithCallback(self.startRestore, MessageBox, _('Are you sure you want to restore your STB backup?\nSTB will restart after the restore'))
else:
self.session.open(MessageBox, _('Sorry no backups found!'), MessageBox.TYPE_INFO, timeout=10)
elif menu == 'backup-files':
self.session.openWithCallback(self.backupfiles_choosen, BackupSelection)
elif menu == 'MultiQuickButton':
self.session.open(MultiQuickButton)
elif menu == 'MountManager':
self.session.open(DeviceManager)
elif menu == 'OscamSmartcard':
self.session.open(OscamSmartcard)
elif menu == 'SwapManager':
self.session.open(Swap)
elif menu == 'RedPanel':
self.session.open(RedPanel)
elif menu == 'Yellow-Key-Action':
self.session.open(YellowPanel)
elif menu == 'LogManager':
self.session.open(LogManager)
elif menu == 'ImageFlash':
self.session.open(FlashOnline)
elif menu == 'Samba':
self.session.open(NetworkSamba)
def services(self):
global menu
menu = 1
self['label1'].setText(_('services'))
self.tlist = []
self.oldmlist = []
self.oldmlist = self.Mlist
self.tlist.append(MenuEntryItem((InfoEntryComponent('MountManager'), _('MountManager'), 'MountManager')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('CronManager'), _('CronManager'), 'CronManager')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('JobManager'), _('JobManager'), 'JobManager')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('SwapManager'), _('SwapManager'), 'SwapManager')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('OscamSmartcard'), _('OscamSmartcard'), 'OscamSmartcard')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Samba'), _('Samba'), 'Samba')))
if os.path.isfile('/usr/lib/enigma2/python/Plugins/Extensions/MultiQuickButton/plugin.pyo') is True:
self.tlist.append(MenuEntryItem((InfoEntryComponent('MultiQuickButton'), _('MultiQuickButton'), 'MultiQuickButton')))
self['Mlist'].moveToIndex(0)
self['Mlist'].l.setList(self.tlist)
def Infos(self):
global menu
menu = 1
self['label1'].setText(_('Infos'))
self.tlist = []
self.oldmlist = []
self.oldmlist1 = []
self.oldmlist = self.Mlist
self.tlist.append(MenuEntryItem((InfoEntryComponent('Service_Team'), _('Service_Team'), 'Service_Team')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('ImageVersion'), _('Image-Version'), 'ImageVersion')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('FreeSpace'), _('FreeSpace'), 'FreeSpace')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Kernel'), _('Kernel'), 'Kernel')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Mounts'), _('Mounts'), 'Mounts')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Network'), _('Network'), 'Network')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Ram'), _('Ram'), 'Ram')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('SystemInfo'), _('SystemInfo'), 'SystemInfo')))
self['Mlist'].moveToIndex(0)
self['Mlist'].l.setList(self.tlist)
self.oldmlist1 = self.tlist
def System(self):
global menu
menu = 2
self['label1'].setText(_('System Info'))
self.tlist = []
self.tlist.append(MenuEntryItem((InfoEntryComponent('Cpu'), _('Cpu'), 'Cpu')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('MemInfo'), _('MemInfo'), 'MemInfo')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Mtd'), _('Mtd'), 'Mtd')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Module'), _('Module'), 'Module')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Partitions'), _('Partitions'), 'Partitions')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Swap'), _('Swap'), 'Swap')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Top'), _('Top'), 'Top')))
self['Mlist'].moveToIndex(0)
self['Mlist'].l.setList(self.tlist)
def System_main(self):
global menu
menu = 1
self["label1"].setText(_("Image/Remote Setup"))
self.tlist = []
self.oldmlist = []
self.oldmlist = self.Mlist
self.tlist.append(MenuEntryItem((InfoEntryComponent('Red-Key-Action'), _("Red Panel"), 'Red-Key-Action')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('Blue-Key-Action'), _("Blue Panel"), 'Blue-Key-Action')))
self["Mlist"].moveToIndex(0)
self["Mlist"].l.setList(self.tlist)
def System_main(self):
global menu
menu = 1
self['label1'].setText(_('System'))
self.tlist = []
self.oldmlist = []
self.oldmlist = self.Mlist
self.tlist.append(MenuEntryItem((InfoEntryComponent('Info'), _('Info'), 'Info')))
self['Mlist'].moveToIndex(0)
self['Mlist'].l.setList(self.tlist)
def Software_Manager(self):
global menu
menu = 1
self['label1'].setText(_('Software Manager'))
self.tlist = []
self.oldmlist = []
self.oldmlist = self.Mlist
self.tlist.append(MenuEntryItem((InfoEntryComponent('SoftwareManager'), _('Software update'), 'software-update')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('BackupSettings'), _('Backup Settings'), 'backup-settings')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('RestoreSettings'), _('Restore Settings'), 'restore-settings')))
self.tlist.append(MenuEntryItem((InfoEntryComponent('BackupFiles'), _('Choose backup files'), 'backup-files')))
self['Mlist'].moveToIndex(0)
self['Mlist'].l.setList(self.tlist)
def backupfiles_choosen(self, ret):
config.plugins.configurationbackup.backupdirs.save()
config.plugins.configurationbackup.save()
config.save()
def backupDone(self, retval = None):
if retval is True:
self.session.open(MessageBox, _('Backup done.'), MessageBox.TYPE_INFO, timeout=10)
else:
self.session.open(MessageBox, _('Backup failed.'), MessageBox.TYPE_INFO, timeout=10)
def startRestore(self, ret = False):
if ret == True:
self.exe = True
self.session.open(RestoreScreen, runRestore=True)
class RedPanel(ConfigListScreen, Screen):
def __init__(self, session):
Screen.__init__(self, session)
self.session = session
self.skinName = 'Setup'
Screen.setTitle(self, _('RedPanel') + '...')
self.setup_title = _('RedPanel') + '...'
self['HelpWindow'] = Pixmap()
self['HelpWindow'].hide()
self['status'] = StaticText()
self['footnote'] = Label('')
self['description'] = Label(_(''))
self['labelExitsave'] = Label('[Exit] = ' + _('Cancel') + ' [Ok] =' + _('Save'))
self.onChangedEntry = []
self.list = []
ConfigListScreen.__init__(self, self.list, session=self.session, on_change=self.changedEntry)
self.createSetup()
self['actions'] = ActionMap(['SetupActions', 'ColorActions'], {'ok': self.keySave,
'cancel': self.keyCancel,
'red': self.keyCancel,
'green': self.keySave,
'menu': self.keyCancel}, -2)
self['key_red'] = StaticText(_('Cancel'))
self['key_green'] = StaticText(_('OK'))
if self.selectionChanged not in self['config'].onSelectionChanged:
self['config'].onSelectionChanged.append(self.selectionChanged)
self.selectionChanged()
def createSetup(self):
self.editListEntry = None
self.list = []
self.list.append(getConfigListEntry(_('Show OPD_panel Red-key'), config.plugins.OPD_panel_redpanel.enabled))
self.list.append(getConfigListEntry(_('Show Softcam-Panel Red-key long'), config.plugins.OPD_panel_redpanel.enabledlong))
self['config'].list = self.list
self['config'].setList(self.list)
if config.usage.sort_settings.value:
self['config'].list.sort()
return
def selectionChanged(self):
self['status'].setText(self['config'].getCurrent()[0])
def changedEntry(self):
for x in self.onChangedEntry:
x()
self.selectionChanged()
def getCurrentEntry(self):
return self['config'].getCurrent()[0]
def getCurrentValue(self):
return str(self['config'].getCurrent()[1].getText())
def getCurrentDescription(self):
return self['config'].getCurrent() and len(self['config'].getCurrent()) > 2 and self['config'].getCurrent()[2] or ''
def createSummary(self):
from Screens.Setup import SetupSummary
return SetupSummary
def saveAll(self):
for x in self['config'].list:
x[1].save()
configfile.save()
def keySave(self):
self.saveAll()
self.close()
def cancelConfirm(self, result):
if not result:
return
for x in self['config'].list:
x[1].cancel()
self.close()
def keyCancel(self):
if self['config'].isChanged():
self.session.openWithCallback(self.cancelConfirm, MessageBox, _('Really close without saving settings?'))
else:
self.close()
class YellowPanel(ConfigListScreen, Screen):
def __init__(self, session):
Screen.__init__(self, session)
self.session = session
self.skinName = 'Setup'
Screen.setTitle(self, _('Yellow Key Action') + '...')
self.setup_title = _('Yellow Key Action') + '...'
self['HelpWindow'] = Pixmap()
self['HelpWindow'].hide()
self['status'] = StaticText()
self['footnote'] = Label('')
self['description'] = Label('')
self['labelExitsave'] = Label('[Exit] = ' + _('Cancel') + ' [Ok] =' + _('Save'))
self.onChangedEntry = []
self.list = []
ConfigListScreen.__init__(self, self.list, session=self.session, on_change=self.changedEntry)
self.createSetup()
self['actions'] = ActionMap(['SetupActions', 'ColorActions'], {'ok': self.keySave,
'cancel': self.keyCancel,
'red': self.keyCancel,
'green': self.keySave,
'menu': self.keyCancel}, -2)
self['key_red'] = StaticText(_('Cancel'))
self['key_green'] = StaticText(_('OK'))
if self.selectionChanged not in self['config'].onSelectionChanged:
self['config'].onSelectionChanged.append(self.selectionChanged)
self.selectionChanged()
def createSetup(self):
self.editListEntry = None
self.list = []
self.list.append(getConfigListEntry(_('Yellow Key Action'), config.plugins.OPD_panel_yellowkey.list))
self['config'].list = self.list
self['config'].setList(self.list)
if config.usage.sort_settings.value:
self['config'].list.sort()
return
def selectionChanged(self):
self['status'].setText(self['config'].getCurrent()[0])
def changedEntry(self):
for x in self.onChangedEntry:
x()
self.selectionChanged()
def getCurrentEntry(self):
return self['config'].getCurrent()[0]
def getCurrentValue(self):
return str(self['config'].getCurrent()[1].getText())
def getCurrentDescription(self):
return self['config'].getCurrent() and len(self['config'].getCurrent()) > 2 and self['config'].getCurrent()[2] or ''
def createSummary(self):
from Screens.Setup import SetupSummary
return SetupSummary
def saveAll(self):
for x in self['config'].list:
x[1].save()
configfile.save()
def keySave(self):
self.saveAll()
self.close()
def cancelConfirm(self, result):
if not result:
return
for x in self['config'].list:
x[1].cancel()
self.close()
def keyCancel(self):
if self['config'].isChanged():
self.session.openWithCallback(self.cancelConfirm, MessageBox, _('Really close without saving settings?'))
else:
self.close()
class Info(Screen):
def __init__(self, session, info):
self.service = None
Screen.__init__(self, session)
self.skin = INFO_SKIN
self['label2'] = Label('INFO')
self['label1'] = ScrollLabel()
if info == 'Service_Team':
self.Service_Team()
if info == 'SystemInfo':
self.SystemInfo()
elif info == 'ImageVersion':
self.ImageVersion()
elif info == 'FreeSpace':
self.FreeSpace()
elif info == 'Mounts':
self.Mounts()
elif info == 'Network':
self.Network()
elif info == 'Kernel':
self.Kernel()
elif info == 'Free':
self.Free()
elif info == 'Cpu':
self.Cpu()
elif info == 'Top':
self.Top()
elif info == 'MemInfo':
self.MemInfo()
elif info == 'Module':
self.Module()
elif info == 'Mtd':
self.Mtd()
elif info == 'Partitions':
self.Partitions()
elif info == 'Swap':
self.Swap()
self['actions'] = ActionMap(['OkCancelActions', 'DirectionActions'], {'cancel': self.Exit,
'ok': self.ok,
'up': self.Up,
'down': self.Down}, -1)
return
def Exit(self):
self.close()
def ok(self):
self.close()
def Down(self):
self['label1'].pageDown()
def Up(self):
self['label1'].pageUp()
def Service_Team(self):
try:
self['label2'].setText('INFO')
info1 = self.Do_cmd('cat', '/etc/motd', None)
if info1.find('wElc0me') > -1:
info1 = info1[info1.find('wElc0me'):len(info1)] + '\n'
info1 = info1.replace('|', '')
else:
info1 = info1[info1.find('INFO'):len(info1)] + '\n'
info2 = self.Do_cmd('cat', '/etc/image-version', None)
info3 = self.Do_cut(info1 + info2)
self['label1'].setText(info3)
except:
self['label1'].setText(_('an internal error has occur'))
return
def SystemInfo(self):
try:
self['label2'].setText(_('Image Info'))
info1 = self.Do_cmd('cat', '/etc/version', None)
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def ImageVersion(self):
try:
self['label2'].setText(_('Image Version'))
now = datetime.now()
info1 = 'Date = ' + now.strftime('%d-%B-%Y') + '\n'
info2 = 'Time = ' + now.strftime('%H:%M:%S') + '\n'
info3 = self.Do_cmd('uptime', None, None)
tmp = info3.split(',')
info3 = 'Uptime = ' + tmp[0].lstrip() + '\n'
info4 = self.Do_cmd('cat', '/etc/image-version', ' | head -n 1')
info4 = info4[9:]
info4 = 'Imagetype = ' + info4 + '\n'
info5 = 'Load = ' + self.Do_cmd('cat', '/proc/loadavg', None)
info6 = self.Do_cut(info1 + info2 + info3 + info4 + info5)
self['label1'].setText(info6)
except:
self['label1'].setText(_('an internal error has occur'))
return
def FreeSpace(self):
try:
self['label2'].setText(_('FreeSpace'))
info1 = self.Do_cmd('df', None, '-h')
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Mounts(self):
try:
self['label2'].setText(_('Mounts'))
info1 = self.Do_cmd('mount', None, None)
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Network(self):
try:
self['label2'].setText(_('Network'))
info1 = self.Do_cmd('ifconfig', None, None) + '\n'
info2 = self.Do_cmd('route', None, '-n')
info3 = self.Do_cut(info1 + info2)
self['label1'].setText(info3)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Kernel(self):
try:
self['label2'].setText(_('Kernel'))
info0 = self.Do_cmd('cat', '/proc/version', None)
info = info0.split('(')
info1 = 'Name = ' + info[0] + '\n'
info2 = 'Owner = ' + info[1].replace(')', '') + '\n'
info3 = 'Mainimage = ' + info[2][0:info[2].find(')')] + '\n'
info4 = 'Date = ' + info[3][info[3].find('SMP') + 4:len(info[3])]
info5 = self.Do_cut(info1 + info2 + info3 + info4)
self['label1'].setText(info5)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Free(self):
try:
self['label2'].setText(_('Ram'))
info1 = self.Do_cmd('free', None, None)
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Cpu(self):
try:
self['label2'].setText(_('Cpu'))
info1 = self.Do_cmd('cat', '/proc/cpuinfo', None, " | sed 's/\t\t/\t/'")
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Top(self):
try:
self['label2'].setText(_('Top'))
info1 = self.Do_cmd('top', None, '-b -n1')
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def MemInfo(self):
try:
self['label2'].setText(_('MemInfo'))
info1 = self.Do_cmd('cat', '/proc/meminfo', None)
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Module(self):
try:
self['label2'].setText(_('Module'))
info1 = self.Do_cmd('cat', '/proc/modules', None)
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Mtd(self):
try:
self['label2'].setText(_('Mtd'))
info1 = self.Do_cmd('cat', '/proc/mtd', None)
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Partitions(self):
try:
self['label2'].setText(_('Partitions'))
info1 = self.Do_cmd('cat', '/proc/partitions', None)
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Swap(self):
try:
self['label2'].setText(_('Swap'))
info0 = self.Do_cmd('cat', '/proc/swaps', None, " | sed 's/\t/ /g; s/[ ]* / /g'")
info0 = info0.split('\n')
info1 = ''
for l in info0[1:]:
l1 = l.split(' ')
info1 = info1 + 'Name: ' + l1[0] + '\n'
info1 = info1 + 'Type: ' + l1[1] + '\n'
info1 = info1 + 'Size: ' + l1[2] + '\n'
info1 = info1 + 'Used: ' + l1[3] + '\n'
info1 = info1 + 'Prio: ' + l1[4] + '\n\n'
if info1[-1:] == '\n':
info1 = info1[:-1]
if info1[-1:] == '\n':
info1 = info1[:-1]
info1 = self.Do_cut(info1)
self['label1'].setText(info1)
except:
self['label1'].setText(_('an internal error has occur'))
return
def Do_find(self, text, search):
text = text + ' '
ret = ''
pos = text.find(search)
pos1 = text.find(' ', pos)
if pos > -1:
ret = text[pos + len(search):pos1]
return ret
def Do_cut(self, text):
text1 = text.split('\n')
text = ''
for line in text1:
text = text + line[:95] + '\n'
if text[-1:] == '\n':
text = text[:-1]
return text
def Do_cmd(self, cmd, file, arg, pipe = ''):
try:
if file != None:
if os.path.exists(file) is True:
o = command(cmd + ' ' + file + pipe, 0)
else:
o = 'File not found: \n' + file
elif arg == None:
o = command(cmd, 0)
else:
o = command(cmd + ' ' + arg, 0)
return o
except:
o = ''
return o
return
####################################################################################################################################
class FileDownloadJob(Job):
def __init__(self, url, filename, file):
Job.__init__(self, _('Downloading %s' % file))
FileDownloadTask(self, url, filename)
class DownloaderPostcondition(Condition):
def check(self, task):
return task.returncode == 0
def getErrorMessage(self, task):
return self.error_message
class FileDownloadTask(Task):
def __init__(self, job, url, path):
Task.__init__(self, job, _('Downloading'))
self.postconditions.append(DownloaderPostcondition())
self.job = job
self.url = url
self.path = path
self.error_message = ''
self.last_recvbytes = 0
self.error_message = None
self.download = None
self.aborted = False
return
def run(self, callback):
self.callback = callback
self.download = downloadWithProgress(self.url, self.path)
self.download.addProgress(self.download_progress)
self.download.start().addCallback(self.download_finished).addErrback(self.download_failed)
print '[FileDownloadTask] downloading', self.url, 'to', self.path
def abort(self):
print '[FileDownloadTask] aborting', self.url
if self.download:
self.download.stop()
self.aborted = True
def download_progress(self, recvbytes, totalbytes):
if recvbytes - self.last_recvbytes > 10000:
self.progress = int(100 * (float(recvbytes) / float(totalbytes)))
self.name = _('Downloading') + ' ' + '%d of %d kBytes' % (recvbytes / 1024, totalbytes / 1024)
self.last_recvbytes = recvbytes
def download_failed(self, failure_instance = None, error_message = ''):
self.error_message = error_message
if error_message == '' and failure_instance is not None:
self.error_message = failure_instance.getErrorMessage()
Task.processFinished(self, 1)
return
def download_finished(self, string = ''):
if self.aborted:
self.finish(aborted=True)
else:
Task.processFinished(self, 0)
| trunca/enigma2 | lib/python/OPENDROID/OPD_panel.py | Python | gpl-2.0 | 35,438 |
// The worker we construct depends on the environment we're in (nodejs or webbrowser);
module.exports = function makeChessWorker() {
try {
// Reference error if in nodejs
Worker;
const worker = new Worker('scalachessworker.js');
return worker;
} catch (e) {
const rootDir = `${__dirname.replace('ctrl', '')}/`;
const path =`${rootDir}vendor/scalachessjs/scalachess.js`;
const ChessWorker = require('tiny-worker');
return new ChessWorker(path);
}
} | Happy0/ssb-chess | ctrl/worker.js | JavaScript | gpl-2.0 | 525 |
<?php
/**
* @copyright Copyright (C) 2007-2013 joomleague.at. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! 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.
* See COPYRIGHT.php for copyright notices and details.
*/
defined('_JEXEC') or die('Restricted access');
class JFormFieldTeam extends JFormField
{
protected $type = 'team';
function getInput() {
$db = JFactory::getDbo();
$lang = JFactory::getLanguage();
$extension = "com_joomleague";
$source = JPath::clean(JPATH_ADMINISTRATOR . '/components/' . $extension);
$lang->load($extension, JPATH_ADMINISTRATOR, null, false, false)
|| $lang->load($extension, $source, null, false, false)
|| $lang->load($extension, JPATH_ADMINISTRATOR, $lang->getDefault(), false, false)
|| $lang->load($extension, $source, $lang->getDefault(), false, false);
$query = 'SELECT t.id, t.name FROM #__joomleague_team t ORDER BY name';
$db->setQuery( $query );
$teams = $db->loadObjectList();
$mitems = array(JHtml::_('select.option', '', JText::_('COM_JOOMLEAGUE_GLOBAL_SELECT')));
foreach ( $teams as $team ) {
$mitems[] = JHtml::_('select.option', $team->id, ' '.$team->name. ' ('.$team->id.')' );
}
$output= JHtml::_('select.genericlist', $mitems, $this->name, 'class="inputbox" size="1"', 'value', 'text', $this->value, $this->id );
return $output;
}
}
| xbegault/clrh-idf | administrator/components/com_joomleague/models/fields/team.php | PHP | gpl-2.0 | 1,573 |
/*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2012 Tieto Poland
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <errno.h>
#include <stdbool.h>
#include <glib.h>
#include <gdbus/gdbus.h>
#include "lib/uuid.h"
#include "plugin.h"
#include "adapter.h"
#include "device.h"
#include "profile.h"
#include "dbus-common.h"
#include "error.h"
#include "attrib/gattrib.h"
#include "attrib/att.h"
#include "attrib/gatt.h"
#include "attio.h"
#include "log.h"
/* min length for ATT indication or notification: opcode (1b) + handle (2b) */
#define ATT_HDR_LEN 3
#define ATT_TIMEOUT 30
#define CYCLINGSPEED_INTERFACE "org.bluez.CyclingSpeed1"
#define CYCLINGSPEED_MANAGER_INTERFACE "org.bluez.CyclingSpeedManager1"
#define CYCLINGSPEED_WATCHER_INTERFACE "org.bluez.CyclingSpeedWatcher1"
#define WHEEL_REV_SUPPORT 0x01
#define CRANK_REV_SUPPORT 0x02
#define MULTI_SENSOR_LOC_SUPPORT 0x04
#define WHEEL_REV_PRESENT 0x01
#define CRANK_REV_PRESENT 0x02
#define SET_CUMULATIVE_VALUE 0x01
#define START_SENSOR_CALIBRATION 0x02
#define UPDATE_SENSOR_LOC 0x03
#define REQUEST_SUPPORTED_SENSOR_LOC 0x04
#define RESPONSE_CODE 0x10
#define RSP_SUCCESS 0x01
#define RSP_NOT_SUPPORTED 0x02
#define RSP_INVALID_PARAM 0x03
#define RSP_FAILED 0x04
struct csc;
struct controlpoint_req {
struct csc *csc;
uint8_t opcode;
guint timeout;
GDBusPendingReply reply_id;
DBusMessage *msg;
uint8_t pending_location;
};
struct csc_adapter {
struct btd_adapter *adapter;
GSList *devices; /* list of registered devices */
GSList *watchers;
};
struct csc {
struct btd_device *dev;
struct csc_adapter *cadapter;
GAttrib *attrib;
guint attioid;
/* attio id for measurement characteristics value notifications */
guint attio_measurement_id;
/* attio id for SC Control Point characteristics value indications */
guint attio_controlpoint_id;
struct att_range *svc_range;
uint16_t measurement_ccc_handle;
uint16_t controlpoint_val_handle;
uint16_t feature;
gboolean has_location;
uint8_t location;
uint8_t num_locations;
uint8_t *locations;
struct controlpoint_req *pending_req;
};
struct watcher {
struct csc_adapter *cadapter;
guint id;
char *srv;
char *path;
};
struct measurement {
struct csc *csc;
bool has_wheel_rev;
uint32_t wheel_rev;
uint16_t last_wheel_time;
bool has_crank_rev;
uint16_t crank_rev;
uint16_t last_crank_time;
};
struct characteristic {
struct csc *csc;
char uuid[MAX_LEN_UUID_STR + 1];
};
static GSList *csc_adapters = NULL;
static const char * const location_enum[] = {
"other", "top-of-shoe", "in-shoe", "hip", "front-wheel", "left-crank",
"right-crank", "left-pedal", "right-pedal", "front-hub",
"rear-dropout", "chainstay", "rear-wheel", "rear-hub"
};
static const char *location2str(uint8_t value)
{
if (value < G_N_ELEMENTS(location_enum))
return location_enum[value];
info("Body Sensor Location [%d] is RFU", value);
return location_enum[0];
}
static int str2location(const char *location)
{
size_t i;
for (i = 0; i < G_N_ELEMENTS(location_enum); i++)
if (!strcmp(location_enum[i], location))
return i;
return -1;
}
static gint cmp_adapter(gconstpointer a, gconstpointer b)
{
const struct csc_adapter *cadapter = a;
const struct btd_adapter *adapter = b;
if (adapter == cadapter->adapter)
return 0;
return -1;
}
static gint cmp_device(gconstpointer a, gconstpointer b)
{
const struct csc *csc = a;
const struct btd_device *dev = b;
if (dev == csc->dev)
return 0;
return -1;
}
static gint cmp_watcher(gconstpointer a, gconstpointer b)
{
const struct watcher *watcher = a;
const struct watcher *match = b;
int ret;
ret = g_strcmp0(watcher->srv, match->srv);
if (ret != 0)
return ret;
return g_strcmp0(watcher->path, match->path);
}
static struct csc_adapter *find_csc_adapter(struct btd_adapter *adapter)
{
GSList *l = g_slist_find_custom(csc_adapters, adapter, cmp_adapter);
if (!l)
return NULL;
return l->data;
}
static void destroy_watcher(gpointer user_data)
{
struct watcher *watcher = user_data;
g_free(watcher->path);
g_free(watcher->srv);
g_free(watcher);
}
static struct watcher *find_watcher(GSList *list, const char *sender,
const char *path)
{
struct watcher *match;
GSList *l;
match = g_new0(struct watcher, 1);
match->srv = g_strdup(sender);
match->path = g_strdup(path);
l = g_slist_find_custom(list, match, cmp_watcher);
destroy_watcher(match);
if (l != NULL)
return l->data;
return NULL;
}
static void remove_watcher(gpointer user_data)
{
struct watcher *watcher = user_data;
g_dbus_remove_watch(btd_get_dbus_connection(), watcher->id);
}
static void destroy_csc_adapter(gpointer user_data)
{
struct csc_adapter *cadapter = user_data;
g_slist_free_full(cadapter->watchers, remove_watcher);
g_free(cadapter);
}
static void destroy_csc(gpointer user_data)
{
struct csc *csc = user_data;
if (csc->attioid > 0)
btd_device_remove_attio_callback(csc->dev, csc->attioid);
if (csc->attrib != NULL) {
g_attrib_unregister(csc->attrib, csc->attio_measurement_id);
g_attrib_unregister(csc->attrib, csc->attio_controlpoint_id);
g_attrib_unref(csc->attrib);
}
btd_device_unref(csc->dev);
g_free(csc->svc_range);
g_free(csc->locations);
g_free(csc);
}
static void char_write_cb(guint8 status, const guint8 *pdu, guint16 len,
gpointer user_data)
{
char *msg = user_data;
if (status != 0)
error("%s failed", msg);
g_free(msg);
}
static gboolean controlpoint_timeout(gpointer user_data)
{
struct controlpoint_req *req = user_data;
if (req->opcode == UPDATE_SENSOR_LOC) {
g_dbus_pending_property_error(req->reply_id,
ERROR_INTERFACE ".Failed",
"Operation failed (timeout)");
} else if (req->opcode == SET_CUMULATIVE_VALUE) {
DBusMessage *reply;
reply = btd_error_failed(req->msg,
"Operation failed (timeout)");
g_dbus_send_message(btd_get_dbus_connection(), reply);
dbus_message_unref(req->msg);
}
req->csc->pending_req = NULL;
g_free(req);
return FALSE;
}
static void controlpoint_write_cb(guint8 status, const guint8 *pdu, guint16 len,
gpointer user_data)
{
struct controlpoint_req *req = user_data;
if (status == 0) {
req->timeout = g_timeout_add_seconds(ATT_TIMEOUT,
controlpoint_timeout,
req);
return;
}
error("SC Control Point write failed (opcode=%d)", req->opcode);
if (req->opcode == UPDATE_SENSOR_LOC) {
g_dbus_pending_property_error(req->reply_id,
ERROR_INTERFACE ".Failed",
"Operation failed (%d)", status);
} else if (req->opcode == SET_CUMULATIVE_VALUE) {
DBusMessage *reply;
reply = btd_error_failed(req->msg, "Operation failed");
g_dbus_send_message(btd_get_dbus_connection(), reply);
dbus_message_unref(req->msg);
}
req->csc->pending_req = NULL;
g_free(req);
}
static void read_supported_locations(struct csc *csc)
{
struct controlpoint_req *req;
req = g_new0(struct controlpoint_req, 1);
req->csc = csc;
req->opcode = REQUEST_SUPPORTED_SENSOR_LOC;
csc->pending_req = req;
gatt_write_char(csc->attrib, csc->controlpoint_val_handle,
&req->opcode, sizeof(req->opcode),
controlpoint_write_cb, req);
}
static void read_feature_cb(guint8 status, const guint8 *pdu, guint16 len,
gpointer user_data)
{
struct csc *csc = user_data;
uint8_t value[2];
ssize_t vlen;
if (status) {
error("CSC Feature read failed: %s", att_ecode2str(status));
return;
}
vlen = dec_read_resp(pdu, len, value, sizeof(value));
if (vlen < 0) {
error("Protocol error");
return;
}
if (vlen != sizeof(value)) {
error("Invalid value length for CSC Feature");
return;
}
csc->feature = att_get_u16(value);
if ((csc->feature & MULTI_SENSOR_LOC_SUPPORT)
&& (csc->locations == NULL))
read_supported_locations(csc);
}
static void read_location_cb(guint8 status, const guint8 *pdu,
guint16 len, gpointer user_data)
{
struct csc *csc = user_data;
uint8_t value;
ssize_t vlen;
if (status) {
error("Sensor Location read failed: %s", att_ecode2str(status));
return;
}
vlen = dec_read_resp(pdu, len, &value, sizeof(value));
if (vlen < 0) {
error("Protocol error");
return;
}
if (vlen != sizeof(value)) {
error("Invalid value length for Sensor Location");
return;
}
csc->has_location = TRUE;
csc->location = value;
g_dbus_emit_property_changed(btd_get_dbus_connection(),
device_get_path(csc->dev),
CYCLINGSPEED_INTERFACE, "Location");
}
static void discover_desc_cb(guint8 status, const guint8 *pdu,
guint16 len, gpointer user_data)
{
struct characteristic *ch = user_data;
struct att_data_list *list = NULL;
uint8_t format;
int i;
if (status != 0) {
error("Discover %s descriptors failed: %s", ch->uuid,
att_ecode2str(status));
goto done;
}
list = dec_find_info_resp(pdu, len, &format);
if (list == NULL)
goto done;
if (format != ATT_FIND_INFO_RESP_FMT_16BIT)
goto done;
for (i = 0; i < list->num; i++) {
uint8_t *value;
uint16_t handle, uuid;
uint8_t attr_val[2];
char *msg;
value = list->data[i];
handle = att_get_u16(value);
uuid = att_get_u16(value + 2);
if (uuid != GATT_CLIENT_CHARAC_CFG_UUID)
continue;
if (g_strcmp0(ch->uuid, CSC_MEASUREMENT_UUID) == 0) {
ch->csc->measurement_ccc_handle = handle;
if (g_slist_length(ch->csc->cadapter->watchers) == 0) {
att_put_u16(0x0000, attr_val);
msg = g_strdup("Disable measurement");
} else {
att_put_u16(GATT_CLIENT_CHARAC_CFG_NOTIF_BIT,
attr_val);
msg = g_strdup("Enable measurement");
}
} else if (g_strcmp0(ch->uuid, SC_CONTROL_POINT_UUID) == 0) {
att_put_u16(GATT_CLIENT_CHARAC_CFG_IND_BIT, attr_val);
msg = g_strdup("Enable SC Control Point indications");
} else {
break;
}
gatt_write_char(ch->csc->attrib, handle, attr_val,
sizeof(attr_val), char_write_cb, msg);
/* We only want CCC, can break here */
break;
}
done:
if (list)
att_data_list_free(list);
g_free(ch);
}
static void discover_desc(struct csc *csc, struct gatt_char *c,
struct gatt_char *c_next)
{
struct characteristic *ch;
uint16_t start, end;
start = c->value_handle + 1;
if (c_next != NULL) {
if (start == c_next->handle)
return;
end = c_next->handle - 1;
} else if (c->value_handle != csc->svc_range->end) {
end = csc->svc_range->end;
} else {
return;
}
ch = g_new0(struct characteristic, 1);
ch->csc = csc;
memcpy(ch->uuid, c->uuid, sizeof(c->uuid));
gatt_find_info(csc->attrib, start, end, discover_desc_cb, ch);
}
static void update_watcher(gpointer data, gpointer user_data)
{
struct watcher *w = data;
struct measurement *m = user_data;
struct csc *csc = m->csc;
const char *path = device_get_path(csc->dev);
DBusMessageIter iter;
DBusMessageIter dict;
DBusMessage *msg;
msg = dbus_message_new_method_call(w->srv, w->path,
CYCLINGSPEED_WATCHER_INTERFACE, "MeasurementReceived");
if (msg == NULL)
return;
dbus_message_iter_init_append(msg, &iter);
dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH , &path);
dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
if (m->has_wheel_rev) {
dict_append_entry(&dict, "WheelRevolutions",
DBUS_TYPE_UINT32, &m->wheel_rev);
dict_append_entry(&dict, "LastWheelEventTime",
DBUS_TYPE_UINT16, &m->last_wheel_time);
}
if (m->has_crank_rev) {
dict_append_entry(&dict, "CrankRevolutions",
DBUS_TYPE_UINT16, &m->crank_rev);
dict_append_entry(&dict, "LastCrankEventTime",
DBUS_TYPE_UINT16, &m->last_crank_time);
}
dbus_message_iter_close_container(&iter, &dict);
dbus_message_set_no_reply(msg, TRUE);
g_dbus_send_message(btd_get_dbus_connection(), msg);
}
static void process_measurement(struct csc *csc, const uint8_t *pdu,
uint16_t len)
{
struct measurement m;
uint8_t flags;
flags = *pdu;
pdu++;
len--;
memset(&m, 0, sizeof(m));
if ((flags & WHEEL_REV_PRESENT) && (csc->feature & WHEEL_REV_SUPPORT)) {
if (len < 6) {
error("Wheel revolutions data fields missing");
return;
}
m.has_wheel_rev = true;
m.wheel_rev = att_get_u32(pdu);
m.last_wheel_time = att_get_u16(pdu + 4);
pdu += 6;
len -= 6;
}
if ((flags & CRANK_REV_PRESENT) && (csc->feature & CRANK_REV_SUPPORT)) {
if (len < 4) {
error("Crank revolutions data fields missing");
return;
}
m.has_crank_rev = true;
m.crank_rev = att_get_u16(pdu);
m.last_crank_time = att_get_u16(pdu + 2);
pdu += 4;
len -= 4;
}
/* Notify all registered watchers */
m.csc = csc;
g_slist_foreach(csc->cadapter->watchers, update_watcher, &m);
}
static void measurement_notify_handler(const uint8_t *pdu, uint16_t len,
gpointer user_data)
{
struct csc *csc = user_data;
/* should be at least opcode (1b) + handle (2b) */
if (len < 3) {
error("Invalid PDU received");
return;
}
process_measurement(csc, pdu + 3, len - 3);
}
static void controlpoint_property_reply(struct controlpoint_req *req,
uint8_t code)
{
switch (code) {
case RSP_SUCCESS:
g_dbus_pending_property_success(req->reply_id);
break;
case RSP_NOT_SUPPORTED:
g_dbus_pending_property_error(req->reply_id,
ERROR_INTERFACE ".NotSupported",
"Feature is not supported");
break;
case RSP_INVALID_PARAM:
g_dbus_pending_property_error(req->reply_id,
ERROR_INTERFACE ".InvalidArguments",
"Invalid arguments in method call");
break;
case RSP_FAILED:
g_dbus_pending_property_error(req->reply_id,
ERROR_INTERFACE ".Failed",
"Operation failed");
break;
default:
g_dbus_pending_property_error(req->reply_id,
ERROR_INTERFACE ".Failed",
"Operation failed (%d)", code);
break;
}
}
static void controlpoint_method_reply(struct controlpoint_req *req,
uint8_t code)
{
DBusMessage *reply;
switch (code) {
case RSP_SUCCESS:
reply = dbus_message_new_method_return(req->msg);
break;
case RSP_NOT_SUPPORTED:
reply = btd_error_not_supported(req->msg);
break;
case RSP_INVALID_PARAM:
reply = btd_error_invalid_args(req->msg);
break;
case RSP_FAILED:
reply = btd_error_failed(req->msg, "Failed");
break;
default:
reply = btd_error_failed(req->msg, "Unknown error");
break;
}
g_dbus_send_message(btd_get_dbus_connection(), reply);
dbus_message_unref(req->msg);
}
static void controlpoint_ind_handler(const uint8_t *pdu, uint16_t len,
gpointer user_data)
{
struct csc *csc = user_data;
struct controlpoint_req *req = csc->pending_req;
uint8_t opcode;
uint8_t req_opcode;
uint8_t rsp_code;
uint8_t *opdu;
uint16_t olen;
size_t plen;
if (len < ATT_HDR_LEN) {
error("Invalid PDU received");
return;
}
/* skip ATT header */
pdu += ATT_HDR_LEN;
len -= ATT_HDR_LEN;
if (len < 1) {
error("Op Code missing");
goto done;
}
opcode = *pdu;
pdu++;
len--;
if (opcode != RESPONSE_CODE) {
DBG("Unsupported Op Code received (%d)", opcode);
goto done;
}
if (len < 2) {
error("Invalid Response Code PDU received");
goto done;
}
req_opcode = *pdu;
rsp_code = *(pdu + 1);
pdu += 2;
len -= 2;
if (req == NULL || req->opcode != req_opcode) {
DBG("Indication received without pending request");
goto done;
}
switch (req->opcode) {
case SET_CUMULATIVE_VALUE:
controlpoint_method_reply(req, rsp_code);
break;
case REQUEST_SUPPORTED_SENSOR_LOC:
if (rsp_code == RSP_SUCCESS) {
csc->num_locations = len;
csc->locations = g_memdup(pdu, len);
} else {
error("Failed to read Supported Sendor Locations");
}
break;
case UPDATE_SENSOR_LOC:
csc->location = req->pending_location;
controlpoint_property_reply(req, rsp_code);
g_dbus_emit_property_changed(btd_get_dbus_connection(),
device_get_path(csc->dev),
CYCLINGSPEED_INTERFACE, "Location");
break;
}
csc->pending_req = NULL;
g_source_remove(req->timeout);
g_free(req);
done:
opdu = g_attrib_get_buffer(csc->attrib, &plen);
olen = enc_confirmation(opdu, plen);
if (olen > 0)
g_attrib_send(csc->attrib, 0, opdu, olen, NULL, NULL, NULL);
}
static void discover_char_cb(GSList *chars, guint8 status, gpointer user_data)
{
struct csc *csc = user_data;
uint16_t feature_val_handle = 0;
if (status) {
error("Discover CSCS characteristics: %s",
att_ecode2str(status));
return;
}
for (; chars; chars = chars->next) {
struct gatt_char *c = chars->data;
struct gatt_char *c_next =
(chars->next ? chars->next->data : NULL);
if (g_strcmp0(c->uuid, CSC_MEASUREMENT_UUID) == 0) {
csc->attio_measurement_id =
g_attrib_register(csc->attrib,
ATT_OP_HANDLE_NOTIFY, c->value_handle,
measurement_notify_handler, csc, NULL);
discover_desc(csc, c, c_next);
} else if (g_strcmp0(c->uuid, CSC_FEATURE_UUID) == 0) {
feature_val_handle = c->value_handle;
} else if (g_strcmp0(c->uuid, SENSOR_LOCATION_UUID) == 0) {
DBG("Sensor Location supported");
gatt_read_char(csc->attrib, c->value_handle,
read_location_cb, csc);
} else if (g_strcmp0(c->uuid, SC_CONTROL_POINT_UUID) == 0) {
DBG("SC Control Point supported");
csc->controlpoint_val_handle = c->value_handle;
csc->attio_controlpoint_id = g_attrib_register(
csc->attrib, ATT_OP_HANDLE_IND,
c->value_handle,
controlpoint_ind_handler, csc, NULL);
discover_desc(csc, c, c_next);
}
}
if (feature_val_handle > 0)
gatt_read_char(csc->attrib, feature_val_handle,
read_feature_cb, csc);
}
static void enable_measurement(gpointer data, gpointer user_data)
{
struct csc *csc = data;
uint16_t handle = csc->measurement_ccc_handle;
uint8_t value[2];
char *msg;
if (csc->attrib == NULL || !handle)
return;
att_put_u16(GATT_CLIENT_CHARAC_CFG_NOTIF_BIT, value);
msg = g_strdup("Enable measurement");
gatt_write_char(csc->attrib, handle, value, sizeof(value),
char_write_cb, msg);
}
static void disable_measurement(gpointer data, gpointer user_data)
{
struct csc *csc = data;
uint16_t handle = csc->measurement_ccc_handle;
uint8_t value[2];
char *msg;
if (csc->attrib == NULL || !handle)
return;
att_put_u16(0x0000, value);
msg = g_strdup("Disable measurement");
gatt_write_char(csc->attrib, handle, value, sizeof(value),
char_write_cb, msg);
}
static void attio_connected_cb(GAttrib *attrib, gpointer user_data)
{
struct csc *csc = user_data;
DBG("");
csc->attrib = g_attrib_ref(attrib);
gatt_discover_char(csc->attrib, csc->svc_range->start,
csc->svc_range->end, NULL,
discover_char_cb, csc);
}
static void attio_disconnected_cb(gpointer user_data)
{
struct csc *csc = user_data;
DBG("");
if (csc->attio_measurement_id > 0) {
g_attrib_unregister(csc->attrib, csc->attio_measurement_id);
csc->attio_measurement_id = 0;
}
if (csc->attio_controlpoint_id > 0) {
g_attrib_unregister(csc->attrib, csc->attio_controlpoint_id);
csc->attio_controlpoint_id = 0;
}
g_attrib_unref(csc->attrib);
csc->attrib = NULL;
}
static void watcher_exit_cb(DBusConnection *conn, void *user_data)
{
struct watcher *watcher = user_data;
struct csc_adapter *cadapter = watcher->cadapter;
DBG("cycling watcher [%s] disconnected", watcher->path);
cadapter->watchers = g_slist_remove(cadapter->watchers, watcher);
g_dbus_remove_watch(conn, watcher->id);
if (g_slist_length(cadapter->watchers) == 0)
g_slist_foreach(cadapter->devices, disable_measurement, 0);
}
static DBusMessage *register_watcher(DBusConnection *conn, DBusMessage *msg,
void *data)
{
struct csc_adapter *cadapter = data;
struct watcher *watcher;
const char *sender = dbus_message_get_sender(msg);
char *path;
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
DBUS_TYPE_INVALID))
return btd_error_invalid_args(msg);
watcher = find_watcher(cadapter->watchers, sender, path);
if (watcher != NULL)
return btd_error_already_exists(msg);
watcher = g_new0(struct watcher, 1);
watcher->cadapter = cadapter;
watcher->id = g_dbus_add_disconnect_watch(conn, sender, watcher_exit_cb,
watcher, destroy_watcher);
watcher->srv = g_strdup(sender);
watcher->path = g_strdup(path);
if (g_slist_length(cadapter->watchers) == 0)
g_slist_foreach(cadapter->devices, enable_measurement, 0);
cadapter->watchers = g_slist_prepend(cadapter->watchers, watcher);
DBG("cycling watcher [%s] registered", path);
return dbus_message_new_method_return(msg);
}
static DBusMessage *unregister_watcher(DBusConnection *conn, DBusMessage *msg,
void *data)
{
struct csc_adapter *cadapter = data;
struct watcher *watcher;
const char *sender = dbus_message_get_sender(msg);
char *path;
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
DBUS_TYPE_INVALID))
return btd_error_invalid_args(msg);
watcher = find_watcher(cadapter->watchers, sender, path);
if (watcher == NULL)
return btd_error_does_not_exist(msg);
cadapter->watchers = g_slist_remove(cadapter->watchers, watcher);
g_dbus_remove_watch(conn, watcher->id);
if (g_slist_length(cadapter->watchers) == 0)
g_slist_foreach(cadapter->devices, disable_measurement, 0);
DBG("cycling watcher [%s] unregistered", path);
return dbus_message_new_method_return(msg);
}
static const GDBusMethodTable cyclingspeed_manager_methods[] = {
{ GDBUS_METHOD("RegisterWatcher",
GDBUS_ARGS({ "agent", "o" }), NULL,
register_watcher) },
{ GDBUS_METHOD("UnregisterWatcher",
GDBUS_ARGS({ "agent", "o" }), NULL,
unregister_watcher) },
{ }
};
static int csc_adapter_probe(struct btd_profile *p, struct btd_adapter *adapter)
{
struct csc_adapter *cadapter;
cadapter = g_new0(struct csc_adapter, 1);
cadapter->adapter = adapter;
csc_adapters = g_slist_prepend(csc_adapters, cadapter);
if (!g_dbus_register_interface(btd_get_dbus_connection(),
adapter_get_path(adapter),
CYCLINGSPEED_MANAGER_INTERFACE,
cyclingspeed_manager_methods,
NULL, NULL, cadapter,
destroy_csc_adapter)) {
error("D-Bus failed to register %s interface",
CYCLINGSPEED_MANAGER_INTERFACE);
destroy_csc_adapter(cadapter);
return -EIO;
}
return 0;
}
static void csc_adapter_remove(struct btd_profile *p,
struct btd_adapter *adapter)
{
struct csc_adapter *cadapter;
cadapter = find_csc_adapter(adapter);
if (cadapter == NULL)
return;
csc_adapters = g_slist_remove(csc_adapters, cadapter);
g_dbus_unregister_interface(btd_get_dbus_connection(),
adapter_get_path(cadapter->adapter),
CYCLINGSPEED_MANAGER_INTERFACE);
}
static gboolean property_get_location(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct csc *csc = data;
const char *loc;
if (!csc->has_location)
return FALSE;
loc = location2str(csc->location);
dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &loc);
return TRUE;
}
static void property_set_location(const GDBusPropertyTable *property,
DBusMessageIter *iter,
GDBusPendingPropertySet id, void *data)
{
struct csc *csc = data;
char *loc;
int loc_val;
uint8_t att_val[2];
struct controlpoint_req *req;
if (csc->pending_req != NULL) {
g_dbus_pending_property_error(id,
ERROR_INTERFACE ".InProgress",
"Operation already in progress");
return;
}
if (!(csc->feature & MULTI_SENSOR_LOC_SUPPORT)) {
g_dbus_pending_property_error(id,
ERROR_INTERFACE ".NotSupported",
"Feature is not supported");
return;
}
if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRING) {
g_dbus_pending_property_error(id,
ERROR_INTERFACE ".InvalidArguments",
"Invalid arguments in method call");
return;
}
dbus_message_iter_get_basic(iter, &loc);
loc_val = str2location(loc);
if (loc_val < 0) {
g_dbus_pending_property_error(id,
ERROR_INTERFACE ".InvalidArguments",
"Invalid arguments in method call");
return;
}
req = g_new(struct controlpoint_req, 1);
req->csc = csc;
req->reply_id = id;
req->opcode = UPDATE_SENSOR_LOC;
req->pending_location = loc_val;
csc->pending_req = req;
att_val[0] = UPDATE_SENSOR_LOC;
att_val[1] = loc_val;
gatt_write_char(csc->attrib, csc->controlpoint_val_handle, att_val,
sizeof(att_val), controlpoint_write_cb, req);
}
static gboolean property_exists_location(const GDBusPropertyTable *property,
void *data)
{
struct csc *csc = data;
return csc->has_location;
}
static gboolean property_get_locations(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct csc *csc = data;
DBusMessageIter entry;
int i;
if (!(csc->feature & MULTI_SENSOR_LOC_SUPPORT))
return FALSE;
dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
DBUS_TYPE_STRING_AS_STRING, &entry);
for (i = 0; i < csc->num_locations; i++) {
char *loc = g_strdup(location2str(csc->locations[i]));
dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &loc);
g_free(loc);
}
dbus_message_iter_close_container(iter, &entry);
return TRUE;
}
static gboolean property_exists_locations(const GDBusPropertyTable *property,
void *data)
{
struct csc *csc = data;
return !!(csc->feature & MULTI_SENSOR_LOC_SUPPORT);
}
static gboolean property_get_wheel_rev_sup(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct csc *csc = data;
dbus_bool_t val;
val = !!(csc->feature & WHEEL_REV_SUPPORT);
dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &val);
return TRUE;
}
static gboolean property_get_multi_loc_sup(const GDBusPropertyTable *property,
DBusMessageIter *iter, void *data)
{
struct csc *csc = data;
dbus_bool_t val;
val = !!(csc->feature & MULTI_SENSOR_LOC_SUPPORT);
dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &val);
return TRUE;
}
static const GDBusPropertyTable cyclingspeed_device_properties[] = {
{ "Location", "s", property_get_location, property_set_location,
property_exists_location },
{ "SupportedLocations", "as", property_get_locations, NULL,
property_exists_locations },
{ "WheelRevolutionDataSupported", "b", property_get_wheel_rev_sup },
{ "MultipleLocationsSupported", "b", property_get_multi_loc_sup },
{ }
};
static DBusMessage *set_cumulative_wheel_rev(DBusConnection *conn,
DBusMessage *msg, void *data)
{
struct csc *csc = data;
dbus_uint32_t value;
struct controlpoint_req *req;
uint8_t att_val[5]; /* uint8 opcode + uint32 value */
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_UINT32, &value,
DBUS_TYPE_INVALID))
return btd_error_invalid_args(msg);
if (csc->pending_req != NULL)
return btd_error_in_progress(msg);
req = g_new(struct controlpoint_req, 1);
req->csc = csc;
req->opcode = SET_CUMULATIVE_VALUE;
req->msg = dbus_message_ref(msg);
csc->pending_req = req;
att_val[0] = SET_CUMULATIVE_VALUE;
att_put_u32(value, att_val + 1);
gatt_write_char(csc->attrib, csc->controlpoint_val_handle, att_val,
sizeof(att_val), controlpoint_write_cb, req);
return NULL;
}
static const GDBusMethodTable cyclingspeed_device_methods[] = {
{ GDBUS_ASYNC_METHOD("SetCumulativeWheelRevolutions",
GDBUS_ARGS({ "value", "u" }), NULL,
set_cumulative_wheel_rev) },
{ }
};
static int csc_device_probe(struct btd_profile *p,
struct btd_device *device, GSList *uuids)
{
struct btd_adapter *adapter;
struct csc_adapter *cadapter;
struct csc *csc;
struct gatt_primary *prim;
prim = btd_device_get_primary(device, CYCLING_SC_UUID);
if (prim == NULL)
return -EINVAL;
adapter = device_get_adapter(device);
cadapter = find_csc_adapter(adapter);
if (cadapter == NULL)
return -1;
csc = g_new0(struct csc, 1);
csc->dev = btd_device_ref(device);
csc->cadapter = cadapter;
if (!g_dbus_register_interface(btd_get_dbus_connection(),
device_get_path(device),
CYCLINGSPEED_INTERFACE,
cyclingspeed_device_methods,
NULL,
cyclingspeed_device_properties,
csc, destroy_csc)) {
error("D-Bus failed to register %s interface",
CYCLINGSPEED_INTERFACE);
destroy_csc(csc);
return -EIO;
}
csc->svc_range = g_new0(struct att_range, 1);
csc->svc_range->start = prim->range.start;
csc->svc_range->end = prim->range.end;
cadapter->devices = g_slist_prepend(cadapter->devices, csc);
csc->attioid = btd_device_add_attio_callback(device, attio_connected_cb,
attio_disconnected_cb, csc);
return 0;
}
static void csc_device_remove(struct btd_profile *p,
struct btd_device *device)
{
struct btd_adapter *adapter;
struct csc_adapter *cadapter;
struct csc *csc;
GSList *l;
adapter = device_get_adapter(device);
cadapter = find_csc_adapter(adapter);
if (cadapter == NULL)
return;
l = g_slist_find_custom(cadapter->devices, device, cmp_device);
if (l == NULL)
return;
csc = l->data;
cadapter->devices = g_slist_remove(cadapter->devices, csc);
g_dbus_unregister_interface(btd_get_dbus_connection(),
device_get_path(device),
CYCLINGSPEED_INTERFACE);
}
static struct btd_profile cscp_profile = {
.name = "Cycling Speed and Cadence GATT Driver",
.remote_uuid = CYCLING_SC_UUID,
.adapter_probe = csc_adapter_probe,
.adapter_remove = csc_adapter_remove,
.device_probe = csc_device_probe,
.device_remove = csc_device_remove,
};
static int cyclingspeed_init(void)
{
return btd_profile_register(&cscp_profile);
}
static void cyclingspeed_exit(void)
{
btd_profile_unregister(&cscp_profile);
}
BLUETOOTH_PLUGIN_DEFINE(cyclingspeed, VERSION,
BLUETOOTH_PLUGIN_PRIORITY_DEFAULT,
cyclingspeed_init, cyclingspeed_exit)
| alvarofagner/bluez | profiles/cyclingspeed/cyclingspeed.c | C | gpl-2.0 | 30,257 |
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "monthlypayments".
*
* @property string $houseNumber
* @property string $propertyName
* @property string $tenantName
* @property integer $iDNo
* @property double $rentArreas
* @property double $rentDue
* @property double $totalRentDue
* @property double $rentPaid
* @property double $balance
* @property double $securtiyArreas
* @property double $currentSecAmount
* @property double $securityTotals
* @property double $securityAmountPaid
* @property double $securityBalance
* @property double $water_bill_balance
* @property double $water_bill
* @property double $paid_water_amount
* @property double $water_arreas
* @property double $gabbageArreas
* @property double $curentGabbageAmount
* @property double $GabbageTotals
* @property double $gabbagePaid
* @property double $gabbageBalance
* @property string $receiptNo
* @property string $modeOfPay
* @property string $dateDeposited
* @property string $receivedDate
* @property string $paidBy
* @property string $rentForMonth
* @property string $accountName
* @property integer $accountNo
* @property string $bankName
* @property string $branchName
*/
class Monthlypayments extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'monthlypayments';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['receiptNo'], 'required'],
[['iDNo', 'accountNo'], 'integer'],
[['rentArreas', 'rentDue', 'totalRentDue', 'rentPaid', 'balance',
'securtiyArreas', 'currentSecAmount', 'securityTotals', 'securityAmountPaid',
'securityBalance', 'gabbageArreas', 'curentGabbageAmount', 'GabbageTotals',
'gabbagePaid','water_bill','paid_water_amount','water_arreas', 'gabbageBalance', 'water_bill_balance'], 'number'],
[['modeOfPay'], 'string'],
[['dateDeposited', 'receivedDate', 'rentForMonth'], 'safe'],
[['houseNumber'], 'string', 'max' => 20],
[['propertyName', 'tenantName', 'paidBy'], 'string', 'max' => 40],
[['receiptNo', 'accountName', 'bankName'], 'string', 'max' => 50],
[['branchName'], 'string', 'max' => 20]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'houseNumber' => 'House Number',
'propertyName' => 'Property Name',
'tenantName' => 'Tenant Name',
'iDNo' => 'ID number',
'rentArreas' => 'Rent Arreas',
'rentDue' => 'Rent Due',
'totalRentDue' => 'Total Rent Due',
'rentPaid' => 'Rent Paid',
'balance' => 'Balance',
'securtiyArreas' => 'Security Arreas',
'currentSecAmount' => 'Security Amount',
'securityTotals' => 'Security Totals',
'securityAmountPaid' => 'Security Amount Paid',
'securityBalance' => 'Security Balance',
'water_bill' => 'Water Bill',
'paid_water_amount'=> 'Water bill Amount Paid',
'water_arreas' => 'Water Arreas',
'water_bill_balance' => 'water bill Balance',
'gabbageArreas' => 'Gabbage Arreas',
'curentGabbageAmount' => ' Gabbage Amount',
'GabbageTotals' => 'Gabbage Totals',
'gabbagePaid' => 'Gabbage Paid',
'gabbageBalance' => 'Gabbage Balance',
'receiptNo' => 'Receipt No',
'modeOfPay' => 'Mode Of Pay',
'dateDeposited' => 'Date Deposited',
'receivedDate' => 'Received Date',
'paidBy' => 'Paid By',
'rentForMonth' => 'Rent For Month',
'accountName' => 'Account Name',
'accountNo' => 'Account No',
'bankName' => 'Bank Name',
'branchName' => 'Branch Name',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public static function getBalance($houseNo) {
$monthlypayments = Monthlypayments::find()
->where(['houseNumber' => $houseNo])
->orderBy('rentForMonth DESC')
->limit(1)
->select(['houseNo AS name','houseNo AS id'])->asArray()->all();
return $monthlypayments;
}
}
| mirr254/paki | models/Monthlypayments.php | PHP | gpl-2.0 | 4,365 |
#include "gtest/gtest.h"
#include "pinhao/Support/YamlOptions.h"
#include "yaml-cpp/yaml.h"
#include <fstream>
using namespace pinhao;
const std::string Filename("dummy.yaml");
/*
* string-opt: string
* int-opt: 42
* vector-opt:
* - 10
* - 20
* - 30
* map-opt:
* ten: 10
* twenty: 20
* thirty: 30
*/
void createDummyFile() {
std::ofstream Out(Filename);
YAML::Emitter Emitter(Out);
Emitter << YAML::BeginMap;
Emitter << YAML::Key << "string-opt" << YAML::Value << "string";
Emitter << YAML::Key << "int-opt" << YAML::Value << "42";
Emitter << YAML::Key << "vector-opt" << YAML::BeginSeq;
Emitter << "10" << "20" << "30" << YAML::EndSeq;
Emitter << YAML::Key << "map-opt" << YAML::BeginMap;
Emitter << YAML::Key << "ten" << YAML::Value << "10";
Emitter << YAML::Key << "twenty" << YAML::Value << "20";
Emitter << YAML::Key << "thirty" << YAML::Value << "30";
Emitter << YAML::EndMap;
Emitter << YAML::EndMap;
}
void checkOpt(config::YamlOpt<std::string> &Opt, YAML::Node Result) {
ASSERT_EQ(Opt.get(), Result.as<std::string>());
}
void checkOpt(config::YamlOpt<int> &Opt, YAML::Node Result) {
ASSERT_EQ(Opt.get(), Result.as<int>());
}
void checkOpt(config::YamlOpt<std::vector<int>> &Opt, YAML::Node Result) {
std::vector<int> Vector = Opt.get();
ASSERT_EQ(Vector.size(), 3);
for (int I = 0, E = Vector.size(); I < E; ++I)
ASSERT_EQ(Vector[I], Result[I].as<int>());
}
void checkOpt(config::YamlOpt<std::map<std::string, int>> &Opt, YAML::Node Result) {
std::map<std::string, int> Map = Opt.get();
ASSERT_EQ(Map.size(), 3);
for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
std::string Key = I->first.as<std::string>();
ASSERT_TRUE(Map.count(Key) > 0);
ASSERT_EQ(Map[Key], I->second.as<int>());
}
}
TEST(YamlOptionsTest, StringTest) {
YAML::Node Node;
Node["string-opt"] = "string";
config::YamlOpt<std::string> String("string-opt", "The String Option.", true, "");
ASSERT_EQ(String.get(), "");
config::parseOptions(Node);
checkOpt(String, Node["string-opt"]);
}
TEST(YamlOptionsTest, IntTest) {
YAML::Node Node;
Node["int-opt"] = "50";
config::YamlOpt<int> Int("int-opt", "The Int Option.", true, 10);
ASSERT_EQ(Int.get(), 10);
config::parseOptions(Node);
checkOpt(Int, Node["int-opt"]);
}
TEST(YamlOptionsTest, VectorTest) {
YAML::Node Node;
Node["vector-opt"].push_back(10);
Node["vector-opt"].push_back(20);
Node["vector-opt"].push_back(30);
config::YamlOpt<std::vector<int>> VectorInt("vector-opt", "The Vector Option.", true);
ASSERT_EQ(VectorInt.get().size(), 0);
config::parseOptions(Node);
checkOpt(VectorInt, Node["vector-opt"]);
}
TEST(YamlOptionsTest, MapTest) {
YAML::Node Node;
Node["map-opt"]["ten"] = "10";
Node["map-opt"]["twenty"] = "20";
Node["map-opt"]["thirty"] = "30";
config::YamlOpt<std::map<std::string, int>> MapInt("map-opt", "The Map Option.", true);
ASSERT_EQ(MapInt.get().size(), 0);
config::parseOptions(Node);
checkOpt(MapInt, Node["map-opt"]);
}
TEST(YamlOptionsTest, ParseTest) {
config::YamlOpt<std::string> String("string-opt", "The String Option.", true, "Default");
config::YamlOpt<int> Int("int-opt", "The Int Option.", true, 10);
config::YamlOpt<std::vector<int>> Vector("vector-opt", "The Vector Option.", true);
config::YamlOpt<std::map<std::string, int>> Map("map-opt", "The Map Option.", true);
ASSERT_EQ(String.get(), "Default");
ASSERT_EQ(Int.get(), 10);
ASSERT_EQ(Vector.get().size(), 0);
ASSERT_EQ(Map.get().size(), 0);
config::parseOptions(Filename);
YAML::Node Node = YAML::LoadFile(Filename);
checkOpt(String, Node["string-opt"]);
checkOpt(Int, Node["int-opt"]);
checkOpt(Vector, Node["vector-opt"]);
checkOpt(Map, Node["map-opt"]);
}
int main(int argc, char **argv) {
createDummyFile();
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| YuKill/pinhao | tests/YamlOptionsTest.cpp | C++ | gpl-2.0 | 3,918 |
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.dlna;
public class WebAudioStream extends WebStream {
public WebAudioStream(String fluxName, String URL, String thumbURL) {
super(fluxName, URL, thumbURL, MediaType.AUDIO);
}
}
| DigitalMediaServer/DigitalMediaServer | src/main/java/net/pms/dlna/WebAudioStream.java | Java | gpl-2.0 | 979 |
<?php
$apps = [];
foreach(glob('../public/apps/*/manifest.json') as $app)
{
$apps[] = [
'manifest' => json_decode(file_get_contents($app)),
'install_time' => 0,
'path' => str_replace(['../public', '..', 'manifest.json'], '', $app)
];
}
$wallpapers = [];
foreach(glob('../public/images/*') as $wall)
{
$wallpapers[] = [
'src' => str_replace(['../public', '..'], '', $wall)
];
}
$windows = WindowQuery::create()
->filterByUserId($from->user['id'])
->find()->toArray();
$windows = array_map(function($w){
return array_change_key_case($w, CASE_LOWER);
}, $windows);
$labels = LabelQuery::create()
->filterByUserId($from->user['id'])
->find()->toArray();
$labels = array_map(function($l) use($apps){
$l = array_change_key_case($l, CASE_LOWER);
$l['app'] = $apps[$l['appid']];
return $l;
}, $labels);
$config = [
'windows' => [
'active' => 0,
'list' => $windows
],
'apps' => [
'list' => $apps
],
'labels' => $labels,
'wallpapers' => $wallpapers,
'user' => $from->user,
'notify' => []
];
$from->send(json_encode([
'callback' => $data->callback,
'status' => 'ok',
'data' => $config
])); | z81/PolarOSServer | commands/get.php | PHP | gpl-2.0 | 1,340 |
<?php
/**
* @file
* Zen theme's implementation to display the basic html structure of a single
* Drupal page.
*
* Variables:
* - $css: An array of CSS files for the current page.
* - $language: (object) The language the site is being displayed in.
* $language->language contains its textual representation. $language->dir
* contains the language direction. It will either be 'ltr' or 'rtl'.
* - $html_attributes: String of attributes for the html element. It can be
* manipulated through the variable $html_attributes_array from preprocess
* functions.
* - $html_attributes_array: Array of html attribute values. It is flattened
* into a string within the variable $html_attributes.
* - $rdf_namespaces: All the RDF namespace prefixes used in the HTML document.
* - $grddl_profile: A GRDDL profile allowing agents to extract the RDF data.
* - $head_title: A modified version of the page title, for use in the TITLE
* tag.
* - $head_title_array: (array) An associative array containing the string parts
* that were used to generate the $head_title variable, already prepared to be
* output as TITLE tag. The key/value pairs may contain one or more of the
* following, depending on conditions:
* - title: The title of the current page, if any.
* - name: The name of the site.
* - slogan: The slogan of the site, if any, and if there is no title.
* - $head: Markup for the HEAD section (including meta tags, keyword tags, and
* so on).
* - $default_mobile_metatags: TRUE if default mobile metatags for responsive
* design should be displayed.
* - $styles: Style tags necessary to import all CSS files for the page.
* - $scripts: Script tags necessary to load the JavaScript files and settings
* for the page.
* - $skip_link_anchor: The HTML ID of the element that the "skip link" should
* link to. Defaults to "main-menu".
* - $skip_link_text: The text for the "skip link". Defaults to "Jump to
* Navigation".
* - $page_top: Initial markup from any modules that have altered the
* page. This variable should always be output first, before all other dynamic
* content.
* - $page: The rendered page content.
* - $page_bottom: Final closing markup from any modules that have altered the
* page. This variable should always be output last, after all other dynamic
* content.
* - $classes: String of classes that can be used to style contextually through
* CSS. It should be placed within the <body> tag. When selecting through CSS
* it's recommended that you use the body tag, e.g., "body.front". It can be
* manipulated through the variable $classes_array from preprocess functions.
* The default values can contain one or more of the following:
* - front: Page is the home page.
* - not-front: Page is not the home page.
* - logged-in: The current viewer is logged in.
* - not-logged-in: The current viewer is not logged in.
* - node-type-[node type]: When viewing a single node, the type of that node.
* For example, if the node is a Blog entry, this would be "node-type-blog".
* Note that the machine name of the content type will often be in a short
* form of the human readable label.
* The following only apply with the default sidebar_first and sidebar_second
* block regions:
* - two-sidebars: When both sidebars have content.
* - no-sidebars: When no sidebar content exists.
* - one-sidebar and sidebar-first or sidebar-second: A combination of the
* two classes when only one of the two sidebars have content.
*
* @see template_preprocess()
* @see template_preprocess_html()
* @see zen_preprocess_html()
* @see template_process()
*/
?><!DOCTYPE html>
<!--[if IEMobile 7]><html class="iem7" <?php print $html_attributes; ?>><![endif]-->
<!--[if lte IE 6]><html class="lt-ie9 lt-ie8 lt-ie7" <?php print $html_attributes; ?>><![endif]-->
<!--[if (IE 7)&(!IEMobile)]><html class="lt-ie9 lt-ie8" <?php print $html_attributes; ?>><![endif]-->
<!--[if IE 8]><html class="lt-ie9" <?php print $html_attributes; ?>><![endif]-->
<!--[if (gte IE 9)|(gt IEMobile 7)]><!--><html <?php print $html_attributes . $rdf_namespaces; ?>><!--<![endif]-->
<head profile="<?php print $grddl_profile; ?>">
<?php print $head; ?>
<title><?php
//echo ($head_title_array['title']) ? $head_title_array['title']." | ";
if($head_title_array['title']) echo $head_title_array['title']." | ";
echo "Austin Public Library";
?></title>
<?php if ($default_mobile_metatags): ?>
<meta name="MobileOptimized" content="width">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width">
<?php endif; ?>
<meta http-equiv="cleartype" content="on">
<?php print $styles; ?>
<?php print $scripts; ?>
<?php if ($add_respond_js): ?>
<!--[if lt IE 9]>
<script src="<?php print $base_path . $path_to_zen; ?>/js/html5-respond.js"></script>
<![endif]-->
<?php elseif ($add_html5_shim): ?>
<!--[if lt IE 9]>
<script src="<?php print $base_path . $path_to_zen; ?>/js/html5.js"></script>
<![endif]-->
<?php endif; ?>
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
<?php if ($skip_link_text && $skip_link_anchor): ?>
<p id="skip-link">
<!--<a href="#<?php print $skip_link_anchor; ?>" class="element-invisible element-focusable"><?php print $skip_link_text; ?></a>-->
<a href="#block-nice-menus-1" class="element-invisible element-focusable"><?php print $skip_link_text; ?></a>
</p>
<?php endif; ?>
<?php print $page_top; ?>
<?php print $page; ?>
<?php print $page_bottom; ?>
</body>
</html>
| bnyce/apl | sites/all/themes/apl_2014/templates/html.tpl.php | PHP | gpl-2.0 | 5,661 |
package com.o2o.business.app;
import com.o2o.core.base.BaseController;
import com.o2o.model.request.FeedBack;
import com.o2o.model.result.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* IDEA
* 提交app用户反馈接口
*
* @Description Created by bowen.ma on 14-10-6.
*/
@Controller
@RequestMapping("/app")
public class FeedBackController extends BaseController {
@RequestMapping("/feedback.json")
@ResponseBody
public Result commitFeedBack(FeedBack feedBack) {
String msg = feedBack.valid(feedBack);
Result result = new Result();
if (msg != null) {
setStatusError(result, msg);
return result;
}
setStatusOk(result, null);
return result;
}
}
| canmind/interface | src/main/java/com/o2o/business/app/FeedBackController.java | Java | gpl-2.0 | 882 |
CREATE DATABASE IF NOT EXISTS `adtracker` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `adtracker`;
-- MySQL dump 10.13 Distrib 5.5.43, for debian-linux-gnu (x86_64)
--
-- Host: 127.0.0.1 Database: adtracker
-- ------------------------------------------------------
-- Server version 5.5.43-0ubuntu0.14.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `goals_converted`
--
DROP TABLE IF EXISTS `goals_converted`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `goals_converted` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`d1` varchar(45) NOT NULL,
`appId` varchar(45) NOT NULL,
`goal` varchar(45) NOT NULL,
`ts` varchar(45) NOT NULL,
`adg` varchar(45) NOT NULL,
`cmp` varchar(45) NOT NULL,
`click_ts` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `goals_converted`
--
LOCK TABLES `goals_converted` WRITE;
/*!40000 ALTER TABLE `goals_converted` DISABLE KEYS */;
INSERT INTO `goals_converted` VALUES (1,'deviceid1','appId1','download','14523494742','adg1','cmp1','1970-08-15'),(2,'deviceid3','appId1','download','14523494742','adg2','cmp2','1970-08-15'),(3,'asjd','kjsd','download','1283759','abc','jhasd','1970-01-01');
/*!40000 ALTER TABLE `goals_converted` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2015-07-03 17:04:09
| chetan-anand/bootcamp-Adtracker | adtracker_goals_converted.sql | SQL | gpl-2.0 | 2,480 |
#
# Copyright (C) 2014-2017 Jian Chang <aa65535@live.com>
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=shadowsocks-libev
PKG_VERSION:=3.0.2
PKG_RELEASE:=2
PKG_SOURCE_PROTO:=git
PKG_SOURCE_URL:=https://github.com/shadowsocks/shadowsocks-libev.git
PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION)-$(PKG_RELEASE)
PKG_SOURCE_VERSION:=46fa5de9e40eabba94d50375b1263d6d51ca9841
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION)-$(PKG_SOURCE_VERSION).tar.xz
PKG_LICENSE:=GPLv3
PKG_LICENSE_FILES:=LICENSE
PKG_MAINTAINER:=Jian Chang <aa65535@live.com>
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)/$(BUILD_VARIANT)/$(PKG_NAME)-$(PKG_VERSION)-$(PKG_RELEASE)
PKG_INSTALL:=1
PKG_FIXUP:=autoreconf
PKG_USE_MIPS16:=0
PKG_BUILD_PARALLEL:=1
include $(INCLUDE_DIR)/package.mk
define Package/shadowsocks-libev/Default
SECTION:=net
CATEGORY:=Network
TITLE:=Lightweight Secured Socks5 Proxy
URL:=https://github.com/shadowsocks/shadowsocks-libev
DEPENDS:=+libev +libudns +libpcre +libpthread +libsodium +libmbedtls
endef
Package/shadowsocks-libev = $(Package/shadowsocks-libev/Default)
Package/shadowsocks-libev-server = $(Package/shadowsocks-libev/Default)
define Package/shadowsocks-libev/description
Shadowsocks-libev is a lightweight secured socks5 proxy for embedded devices and low end boxes.
endef
Package/shadowsocks-libev-server/description = $(Package/shadowsocks-libev/description)
CONFIGURE_ARGS += --disable-ssp --disable-documentation --disable-assert --with-crypto-library=mbedtls
define Package/shadowsocks-libev/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/src/ss-{local,redir,tunnel} $(1)/usr/bin
endef
define Package/shadowsocks-libev-server/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/src/ss-server $(1)/usr/bin
endef
$(eval $(call BuildPackage,shadowsocks-libev))
$(eval $(call BuildPackage,shadowsocks-libev-server))
| male-puppies/openwrt-packages-puppies | net/shadowsocks-libev/Makefile | Makefile | gpl-2.0 | 1,976 |
<?php
/**
* @version CVS: 1.0.0
* @package Com_Catering
* @author Cristopher Chong <chris@none.ru>
* @copyright 2017 nOne
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
jimport('joomla.form.formfield');
/**
* Supports an HTML select list of categories
*
* @since 1.6
*/
class JFormFieldCreatedby extends JFormField
{
/**
* The form field type.
*
* @var string
* @since 1.6
*/
protected $type = 'createdby';
/**
* Method to get the field input markup.
*
* @return string The field input markup.
*
* @since 1.6
*/
protected function getInput()
{
// Initialize variables.
$html = array();
// Load user
$user_id = $this->value;
if ($user_id)
{
$user = JFactory::getUser($user_id);
}
else
{
$user = JFactory::getUser();
$html[] = '<input type="hidden" name="' . $this->name . '" value="' . $user->id . '" />';
}
if (!$this->hidden)
{
$html[] = "<div>" . $user->name . " (" . $user->username . ")</div>";
}
return implode($html);
}
}
| vicarius123/100 | components/com_catering/models/fields/createdby.php | PHP | gpl-2.0 | 1,107 |
/*
* (C) Copyright 2009 DENX Software Engineering
* Author: John Rigby <jrigby@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#ifndef __CONFIG_H
#define __CONFIG_H
//only used in fdl2 .in uart download, the debug infors from serial will break the download process.
#define CONFIG_FDL2_PRINT 0
#define BOOT_NATIVE_LINUX (0)
#define CONFIG_SILENT_CONSOLE
#define CONFIG_GPIOLIB 1
//#define NAND_DEBUG
//#define DEBUG
#define U_BOOT_SPRD_VER 1
/*#define SPRD_EVM_TAG_ON 1*/
#ifdef SPRD_EVM_TAG_ON
#define SPRD_EVM_ADDR_START 0x40006000
#define SPRD_EVM_TAG(_x) (*(((unsigned long *)SPRD_EVM_ADDR_START)+_x) = *(volatile unsigned long *)0x87003004)
#endif
#define CONFIG_L2_OFF 1
#define BOOT_DEBUG 1
#define CONFIG_YAFFS2 1
#define BOOT_PART "boot"
//#define BOOT_PART "kernel"
#define RECOVERY_PART "recovery"
/*
* SPREADTRUM BIGPHONE board - SoC Configuration
*/
#define CONFIG_SC8810
#define CONFIG_SP8810
#define CONFIG_SP6821A
#ifdef CONFIG_SC8810
#define CHIP_ENDIAN_LITTLE
#define SC8800S_LITTLE_ENDIAN FALSE
#define _LITTLE_ENDIAN 1
#define EXT_MEM_TYPE_DDR 1
#endif
#define CONFIG_RAM128M
#define BB_DRAM_TYPE_256MB_32BIT
#define CONFIG_MTD_NAND_SC8810 1
#define CONFIG_SYS_HZ 1000
#define CONFIG_SPRD_TIMER_CLK 1000 /*32768*/
//#define CONFIG_SYS_HUSH_PARSER
#ifdef CONFIG_SYS_HUSH_PARSER
#define CONFIG_SYS_PROMPT_HUSH_PS2 "> "
#endif
#define DSP_SIZE (3968 * 1024)
#define VMJALUNA_SIZE (300 * 1024)
#ifdef CONFIG_SP8810W
#define FIXNV_SIZE (120 * 1024)
#define FIRMWARE_SIZE (9933 * 1024) /* 9.7M */
#else
#define FIXNV_SIZE (64 * 1024)
#define SIMLOCK_SIZE 1024
#endif
#define PRODUCTINFO_SIZE (3 * 1024)
#define RUNTIMENV_SIZE (256 * 1024)
#ifdef MCP_F2R1
#define MODEM_SIZE (3500 * 1024) /* 3.5MB */
#else
#define MODEM_SIZE (6 * 1024 * 1024)
#endif
#define CONFIG_SPL_LOAD_LEN (0x4000)
#define PRODUCTINFO_ADR (0x00490000)
/*#define CMDLINE_NEED_CONV */
#define WATCHDOG_LOAD_VALUE 0x4000
#define CONFIG_SYS_STACK_SIZE 0x400
//#define CONFIG_SYS_MONITOR_LEN (256 << 10) /* 256 kB for U-Boot */
/* NAND BOOT is the only boot method */
#define CONFIG_NAND_U_BOOT
#define DYNAMIC_CRC_TABLE
/* Start copying real U-boot from the second page */
#define CONFIG_SYS_NAND_U_BOOT_OFFS 0x40000
#define CONFIG_SYS_NAND_U_BOOT_SIZE 0x80000
#define RAM_TYPPE_IS_SDRAM 0
/* Load U-Boot to this address */
#define CONFIG_SYS_NAND_U_BOOT_DST 0x00f00000
#define CONFIG_SYS_NAND_U_BOOT_START CONFIG_SYS_NAND_U_BOOT_DST
#ifdef CONFIG_NAND_SPL
#define CONFIG_SYS_SDRAM_BASE 0x00000000
#define CONFIG_SYS_INIT_SP_ADDR (CONFIG_SYS_SDRAM_BASE + 0x4000)
#else
#define CONFIG_MMU_TABLE_ADDR (0x40000000)
#define CONFIG_SYS_SDRAM_BASE 0x00000000
#define CONFIG_SYS_INIT_SP_ADDR \
(CONFIG_SYS_SDRAM_BASE + 0x1000 - GENERATED_GBL_DATA_SIZE)
#define CONFIG_SKIP_LOWLEVEL_INIT
#endif
#define CONFIG_HW_WATCHDOG
#define CONFIG_DISPLAY_CPUINFO
#define CONFIG_CMDLINE_TAG 1 /* enable passing of ATAGs */
#define CONFIG_SETUP_MEMORY_TAGS 1
#define CONFIG_INITRD_TAG 1
/*
* Memory Info
*/
/* malloc() len */
#define CONFIG_SYS_MALLOC_LEN (2 << 20) /* 1 MiB */
/*
* Board has 2 32MB banks of DRAM but there is a bug when using
* both so only the first is configured
*/
#define CONFIG_NR_DRAM_BANKS 1
#define PHYS_SDRAM_1 0x00000000
#define PHYS_SDRAM_1_SIZE 0x10000000
#if (CONFIG_NR_DRAM_BANKS == 2)
#define PHYS_SDRAM_2 0x90000000
#define PHYS_SDRAM_2_SIZE 0x02000000
#endif
/* 8MB DRAM test */
#define CONFIG_SYS_MEMTEST_START PHYS_SDRAM_1
#define CONFIG_SYS_MEMTEST_END (PHYS_SDRAM_1+0x0800000)
#define CONFIG_STACKSIZE (256 * 1024) /* regular stack */
/*
* Serial Info
*/
#define CONFIG_SPRD_UART 1
#define CONFIG_SYS_SC8800X_UART1 1
#define CONFIG_CONS_INDEX 1 /* use UART0 for console */
#define CONFIG_BAUDRATE 115200 /* Default baud rate */
#define CONFIG_SYS_BAUDRATE_TABLE { 9600, 19200, 38400, 57600, 115200 }
/*
* Flash & Environment
*/
/* No NOR flash present */
#define CONFIG_SYS_MONITOR_LEN ((CONFIG_SYS_NAND_U_BOOT_OFFS)+(CONFIG_SYS_NAND_U_BOOT_SIZE))
#define CONFIG_SYS_NO_FLASH 1
#define CONFIG_ENV_IS_NOWHERE
#define CONFIG_ENV_SIZE (128 * 1024)
/*
#define CONFIG_ENV_IS_IN_NAND
#define CONFIG_ENV_OFFSET CONFIG_SYS_MONITOR_LEN
#define CONFIG_ENV_OFFSET_REDUND (CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE)
*/
/* NAND */
#define CONFIG_NAND_SC8810
#define CONFIG_SPRD_NAND_REGS_BASE (0x60000000)
#define CONFIG_SYS_MAX_NAND_DEVICE 1
#define CONFIG_SYS_NAND_BASE (0x60000000)
//#define CONFIG_JFFS2_NAND
//#define CONFIG_SPRD_NAND_HWECC
#define CONFIG_SYS_NAND_HW_ECC
#define CONFIG_SYS_NAND_LARGEPAGE
//#define CONFIG_SYS_NAND_5_ADDR_CYCLE
#define CONFIG_SYS_64BIT_VSPRINTF
#define CONFIG_CMD_MTDPARTS
#define CONFIG_MTD_PARTITIONS
#define CONFIG_MTD_DEVICE
#define CONFIG_CMD_UBI
#define CONFIG_RBTREE
/* U-Boot general configuration */
#define CONFIG_SYS_PROMPT "=> " /* Monitor Command Prompt */
#define CONFIG_SYS_CBSIZE 1024 /* Console I/O Buffer Size */
/* Print buffer sz */
#define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE + \
sizeof(CONFIG_SYS_PROMPT) + 16)
#define CONFIG_SYS_MAXARGS 32 /* max number of command args */
/* Boot Argument Buffer Size */
#define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE
#define CONFIG_CMDLINE_EDITING
#define CONFIG_SYS_LONGHELP
/* support OS choose */
#undef CONFIG_BOOTM_NETBSD
#undef CONFIG_BOOTM_RTEMS
/* U-Boot commands */
#include <config_cmd_default.h>
#define CONFIG_CMD_NAND
#undef CONFIG_CMD_FPGA
#undef CONFIG_CMD_LOADS
#undef CONFIG_CMD_NET
#undef CONFIG_CMD_NFS
#undef CONFIG_CMD_SETGETDCR
#define CONFIG_ENV_OVERWRITE
#ifdef SPRD_EVM_TAG_ON
#define CONFIG_BOOTDELAY 0
#else
#define CONFIG_BOOTDELAY 0
#define CONFIG_ZERO_BOOTDELAY_CHECK
#endif
#define CONFIG_LOADADDR 0x01000000 /* loadaddr env var */
#define CONFIG_SYS_LOAD_ADDR CONFIG_LOADADDR
#define xstr(s) str(s)
#define str(s) #s
#define MTDIDS_DEFAULT "nand0=sprd-nand"
#ifdef CONFIG_G2PHONE
#define MTDPARTS_DEFAULT "mtdparts=sprd-nand:384k@256k(boot),256k(params),6m(kernel),6m(ramdisk),6m(recovery),70m(system),30m(userdata),7m(cache)"
#define CONFIG_BOOTARGS "mem=64M console=ttyS1,115200n8 init=/init "MTDPARTS_DEFAULT
#elif defined CONFIG_SP8810
/*#define MTDPARTS_DEFAULT "mtdparts=sprd-nand:256k(spl),384k(2ndbl),128k(params),512k(vmjaluna),6016k(modem),7680k(kernel),5120k(dsp),1280k(fixnv),2560k(runtimenv),6400k(recovery),100m(system),198m(userdata),1m(boot_logo),1m(fastboot_logo),2m(cache),256k(misc)"*/
//#define MTDPARTS_DEFAULT "mtdparts=sprd-nand:256k(spl),512k(2ndbl),128k(params),512k(vmjaluna),10m(modem),10m(boot),5120k(dsp),1280k(fixnv),3840k(backupfixnv),3840k(runtimenv),10m(recovery),150m(system),300m(userdata),1m(boot_logo),1m(fastboot_logo),2m(cache),256k(misc)"
//#define MTDPARTS_DEFAULT "mtdparts=sprd-nand:256k(spl),512k(2ndbl),128k(params),512k(vmjaluna),10m(modem),10m(boot)"
//#define MTDPARTS_DEFAULT "mtdparts=sprd-nand:256k(spl),512k(2ndbl),256k(params),512k(vmjaluna),10m(modem),3840k(fixnv),3840k(backupfixnv),5120k(dsp),3840k(runtimenv),10m(boot),10m(recovery),250m(system),180m(userdata),20m(cache),256k(misc),1m(boot_logo),1m(fastboot_logo),3840k(productinfo),512k(kpanic)"
//#define MTDPARTS_DEFAULT "mtdparts=sprd-nand:256k(spl),768k(2ndbl),256k(params),512k(vmjaluna),6m(modem),2816k(fixnv),2816k(backupfixnv),4m(dsp),3840k(runtimenv),6m(boot),6m(recovery),110m(system),97m(userdata),7m(cache),256k(misc),512k(boot_logo),512k(fastboot_logo),2816k(productinfo),512k(kpanic),512k(simlock)"
#define MTDPARTS_DEFAULT "mtdparts=sprd-nand:256k(spl),768k(2ndbl),256k(params),512k(vmjaluna),6m(modem),2816k(fixnv),2816k(backupfixnv),4m(dsp),3840k(runtimenv),6m(boot),6m(recovery),110m(system),87m(userdata),10m(media),7m(cache),256k(misc),512k(boot_logo),512k(fastboot_logo),2816k(productinfo),512k(kpanic),512k(simlock)"
#define CONFIG_BOOTARGS "mem=240M console=ttyS1,115200n8 init=/init " MTDPARTS_DEFAULT
#endif
#define CONFIG_LOOP_PER_JIFFY 3350528
#define COPY_LINUX_KERNEL_SIZE (0x600000)
#define LINUX_INITRD_NAME "modem"
#define CONFIG_BOOTCOMMAND "cboot normal"
#define CONFIG_EXTRA_ENV_SETTINGS ""
#ifdef CONFIG_CMD_NET
#define CONFIG_IPADDR 192.168.10.2
#define CONFIG_SERVERIP 192.168.10.5
#define CONFIG_NETMASK 255.255.255.0
#define CONFIG_USBNET_DEVADDR 26:03:ee:00:87:9f
#define CONFIG_USBNET_HOSTADDR 9a:04:c7:d6:30:d0
#define CONFIG_NET_MULTI
#define CONFIG_CMD_DNS
#define CONFIG_CMD_NFS
#define CONFIG_CMD_RARP
#define CONFIG_CMD_PING
/*#define CONFIG_CMD_SNTP */
#endif
#define CONFIG_USB_GADGET_SC8800G
#define CONFIG_USB_DWC
#define CONFIG_USB_GADGET_DUALSPEED
//#define CONFIG_USB_ETHER
#define CONFIG_CMD_FASTBOOT
#define SCRATCH_ADDR 0x1000000
#define FB_DOWNLOAD_BUF_SIZE (200*1024*1024)
#define CONFIG_MODEM_CALIBERATE
/*
#define CONFIG_UPDATE_TFTP
#define CONFIG_FIT
#define CONFIG_OF_LIBFDT
#define CONFIG_SYS_MAX_FLASH_BANKS 1
#define CONFIG_SYS_MAX_FLASH_SECT 128
*/
#define CONFIG_LCD
#ifdef CONFIG_LCD
#define CONFIG_SPLASH_SCREEN
#define LCD_BPP LCD_COLOR16
#define CONFIG_LCD_HVGA 1
//#define CONFIG_LCD_WVGA 1
//#define CONFIG_LCD_INFO
//#define LCD_TEST_PATTERN
//#define CONFIG_LCD_LOGO
#define CONFIG_SYS_WHITE_ON_BLACK
#define CONFIG_LCD_HX8357_1
#define CONFIG_LCD_ILI9481
#define CONFIG_LCD_NT35310
#define CONFIG_LCD_HX8357D
#define CONFIG_LCD_R61581B
#define CONFIG_LCD_ILI9488
#define CONFIG_LCD_DATA_WIDTH_8BIT 1
#ifdef LCD_TEST_PATTERN
#define CONSOLE_COLOR_RED 0xf800
#define CONSOLE_COLOR_GREEN 0x07e0
#define CONSOLE_COLOR_YELLOW 0x07e0
#define CONSOLE_COLOR_BLUE 0x001f
#define CONSOLE_COLOR_MAGENTA 0x001f
#define CONSOLE_COLOR_CYAN 0x001f
#endif
#endif // CONFIG_LCD
/*
* MMC definition
*/
#define CONFIG_CMD_MMC
#ifdef CONFIG_CMD_MMC
#define CONFIG_CMD_FAT 1
#define CONFIG_FAT_WRITE 1
#define CONFIG_MMC 1
#define CONFIG_GENERIC_MMC 1
#define CONFIG_SDHCI 1
#define CONFIG_SYS_MMC_MAX_BLK_COUNT 0x1000
#define CONFIG_MMC_SDMA 1
#define CONFIG_MV_SDHCI 1
#define CONFIG_DOS_PARTITION 1
#define CONFIG_EFI_PARTITION 1
#define CONFIG_SYS_MMC_NUM 1
#define CONFIG_SYS_MMC_BASE {0x20500000}
#endif
#define CALIBRATE_ENUM_MS 15000
#define CALIBRATE_IO_MS 10000
#define LOW_BAT_VOL 3500 /*phone battery voltage low than this value will not boot up*/
#define LOW_BAT_VOL_CHG 3300 //3.3V charger connect
#define PWR_KEY_DETECT_CNT 12 /*this should match the count of boot_pwr_check() function */
#define ALARM_LEAD_SET_MS 0 /* time set for alarm boot in advancd */
#define CONFIG_SPRD_SYSDUMP
#define SPRD_SYSDUMP_MAGIC (128*1024*1024 - SZ_1M)
#define CONFIG_RAMDUMP_NO_SPLIT 1 /* Don't split sysdump file */
/* press key to enter fastboot mode, the keycode same to linux keycode,
* remove the define if not need
* */
#define CONFIG_FASTBOOT_KEY 139
//======================== Macro for ZYT =================================
#define CONFIG_ZYT_SUPPORT
// Select Freecom Customer Name.
// Examples:
// 1 ZhouJiTong
// 2 ZongWeiGuoJi
// 3 CaiFuZhiZhou
// 4 PengYu
// 5 PuYuan
// 6 YingTai
// 7 HanRen
// 8 JiaLanDe
#define CONFIG_ZYT_CUST 37
#endif /* __CONFIG_H */
| abgoyal/zen_u105_uboot | include/configs/sp6821a.h | C | gpl-2.0 | 11,795 |
/*
* drivers/video/tegra/host/host1x/channel_host1x.c
*
* Tegra Graphics Host Channel
*
* Copyright (c) 2010-2012, NVIDIA Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 "nvhost_channel.h"
#include "dev.h"
#include "nvhost_hwctx.h"
#include <trace/events/nvhost.h>
#include <linux/slab.h>
#include "host1x_syncpt.h"
#include "host1x_channel.h"
#include "host1x_hardware.h"
#include "host1x_hwctx.h"
#include "nvhost_intr.h"
#define NV_FIFO_READ_TIMEOUT 200000
static void sync_waitbases(struct nvhost_channel *ch, u32 syncpt_val)
{
unsigned long waitbase;
unsigned long int waitbase_mask = ch->dev->waitbases;
if (ch->dev->waitbasesync) {
waitbase = find_first_bit(&waitbase_mask, BITS_PER_LONG);
nvhost_cdma_push(&ch->cdma,
nvhost_opcode_setclass(NV_HOST1X_CLASS_ID,
NV_CLASS_HOST_LOAD_SYNCPT_BASE,
1),
nvhost_class_host_load_syncpt_base(waitbase,
syncpt_val));
}
}
int host1x_channel_submit(struct nvhost_job *job)
{
struct host1x_hwctx *hwctx_to_save = NULL;
struct nvhost_channel *channel = job->ch;
struct nvhost_syncpt *sp = &nvhost_get_host(job->ch->dev)->syncpt;
u32 user_syncpt_incrs = job->syncpt_incrs;
bool need_restore = false;
u32 syncval;
int err;
void *ctxrestore_waiter = NULL;
void *ctxsave_waiter, *completed_waiter;
if (job->hwctx && job->hwctx->has_timedout)
return -ETIMEDOUT;
ctxsave_waiter = nvhost_intr_alloc_waiter();
completed_waiter = nvhost_intr_alloc_waiter();
if (!ctxsave_waiter || !completed_waiter) {
err = -ENOMEM;
goto done;
}
/* keep module powered */
nvhost_module_busy(channel->dev);
if (channel->dev->busy)
channel->dev->busy(channel->dev);
/* before error checks, return current max */
job->syncpt_end = nvhost_syncpt_read_max(sp, job->syncpt_id);
/* get submit lock */
err = mutex_lock_interruptible(&channel->submitlock);
if (err) {
nvhost_module_idle(channel->dev);
goto done;
}
/* If we are going to need a restore, allocate a waiter for it */
if (channel->cur_ctx != job->hwctx && job->hwctx && job->hwctx->valid) {
ctxrestore_waiter = nvhost_intr_alloc_waiter();
if (!ctxrestore_waiter) {
mutex_unlock(&channel->submitlock);
nvhost_module_idle(channel->dev);
err = -ENOMEM;
goto done;
}
need_restore = true;
}
/* remove stale waits */
if (job->num_waitchk) {
err = nvhost_syncpt_wait_check(sp,
job->nvmap,
job->waitchk_mask,
job->waitchk,
job->num_waitchk);
if (err) {
dev_warn(&channel->dev->dev,
"nvhost_syncpt_wait_check failed: %d\n", err);
mutex_unlock(&channel->submitlock);
nvhost_module_idle(channel->dev);
goto done;
}
}
/* begin a CDMA submit */
err = nvhost_cdma_begin(&channel->cdma, job);
if (err) {
mutex_unlock(&channel->submitlock);
nvhost_module_idle(channel->dev);
goto done;
}
sync_waitbases(channel, job->syncpt_end);
/* context switch */
if (channel->cur_ctx != job->hwctx) {
trace_nvhost_channel_context_switch(channel->dev->name,
channel->cur_ctx, job->hwctx);
hwctx_to_save = channel->cur_ctx ?
to_host1x_hwctx(channel->cur_ctx) : NULL;
if (hwctx_to_save &&
hwctx_to_save->hwctx.has_timedout) {
hwctx_to_save = NULL;
dev_dbg(&channel->dev->dev,
"%s: skip save of timed out context (0x%p)\n",
__func__, channel->cur_ctx);
}
if (hwctx_to_save) {
job->syncpt_incrs += hwctx_to_save->save_incrs;
hwctx_to_save->hwctx.valid = true;
channel->ctxhandler->get(&hwctx_to_save->hwctx);
}
channel->cur_ctx = job->hwctx;
if (need_restore)
job->syncpt_incrs +=
to_host1x_hwctx(job->hwctx)->restore_incrs;
}
/* get absolute sync value */
if (BIT(job->syncpt_id) & sp->client_managed)
syncval = nvhost_syncpt_set_max(sp,
job->syncpt_id, job->syncpt_incrs);
else
syncval = nvhost_syncpt_incr_max(sp,
job->syncpt_id, job->syncpt_incrs);
job->syncpt_end = syncval;
/* push save buffer (pre-gather setup depends on unit) */
if (hwctx_to_save)
channel->ctxhandler->save_push(&hwctx_to_save->hwctx,
&channel->cdma);
/* gather restore buffer */
if (need_restore) {
struct host1x_hwctx *cur_ctx =
to_host1x_hwctx(channel->cur_ctx);
nvhost_cdma_push_gather(&channel->cdma,
nvhost_get_host(channel->dev)->nvmap,
nvmap_ref_to_handle(cur_ctx->restore),
nvhost_opcode_gather(cur_ctx->restore_size),
cur_ctx->restore_phys);
channel->ctxhandler->get(channel->cur_ctx);
}
/* add a setclass for modules that require it (unless ctxsw added it) */
if (!hwctx_to_save && !need_restore && channel->dev->class)
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_setclass(channel->dev->class, 0, 0),
NVHOST_OPCODE_NOOP);
if (job->null_kickoff) {
int incr;
u32 op_incr;
/* TODO ideally we'd also perform host waits here */
/* push increments that correspond to nulled out commands */
op_incr = nvhost_opcode_imm(0, 0x100 | job->syncpt_id);
for (incr = 0; incr < (user_syncpt_incrs >> 1); incr++)
nvhost_cdma_push(&channel->cdma, op_incr, op_incr);
if (user_syncpt_incrs & 1)
nvhost_cdma_push(&channel->cdma,
op_incr, NVHOST_OPCODE_NOOP);
/* for 3d, waitbase needs to be incremented after each submit */
if (channel->dev->class == NV_GRAPHICS_3D_CLASS_ID)
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_setclass(
NV_HOST1X_CLASS_ID,
NV_CLASS_HOST_INCR_SYNCPT_BASE,
1),
nvhost_class_host_incr_syncpt_base(
NVWAITBASE_3D,
user_syncpt_incrs));
} else {
/* push user gathers */
int i = 0;
for ( ; i < job->num_gathers; i++) {
u32 op1 = nvhost_opcode_gather(job->gathers[i].words);
u32 op2 = job->gathers[i].mem;
nvhost_cdma_push_gather(&channel->cdma,
job->nvmap, job->unpins[i/2],
op1, op2);
}
}
/* end CDMA submit & stash pinned hMems into sync queue */
nvhost_cdma_end(&channel->cdma, job);
trace_nvhost_channel_submitted(channel->dev->name,
syncval - job->syncpt_incrs, syncval);
/*
* schedule a context save interrupt (to drain the host FIFO
* if necessary, and to release the restore buffer)
*/
if (hwctx_to_save) {
err = nvhost_intr_add_action(
&nvhost_get_host(channel->dev)->intr,
job->syncpt_id,
syncval - job->syncpt_incrs
+ hwctx_to_save->save_thresh,
NVHOST_INTR_ACTION_CTXSAVE, &hwctx_to_save->hwctx,
ctxsave_waiter,
NULL);
ctxsave_waiter = NULL;
WARN(err, "Failed to set ctx save interrupt");
}
if (need_restore) {
BUG_ON(!ctxrestore_waiter);
err = nvhost_intr_add_action(
&nvhost_get_host(channel->dev)->intr,
job->syncpt_id,
syncval - user_syncpt_incrs,
NVHOST_INTR_ACTION_CTXRESTORE, channel->cur_ctx,
ctxrestore_waiter,
NULL);
ctxrestore_waiter = NULL;
WARN(err, "Failed to set ctx restore interrupt");
}
/* schedule a submit complete interrupt */
err = nvhost_intr_add_action(&nvhost_get_host(channel->dev)->intr,
job->syncpt_id, syncval,
NVHOST_INTR_ACTION_SUBMIT_COMPLETE, channel,
completed_waiter,
NULL);
completed_waiter = NULL;
WARN(err, "Failed to set submit complete interrupt");
mutex_unlock(&channel->submitlock);
done:
kfree(ctxrestore_waiter);
kfree(ctxsave_waiter);
kfree(completed_waiter);
return err;
}
int host1x_channel_read_3d_reg(
struct nvhost_channel *channel,
struct nvhost_hwctx *hwctx,
u32 offset,
u32 *value)
{
struct host1x_hwctx *hwctx_to_save = NULL;
struct nvhost_hwctx_handler *h = hwctx->h;
struct host1x_hwctx_handler *p = to_host1x_hwctx_handler(h);
bool need_restore = false;
u32 syncpt_incrs = 4;
unsigned int pending = 0;
DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
void *ref;
void *ctx_waiter, *read_waiter, *completed_waiter;
struct nvhost_job *job;
u32 syncval;
int err;
if (hwctx && hwctx->has_timedout)
return -ETIMEDOUT;
ctx_waiter = nvhost_intr_alloc_waiter();
read_waiter = nvhost_intr_alloc_waiter();
completed_waiter = nvhost_intr_alloc_waiter();
if (!ctx_waiter || !read_waiter || !completed_waiter) {
err = -ENOMEM;
goto done;
}
job = nvhost_job_alloc(channel, hwctx,
NULL,
nvhost_get_host(channel->dev)->nvmap, 0, 0);
if (!job) {
err = -ENOMEM;
goto done;
}
/* keep module powered */
nvhost_module_busy(channel->dev);
/* get submit lock */
err = mutex_lock_interruptible(&channel->submitlock);
if (err) {
nvhost_module_idle(channel->dev);
return err;
}
/* context switch */
if (channel->cur_ctx != hwctx) {
hwctx_to_save = channel->cur_ctx ?
to_host1x_hwctx(channel->cur_ctx) : NULL;
if (hwctx_to_save) {
syncpt_incrs += hwctx_to_save->save_incrs;
hwctx_to_save->hwctx.valid = true;
channel->ctxhandler->get(&hwctx_to_save->hwctx);
}
channel->cur_ctx = hwctx;
if (channel->cur_ctx && channel->cur_ctx->valid) {
need_restore = true;
syncpt_incrs += to_host1x_hwctx(channel->cur_ctx)
->restore_incrs;
}
}
syncval = nvhost_syncpt_incr_max(&nvhost_get_host(channel->dev)->syncpt,
p->syncpt, syncpt_incrs);
job->syncpt_id = p->syncpt;
job->syncpt_incrs = syncpt_incrs;
job->syncpt_end = syncval;
/* begin a CDMA submit */
nvhost_cdma_begin(&channel->cdma, job);
/* push save buffer (pre-gather setup depends on unit) */
if (hwctx_to_save)
h->save_push(&hwctx_to_save->hwctx, &channel->cdma);
/* gather restore buffer */
if (need_restore)
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_gather(to_host1x_hwctx(channel->cur_ctx)
->restore_size),
to_host1x_hwctx(channel->cur_ctx)->restore_phys);
/* Switch to 3D - wait for it to complete what it was doing */
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_setclass(NV_GRAPHICS_3D_CLASS_ID, 0, 0),
nvhost_opcode_imm_incr_syncpt(NV_SYNCPT_OP_DONE,
p->syncpt));
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_setclass(NV_HOST1X_CLASS_ID,
NV_CLASS_HOST_WAIT_SYNCPT_BASE, 1),
nvhost_class_host_wait_syncpt_base(p->syncpt,
p->waitbase, 1));
/* Tell 3D to send register value to FIFO */
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_nonincr(NV_CLASS_HOST_INDOFF, 1),
nvhost_class_host_indoff_reg_read(NV_HOST_MODULE_GR3D,
offset, false));
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_imm(NV_CLASS_HOST_INDDATA, 0),
NVHOST_OPCODE_NOOP);
/* Increment syncpt to indicate that FIFO can be read */
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_imm_incr_syncpt(NV_SYNCPT_IMMEDIATE,
p->syncpt),
NVHOST_OPCODE_NOOP);
/* Wait for value to be read from FIFO */
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_nonincr(NV_CLASS_HOST_WAIT_SYNCPT_BASE, 1),
nvhost_class_host_wait_syncpt_base(p->syncpt,
p->waitbase, 3));
/* Indicate submit complete */
nvhost_cdma_push(&channel->cdma,
nvhost_opcode_nonincr(NV_CLASS_HOST_INCR_SYNCPT_BASE, 1),
nvhost_class_host_incr_syncpt_base(p->waitbase, 4));
nvhost_cdma_push(&channel->cdma,
NVHOST_OPCODE_NOOP,
nvhost_opcode_imm_incr_syncpt(NV_SYNCPT_IMMEDIATE,
p->syncpt));
/* end CDMA submit */
nvhost_cdma_end(&channel->cdma, job);
nvhost_job_put(job);
job = NULL;
/*
* schedule a context save interrupt (to drain the host FIFO
* if necessary, and to release the restore buffer)
*/
if (hwctx_to_save) {
err = nvhost_intr_add_action(
&nvhost_get_host(channel->dev)->intr,
p->syncpt,
syncval - syncpt_incrs
+ hwctx_to_save->save_incrs
- 1,
NVHOST_INTR_ACTION_CTXSAVE, hwctx_to_save,
ctx_waiter,
NULL);
ctx_waiter = NULL;
WARN(err, "Failed to set context save interrupt");
}
/* Wait for FIFO to be ready */
err = nvhost_intr_add_action(&nvhost_get_host(channel->dev)->intr,
p->syncpt, syncval - 2,
NVHOST_INTR_ACTION_WAKEUP, &wq,
read_waiter,
&ref);
read_waiter = NULL;
WARN(err, "Failed to set wakeup interrupt");
wait_event(wq,
nvhost_syncpt_is_expired(&nvhost_get_host(channel->dev)->syncpt,
p->syncpt, syncval - 2));
nvhost_intr_put_ref(&nvhost_get_host(channel->dev)->intr, ref);
/* Read the register value from FIFO */
err = host1x_drain_read_fifo(channel->aperture,
value, 1, &pending);
/* Indicate we've read the value */
nvhost_syncpt_cpu_incr(&nvhost_get_host(channel->dev)->syncpt,
p->syncpt);
/* Schedule a submit complete interrupt */
err = nvhost_intr_add_action(&nvhost_get_host(channel->dev)->intr,
p->syncpt, syncval,
NVHOST_INTR_ACTION_SUBMIT_COMPLETE, channel,
completed_waiter, NULL);
completed_waiter = NULL;
WARN(err, "Failed to set submit complete interrupt");
mutex_unlock(&channel->submitlock);
done:
kfree(ctx_waiter);
kfree(read_waiter);
kfree(completed_waiter);
return err;
}
int host1x_drain_read_fifo(void __iomem *chan_regs,
u32 *ptr, unsigned int count, unsigned int *pending)
{
unsigned int entries = *pending;
unsigned long timeout = jiffies + NV_FIFO_READ_TIMEOUT;
while (count) {
unsigned int num;
while (!entries && time_before(jiffies, timeout)) {
/* query host for number of entries in fifo */
entries = HOST1X_VAL(CHANNEL_FIFOSTAT, OUTFENTRIES,
readl(chan_regs + HOST1X_CHANNEL_FIFOSTAT));
if (!entries)
cpu_relax();
}
/* timeout -> return error */
if (!entries)
return -EIO;
num = min(entries, count);
entries -= num;
count -= num;
while (num & ~0x3) {
u32 arr[4];
arr[0] = readl(chan_regs + HOST1X_CHANNEL_INDDATA);
arr[1] = readl(chan_regs + HOST1X_CHANNEL_INDDATA);
arr[2] = readl(chan_regs + HOST1X_CHANNEL_INDDATA);
arr[3] = readl(chan_regs + HOST1X_CHANNEL_INDDATA);
memcpy(ptr, arr, 4*sizeof(u32));
ptr += 4;
num -= 4;
}
while (num--)
*ptr++ = readl(chan_regs + HOST1X_CHANNEL_INDDATA);
}
*pending = entries;
return 0;
}
int host1x_save_context(struct nvhost_device *dev, u32 syncpt_id)
{
struct nvhost_channel *ch = dev->channel;
struct nvhost_hwctx *hwctx_to_save;
DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq);
u32 syncpt_incrs, syncpt_val;
int err = 0;
void *ref;
void *ctx_waiter = NULL, *wakeup_waiter = NULL;
struct nvhost_job *job;
ctx_waiter = nvhost_intr_alloc_waiter();
wakeup_waiter = nvhost_intr_alloc_waiter();
if (!ctx_waiter || !wakeup_waiter) {
err = -ENOMEM;
goto done;
}
if (dev->busy)
dev->busy(dev);
mutex_lock(&ch->submitlock);
hwctx_to_save = ch->cur_ctx;
if (!hwctx_to_save) {
mutex_unlock(&ch->submitlock);
goto done;
}
job = nvhost_job_alloc(ch, hwctx_to_save,
NULL,
nvhost_get_host(ch->dev)->nvmap, 0, 0);
if (IS_ERR_OR_NULL(job)) {
err = PTR_ERR(job);
mutex_unlock(&ch->submitlock);
goto done;
}
hwctx_to_save->valid = true;
ch->ctxhandler->get(hwctx_to_save);
ch->cur_ctx = NULL;
syncpt_incrs = to_host1x_hwctx(hwctx_to_save)->save_incrs;
syncpt_val = nvhost_syncpt_incr_max(&nvhost_get_host(ch->dev)->syncpt,
syncpt_id, syncpt_incrs);
job->syncpt_id = syncpt_id;
job->syncpt_incrs = syncpt_incrs;
job->syncpt_end = syncpt_val;
err = nvhost_cdma_begin(&ch->cdma, job);
if (err) {
mutex_unlock(&ch->submitlock);
goto done;
}
ch->ctxhandler->save_push(hwctx_to_save, &ch->cdma);
nvhost_cdma_end(&ch->cdma, job);
nvhost_job_put(job);
job = NULL;
err = nvhost_intr_add_action(&nvhost_get_host(ch->dev)->intr, syncpt_id,
syncpt_val - syncpt_incrs +
to_host1x_hwctx(hwctx_to_save)->save_thresh,
NVHOST_INTR_ACTION_CTXSAVE, hwctx_to_save,
ctx_waiter,
NULL);
ctx_waiter = NULL;
WARN(err, "Failed to set context save interrupt");
err = nvhost_intr_add_action(&nvhost_get_host(ch->dev)->intr,
syncpt_id, syncpt_val,
NVHOST_INTR_ACTION_WAKEUP, &wq,
wakeup_waiter,
&ref);
wakeup_waiter = NULL;
WARN(err, "Failed to set wakeup interrupt");
wait_event(wq,
nvhost_syncpt_is_expired(&nvhost_get_host(ch->dev)->syncpt,
syncpt_id, syncpt_val));
nvhost_intr_put_ref(&nvhost_get_host(ch->dev)->intr, ref);
nvhost_cdma_update(&ch->cdma);
mutex_unlock(&ch->submitlock);
done:
kfree(ctx_waiter);
kfree(wakeup_waiter);
return err;
}
| pershoot/galaxy-2636 | drivers/video/tegra-ics/host/host1x/host1x_channel.c | C | gpl-2.0 | 16,331 |
<!DOCTYPE html>
<html lang="en">
<head>
{%load staticfiles%}
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta charset="utf-8" />
<title>Dashboard - Ace Admin</title>
<meta name="description" content="overview & stats" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<!-- bootstrap & fontawesome -->
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css'%}" />
<link rel="stylesheet" href="{% static 'font-awesome/4.2.0/css/font-awesome.min.css'%}" />
<!-- page specific plugin styles -->
<!-- text fonts -->
<link rel="stylesheet" href="{% static 'fonts/fonts.googleapis.com.css'%}" />
<!-- ace styles -->
<link rel="stylesheet" href="{% static 'css/ace.min.css'%}" class="ace-main-stylesheet" id="main-ace-style" />
<script src="{% static 'js/ace-extra.min.js'%}"></script>
</head>
<body class="no-skin">
<div id="navbar" class="navbar navbar-default">
<script type="text/javascript">
try{ace.settings.check('navbar' , 'fixed')}catch(e){}
</script>
<div class="navbar-container" id="navbar-container">
<button type="button" class="navbar-toggle menu-toggler pull-left" id="menu-toggler" data-target="#sidebar">
<span class="sr-only">Toggle sidebar</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="navbar-header pull-left">
<a href="index.html" class="navbar-brand">
<small>
<i class="fa fa-leaf"></i>
Ace Admin
</small>
</a>
</div>
<div class="navbar-buttons navbar-header pull-right" role="navigation">
<ul class="nav ace-nav">
<li class="grey">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<i class="ace-icon fa fa-tasks"></i>
<span class="badge badge-grey">4</span>
</a>
<ul class="dropdown-menu-right dropdown-navbar dropdown-menu dropdown-caret dropdown-close">
<li class="dropdown-header">
<i class="ace-icon fa fa-check"></i>
4 Tasks to complete
</li>
<li class="dropdown-content">
<ul class="dropdown-menu dropdown-navbar">
<li>
<a href="#">
<div class="clearfix">
<span class="pull-left">Software Update</span>
<span class="pull-right">65%</span>
</div>
<div class="progress progress-mini">
<div style="width:65%" class="progress-bar"></div>
</div>
</a>
</li>
<li>
<a href="#">
<div class="clearfix">
<span class="pull-left">Hardware Upgrade</span>
<span class="pull-right">35%</span>
</div>
<div class="progress progress-mini">
<div style="width:35%" class="progress-bar progress-bar-danger"></div>
</div>
</a>
</li>
<li>
<a href="#">
<div class="clearfix">
<span class="pull-left">Unit Testing</span>
<span class="pull-right">15%</span>
</div>
<div class="progress progress-mini">
<div style="width:15%" class="progress-bar progress-bar-warning"></div>
</div>
</a>
</li>
<li>
<a href="#">
<div class="clearfix">
<span class="pull-left">Bug Fixes</span>
<span class="pull-right">90%</span>
</div>
<div class="progress progress-mini progress-striped active">
<div style="width:90%" class="progress-bar progress-bar-success"></div>
</div>
</a>
</li>
</ul>
</li>
<li class="dropdown-footer">
<a href="#">
See tasks with details
<i class="ace-icon fa fa-arrow-right"></i>
</a>
</li>
</ul>
</li>
<li class="purple">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<i class="ace-icon fa fa-bell icon-animated-bell"></i>
<span class="badge badge-important">8</span>
</a>
<ul class="dropdown-menu-right dropdown-navbar navbar-pink dropdown-menu dropdown-caret dropdown-close">
<li class="dropdown-header">
<i class="ace-icon fa fa-exclamation-triangle"></i>
8 Notifications
</li>
<li class="dropdown-content">
<ul class="dropdown-menu dropdown-navbar navbar-pink">
<li>
<a href="#">
<div class="clearfix">
<span class="pull-left">
<i class="btn btn-xs no-hover btn-pink fa fa-comment"></i>
New Comments
</span>
<span class="pull-right badge badge-info">+12</span>
</div>
</a>
</li>
<li>
<a href="#">
<i class="btn btn-xs btn-primary fa fa-user"></i>
Bob just signed up as an editor ...
</a>
</li>
<li>
<a href="#">
<div class="clearfix">
<span class="pull-left">
<i class="btn btn-xs no-hover btn-success fa fa-shopping-cart"></i>
New Orders
</span>
<span class="pull-right badge badge-success">+8</span>
</div>
</a>
</li>
<li>
<a href="#">
<div class="clearfix">
<span class="pull-left">
<i class="btn btn-xs no-hover btn-info fa fa-twitter"></i>
Followers
</span>
<span class="pull-right badge badge-info">+11</span>
</div>
</a>
</li>
</ul>
</li>
<li class="dropdown-footer">
<a href="#">
See all notifications
<i class="ace-icon fa fa-arrow-right"></i>
</a>
</li>
</ul>
</li>
<li class="green">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<i class="ace-icon fa fa-envelope icon-animated-vertical"></i>
<span class="badge badge-success">5</span>
</a>
<ul class="dropdown-menu-right dropdown-navbar dropdown-menu dropdown-caret dropdown-close">
<li class="dropdown-header">
<i class="ace-icon fa fa-envelope-o"></i>
5 Messages
</li>
<li class="dropdown-content">
<ul class="dropdown-menu dropdown-navbar">
<li>
<a href="#" class="clearfix">
<img src="assets/avatars/avatar.png" class="msg-photo" alt="Alex's Avatar" />
<span class="msg-body">
<span class="msg-title">
<span class="blue">Alex:</span>
Ciao sociis natoque penatibus et auctor ...
</span>
<span class="msg-time">
<i class="ace-icon fa fa-clock-o"></i>
<span>a moment ago</span>
</span>
</span>
</a>
</li>
<li>
<a href="#" class="clearfix">
<img src="assets/avatars/avatar3.png" class="msg-photo" alt="Susan's Avatar" />
<span class="msg-body">
<span class="msg-title">
<span class="blue">Susan:</span>
Vestibulum id ligula porta felis euismod ...
</span>
<span class="msg-time">
<i class="ace-icon fa fa-clock-o"></i>
<span>20 minutes ago</span>
</span>
</span>
</a>
</li>
<li>
<a href="#" class="clearfix">
<img src="assets/avatars/avatar4.png" class="msg-photo" alt="Bob's Avatar" />
<span class="msg-body">
<span class="msg-title">
<span class="blue">Bob:</span>
Nullam quis risus eget urna mollis ornare ...
</span>
<span class="msg-time">
<i class="ace-icon fa fa-clock-o"></i>
<span>3:15 pm</span>
</span>
</span>
</a>
</li>
<li>
<a href="#" class="clearfix">
<img src="assets/avatars/avatar2.png" class="msg-photo" alt="Kate's Avatar" />
<span class="msg-body">
<span class="msg-title">
<span class="blue">Kate:</span>
Ciao sociis natoque eget urna mollis ornare ...
</span>
<span class="msg-time">
<i class="ace-icon fa fa-clock-o"></i>
<span>1:33 pm</span>
</span>
</span>
</a>
</li>
<li>
<a href="#" class="clearfix">
<img src="assets/avatars/avatar5.png" class="msg-photo" alt="Fred's Avatar" />
<span class="msg-body">
<span class="msg-title">
<span class="blue">Fred:</span>
Vestibulum id penatibus et auctor ...
</span>
<span class="msg-time">
<i class="ace-icon fa fa-clock-o"></i>
<span>10:09 am</span>
</span>
</span>
</a>
</li>
</ul>
</li>
<li class="dropdown-footer">
<a href="inbox.html">
See all messages
<i class="ace-icon fa fa-arrow-right"></i>
</a>
</li>
</ul>
</li>
<li class="light-blue">
<a data-toggle="dropdown" href="#" class="dropdown-toggle">
<img class="nav-user-photo" src="assets/avatars/user.jpg" alt="Jason's Photo" />
<span class="user-info">
<small>Welcome,</small>
Jason
</span>
<i class="ace-icon fa fa-caret-down"></i>
</a>
<ul class="user-menu dropdown-menu-right dropdown-menu dropdown-yellow dropdown-caret dropdown-close">
<li>
<a href="#">
<i class="ace-icon fa fa-cog"></i>
Settings
</a>
</li>
<li>
<a href="profile.html">
<i class="ace-icon fa fa-user"></i>
Profile
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<i class="ace-icon fa fa-power-off"></i>
Logout
</a>
</li>
</ul>
</li>
</ul>
</div>
</div><!-- /.navbar-container -->
</div>
<div class="main-container" id="main-container">
<script type="text/javascript">
try{ace.settings.check('main-container' , 'fixed')}catch(e){}
</script>
<div id="sidebar" class="sidebar responsive">
<script type="text/javascript">
try{ace.settings.check('sidebar' , 'fixed')}catch(e){}
</script>
<div class="sidebar-shortcuts" id="sidebar-shortcuts">
<div class="sidebar-shortcuts-large" id="sidebar-shortcuts-large">
<button class="btn btn-success">
<i class="ace-icon fa fa-signal"></i>
</button>
<button class="btn btn-info">
<i class="ace-icon fa fa-pencil"></i>
</button>
<button class="btn btn-warning">
<i class="ace-icon fa fa-users"></i>
</button>
<button class="btn btn-danger">
<i class="ace-icon fa fa-cogs"></i>
</button>
</div>
<div class="sidebar-shortcuts-mini" id="sidebar-shortcuts-mini">
<span class="btn btn-success"></span>
<span class="btn btn-info"></span>
<span class="btn btn-warning"></span>
<span class="btn btn-danger"></span>
</div>
</div><!-- /.sidebar-shortcuts -->
<ul class="nav nav-list">
<li class="active">
<a href="index.html">
<i class="menu-icon fa fa-tachometer"></i>
<span class="menu-text"> Dashboard </span>
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa fa-desktop"></i>
<span class="menu-text">
UI & Elements
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="">
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa fa-caret-right"></i>
Layouts
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="">
<a href="top-menu.html">
<i class="menu-icon fa fa-caret-right"></i>
Top Menu
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="two-menu-1.html">
<i class="menu-icon fa fa-caret-right"></i>
Two Menus 1
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="two-menu-2.html">
<i class="menu-icon fa fa-caret-right"></i>
Two Menus 2
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="mobile-menu-1.html">
<i class="menu-icon fa fa-caret-right"></i>
Default Mobile Menu
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="mobile-menu-2.html">
<i class="menu-icon fa fa-caret-right"></i>
Mobile Menu 2
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="mobile-menu-3.html">
<i class="menu-icon fa fa-caret-right"></i>
Mobile Menu 3
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="">
<a href="typography.html">
<i class="menu-icon fa fa-caret-right"></i>
Typography
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="elements.html">
<i class="menu-icon fa fa-caret-right"></i>
Elements
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="buttons.html">
<i class="menu-icon fa fa-caret-right"></i>
Buttons & Icons
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="content-slider.html">
<i class="menu-icon fa fa-caret-right"></i>
Content Sliders
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="treeview.html">
<i class="menu-icon fa fa-caret-right"></i>
Treeview
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="jquery-ui.html">
<i class="menu-icon fa fa-caret-right"></i>
jQuery UI
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="nestable-list.html">
<i class="menu-icon fa fa-caret-right"></i>
Nestable Lists
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa fa-caret-right"></i>
Three Level Menu
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="">
<a href="#">
<i class="menu-icon fa fa-leaf green"></i>
Item #1
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa fa-pencil orange"></i>
4th level
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="">
<a href="#">
<i class="menu-icon fa fa-plus purple"></i>
Add Product
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="#">
<i class="menu-icon fa fa-eye pink"></i>
View Products
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="">
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa fa-list"></i>
<span class="menu-text"> Tables </span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="">
<a href="tables.html">
<i class="menu-icon fa fa-caret-right"></i>
Simple & Dynamic
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="jqgrid.html">
<i class="menu-icon fa fa-caret-right"></i>
jqGrid plugin
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="">
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa fa-pencil-square-o"></i>
<span class="menu-text"> Forms </span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="">
<a href="form-elements.html">
<i class="menu-icon fa fa-caret-right"></i>
Form Elements
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="form-elements-2.html">
<i class="menu-icon fa fa-caret-right"></i>
Form Elements 2
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="form-wizard.html">
<i class="menu-icon fa fa-caret-right"></i>
Wizard & Validation
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="wysiwyg.html">
<i class="menu-icon fa fa-caret-right"></i>
Wysiwyg & Markdown
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="dropzone.html">
<i class="menu-icon fa fa-caret-right"></i>
Dropzone File Upload
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="">
<a href="widgets.html">
<i class="menu-icon fa fa-list-alt"></i>
<span class="menu-text"> Widgets </span>
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="calendar.html">
<i class="menu-icon fa fa-calendar"></i>
<span class="menu-text">
Calendar
<span class="badge badge-transparent tooltip-error" title="2 Important Events">
<i class="ace-icon fa fa-exclamation-triangle red bigger-130"></i>
</span>
</span>
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="gallery.html">
<i class="menu-icon fa fa-picture-o"></i>
<span class="menu-text"> Gallery </span>
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa fa-tag"></i>
<span class="menu-text"> More Pages </span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="">
<a href="profile.html">
<i class="menu-icon fa fa-caret-right"></i>
User Profile
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="inbox.html">
<i class="menu-icon fa fa-caret-right"></i>
Inbox
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="pricing.html">
<i class="menu-icon fa fa-caret-right"></i>
Pricing Tables
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="invoice.html">
<i class="menu-icon fa fa-caret-right"></i>
Invoice
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="timeline.html">
<i class="menu-icon fa fa-caret-right"></i>
Timeline
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="email.html">
<i class="menu-icon fa fa-caret-right"></i>
Email Templates
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="login.html">
<i class="menu-icon fa fa-caret-right"></i>
Login & Register
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
<li class="">
<a href="#" class="dropdown-toggle">
<i class="menu-icon fa fa-file-o"></i>
<span class="menu-text">
Other Pages
<span class="badge badge-primary">5</span>
</span>
<b class="arrow fa fa-angle-down"></b>
</a>
<b class="arrow"></b>
<ul class="submenu">
<li class="">
<a href="faq.html">
<i class="menu-icon fa fa-caret-right"></i>
FAQ
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="error-404.html">
<i class="menu-icon fa fa-caret-right"></i>
Error 404
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="error-500.html">
<i class="menu-icon fa fa-caret-right"></i>
Error 500
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="grid.html">
<i class="menu-icon fa fa-caret-right"></i>
Grid
</a>
<b class="arrow"></b>
</li>
<li class="">
<a href="blank.html">
<i class="menu-icon fa fa-caret-right"></i>
Blank Page
</a>
<b class="arrow"></b>
</li>
</ul>
</li>
</ul><!-- /.nav-list -->
<div class="sidebar-toggle sidebar-collapse" id="sidebar-collapse">
<i class="ace-icon fa fa-angle-double-left" data-icon1="ace-icon fa fa-angle-double-left" data-icon2="ace-icon fa fa-angle-double-right"></i>
</div>
<script type="text/javascript">
try{ace.settings.check('sidebar' , 'collapsed')}catch(e){}
</script>
</div>
<div class="main-content">
<div class="main-content-inner">
<div class="breadcrumbs" id="breadcrumbs">
<script type="text/javascript">
try{ace.settings.check('breadcrumbs' , 'fixed')}catch(e){}
</script>
<ul class="breadcrumb">
<li>
<i class="ace-icon fa fa-home home-icon"></i>
<a href="#">Home</a>
</li>
<li class="active">Dashboard</li>
</ul><!-- /.breadcrumb -->
<div class="nav-search" id="nav-search">
<form class="form-search">
<span class="input-icon">
<input type="text" placeholder="Search ..." class="nav-search-input" id="nav-search-input" autocomplete="off" />
<i class="ace-icon fa fa-search nav-search-icon"></i>
</span>
</form>
</div><!-- /.nav-search -->
</div>
<div class="page-content">
<div class="ace-settings-container" id="ace-settings-container">
<div class="btn btn-app btn-xs btn-warning ace-settings-btn" id="ace-settings-btn">
<i class="ace-icon fa fa-cog bigger-130"></i>
</div>
<div class="ace-settings-box clearfix" id="ace-settings-box">
<div class="pull-left width-50">
<div class="ace-settings-item">
<div class="pull-left">
<select id="skin-colorpicker" class="hide">
<option data-skin="no-skin" value="#438EB9">#438EB9</option>
<option data-skin="skin-1" value="#222A2D">#222A2D</option>
<option data-skin="skin-2" value="#C6487E">#C6487E</option>
<option data-skin="skin-3" value="#D0D0D0">#D0D0D0</option>
</select>
</div>
<span> Choose Skin</span>
</div>
<div class="ace-settings-item">
<input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-navbar" />
<label class="lbl" for="ace-settings-navbar"> Fixed Navbar</label>
</div>
<div class="ace-settings-item">
<input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-sidebar" />
<label class="lbl" for="ace-settings-sidebar"> Fixed Sidebar</label>
</div>
<div class="ace-settings-item">
<input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-breadcrumbs" />
<label class="lbl" for="ace-settings-breadcrumbs"> Fixed Breadcrumbs</label>
</div>
<div class="ace-settings-item">
<input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-rtl" />
<label class="lbl" for="ace-settings-rtl"> Right To Left (rtl)</label>
</div>
<div class="ace-settings-item">
<input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-add-container" />
<label class="lbl" for="ace-settings-add-container">
Inside
<b>.container</b>
</label>
</div>
</div><!-- /.pull-left -->
<div class="pull-left width-50">
<div class="ace-settings-item">
<input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-hover" />
<label class="lbl" for="ace-settings-hover"> Submenu on Hover</label>
</div>
<div class="ace-settings-item">
<input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-compact" />
<label class="lbl" for="ace-settings-compact"> Compact Sidebar</label>
</div>
<div class="ace-settings-item">
<input type="checkbox" class="ace ace-checkbox-2" id="ace-settings-highlight" />
<label class="lbl" for="ace-settings-highlight"> Alt. Active Item</label>
</div>
</div><!-- /.pull-left -->
</div><!-- /.ace-settings-box -->
</div><!-- /.ace-settings-container -->
<div class="page-header">
<h1>
Dashboard
<small>
<i class="ace-icon fa fa-angle-double-right"></i>
overview & stats
</small>
</h1>
</div><!-- /.page-header -->
<div class="row">
<div class="col-xs-12">
<!-- PAGE CONTENT BEGINS -->
<div class="alert alert-block alert-success">
<button type="button" class="close" data-dismiss="alert">
<i class="ace-icon fa fa-times"></i>
</button>
<i class="ace-icon fa fa-check green"></i>
Welcome to
<strong class="green">
Ace
<small>(v1.3.3)</small>
</strong>,
легкий, много-функциональный и простой в использовании шаблон для админки на bootstrap 3.3. Загрузить исходники с <a href="https://github.com/bopoda/ace">github</a> (with minified ace js files).
</div>
<div class="row">
<div class="space-6"></div>
<div class="col-sm-7 infobox-container">
<div class="infobox infobox-green">
<div class="infobox-icon">
<i class="ace-icon fa fa-comments"></i>
</div>
<div class="infobox-data">
<span class="infobox-data-number">32</span>
<div class="infobox-content">comments + 2 reviews</div>
</div>
<div class="stat stat-success">8%</div>
</div>
<div class="infobox infobox-blue">
<div class="infobox-icon">
<i class="ace-icon fa fa-twitter"></i>
</div>
<div class="infobox-data">
<span class="infobox-data-number">11</span>
<div class="infobox-content">new followers</div>
</div>
<div class="badge badge-success">
+32%
<i class="ace-icon fa fa-arrow-up"></i>
</div>
</div>
<div class="infobox infobox-pink">
<div class="infobox-icon">
<i class="ace-icon fa fa-shopping-cart"></i>
</div>
<div class="infobox-data">
<span class="infobox-data-number">8</span>
<div class="infobox-content">new orders</div>
</div>
<div class="stat stat-important">4%</div>
</div>
<div class="infobox infobox-red">
<div class="infobox-icon">
<i class="ace-icon fa fa-flask"></i>
</div>
<div class="infobox-data">
<span class="infobox-data-number">7</span>
<div class="infobox-content">experiments</div>
</div>
</div>
<div class="infobox infobox-orange2">
<div class="infobox-chart">
<span class="sparkline" data-values="196,128,202,177,154,94,100,170,224"></span>
</div>
<div class="infobox-data">
<span class="infobox-data-number">6,251</span>
<div class="infobox-content">pageviews</div>
</div>
<div class="badge badge-success">
7.2%
<i class="ace-icon fa fa-arrow-up"></i>
</div>
</div>
<div class="infobox infobox-blue2">
<div class="infobox-progress">
<div class="easy-pie-chart percentage" data-percent="42" data-size="46">
<span class="percent">42</span>%
</div>
</div>
<div class="infobox-data">
<span class="infobox-text">traffic used</span>
<div class="infobox-content">
<span class="bigger-110">~</span>
58GB remaining
</div>
</div>
</div>
<div class="space-6"></div>
<div class="infobox infobox-green infobox-small infobox-dark">
<div class="infobox-progress">
<div class="easy-pie-chart percentage" data-percent="61" data-size="39">
<span class="percent">61</span>%
</div>
</div>
<div class="infobox-data">
<div class="infobox-content">Task</div>
<div class="infobox-content">Completion</div>
</div>
</div>
<div class="infobox infobox-blue infobox-small infobox-dark">
<div class="infobox-chart">
<span class="sparkline" data-values="3,4,2,3,4,4,2,2"></span>
</div>
<div class="infobox-data">
<div class="infobox-content">Earnings</div>
<div class="infobox-content">$32,000</div>
</div>
</div>
<div class="infobox infobox-grey infobox-small infobox-dark">
<div class="infobox-icon">
<i class="ace-icon fa fa-download"></i>
</div>
<div class="infobox-data">
<div class="infobox-content">Downloads</div>
<div class="infobox-content">1,205</div>
</div>
</div>
</div>
<div class="vspace-12-sm"></div>
<div class="col-sm-5">
<div class="widget-box">
<div class="widget-header widget-header-flat widget-header-small">
<h5 class="widget-title">
<i class="ace-icon fa fa-signal"></i>
Traffic Sources
</h5>
<div class="widget-toolbar no-border">
<div class="inline dropdown-hover">
<button class="btn btn-minier btn-primary">
This Week
<i class="ace-icon fa fa-angle-down icon-on-right bigger-110"></i>
</button>
<ul class="dropdown-menu dropdown-menu-right dropdown-125 dropdown-lighter dropdown-close dropdown-caret">
<li class="active">
<a href="#" class="blue">
<i class="ace-icon fa fa-caret-right bigger-110"> </i>
This Week
</a>
</li>
<li>
<a href="#">
<i class="ace-icon fa fa-caret-right bigger-110 invisible"> </i>
Last Week
</a>
</li>
<li>
<a href="#">
<i class="ace-icon fa fa-caret-right bigger-110 invisible"> </i>
This Month
</a>
</li>
<li>
<a href="#">
<i class="ace-icon fa fa-caret-right bigger-110 invisible"> </i>
Last Month
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="widget-body">
<div class="widget-main">
<div id="piechart-placeholder"></div>
<div class="hr hr8 hr-double"></div>
<div class="clearfix">
<div class="grid3">
<span class="grey">
<i class="ace-icon fa fa-facebook-square fa-2x blue"></i>
likes
</span>
<h4 class="bigger pull-right">1,255</h4>
</div>
<div class="grid3">
<span class="grey">
<i class="ace-icon fa fa-twitter-square fa-2x purple"></i>
tweets
</span>
<h4 class="bigger pull-right">941</h4>
</div>
<div class="grid3">
<span class="grey">
<i class="ace-icon fa fa-pinterest-square fa-2x red"></i>
pins
</span>
<h4 class="bigger pull-right">1,050</h4>
</div>
</div>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.widget-box -->
</div><!-- /.col -->
</div><!-- /.row -->
<div class="hr hr32 hr-dotted"></div>
<div class="row">
<div class="col-sm-5">
<div class="widget-box transparent">
<div class="widget-header widget-header-flat">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-star orange"></i>
Popular Domains
</h4>
<div class="widget-toolbar">
<a href="#" data-action="collapse">
<i class="ace-icon fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<table class="table table-bordered table-striped">
<thead class="thin-border-bottom">
<tr>
<th>
<i class="ace-icon fa fa-caret-right blue"></i>name
</th>
<th>
<i class="ace-icon fa fa-caret-right blue"></i>price
</th>
<th class="hidden-480">
<i class="ace-icon fa fa-caret-right blue"></i>status
</th>
</tr>
</thead>
<tbody>
<tr>
<td>internet.com</td>
<td>
<small>
<s class="red">$29.99</s>
</small>
<b class="green">$19.99</b>
</td>
<td class="hidden-480">
<span class="label label-info arrowed-right arrowed-in">on sale</span>
</td>
</tr>
<tr>
<td>online.com</td>
<td>
<b class="blue">$16.45</b>
</td>
<td class="hidden-480">
<span class="label label-success arrowed-in arrowed-in-right">approved</span>
</td>
</tr>
<tr>
<td>newnet.com</td>
<td>
<b class="blue">$15.00</b>
</td>
<td class="hidden-480">
<span class="label label-danger arrowed">pending</span>
</td>
</tr>
<tr>
<td>web.com</td>
<td>
<small>
<s class="red">$24.99</s>
</small>
<b class="green">$19.95</b>
</td>
<td class="hidden-480">
<span class="label arrowed">
<s>out of stock</s>
</span>
</td>
</tr>
<tr>
<td>domain.com</td>
<td>
<b class="blue">$12.00</b>
</td>
<td class="hidden-480">
<span class="label label-warning arrowed arrowed-right">SOLD</span>
</td>
</tr>
</tbody>
</table>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.widget-box -->
</div><!-- /.col -->
<div class="col-sm-7">
<div class="widget-box transparent">
<div class="widget-header widget-header-flat">
<h4 class="widget-title lighter">
<i class="ace-icon fa fa-signal"></i>
Sale Stats
</h4>
<div class="widget-toolbar">
<a href="#" data-action="collapse">
<i class="ace-icon fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="widget-body">
<div class="widget-main padding-4">
<div id="sales-charts"></div>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.widget-box -->
</div><!-- /.col -->
</div><!-- /.row -->
<div class="hr hr32 hr-dotted"></div>
<div class="row">
<div class="col-sm-6">
<div class="widget-box transparent" id="recent-box">
<div class="widget-header">
<h4 class="widget-title lighter smaller">
<i class="ace-icon fa fa-rss orange"></i>RECENT
</h4>
<div class="widget-toolbar no-border">
<ul class="nav nav-tabs" id="recent-tab">
<li class="active">
<a data-toggle="tab" href="#task-tab">Tasks</a>
</li>
<li>
<a data-toggle="tab" href="#member-tab">Members</a>
</li>
<li>
<a data-toggle="tab" href="#comment-tab">Comments</a>
</li>
</ul>
</div>
</div>
<div class="widget-body">
<div class="widget-main padding-4">
<div class="tab-content padding-8">
<div id="task-tab" class="tab-pane active">
<h4 class="smaller lighter green">
<i class="ace-icon fa fa-list"></i>
Sortable Lists
</h4>
<ul id="tasks" class="item-list">
<li class="item-orange clearfix">
<label class="inline">
<input type="checkbox" class="ace" />
<span class="lbl"> Answering customer questions</span>
</label>
<div class="pull-right easy-pie-chart percentage" data-size="30" data-color="#ECCB71" data-percent="42">
<span class="percent">42</span>%
</div>
</li>
<li class="item-red clearfix">
<label class="inline">
<input type="checkbox" class="ace" />
<span class="lbl"> Fixing bugs</span>
</label>
<div class="pull-right action-buttons">
<a href="#" class="blue">
<i class="ace-icon fa fa-pencil bigger-130"></i>
</a>
<span class="vbar"></span>
<a href="#" class="red">
<i class="ace-icon fa fa-trash-o bigger-130"></i>
</a>
<span class="vbar"></span>
<a href="#" class="green">
<i class="ace-icon fa fa-flag bigger-130"></i>
</a>
</div>
</li>
<li class="item-default clearfix">
<label class="inline">
<input type="checkbox" class="ace" />
<span class="lbl"> Adding new features</span>
</label>
<div class="inline pull-right position-relative dropdown-hover">
<button class="btn btn-minier bigger btn-primary">
<i class="ace-icon fa fa-cog icon-only bigger-120"></i>
</button>
<ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-caret dropdown-close dropdown-menu-right">
<li>
<a href="#" class="tooltip-success" data-rel="tooltip" title="Mark as done">
<span class="green">
<i class="ace-icon fa fa-check bigger-110"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
<span class="red">
<i class="ace-icon fa fa-trash-o bigger-110"></i>
</span>
</a>
</li>
</ul>
</div>
</li>
<li class="item-blue clearfix">
<label class="inline">
<input type="checkbox" class="ace" />
<span class="lbl"> Upgrading scripts used in template</span>
</label>
</li>
<li class="item-grey clearfix">
<label class="inline">
<input type="checkbox" class="ace" />
<span class="lbl"> Adding new skins</span>
</label>
</li>
<li class="item-green clearfix">
<label class="inline">
<input type="checkbox" class="ace" />
<span class="lbl"> Updating server software up</span>
</label>
</li>
<li class="item-pink clearfix">
<label class="inline">
<input type="checkbox" class="ace" />
<span class="lbl"> Cleaning up</span>
</label>
</li>
</ul>
</div>
<div id="member-tab" class="tab-pane">
<div class="clearfix">
<div class="itemdiv memberdiv">
<div class="user">
<img alt="Bob Doe's avatar" src="assets/avatars/user.jpg" />
</div>
<div class="body">
<div class="name">
<a href="#">Bob Doe</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">20 min</span>
</div>
<div>
<span class="label label-warning label-sm">pending</span>
<div class="inline position-relative">
<button class="btn btn-minier btn-yellow btn-no-border dropdown-toggle" data-toggle="dropdown" data-position="auto">
<i class="ace-icon fa fa-angle-down icon-only bigger-120"></i>
</button>
<ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
<li>
<a href="#" class="tooltip-success" data-rel="tooltip" title="Approve">
<span class="green">
<i class="ace-icon fa fa-check bigger-110"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-warning" data-rel="tooltip" title="Reject">
<span class="orange">
<i class="ace-icon fa fa-times bigger-110"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
<span class="red">
<i class="ace-icon fa fa-trash-o bigger-110"></i>
</span>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="itemdiv memberdiv">
<div class="user">
<img alt="Joe Doe's avatar" src="assets/avatars/avatar2.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Joe Doe</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">1 hour</span>
</div>
<div>
<span class="label label-warning label-sm">pending</span>
<div class="inline position-relative">
<button class="btn btn-minier btn-yellow btn-no-border dropdown-toggle" data-toggle="dropdown" data-position="auto">
<i class="ace-icon fa fa-angle-down icon-only bigger-120"></i>
</button>
<ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
<li>
<a href="#" class="tooltip-success" data-rel="tooltip" title="Approve">
<span class="green">
<i class="ace-icon fa fa-check bigger-110"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-warning" data-rel="tooltip" title="Reject">
<span class="orange">
<i class="ace-icon fa fa-times bigger-110"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
<span class="red">
<i class="ace-icon fa fa-trash-o bigger-110"></i>
</span>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="itemdiv memberdiv">
<div class="user">
<img alt="Jim Doe's avatar" src="assets/avatars/avatar.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Jim Doe</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">2 hour</span>
</div>
<div>
<span class="label label-warning label-sm">pending</span>
<div class="inline position-relative">
<button class="btn btn-minier btn-yellow btn-no-border dropdown-toggle" data-toggle="dropdown" data-position="auto">
<i class="ace-icon fa fa-angle-down icon-only bigger-120"></i>
</button>
<ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
<li>
<a href="#" class="tooltip-success" data-rel="tooltip" title="Approve">
<span class="green">
<i class="ace-icon fa fa-check bigger-110"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-warning" data-rel="tooltip" title="Reject">
<span class="orange">
<i class="ace-icon fa fa-times bigger-110"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
<span class="red">
<i class="ace-icon fa fa-trash-o bigger-110"></i>
</span>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="itemdiv memberdiv">
<div class="user">
<img alt="Alex Doe's avatar" src="assets/avatars/avatar5.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Alex Doe</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">3 hour</span>
</div>
<div>
<span class="label label-danger label-sm">blocked</span>
</div>
</div>
</div>
<div class="itemdiv memberdiv">
<div class="user">
<img alt="Bob Doe's avatar" src="assets/avatars/avatar2.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Bob Doe</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">6 hour</span>
</div>
<div>
<span class="label label-success label-sm arrowed-in">approved</span>
</div>
</div>
</div>
<div class="itemdiv memberdiv">
<div class="user">
<img alt="Susan's avatar" src="assets/avatars/avatar3.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Susan</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">yesterday</span>
</div>
<div>
<span class="label label-success label-sm arrowed-in">approved</span>
</div>
</div>
</div>
<div class="itemdiv memberdiv">
<div class="user">
<img alt="Phil Doe's avatar" src="assets/avatars/avatar4.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Phil Doe</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">2 days ago</span>
</div>
<div>
<span class="label label-info label-sm arrowed-in arrowed-in-right">online</span>
</div>
</div>
</div>
<div class="itemdiv memberdiv">
<div class="user">
<img alt="Alexa Doe's avatar" src="assets/avatars/avatar1.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Alexa Doe</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">3 days ago</span>
</div>
<div>
<span class="label label-success label-sm arrowed-in">approved</span>
</div>
</div>
</div>
</div>
<div class="space-4"></div>
<div class="center">
<i class="ace-icon fa fa-users fa-2x green middle"></i>
<a href="#" class="btn btn-sm btn-white btn-info">
See all members
<i class="ace-icon fa fa-arrow-right"></i>
</a>
</div>
<div class="hr hr-double hr8"></div>
</div><!-- /.#member-tab -->
<div id="comment-tab" class="tab-pane">
<div class="comments">
<div class="itemdiv commentdiv">
<div class="user">
<img alt="Bob Doe's Avatar" src="assets/avatars/avatar.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Bob Doe</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">6 min</span>
</div>
<div class="text">
<i class="ace-icon fa fa-quote-left"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque commodo massa sed ipsum porttitor facilisis …
</div>
</div>
<div class="tools">
<div class="inline position-relative">
<button class="btn btn-minier bigger btn-yellow dropdown-toggle" data-toggle="dropdown">
<i class="ace-icon fa fa-angle-down icon-only bigger-120"></i>
</button>
<ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
<li>
<a href="#" class="tooltip-success" data-rel="tooltip" title="Approve">
<span class="green">
<i class="ace-icon fa fa-check bigger-110"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-warning" data-rel="tooltip" title="Reject">
<span class="orange">
<i class="ace-icon fa fa-times bigger-110"></i>
</span>
</a>
</li>
<li>
<a href="#" class="tooltip-error" data-rel="tooltip" title="Delete">
<span class="red">
<i class="ace-icon fa fa-trash-o bigger-110"></i>
</span>
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="itemdiv commentdiv">
<div class="user">
<img alt="Jennifer's Avatar" src="assets/avatars/avatar1.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Jennifer</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="blue">15 min</span>
</div>
<div class="text">
<i class="ace-icon fa fa-quote-left"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque commodo massa sed ipsum porttitor facilisis …
</div>
</div>
<div class="tools">
<div class="action-buttons bigger-125">
<a href="#">
<i class="ace-icon fa fa-pencil blue"></i>
</a>
<a href="#">
<i class="ace-icon fa fa-trash-o red"></i>
</a>
</div>
</div>
</div>
<div class="itemdiv commentdiv">
<div class="user">
<img alt="Joe's Avatar" src="assets/avatars/avatar2.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Joe</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="orange">22 min</span>
</div>
<div class="text">
<i class="ace-icon fa fa-quote-left"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque commodo massa sed ipsum porttitor facilisis …
</div>
</div>
<div class="tools">
<div class="action-buttons bigger-125">
<a href="#">
<i class="ace-icon fa fa-pencil blue"></i>
</a>
<a href="#">
<i class="ace-icon fa fa-trash-o red"></i>
</a>
</div>
</div>
</div>
<div class="itemdiv commentdiv">
<div class="user">
<img alt="Rita's Avatar" src="assets/avatars/avatar3.png" />
</div>
<div class="body">
<div class="name">
<a href="#">Rita</a>
</div>
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="red">50 min</span>
</div>
<div class="text">
<i class="ace-icon fa fa-quote-left"></i>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque commodo massa sed ipsum porttitor facilisis …
</div>
</div>
<div class="tools">
<div class="action-buttons bigger-125">
<a href="#">
<i class="ace-icon fa fa-pencil blue"></i>
</a>
<a href="#">
<i class="ace-icon fa fa-trash-o red"></i>
</a>
</div>
</div>
</div>
</div>
<div class="hr hr8"></div>
<div class="center">
<i class="ace-icon fa fa-comments-o fa-2x green middle"></i>
<a href="#" class="btn btn-sm btn-white btn-info">
See all comments
<i class="ace-icon fa fa-arrow-right"></i>
</a>
</div>
<div class="hr hr-double hr8"></div>
</div>
</div>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.widget-box -->
</div><!-- /.col -->
<div class="col-sm-6">
<div class="widget-box">
<div class="widget-header">
<h4 class="widget-title lighter smaller">
<i class="ace-icon fa fa-comment blue"></i>
Conversation
</h4>
</div>
<div class="widget-body">
<div class="widget-main no-padding">
<div class="dialogs">
<div class="itemdiv dialogdiv">
<div class="user">
<img alt="Alexa's Avatar" src="assets/avatars/avatar1.png" />
</div>
<div class="body">
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">4 sec</span>
</div>
<div class="name">
<a href="#">Alexa</a>
</div>
<div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque commodo massa sed ipsum porttitor facilisis.</div>
<div class="tools">
<a href="#" class="btn btn-minier btn-info">
<i class="icon-only ace-icon fa fa-share"></i>
</a>
</div>
</div>
</div>
<div class="itemdiv dialogdiv">
<div class="user">
<img alt="John's Avatar" src="assets/avatars/avatar.png" />
</div>
<div class="body">
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="blue">38 sec</span>
</div>
<div class="name">
<a href="#">John</a>
</div>
<div class="text">Raw denim you probably haven't heard of them jean shorts Austin.</div>
<div class="tools">
<a href="#" class="btn btn-minier btn-info">
<i class="icon-only ace-icon fa fa-share"></i>
</a>
</div>
</div>
</div>
<div class="itemdiv dialogdiv">
<div class="user">
<img alt="Bob's Avatar" src="assets/avatars/user.jpg" />
</div>
<div class="body">
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="orange">2 min</span>
</div>
<div class="name">
<a href="#">Bob</a>
<span class="label label-info arrowed arrowed-in-right">admin</span>
</div>
<div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque commodo massa sed ipsum porttitor facilisis.</div>
<div class="tools">
<a href="#" class="btn btn-minier btn-info">
<i class="icon-only ace-icon fa fa-share"></i>
</a>
</div>
</div>
</div>
<div class="itemdiv dialogdiv">
<div class="user">
<img alt="Jim's Avatar" src="assets/avatars/avatar4.png" />
</div>
<div class="body">
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="grey">3 min</span>
</div>
<div class="name">
<a href="#">Jim</a>
</div>
<div class="text">Raw denim you probably haven't heard of them jean shorts Austin.</div>
<div class="tools">
<a href="#" class="btn btn-minier btn-info">
<i class="icon-only ace-icon fa fa-share"></i>
</a>
</div>
</div>
</div>
<div class="itemdiv dialogdiv">
<div class="user">
<img alt="Alexa's Avatar" src="assets/avatars/avatar1.png" />
</div>
<div class="body">
<div class="time">
<i class="ace-icon fa fa-clock-o"></i>
<span class="green">4 min</span>
</div>
<div class="name">
<a href="#">Alexa</a>
</div>
<div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
<div class="tools">
<a href="#" class="btn btn-minier btn-info">
<i class="icon-only ace-icon fa fa-share"></i>
</a>
</div>
</div>
</div>
</div>
<form>
<div class="form-actions">
<div class="input-group">
<input placeholder="Type your message here ..." type="text" class="form-control" name="message" />
<span class="input-group-btn">
<button class="btn btn-sm btn-info no-radius" type="button">
<i class="ace-icon fa fa-share"></i>
Send
</button>
</span>
</div>
</div>
</form>
</div><!-- /.widget-main -->
</div><!-- /.widget-body -->
</div><!-- /.widget-box -->
</div><!-- /.col -->
</div><!-- /.row -->
<!-- PAGE CONTENT ENDS -->
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content -->
</div>
</div><!-- /.main-content -->
<div class="footer">
<div class="footer-inner">
<div class="footer-content">
<span class="bigger-120">
<span class="blue bolder">Ace</span>
Application © 2013-2014
</span>
<span class="action-buttons">
<a href="#">
<i class="ace-icon fa fa-twitter-square light-blue bigger-150"></i>
</a>
<a href="#">
<i class="ace-icon fa fa-facebook-square text-primary bigger-150"></i>
</a>
<a href="#">
<i class="ace-icon fa fa-rss-square orange bigger-150"></i>
</a>
</span>
</div>
</div>
</div>
<a href="#" id="btn-scroll-up" class="btn-scroll-up btn btn-sm btn-inverse">
<i class="ace-icon fa fa-angle-double-up icon-only bigger-110"></i>
</a>
</div><!-- /.main-container -->
<!-- basic scripts -->
<!--[if !IE]> -->
<script src="{% static 'js/jquery.2.1.1.min.js'%}"></script>
<!-- <![endif]-->
<!--[if IE]>
<script src="assets/js/jquery.1.11.1.min.js"></script>
<![endif]-->
<!--[if !IE]> -->
<script type="text/javascript">
window.jQuery || document.write("<script src='"+"{% static 'js/jquery.min.js'%}"+"'>"+"<"+"/script>");
</script>
<!-- <![endif]-->
<!--[if IE]>
<script type="text/javascript">
window.jQuery || document.write("<script src='assets/js/jquery1x.min.js'>"+"<"+"/script>");
</script>
<![endif]-->
<script type="text/javascript">
if('ontouchstart' in document.documentElement) document.write("<script src='"+"{% static 'js/jquery.mobile.custom.min.js'%}"+">"+"<"+"/script>");
</script>
<script src="{% static 'js/bootstrap.min.js'%}"></script>
<!-- page specific plugin scripts -->
<!--[if lte IE 8]>
<script src="assets/js/excanvas.min.js"></script>
<![endif]-->
<script src="{% static 'js/jquery-ui.custom.min.js'%}"></script>
<script src="{% static 'js/jquery.ui.touch-punch.min.js'%}"></script>
<script src="{% static 'js/jquery.easypiechart.min.js'%}"></script>
<script src="{% static 'js/jquery.sparkline.min.js'%}"></script>
<script src="{% static 'js/jquery.flot.min.js'%}"></script>
<script src="{% static 'js/jquery.flot.pie.min.js'%}"></script>
<script src="{% static 'js/jquery.flot.resize.min.js'%}"></script>
<!-- ace scripts -->
<script src="{% static 'js/ace-elements.min.js'%}"></script>
<script src="{% static 'js/ace.min.js'%}"></script>
<!-- inline scripts related to this page -->
<script type="text/javascript">
jQuery(function($) {
$('.easy-pie-chart.percentage').each(function(){
var $box = $(this).closest('.infobox');
var barColor = $(this).data('color') || (!$box.hasClass('infobox-dark') ? $box.css('color') : 'rgba(255,255,255,0.95)');
var trackColor = barColor == 'rgba(255,255,255,0.95)' ? 'rgba(255,255,255,0.25)' : '#E2E2E2';
var size = parseInt($(this).data('size')) || 50;
$(this).easyPieChart({
barColor: barColor,
trackColor: trackColor,
scaleColor: false,
lineCap: 'butt',
lineWidth: parseInt(size/10),
animate: /msie\s*(8|7|6)/.test(navigator.userAgent.toLowerCase()) ? false : 1000,
size: size
});
})
$('.sparkline').each(function(){
var $box = $(this).closest('.infobox');
var barColor = !$box.hasClass('infobox-dark') ? $box.css('color') : '#FFF';
$(this).sparkline('html',
{
tagValuesAttribute:'data-values',
type: 'bar',
barColor: barColor ,
chartRangeMin:$(this).data('min') || 0
});
});
//flot chart resize plugin, somehow manipulates default browser resize event to optimize it!
//but sometimes it brings up errors with normal resize event handlers
$.resize.throttleWindow = false;
var placeholder = $('#piechart-placeholder').css({'width':'90%' , 'min-height':'150px'});
var data = [
{ label: "social networks", data: 38.7, color: "#68BC31"},
{ label: "search engines", data: 24.5, color: "#2091CF"},
{ label: "ad campaigns", data: 8.2, color: "#AF4E96"},
{ label: "direct traffic", data: 18.6, color: "#DA5430"},
{ label: "other", data: 10, color: "#FEE074"}
]
function drawPieChart(placeholder, data, position) {
$.plot(placeholder, data, {
series: {
pie: {
show: true,
tilt:0.8,
highlight: {
opacity: 0.25
},
stroke: {
color: '#fff',
width: 2
},
startAngle: 2
}
},
legend: {
show: true,
position: position || "ne",
labelBoxBorderColor: null,
margin:[-30,15]
}
,
grid: {
hoverable: true,
clickable: true
}
})
}
drawPieChart(placeholder, data);
/**
we saved the drawing function and the data to redraw with different position later when switching to RTL mode dynamically
so that's not needed actually.
*/
placeholder.data('chart', data);
placeholder.data('draw', drawPieChart);
//pie chart tooltip example
var $tooltip = $("<div class='tooltip top in'><div class='tooltip-inner'></div></div>").hide().appendTo('body');
var previousPoint = null;
placeholder.on('plothover', function (event, pos, item) {
if(item) {
if (previousPoint != item.seriesIndex) {
previousPoint = item.seriesIndex;
var tip = item.series['label'] + " : " + item.series['percent']+'%';
$tooltip.show().children(0).text(tip);
}
$tooltip.css({top:pos.pageY + 10, left:pos.pageX + 10});
} else {
$tooltip.hide();
previousPoint = null;
}
});
/////////////////////////////////////
$(document).one('ajaxloadstart.page', function(e) {
$tooltip.remove();
});
var d1 = [];
for (var i = 0; i < Math.PI * 2; i += 0.5) {
d1.push([i, Math.sin(i)]);
}
var d2 = [];
for (var i = 0; i < Math.PI * 2; i += 0.5) {
d2.push([i, Math.cos(i)]);
}
var d3 = [];
for (var i = 0; i < Math.PI * 2; i += 0.2) {
d3.push([i, Math.tan(i)]);
}
var sales_charts = $('#sales-charts').css({'width':'100%' , 'height':'220px'});
$.plot("#sales-charts", [
{ label: "Domains", data: d1 },
{ label: "Hosting", data: d2 },
{ label: "Services", data: d3 }
], {
hoverable: true,
shadowSize: 0,
series: {
lines: { show: true },
points: { show: true }
},
xaxis: {
tickLength: 0
},
yaxis: {
ticks: 10,
min: -2,
max: 2,
tickDecimals: 3
},
grid: {
backgroundColor: { colors: [ "#fff", "#fff" ] },
borderWidth: 1,
borderColor:'#555'
}
});
$('#recent-box [data-rel="tooltip"]').tooltip({placement: tooltip_placement});
function tooltip_placement(context, source) {
var $source = $(source);
var $parent = $source.closest('.tab-content')
var off1 = $parent.offset();
var w1 = $parent.width();
var off2 = $source.offset();
//var w2 = $source.width();
if( parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2) ) return 'right';
return 'left';
}
$('.dialogs,.comments').ace_scroll({
size: 300
});
//Android's default browser somehow is confused when tapping on label which will lead to dragging the task
//so disable dragging when clicking on label
var agent = navigator.userAgent.toLowerCase();
if("ontouchstart" in document && /applewebkit/.test(agent) && /android/.test(agent))
$('#tasks').on('touchstart', function(e){
var li = $(e.target).closest('#tasks li');
if(li.length == 0)return;
var label = li.find('label.inline').get(0);
if(label == e.target || $.contains(label, e.target)) e.stopImmediatePropagation() ;
});
$('#tasks').sortable({
opacity:0.8,
revert:true,
forceHelperSize:true,
placeholder: 'draggable-placeholder',
forcePlaceholderSize:true,
tolerance:'pointer',
stop: function( event, ui ) {
//just for Chrome!!!! so that dropdowns on items don't appear below other items after being moved
$(ui.item).css('z-index', 'auto');
}
}
);
$('#tasks').disableSelection();
$('#tasks input:checkbox').removeAttr('checked').on('click', function(){
if(this.checked) $(this).closest('li').addClass('selected');
else $(this).closest('li').removeClass('selected');
});
//show the dropdowns on top or bottom depending on window height and menu position
$('#task-tab .dropdown-hover').on('mouseenter', function(e) {
var offset = $(this).offset();
var $w = $(window)
if (offset.top > $w.scrollTop() + $w.innerHeight() - 100)
$(this).addClass('dropup');
else $(this).removeClass('dropup');
});
})
</script>
</body>
</html>
| elberthcabrales/djangoerp | source/templates/index.html | HTML | gpl-2.0 | 143,359 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.