code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<?php
/**
* The sent table file.
*
* @version $Id: $
* @copyright Copyright (C) 2011 Migur Ltd. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access.
defined('_JEXEC') or die;
/**
* Class of downloads table. Implement the functionality for it.
*
* @since 1.0
* @package Migur.Newsletter
*/
class NewsletterTableDownloads extends JTable
{
/**
* The constructor of a class.
*
* @param object $config An object of configuration settings.
*
* @return void
* @since 1.0
*/
public function __construct(&$_db)
{
parent::__construct(
'#__newsletter_downloads',
'downloads_id',
$_db
);
}
/**
* Get all the extensions for newsletter.
*
* @param int $id id of a newsletter
* @return array list of extensions
*/
public function getRowsBy($id)
{
$db = $this->_db;
$query = $db->getQuery(true);
// Select the required fields from the table.
$query->select('a.*');
$query->from('#__newsletter_downloads AS a');
$query->where('newsletter_id=' . intval($id));
$db->setQuery($query);
//echo nl2br(str_replace('#__','jos_',$query)); die;
return $db->loadAssocList();
}
}
|
Rikisha/proj
|
administrator/components/com_newsletter/tables/downloads.php
|
PHP
|
gpl-2.0
| 1,220 |
/*
Copyright (C) 2007 Paul Davis
Author: Dave Robillard
Author: Hans Baier
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 "evoral/Note.hpp"
#include "canvas/rectangle.h"
#include "canvas/debug.h"
#include "note.h"
#include "public_editor.h"
using namespace ARDOUR;
using namespace ArdourCanvas;
Note::Note (
MidiRegionView& region, Item* parent, const boost::shared_ptr<NoteType> note, bool with_events)
: NoteBase (region, with_events, note)
, _rectangle (new ArdourCanvas::Rectangle (parent))
{
CANVAS_DEBUG_NAME (_rectangle, "note");
set_item (_rectangle);
}
Note::~Note ()
{
delete _rectangle;
}
void
Note::move_event (double dx, double dy)
{
_rectangle->set (_rectangle->get().translate (Duple (dx, dy)));
}
Coord
Note::x0 () const
{
return _rectangle->x0 ();
}
Coord
Note::x1 () const
{
return _rectangle->x1 ();
}
Coord
Note::y0 () const
{
return _rectangle->y0 ();
}
Coord
Note::y1 () const
{
return _rectangle->y1 ();
}
void
Note::set_outline_color (uint32_t color)
{
_rectangle->set_outline_color (color);
}
void
Note::set_fill_color (uint32_t color)
{
_rectangle->set_fill_color (color);
}
void
Note::show ()
{
_rectangle->show ();
}
void
Note::hide ()
{
_rectangle->hide ();
}
void
Note::set (ArdourCanvas::Rect rect)
{
_rectangle->set (rect);
}
void
Note::set_x0 (Coord x0)
{
_rectangle->set_x0 (x0);
}
void
Note::set_y0 (Coord y0)
{
_rectangle->set_y0 (y0);
}
void
Note::set_x1 (Coord x1)
{
_rectangle->set_x1 (x1);
}
void
Note::set_y1 (Coord y1)
{
_rectangle->set_y1 (y1);
}
void
Note::set_outline_what (ArdourCanvas::Rectangle::What what)
{
_rectangle->set_outline_what (what);
}
void
Note::set_outline_all ()
{
_rectangle->set_outline_all ();
}
void
Note::set_ignore_events (bool ignore)
{
_rectangle->set_ignore_events (ignore);
}
|
nphilipp/ardour
|
gtk2_ardour/note.cc
|
C++
|
gpl-2.0
| 2,477 |
/* Copyright (c) 2010-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/interrupt.h>
#include <mach/msm_iomap.h>
#include <mach/msm_bus.h>
#include <mach/socinfo.h>
#include "kgsl.h"
#include "kgsl_pwrscale.h"
#include "kgsl_device.h"
#include "kgsl_trace.h"
#define KGSL_PWRFLAGS_POWER_ON 0
#define KGSL_PWRFLAGS_CLK_ON 1
#define KGSL_PWRFLAGS_AXI_ON 2
#define KGSL_PWRFLAGS_IRQ_ON 3
#define UPDATE_BUSY_VAL 1000000
#define UPDATE_BUSY 50
struct clk_pair {
const char *name;
uint map;
};
struct clk_pair clks[KGSL_MAX_CLKS] = {
{
.name = "src_clk",
.map = KGSL_CLK_SRC,
},
{
.name = "core_clk",
.map = KGSL_CLK_CORE,
},
{
.name = "iface_clk",
.map = KGSL_CLK_IFACE,
},
{
.name = "mem_clk",
.map = KGSL_CLK_MEM,
},
{
.name = "mem_iface_clk",
.map = KGSL_CLK_MEM_IFACE,
},
};
static void kgsl_pwrctrl_set_lowest_level(struct kgsl_device *device)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
const int new_level = pwr->num_pwrlevels - 1;
if (new_level >= pwr->thermal_pwrlevel && new_level != pwr->active_pwrlevel) {
struct kgsl_pwrlevel *pwrlevel = &pwr->pwrlevels[new_level];
pwr->active_pwrlevel = new_level;
if ((test_bit(KGSL_PWRFLAGS_CLK_ON, &pwr->power_flags)) ||
(device->state == KGSL_STATE_NAP))
clk_set_rate(pwr->grp_clks[0], pwrlevel->gpu_freq);
if (test_bit(KGSL_PWRFLAGS_AXI_ON, &pwr->power_flags)) {
if (pwr->pcl)
msm_bus_scale_client_update_request(pwr->pcl,
pwrlevel->bus_freq);
else if (pwr->ebi1_clk)
clk_set_rate(pwr->ebi1_clk, pwrlevel->bus_freq);
}
trace_kgsl_pwrlevel(device, pwr->active_pwrlevel,
pwrlevel->gpu_freq);
}
}
void kgsl_pwrctrl_pwrlevel_change(struct kgsl_device *device,
unsigned int new_level)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
if (new_level < (pwr->num_pwrlevels - 1) &&
new_level >= pwr->thermal_pwrlevel &&
new_level != pwr->active_pwrlevel) {
struct kgsl_pwrlevel *pwrlevel = &pwr->pwrlevels[new_level];
pwr->active_pwrlevel = new_level;
if ((test_bit(KGSL_PWRFLAGS_CLK_ON, &pwr->power_flags)) ||
(device->state == KGSL_STATE_NAP))
clk_set_rate(pwr->grp_clks[0], pwrlevel->gpu_freq);
if (test_bit(KGSL_PWRFLAGS_AXI_ON, &pwr->power_flags)) {
if (pwr->pcl)
msm_bus_scale_client_update_request(pwr->pcl,
pwrlevel->bus_freq);
else if (pwr->ebi1_clk)
clk_set_rate(pwr->ebi1_clk, pwrlevel->bus_freq);
}
trace_kgsl_pwrlevel(device, pwr->active_pwrlevel,
pwrlevel->gpu_freq);
}
}
EXPORT_SYMBOL(kgsl_pwrctrl_pwrlevel_change);
static int __gpuclk_store(int max, struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{ int ret, i, delta = 5000000;
unsigned long val;
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
ret = sscanf(buf, "%ld", &val);
if (ret != 1)
return count;
mutex_lock(&device->mutex);
for (i = 0; i < pwr->num_pwrlevels; i++) {
if (abs(pwr->pwrlevels[i].gpu_freq - val) < delta) {
if (max)
pwr->thermal_pwrlevel = i;
break;
}
}
if (i == pwr->num_pwrlevels)
goto done;
/*
* If the current or requested clock speed is greater than the
* thermal limit, bump down immediately.
*/
if (pwr->pwrlevels[pwr->active_pwrlevel].gpu_freq >
pwr->pwrlevels[pwr->thermal_pwrlevel].gpu_freq)
if (max && pwr->thermal_pwrlevel == pwr->thermal_pwrlevel) {
kgsl_pwrctrl_set_lowest_level(device);
} else
kgsl_pwrctrl_pwrlevel_change(device, pwr->thermal_pwrlevel);
else if (!max)
kgsl_pwrctrl_pwrlevel_change(device, i);
done:
mutex_unlock(&device->mutex);
return count;
}
static int kgsl_pwrctrl_max_gpuclk_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return __gpuclk_store(1, dev, attr, buf, count);
}
static int kgsl_pwrctrl_max_gpuclk_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
return snprintf(buf, PAGE_SIZE, "%d\n",
pwr->pwrlevels[pwr->thermal_pwrlevel].gpu_freq);
}
static int kgsl_pwrctrl_gpuclk_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return __gpuclk_store(0, dev, attr, buf, count);
}
static int kgsl_pwrctrl_gpuclk_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
return snprintf(buf, PAGE_SIZE, "%d\n",
pwr->pwrlevels[pwr->active_pwrlevel].gpu_freq);
}
static int kgsl_pwrctrl_pwrnap_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
char temp[20];
unsigned long val;
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
int rc;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
snprintf(temp, sizeof(temp), "%.*s",
(int)min(count, sizeof(temp) - 1), buf);
rc = strict_strtoul(temp, 0, &val);
if (rc)
return rc;
mutex_lock(&device->mutex);
if (val == 1)
pwr->nap_allowed = true;
else if (val == 0)
pwr->nap_allowed = false;
mutex_unlock(&device->mutex);
return count;
}
static int kgsl_pwrctrl_pwrnap_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct kgsl_device *device = kgsl_device_from_dev(dev);
if (device == NULL)
return 0;
return snprintf(buf, PAGE_SIZE, "%d\n", device->pwrctrl.nap_allowed);
}
static int kgsl_pwrctrl_idle_timer_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
char temp[20];
unsigned long val;
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
const long div = 1000/HZ;
static unsigned int org_interval_timeout = 1;
int rc;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
snprintf(temp, sizeof(temp), "%.*s",
(int)min(count, sizeof(temp) - 1), buf);
rc = strict_strtoul(temp, 0, &val);
if (rc)
return rc;
if (org_interval_timeout == 1)
org_interval_timeout = pwr->interval_timeout;
mutex_lock(&device->mutex);
/* Let the timeout be requested in ms, but convert to jiffies. */
val /= div;
if (val >= org_interval_timeout)
pwr->interval_timeout = val;
mutex_unlock(&device->mutex);
return count;
}
static int kgsl_pwrctrl_idle_timer_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct kgsl_device *device = kgsl_device_from_dev(dev);
if (device == NULL)
return 0;
return snprintf(buf, PAGE_SIZE, "%d\n",
device->pwrctrl.interval_timeout);
}
static int kgsl_pwrctrl_gpubusy_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_busy *b = &device->pwrctrl.busy;
ret = snprintf(buf, 17, "%7d %7d\n",
b->on_time_old, b->time_old);
if (!test_bit(KGSL_PWRFLAGS_AXI_ON, &device->pwrctrl.power_flags)) {
b->on_time_old = 0;
b->time_old = 0;
}
return ret;
}
DEVICE_ATTR(gpuclk, 0644, kgsl_pwrctrl_gpuclk_show, kgsl_pwrctrl_gpuclk_store);
DEVICE_ATTR(max_gpuclk, 0644, kgsl_pwrctrl_max_gpuclk_show,
kgsl_pwrctrl_max_gpuclk_store);
DEVICE_ATTR(pwrnap, 0644, kgsl_pwrctrl_pwrnap_show, kgsl_pwrctrl_pwrnap_store);
DEVICE_ATTR(idle_timer, 0644, kgsl_pwrctrl_idle_timer_show,
kgsl_pwrctrl_idle_timer_store);
DEVICE_ATTR(gpubusy, 0644, kgsl_pwrctrl_gpubusy_show,
NULL);
static const struct device_attribute *pwrctrl_attr_list[] = {
&dev_attr_gpuclk,
&dev_attr_max_gpuclk,
&dev_attr_pwrnap,
&dev_attr_idle_timer,
&dev_attr_gpubusy,
NULL
};
int kgsl_pwrctrl_init_sysfs(struct kgsl_device *device)
{
return kgsl_create_device_sysfs_files(device->dev, pwrctrl_attr_list);
}
void kgsl_pwrctrl_uninit_sysfs(struct kgsl_device *device)
{
kgsl_remove_device_sysfs_files(device->dev, pwrctrl_attr_list);
}
/* Track the amount of time the gpu is on vs the total system time. *
* Regularly update the percentage of busy time displayed by sysfs. */
static void kgsl_pwrctrl_busy_time(struct kgsl_device *device, bool on_time)
{
struct kgsl_busy *b = &device->pwrctrl.busy;
int elapsed;
if (b->start.tv_sec == 0)
do_gettimeofday(&(b->start));
do_gettimeofday(&(b->stop));
elapsed = (b->stop.tv_sec - b->start.tv_sec) * 1000000;
elapsed += b->stop.tv_usec - b->start.tv_usec;
b->time += elapsed;
if (on_time)
b->on_time += elapsed;
/* Update the output regularly and reset the counters. */
if ((b->time > UPDATE_BUSY_VAL) ||
!test_bit(KGSL_PWRFLAGS_AXI_ON, &device->pwrctrl.power_flags)) {
b->on_time_old = b->on_time;
b->time_old = b->time;
b->on_time = 0;
b->time = 0;
}
do_gettimeofday(&(b->start));
}
void kgsl_pwrctrl_clk(struct kgsl_device *device, int state)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
int i = 0;
if (state == KGSL_PWRFLAGS_OFF) {
if (test_and_clear_bit(KGSL_PWRFLAGS_CLK_ON,
&pwr->power_flags)) {
trace_kgsl_clk(device, state);
for (i = KGSL_MAX_CLKS - 1; i > 0; i--)
if (pwr->grp_clks[i])
clk_disable(pwr->grp_clks[i]);
if ((pwr->pwrlevels[0].gpu_freq > 0) &&
(device->requested_state != KGSL_STATE_NAP))
clk_set_rate(pwr->grp_clks[0],
pwr->pwrlevels[pwr->num_pwrlevels - 1].
gpu_freq);
kgsl_pwrctrl_busy_time(device, true);
}
} else if (state == KGSL_PWRFLAGS_ON) {
if (!test_and_set_bit(KGSL_PWRFLAGS_CLK_ON,
&pwr->power_flags)) {
trace_kgsl_clk(device, state);
if ((pwr->pwrlevels[0].gpu_freq > 0) &&
(device->state != KGSL_STATE_NAP))
clk_set_rate(pwr->grp_clks[0],
pwr->pwrlevels[pwr->active_pwrlevel].
gpu_freq);
/* as last step, enable grp_clk
this is to let GPU interrupt to come */
for (i = KGSL_MAX_CLKS - 1; i > 0; i--)
if (pwr->grp_clks[i])
clk_enable(pwr->grp_clks[i]);
kgsl_pwrctrl_busy_time(device, false);
}
}
}
EXPORT_SYMBOL(kgsl_pwrctrl_clk);
void kgsl_pwrctrl_axi(struct kgsl_device *device, int state)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
if (state == KGSL_PWRFLAGS_OFF) {
if (test_and_clear_bit(KGSL_PWRFLAGS_AXI_ON,
&pwr->power_flags)) {
trace_kgsl_bus(device, state);
if (pwr->ebi1_clk) {
clk_set_rate(pwr->ebi1_clk, 0);
clk_disable(pwr->ebi1_clk);
}
if (pwr->pcl)
msm_bus_scale_client_update_request(pwr->pcl,
0);
}
} else if (state == KGSL_PWRFLAGS_ON) {
if (!test_and_set_bit(KGSL_PWRFLAGS_AXI_ON,
&pwr->power_flags)) {
trace_kgsl_bus(device, state);
if (pwr->ebi1_clk) {
clk_enable(pwr->ebi1_clk);
clk_set_rate(pwr->ebi1_clk,
pwr->pwrlevels[pwr->active_pwrlevel].
bus_freq);
}
if (pwr->pcl)
msm_bus_scale_client_update_request(pwr->pcl,
pwr->pwrlevels[pwr->active_pwrlevel].
bus_freq);
}
}
}
void kgsl_pwrctrl_pwrrail(struct kgsl_device *device, int state)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
if (state == KGSL_PWRFLAGS_OFF) {
if (test_and_clear_bit(KGSL_PWRFLAGS_POWER_ON,
&pwr->power_flags)) {
trace_kgsl_rail(device, state);
if (pwr->gpu_reg)
regulator_disable(pwr->gpu_reg);
}
} else if (state == KGSL_PWRFLAGS_ON) {
if (!test_and_set_bit(KGSL_PWRFLAGS_POWER_ON,
&pwr->power_flags)) {
trace_kgsl_rail(device, state);
if (pwr->gpu_reg)
regulator_enable(pwr->gpu_reg);
}
}
}
void kgsl_pwrctrl_irq(struct kgsl_device *device, int state)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
if (state == KGSL_PWRFLAGS_ON) {
if (!test_and_set_bit(KGSL_PWRFLAGS_IRQ_ON,
&pwr->power_flags)) {
trace_kgsl_irq(device, state);
enable_irq(pwr->interrupt_num);
}
} else if (state == KGSL_PWRFLAGS_OFF) {
if (test_and_clear_bit(KGSL_PWRFLAGS_IRQ_ON,
&pwr->power_flags)) {
trace_kgsl_irq(device, state);
if (in_interrupt())
disable_irq_nosync(pwr->interrupt_num);
else
disable_irq(pwr->interrupt_num);
}
}
}
EXPORT_SYMBOL(kgsl_pwrctrl_irq);
int kgsl_pwrctrl_init(struct kgsl_device *device)
{
int i, result = 0;
struct clk *clk;
struct platform_device *pdev =
container_of(device->parentdev, struct platform_device, dev);
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
struct kgsl_device_platform_data *pdata = pdev->dev.platform_data;
/*acquire clocks */
for (i = 0; i < KGSL_MAX_CLKS; i++) {
if (pdata->clk_map & clks[i].map) {
clk = clk_get(&pdev->dev, clks[i].name);
if (IS_ERR(clk))
goto clk_err;
pwr->grp_clks[i] = clk;
}
}
/* Make sure we have a source clk for freq setting */
if (pwr->grp_clks[0] == NULL)
pwr->grp_clks[0] = pwr->grp_clks[1];
/* put the AXI bus into asynchronous mode with the graphics cores */
if (pdata->set_grp_async != NULL)
pdata->set_grp_async();
if (pdata->num_levels > KGSL_MAX_PWRLEVELS) {
KGSL_PWR_ERR(device, "invalid power level count: %d\n",
pdata->num_levels);
result = -EINVAL;
goto done;
}
pwr->num_pwrlevels = pdata->num_levels;
pwr->active_pwrlevel = pdata->init_level;
for (i = 0; i < pdata->num_levels; i++) {
pwr->pwrlevels[i].gpu_freq =
(pdata->pwrlevel[i].gpu_freq > 0) ?
clk_round_rate(pwr->grp_clks[0],
pdata->pwrlevel[i].
gpu_freq) : 0;
pwr->pwrlevels[i].bus_freq =
pdata->pwrlevel[i].bus_freq;
pwr->pwrlevels[i].io_fraction =
pdata->pwrlevel[i].io_fraction;
}
/* Do not set_rate for targets in sync with AXI */
if (pwr->pwrlevels[0].gpu_freq > 0)
clk_set_rate(pwr->grp_clks[0], pwr->
pwrlevels[pwr->num_pwrlevels - 1].gpu_freq);
pwr->gpu_reg = regulator_get(NULL, pwr->regulator_name);
if (IS_ERR(pwr->gpu_reg))
pwr->gpu_reg = NULL;
pwr->power_flags = 0;
pwr->nap_allowed = pdata->nap_allowed;
pwr->interval_timeout = pdata->idle_timeout;
pwr->ebi1_clk = clk_get(&pdev->dev, "bus_clk");
if (IS_ERR(pwr->ebi1_clk))
pwr->ebi1_clk = NULL;
else
clk_set_rate(pwr->ebi1_clk,
pwr->pwrlevels[pwr->active_pwrlevel].
bus_freq);
if (pdata->bus_scale_table != NULL) {
pwr->pcl = msm_bus_scale_register_client(pdata->
bus_scale_table);
if (!pwr->pcl) {
KGSL_PWR_ERR(device,
"msm_bus_scale_register_client failed: "
"id %d table %p", device->id,
pdata->bus_scale_table);
result = -EINVAL;
goto done;
}
}
/*acquire interrupt */
pwr->interrupt_num =
platform_get_irq_byname(pdev, pwr->irq_name);
if (pwr->interrupt_num <= 0) {
KGSL_PWR_ERR(device, "platform_get_irq_byname failed: %d\n",
pwr->interrupt_num);
result = -EINVAL;
goto done;
}
register_early_suspend(&device->display_off);
return result;
clk_err:
result = PTR_ERR(clk);
KGSL_PWR_ERR(device, "clk_get(%s) failed: %d\n",
clks[i].name, result);
done:
return result;
}
void kgsl_pwrctrl_close(struct kgsl_device *device)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
int i;
KGSL_PWR_INFO(device, "close device %d\n", device->id);
unregister_early_suspend(&device->display_off);
if (pwr->interrupt_num > 0) {
if (pwr->have_irq) {
free_irq(pwr->interrupt_num, NULL);
pwr->have_irq = 0;
}
pwr->interrupt_num = 0;
}
clk_put(pwr->ebi1_clk);
if (pwr->pcl)
msm_bus_scale_unregister_client(pwr->pcl);
pwr->pcl = 0;
if (pwr->gpu_reg) {
regulator_put(pwr->gpu_reg);
pwr->gpu_reg = NULL;
}
for (i = 1; i < KGSL_MAX_CLKS; i++)
if (pwr->grp_clks[i]) {
clk_put(pwr->grp_clks[i]);
pwr->grp_clks[i] = NULL;
}
pwr->grp_clks[0] = NULL;
pwr->power_flags = 0;
}
void kgsl_idle_check(struct work_struct *work)
{
struct kgsl_device *device = container_of(work, struct kgsl_device,
idle_check_ws);
WARN_ON(device == NULL);
if (device == NULL)
return;
mutex_lock(&device->mutex);
if (device->state & (KGSL_STATE_ACTIVE | KGSL_STATE_NAP)) {
if ((device->requested_state != KGSL_STATE_SLEEP) &&
(device->requested_state != KGSL_STATE_SLUMBER))
kgsl_pwrscale_idle(device);
if (kgsl_pwrctrl_sleep(device) != 0) {
mod_timer(&device->idle_timer,
jiffies +
device->pwrctrl.interval_timeout);
device->idle_timer_enabled = true;
/* If the GPU has been too busy to sleep, make sure *
* that is acurately reflected in the % busy numbers. */
device->pwrctrl.busy.no_nap_cnt++;
if (device->pwrctrl.busy.no_nap_cnt > UPDATE_BUSY) {
kgsl_pwrctrl_busy_time(device, true);
device->pwrctrl.busy.no_nap_cnt = 0;
}
}
} else if (device->state & (KGSL_STATE_HUNG |
KGSL_STATE_DUMP_AND_RECOVER)) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
}
mutex_unlock(&device->mutex);
}
void kgsl_timer(unsigned long data)
{
struct kgsl_device *device = (struct kgsl_device *) data;
KGSL_PWR_INFO(device, "idle timer expired device %d\n", device->id);
if (device->requested_state != KGSL_STATE_SUSPEND) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_SLEEP);
/* Have work run in a non-interrupt context. */
queue_work(device->work_queue, &device->idle_check_ws);
}
}
void kgsl_pre_hwaccess(struct kgsl_device *device)
{
BUG_ON(!mutex_is_locked(&device->mutex));
if (device->state & (KGSL_STATE_SLEEP | KGSL_STATE_NAP |
KGSL_STATE_SLUMBER))
kgsl_pwrctrl_wake(device);
}
EXPORT_SYMBOL(kgsl_pre_hwaccess);
void kgsl_check_suspended(struct kgsl_device *device)
{
if (device->requested_state == KGSL_STATE_SUSPEND ||
device->state == KGSL_STATE_SUSPEND) {
mutex_unlock(&device->mutex);
wait_for_completion(&device->hwaccess_gate);
mutex_lock(&device->mutex);
} else if (device->state == KGSL_STATE_DUMP_AND_RECOVER) {
mutex_unlock(&device->mutex);
wait_for_completion(&device->recovery_gate);
mutex_lock(&device->mutex);
} else if (device->state == KGSL_STATE_SLUMBER)
kgsl_pwrctrl_wake(device);
}
static int
_nap(struct kgsl_device *device)
{
switch (device->state) {
case KGSL_STATE_ACTIVE:
if (!device->ftbl->isidle(device)) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
return -EBUSY;
}
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_set_state(device, KGSL_STATE_NAP);
if (device->idle_wakelock.name)
wake_unlock(&device->idle_wakelock);
case KGSL_STATE_NAP:
case KGSL_STATE_SLEEP:
case KGSL_STATE_SLUMBER:
break;
default:
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
break;
}
return 0;
}
static void
_sleep_accounting(struct kgsl_device *device)
{
kgsl_pwrctrl_busy_time(device, false);
device->pwrctrl.busy.start.tv_sec = 0;
device->pwrctrl.time = 0;
kgsl_pwrscale_sleep(device);
}
static int
_sleep(struct kgsl_device *device)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
switch (device->state) {
case KGSL_STATE_ACTIVE:
if (!device->ftbl->isidle(device)) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
return -EBUSY;
}
/* fall through */
case KGSL_STATE_NAP:
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_axi(device, KGSL_PWRFLAGS_OFF);
if (pwr->pwrlevels[0].gpu_freq > 0)
clk_set_rate(pwr->grp_clks[0],
pwr->pwrlevels[pwr->num_pwrlevels - 1].
gpu_freq);
_sleep_accounting(device);
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_set_state(device, KGSL_STATE_SLEEP);
if (device->idle_wakelock.name)
wake_unlock(&device->idle_wakelock);
break;
case KGSL_STATE_SLEEP:
case KGSL_STATE_SLUMBER:
break;
default:
KGSL_PWR_WARN(device, "unhandled state %s\n",
kgsl_pwrstate_to_str(device->state));
break;
}
return 0;
}
static int
_slumber(struct kgsl_device *device)
{
switch (device->state) {
case KGSL_STATE_ACTIVE:
if (!device->ftbl->isidle(device)) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
device->pwrctrl.restore_slumber = true;
return -EBUSY;
}
/* fall through */
case KGSL_STATE_NAP:
case KGSL_STATE_SLEEP:
del_timer_sync(&device->idle_timer);
device->idle_timer_enabled = false;
kgsl_pwrctrl_pwrlevel_change(device, KGSL_PWRLEVEL_NOMINAL);
device->ftbl->suspend_context(device);
device->ftbl->stop(device);
device->pwrctrl.restore_slumber = true;
_sleep_accounting(device);
kgsl_pwrctrl_set_state(device, KGSL_STATE_SLUMBER);
if (device->idle_wakelock.name)
wake_unlock(&device->idle_wakelock);
break;
case KGSL_STATE_SLUMBER:
break;
default:
KGSL_PWR_WARN(device, "unhandled state %s\n",
kgsl_pwrstate_to_str(device->state));
break;
}
return 0;
}
/******************************************************************/
/* Caller must hold the device mutex. */
int kgsl_pwrctrl_sleep(struct kgsl_device *device)
{
int status = 0;
KGSL_PWR_INFO(device, "sleep device %d\n", device->id);
/* Work through the legal state transitions */
switch (device->requested_state) {
case KGSL_STATE_NAP:
if (device->pwrctrl.restore_slumber) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
break;
}
status = _nap(device);
break;
case KGSL_STATE_SLEEP:
if (device->pwrctrl.restore_slumber)
status = _slumber(device);
else
status = _sleep(device);
break;
case KGSL_STATE_SLUMBER:
status = _slumber(device);
break;
default:
KGSL_PWR_INFO(device, "bad state request 0x%x\n",
device->requested_state);
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
status = -EINVAL;
break;
}
return status;
}
EXPORT_SYMBOL(kgsl_pwrctrl_sleep);
/******************************************************************/
/* Caller must hold the device mutex. */
void kgsl_pwrctrl_wake(struct kgsl_device *device)
{
int status;
kgsl_pwrctrl_request_state(device, KGSL_STATE_ACTIVE);
switch (device->state) {
case KGSL_STATE_SLUMBER:
status = device->ftbl->start(device, 0);
if (status) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
KGSL_DRV_ERR(device, "start failed %d\n", status);
break;
}
/* fall through */
case KGSL_STATE_SLEEP:
kgsl_pwrctrl_axi(device, KGSL_PWRFLAGS_ON);
kgsl_pwrscale_wake(device);
/* fall through */
case KGSL_STATE_NAP:
/* Turn on the core clocks */
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_ON);
/* Enable state before turning on irq */
kgsl_pwrctrl_set_state(device, KGSL_STATE_ACTIVE);
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_ON);
/* Re-enable HW access */
mod_timer(&device->idle_timer,
jiffies + device->pwrctrl.interval_timeout);
device->idle_timer_enabled = true;
if (device->idle_wakelock.name)
wake_lock(&device->idle_wakelock);
case KGSL_STATE_ACTIVE:
break;
default:
KGSL_PWR_WARN(device, "unhandled state %s\n",
kgsl_pwrstate_to_str(device->state));
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
break;
}
}
EXPORT_SYMBOL(kgsl_pwrctrl_wake);
void kgsl_pwrctrl_enable(struct kgsl_device *device)
{
/* Order pwrrail/clk sequence based upon platform */
kgsl_pwrctrl_pwrrail(device, KGSL_PWRFLAGS_ON);
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_ON);
kgsl_pwrctrl_axi(device, KGSL_PWRFLAGS_ON);
}
EXPORT_SYMBOL(kgsl_pwrctrl_enable);
void kgsl_pwrctrl_disable(struct kgsl_device *device)
{
/* Order pwrrail/clk sequence based upon platform */
kgsl_pwrctrl_axi(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_pwrrail(device, KGSL_PWRFLAGS_OFF);
}
EXPORT_SYMBOL(kgsl_pwrctrl_disable);
void kgsl_pwrctrl_stop_work(struct kgsl_device *device)
{
del_timer_sync(&device->idle_timer);
device->idle_timer_enabled = false;
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF);
mutex_unlock(&device->mutex);
flush_workqueue(device->work_queue);
mutex_lock(&device->mutex);
}
EXPORT_SYMBOL(kgsl_pwrctrl_stop_work);
void kgsl_pwrctrl_set_state(struct kgsl_device *device, unsigned int state)
{
trace_kgsl_pwr_set_state(device, state);
device->state = state;
device->requested_state = KGSL_STATE_NONE;
}
EXPORT_SYMBOL(kgsl_pwrctrl_set_state);
void kgsl_pwrctrl_request_state(struct kgsl_device *device, unsigned int state)
{
if (state != KGSL_STATE_NONE && state != device->requested_state)
trace_kgsl_pwr_request_state(device, state);
device->requested_state = state;
}
EXPORT_SYMBOL(kgsl_pwrctrl_request_state);
const char *kgsl_pwrstate_to_str(unsigned int state)
{
switch (state) {
case KGSL_STATE_NONE:
return "NONE";
case KGSL_STATE_INIT:
return "INIT";
case KGSL_STATE_ACTIVE:
return "ACTIVE";
case KGSL_STATE_NAP:
return "NAP";
case KGSL_STATE_SLEEP:
return "SLEEP";
case KGSL_STATE_SUSPEND:
return "SUSPEND";
case KGSL_STATE_HUNG:
return "HUNG";
case KGSL_STATE_DUMP_AND_RECOVER:
return "DNR";
case KGSL_STATE_SLUMBER:
return "SLUMBER";
default:
break;
}
return "UNKNOWN";
}
EXPORT_SYMBOL(kgsl_pwrstate_to_str);
|
mdeejay/android_kernel_ville
|
drivers/gpu/msm/kgsl_pwrctrl.c
|
C
|
gpl-2.0
| 25,058 |
#!/bin/bash
DIR="$(cd "$(dirname "$0")" && pwd)"
TCLLIBPATH="$DIR/../../"
export TCLLIBPATH=$TCLLIBPATH
export NINEPM_CONFIG="$DIR/env_conf.yaml"
$DIR/env_args.tcl
$DIR/cmdl_args.tcl -c "$DIR/cmdl_conf.yaml"
|
andbof/9pm
|
unit_tests/args/precedence.sh
|
Shell
|
gpl-2.0
| 211 |
import threading
import serial
import wx
from wx.lib.pubsub import pub as Publisher
from numpy import *
from math import sqrt
from time import sleep
class Corregister(threading.Thread):
def __init__(self, bases, flag):
threading.Thread.__init__(self)
self.Minv = bases[0]
self.N = bases[1]
self.q1 = bases[2]
self.q2 = bases[3]
self.flag = flag
self._pause_ = 0
self.start()
def stop(self):
# Stop neuronavigation
self._pause_ = 1
def Coordinates(self):
#Get Polhemus points for neuronavigation
ser = serial.Serial(0)
ser.write("Y")
ser.write("P")
str = ser.readline()
ser.write("Y")
str = str.replace("\r\n","")
str = str.replace("-"," -")
aostr = [s for s in str.split()]
#aoflt -> 0:letter 1:x 2:y 3:z
aoflt = [float(aostr[1]), float(aostr[2]), float(aostr[3]),
float(aostr[4]), float(aostr[5]), float(aostr[6])]
ser.close()
#Unit change: inches to millimeters
x = 25.4
y = 25.4
z = -25.4
coord = (aoflt[0]*x, aoflt[1]*y, aoflt[2]*z)
return coord
def run(self):
while self.flag == True:
#Neuronavigation with Polhemus
trck = self.Coordinates()
tracker = matrix([[trck[0]], [trck[1]], [trck[2]]])
img = self.q1 + (self.Minv*self.N)*(tracker - self.q2)
coord = [float(img[0]), float(img[1]), float(img[2])]
coord_cam = float(img[0]), float(img[1]), float(img[2])
Publisher.sendMessage('Set ball reference position based on bound', coord_cam)
Publisher.sendMessage('Set camera in volume', coord_cam)
wx.CallAfter(Publisher.sendMessage, 'Render volume viewer')
wx.CallAfter(Publisher.sendMessage, 'Co-registered Points', coord)
sleep(0.005)
if self._pause_:
return
|
givanaldo/invesalius3
|
invesalius/data/co_registration.py
|
Python
|
gpl-2.0
| 2,140 |
/* Copyright (c) 2002,2007-2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/vmalloc.h>
#include <linux/memory_alloc.h>
#include <asm/cacheflush.h>
#include "kgsl.h"
#include "kgsl_sharedmem.h"
#include "kgsl_cffdump.h"
#include "kgsl_device.h"
static struct kgsl_process_private *
_get_priv_from_kobj(struct kobject *kobj)
{
struct kgsl_process_private *private;
unsigned long name;
if (!kobj)
return NULL;
if (sscanf(kobj->name, "%ld", &name) != 1)
return NULL;
list_for_each_entry(private, &kgsl_driver.process_list, list) {
if (private->pid == name)
return private;
}
return NULL;
}
/* sharedmem / memory sysfs files */
static ssize_t
process_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
struct kgsl_process_private *priv;
unsigned int val = 0;
mutex_lock(&kgsl_driver.process_mutex);
priv = _get_priv_from_kobj(kobj);
if (priv == NULL) {
mutex_unlock(&kgsl_driver.process_mutex);
return 0;
}
if (!strncmp(attr->attr.name, "user", 4))
val = priv->stats.user;
if (!strncmp(attr->attr.name, "user_max", 8))
val = priv->stats.user_max;
if (!strncmp(attr->attr.name, "mapped", 6))
val = priv->stats.mapped;
if (!strncmp(attr->attr.name, "mapped_max", 10))
val = priv->stats.mapped_max;
if (!strncmp(attr->attr.name, "flushes", 7))
val = priv->stats.flushes;
mutex_unlock(&kgsl_driver.process_mutex);
return snprintf(buf, PAGE_SIZE, "%u\n", val);
}
#define KGSL_MEMSTAT_ATTR(_name, _show) \
static struct kobj_attribute attr_##_name = \
__ATTR(_name, 0444, _show, NULL)
KGSL_MEMSTAT_ATTR(user, process_show);
KGSL_MEMSTAT_ATTR(user_max, process_show);
KGSL_MEMSTAT_ATTR(mapped, process_show);
KGSL_MEMSTAT_ATTR(mapped_max, process_show);
KGSL_MEMSTAT_ATTR(flushes, process_show);
static struct attribute *process_attrs[] = {
&attr_user.attr,
&attr_user_max.attr,
&attr_mapped.attr,
&attr_mapped_max.attr,
&attr_flushes.attr,
NULL
};
static struct attribute_group process_attr_group = {
.attrs = process_attrs,
};
void
kgsl_process_uninit_sysfs(struct kgsl_process_private *private)
{
/* Remove the sysfs entry */
if (private->kobj) {
sysfs_remove_group(private->kobj, &process_attr_group);
kobject_put(private->kobj);
}
}
void
kgsl_process_init_sysfs(struct kgsl_process_private *private)
{
unsigned char name[16];
/* Add a entry to the sysfs device */
snprintf(name, sizeof(name), "%d", private->pid);
private->kobj = kobject_create_and_add(name, kgsl_driver.prockobj);
/* sysfs failure isn't fatal, just annoying */
if (private->kobj != NULL) {
if (sysfs_create_group(private->kobj, &process_attr_group)) {
kobject_put(private->kobj);
private->kobj = NULL;
}
}
}
static int kgsl_drv_memstat_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
unsigned int val = 0;
if (!strncmp(attr->attr.name, "vmalloc", 7))
val = kgsl_driver.stats.vmalloc;
else if (!strncmp(attr->attr.name, "vmalloc_max", 11))
val = kgsl_driver.stats.vmalloc_max;
else if (!strncmp(attr->attr.name, "coherent", 8))
val = kgsl_driver.stats.coherent;
else if (!strncmp(attr->attr.name, "coherent_max", 12))
val = kgsl_driver.stats.coherent_max;
else if (!strncmp(attr->attr.name, "mapped", 6))
val = kgsl_driver.stats.mapped;
else if (!strncmp(attr->attr.name, "mapped_max", 10))
val = kgsl_driver.stats.mapped_max;
return snprintf(buf, PAGE_SIZE, "%u\n", val);
}
static int kgsl_drv_histogram_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int len = 0;
int i;
for (i = 0; i < 16; i++)
len += snprintf(buf + len, PAGE_SIZE - len, "%d ",
kgsl_driver.stats.histogram[i]);
len += snprintf(buf + len, PAGE_SIZE - len, "\n");
return len;
}
DEVICE_ATTR(vmalloc, 0444, kgsl_drv_memstat_show, NULL);
DEVICE_ATTR(vmalloc_max, 0444, kgsl_drv_memstat_show, NULL);
DEVICE_ATTR(coherent, 0444, kgsl_drv_memstat_show, NULL);
DEVICE_ATTR(coherent_max, 0444, kgsl_drv_memstat_show, NULL);
DEVICE_ATTR(mapped, 0444, kgsl_drv_memstat_show, NULL);
DEVICE_ATTR(mapped_max, 0444, kgsl_drv_memstat_show, NULL);
DEVICE_ATTR(histogram, 0444, kgsl_drv_histogram_show, NULL);
static const struct device_attribute *drv_attr_list[] = {
&dev_attr_vmalloc,
&dev_attr_vmalloc_max,
&dev_attr_coherent,
&dev_attr_coherent_max,
&dev_attr_mapped,
&dev_attr_mapped_max,
&dev_attr_histogram,
NULL
};
void
kgsl_sharedmem_uninit_sysfs(void)
{
kgsl_remove_device_sysfs_files(&kgsl_driver.virtdev, drv_attr_list);
}
int
kgsl_sharedmem_init_sysfs(void)
{
return kgsl_create_device_sysfs_files(&kgsl_driver.virtdev,
drv_attr_list);
}
#ifdef CONFIG_OUTER_CACHE
static void _outer_cache_range_op(int op, unsigned long addr, size_t size)
{
switch (op) {
case KGSL_CACHE_OP_FLUSH:
outer_flush_range(addr, addr + size);
break;
case KGSL_CACHE_OP_CLEAN:
outer_clean_range(addr, addr + size);
break;
case KGSL_CACHE_OP_INV:
outer_inv_range(addr, addr + size);
break;
}
}
#endif
static unsigned long kgsl_vmalloc_physaddr(struct kgsl_memdesc *memdesc,
unsigned int offset)
{
unsigned int addr;
if (offset > memdesc->size)
return 0;
addr = vmalloc_to_pfn(memdesc->hostptr + offset);
return addr << PAGE_SHIFT;
}
#ifdef CONFIG_OUTER_CACHE
static void kgsl_vmalloc_outer_cache(struct kgsl_memdesc *memdesc, int op)
{
void *vaddr = memdesc->hostptr;
for (; vaddr < (memdesc->hostptr + memdesc->size); vaddr += PAGE_SIZE) {
unsigned long paddr = page_to_phys(vmalloc_to_page(vaddr));
_outer_cache_range_op(op, paddr, PAGE_SIZE);
}
}
#endif
static int kgsl_vmalloc_vmfault(struct kgsl_memdesc *memdesc,
struct vm_area_struct *vma,
struct vm_fault *vmf)
{
unsigned long offset, pg;
struct page *page;
offset = (unsigned long) vmf->virtual_address - vma->vm_start;
pg = (unsigned long) memdesc->hostptr + offset;
page = vmalloc_to_page((void *) pg);
if (page == NULL)
return VM_FAULT_SIGBUS;
get_page(page);
vmf->page = page;
return 0;
}
static int kgsl_vmalloc_vmflags(struct kgsl_memdesc *memdesc)
{
return VM_RESERVED | VM_DONTEXPAND;
}
static void kgsl_vmalloc_free(struct kgsl_memdesc *memdesc)
{
kgsl_driver.stats.vmalloc -= memdesc->size;
vfree(memdesc->hostptr);
}
static int kgsl_contiguous_vmflags(struct kgsl_memdesc *memdesc)
{
return VM_RESERVED | VM_IO | VM_PFNMAP | VM_DONTEXPAND;
}
static int kgsl_contiguous_vmfault(struct kgsl_memdesc *memdesc,
struct vm_area_struct *vma,
struct vm_fault *vmf)
{
unsigned long offset, pfn;
int ret;
offset = ((unsigned long) vmf->virtual_address - vma->vm_start) >>
PAGE_SHIFT;
pfn = (memdesc->physaddr >> PAGE_SHIFT) + offset;
ret = vm_insert_pfn(vma, (unsigned long) vmf->virtual_address, pfn);
if (ret == -ENOMEM || ret == -EAGAIN)
return VM_FAULT_OOM;
else if (ret == -EFAULT)
return VM_FAULT_SIGBUS;
return VM_FAULT_NOPAGE;
}
static void kgsl_ebimem_free(struct kgsl_memdesc *memdesc)
{
kgsl_driver.stats.coherent -= memdesc->size;
if (memdesc->hostptr)
iounmap(memdesc->hostptr);
free_contiguous_memory_by_paddr(memdesc->physaddr);
}
static void kgsl_coherent_free(struct kgsl_memdesc *memdesc)
{
kgsl_driver.stats.coherent -= memdesc->size;
dma_free_coherent(NULL, memdesc->size,
memdesc->hostptr, memdesc->physaddr);
}
static unsigned long kgsl_contiguous_physaddr(struct kgsl_memdesc *memdesc,
unsigned int offset)
{
if (offset > memdesc->size)
return 0;
return memdesc->physaddr + offset;
}
#ifdef CONFIG_OUTER_CACHE
static void kgsl_contiguous_outer_cache(struct kgsl_memdesc *memdesc, int op)
{
_outer_cache_range_op(op, memdesc->physaddr, memdesc->size);
}
#endif
#ifdef CONFIG_OUTER_CACHE
static void kgsl_userptr_outer_cache(struct kgsl_memdesc *memdesc, int op)
{
void *vaddr = memdesc->hostptr;
for (; vaddr < (memdesc->hostptr + memdesc->size); vaddr += PAGE_SIZE) {
unsigned long paddr = kgsl_virtaddr_to_physaddr(vaddr);
if (paddr)
_outer_cache_range_op(op, paddr, PAGE_SIZE);
}
}
#endif
static unsigned long kgsl_userptr_physaddr(struct kgsl_memdesc *memdesc,
unsigned int offset)
{
return kgsl_virtaddr_to_physaddr(memdesc->hostptr + offset);
}
/* Global - also used by kgsl_drm.c */
struct kgsl_memdesc_ops kgsl_vmalloc_ops = {
.physaddr = kgsl_vmalloc_physaddr,
.free = kgsl_vmalloc_free,
.vmflags = kgsl_vmalloc_vmflags,
.vmfault = kgsl_vmalloc_vmfault,
#ifdef CONFIG_OUTER_CACHE
.outer_cache = kgsl_vmalloc_outer_cache,
#endif
};
EXPORT_SYMBOL(kgsl_vmalloc_ops);
static struct kgsl_memdesc_ops kgsl_ebimem_ops = {
.physaddr = kgsl_contiguous_physaddr,
.free = kgsl_ebimem_free,
.vmflags = kgsl_contiguous_vmflags,
.vmfault = kgsl_contiguous_vmfault,
#ifdef CONFIG_OUTER_CACHE
.outer_cache = kgsl_contiguous_outer_cache,
#endif
};
static struct kgsl_memdesc_ops kgsl_coherent_ops = {
.physaddr = kgsl_contiguous_physaddr,
.free = kgsl_coherent_free,
#ifdef CONFIG_OUTER_CACHE
.outer_cache = kgsl_contiguous_outer_cache,
#endif
};
/* Global - also used by kgsl.c and kgsl_drm.c */
struct kgsl_memdesc_ops kgsl_contiguous_ops = {
.physaddr = kgsl_contiguous_physaddr,
#ifdef CONFIG_OUTER_CACHE
.outer_cache = kgsl_contiguous_outer_cache
#endif
};
EXPORT_SYMBOL(kgsl_contiguous_ops);
/* Global - also used by kgsl.c */
struct kgsl_memdesc_ops kgsl_userptr_ops = {
.physaddr = kgsl_userptr_physaddr,
#ifdef CONFIG_OUTER_CACHE
.outer_cache = kgsl_userptr_outer_cache,
#endif
};
EXPORT_SYMBOL(kgsl_userptr_ops);
void kgsl_cache_range_op(struct kgsl_memdesc *memdesc, int op)
{
void *addr = memdesc->hostptr;
int size = memdesc->size;
switch (op) {
case KGSL_CACHE_OP_FLUSH:
dmac_flush_range(addr, addr + size);
break;
case KGSL_CACHE_OP_CLEAN:
dmac_clean_range(addr, addr + size);
break;
case KGSL_CACHE_OP_INV:
dmac_inv_range(addr, addr + size);
break;
}
if (memdesc->ops->outer_cache)
memdesc->ops->outer_cache(memdesc, op);
}
EXPORT_SYMBOL(kgsl_cache_range_op);
static int
_kgsl_sharedmem_vmalloc(struct kgsl_memdesc *memdesc,
struct kgsl_pagetable *pagetable,
void *ptr, size_t size, unsigned int protflags)
{
int result;
memdesc->size = size;
memdesc->pagetable = pagetable;
memdesc->priv = KGSL_MEMFLAGS_CACHED;
memdesc->ops = &kgsl_vmalloc_ops;
memdesc->hostptr = (void *) ptr;
kgsl_cache_range_op(memdesc, KGSL_CACHE_OP_INV);
result = kgsl_mmu_map(pagetable, memdesc, protflags);
if (result) {
kgsl_sharedmem_free(memdesc);
} else {
int order;
KGSL_STATS_ADD(size, kgsl_driver.stats.vmalloc,
kgsl_driver.stats.vmalloc_max);
order = get_order(size);
if (order < 16)
kgsl_driver.stats.histogram[order]++;
}
return result;
}
int
kgsl_sharedmem_vmalloc(struct kgsl_memdesc *memdesc,
struct kgsl_pagetable *pagetable, size_t size)
{
void *ptr;
BUG_ON(size == 0);
size = ALIGN(size, PAGE_SIZE * 2);
ptr = vmalloc(size);
if (ptr == NULL) {
KGSL_CORE_ERR("vmalloc(%d) failed\n", size);
return -ENOMEM;
}
return _kgsl_sharedmem_vmalloc(memdesc, pagetable, ptr, size,
GSL_PT_PAGE_RV | GSL_PT_PAGE_WV);
}
EXPORT_SYMBOL(kgsl_sharedmem_vmalloc);
int
kgsl_sharedmem_vmalloc_user(struct kgsl_memdesc *memdesc,
struct kgsl_pagetable *pagetable,
size_t size, int flags)
{
void *ptr;
unsigned int protflags;
BUG_ON(size == 0);
ptr = vmalloc_user(size);
if (ptr == NULL) {
KGSL_CORE_ERR("vmalloc_user(%d) failed: allocated=%d\n",
size, kgsl_driver.stats.vmalloc);
return -ENOMEM;
}
protflags = GSL_PT_PAGE_RV;
if (!(flags & KGSL_MEMFLAGS_GPUREADONLY))
protflags |= GSL_PT_PAGE_WV;
return _kgsl_sharedmem_vmalloc(memdesc, pagetable, ptr, size,
protflags);
}
EXPORT_SYMBOL(kgsl_sharedmem_vmalloc_user);
int
kgsl_sharedmem_alloc_coherent(struct kgsl_memdesc *memdesc, size_t size)
{
size = ALIGN(size, PAGE_SIZE);
memdesc->hostptr = dma_alloc_coherent(NULL, size, &memdesc->physaddr,
GFP_KERNEL);
if (memdesc->hostptr == NULL) {
KGSL_CORE_ERR("dma_alloc_coherent(%d) failed\n", size);
return -ENOMEM;
}
memdesc->size = size;
memdesc->ops = &kgsl_coherent_ops;
/* Record statistics */
KGSL_STATS_ADD(size, kgsl_driver.stats.coherent,
kgsl_driver.stats.coherent_max);
return 0;
}
EXPORT_SYMBOL(kgsl_sharedmem_alloc_coherent);
void kgsl_sharedmem_free(struct kgsl_memdesc *memdesc)
{
if (memdesc == NULL || memdesc->size == 0)
return;
if (memdesc->gpuaddr)
kgsl_mmu_unmap(memdesc->pagetable, memdesc);
if (memdesc->ops->free)
memdesc->ops->free(memdesc);
memset(memdesc, 0, sizeof(*memdesc));
}
EXPORT_SYMBOL(kgsl_sharedmem_free);
static int
_kgsl_sharedmem_ebimem(struct kgsl_memdesc *memdesc,
struct kgsl_pagetable *pagetable, size_t size)
{
int result;
memdesc->physaddr = allocate_contiguous_ebi_nomap(size, SZ_8K);
if (memdesc->physaddr == 0) {
KGSL_CORE_ERR("allocate_contiguous_ebi_nomap(%d) failed\n",
size);
return -ENOMEM;
}
memdesc->size = size;
memdesc->pagetable = pagetable;
memdesc->ops = &kgsl_ebimem_ops;
result = kgsl_mmu_map(pagetable, memdesc,
GSL_PT_PAGE_RV | GSL_PT_PAGE_WV);
if (result)
kgsl_sharedmem_free(memdesc);
KGSL_STATS_ADD(size, kgsl_driver.stats.coherent,
kgsl_driver.stats.coherent_max);
return result;
}
int
kgsl_sharedmem_ebimem_user(struct kgsl_memdesc *memdesc,
struct kgsl_pagetable *pagetable,
size_t size, int flags)
{
size = ALIGN(size, PAGE_SIZE);
return _kgsl_sharedmem_ebimem(memdesc, pagetable, size);
}
EXPORT_SYMBOL(kgsl_sharedmem_ebimem_user);
int
kgsl_sharedmem_ebimem(struct kgsl_memdesc *memdesc,
struct kgsl_pagetable *pagetable, size_t size)
{
int result;
size = ALIGN(size, 8192);
result = _kgsl_sharedmem_ebimem(memdesc, pagetable, size);
if (result)
return result;
memdesc->hostptr = ioremap(memdesc->physaddr, size);
if (memdesc->hostptr == NULL) {
KGSL_CORE_ERR("ioremap failed\n");
kgsl_sharedmem_free(memdesc);
return -ENOMEM;
}
return 0;
}
EXPORT_SYMBOL(kgsl_sharedmem_ebimem);
int
kgsl_sharedmem_readl(const struct kgsl_memdesc *memdesc,
uint32_t *dst,
unsigned int offsetbytes)
{
BUG_ON(memdesc == NULL || memdesc->hostptr == NULL || dst == NULL);
WARN_ON(offsetbytes + sizeof(unsigned int) > memdesc->size);
if (offsetbytes + sizeof(unsigned int) > memdesc->size)
return -ERANGE;
*dst = readl_relaxed(memdesc->hostptr + offsetbytes);
return 0;
}
EXPORT_SYMBOL(kgsl_sharedmem_readl);
int
kgsl_sharedmem_writel(const struct kgsl_memdesc *memdesc,
unsigned int offsetbytes,
uint32_t src)
{
BUG_ON(memdesc == NULL || memdesc->hostptr == NULL);
BUG_ON(offsetbytes + sizeof(unsigned int) > memdesc->size);
kgsl_cffdump_setmem(memdesc->physaddr + offsetbytes,
src, sizeof(uint));
writel_relaxed(src, memdesc->hostptr + offsetbytes);
return 0;
}
EXPORT_SYMBOL(kgsl_sharedmem_writel);
int
kgsl_sharedmem_set(const struct kgsl_memdesc *memdesc, unsigned int offsetbytes,
unsigned int value, unsigned int sizebytes)
{
BUG_ON(memdesc == NULL || memdesc->hostptr == NULL);
BUG_ON(offsetbytes + sizebytes > memdesc->size);
kgsl_cffdump_setmem(memdesc->physaddr + offsetbytes, value,
sizebytes);
memset(memdesc->hostptr + offsetbytes, value, sizebytes);
return 0;
}
EXPORT_SYMBOL(kgsl_sharedmem_set);
|
shaumux/semc-kernel-qsd8k-jb
|
drivers/gpu/msm/kgsl_sharedmem.c
|
C
|
gpl-2.0
| 15,617 |
/* aide, Advanced Intrusion Detection Environment
*
* Copyright (C) 1999-2006 Rami Lehti, Pablo Virolainen, Mike
* Markley, Richard van den Berg
* $Header$
*
* 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 "aide.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifdef HAVE_SYSLOG
#include <syslog.h>
#endif
#include "report.h"
#include "list.h"
#include "be.h"
/*for locale support*/
#include "locale-aide.h"
/*for locale support*/
#include "util.h"
int cmp_url(url_t* url1,url_t* url2){
return ((url1->type==url2->type)&&(strcmp(url1->value,url2->value)==0));
}
int error_init(url_t* url,int initial)
{
list* r=NULL;
FILE* fh=NULL;
int sfac;
if (url->type==url_database) {
conf->report_db++;
return RETOK;
}
if(initial==1){
if (url->type==url_syslog) {
conf->report_syslog++;
#ifdef HAVE_SYSLOG
conf->initial_report_url=url;
conf->initial_report_fd=NULL;
sfac=syslog_facility_lookup(url->value);
openlog(AIDE_IDENT,AIDE_LOGOPT, sfac);
return RETOK;
#endif
#ifndef HAVE_SYSLOG
error(0,_("This binary has no syslog support\n"));
exit(INVALID_ARGUMENT_ERROR);
#endif
}
fh=be_init(0,url,0);
if(fh!=NULL){
conf->initial_report_fd=fh;
conf->initial_report_url=url;
return RETOK;
}
error(0,_("Cannot open %s for writing\n"),url->value);
exit(INVALID_ARGUMENT_ERROR);
}
if(conf->verbose_level>=200){
error(5,_("WARNING: Debug output enabled\n"));
}
for(r=conf->report_url;r;r=r->next){
if (cmp_url((url_t*)r->data,url)) {
error(5,_("WARNING: Already have report output %s\n"),url->value);
return RETOK;
}
}
if (url->type==url_syslog) {
conf->report_syslog++;
#ifdef HAVE_SYSLOG
/* If you add support for facility changing in config
consider multiple calls of openlog.
This openlog MUST NOT mess up initial errorsto openlog.
RvdB 22/1/2006: the 2 openlog calls where the same before my
change, and they are still the same, I assume I did not brake anything
*/
sfac=syslog_facility_lookup(url->value);
if(conf->report_syslog<2)
openlog(AIDE_IDENT,AIDE_LOGOPT, sfac);
return RETOK;
#endif
#ifndef HAVE_SYSLOG
error(0,_("This binary has no syslog support\n"));
return RETFAIL;
#endif
}
fh=be_init(0,url,0);
if(fh!=NULL) {
conf->report_fd=list_append(conf->report_fd,(void*)fh);
conf->report_url=list_append(conf->report_url,(void*)url);
return RETOK;
}
error(0,_("Cannot open %s for writing\n"),url->value);
return RETFAIL;
}
void error(int errorlevel,char* error_msg,...)
{
va_list ap;
int retval=0;
list* r=NULL;
if(conf->verbose_level==-1){
if(5<errorlevel){
return;
}
}else{
if(conf->verbose_level<errorlevel){
return;
}
}
if(conf->use_initial_errorsto){
/* We are still using the initial errorsto */
va_start(ap, error_msg);
if(conf->initial_report_url==NULL){
/* Error called before error_init(url,1)
This most likely means that parsing compiled in initial
report url failed.
*/
vfprintf(stderr,error_msg,ap);
va_end(ap);
fprintf(stderr,
"Initial report url broken. Reconfigure and recompile.\n");
exit(INVALID_ARGUMENT_ERROR);
}
#ifdef HAVE_SYSLOG
if(conf->initial_report_url->type==url_syslog){
#ifdef HAVE_VSYSLOG
vsyslog(SYSLOG_PRIORITY,error_msg,ap);
#else
char buf[1024];
vsnprintf(buf,1024,error_msg,ap);
syslog(SYSLOG_PRIORITY,"%s",buf);
#endif
va_end(ap);
return;
}
#endif
vfprintf(conf->initial_report_fd,error_msg,ap);
va_end(ap);
return;
}
#ifdef HAVE_SYSLOG
if (conf->report_syslog!=0) {
#ifdef HAVE_VSYSLOG
va_start(ap,error_msg);
vsyslog(SYSLOG_PRIORITY,error_msg,ap);
va_end(ap);
#else
char buf[1024];
va_start(ap,error_msg);
vsnprintf(buf,1024,error_msg,ap);
va_end(ap);
syslog(SYSLOG_PRIORITY,"%s",buf);
#endif
}
#endif
#ifdef WITH_DBERROR
if (conf->report_db!=0 && ( conf->db_out!=NULL
#ifdef WITH_ZLIB
|| conf->db_gzout
#endif
)) {
db_line line;
int len;
memset(&line,0,sizeof(db_line));
line.filename=(char*)malloc(3);
if (line.filename!=NULL) {
va_start(ap,error_msg);
len=vsnprintf(line.filename,2,error_msg,ap);
va_end(ap);
free(line.filename);
line.filename=malloc(len+2);
line.filename[0]='#';
if (line.filename!=NULL) {
line.attr=DB_FILENAME;
va_start(ap,error_msg);
len=vsnprintf(line.filename+1,len+1,error_msg,ap);
va_end(ap);
db_writeline(&line,conf);
free(line.filename);
}
}
}
#endif
for(r=conf->report_fd;r;r=r->next){
va_start(ap, error_msg);
retval=vfprintf((FILE*)r->data, error_msg,ap);
va_end(ap);
if(retval==0){
va_start(ap, error_msg);
retval=vfprintf((FILE*)r->data, error_msg,ap);
va_end(ap);
if(retval==0){
exit(ERROR_WRITING_ERROR);
}
}
}
return;
}
const char* aide_key_0=CONFHMACKEY_00;
const char* db_key_0=DBHMACKEY_00;
|
po1vo/aide
|
src/error.c
|
C
|
gpl-2.0
| 5,854 |
namespace KeePass.Forms
{
partial class IconPickerForm
{
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.m_lvIcons = new KeePass.UI.CustomListViewEx();
this.m_btnOK = new System.Windows.Forms.Button();
this.m_lvCustomIcons = new KeePass.UI.CustomListViewEx();
this.m_radioStandard = new System.Windows.Forms.RadioButton();
this.m_radioCustom = new System.Windows.Forms.RadioButton();
this.m_lblSeparator = new System.Windows.Forms.Label();
this.m_btnCustomAdd = new System.Windows.Forms.Button();
this.m_btnCustomRemove = new System.Windows.Forms.Button();
this.m_btnCustomExport = new System.Windows.Forms.Button();
this.m_btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// m_lvIcons
//
this.m_lvIcons.HideSelection = false;
this.m_lvIcons.Location = new System.Drawing.Point(32, 35);
this.m_lvIcons.MultiSelect = false;
this.m_lvIcons.Name = "m_lvIcons";
this.m_lvIcons.Size = new System.Drawing.Size(462, 197);
this.m_lvIcons.TabIndex = 3;
this.m_lvIcons.UseCompatibleStateImageBehavior = false;
this.m_lvIcons.View = System.Windows.Forms.View.List;
this.m_lvIcons.ItemActivate += new System.EventHandler(this.OnIconsItemActivate);
this.m_lvIcons.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.OnIconsItemSelectionChanged);
//
// m_btnOK
//
this.m_btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.m_btnOK.Location = new System.Drawing.Point(338, 414);
this.m_btnOK.Name = "m_btnOK";
this.m_btnOK.Size = new System.Drawing.Size(75, 23);
this.m_btnOK.TabIndex = 0;
this.m_btnOK.Text = "OK";
this.m_btnOK.UseVisualStyleBackColor = true;
this.m_btnOK.Click += new System.EventHandler(this.OnBtnOK);
//
// m_lvCustomIcons
//
this.m_lvCustomIcons.HideSelection = false;
this.m_lvCustomIcons.Location = new System.Drawing.Point(32, 271);
this.m_lvCustomIcons.Name = "m_lvCustomIcons";
this.m_lvCustomIcons.Size = new System.Drawing.Size(381, 121);
this.m_lvCustomIcons.TabIndex = 5;
this.m_lvCustomIcons.UseCompatibleStateImageBehavior = false;
this.m_lvCustomIcons.View = System.Windows.Forms.View.List;
this.m_lvCustomIcons.ItemActivate += new System.EventHandler(this.OnCustomIconsItemActivate);
this.m_lvCustomIcons.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.OnCustomIconsItemSelectionChanged);
//
// m_radioStandard
//
this.m_radioStandard.AutoSize = true;
this.m_radioStandard.Location = new System.Drawing.Point(12, 12);
this.m_radioStandard.Name = "m_radioStandard";
this.m_radioStandard.Size = new System.Drawing.Size(114, 17);
this.m_radioStandard.TabIndex = 2;
this.m_radioStandard.TabStop = true;
this.m_radioStandard.Text = "Use standard icon:";
this.m_radioStandard.UseVisualStyleBackColor = true;
this.m_radioStandard.CheckedChanged += new System.EventHandler(this.OnStandardRadioCheckedChanged);
//
// m_radioCustom
//
this.m_radioCustom.AutoSize = true;
this.m_radioCustom.Location = new System.Drawing.Point(12, 248);
this.m_radioCustom.Name = "m_radioCustom";
this.m_radioCustom.Size = new System.Drawing.Size(278, 17);
this.m_radioCustom.TabIndex = 4;
this.m_radioCustom.TabStop = true;
this.m_radioCustom.Text = "Use custom icon (embedded in the current database):";
this.m_radioCustom.UseVisualStyleBackColor = true;
//
// m_lblSeparator
//
this.m_lblSeparator.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.m_lblSeparator.Location = new System.Drawing.Point(-1, 407);
this.m_lblSeparator.Name = "m_lblSeparator";
this.m_lblSeparator.Size = new System.Drawing.Size(507, 2);
this.m_lblSeparator.TabIndex = 9;
//
// m_btnCustomAdd
//
this.m_btnCustomAdd.Location = new System.Drawing.Point(419, 270);
this.m_btnCustomAdd.Name = "m_btnCustomAdd";
this.m_btnCustomAdd.Size = new System.Drawing.Size(75, 23);
this.m_btnCustomAdd.TabIndex = 6;
this.m_btnCustomAdd.Text = "&Add...";
this.m_btnCustomAdd.UseVisualStyleBackColor = true;
this.m_btnCustomAdd.Click += new System.EventHandler(this.OnBtnCustomAdd);
//
// m_btnCustomRemove
//
this.m_btnCustomRemove.Location = new System.Drawing.Point(419, 299);
this.m_btnCustomRemove.Name = "m_btnCustomRemove";
this.m_btnCustomRemove.Size = new System.Drawing.Size(75, 23);
this.m_btnCustomRemove.TabIndex = 7;
this.m_btnCustomRemove.Text = "&Remove";
this.m_btnCustomRemove.UseVisualStyleBackColor = true;
this.m_btnCustomRemove.Click += new System.EventHandler(this.OnBtnCustomRemove);
//
// m_btnCustomExport
//
this.m_btnCustomExport.Location = new System.Drawing.Point(419, 370);
this.m_btnCustomExport.Name = "m_btnCustomExport";
this.m_btnCustomExport.Size = new System.Drawing.Size(75, 23);
this.m_btnCustomExport.TabIndex = 8;
this.m_btnCustomExport.Text = "E&xport...";
this.m_btnCustomExport.UseVisualStyleBackColor = true;
this.m_btnCustomExport.Click += new System.EventHandler(this.OnBtnCustomSave);
//
// m_btnCancel
//
this.m_btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.m_btnCancel.Location = new System.Drawing.Point(419, 414);
this.m_btnCancel.Name = "m_btnCancel";
this.m_btnCancel.Size = new System.Drawing.Size(75, 23);
this.m_btnCancel.TabIndex = 1;
this.m_btnCancel.Text = "Cancel";
this.m_btnCancel.UseVisualStyleBackColor = true;
//
// IconPickerForm
//
this.AcceptButton = this.m_btnOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.m_btnCancel;
this.ClientSize = new System.Drawing.Size(506, 449);
this.Controls.Add(this.m_btnCancel);
this.Controls.Add(this.m_btnCustomExport);
this.Controls.Add(this.m_btnCustomRemove);
this.Controls.Add(this.m_btnCustomAdd);
this.Controls.Add(this.m_lblSeparator);
this.Controls.Add(this.m_radioCustom);
this.Controls.Add(this.m_radioStandard);
this.Controls.Add(this.m_lvCustomIcons);
this.Controls.Add(this.m_btnOK);
this.Controls.Add(this.m_lvIcons);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "IconPickerForm";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Icon Picker";
this.Load += new System.EventHandler(this.OnFormLoad);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.OnFormClosed);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private KeePass.UI.CustomListViewEx m_lvIcons;
private System.Windows.Forms.Button m_btnOK;
private KeePass.UI.CustomListViewEx m_lvCustomIcons;
private System.Windows.Forms.RadioButton m_radioStandard;
private System.Windows.Forms.RadioButton m_radioCustom;
private System.Windows.Forms.Label m_lblSeparator;
private System.Windows.Forms.Button m_btnCustomAdd;
private System.Windows.Forms.Button m_btnCustomRemove;
private System.Windows.Forms.Button m_btnCustomExport;
private System.Windows.Forms.Button m_btnCancel;
}
}
|
haro-freezd/KeePass
|
KeePass/Forms/IconPickerForm.Designer.cs
|
C#
|
gpl-2.0
| 8,141 |
/******************************************************************************
*
* Copyright(c) 2013 Realtek Corporation. 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.
*
* 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, USA
*
*
******************************************************************************/
/*
* Description:
* This file can be applied to following platforms:
* CONFIG_PLATFORM_ARM_SUNXI Series platform
*
*/
#include <drv_types.h>
#include <mach/sys_config.h>
#ifdef CONFIG_PLATFORM_ARM_SUNxI
extern int sw_usb_disable_hcd(__u32 usbc_no);
extern int sw_usb_enable_hcd(__u32 usbc_no);
static int usb_wifi_host = 2;
#endif
#if defined(CONFIG_PLATFORM_ARM_SUN6I) || defined(CONFIG_PLATFORM_ARM_SUN7I)
extern int sw_usb_disable_hcd(__u32 usbc_no);
extern int sw_usb_enable_hcd(__u32 usbc_no);
extern void wifi_pm_power(int on);
static script_item_u item;
#endif
#ifdef CONFIG_PLATFORM_ARM_SUN8I
extern int sunxi_usb_disable_hcd(__u32 usbc_no);
extern int sunxi_usb_enable_hcd(__u32 usbc_no);
extern void wifi_pm_power(int on);
static script_item_u item;
#endif
int platform_wifi_power_on(void)
{
int ret = 0;
#ifdef CONFIG_PLATFORM_ARM_SUNxI
#ifndef CONFIG_RTL8723A
{
/* ----------get usb_wifi_usbc_num------------- */
ret = script_parser_fetch("usb_wifi_para", "usb_wifi_usbc_num", (int *)&usb_wifi_host, 64);
if(ret != 0){
DBG_8192C("ERR: script_parser_fetch usb_wifi_usbc_num failed\n");
ret = -ENOMEM;
goto exit;
}
DBG_8192C("sw_usb_enable_hcd: usbc_num = %d\n", usb_wifi_host);
sw_usb_enable_hcd(usb_wifi_host);
}
#endif //CONFIG_RTL8723A
#endif //CONFIG_PLATFORM_ARM_SUNxI
#if defined(CONFIG_PLATFORM_ARM_SUN6I) || defined(CONFIG_PLATFORM_ARM_SUN7I)
{
script_item_value_type_e type;
type = script_get_item("wifi_para", "wifi_usbc_id", &item);
if(SCIRPT_ITEM_VALUE_TYPE_INT != type){
printk("ERR: script_get_item wifi_usbc_id failed\n");
ret = -ENOMEM;
goto exit;
}
printk("sw_usb_enable_hcd: usbc_num = %d\n", item.val);
wifi_pm_power(1);
mdelay(10);
#if !(defined(CONFIG_RTL8723A)) && !(defined(CONFIG_RTL8723B))
sw_usb_enable_hcd(item.val);
#endif
}
#endif //defined(CONFIG_PLATFORM_ARM_SUN6I) || defined(CONFIG_PLATFORM_ARM_SUN7I)
#if defined(CONFIG_PLATFORM_ARM_SUN8I)
{
script_item_value_type_e type;
type = script_get_item("wifi_para", "wifi_usbc_id", &item);
if(SCIRPT_ITEM_VALUE_TYPE_INT != type){
printk("ERR: script_get_item wifi_usbc_id failed\n");
ret = -ENOMEM;
goto exit;
}
printk("sw_usb_enable_hcd: usbc_num = %d\n", item.val);
#if defined(CONFIG_ARCH_SUN8IW7P1)
printk(KERN_ERR "notice: set wl_reg_on 0 to power on 8188eu in sun8iw7p1!\n");
wifi_pm_power(0);
#else
wifi_pm_power(1);
#endif //defined(CONFIG_ARCH_SUN8IW7P1)
mdelay(10);
#if !(defined(CONFIG_RTL8723A)) && !(defined(CONFIG_RTL8723B))
sunxi_usb_enable_hcd(item.val);
#endif
}
#endif //CONFIG_PLATFORM_ARM_SUN8I
exit:
return ret;
}
void platform_wifi_power_off(void)
{
#ifdef CONFIG_PLATFORM_ARM_SUNxI
#ifndef CONFIG_RTL8723A
DBG_8192C("sw_usb_disable_hcd: usbc_num = %d\n", usb_wifi_host);
sw_usb_disable_hcd(usb_wifi_host);
#endif //ifndef CONFIG_RTL8723A
#endif //CONFIG_PLATFORM_ARM_SUNxI
#if defined(CONFIG_PLATFORM_ARM_SUN6I) || defined(CONFIG_PLATFORM_ARM_SUN7I)
#if !(defined(CONFIG_RTL8723A)) && !(defined(CONFIG_RTL8723B))
sw_usb_disable_hcd(item.val);
#endif
wifi_pm_power(0);
#endif //defined(CONFIG_PLATFORM_ARM_SUN6I) || defined(CONFIG_PLATFORM_ARM_SUN7I)
#if defined(CONFIG_PLATFORM_ARM_SUN8I)
#if !(defined(CONFIG_RTL8723A)) && !(defined(CONFIG_RTL8723B))
sunxi_usb_disable_hcd(item.val);
#endif
#if defined(CONFIG_ARCH_SUN8IW7P1)
printk(KERN_ERR "notice: set wl_reg_on 1 to power off 8188eu in sun8iw7p1!\n");
wifi_pm_power(1);
#else
wifi_pm_power(0);
#endif //defined(CONFIG_ARCH_SUN8IW7P1)
#endif //defined(CONFIG_PLATFORM_ARM_SUN8I)
}
|
willemwouters/orangepi_kernel
|
drivers/net/wireless/rtl8188eu/platform/platform_ARM_SUNxI_usb.c
|
C
|
gpl-2.0
| 4,467 |
( function( $, undefined ) {
"use strict";
$.fn.uirange = function() {
return this.each(function() {
this.type = 'text';
var input = $( this );
input.parent().wrap( '<div class="ui-range"></div>' );
var wrap = $( this ).closest( '.ui-range' );
var sl = wrap.append( '<div class="ui-range-slider"></div>' ).find( '.ui-range-slider' );
// an object with the definitions of our range
var range = {};
range.min = parseFloat( input.attr( "min" ), 10 );
range.max = parseFloat( input.attr( "max" ), 10 );
range.step = parseFloat( input.attr( "step" ), 10 );
if ( input.val() === '' ) {
input.val( range.min );
}
// initialize ui.slider
sl.slider( {
range: "min",
min: range.min,
max: range.max,
value: ( input.val() === '' ? range.min : parseFloat( input.val(), 10 ) ),
step: range.step || 1,
slide: function( evt, ui ) {
input.val( ui.value ).change();
},
change: function( evt, ui ) {
input.val( ui.value ).change();
}
} );
input.change( function() {
// undo the user input if it's outside the range
if ( input.val() < range.min || input.val() > range.max || input.val() === '' ) {
input.val( sl.slider( 'value' ) );
} else {
// otherwise correct the slider's position
var prev = $( this ).data( 'prev-value' );
if ( prev !== input.val() ) {
$( this ).data( 'prev-value', input.val() );
sl.slider( 'value', input.val() );
}
}
});
});
};
} )( jQuery );
|
haidenmcgrath/zoo-sport
|
wp-content/themes/fitness-wellness/vamtam/admin/assets/js/jquery.ui.range.js
|
JavaScript
|
gpl-2.0
| 1,517 |
<?php
namespace Google\AdsApi\Dfp\v201705;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class TrackingUrls
{
/**
* @var string[] $urls
*/
protected $urls = null;
/**
* @param string[] $urls
*/
public function __construct(array $urls = null)
{
$this->urls = $urls;
}
/**
* @return string[]
*/
public function getUrls()
{
return $this->urls;
}
/**
* @param string[] $urls
* @return \Google\AdsApi\Dfp\v201705\TrackingUrls
*/
public function setUrls(array $urls)
{
$this->urls = $urls;
return $this;
}
}
|
renshuki/dfp-manager
|
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201705/TrackingUrls.php
|
PHP
|
gpl-2.0
| 648 |
/*
* linux/kernel/printk.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Modified to make sys_syslog() more flexible: added commands to
* return the last 4k of kernel messages, regardless of whether
* they've been read or not. Added option to suppress kernel printk's
* to the console. Added hook for sending the console messages
* elsewhere, in preparation for a serial line console (someday).
* Ted Ts'o, 2/11/93.
* Modified for sysctl support, 1/8/97, Chris Horn.
* Fixed SMP synchronization, 08/08/99, Manfred Spraul
* [email protected]
* Rewrote bits to get rid of console_lock
* 01Mar01 Andrew Morton
*/
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/nmi.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/interrupt.h> /* For in_interrupt() */
#include <linux/delay.h>
#include <linux/smp.h>
#include <linux/security.h>
#include <linux/bootmem.h>
#include <linux/memblock.h>
#include <linux/aio.h>
#include <linux/syscalls.h>
#include <linux/kexec.h>
#include <linux/kdb.h>
#include <linux/ratelimit.h>
#include <linux/kmsg_dump.h>
#include <linux/syslog.h>
#include <linux/cpu.h>
#include <linux/notifier.h>
#include <linux/rculist.h>
#include <linux/poll.h>
#include <linux/irq_work.h>
#include <linux/utsname.h>
#include <asm/uaccess.h>
#define CREATE_TRACE_POINTS
#include <trace/events/printk.h>
#ifdef CONFIG_EARLY_PRINTK_DIRECT
extern void printascii(char *);
#endif
/* printk's without a loglevel use this.. */
#define DEFAULT_MESSAGE_LOGLEVEL CONFIG_DEFAULT_MESSAGE_LOGLEVEL
/* We show everything that is MORE important than this.. */
#define MINIMUM_CONSOLE_LOGLEVEL 1 /* Minimum loglevel we let people use */
#define DEFAULT_CONSOLE_LOGLEVEL 7 /* anything MORE serious than KERN_DEBUG */
int console_printk[4] = {
DEFAULT_CONSOLE_LOGLEVEL, /* console_loglevel */
DEFAULT_MESSAGE_LOGLEVEL, /* default_message_loglevel */
MINIMUM_CONSOLE_LOGLEVEL, /* minimum_console_loglevel */
DEFAULT_CONSOLE_LOGLEVEL, /* default_console_loglevel */
};
/*
* Low level drivers may need that to know if they can schedule in
* their unblank() callback or not. So let's export it.
*/
int oops_in_progress;
EXPORT_SYMBOL(oops_in_progress);
/*
* console_sem protects the console_drivers list, and also
* provides serialisation for access to the entire console
* driver system.
*/
static DEFINE_SEMAPHORE(console_sem);
struct console *console_drivers;
EXPORT_SYMBOL_GPL(console_drivers);
#ifdef CONFIG_LOCKDEP
static struct lockdep_map console_lock_dep_map = {
.name = "console_lock"
};
#endif
/*
* This is used for debugging the mess that is the VT code by
* keeping track if we have the console semaphore held. It's
* definitely not the perfect debug tool (we don't know if _WE_
* hold it are racing, but it helps tracking those weird code
* path in the console code where we end up in places I want
* locked without the console sempahore held
*/
static int console_locked, console_suspended;
/*
* If exclusive_console is non-NULL then only this console is to be printed to.
*/
static struct console *exclusive_console;
/*
* Array of consoles built from command line options (console=)
*/
struct console_cmdline
{
char name[16]; /* Name of the driver */
int index; /* Minor dev. to use */
char *options; /* Options for the driver */
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
char *brl_options; /* Options for braille driver */
#endif
};
#define MAX_CMDLINECONSOLES 8
static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
static int selected_console = -1;
static int preferred_console = -1;
int console_set_on_cmdline;
EXPORT_SYMBOL(console_set_on_cmdline);
/* Flag: console code may call schedule() */
static int console_may_schedule;
/*
* The printk log buffer consists of a chain of concatenated variable
* length records. Every record starts with a record header, containing
* the overall length of the record.
*
* The heads to the first and last entry in the buffer, as well as the
* sequence numbers of these both entries are maintained when messages
* are stored..
*
* If the heads indicate available messages, the length in the header
* tells the start next message. A length == 0 for the next message
* indicates a wrap-around to the beginning of the buffer.
*
* Every record carries the monotonic timestamp in microseconds, as well as
* the standard userspace syslog level and syslog facility. The usual
* kernel messages use LOG_KERN; userspace-injected messages always carry
* a matching syslog facility, by default LOG_USER. The origin of every
* message can be reliably determined that way.
*
* The human readable log message directly follows the message header. The
* length of the message text is stored in the header, the stored message
* is not terminated.
*
* Optionally, a message can carry a dictionary of properties (key/value pairs),
* to provide userspace with a machine-readable message context.
*
* Examples for well-defined, commonly used property names are:
* DEVICE=b12:8 device identifier
* b12:8 block dev_t
* c127:3 char dev_t
* n8 netdev ifindex
* +sound:card0 subsystem:devname
* SUBSYSTEM=pci driver-core subsystem name
*
* Valid characters in property names are [a-zA-Z0-9.-_]. The plain text value
* follows directly after a '=' character. Every property is terminated by
* a '\0' character. The last property is not terminated.
*
* Example of a message structure:
* 0000 ff 8f 00 00 00 00 00 00 monotonic time in nsec
* 0008 34 00 record is 52 bytes long
* 000a 0b 00 text is 11 bytes long
* 000c 1f 00 dictionary is 23 bytes long
* 000e 03 00 LOG_KERN (facility) LOG_ERR (level)
* 0010 69 74 27 73 20 61 20 6c "it's a l"
* 69 6e 65 "ine"
* 001b 44 45 56 49 43 "DEVIC"
* 45 3d 62 38 3a 32 00 44 "E=b8:2\0D"
* 52 49 56 45 52 3d 62 75 "RIVER=bu"
* 67 "g"
* 0032 00 00 00 padding to next message header
*
* The 'struct log' buffer header must never be directly exported to
* userspace, it is a kernel-private implementation detail that might
* need to be changed in the future, when the requirements change.
*
* /dev/kmsg exports the structured data in the following line format:
* "level,sequnum,timestamp;<message text>\n"
*
* The optional key/value pairs are attached as continuation lines starting
* with a space character and terminated by a newline. All possible
* non-prinatable characters are escaped in the "\xff" notation.
*
* Users of the export format should ignore possible additional values
* separated by ',', and find the message after the ';' character.
*/
enum log_flags {
LOG_NOCONS = 1, /* already flushed, do not print to console */
LOG_NEWLINE = 2, /* text ended with a newline */
LOG_PREFIX = 4, /* text started with a prefix */
LOG_CONT = 8, /* text is a fragment of a continuation line */
};
struct log {
u64 ts_nsec; /* timestamp in nanoseconds */
u16 len; /* length of entire record */
u16 text_len; /* length of text buffer */
u16 dict_len; /* length of dictionary buffer */
u8 facility; /* syslog facility */
u8 flags:5; /* internal record flags */
u8 level:3; /* syslog level */
#if defined(CONFIG_LOG_BUF_MAGIC)
u32 magic; /* handle for ramdump analysis tools */
#endif
};
/*
* The logbuf_lock protects kmsg buffer, indices, counters. It is also
* used in interesting ways to provide interlocking in console_unlock();
*/
static DEFINE_RAW_SPINLOCK(logbuf_lock);
#ifdef CONFIG_PRINTK
DECLARE_WAIT_QUEUE_HEAD(log_wait);
/* the next printk record to read by syslog(READ) or /proc/kmsg */
static u64 syslog_seq;
static u32 syslog_idx;
static enum log_flags syslog_prev;
static size_t syslog_partial;
/* index and sequence number of the first record stored in the buffer */
static u64 log_first_seq;
static u32 log_first_idx;
/* index and sequence number of the next record to store in the buffer */
static u64 log_next_seq;
static u32 log_next_idx;
/* the next printk record to write to the console */
static u64 console_seq;
static u32 console_idx;
static enum log_flags console_prev;
/* the next printk record to read after the last 'clear' command */
static u64 clear_seq;
static u32 clear_idx;
#define PREFIX_MAX 32
#define LOG_LINE_MAX 1024 - PREFIX_MAX
/* record buffer */
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
#define LOG_ALIGN 4
#else
#define LOG_ALIGN __alignof__(struct log)
#endif
#define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
static char *log_buf = __log_buf;
static u32 log_buf_len = __LOG_BUF_LEN;
#if defined(CONFIG_OOPS_LOG_BUFFER)
#define __OOPS_LOG_BUF_LEN (1 << CONFIG_OOPS_LOG_BUF_SHIFT)
static char __log_oops_buf[__OOPS_LOG_BUF_LEN] __aligned(LOG_ALIGN);
static char *log_oops_buf = __log_oops_buf;
static u32 log_oops_buf_len = __OOPS_LOG_BUF_LEN;
static int log_oops_full;
/* if this sequence of log entry starts to wrap arounds, move to oops buffer */
static u64 log_oops_first_seq = ULLONG_MAX;
static u64 log_oops_last_seq;
static u32 log_oops_next_idx;
static u32 syslog_oops_buf_idx;
static const char log_oops_end[] = "---end of oops log buffer---";
#endif
#if defined(CONFIG_LOG_BUF_MAGIC)
static u32 __log_align __used = LOG_ALIGN;
#define LOG_MAGIC(msg) ((msg)->magic = 0x5d7aefca)
#else
#define LOG_MAGIC(msg)
#endif
/* cpu currently holding logbuf_lock */
static volatile unsigned int logbuf_cpu = UINT_MAX;
/* human readable text of the record */
static char *log_text(const struct log *msg)
{
return (char *)msg + sizeof(struct log);
}
/* optional key/value pair dictionary attached to the record */
static char *log_dict(const struct log *msg)
{
return (char *)msg + sizeof(struct log) + msg->text_len;
}
/* get record by index; idx must point to valid msg */
static struct log *log_from_idx(u32 idx, bool logbuf)
{
struct log *msg;
char *buf;
#if defined(CONFIG_OOPS_LOG_BUFFER)
buf = logbuf ? log_buf : log_oops_buf;
#else
buf = log_buf;
BUG_ON(!logbuf);
#endif
msg = (struct log *)(buf + idx);
/*
* A length == 0 record is the end of buffer marker. Wrap around and
* read the message at the start of the buffer.
*/
if (!msg->len)
return (struct log *)buf;
return msg;
}
/* get next record; idx must point to valid msg */
static u32 log_next(u32 idx, bool logbuf)
{
struct log *msg;
char *buf;
#if defined(CONFIG_OOPS_LOG_BUFFER)
buf = logbuf ? log_buf : log_oops_buf;
#else
buf = log_buf;
BUG_ON(!logbuf);
#endif
msg = (struct log *)(buf + idx);
/* length == 0 indicates the end of the buffer; wrap */
/*
* A length == 0 record is the end of buffer marker. Wrap around and
* read the message at the start of the buffer as *this* one, and
* return the one after that.
*/
if (!msg->len) {
msg = (struct log *)buf;
return msg->len;
}
return idx + msg->len;
}
#if defined(CONFIG_OOPS_LOG_BUFFER)
void oops_printk_start(void)
{
unsigned long flags;
raw_spin_lock_irqsave(&logbuf_lock, flags);
if (log_oops_first_seq == ULLONG_MAX)
log_oops_first_seq = log_next_seq;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
}
static void log_oops_store(struct log *msg)
{
u32 free;
const int eom_len = strlen(log_oops_end);
const size_t eom_size = sizeof(struct log) + eom_len;
char buf[eom_size + LOG_ALIGN];
u32 pad_len;
u64 ts_nsec;
int eom = 0;
if (log_first_seq >= log_oops_first_seq && !log_oops_full) {
free = log_oops_buf_len - log_oops_next_idx;
pad_len = (-eom_size) & (LOG_ALIGN - 1);
if ((free - msg->len) < (eom_size + pad_len)) {
ts_nsec = msg->ts_nsec;
msg = (struct log *)buf;
memcpy(log_text(msg), log_oops_end, eom_len);
msg->len = eom_size + pad_len;
msg->text_len = eom_len;
msg->dict_len = 0;
msg->facility = 1;
msg->level = default_message_loglevel & 7;
msg->flags = (LOG_NEWLINE | LOG_PREFIX) & 0x1f;
msg->ts_nsec = ts_nsec;
eom = 1;
}
if (free >= msg->len) {
memcpy(log_oops_buf + log_oops_next_idx, msg, msg->len);
log_oops_next_idx += msg->len;
log_oops_last_seq = log_first_seq;
if (eom)
log_oops_full = 1;
} else {
log_oops_full = 1;
}
}
}
#else
static void log_oops_store(struct log *msg)
{
}
#endif
/* insert record into the buffer, discard old ones, update heads */
static void log_store(int facility, int level,
enum log_flags flags, u64 ts_nsec,
const char *dict, u16 dict_len,
const char *text, u16 text_len)
{
struct log *msg;
u32 size, pad_len;
/* number of '\0' padding bytes to next message */
size = sizeof(struct log) + text_len + dict_len;
pad_len = (-size) & (LOG_ALIGN - 1);
size += pad_len;
while (log_first_seq < log_next_seq) {
u32 free;
if (log_next_idx > log_first_idx)
free = max(log_buf_len - log_next_idx, log_first_idx);
else
free = log_first_idx - log_next_idx;
if (free > size + sizeof(struct log))
break;
msg = (struct log *)(log_buf + log_first_idx);
log_oops_store(msg);
/* drop old messages until we have enough contiuous space */
log_first_idx = log_next(log_first_idx, true);
log_first_seq++;
}
if (log_next_idx + size + sizeof(struct log) >= log_buf_len) {
/*
* This message + an additional empty header does not fit
* at the end of the buffer. Add an empty header with len == 0
* to signify a wrap around.
*/
memset(log_buf + log_next_idx, 0, sizeof(struct log));
LOG_MAGIC((struct log *)(log_buf + log_next_idx));
log_next_idx = 0;
}
/* fill message */
msg = (struct log *)(log_buf + log_next_idx);
memcpy(log_text(msg), text, text_len);
msg->text_len = text_len;
memcpy(log_dict(msg), dict, dict_len);
msg->dict_len = dict_len;
msg->facility = facility;
msg->level = level & 7;
msg->flags = flags & 0x1f;
LOG_MAGIC(msg);
if (ts_nsec > 0)
msg->ts_nsec = ts_nsec;
else
msg->ts_nsec = local_clock();
memset(log_dict(msg) + dict_len, 0, pad_len);
msg->len = sizeof(struct log) + text_len + dict_len + pad_len;
/* insert message */
log_next_idx += msg->len;
log_next_seq++;
}
#ifdef CONFIG_SECURITY_DMESG_RESTRICT
int dmesg_restrict = 1;
#else
int dmesg_restrict;
#endif
static int syslog_action_restricted(int type)
{
if (dmesg_restrict)
return 1;
/*
* Unless restricted, we allow "read all" and "get buffer size"
* for everybody.
*/
return type != SYSLOG_ACTION_READ_ALL &&
type != SYSLOG_ACTION_SIZE_BUFFER;
}
static int check_syslog_permissions(int type, bool from_file)
{
/*
* If this is from /proc/kmsg and we've already opened it, then we've
* already done the capabilities checks at open time.
*/
if (from_file && type != SYSLOG_ACTION_OPEN)
return 0;
if (syslog_action_restricted(type)) {
if (capable(CAP_SYSLOG))
return 0;
/*
* For historical reasons, accept CAP_SYS_ADMIN too, with
* a warning.
*/
if (capable(CAP_SYS_ADMIN)) {
pr_warn_once("%s (%d): Attempt to access syslog with "
"CAP_SYS_ADMIN but no CAP_SYSLOG "
"(deprecated).\n",
current->comm, task_pid_nr(current));
return 0;
}
return -EPERM;
}
return security_syslog(type);
}
/* /dev/kmsg - userspace message inject/listen interface */
struct devkmsg_user {
u64 seq;
u32 idx;
enum log_flags prev;
struct mutex lock;
char buf[8192];
};
static ssize_t devkmsg_writev(struct kiocb *iocb, const struct iovec *iv,
unsigned long count, loff_t pos)
{
char *buf, *line;
int i;
int level = default_message_loglevel;
int facility = 1; /* LOG_USER */
size_t len = iov_length(iv, count);
ssize_t ret = len;
if (len > LOG_LINE_MAX)
return -EINVAL;
buf = kmalloc(len+1, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
line = buf;
for (i = 0; i < count; i++) {
if (copy_from_user(line, iv[i].iov_base, iv[i].iov_len)) {
ret = -EFAULT;
goto out;
}
line += iv[i].iov_len;
}
/*
* Extract and skip the syslog prefix <[0-9]*>. Coming from userspace
* the decimal value represents 32bit, the lower 3 bit are the log
* level, the rest are the log facility.
*
* If no prefix or no userspace facility is specified, we
* enforce LOG_USER, to be able to reliably distinguish
* kernel-generated messages from userspace-injected ones.
*/
line = buf;
if (line[0] == '<') {
char *endp = NULL;
i = simple_strtoul(line+1, &endp, 10);
if (endp && endp[0] == '>') {
level = i & 7;
if (i >> 3)
facility = i >> 3;
endp++;
len -= endp - line;
line = endp;
}
}
line[len] = '\0';
printk_emit(facility, level, NULL, 0, "%s", line);
out:
kfree(buf);
return ret;
}
#if defined(CONFIG_OOPS_LOG_BUFFER)
static bool devkmsg_seq_passed(struct devkmsg_user *user)
{
if ((log_oops_first_seq == ULLONG_MAX && user->seq < log_first_seq) ||
(log_oops_first_seq != ULLONG_MAX &&
user->seq < log_oops_first_seq))
return true;
else
return false;
}
#else
static bool devkmsg_seq_passed(struct devkmsg_user *user)
{
return user->seq < log_first_seq;
}
#endif
static ssize_t devkmsg_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct devkmsg_user *user = file->private_data;
struct log *msg;
u64 ts_usec;
size_t i;
char cont = '-';
size_t len;
ssize_t ret;
bool regular_buf = true;
if (!user)
return -EBADF;
ret = mutex_lock_interruptible(&user->lock);
if (ret)
return ret;
raw_spin_lock_irq(&logbuf_lock);
while (user->seq == log_next_seq) {
if (file->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
raw_spin_unlock_irq(&logbuf_lock);
goto out;
}
raw_spin_unlock_irq(&logbuf_lock);
ret = wait_event_interruptible(log_wait,
user->seq != log_next_seq);
if (ret)
goto out;
raw_spin_lock_irq(&logbuf_lock);
}
if (devkmsg_seq_passed(user)) {
/* our last seen message is gone, return error and reset */
user->idx = log_first_idx;
user->seq = log_first_seq;
ret = -EPIPE;
raw_spin_unlock_irq(&logbuf_lock);
goto out;
}
#if defined(CONFIG_OOPS_LOG_BUFFER)
else if (log_oops_first_seq != ULLONG_MAX) {
if (user->seq <= log_oops_first_seq) {
user->idx = 0;
regular_buf = false;
} else if (user->seq > log_oops_first_seq &&
user->seq < log_oops_last_seq) {
regular_buf = false;
} else if (user->seq < log_first_seq) {
user->idx = log_first_idx;
user->seq = log_first_seq;
}
}
#endif
msg = log_from_idx(user->idx, regular_buf);
ts_usec = msg->ts_nsec;
do_div(ts_usec, 1000);
/*
* If we couldn't merge continuation line fragments during the print,
* export the stored flags to allow an optional external merge of the
* records. Merging the records isn't always neccessarily correct, like
* when we hit a race during printing. In most cases though, it produces
* better readable output. 'c' in the record flags mark the first
* fragment of a line, '+' the following.
*/
if (msg->flags & LOG_CONT && !(user->prev & LOG_CONT))
cont = 'c';
else if ((msg->flags & LOG_CONT) ||
((user->prev & LOG_CONT) && !(msg->flags & LOG_PREFIX)))
cont = '+';
len = sprintf(user->buf, "%u,%llu,%llu,%c;",
(msg->facility << 3) | msg->level,
user->seq, ts_usec, cont);
user->prev = msg->flags;
/* escape non-printable characters */
for (i = 0; i < msg->text_len; i++) {
unsigned char c = log_text(msg)[i];
if (c < ' ' || c >= 127 || c == '\\')
len += sprintf(user->buf + len, "\\x%02x", c);
else
user->buf[len++] = c;
}
user->buf[len++] = '\n';
if (msg->dict_len) {
bool line = true;
for (i = 0; i < msg->dict_len; i++) {
unsigned char c = log_dict(msg)[i];
if (line) {
user->buf[len++] = ' ';
line = false;
}
if (c == '\0') {
user->buf[len++] = '\n';
line = true;
continue;
}
if (c < ' ' || c >= 127 || c == '\\') {
len += sprintf(user->buf + len, "\\x%02x", c);
continue;
}
user->buf[len++] = c;
}
user->buf[len++] = '\n';
}
user->idx = log_next(user->idx, regular_buf);
user->seq++;
raw_spin_unlock_irq(&logbuf_lock);
if (len > count) {
ret = -EINVAL;
goto out;
}
if (copy_to_user(buf, user->buf, len)) {
ret = -EFAULT;
goto out;
}
ret = len;
out:
mutex_unlock(&user->lock);
return ret;
}
static void devkmsg_set_first(struct devkmsg_user *user)
{
#if defined(CONFIG_OOPS_LOG_BUFFER)
if (log_oops_first_seq != ULLONG_MAX) {
user->idx = 0;
user->seq = log_oops_first_seq;
} else
#endif
{
user->idx = log_first_idx;
user->seq = log_first_seq;
}
}
static loff_t devkmsg_llseek(struct file *file, loff_t offset, int whence)
{
struct devkmsg_user *user = file->private_data;
loff_t ret = 0;
if (!user)
return -EBADF;
if (offset)
return -ESPIPE;
raw_spin_lock_irq(&logbuf_lock);
switch (whence) {
case SEEK_SET:
/* the first record */
devkmsg_set_first(user);
break;
case SEEK_DATA:
/*
* The first record after the last SYSLOG_ACTION_CLEAR,
* like issued by 'dmesg -c'. Reading /dev/kmsg itself
* changes no global state, and does not clear anything.
*/
user->idx = clear_idx;
user->seq = clear_seq;
break;
case SEEK_END:
/* after the last record */
user->idx = log_next_idx;
user->seq = log_next_seq;
break;
default:
ret = -EINVAL;
}
raw_spin_unlock_irq(&logbuf_lock);
return ret;
}
static unsigned int devkmsg_poll(struct file *file, poll_table *wait)
{
struct devkmsg_user *user = file->private_data;
int ret = 0;
if (!user)
return POLLERR|POLLNVAL;
poll_wait(file, &log_wait, wait);
raw_spin_lock_irq(&logbuf_lock);
if (user->seq < log_next_seq) {
/* return error when data has vanished underneath us */
if (user->seq < log_first_seq)
ret = POLLIN|POLLRDNORM|POLLERR|POLLPRI;
else
ret = POLLIN|POLLRDNORM;
}
raw_spin_unlock_irq(&logbuf_lock);
return ret;
}
static int devkmsg_open(struct inode *inode, struct file *file)
{
struct devkmsg_user *user;
int err;
/* write-only does not need any file context */
if ((file->f_flags & O_ACCMODE) == O_WRONLY)
return 0;
err = check_syslog_permissions(SYSLOG_ACTION_READ_ALL,
SYSLOG_FROM_READER);
if (err)
return err;
user = kmalloc(sizeof(struct devkmsg_user), GFP_KERNEL);
if (!user)
return -ENOMEM;
mutex_init(&user->lock);
raw_spin_lock_irq(&logbuf_lock);
devkmsg_set_first(user);
raw_spin_unlock_irq(&logbuf_lock);
file->private_data = user;
return 0;
}
static int devkmsg_release(struct inode *inode, struct file *file)
{
struct devkmsg_user *user = file->private_data;
if (!user)
return 0;
mutex_destroy(&user->lock);
kfree(user);
return 0;
}
const struct file_operations kmsg_fops = {
.open = devkmsg_open,
.read = devkmsg_read,
.aio_write = devkmsg_writev,
.llseek = devkmsg_llseek,
.poll = devkmsg_poll,
.release = devkmsg_release,
};
#ifdef CONFIG_KEXEC
/*
* This appends the listed symbols to /proc/vmcoreinfo
*
* /proc/vmcoreinfo is used by various utiilties, like crash and makedumpfile to
* obtain access to symbols that are otherwise very difficult to locate. These
* symbols are specifically used so that utilities can access and extract the
* dmesg log from a vmcore file after a crash.
*/
void log_buf_kexec_setup(void)
{
VMCOREINFO_SYMBOL(log_buf);
VMCOREINFO_SYMBOL(log_buf_len);
VMCOREINFO_SYMBOL(log_first_idx);
VMCOREINFO_SYMBOL(log_next_idx);
/*
* Export struct log size and field offsets. User space tools can
* parse it and detect any changes to structure down the line.
*/
VMCOREINFO_STRUCT_SIZE(log);
VMCOREINFO_OFFSET(log, ts_nsec);
VMCOREINFO_OFFSET(log, len);
VMCOREINFO_OFFSET(log, text_len);
VMCOREINFO_OFFSET(log, dict_len);
}
#endif
/* requested log_buf_len from kernel cmdline */
static unsigned long __initdata new_log_buf_len;
/* save requested log_buf_len since it's too early to process it */
static int __init log_buf_len_setup(char *str)
{
unsigned size = memparse(str, &str);
if (size)
size = roundup_pow_of_two(size);
if (size > log_buf_len)
new_log_buf_len = size;
return 0;
}
early_param("log_buf_len", log_buf_len_setup);
void __init setup_log_buf(int early)
{
unsigned long flags;
char *new_log_buf;
int free;
if (!new_log_buf_len)
return;
if (early) {
unsigned long mem;
mem = memblock_alloc(new_log_buf_len, PAGE_SIZE);
if (!mem)
return;
new_log_buf = __va(mem);
} else {
new_log_buf = alloc_bootmem_nopanic(new_log_buf_len);
}
if (unlikely(!new_log_buf)) {
pr_err("log_buf_len: %ld bytes not available\n",
new_log_buf_len);
return;
}
raw_spin_lock_irqsave(&logbuf_lock, flags);
log_buf_len = new_log_buf_len;
log_buf = new_log_buf;
new_log_buf_len = 0;
free = __LOG_BUF_LEN - log_next_idx;
memcpy(log_buf, __log_buf, __LOG_BUF_LEN);
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
pr_info("log_buf_len: %d\n", log_buf_len);
pr_info("early log buf free: %d(%d%%)\n",
free, (free * 100) / __LOG_BUF_LEN);
}
static bool __read_mostly ignore_loglevel;
static int __init ignore_loglevel_setup(char *str)
{
ignore_loglevel = 1;
printk(KERN_INFO "debug: ignoring loglevel setting.\n");
return 0;
}
early_param("ignore_loglevel", ignore_loglevel_setup);
module_param(ignore_loglevel, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(ignore_loglevel, "ignore loglevel setting, to"
"print all kernel messages to the console.");
#ifdef CONFIG_BOOT_PRINTK_DELAY
static int boot_delay; /* msecs delay after each printk during bootup */
static unsigned long long loops_per_msec; /* based on boot_delay */
static int __init boot_delay_setup(char *str)
{
unsigned long lpj;
lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
get_option(&str, &boot_delay);
if (boot_delay > 10 * 1000)
boot_delay = 0;
pr_debug("boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
"HZ: %d, loops_per_msec: %llu\n",
boot_delay, preset_lpj, lpj, HZ, loops_per_msec);
return 1;
}
__setup("boot_delay=", boot_delay_setup);
static void boot_delay_msec(int level)
{
unsigned long long k;
unsigned long timeout;
if ((boot_delay == 0 || system_state != SYSTEM_BOOTING)
|| (level >= console_loglevel && !ignore_loglevel)) {
return;
}
k = (unsigned long long)loops_per_msec * boot_delay;
timeout = jiffies + msecs_to_jiffies(boot_delay);
while (k) {
k--;
cpu_relax();
/*
* use (volatile) jiffies to prevent
* compiler reduction; loop termination via jiffies
* is secondary and may or may not happen.
*/
if (time_after(jiffies, timeout))
break;
touch_nmi_watchdog();
}
}
#else
static inline void boot_delay_msec(int level)
{
}
#endif
#if defined(CONFIG_PRINTK_TIME)
static bool printk_time = 1;
#else
static bool printk_time;
#endif
module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
static size_t print_time(u64 ts, char *buf)
{
unsigned long rem_nsec;
if (!printk_time)
return 0;
rem_nsec = do_div(ts, 1000000000);
if (!buf)
return snprintf(NULL, 0, "[%5lu.000000] ", (unsigned long)ts);
return sprintf(buf, "[%5lu.%06lu] ",
(unsigned long)ts, rem_nsec / 1000);
}
static size_t print_prefix(const struct log *msg, bool syslog, char *buf)
{
size_t len = 0;
unsigned int prefix = (msg->facility << 3) | msg->level;
if (syslog) {
if (buf) {
len += sprintf(buf, "<%u>", prefix);
} else {
len += 3;
if (prefix > 999)
len += 3;
else if (prefix > 99)
len += 2;
else if (prefix > 9)
len++;
}
}
len += print_time(msg->ts_nsec, buf ? buf + len : NULL);
return len;
}
static size_t msg_print_text(const struct log *msg, enum log_flags prev,
bool syslog, char *buf, size_t size)
{
const char *text = log_text(msg);
size_t text_size = msg->text_len;
bool prefix = true;
bool newline = true;
size_t len = 0;
if ((prev & LOG_CONT) && !(msg->flags & LOG_PREFIX))
prefix = false;
if (msg->flags & LOG_CONT) {
if ((prev & LOG_CONT) && !(prev & LOG_NEWLINE))
prefix = false;
if (!(msg->flags & LOG_NEWLINE))
newline = false;
}
do {
const char *next = memchr(text, '\n', text_size);
size_t text_len;
if (next) {
text_len = next - text;
next++;
text_size -= next - text;
} else {
text_len = text_size;
}
if (buf) {
if (print_prefix(msg, syslog, NULL) +
text_len + 1 >= size - len)
break;
if (prefix)
len += print_prefix(msg, syslog, buf + len);
memcpy(buf + len, text, text_len);
len += text_len;
if (next || newline)
buf[len++] = '\n';
} else {
/* SYSLOG_ACTION_* buffer size only calculation */
if (prefix)
len += print_prefix(msg, syslog, NULL);
len += text_len;
if (next || newline)
len++;
}
prefix = true;
text = next;
} while (text);
return len;
}
#if defined(CONFIG_OOPS_LOG_BUFFER)
static int syslog_oops_buf_print(char __user *buf, int size, char *text)
{
struct log *msg;
size_t n;
size_t skip;
int len = 0;
raw_spin_lock_irq(&logbuf_lock);
if (log_oops_first_seq != ULLONG_MAX &&
syslog_seq < log_oops_first_seq) {
syslog_seq = log_oops_first_seq;
syslog_oops_buf_idx = 0;
}
while (size > 0 && log_oops_last_seq > syslog_seq) {
skip = syslog_partial;
msg = log_from_idx(syslog_oops_buf_idx, false);
n = msg_print_text(msg, syslog_prev, true, text,
LOG_LINE_MAX + PREFIX_MAX);
if (n - syslog_partial <= size) {
/* message fits into buffer, move forward */
syslog_oops_buf_idx = log_next(syslog_oops_buf_idx,
false);
syslog_seq++;
syslog_prev = msg->flags;
n -= syslog_partial;
syslog_partial = 0;
} else if (!len) {
/* partial read(), remember position */
n = size;
syslog_partial += n;
} else {
n = 0;
}
if (!n)
break;
raw_spin_unlock_irq(&logbuf_lock);
if (copy_to_user(buf, text + skip, n)) {
raw_spin_lock_irq(&logbuf_lock);
if (!len)
len = -EFAULT;
break;
}
raw_spin_lock_irq(&logbuf_lock);
len += n;
size -= n;
buf += n;
}
raw_spin_unlock_irq(&logbuf_lock);
return len;
}
static int syslog_print_oops_buf_all(char __user *buf, int size, bool clear,
char *text)
{
int len = 0;
u32 idx = 0;
u64 seq = clear_seq;
enum log_flags prev = 0;
u64 next_seq;
if (!buf)
return len;
raw_spin_lock_irq(&logbuf_lock);
seq = log_oops_first_seq;
next_seq = log_oops_last_seq;
while (len >= 0 && len < size && seq < next_seq) {
struct log *msg = log_from_idx(idx, false);
int textlen;
textlen = msg_print_text(msg, prev, true, text,
LOG_LINE_MAX + PREFIX_MAX);
if (textlen < 0) {
len = textlen;
break;
}
idx = log_next(idx, false);
seq++;
prev = msg->flags;
raw_spin_unlock_irq(&logbuf_lock);
if (copy_to_user(buf + len, text, textlen))
len = -EFAULT;
else
len += textlen;
raw_spin_lock_irq(&logbuf_lock);
}
raw_spin_unlock_irq(&logbuf_lock);
return len;
}
#else
static int syslog_oops_buf_print(char __user *buf, int size, char *text)
{
return 0;
}
static int syslog_print_oops_buf_all(char __user *buf, int size, bool clear,
char *text)
{
return 0;
}
#endif
int syslog_print(char __user *buf, int size)
{
char *text;
struct log *msg;
int oops_buf_len;
int len = 0;
text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
if (!text)
return -ENOMEM;
oops_buf_len = syslog_oops_buf_print(buf, size, text);
if (oops_buf_len < 0)
return oops_buf_len;
size -= oops_buf_len;
while (size > 0) {
size_t n;
size_t skip;
raw_spin_lock_irq(&logbuf_lock);
if (syslog_seq < log_first_seq) {
/* messages are gone, move to first one */
syslog_seq = log_first_seq;
syslog_idx = log_first_idx;
syslog_prev = 0;
syslog_partial = 0;
}
if (syslog_seq == log_next_seq) {
raw_spin_unlock_irq(&logbuf_lock);
break;
}
skip = syslog_partial;
msg = log_from_idx(syslog_idx, true);
n = msg_print_text(msg, syslog_prev, true, text,
LOG_LINE_MAX + PREFIX_MAX);
if (n - syslog_partial <= size) {
/* message fits into buffer, move forward */
syslog_idx = log_next(syslog_idx, true);
syslog_seq++;
syslog_prev = msg->flags;
n -= syslog_partial;
syslog_partial = 0;
} else if (!len){
/* partial read(), remember position */
n = size;
syslog_partial += n;
} else
n = 0;
raw_spin_unlock_irq(&logbuf_lock);
if (!n)
break;
if (copy_to_user(buf + oops_buf_len, text + skip, n)) {
if (!len)
len = -EFAULT;
break;
}
len += n;
size -= n;
buf += n;
}
kfree(text);
if (len > 0)
len += oops_buf_len;
return len;
}
static int syslog_print_all(char __user *buf, int size, bool clear)
{
char *text;
int oops_len;
int len = 0;
text = kmalloc(LOG_LINE_MAX + PREFIX_MAX, GFP_KERNEL);
if (!text)
return -ENOMEM;
oops_len = syslog_print_oops_buf_all(buf, size, clear, text);
if (oops_len < 0)
return oops_len;
raw_spin_lock_irq(&logbuf_lock);
if (buf) {
u64 next_seq;
u64 seq;
u32 idx;
u64 start_seq;
u32 start_idx;
enum log_flags prev;
if (clear_seq < log_first_seq) {
/* messages are gone, move to first available one */
start_seq = log_first_seq;
start_idx = log_first_idx;
} else {
start_seq = clear_seq;
start_idx = clear_idx;
}
/*
* Find first record that fits, including all following records,
* into the user-provided buffer for this dump.
*/
seq = start_seq;
idx = start_idx;
prev = 0;
while (seq < log_next_seq) {
struct log *msg = log_from_idx(idx, true);
len += msg_print_text(msg, prev, true, NULL, 0);
prev = msg->flags;
idx = log_next(idx, true);
seq++;
}
/* move first record forward until length fits into the buffer */
seq = start_seq;
idx = start_idx;
prev = 0;
while ((len > size - oops_len) && seq < log_next_seq) {
struct log *msg = log_from_idx(idx, true);
len -= msg_print_text(msg, prev, true, NULL, 0);
prev = msg->flags;
idx = log_next(idx, true);
seq++;
}
/* last message fitting into this dump */
next_seq = log_next_seq;
len = 0;
prev = 0;
while (len >= 0 && seq < next_seq) {
struct log *msg = log_from_idx(idx, true);
int textlen;
textlen = msg_print_text(msg, prev, true, text,
LOG_LINE_MAX + PREFIX_MAX);
if (textlen < 0) {
len = textlen;
break;
}
idx = log_next(idx, true);
seq++;
prev = msg->flags;
raw_spin_unlock_irq(&logbuf_lock);
if (copy_to_user(buf + len + oops_len, text, textlen))
len = -EFAULT;
else
len += textlen;
raw_spin_lock_irq(&logbuf_lock);
if (seq < log_first_seq) {
/* messages are gone, move to next one */
seq = log_first_seq;
idx = log_first_idx;
prev = 0;
}
}
}
if (clear) {
clear_seq = log_next_seq;
clear_idx = log_next_idx;
}
raw_spin_unlock_irq(&logbuf_lock);
kfree(text);
if (len > 0)
len += oops_len;
return len;
}
int do_syslog(int type, char __user *buf, int len, bool from_file)
{
bool clear = false;
static int saved_console_loglevel = -1;
int error;
error = check_syslog_permissions(type, from_file);
if (error)
goto out;
error = security_syslog(type);
if (error)
return error;
switch (type) {
case SYSLOG_ACTION_CLOSE: /* Close log */
break;
case SYSLOG_ACTION_OPEN: /* Open log */
break;
case SYSLOG_ACTION_READ: /* Read from log */
error = -EINVAL;
if (!buf || len < 0)
goto out;
error = 0;
if (!len)
goto out;
if (!access_ok(VERIFY_WRITE, buf, len)) {
error = -EFAULT;
goto out;
}
error = wait_event_interruptible(log_wait,
syslog_seq != log_next_seq);
if (error)
goto out;
error = syslog_print(buf, len);
break;
/* Read/clear last kernel messages */
case SYSLOG_ACTION_READ_CLEAR:
clear = true;
/* FALL THRU */
/* Read last kernel messages */
case SYSLOG_ACTION_READ_ALL:
error = -EINVAL;
if (!buf || len < 0)
goto out;
error = 0;
if (!len)
goto out;
if (!access_ok(VERIFY_WRITE, buf, len)) {
error = -EFAULT;
goto out;
}
error = syslog_print_all(buf, len, clear);
break;
/* Clear ring buffer */
case SYSLOG_ACTION_CLEAR:
syslog_print_all(NULL, 0, true);
break;
/* Disable logging to console */
case SYSLOG_ACTION_CONSOLE_OFF:
if (saved_console_loglevel == -1)
saved_console_loglevel = console_loglevel;
console_loglevel = minimum_console_loglevel;
break;
/* Enable logging to console */
case SYSLOG_ACTION_CONSOLE_ON:
if (saved_console_loglevel != -1) {
console_loglevel = saved_console_loglevel;
saved_console_loglevel = -1;
}
break;
/* Set level of messages printed to console */
case SYSLOG_ACTION_CONSOLE_LEVEL:
error = -EINVAL;
if (len < 1 || len > 8)
goto out;
if (len < minimum_console_loglevel)
len = minimum_console_loglevel;
console_loglevel = len;
/* Implicitly re-enable logging to console */
saved_console_loglevel = -1;
error = 0;
break;
/* Number of chars in the log buffer */
case SYSLOG_ACTION_SIZE_UNREAD:
raw_spin_lock_irq(&logbuf_lock);
if (syslog_seq < log_first_seq) {
/* messages are gone, move to first one */
syslog_seq = log_first_seq;
syslog_idx = log_first_idx;
syslog_prev = 0;
syslog_partial = 0;
}
if (from_file) {
/*
* Short-cut for poll(/"proc/kmsg") which simply checks
* for pending data, not the size; return the count of
* records, not the length.
*/
error = log_next_idx - syslog_idx;
} else {
u64 seq = syslog_seq;
u32 idx = syslog_idx;
enum log_flags prev = syslog_prev;
error = 0;
while (seq < log_next_seq) {
struct log *msg = log_from_idx(idx,
true);
error += msg_print_text(msg, prev, true, NULL, 0);
idx = log_next(idx, true);
seq++;
prev = msg->flags;
}
error -= syslog_partial;
}
raw_spin_unlock_irq(&logbuf_lock);
break;
/* Size of the log buffer */
case SYSLOG_ACTION_SIZE_BUFFER:
error = log_buf_len;
#if defined(CONFIG_OOPS_LOG_BUFFER)
error += log_oops_buf_len;
#endif
break;
default:
error = -EINVAL;
break;
}
out:
return error;
}
SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
{
return do_syslog(type, buf, len, SYSLOG_FROM_READER);
}
/*
* Call the console drivers, asking them to write out
* log_buf[start] to log_buf[end - 1].
* The console_lock must be held.
*/
static void call_console_drivers(int level, const char *text, size_t len)
{
struct console *con;
trace_console(text, len);
if (level >= console_loglevel && !ignore_loglevel)
return;
if (!console_drivers)
return;
for_each_console(con) {
if (exclusive_console && con != exclusive_console)
continue;
if (!(con->flags & CON_ENABLED))
continue;
if (!con->write)
continue;
if (!cpu_online(smp_processor_id()) &&
!(con->flags & CON_ANYTIME))
continue;
con->write(con, text, len);
}
}
/*
* Zap console related locks when oopsing. Only zap at most once
* every 10 seconds, to leave time for slow consoles to print a
* full oops.
*/
static void zap_locks(void)
{
static unsigned long oops_timestamp;
if (time_after_eq(jiffies, oops_timestamp) &&
!time_after(jiffies, oops_timestamp + 30 * HZ))
return;
oops_timestamp = jiffies;
debug_locks_off();
/* If a crash is occurring, make sure we can't deadlock */
raw_spin_lock_init(&logbuf_lock);
/* And make sure that we print immediately */
sema_init(&console_sem, 1);
}
/* Check if we have any console registered that can be called early in boot. */
static int have_callable_console(void)
{
struct console *con;
for_each_console(con)
if (con->flags & CON_ANYTIME)
return 1;
return 0;
}
/*
* Can we actually use the console at this time on this cpu?
*
* Console drivers may assume that per-cpu resources have
* been allocated. So unless they're explicitly marked as
* being able to cope (CON_ANYTIME) don't call them until
* this CPU is officially up.
*/
static inline int can_use_console(unsigned int cpu)
{
return cpu_online(cpu) || have_callable_console();
}
/*
* Try to get console ownership to actually show the kernel
* messages from a 'printk'. Return true (and with the
* console_lock held, and 'console_locked' set) if it
* is successful, false otherwise.
*
* This gets called with the 'logbuf_lock' spinlock held and
* interrupts disabled. It should return with 'lockbuf_lock'
* released but interrupts still disabled.
*/
static int console_trylock_for_printk(unsigned int cpu)
__releases(&logbuf_lock)
{
int retval = 0, wake = 0;
if (console_trylock()) {
retval = 1;
/*
* If we can't use the console, we need to release
* the console semaphore by hand to avoid flushing
* the buffer. We need to hold the console semaphore
* in order to do this test safely.
*/
if (!can_use_console(cpu)) {
console_locked = 0;
wake = 1;
retval = 0;
}
}
logbuf_cpu = UINT_MAX;
raw_spin_unlock(&logbuf_lock);
if (wake)
up(&console_sem);
return retval;
}
int printk_delay_msec __read_mostly;
static inline void printk_delay(void)
{
if (unlikely(printk_delay_msec)) {
int m = printk_delay_msec;
while (m--) {
mdelay(1);
touch_nmi_watchdog();
}
}
}
/*
* Continuation lines are buffered, and not committed to the record buffer
* until the line is complete, or a race forces it. The line fragments
* though, are printed immediately to the consoles to ensure everything has
* reached the console in case of a kernel crash.
*/
static struct cont {
char buf[LOG_LINE_MAX];
size_t len; /* length == 0 means unused buffer */
size_t cons; /* bytes written to console */
struct task_struct *owner; /* task of first print*/
u64 ts_nsec; /* time of first print */
u8 level; /* log level of first message */
u8 facility; /* log level of first message */
enum log_flags flags; /* prefix, newline flags */
bool flushed:1; /* buffer sealed and committed */
} cont;
static void cont_flush(enum log_flags flags)
{
if (cont.flushed)
return;
if (cont.len == 0)
return;
if (cont.cons) {
/*
* If a fragment of this line was directly flushed to the
* console; wait for the console to pick up the rest of the
* line. LOG_NOCONS suppresses a duplicated output.
*/
log_store(cont.facility, cont.level, flags | LOG_NOCONS,
cont.ts_nsec, NULL, 0, cont.buf, cont.len);
cont.flags = flags;
cont.flushed = true;
} else {
/*
* If no fragment of this line ever reached the console,
* just submit it to the store and free the buffer.
*/
log_store(cont.facility, cont.level, flags, 0,
NULL, 0, cont.buf, cont.len);
cont.len = 0;
}
}
static bool cont_add(int facility, int level, const char *text, size_t len)
{
if (cont.len && cont.flushed)
return false;
if (cont.len + len > sizeof(cont.buf)) {
/* the line gets too long, split it up in separate records */
cont_flush(LOG_CONT);
return false;
}
if (!cont.len) {
cont.facility = facility;
cont.level = level;
cont.owner = current;
cont.ts_nsec = local_clock();
cont.flags = 0;
cont.cons = 0;
cont.flushed = false;
}
memcpy(cont.buf + cont.len, text, len);
cont.len += len;
if (cont.len > (sizeof(cont.buf) * 80) / 100)
cont_flush(LOG_CONT);
return true;
}
static size_t cont_print_text(char *text, size_t size)
{
size_t textlen = 0;
size_t len;
if (cont.cons == 0 && (console_prev & LOG_NEWLINE)) {
textlen += print_time(cont.ts_nsec, text);
size -= textlen;
}
len = cont.len - cont.cons;
if (len > 0) {
if (len+1 > size)
len = size-1;
memcpy(text + textlen, cont.buf + cont.cons, len);
textlen += len;
cont.cons = cont.len;
}
if (cont.flushed) {
if (cont.flags & LOG_NEWLINE)
text[textlen++] = '\n';
/* got everything, release buffer */
cont.len = 0;
}
return textlen;
}
asmlinkage int vprintk_emit(int facility, int level,
const char *dict, size_t dictlen,
const char *fmt, va_list args)
{
static int recursion_bug;
static char textbuf[LOG_LINE_MAX];
char *text = textbuf;
size_t text_len;
enum log_flags lflags = 0;
unsigned long flags;
int this_cpu;
int printed_len = 0;
boot_delay_msec(level);
printk_delay();
/* This stops the holder of console_sem just where we want him */
local_irq_save(flags);
this_cpu = smp_processor_id();
/*
* Ouch, printk recursed into itself!
*/
if (unlikely(logbuf_cpu == this_cpu)) {
/*
* If a crash is occurring during printk() on this CPU,
* then try to get the crash message out but make sure
* we can't deadlock. Otherwise just return to avoid the
* recursion and return - but flag the recursion so that
* it can be printed at the next appropriate moment:
*/
if (!oops_in_progress && !lockdep_recursing(current)) {
recursion_bug = 1;
goto out_restore_irqs;
}
zap_locks();
}
lockdep_off();
raw_spin_lock(&logbuf_lock);
logbuf_cpu = this_cpu;
if (recursion_bug) {
static const char recursion_msg[] =
"BUG: recent printk recursion!";
recursion_bug = 0;
printed_len += strlen(recursion_msg);
/* emit KERN_CRIT message */
log_store(0, 2, LOG_PREFIX|LOG_NEWLINE, 0,
NULL, 0, recursion_msg, printed_len);
}
/*
* The printf needs to come first; we need the syslog
* prefix which might be passed-in as a parameter.
*/
text_len = vscnprintf(text, sizeof(textbuf), fmt, args);
/* mark and strip a trailing newline */
if (text_len && text[text_len-1] == '\n') {
text_len--;
lflags |= LOG_NEWLINE;
}
/* strip kernel syslog prefix and extract log level or control flags */
if (facility == 0) {
int kern_level = printk_get_level(text);
if (kern_level) {
const char *end_of_header = printk_skip_level(text);
switch (kern_level) {
case '0' ... '7':
if (level == -1)
level = kern_level - '0';
case 'd': /* KERN_DEFAULT */
lflags |= LOG_PREFIX;
case 'c': /* KERN_CONT */
break;
}
text_len -= end_of_header - text;
text = (char *)end_of_header;
}
}
#ifdef CONFIG_EARLY_PRINTK_DIRECT
printascii(text);
#endif
if (level == -1)
level = default_message_loglevel;
if (dict)
lflags |= LOG_PREFIX|LOG_NEWLINE;
if (!(lflags & LOG_NEWLINE)) {
/*
* Flush the conflicting buffer. An earlier newline was missing,
* or another task also prints continuation lines.
*/
if (cont.len && (lflags & LOG_PREFIX || cont.owner != current))
cont_flush(LOG_NEWLINE);
/* buffer line if possible, otherwise store it right away */
if (!cont_add(facility, level, text, text_len))
log_store(facility, level, lflags | LOG_CONT, 0,
dict, dictlen, text, text_len);
} else {
bool stored = false;
/*
* If an earlier newline was missing and it was the same task,
* either merge it with the current buffer and flush, or if
* there was a race with interrupts (prefix == true) then just
* flush it out and store this line separately.
*/
if (cont.len && cont.owner == current) {
if (!(lflags & LOG_PREFIX))
stored = cont_add(facility, level, text, text_len);
cont_flush(LOG_NEWLINE);
}
if (!stored)
log_store(facility, level, lflags, 0,
dict, dictlen, text, text_len);
}
printed_len += text_len;
/*
* Try to acquire and then immediately release the console semaphore.
* The release will print out buffers and wake up /dev/kmsg and syslog()
* users.
*
* The console_trylock_for_printk() function will release 'logbuf_lock'
* regardless of whether it actually gets the console semaphore or not.
*/
if (console_trylock_for_printk(this_cpu))
console_unlock();
lockdep_on();
out_restore_irqs:
local_irq_restore(flags);
return printed_len;
}
EXPORT_SYMBOL(vprintk_emit);
asmlinkage int vprintk(const char *fmt, va_list args)
{
return vprintk_emit(0, -1, NULL, 0, fmt, args);
}
EXPORT_SYMBOL(vprintk);
asmlinkage int printk_emit(int facility, int level,
const char *dict, size_t dictlen,
const char *fmt, ...)
{
va_list args;
int r;
va_start(args, fmt);
r = vprintk_emit(facility, level, dict, dictlen, fmt, args);
va_end(args);
return r;
}
EXPORT_SYMBOL(printk_emit);
/**
* printk - print a kernel message
* @fmt: format string
*
* This is printk(). It can be called from any context. We want it to work.
*
* We try to grab the console_lock. If we succeed, it's easy - we log the
* output and call the console drivers. If we fail to get the semaphore, we
* place the output into the log buffer and return. The current holder of
* the console_sem will notice the new output in console_unlock(); and will
* send it to the consoles before releasing the lock.
*
* One effect of this deferred printing is that code which calls printk() and
* then changes console_loglevel may break. This is because console_loglevel
* is inspected when the actual printing occurs.
*
* See also:
* printf(3)
*
* See the vsnprintf() documentation for format string extensions over C99.
*/
asmlinkage int printk(const char *fmt, ...)
{
va_list args;
int r;
#ifdef CONFIG_KGDB_KDB
if (unlikely(kdb_trap_printk)) {
va_start(args, fmt);
r = vkdb_printf(fmt, args);
va_end(args);
return r;
}
#endif
va_start(args, fmt);
r = vprintk_emit(0, -1, NULL, 0, fmt, args);
va_end(args);
return r;
}
EXPORT_SYMBOL(printk);
#else /* CONFIG_PRINTK */
#define LOG_LINE_MAX 0
#define PREFIX_MAX 0
#define LOG_LINE_MAX 0
static u64 syslog_seq;
static u32 syslog_idx;
static u64 console_seq;
static u32 console_idx;
static enum log_flags syslog_prev;
static u64 log_first_seq;
static u32 log_first_idx;
static u64 log_next_seq;
static enum log_flags console_prev;
static struct cont {
size_t len;
size_t cons;
u8 level;
bool flushed:1;
} cont;
static struct log *log_from_idx(u32 idx, bool logbuf) { return NULL; }
static u32 log_next(u32 idx, bool logbuf) { return 0; }
static void call_console_drivers(int level, const char *text, size_t len) {}
static size_t msg_print_text(const struct log *msg, enum log_flags prev,
bool syslog, char *buf, size_t size) { return 0; }
static size_t cont_print_text(char *text, size_t size) { return 0; }
#endif /* CONFIG_PRINTK */
#ifdef CONFIG_EARLY_PRINTK
struct console *early_console;
void early_vprintk(const char *fmt, va_list ap)
{
if (early_console) {
char buf[512];
int n = vscnprintf(buf, sizeof(buf), fmt, ap);
early_console->write(early_console, buf, n);
}
}
asmlinkage void early_printk(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
early_vprintk(fmt, ap);
va_end(ap);
}
#endif
static int __add_preferred_console(char *name, int idx, char *options,
char *brl_options)
{
struct console_cmdline *c;
int i;
/*
* See if this tty is not yet registered, and
* if we have a slot free.
*/
for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
if (strcmp(console_cmdline[i].name, name) == 0 &&
console_cmdline[i].index == idx) {
if (!brl_options)
selected_console = i;
return 0;
}
if (i == MAX_CMDLINECONSOLES)
return -E2BIG;
if (!brl_options)
selected_console = i;
c = &console_cmdline[i];
strlcpy(c->name, name, sizeof(c->name));
c->options = options;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
c->brl_options = brl_options;
#endif
c->index = idx;
return 0;
}
/*
* Set up a list of consoles. Called from init/main.c
*/
static int __init console_setup(char *str)
{
char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
char *s, *options, *brl_options = NULL;
int idx;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
if (!memcmp(str, "brl,", 4)) {
brl_options = "";
str += 4;
} else if (!memcmp(str, "brl=", 4)) {
brl_options = str + 4;
str = strchr(brl_options, ',');
if (!str) {
printk(KERN_ERR "need port name after brl=\n");
return 1;
}
*(str++) = 0;
}
#endif
/*
* Decode str into name, index, options.
*/
if (str[0] >= '0' && str[0] <= '9') {
strcpy(buf, "ttyS");
strncpy(buf + 4, str, sizeof(buf) - 5);
} else {
strncpy(buf, str, sizeof(buf) - 1);
}
buf[sizeof(buf) - 1] = 0;
if ((options = strchr(str, ',')) != NULL)
*(options++) = 0;
#ifdef __sparc__
if (!strcmp(str, "ttya"))
strcpy(buf, "ttyS0");
if (!strcmp(str, "ttyb"))
strcpy(buf, "ttyS1");
#endif
for (s = buf; *s; s++)
if ((*s >= '0' && *s <= '9') || *s == ',')
break;
idx = simple_strtoul(s, NULL, 10);
*s = 0;
__add_preferred_console(buf, idx, options, brl_options);
console_set_on_cmdline = 1;
return 1;
}
__setup("console=", console_setup);
/**
* add_preferred_console - add a device to the list of preferred consoles.
* @name: device name
* @idx: device index
* @options: options for this console
*
* The last preferred console added will be used for kernel messages
* and stdin/out/err for init. Normally this is used by console_setup
* above to handle user-supplied console arguments; however it can also
* be used by arch-specific code either to override the user or more
* commonly to provide a default console (ie from PROM variables) when
* the user has not supplied one.
*/
int add_preferred_console(char *name, int idx, char *options)
{
return __add_preferred_console(name, idx, options, NULL);
}
int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
{
struct console_cmdline *c;
int i;
for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
if (strcmp(console_cmdline[i].name, name) == 0 &&
console_cmdline[i].index == idx) {
c = &console_cmdline[i];
strlcpy(c->name, name_new, sizeof(c->name));
c->name[sizeof(c->name) - 1] = 0;
c->options = options;
c->index = idx_new;
return i;
}
/* not found */
return -1;
}
bool console_suspend_enabled = 1;
EXPORT_SYMBOL(console_suspend_enabled);
static int __init console_suspend_disable(char *str)
{
console_suspend_enabled = 0;
return 1;
}
__setup("no_console_suspend", console_suspend_disable);
module_param_named(console_suspend, console_suspend_enabled,
bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(console_suspend, "suspend console during suspend"
" and hibernate operations");
/**
* suspend_console - suspend the console subsystem
*
* This disables printk() while we go into suspend states
*/
void suspend_console(void)
{
if (!console_suspend_enabled)
return;
printk("Suspending console(s) (use no_console_suspend to debug)\n");
console_lock();
console_suspended = 1;
up(&console_sem);
}
void resume_console(void)
{
if (!console_suspend_enabled)
return;
down(&console_sem);
console_suspended = 0;
console_unlock();
}
static void console_flush(struct work_struct *work)
{
console_lock();
console_unlock();
}
static DECLARE_WORK(console_cpu_notify_work, console_flush);
/**
* console_cpu_notify - print deferred console messages after CPU hotplug
* @self: notifier struct
* @action: CPU hotplug event
* @hcpu: unused
*
* If printk() is called from a CPU that is not online yet, the messages
* will be spooled but will not show up on the console. This function is
* called when a new CPU comes online (or fails to come up), and ensures
* that any such output gets printed.
*
* Special handling must be done for cases invoked from an atomic context,
* as we can't be taking the console semaphore here.
*/
static int console_cpu_notify(struct notifier_block *self,
unsigned long action, void *hcpu)
{
switch (action) {
case CPU_DEAD:
case CPU_DOWN_FAILED:
case CPU_UP_CANCELED:
#ifdef CONFIG_CONSOLE_FLUSH_ON_HOTPLUG
console_lock();
console_unlock();
#endif
break;
case CPU_ONLINE:
case CPU_DYING:
/* invoked with preemption disabled, so defer */
if (!console_trylock())
schedule_work(&console_cpu_notify_work);
else
console_unlock();
}
return NOTIFY_OK;
}
/**
* console_lock - lock the console system for exclusive use.
*
* Acquires a lock which guarantees that the caller has
* exclusive access to the console system and the console_drivers list.
*
* Can sleep, returns nothing.
*/
void console_lock(void)
{
might_sleep();
down(&console_sem);
if (console_suspended)
return;
console_locked = 1;
console_may_schedule = 1;
mutex_acquire(&console_lock_dep_map, 0, 0, _RET_IP_);
}
EXPORT_SYMBOL(console_lock);
/**
* console_trylock - try to lock the console system for exclusive use.
*
* Tried to acquire a lock which guarantees that the caller has
* exclusive access to the console system and the console_drivers list.
*
* returns 1 on success, and 0 on failure to acquire the lock.
*/
int console_trylock(void)
{
if (down_trylock(&console_sem))
return 0;
if (console_suspended) {
up(&console_sem);
return 0;
}
console_locked = 1;
console_may_schedule = 0;
mutex_acquire(&console_lock_dep_map, 0, 1, _RET_IP_);
return 1;
}
EXPORT_SYMBOL(console_trylock);
int is_console_locked(void)
{
return console_locked;
}
static void console_cont_flush(char *text, size_t size)
{
unsigned long flags;
size_t len;
raw_spin_lock_irqsave(&logbuf_lock, flags);
if (!cont.len)
goto out;
/*
* We still queue earlier records, likely because the console was
* busy. The earlier ones need to be printed before this one, we
* did not flush any fragment so far, so just let it queue up.
*/
if (console_seq < log_next_seq && !cont.cons)
goto out;
len = cont_print_text(text, size);
raw_spin_unlock(&logbuf_lock);
stop_critical_timings();
call_console_drivers(cont.level, text, len);
start_critical_timings();
local_irq_restore(flags);
return;
out:
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
}
/**
* console_unlock - unlock the console system
*
* Releases the console_lock which the caller holds on the console system
* and the console driver list.
*
* While the console_lock was held, console output may have been buffered
* by printk(). If this is the case, console_unlock(); emits
* the output prior to releasing the lock.
*
* If there is output waiting, we wake /dev/kmsg and syslog() users.
*
* console_unlock(); may be called from any context.
*/
void console_unlock(void)
{
static char text[LOG_LINE_MAX + PREFIX_MAX];
static u64 seen_seq;
unsigned long flags;
bool wake_klogd = false;
bool retry;
if (console_suspended) {
up(&console_sem);
return;
}
console_may_schedule = 0;
/* flush buffered message fragment immediately to console */
console_cont_flush(text, sizeof(text));
again:
for (;;) {
struct log *msg;
size_t len;
int level;
raw_spin_lock_irqsave(&logbuf_lock, flags);
if (seen_seq != log_next_seq) {
wake_klogd = true;
seen_seq = log_next_seq;
}
if (console_seq < log_first_seq) {
/* messages are gone, move to first one */
console_seq = log_first_seq;
console_idx = log_first_idx;
console_prev = 0;
}
skip:
if (console_seq == log_next_seq)
break;
msg = log_from_idx(console_idx, true);
if (msg->flags & LOG_NOCONS) {
/*
* Skip record we have buffered and already printed
* directly to the console when we received it.
*/
console_idx = log_next(console_idx, true);
console_seq++;
/*
* We will get here again when we register a new
* CON_PRINTBUFFER console. Clear the flag so we
* will properly dump everything later.
*/
msg->flags &= ~LOG_NOCONS;
console_prev = msg->flags;
goto skip;
}
level = msg->level;
len = msg_print_text(msg, console_prev, false,
text, sizeof(text));
console_idx = log_next(console_idx, true);
console_seq++;
console_prev = msg->flags;
raw_spin_unlock(&logbuf_lock);
stop_critical_timings(); /* don't trace print latency */
call_console_drivers(level, text, len);
start_critical_timings();
local_irq_restore(flags);
}
console_locked = 0;
mutex_release(&console_lock_dep_map, 1, _RET_IP_);
/* Release the exclusive_console once it is used */
if (unlikely(exclusive_console))
exclusive_console = NULL;
raw_spin_unlock(&logbuf_lock);
up(&console_sem);
/*
* Someone could have filled up the buffer again, so re-check if there's
* something to flush. In case we cannot trylock the console_sem again,
* there's a new owner and the console_unlock() from them will do the
* flush, no worries.
*/
raw_spin_lock(&logbuf_lock);
retry = console_seq != log_next_seq;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
if (retry && console_trylock())
goto again;
if (wake_klogd)
wake_up_klogd();
}
EXPORT_SYMBOL(console_unlock);
/**
* console_conditional_schedule - yield the CPU if required
*
* If the console code is currently allowed to sleep, and
* if this CPU should yield the CPU to another task, do
* so here.
*
* Must be called within console_lock();.
*/
void __sched console_conditional_schedule(void)
{
if (console_may_schedule)
cond_resched();
}
EXPORT_SYMBOL(console_conditional_schedule);
void console_unblank(void)
{
struct console *c;
/*
* console_unblank can no longer be called in interrupt context unless
* oops_in_progress is set to 1..
*/
if (oops_in_progress) {
if (down_trylock(&console_sem) != 0)
return;
} else
console_lock();
console_locked = 1;
console_may_schedule = 0;
for_each_console(c)
if ((c->flags & CON_ENABLED) && c->unblank)
c->unblank();
console_unlock();
}
/*
* Return the console tty driver structure and its associated index
*/
struct tty_driver *console_device(int *index)
{
struct console *c;
struct tty_driver *driver = NULL;
console_lock();
for_each_console(c) {
if (!c->device)
continue;
driver = c->device(c, index);
if (driver)
break;
}
console_unlock();
return driver;
}
/*
* Prevent further output on the passed console device so that (for example)
* serial drivers can disable console output before suspending a port, and can
* re-enable output afterwards.
*/
void console_stop(struct console *console)
{
console_lock();
console->flags &= ~CON_ENABLED;
console_unlock();
}
EXPORT_SYMBOL(console_stop);
void console_start(struct console *console)
{
console_lock();
console->flags |= CON_ENABLED;
console_unlock();
}
EXPORT_SYMBOL(console_start);
static int __read_mostly keep_bootcon;
static int __init keep_bootcon_setup(char *str)
{
keep_bootcon = 1;
printk(KERN_INFO "debug: skip boot console de-registration.\n");
return 0;
}
early_param("keep_bootcon", keep_bootcon_setup);
/*
* The console driver calls this routine during kernel initialization
* to register the console printing procedure with printk() and to
* print any messages that were printed by the kernel before the
* console driver was initialized.
*
* This can happen pretty early during the boot process (because of
* early_printk) - sometimes before setup_arch() completes - be careful
* of what kernel features are used - they may not be initialised yet.
*
* There are two types of consoles - bootconsoles (early_printk) and
* "real" consoles (everything which is not a bootconsole) which are
* handled differently.
* - Any number of bootconsoles can be registered at any time.
* - As soon as a "real" console is registered, all bootconsoles
* will be unregistered automatically.
* - Once a "real" console is registered, any attempt to register a
* bootconsoles will be rejected
*/
void register_console(struct console *newcon)
{
int i;
unsigned long flags;
struct console *bcon = NULL;
/*
* before we register a new CON_BOOT console, make sure we don't
* already have a valid console
*/
if (console_drivers && newcon->flags & CON_BOOT) {
/* find the last or real console */
for_each_console(bcon) {
if (!(bcon->flags & CON_BOOT)) {
printk(KERN_INFO "Too late to register bootconsole %s%d\n",
newcon->name, newcon->index);
return;
}
}
}
if (console_drivers && console_drivers->flags & CON_BOOT)
bcon = console_drivers;
if (preferred_console < 0 || bcon || !console_drivers)
preferred_console = selected_console;
if (newcon->early_setup)
newcon->early_setup();
/*
* See if we want to use this console driver. If we
* didn't select a console we take the first one
* that registers here.
*/
if (preferred_console < 0) {
if (newcon->index < 0)
newcon->index = 0;
if (newcon->setup == NULL ||
newcon->setup(newcon, NULL) == 0) {
newcon->flags |= CON_ENABLED;
if (newcon->device) {
newcon->flags |= CON_CONSDEV;
preferred_console = 0;
}
}
}
/*
* See if this console matches one we selected on
* the command line.
*/
for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0];
i++) {
BUILD_BUG_ON(sizeof(console_cmdline[i].name) !=
sizeof(newcon->name));
if (strcmp(console_cmdline[i].name, newcon->name) != 0)
continue;
if (newcon->index >= 0 &&
newcon->index != console_cmdline[i].index)
continue;
if (newcon->index < 0)
newcon->index = console_cmdline[i].index;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
if (console_cmdline[i].brl_options) {
newcon->flags |= CON_BRL;
braille_register_console(newcon,
console_cmdline[i].index,
console_cmdline[i].options,
console_cmdline[i].brl_options);
return;
}
#endif
if (newcon->setup &&
newcon->setup(newcon, console_cmdline[i].options) != 0)
break;
newcon->flags |= CON_ENABLED;
newcon->index = console_cmdline[i].index;
if (i == selected_console) {
newcon->flags |= CON_CONSDEV;
preferred_console = selected_console;
}
break;
}
if (!(newcon->flags & CON_ENABLED))
return;
/*
* If we have a bootconsole, and are switching to a real console,
* don't print everything out again, since when the boot console, and
* the real console are the same physical device, it's annoying to
* see the beginning boot messages twice
*/
if (bcon && ((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV))
newcon->flags &= ~CON_PRINTBUFFER;
/*
* Put this console in the list - keep the
* preferred driver at the head of the list.
*/
console_lock();
if ((newcon->flags & CON_CONSDEV) || console_drivers == NULL) {
newcon->next = console_drivers;
console_drivers = newcon;
if (newcon->next)
newcon->next->flags &= ~CON_CONSDEV;
} else {
newcon->next = console_drivers->next;
console_drivers->next = newcon;
}
if (newcon->flags & CON_PRINTBUFFER) {
/*
* console_unlock(); will print out the buffered messages
* for us.
*/
raw_spin_lock_irqsave(&logbuf_lock, flags);
console_seq = syslog_seq;
console_idx = syslog_idx;
console_prev = syslog_prev;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
/*
* We're about to replay the log buffer. Only do this to the
* just-registered console to avoid excessive message spam to
* the already-registered consoles.
*/
exclusive_console = newcon;
}
console_unlock();
console_sysfs_notify();
/*
* By unregistering the bootconsoles after we enable the real console
* we get the "console xxx enabled" message on all the consoles -
* boot consoles, real consoles, etc - this is to ensure that end
* users know there might be something in the kernel's log buffer that
* went to the bootconsole (that they do not see on the real console)
*/
if (bcon &&
((newcon->flags & (CON_CONSDEV | CON_BOOT)) == CON_CONSDEV) &&
!keep_bootcon) {
/* we need to iterate through twice, to make sure we print
* everything out, before we unregister the console(s)
*/
printk(KERN_INFO "console [%s%d] enabled, bootconsole disabled\n",
newcon->name, newcon->index);
for_each_console(bcon)
if (bcon->flags & CON_BOOT)
unregister_console(bcon);
} else {
printk(KERN_INFO "%sconsole [%s%d] enabled\n",
(newcon->flags & CON_BOOT) ? "boot" : "" ,
newcon->name, newcon->index);
}
}
EXPORT_SYMBOL(register_console);
int unregister_console(struct console *console)
{
struct console *a, *b;
int res = 1;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
if (console->flags & CON_BRL)
return braille_unregister_console(console);
#endif
console_lock();
if (console_drivers == console) {
console_drivers=console->next;
res = 0;
} else if (console_drivers) {
for (a=console_drivers->next, b=console_drivers ;
a; b=a, a=b->next) {
if (a == console) {
b->next = a->next;
res = 0;
break;
}
}
}
/*
* If this isn't the last console and it has CON_CONSDEV set, we
* need to set it on the next preferred console.
*/
if (console_drivers != NULL && console->flags & CON_CONSDEV)
console_drivers->flags |= CON_CONSDEV;
console_unlock();
console_sysfs_notify();
return res;
}
EXPORT_SYMBOL(unregister_console);
static int __init printk_late_init(void)
{
struct console *con;
for_each_console(con) {
if (!keep_bootcon && con->flags & CON_BOOT) {
printk(KERN_INFO "turn off boot console %s%d\n",
con->name, con->index);
unregister_console(con);
}
}
hotcpu_notifier(console_cpu_notify, 0);
return 0;
}
late_initcall(printk_late_init);
#if defined CONFIG_PRINTK
/*
* Delayed printk version, for scheduler-internal messages:
*/
#define PRINTK_BUF_SIZE 512
#define PRINTK_PENDING_WAKEUP 0x01
#define PRINTK_PENDING_SCHED 0x02
static DEFINE_PER_CPU(int, printk_pending);
static DEFINE_PER_CPU(char [PRINTK_BUF_SIZE], printk_sched_buf);
static void wake_up_klogd_work_func(struct irq_work *irq_work)
{
int pending = __this_cpu_xchg(printk_pending, 0);
if (pending & PRINTK_PENDING_SCHED) {
char *buf = __get_cpu_var(printk_sched_buf);
printk(KERN_WARNING "[sched_delayed] %s", buf);
}
if (pending & PRINTK_PENDING_WAKEUP)
wake_up_interruptible(&log_wait);
}
static DEFINE_PER_CPU(struct irq_work, wake_up_klogd_work) = {
.func = wake_up_klogd_work_func,
.flags = IRQ_WORK_LAZY,
};
void wake_up_klogd(void)
{
preempt_disable();
if (waitqueue_active(&log_wait)) {
this_cpu_or(printk_pending, PRINTK_PENDING_WAKEUP);
irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
}
preempt_enable();
}
int printk_deferred(const char *fmt, ...)
{
unsigned long flags;
va_list args;
char *buf;
int r;
local_irq_save(flags);
buf = __get_cpu_var(printk_sched_buf);
va_start(args, fmt);
r = vsnprintf(buf, PRINTK_BUF_SIZE, fmt, args);
va_end(args);
__this_cpu_or(printk_pending, PRINTK_PENDING_SCHED);
irq_work_queue(&__get_cpu_var(wake_up_klogd_work));
local_irq_restore(flags);
return r;
}
/*
* printk rate limiting, lifted from the networking subsystem.
*
* This enforces a rate limit: not more than 10 kernel messages
* every 5s to make a denial-of-service attack impossible.
*/
DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
int __printk_ratelimit(const char *func)
{
return ___ratelimit(&printk_ratelimit_state, func);
}
EXPORT_SYMBOL(__printk_ratelimit);
/**
* printk_timed_ratelimit - caller-controlled printk ratelimiting
* @caller_jiffies: pointer to caller's state
* @interval_msecs: minimum interval between prints
*
* printk_timed_ratelimit() returns true if more than @interval_msecs
* milliseconds have elapsed since the last time printk_timed_ratelimit()
* returned true.
*/
bool printk_timed_ratelimit(unsigned long *caller_jiffies,
unsigned int interval_msecs)
{
if (*caller_jiffies == 0
|| !time_in_range(jiffies, *caller_jiffies,
*caller_jiffies
+ msecs_to_jiffies(interval_msecs))) {
*caller_jiffies = jiffies;
return true;
}
return false;
}
EXPORT_SYMBOL(printk_timed_ratelimit);
static DEFINE_SPINLOCK(dump_list_lock);
static LIST_HEAD(dump_list);
/**
* kmsg_dump_register - register a kernel log dumper.
* @dumper: pointer to the kmsg_dumper structure
*
* Adds a kernel log dumper to the system. The dump callback in the
* structure will be called when the kernel oopses or panics and must be
* set. Returns zero on success and %-EINVAL or %-EBUSY otherwise.
*/
int kmsg_dump_register(struct kmsg_dumper *dumper)
{
unsigned long flags;
int err = -EBUSY;
/* The dump callback needs to be set */
if (!dumper->dump)
return -EINVAL;
spin_lock_irqsave(&dump_list_lock, flags);
/* Don't allow registering multiple times */
if (!dumper->registered) {
dumper->registered = 1;
list_add_tail_rcu(&dumper->list, &dump_list);
err = 0;
}
spin_unlock_irqrestore(&dump_list_lock, flags);
return err;
}
EXPORT_SYMBOL_GPL(kmsg_dump_register);
/**
* kmsg_dump_unregister - unregister a kmsg dumper.
* @dumper: pointer to the kmsg_dumper structure
*
* Removes a dump device from the system. Returns zero on success and
* %-EINVAL otherwise.
*/
int kmsg_dump_unregister(struct kmsg_dumper *dumper)
{
unsigned long flags;
int err = -EINVAL;
spin_lock_irqsave(&dump_list_lock, flags);
if (dumper->registered) {
dumper->registered = 0;
list_del_rcu(&dumper->list);
err = 0;
}
spin_unlock_irqrestore(&dump_list_lock, flags);
synchronize_rcu();
return err;
}
EXPORT_SYMBOL_GPL(kmsg_dump_unregister);
static bool always_kmsg_dump;
module_param_named(always_kmsg_dump, always_kmsg_dump, bool, S_IRUGO | S_IWUSR);
/**
* kmsg_dump - dump kernel log to kernel message dumpers.
* @reason: the reason (oops, panic etc) for dumping
*
* Call each of the registered dumper's dump() callback, which can
* retrieve the kmsg records with kmsg_dump_get_line() or
* kmsg_dump_get_buffer().
*/
void kmsg_dump(enum kmsg_dump_reason reason)
{
struct kmsg_dumper *dumper;
unsigned long flags;
if ((reason > KMSG_DUMP_OOPS) && !always_kmsg_dump)
return;
rcu_read_lock();
list_for_each_entry_rcu(dumper, &dump_list, list) {
if (dumper->max_reason && reason > dumper->max_reason)
continue;
/* initialize iterator with data about the stored records */
dumper->active = true;
raw_spin_lock_irqsave(&logbuf_lock, flags);
dumper->cur_seq = clear_seq;
dumper->cur_idx = clear_idx;
dumper->next_seq = log_next_seq;
dumper->next_idx = log_next_idx;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
/* invoke dumper which will iterate over records */
dumper->dump(dumper, reason);
/* reset iterator */
dumper->active = false;
}
rcu_read_unlock();
}
/**
* kmsg_dump_get_line_nolock - retrieve one kmsg log line (unlocked version)
* @dumper: registered kmsg dumper
* @syslog: include the "<4>" prefixes
* @line: buffer to copy the line to
* @size: maximum size of the buffer
* @len: length of line placed into buffer
*
* Start at the beginning of the kmsg buffer, with the oldest kmsg
* record, and copy one record into the provided buffer.
*
* Consecutive calls will return the next available record moving
* towards the end of the buffer with the youngest messages.
*
* A return value of FALSE indicates that there are no more records to
* read.
*
* The function is similar to kmsg_dump_get_line(), but grabs no locks.
*/
bool kmsg_dump_get_line_nolock(struct kmsg_dumper *dumper, bool syslog,
char *line, size_t size, size_t *len)
{
struct log *msg;
size_t l = 0;
bool ret = false;
if (!dumper->active)
goto out;
if (dumper->cur_seq < log_first_seq) {
/* messages are gone, move to first available one */
dumper->cur_seq = log_first_seq;
dumper->cur_idx = log_first_idx;
}
/* last entry */
if (dumper->cur_seq >= log_next_seq)
goto out;
msg = log_from_idx(dumper->cur_idx, true);
l = msg_print_text(msg, 0, syslog, line, size);
dumper->cur_idx = log_next(dumper->cur_idx, true);
dumper->cur_seq++;
ret = true;
out:
if (len)
*len = l;
return ret;
}
/**
* kmsg_dump_get_line - retrieve one kmsg log line
* @dumper: registered kmsg dumper
* @syslog: include the "<4>" prefixes
* @line: buffer to copy the line to
* @size: maximum size of the buffer
* @len: length of line placed into buffer
*
* Start at the beginning of the kmsg buffer, with the oldest kmsg
* record, and copy one record into the provided buffer.
*
* Consecutive calls will return the next available record moving
* towards the end of the buffer with the youngest messages.
*
* A return value of FALSE indicates that there are no more records to
* read.
*/
bool kmsg_dump_get_line(struct kmsg_dumper *dumper, bool syslog,
char *line, size_t size, size_t *len)
{
unsigned long flags;
bool ret;
raw_spin_lock_irqsave(&logbuf_lock, flags);
ret = kmsg_dump_get_line_nolock(dumper, syslog, line, size, len);
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(kmsg_dump_get_line);
/**
* kmsg_dump_get_buffer - copy kmsg log lines
* @dumper: registered kmsg dumper
* @syslog: include the "<4>" prefixes
* @buf: buffer to copy the line to
* @size: maximum size of the buffer
* @len: length of line placed into buffer
*
* Start at the end of the kmsg buffer and fill the provided buffer
* with as many of the the *youngest* kmsg records that fit into it.
* If the buffer is large enough, all available kmsg records will be
* copied with a single call.
*
* Consecutive calls will fill the buffer with the next block of
* available older records, not including the earlier retrieved ones.
*
* A return value of FALSE indicates that there are no more records to
* read.
*/
bool kmsg_dump_get_buffer(struct kmsg_dumper *dumper, bool syslog,
char *buf, size_t size, size_t *len)
{
unsigned long flags;
u64 seq;
u32 idx;
u64 next_seq;
u32 next_idx;
enum log_flags prev;
size_t l = 0;
bool ret = false;
if (!dumper->active)
goto out;
raw_spin_lock_irqsave(&logbuf_lock, flags);
if (dumper->cur_seq < log_first_seq) {
/* messages are gone, move to first available one */
dumper->cur_seq = log_first_seq;
dumper->cur_idx = log_first_idx;
}
/* last entry */
if (dumper->cur_seq >= dumper->next_seq) {
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
goto out;
}
/* calculate length of entire buffer */
seq = dumper->cur_seq;
idx = dumper->cur_idx;
prev = 0;
while (seq < dumper->next_seq) {
struct log *msg = log_from_idx(idx, true);
l += msg_print_text(msg, prev, true, NULL, 0);
idx = log_next(idx, true);
seq++;
prev = msg->flags;
}
/* move first record forward until length fits into the buffer */
seq = dumper->cur_seq;
idx = dumper->cur_idx;
prev = 0;
while (l > size && seq < dumper->next_seq) {
struct log *msg = log_from_idx(idx, true);
l -= msg_print_text(msg, prev, true, NULL, 0);
idx = log_next(idx, true);
seq++;
prev = msg->flags;
}
/* last message in next interation */
next_seq = seq;
next_idx = idx;
l = 0;
prev = 0;
while (seq < dumper->next_seq) {
struct log *msg = log_from_idx(idx, true);
l += msg_print_text(msg, prev, syslog, buf + l, size - l);
idx = log_next(idx, true);
seq++;
prev = msg->flags;
}
dumper->next_seq = next_seq;
dumper->next_idx = next_idx;
ret = true;
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
out:
if (len)
*len = l;
return ret;
}
EXPORT_SYMBOL_GPL(kmsg_dump_get_buffer);
/**
* kmsg_dump_rewind_nolock - reset the interator (unlocked version)
* @dumper: registered kmsg dumper
*
* Reset the dumper's iterator so that kmsg_dump_get_line() and
* kmsg_dump_get_buffer() can be called again and used multiple
* times within the same dumper.dump() callback.
*
* The function is similar to kmsg_dump_rewind(), but grabs no locks.
*/
void kmsg_dump_rewind_nolock(struct kmsg_dumper *dumper)
{
dumper->cur_seq = clear_seq;
dumper->cur_idx = clear_idx;
dumper->next_seq = log_next_seq;
dumper->next_idx = log_next_idx;
}
/**
* kmsg_dump_rewind - reset the interator
* @dumper: registered kmsg dumper
*
* Reset the dumper's iterator so that kmsg_dump_get_line() and
* kmsg_dump_get_buffer() can be called again and used multiple
* times within the same dumper.dump() callback.
*/
void kmsg_dump_rewind(struct kmsg_dumper *dumper)
{
unsigned long flags;
raw_spin_lock_irqsave(&logbuf_lock, flags);
kmsg_dump_rewind_nolock(dumper);
raw_spin_unlock_irqrestore(&logbuf_lock, flags);
}
EXPORT_SYMBOL_GPL(kmsg_dump_rewind);
static char dump_stack_arch_desc_str[128];
/**
* dump_stack_set_arch_desc - set arch-specific str to show with task dumps
* @fmt: printf-style format string
* @...: arguments for the format string
*
* The configured string will be printed right after utsname during task
* dumps. Usually used to add arch-specific system identifiers. If an
* arch wants to make use of such an ID string, it should initialize this
* as soon as possible during boot.
*/
void __init dump_stack_set_arch_desc(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vsnprintf(dump_stack_arch_desc_str, sizeof(dump_stack_arch_desc_str),
fmt, args);
va_end(args);
}
/**
* dump_stack_print_info - print generic debug info for dump_stack()
* @log_lvl: log level
*
* Arch-specific dump_stack() implementations can use this function to
* print out the same debug information as the generic dump_stack().
*/
void dump_stack_print_info(const char *log_lvl)
{
printk("%sCPU: %d PID: %d Comm: %.20s %s %s %.*s\n",
log_lvl, raw_smp_processor_id(), current->pid, current->comm,
print_tainted(), init_utsname()->release,
(int)strcspn(init_utsname()->version, " "),
init_utsname()->version);
if (dump_stack_arch_desc_str[0] != '\0')
printk("%sHardware name: %s\n",
log_lvl, dump_stack_arch_desc_str);
print_worker_info(log_lvl, current);
}
/**
* show_regs_print_info - print generic debug info for show_regs()
* @log_lvl: log level
*
* show_regs() implementations can use this function to print out generic
* debug information.
*/
void show_regs_print_info(const char *log_lvl)
{
dump_stack_print_info(log_lvl);
printk("%stask: %p ti: %p task.ti: %p\n",
log_lvl, current, current_thread_info(),
task_thread_info(current));
}
#endif
|
JustAkan/jolla-kernel_bullhead
|
kernel/printk.c
|
C
|
gpl-2.0
| 81,658 |
<?php
class MVCGrid_Export extends MVCGrid {
public $export_csv = true;
public $export_xls = true;
public $export_pdf = true;
public $can_add = true;
function init(){
parent::init();
$this->api->addHook("pre-render", array($this, "add_buttons"));
}
function add_buttons(){
if ($this->can_add){
$this->add_button = $this->addButton("Add");
$this->add_button->js('click')->univ()->frameURL("Add new", $this->api->getDestinationURL("./add"));
}
if ($this->export_csv){
$this->addButton("Export CSV")->js("click")->univ()->redirect($this->api->getDestinationURL(null,
array("export_csv" => $this->name)));
}
if ($this->export_pdf){
$this->addButton("Export PDF")->js("click")->univ()->redirect($this->api->getDestinationURL(null,
array("export_pdf" => $this->name)));
}
if ($this->export_xls){
$this->addButton("Export XLS")->js("click")->univ()->redirect($this->api->getDestinationURL(null,
array("export_xls" => $this->name)));
}
//$this->js(true)->univ()->ajaxifyLinks();
}
function setModel($a,$b=null){
$m = parent::setModel($a,$b);
if ($_GET["export_csv"] == $this->name){
/* format csv, export */
$export = $this->add("Export");
$data = $export->getDataFromMVCGrid($this);
$export->setHeaderModel($a);
$export->convertToCSV($data);
$export->exportCSV("export.csv");
}
if ($_GET["export_pdf"] == $this->name){
/* format csv, export */
$export = $this->add("Export");
$data = $export->getDataFromMVCGrid($this);
$export->setHeaderModel($a);
$export->convertToPDF($data);
$export->exportPDF("export.pdf");
}
if ($_GET["export_xls"] == $this->name){
/* format csv, export */
$export = $this->add("Export");
$data = $export->getDataFromMVCGrid($this);
$export->setHeaderModel($a);
$export->setConverterTemplate("export/xls");
$export->convertToXLS($data);
$export->exportXLS("export.xls");
}
$this->addColumn('delete','delete');
$this->owner->js('reload',$this->js()->reload());
return $m;
}
}
|
gowrav-vishwakarma/ffm
|
users/atk4-addons/mvc/MVCGrid/Export.php
|
PHP
|
gpl-2.0
| 2,455 |
/* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/
* Copyright : Copyright © Nequeo Pty Ltd 2012 http://www.nequeo.com.au/
*
* File :
* Purpose :
*
*/
#region Nequeo Pty Ltd License
/*
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.
*/
#endregion
namespace Nequeo.Net.Core.Messaging
{
using System;
using System.Diagnostics.Contracts;
using System.IO;
/// <summary>
/// An interface implemented by <see cref="DataBag"/>-derived types that support binary serialization.
/// </summary>
[ContractClass(typeof(IStreamSerializingDataBaContract))]
public interface IStreamSerializingDataBag {
/// <summary>
/// Serializes the instance to the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
void Serialize(Stream stream);
/// <summary>
/// Initializes the fields on this instance from the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
void Deserialize(Stream stream);
}
/// <summary>
/// Code Contract for the <see cref="IStreamSerializingDataBag"/> interface.
/// </summary>
[ContractClassFor(typeof(IStreamSerializingDataBag))]
public abstract class IStreamSerializingDataBaContract : IStreamSerializingDataBag
{
/// <summary>
/// Serializes the instance to the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
void IStreamSerializingDataBag.Serialize(Stream stream) {
Contract.Requires(stream != null);
Contract.Requires(stream.CanWrite);
throw new NotImplementedException();
}
/// <summary>
/// Initializes the fields on this instance from the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
void IStreamSerializingDataBag.Deserialize(Stream stream) {
Contract.Requires(stream != null);
Contract.Requires(stream.CanRead);
throw new NotImplementedException();
}
}
}
|
drazenzadravec/nequeo
|
Source/Components/Net/Nequeo.Net.Core/Nequeo.Net.Core/Core/Messaging/IStreamSerializingDataBag.cs
|
C#
|
gpl-2.0
| 3,053 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Sales
* @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Enter description here ...
*
* @category Mage
* @package Mage_Sales
* @author Magento Core Team <[email protected]>
*/
class Mage_Sales_Model_Mysql4_Order_Invoice_Attribute_Backend_Item
extends Mage_Sales_Model_Resource_Order_Invoice_Attribute_Backend_Item
{
}
|
miguelangelramirez/magento.dev
|
app/code/core/Mage/Sales/Model/Mysql4/Order/Invoice/Attribute/Backend/Item.php
|
PHP
|
gpl-2.0
| 1,257 |
//>>built
define("dojox/mvc/getPlainValue",["dojo/_base/array","dojo/_base/lang","dojo/Stateful"],function(_1,_2,_3){
var _4={getType:function(v){
return _2.isArray(v)?"array":v!=null&&{}.toString.call(v)=="[object Object]"?"object":"value";
},getPlainArray:function(a){
return _1.map(a,function(_5){
return _6(_5,this);
},this);
},getPlainObject:function(o){
var _7={};
for(var s in o){
if(!(s in _3.prototype)&&s!="_watchCallbacks"){
_7[s]=_6(o[s],this);
}
}
return _7;
},getPlainValue:function(v){
return v;
}};
var _6=function(_8,_9){
return (_9||_6)["getPlain"+(_9||_6).getType(_8).replace(/^[a-z]/,function(c){
return c.toUpperCase();
})](_8);
};
return _2.setObject("dojox.mvc.getPlainValue",_2.mixin(_6,_4));
});
|
hariomkumarmth/champaranexpress
|
wp-content/plugins/dojo/dojox/mvc/getPlainValue.js
|
JavaScript
|
gpl-2.0
| 747 |
#ifndef __TERM_H
#define __TERM_H
typedef struct _TERM_WINDOW TERM_WINDOW;
/* text attributes */
#define ATTR_RESETFG 0x0100
#define ATTR_RESETBG 0x0200
#define ATTR_BOLD 0x0400
#define ATTR_BLINK 0x0800
#define ATTR_UNDERLINE 0x1000
#define ATTR_REVERSE 0x2000
#define ATTR_RESET (ATTR_RESETFG|ATTR_RESETBG)
#define ATTR_NOCOLORS (ATTR_UNDERLINE|ATTR_REVERSE)
/* terminal types */
#define TERM_TYPE_8BIT 0 /* normal 8bit text */
#define TERM_TYPE_UTF8 1
#define TERM_TYPE_BIG5 2
typedef guint32 unichar;
extern TERM_WINDOW *root_window;
extern int term_width, term_height;
extern int term_use_colors, term_type, term_detached;
/* Initialize / deinitialize terminal */
int term_init(void);
void term_deinit(void);
/* Gets the current terminal size, returns TRUE if ok. */
int term_get_size(int *width, int *height);
/* Resize terminal - if width or height is negative,
the new size is unknown and should be figured out somehow */
void term_resize(int width, int height);
void term_resize_final(int width, int height);
/* Resize the terminal if needed */
void term_resize_dirty(void);
/* Returns TRUE if terminal has colors */
int term_has_colors(void);
/* Force the colors on any way you can */
void term_force_colors(int set);
/* Clear screen */
void term_clear(void);
/* Beep */
void term_beep(void);
/* Create a new window in terminal */
TERM_WINDOW *term_window_create(int x, int y, int width, int height);
/* Destroy a terminal window */
void term_window_destroy(TERM_WINDOW *window);
/* Move/resize window */
void term_window_move(TERM_WINDOW *window, int x, int y,
int width, int height);
/* Clear window */
void term_window_clear(TERM_WINDOW *window);
/* Scroll window up/down */
void term_window_scroll(TERM_WINDOW *window, int count);
void term_set_color(TERM_WINDOW *window, int col);
void term_move(TERM_WINDOW *window, int x, int y);
void term_addch(TERM_WINDOW *window, int chr);
void term_add_unichar(TERM_WINDOW *window, unichar chr);
void term_addstr(TERM_WINDOW *window, const char *str);
void term_clrtoeol(TERM_WINDOW *window);
void term_move_cursor(int x, int y);
void term_refresh_freeze(void);
void term_refresh_thaw(void);
void term_refresh(TERM_WINDOW *window);
/* Automatically detach irssi when terminal is lost */
void term_auto_detach(int set);
void term_detach(void);
void term_attach(FILE *in, FILE *out);
void term_stop(void);
/* keyboard input handling */
void term_set_input_type(int type);
int term_gets(unichar *buffer, int size);
/* internal */
void term_common_init(void);
void term_common_deinit(void);
#endif
|
ipwndev/DSLinux-Mirror
|
user/irssi/src/src/fe-text/term.h
|
C
|
gpl-2.0
| 2,591 |
namespace MrCMS.Web.Apps.Ecommerce.Areas.Admin.Services.NopImport.Processors
{
public interface IImportRegionData
{
string ProcessRegions(NopCommerceDataReader importParams, NopImportContext nopImportContext);
}
}
|
MaiLT/Ecommerce
|
MrCMS.Web/Apps/Ecommerce/Areas/Admin/Services/NopImport/Processors/IImportRegionData.cs
|
C#
|
gpl-2.0
| 233 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_Compute_UrlMapsScopedList extends Google_Collection
{
protected $collection_key = 'urlMaps';
protected $urlMapsType = 'Google_Service_Compute_UrlMap';
protected $urlMapsDataType = 'array';
protected $warningType = 'Google_Service_Compute_UrlMapsScopedListWarning';
protected $warningDataType = '';
/**
* @param Google_Service_Compute_UrlMap[]
*/
public function setUrlMaps($urlMaps)
{
$this->urlMaps = $urlMaps;
}
/**
* @return Google_Service_Compute_UrlMap[]
*/
public function getUrlMaps()
{
return $this->urlMaps;
}
/**
* @param Google_Service_Compute_UrlMapsScopedListWarning
*/
public function setWarning(Google_Service_Compute_UrlMapsScopedListWarning $warning)
{
$this->warning = $warning;
}
/**
* @return Google_Service_Compute_UrlMapsScopedListWarning
*/
public function getWarning()
{
return $this->warning;
}
}
|
palasthotel/grid-wordpress-box-social
|
vendor/google/apiclient-services/src/Google/Service/Compute/UrlMapsScopedList.php
|
PHP
|
gpl-2.0
| 1,524 |
/***************************************************************************
qgsellipsesymbollayerwidget.cpp
---------------------
begin : June 2011
copyright : (C) 2011 by Marco Hugentobler
email : marco dot hugentobler at sourcepole dot ch
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsellipsesymbollayerwidget.h"
#include "qgsellipsesymbollayer.h"
#include "qgsvectorlayer.h"
#include <QColorDialog>
QgsEllipseSymbolLayerWidget::QgsEllipseSymbolLayerWidget( QgsVectorLayer *vl, QWidget *parent )
: QgsSymbolLayerWidget( parent, vl )
{
setupUi( this );
connect( mShapeListWidget, &QListWidget::itemSelectionChanged, this, &QgsEllipseSymbolLayerWidget::mShapeListWidget_itemSelectionChanged );
connect( mWidthSpinBox, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsEllipseSymbolLayerWidget::mWidthSpinBox_valueChanged );
connect( mHeightSpinBox, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsEllipseSymbolLayerWidget::mHeightSpinBox_valueChanged );
connect( mRotationSpinBox, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsEllipseSymbolLayerWidget::mRotationSpinBox_valueChanged );
connect( mStrokeStyleComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsEllipseSymbolLayerWidget::mStrokeStyleComboBox_currentIndexChanged );
connect( mStrokeWidthSpinBox, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsEllipseSymbolLayerWidget::mStrokeWidthSpinBox_valueChanged );
connect( btnChangeColorStroke, &QgsColorButton::colorChanged, this, &QgsEllipseSymbolLayerWidget::btnChangeColorStroke_colorChanged );
connect( btnChangeColorFill, &QgsColorButton::colorChanged, this, &QgsEllipseSymbolLayerWidget::btnChangeColorFill_colorChanged );
connect( mSymbolWidthUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsEllipseSymbolLayerWidget::mSymbolWidthUnitWidget_changed );
connect( mStrokeWidthUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsEllipseSymbolLayerWidget::mStrokeWidthUnitWidget_changed );
connect( mSymbolHeightUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsEllipseSymbolLayerWidget::mSymbolHeightUnitWidget_changed );
connect( mOffsetUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsEllipseSymbolLayerWidget::mOffsetUnitWidget_changed );
connect( mHorizontalAnchorComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsEllipseSymbolLayerWidget::mHorizontalAnchorComboBox_currentIndexChanged );
connect( mVerticalAnchorComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsEllipseSymbolLayerWidget::mVerticalAnchorComboBox_currentIndexChanged );
mSymbolWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
mSymbolHeightUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
mStrokeWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
mOffsetUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
btnChangeColorFill->setAllowOpacity( true );
btnChangeColorFill->setColorDialogTitle( tr( "Select Fill Color" ) );
btnChangeColorFill->setContext( QStringLiteral( "symbology" ) );
btnChangeColorFill->setShowNoColor( true );
btnChangeColorFill->setNoColorString( tr( "Transparent Fill" ) );
btnChangeColorStroke->setAllowOpacity( true );
btnChangeColorStroke->setColorDialogTitle( tr( "Select Stroke Color" ) );
btnChangeColorStroke->setContext( QStringLiteral( "symbology" ) );
btnChangeColorStroke->setShowNoColor( true );
btnChangeColorStroke->setNoColorString( tr( "Transparent Stroke" ) );
mFillColorDDBtn->registerLinkedWidget( btnChangeColorFill );
mStrokeColorDDBtn->registerLinkedWidget( btnChangeColorStroke );
spinOffsetX->setClearValue( 0.0 );
spinOffsetY->setClearValue( 0.0 );
mRotationSpinBox->setClearValue( 0.0 );
QStringList names;
names << QStringLiteral( "circle" ) << QStringLiteral( "rectangle" ) << QStringLiteral( "diamond" ) << QStringLiteral( "cross" ) << QStringLiteral( "triangle" ) << QStringLiteral( "right_half_triangle" ) << QStringLiteral( "left_half_triangle" ) << QStringLiteral( "semi_circle" );
int size = mShapeListWidget->iconSize().width();
size = std::max( 30, static_cast< int >( std::round( Qgis::UI_SCALE_FACTOR * fontMetrics().width( QStringLiteral( "XXX" ) ) ) ) );
mShapeListWidget->setGridSize( QSize( size * 1.2, size * 1.2 ) );
mShapeListWidget->setIconSize( QSize( size, size ) );
double markerSize = size * 0.8;
const auto constNames = names;
for ( const QString &name : constNames )
{
QgsEllipseSymbolLayer *lyr = new QgsEllipseSymbolLayer();
lyr->setSymbolWidthUnit( QgsUnitTypes::RenderPixels );
lyr->setSymbolHeightUnit( QgsUnitTypes::RenderPixels );
lyr->setSymbolName( name );
lyr->setStrokeColor( QColor( 0, 0, 0 ) );
lyr->setFillColor( QColor( 200, 200, 200 ) );
lyr->setSymbolWidth( markerSize );
lyr->setSymbolHeight( markerSize * 0.75 );
QIcon icon = QgsSymbolLayerUtils::symbolLayerPreviewIcon( lyr, QgsUnitTypes::RenderPixels, QSize( size, size ) );
QListWidgetItem *item = new QListWidgetItem( icon, QString(), mShapeListWidget );
item->setToolTip( name );
item->setData( Qt::UserRole, name );
delete lyr;
}
// show at least 2 rows (only 1 row is required, but looks too cramped)
mShapeListWidget->setMinimumHeight( mShapeListWidget->gridSize().height() * 2.1 );
connect( spinOffsetX, static_cast < void ( QgsDoubleSpinBox::* )( double ) > ( &QgsDoubleSpinBox::valueChanged ), this, &QgsEllipseSymbolLayerWidget::setOffset );
connect( spinOffsetY, static_cast < void ( QgsDoubleSpinBox::* )( double ) > ( &QgsDoubleSpinBox::valueChanged ), this, &QgsEllipseSymbolLayerWidget::setOffset );
connect( cboJoinStyle, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsEllipseSymbolLayerWidget::penJoinStyleChanged );
}
void QgsEllipseSymbolLayerWidget::setSymbolLayer( QgsSymbolLayer *layer )
{
if ( !layer || layer->layerType() != QLatin1String( "EllipseMarker" ) )
{
return;
}
mLayer = static_cast<QgsEllipseSymbolLayer *>( layer );
mWidthSpinBox->setValue( mLayer->symbolWidth() );
mHeightSpinBox->setValue( mLayer->symbolHeight() );
mRotationSpinBox->setValue( mLayer->angle() );
mStrokeStyleComboBox->setPenStyle( mLayer->strokeStyle() );
mStrokeWidthSpinBox->setValue( mLayer->strokeWidth() );
btnChangeColorStroke->setColor( mLayer->strokeColor() );
btnChangeColorFill->setColor( mLayer->fillColor() );
QList<QListWidgetItem *> symbolItemList = mShapeListWidget->findItems( mLayer->symbolName(), Qt::MatchExactly );
if ( !symbolItemList.isEmpty() )
{
mShapeListWidget->setCurrentItem( symbolItemList.at( 0 ) );
}
//set combo entries to current values
blockComboSignals( true );
mSymbolWidthUnitWidget->setUnit( mLayer->symbolWidthUnit() );
mSymbolWidthUnitWidget->setMapUnitScale( mLayer->symbolWidthMapUnitScale() );
mStrokeWidthUnitWidget->setUnit( mLayer->strokeWidthUnit() );
mStrokeWidthUnitWidget->setMapUnitScale( mLayer->strokeWidthMapUnitScale() );
mSymbolHeightUnitWidget->setUnit( mLayer->symbolHeightUnit() );
mSymbolHeightUnitWidget->setMapUnitScale( mLayer->symbolHeightMapUnitScale() );
mOffsetUnitWidget->setUnit( mLayer->offsetUnit() );
mOffsetUnitWidget->setMapUnitScale( mLayer->offsetMapUnitScale() );
QPointF offsetPt = mLayer->offset();
spinOffsetX->setValue( offsetPt.x() );
spinOffsetY->setValue( offsetPt.y() );
mHorizontalAnchorComboBox->setCurrentIndex( mLayer->horizontalAnchorPoint() );
mVerticalAnchorComboBox->setCurrentIndex( mLayer->verticalAnchorPoint() );
cboJoinStyle->setPenJoinStyle( mLayer->penJoinStyle() );
blockComboSignals( false );
registerDataDefinedButton( mSymbolWidthDDBtn, QgsSymbolLayer::PropertyWidth );
registerDataDefinedButton( mSymbolHeightDDBtn, QgsSymbolLayer::PropertyHeight );
registerDataDefinedButton( mRotationDDBtn, QgsSymbolLayer::PropertyAngle );
registerDataDefinedButton( mStrokeWidthDDBtn, QgsSymbolLayer::PropertyStrokeWidth );
registerDataDefinedButton( mFillColorDDBtn, QgsSymbolLayer::PropertyFillColor );
registerDataDefinedButton( mStrokeColorDDBtn, QgsSymbolLayer::PropertyStrokeColor );
registerDataDefinedButton( mStrokeStyleDDBtn, QgsSymbolLayer::PropertyStrokeStyle );
registerDataDefinedButton( mJoinStyleDDBtn, QgsSymbolLayer::PropertyJoinStyle );
registerDataDefinedButton( mShapeDDBtn, QgsSymbolLayer::PropertyName );
registerDataDefinedButton( mOffsetDDBtn, QgsSymbolLayer::PropertyOffset );
registerDataDefinedButton( mHorizontalAnchorDDBtn, QgsSymbolLayer::PropertyHorizontalAnchor );
registerDataDefinedButton( mVerticalAnchorDDBtn, QgsSymbolLayer::PropertyVerticalAnchor );
}
QgsSymbolLayer *QgsEllipseSymbolLayerWidget::symbolLayer()
{
return mLayer;
}
void QgsEllipseSymbolLayerWidget::mShapeListWidget_itemSelectionChanged()
{
if ( mLayer )
{
QListWidgetItem *item = mShapeListWidget->currentItem();
if ( item )
{
mLayer->setSymbolName( item->data( Qt::UserRole ).toString() );
emit changed();
}
}
}
void QgsEllipseSymbolLayerWidget::mWidthSpinBox_valueChanged( double d )
{
if ( mLayer )
{
mLayer->setSymbolWidth( d );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::mHeightSpinBox_valueChanged( double d )
{
if ( mLayer )
{
mLayer->setSymbolHeight( d );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::mRotationSpinBox_valueChanged( double d )
{
if ( mLayer )
{
mLayer->setAngle( d );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::mStrokeStyleComboBox_currentIndexChanged( int index )
{
Q_UNUSED( index );
if ( mLayer )
{
mLayer->setStrokeStyle( mStrokeStyleComboBox->penStyle() );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::mStrokeWidthSpinBox_valueChanged( double d )
{
if ( mLayer )
{
mLayer->setStrokeWidth( d );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::btnChangeColorStroke_colorChanged( const QColor &newColor )
{
if ( !mLayer )
{
return;
}
mLayer->setStrokeColor( newColor );
emit changed();
}
void QgsEllipseSymbolLayerWidget::btnChangeColorFill_colorChanged( const QColor &newColor )
{
if ( !mLayer )
{
return;
}
mLayer->setFillColor( newColor );
emit changed();
}
void QgsEllipseSymbolLayerWidget::mSymbolWidthUnitWidget_changed()
{
if ( mLayer )
{
mLayer->setSymbolWidthUnit( mSymbolWidthUnitWidget->unit() );
mLayer->setSymbolWidthMapUnitScale( mSymbolWidthUnitWidget->getMapUnitScale() );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::mStrokeWidthUnitWidget_changed()
{
if ( mLayer )
{
mLayer->setStrokeWidthUnit( mStrokeWidthUnitWidget->unit() );
mLayer->setStrokeWidthMapUnitScale( mStrokeWidthUnitWidget->getMapUnitScale() );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::mSymbolHeightUnitWidget_changed()
{
if ( mLayer )
{
mLayer->setSymbolHeightUnit( mSymbolHeightUnitWidget->unit() );
mLayer->setSymbolHeightMapUnitScale( mSymbolHeightUnitWidget->getMapUnitScale() );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::mOffsetUnitWidget_changed()
{
if ( mLayer )
{
mLayer->setOffsetUnit( mOffsetUnitWidget->unit() );
mLayer->setOffsetMapUnitScale( mOffsetUnitWidget->getMapUnitScale() );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::penJoinStyleChanged()
{
mLayer->setPenJoinStyle( cboJoinStyle->penJoinStyle() );
emit changed();
}
void QgsEllipseSymbolLayerWidget::blockComboSignals( bool block )
{
mSymbolWidthUnitWidget->blockSignals( block );
mStrokeWidthUnitWidget->blockSignals( block );
mSymbolHeightUnitWidget->blockSignals( block );
mHorizontalAnchorComboBox->blockSignals( block );
mVerticalAnchorComboBox->blockSignals( block );
mSymbolWidthUnitWidget->blockSignals( block );
mStrokeWidthUnitWidget->blockSignals( block );
mSymbolHeightUnitWidget->blockSignals( block );
mOffsetUnitWidget->blockSignals( block );
cboJoinStyle->blockSignals( block );
}
void QgsEllipseSymbolLayerWidget::mHorizontalAnchorComboBox_currentIndexChanged( int index )
{
if ( mLayer )
{
mLayer->setHorizontalAnchorPoint( ( QgsMarkerSymbolLayer::HorizontalAnchorPoint ) index );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::mVerticalAnchorComboBox_currentIndexChanged( int index )
{
if ( mLayer )
{
mLayer->setVerticalAnchorPoint( ( QgsMarkerSymbolLayer::VerticalAnchorPoint ) index );
emit changed();
}
}
void QgsEllipseSymbolLayerWidget::setOffset()
{
mLayer->setOffset( QPointF( spinOffsetX->value(), spinOffsetY->value() ) );
emit changed();
}
|
m-kuhn/QGIS
|
src/gui/symbology/qgsellipsesymbollayerwidget.cpp
|
C++
|
gpl-2.0
| 14,426 |
# Copyright (c) 2014 ACS, ICT.
# All rights reserved.
#
# Author: Jiuyue Ma
import optparse
import sys
import m5
from m5.defines import buildEnv
from m5.objects import *
from m5.util import addToPath, fatal
addToPath('common')
addToPath('../../gem5-latest/configs/common')
from FSConfig import *
from SysPaths import *
from Benchmarks import *
import Simulation
import CacheConfig
import MemConfig
from Caches import *
import Options
class CPNetwork(NoncoherentXBar):
fake_responder = IsaFake(pio_addr=0, pio_size=Addr('16MB'))
default = Self.fake_responder.pio
#GlobalManager configurations
GMSysConfig = SysConfig(disk="PARDg5GM.img", mem="32MB")
GMBootOSFlags = 'earlyprintk=ttyS0 console=ttyS0 lpj=7999923 ' + \
'root=/dev/sda1 no_timer_check init=/sbin/init'
GMKernel = binary('linux-2.6.28.4-prm/vmlinux')
GMCPUClass = AtomicSimpleCPU
FutureClass = None
gm_mem_mode = 'atomic'
GMMemClass = SimpleMemory
class GMMemory(SimpleMemory):
range = AddrRange('32MB')
def build_gm_system():
self = makeLinuxX86System(gm_mem_mode, 1, GMSysConfig)
# IntelMPTable
self.intel_mp_table.oem_id = "FSG"
self.intel_mp_table.product_id = "PARDg5-V.r0"
# Config kernel & boot flags
self.boot_osflags = GMBootOSFlags
self.kernel = GMKernel
# Create voltage domain & source clock
self.voltage_domain = VoltageDomain(voltage = '1.0V')
self.cpu_voltage_domain = VoltageDomain()
self.clk_domain = SrcClockDomain(voltage_domain = self.voltage_domain,
clock = '1GHz')
self.cpu_clk_domain = SrcClockDomain(voltage_domain = self.cpu_voltage_domain,
clock = '100MHz')
# For now, assign all the CPUs to the same clock domain
self.cpu = GMCPUClass(clk_domain=self.cpu_clk_domain, cpu_id=0)
self.cpu.createThreads()
self.cpu.createInterruptController()
self.cpu.connectAllPorts(self.membus)
# Config Memory
self.mem_ctrl = GMMemory()
self.mem_ctrl.port = self.membus.master
# Config IO Bridge
self.iobridge = Bridge(delay='50ns', ranges = self.mem_ranges)
self.iobridge.slave = self.iobus.master
self.iobridge.master = self.membus.slave
####
##### Config Ethernet
####self.pc.eth0 = IGbE_e1000(pci_bus=0, pci_dev=2, pci_func=0,
#### InterruptLine=13, InterruptPin=1)
####self.pc.eth0.pio = self.iobus.master
####self.pc.eth0.config = self.iobus.master
####self.pc.eth0.dma = self.iobus.slave
####self.ethertap = PARDg5VEtherTap(port=3500)
####self.etherlink = EtherLink()
####self.etherlink.int0 = self.pc.eth0.interface
####self.etherlink.int1 = self.ethertap.tap
#####self.etherdump = EtherDump(file="eth0.dump")
#####self.ethertap.dump = system.etherdump
####
return self
|
fsg-ict/PARD-gem5
|
configs/PARDg5GM.py
|
Python
|
gpl-2.0
| 2,850 |
<?php
/**
* Template Name: Service Template
*
* lambda framework v 2.1
* by www.unitedthemes.com
* since lambda framework v 1.0
* based on skeleton
*/
global $lambda_meta_data, $theme_path;
$meta_sidebar = $lambda_meta_data->get_the_value('sidebar');
$meta_sidebar = (!empty( $meta_sidebar )) ? $meta_sidebar : get_option_tree( 'select_sidebar' );
//includes the header.php
get_header();
//includes the template-part-slider.php
get_template_part( 'template-part', 'slider' );
//includes the template-part-teaser.php
get_template_part( 'template-part', 'teaser' );
//content opener - this function can be found in functions/theme-layout-functions.php line 5-50
lambda_before_content($columns='sixteen');
?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<section>
<article>
<div class="entry-content">
<?php the_content(); ?>
</div>
</article>
</section>
<?php endwhile; // end of the loop. ?>
<?php
#-----------------------------------------------------------------
# Service Template
#-----------------------------------------------------------------
?>
<?php if ( !post_password_required( $post ) ) : ?>
<?php
//retrieve faq items
$tab_items = $lambda_meta_data->get_the_value(UT_THEME_INITIAL.'verticaltabs');
//check if faq items exists
if(is_array($tab_items)) { ?>
<script type="text/javascript">
jQuery(document).ready(function($){
//url call for tabs
var contentLocation = window.location.href.slice(window.location.href.indexOf('?') + 1).split('#');
var contentLocator = contentLocation[1];
//settings
var $items = $('#vmenu > ul > li');
var initialindex = 0;
if(contentLocation[1]) {
initialindex = parseInt(contentLocation[1]);
}
$(window).load(function(){
$('#vtabs').css('height', $('#vtabs > div').eq(initialindex).height());
$('#vtab').removeClass('overflow-hidden');
$('#service-loader').hide();
$(".lambda-video").fitVids();
});
$items.click(function() {
$items.removeClass('selected');
$(this).addClass('selected');
var index = $items.index( $(this) );
$('#vtabs > div').css({ visibility : 'hidden', position: 'absolute' , "z-index": '1' }).eq(index).css({ visibility : 'visible', position: 'absolute' , "z-index": '9999' });
$('#vtabs').css('height', $('#vtabs > div').eq(index).height());
}).eq(initialindex).click();
});
</script>
<section class="verticaltabs-wrap clearfix">
<div id="vtab" class="clearfix overflow-hidden">
<div class="one_fourth" id="vmenu">
<ul>
<?php $z=1; foreach($tab_items as $tab) { ?>
<li class="tab tab_<?php echo $z; ?>"><h3><?php echo isset($tab['tab_name']) ? lambda_translate_meta($tab['tab_name']) : ''; ?></h3></li>
<?php $z++; } ?>
</ul>
</div>
<div id="vtabs" class="clearfix">
<?php $z=1; foreach($tab_items as $tab) { ?>
<div class="three_fourths last entry-content" style="right:0px; display:block;"><?php echo (isset($tab['tab_content'])) ? do_shortcode(apply_filters('the_content', $tab['tab_content'])): ''; ?></div>
<?php $z++; } ?>
</div>
<div id="service-loader" class="three_fourths last" style="right:0px; top:0px; height:100%; display:block; position:absolute;">
<img src="<?php echo THEME_WEB_ROOT ; ?>/images/103.gif" />
</div>
</div>
</section>
<div class="clear"></div>
<?php } ?>
<?php
//content closer - this function can be found in functions/theme-layout-functions.php line 56-61
lambda_after_content();
//end password protection
endif;
//includes the footer.php
get_footer();
?>
|
cphillipp/deepwood
|
wp-content/themes/nevada/template-service.php
|
PHP
|
gpl-2.0
| 3,863 |
#!/bin/sh
# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
# This file is public domain and comes with NO WARRANTY of any kind
#
# Script to start the MySQL daemon and restart it if it dies unexpectedly
#
# This should be executed in the MySQL base directory if you are using a
# binary installation that is not installed in its compile-time default
# location
#
# mysql.server works by first doing a cd to the base directory and from there
# executing mysqld_safe
# Initialize script globals
KILL_MYSQLD=1;
MYSQLD=
niceness=0
mysqld_ld_preload=
mysqld_ld_library_path=
load_jemalloc=1
flush_caches=0
numa_interleave=0
# Initial logging status: error log is not open, and not using syslog
logging=init
want_syslog=0
syslog_tag=
user='@MYSQLD_USER@'
pid_file=
err_log=
syslog_tag_mysqld=mysqld
syslog_tag_mysqld_safe=mysqld_safe
trap '' 1 2 3 15 # we shouldn't let anyone kill us
trap '' 13 # not even SIGPIPE
# MySQL-specific environment variable. First off, it's not really a umask,
# it's the desired mode. Second, it follows umask(2), not umask(3) in that
# octal needs to be explicit. Our shell might be a proper sh without printf,
# multiple-base arithmetic, and binary arithmetic, so this will get ugly.
# We reject decimal values to keep things at least half-sane.
umask 007 # fallback
UMASK="${UMASK-0640}"
fmode=`echo "$UMASK" | sed -e 's/[^0246]//g'`
octalp=`echo "$fmode"|cut -c1`
fmlen=`echo "$fmode"|wc -c|sed -e 's/ //g'`
if [ "x$octalp" != "x0" -o "x$UMASK" != "x$fmode" -o "x$fmlen" != "x5" ]
then
fmode=0640
echo "UMASK must be a 3-digit mode with an additional leading 0 to indicate octal." >&2
echo "The first digit will be corrected to 6, the others may be 0, 2, 4, or 6." >&2
fi
fmode=`echo "$fmode"|cut -c3-4`
fmode="6$fmode"
if [ "x$UMASK" != "x0$fmode" ]
then
echo "UMASK corrected from $UMASK to 0$fmode ..."
fi
defaults=
case "$1" in
--no-defaults|--defaults-file=*|--defaults-extra-file=*)
defaults="$1"; shift
;;
esac
usage () {
cat <<EOF
Usage: $0 [OPTIONS]
--no-defaults Don't read the system defaults file
--defaults-file=FILE Use the specified defaults file
--defaults-extra-file=FILE Also use defaults from the specified file
--ledir=DIRECTORY Look for mysqld in the specified directory
--open-files-limit=LIMIT Limit the number of open files
--core-file-size=LIMIT Limit core files to the specified size
--timezone=TZ Set the system timezone
--malloc-lib=LIB Preload shared library LIB if available
--mysqld=FILE Use the specified file as mysqld
--mysqld-version=VERSION Use "mysqld-VERSION" as mysqld
--nice=NICE Set the scheduling priority of mysqld
--plugin-dir=DIR Plugins are under DIR or DIR/VERSION, if
VERSION is given
--skip-kill-mysqld Don't try to kill stray mysqld processes
--syslog Log messages to syslog with 'logger'
--skip-syslog Log messages to error log (default)
--syslog-tag=TAG Pass -t "mysqld-TAG" to 'logger'
--flush-caches Flush and purge buffers/caches before
starting the server
--numa-interleave Run mysqld with its memory interleaved
on all NUMA nodes
All other options are passed to the mysqld program.
EOF
exit 1
}
my_which ()
{
save_ifs="${IFS-UNSET}"
IFS=:
ret=0
for file
do
for dir in $PATH
do
if [ -f "$dir/$file" ]
then
echo "$dir/$file"
continue 2
fi
done
ret=1 #signal an error
break
done
if [ "$save_ifs" = UNSET ]
then
unset IFS
else
IFS="$save_ifs"
fi
return $ret # Success
}
log_generic () {
priority="$1"
shift
msg="`date +'%y%m%d %H:%M:%S'` mysqld_safe $*"
echo "$msg"
case $logging in
init) ;; # Just echo the message, don't save it anywhere
file) echo "$msg" >> "$err_log" ;;
syslog) logger -t "$syslog_tag_mysqld_safe" -p "$priority" "$*" ;;
*)
echo "Internal program error (non-fatal):" \
" unknown logging method '$logging'" >&2
;;
esac
}
log_error () {
log_generic daemon.error "$@" >&2
}
log_notice () {
log_generic daemon.notice "$@"
}
eval_log_error () {
cmd="$1"
case $logging in
file) cmd="$cmd >> "`shell_quote_string "$err_log"`" 2>&1" ;;
syslog)
# mysqld often prefixes its messages with a timestamp, which is
# redundant when logging to syslog (which adds its own timestamp)
# However, we don't strip the timestamp with sed here, because
# sed buffers output (only GNU sed supports a -u (unbuffered) option)
# which means that messages may not get sent to syslog until the
# mysqld process quits.
cmd="$cmd 2>&1 | logger -t '$syslog_tag_mysqld' -p daemon.error"
;;
*)
echo "Internal program error (non-fatal):" \
" unknown logging method '$logging'" >&2
;;
esac
#echo "Running mysqld: [$cmd]"
eval "$cmd"
}
shell_quote_string() {
# This sed command makes sure that any special chars are quoted,
# so the arg gets passed exactly to the server.
echo "$1" | sed -e 's,\([^a-zA-Z0-9/_.=-]\),\\\1,g'
}
parse_arguments() {
# We only need to pass arguments through to the server if we don't
# handle them here. So, we collect unrecognized options (passed on
# the command line) into the args variable.
pick_args=
if test "$1" = PICK-ARGS-FROM-ARGV
then
pick_args=1
shift
fi
for arg do
# the parameter after "=", or the whole $arg if no match
val=`echo "$arg" | sed -e 's;^--[^=]*=;;'`
# what's before "=", or the whole $arg if no match
optname=`echo "$arg" | sed -e 's/^\(--[^=]*\)=.*$/\1/'`
# replace "_" by "-" ; mysqld_safe must accept "_" like mysqld does.
optname_subst=`echo "$optname" | sed 's/_/-/g'`
arg=`echo $arg | sed "s/^$optname/$optname_subst/"`
case "$arg" in
# these get passed explicitly to mysqld
--basedir=*) MY_BASEDIR_VERSION="$val" ;;
--datadir=*) DATADIR="$val" ;;
--pid-file=*) pid_file="$val" ;;
--plugin-dir=*) PLUGIN_DIR="$val" ;;
--user=*) user="$val"; SET_USER=1 ;;
# these might have been set in a [mysqld_safe] section of my.cnf
# they are added to mysqld command line to override settings from my.cnf
--log-error=*) err_log="$val" ;;
--port=*) mysql_tcp_port="$val" ;;
--socket=*) mysql_unix_port="$val" ;;
# mysqld_safe-specific options - must be set in my.cnf ([mysqld_safe])!
--core-file-size=*) core_file_size="$val" ;;
--ledir=*) ledir="$val" ;;
--malloc-lib=*)
set_malloc_lib "$val"
load_jemalloc=0
;;
--mysqld=*) MYSQLD="$val" ;;
--mysqld-version=*)
if test -n "$val"
then
MYSQLD="mysqld-$val"
PLUGIN_VARIANT="/$val"
else
MYSQLD="mysqld"
fi
;;
--nice=*) niceness="$val" ;;
--open-files-limit=*) open_files="$val" ;;
--open_files_limit=*) open_files="$val" ;;
--skip-kill-mysqld*) KILL_MYSQLD=0 ;;
--syslog) want_syslog=1 ;;
--skip-syslog) want_syslog=0 ;;
--syslog-tag=*) syslog_tag="$val" ;;
--timezone=*) TZ="$val"; export TZ; ;;
--flush-caches=*) flush_caches="$val" ;;
--numa-interleave=*) numa_interleave="$val" ;;
--help) usage ;;
*)
if test -n "$pick_args"
then
append_arg_to_args "$arg"
fi
;;
esac
done
}
# Add a single shared library to the list of libraries which will be added to
# LD_PRELOAD for mysqld
#
# Since LD_PRELOAD is a space-separated value (for historical reasons), if a
# shared lib's path contains spaces, that path will be prepended to
# LD_LIBRARY_PATH and stripped from the lib value.
add_mysqld_ld_preload() {
lib_to_add="$1"
log_notice "Adding '$lib_to_add' to LD_PRELOAD for mysqld"
case "$lib_to_add" in
*' '*)
# Must strip path from lib, and add it to LD_LIBRARY_PATH
lib_file=`basename "$lib_to_add"`
case "$lib_file" in
*' '*)
# The lib file itself has a space in its name, and can't
# be used in LD_PRELOAD
log_error "library name '$lib_to_add' contains spaces and can not be used with LD_PRELOAD"
exit 1
;;
esac
lib_path=`dirname "$lib_to_add"`
lib_to_add="$lib_file"
[ -n "$mysqld_ld_library_path" ] && mysqld_ld_library_path="$mysqld_ld_library_path:"
mysqld_ld_library_path="$mysqld_ld_library_path$lib_path"
;;
esac
# LD_PRELOAD is a space-separated
[ -n "$mysqld_ld_preload" ] && mysqld_ld_preload="$mysqld_ld_preload "
mysqld_ld_preload="${mysqld_ld_preload}$lib_to_add"
}
# Returns LD_PRELOAD (and LD_LIBRARY_PATH, if needed) text, quoted to be
# suitable for use in the eval that calls mysqld.
#
# All values in mysqld_ld_preload are prepended to LD_PRELOAD.
mysqld_ld_preload_text() {
text=
if [ -n "$mysqld_ld_preload" ]; then
new_text="$mysqld_ld_preload"
[ -n "$LD_PRELOAD" ] && new_text="$new_text $LD_PRELOAD"
text="${text}LD_PRELOAD="`shell_quote_string "$new_text"`' '
fi
if [ -n "$mysqld_ld_library_path" ]; then
new_text="$mysqld_ld_library_path"
[ -n "$LD_LIBRARY_PATH" ] && new_text="$new_text:$LD_LIBRARY_PATH"
text="${text}LD_LIBRARY_PATH="`shell_quote_string "$new_text"`' '
fi
echo "$text"
}
mysql_config=
get_mysql_config() {
if [ -z "$mysql_config" ]; then
mysql_config=`echo "$0" | sed 's,/[^/][^/]*$,/mysql_config,'`
if [ ! -x "$mysql_config" ]; then
log_error "Can not run mysql_config $@ from '$mysql_config'"
exit 1
fi
fi
"$mysql_config" "$@"
}
# set_malloc_lib LIB
# - If LIB is empty, do nothing and return
# - If LIB is 'tcmalloc', look for tcmalloc shared library in /usr/lib
# then pkglibdir. tcmalloc is part of the Google perftools project.
# - If LIB is an absolute path, assume it is a malloc shared library
#
# Put LIB in mysqld_ld_preload, which will be added to LD_PRELOAD when
# running mysqld. See ld.so for details.
set_malloc_lib() {
malloc_lib="$1"
if [ "$malloc_lib" = tcmalloc ]; then
pkglibdir=`get_mysql_config --variable=pkglibdir`
malloc_lib=
# This list is kept intentionally simple. Simply set --malloc-lib
# to a full path if another location is desired.
for libdir in /usr/lib "$pkglibdir" "$pkglibdir/mysql"; do
for flavor in _minimal '' _and_profiler _debug; do
tmp="$libdir/libtcmalloc$flavor.so"
#log_notice "DEBUG: Checking for malloc lib '$tmp'"
[ -r "$tmp" ] || continue
malloc_lib="$tmp"
break 2
done
done
if [ -z "$malloc_lib" ]; then
log_error "no shared library for --malloc-lib=tcmalloc found in /usr/lib or $pkglibdir"
exit 1
fi
fi
# Allow --malloc-lib='' to override other settings
[ -z "$malloc_lib" ] && return
case "$malloc_lib" in
/*)
if [ ! -r "$malloc_lib" ]; then
log_error "--malloc-lib '$malloc_lib' can not be read and will not be used"
exit 1
fi
;;
*)
log_error "--malloc-lib must be an absolute path or 'tcmalloc'; " \
"ignoring value '$malloc_lib'"
exit 1
;;
esac
add_mysqld_ld_preload "$malloc_lib"
}
#
# First, try to find BASEDIR and ledir (where mysqld is)
#
if echo '@pkgdatadir@' | grep '^@prefix@' > /dev/null
then
relpkgdata=`echo '@pkgdatadir@' | sed -e 's,^@prefix@,,' -e 's,^/,,' -e 's,^,./,'`
else
# pkgdatadir is not relative to prefix
relpkgdata='@pkgdatadir@'
fi
MY_PWD=`pwd`
# Check for the directories we would expect from a binary release install
if test -n "$MY_BASEDIR_VERSION" -a -d "$MY_BASEDIR_VERSION"
then
# BASEDIR is already overridden on command line. Do not re-set.
# Use BASEDIR to discover le.
if test -x "$MY_BASEDIR_VERSION/libexec/mysqld"
then
ledir="$MY_BASEDIR_VERSION/libexec"
elif test -x "$MY_BASEDIR_VERSION/sbin/mysqld"
then
ledir="$MY_BASEDIR_VERSION/sbin"
else
ledir="$MY_BASEDIR_VERSION/bin"
fi
elif test -f "$relpkgdata"/english/errmsg.sys -a -x "$MY_PWD/bin/mysqld"
then
MY_BASEDIR_VERSION="$MY_PWD" # Where bin, share and data are
ledir="$MY_PWD/bin" # Where mysqld is
# Check for the directories we would expect from a source install
elif test -f "$relpkgdata"/english/errmsg.sys -a -x "$MY_PWD/libexec/mysqld"
then
MY_BASEDIR_VERSION="$MY_PWD" # Where libexec, share and var are
ledir="$MY_PWD/libexec" # Where mysqld is
elif test -f "$relpkgdata"/english/errmsg.sys -a -x "$MY_PWD/sbin/mysqld"
then
MY_BASEDIR_VERSION="$MY_PWD" # Where sbin, share and var are
ledir="$MY_PWD/sbin" # Where mysqld is
# Since we didn't find anything, used the compiled-in defaults
else
MY_BASEDIR_VERSION='@prefix@'
ledir='@libexecdir@'
fi
#
# Second, try to find the data directory
#
# Try where the binary installs put it
if test -d $MY_BASEDIR_VERSION/data/mysql
then
DATADIR=$MY_BASEDIR_VERSION/data
if test -z "$defaults" -a -r "$DATADIR/my.cnf"
then
defaults="--defaults-extra-file=$DATADIR/my.cnf"
fi
# Next try where the source installs put it
elif test -d $MY_BASEDIR_VERSION/var/mysql
then
DATADIR=$MY_BASEDIR_VERSION/var
# Or just give up and use our compiled-in default
else
DATADIR=@localstatedir@
fi
if test -z "$MYSQL_HOME"
then
if test -r "$MY_BASEDIR_VERSION/my.cnf" && test -r "$DATADIR/my.cnf"
then
log_error "WARNING: Found two instances of my.cnf -
$MY_BASEDIR_VERSION/my.cnf and
$DATADIR/my.cnf
IGNORING $DATADIR/my.cnf"
MYSQL_HOME=$MY_BASEDIR_VERSION
elif test -r "$DATADIR/my.cnf"
then
log_error "WARNING: Found $DATADIR/my.cnf
The data directory is a deprecated location for my.cnf, please move it to
$MY_BASEDIR_VERSION/my.cnf"
MYSQL_HOME=$DATADIR
else
MYSQL_HOME=$MY_BASEDIR_VERSION
fi
fi
export MYSQL_HOME
# Get first arguments from the my.cnf file, groups [mysqld] and [mysqld_safe]
# and then merge with the command line arguments
if test -x "$MY_BASEDIR_VERSION/bin/my_print_defaults"
then
print_defaults="$MY_BASEDIR_VERSION/bin/my_print_defaults"
elif test -x `dirname $0`/my_print_defaults
then
print_defaults="`dirname $0`/my_print_defaults"
elif test -x ./bin/my_print_defaults
then
print_defaults="./bin/my_print_defaults"
elif test -x @bindir@/my_print_defaults
then
print_defaults="@bindir@/my_print_defaults"
elif test -x @bindir@/mysql_print_defaults
then
print_defaults="@bindir@/mysql_print_defaults"
else
print_defaults="my_print_defaults"
fi
append_arg_to_args () {
args="$args "`shell_quote_string "$1"`
}
args=
SET_USER=2
parse_arguments `$print_defaults $defaults --loose-verbose mysqld server`
if test $SET_USER -eq 2
then
SET_USER=0
fi
parse_arguments `$print_defaults $defaults --loose-verbose mysqld_safe safe_mysqld`
parse_arguments PICK-ARGS-FROM-ARGV "$@"
#
# Add jemalloc to ld_preload if no other malloc forced - needed for TokuDB
#
if test $load_jemalloc -eq 1
then
for libjemall in "/usr/lib64" "/usr/lib/x86_64-linux-gnu" "/usr/lib"; do
if [ -r "$libjemall/libjemalloc.so.1" ]; then
add_mysqld_ld_preload "$libjemall/libjemalloc.so.1"
break
fi
done
fi
#
# Try to find the plugin directory
#
# Use user-supplied argument
if [ -n "${PLUGIN_DIR}" ]; then
plugin_dir="${PLUGIN_DIR}"
else
# Try to find plugin dir relative to basedir
for dir in lib/mysql/plugin lib/plugin
do
if [ -d "${MY_BASEDIR_VERSION}/${dir}" ]; then
plugin_dir="${MY_BASEDIR_VERSION}/${dir}"
break
fi
done
# Give up and use compiled-in default
if [ -z "${plugin_dir}" ]; then
plugin_dir='@pkgplugindir@'
fi
fi
plugin_dir="${plugin_dir}${PLUGIN_VARIANT}"
# Determine what logging facility to use
# Ensure that 'logger' exists, if it's requested
if [ $want_syslog -eq 1 ]
then
my_which logger > /dev/null 2>&1
if [ $? -ne 0 ]
then
log_error "--syslog requested, but no 'logger' program found. Please ensure that 'logger' is in your PATH, or do not specify the --syslog option to mysqld_safe."
exit 1
fi
fi
if [ -n "$err_log" -o $want_syslog -eq 0 ]
then
if [ -n "$err_log" ]
then
# mysqld adds ".err" if there is no extension on the --log-error
# argument; must match that here, or mysqld_safe will write to a
# different log file than mysqld
# mysqld does not add ".err" to "--log-error=foo."; it considers a
# trailing "." as an extension
if expr "$err_log" : '.*\.[^/]*$' > /dev/null
then
:
else
err_log="$err_log".err
fi
case "$err_log" in
/* ) ;;
* ) err_log="$DATADIR/$err_log" ;;
esac
else
err_log=$DATADIR/`@HOSTNAME@`.err
fi
append_arg_to_args "--log-error=$err_log"
if [ $want_syslog -eq 1 ]
then
# User explicitly asked for syslog, so warn that it isn't used
log_error "Can't log to error log and syslog at the same time. Remove all --log-error configuration options for --syslog to take effect."
fi
# Log to err_log file
log_notice "Logging to '$err_log'."
logging=file
if [ ! -f "$err_log" ]; then # if error log already exists,
touch "$err_log" # we just append. otherwise,
chmod "$fmode" "$err_log" # fix the permissions here!
fi
else
if [ -n "$syslog_tag" ]
then
# Sanitize the syslog tag
syslog_tag=`echo "$syslog_tag" | sed -e 's/[^a-zA-Z0-9_-]/_/g'`
syslog_tag_mysqld_safe="${syslog_tag_mysqld_safe}-$syslog_tag"
syslog_tag_mysqld="${syslog_tag_mysqld}-$syslog_tag"
fi
log_notice "Logging to syslog."
logging=syslog
fi
USER_OPTION=""
if test -w / -o "$USER" = "root"
then
if test "$user" != "root" -o $SET_USER = 1
then
USER_OPTION="--user=$user"
fi
# Change the err log to the right user, if it is in use
if [ $want_syslog -eq 0 ]; then
touch "$err_log"
chown $user "$err_log"
fi
if test -n "$open_files"
then
ulimit -n $open_files
fi
fi
if test -n "$open_files"
then
append_arg_to_args "--open-files-limit=$open_files"
fi
safe_mysql_unix_port=${mysql_unix_port:-${MYSQL_UNIX_PORT:-@MYSQL_UNIX_ADDR@}}
# Make sure that directory for $safe_mysql_unix_port exists
mysql_unix_port_dir=`dirname $safe_mysql_unix_port`
if [ ! -d $mysql_unix_port_dir ]
then
mkdir $mysql_unix_port_dir
chown $user $mysql_unix_port_dir
chmod 755 $mysql_unix_port_dir
fi
# If the user doesn't specify a binary, we assume name "mysqld"
if test -z "$MYSQLD"
then
MYSQLD=mysqld
fi
if test ! -x "$ledir/$MYSQLD"
then
log_error "The file $ledir/$MYSQLD
does not exist or is not executable. Please cd to the mysql installation
directory and restart this script from there as follows:
./bin/mysqld_safe&
See http://dev.mysql.com/doc/mysql/en/mysqld-safe.html for more information"
exit 1
fi
if test -z "$pid_file"
then
pid_file="$DATADIR/`@HOSTNAME@`.pid"
else
case "$pid_file" in
/* ) ;;
* ) pid_file="$DATADIR/$pid_file" ;;
esac
fi
append_arg_to_args "--pid-file=$pid_file"
if test -n "$mysql_unix_port"
then
append_arg_to_args "--socket=$mysql_unix_port"
fi
if test -n "$mysql_tcp_port"
then
append_arg_to_args "--port=$mysql_tcp_port"
fi
if test $niceness -eq 0
then
NOHUP_NICENESS="nohup"
else
NOHUP_NICENESS="nohup nice -$niceness"
fi
# Using nice with no args to get the niceness level is GNU-specific.
# This check could be extended for other operating systems (e.g.,
# BSD could use "nohup sh -c 'ps -o nice -p $$' | tail -1").
# But, it also seems that GNU nohup is the only one which messes
# with the priority, so this is okay.
if nohup nice > /dev/null 2>&1
then
normal_niceness=`nice`
nohup_niceness=`nohup nice 2>/dev/null`
numeric_nice_values=1
for val in $normal_niceness $nohup_niceness
do
case "$val" in
-[0-9] | -[0-9][0-9] | -[0-9][0-9][0-9] | \
[0-9] | [0-9][0-9] | [0-9][0-9][0-9] )
;;
* )
numeric_nice_values=0 ;;
esac
done
if test $numeric_nice_values -eq 1
then
nice_value_diff=`expr $nohup_niceness - $normal_niceness`
if test $? -eq 0 && test $nice_value_diff -gt 0 && \
nice --$nice_value_diff echo testing > /dev/null 2>&1
then
# nohup increases the priority (bad), and we are permitted
# to lower the priority with respect to the value the user
# might have been given
niceness=`expr $niceness - $nice_value_diff`
NOHUP_NICENESS="nice -$niceness nohup"
fi
fi
else
if nohup echo testing > /dev/null 2>&1
then
:
else
# nohup doesn't work on this system
NOHUP_NICENESS=""
fi
fi
# Try to set the core file size (even if we aren't root) because many systems
# don't specify a hard limit on core file size.
if test -n "$core_file_size"
then
ulimit -c $core_file_size
fi
#
# If there exists an old pid file, check if the daemon is already running
# Note: The switches to 'ps' may depend on your operating system
if test -f "$pid_file"
then
PID=`cat "$pid_file"`
if @CHECK_PID@
then
if @FIND_PROC@
then # The pid contains a mysqld process
log_error "A mysqld process already exists"
exit 1
fi
fi
rm -f "$pid_file"
if test -f "$pid_file"
then
log_error "Fatal error: Can't remove the pid file:
$pid_file
Please remove it manually and start $0 again;
mysqld daemon not started"
exit 1
fi
fi
#
# Flush and purge buffers/caches.
#
if @TARGET_LINUX@ && test $flush_caches -eq 1
then
# Locate sync, ensure it exists.
if ! my_which sync > /dev/null 2>&1
then
log_error "sync command not found, required for --flush-caches"
exit 1
# Flush file system buffers.
elif ! sync
then
# Huh, the sync() function is always successful...
log_error "sync failed, check if sync is properly installed"
fi
# Locate sysctl, ensure it exists.
if ! my_which sysctl > /dev/null 2>&1
then
log_error "sysctl command not found, required for --flush-caches"
exit 1
# Purge page cache, dentries and inodes.
elif ! sysctl -q -w vm.drop_caches=3
then
log_error "sysctl failed, check the error message for details"
exit 1
fi
elif test $flush_caches -eq 1
then
log_error "--flush-caches is not supported on this platform"
exit 1
fi
#
# Uncomment the following lines if you want all tables to be automatically
# checked and repaired during startup. You should add sensible key_buffer
# and sort_buffer values to my.cnf to improve check performance or require
# less disk space.
# Alternatively, you can start mysqld with the "myisam-recover" option. See
# the manual for details.
#
# echo "Checking tables in $DATADIR"
# $MY_BASEDIR_VERSION/bin/myisamchk --silent --force --fast --medium-check $DATADIR/*/*.MYI
# $MY_BASEDIR_VERSION/bin/isamchk --silent --force $DATADIR/*/*.ISM
# Does this work on all systems?
#if type ulimit | grep "shell builtin" > /dev/null
#then
# ulimit -n 256 > /dev/null 2>&1 # Fix for BSD and FreeBSD systems
#fi
cmd="`mysqld_ld_preload_text`$NOHUP_NICENESS"
#
# Set mysqld's memory interleave policy.
#
if @TARGET_LINUX@ && test $numa_interleave -eq 1
then
# Locate numactl, ensure it exists.
if ! my_which numactl > /dev/null 2>&1
then
log_error "numactl command not found, required for --numa-interleave"
exit 1
# Attempt to run a command, ensure it works.
elif ! numactl --interleave=all true
then
log_error "numactl failed, check if numactl is properly installed"
fi
# Launch mysqld with numactl.
cmd="$cmd numactl --interleave=all"
elif test $numa_interleave -eq 1
then
log_error "--numa-interleave is not supported on this platform"
exit 1
fi
for i in "$ledir/$MYSQLD" "$defaults" "--basedir=$MY_BASEDIR_VERSION" \
"--datadir=$DATADIR" "--plugin-dir=$plugin_dir" "$USER_OPTION"
do
cmd="$cmd "`shell_quote_string "$i"`
done
cmd="$cmd $args"
# Avoid 'nohup: ignoring input' warning
test -n "$NOHUP_NICENESS" && cmd="$cmd < /dev/null"
log_notice "Starting $MYSQLD daemon with databases from $DATADIR"
# variable to track the current number of "fast" (a.k.a. subsecond) restarts
fast_restart=0
# maximum number of restarts before trottling kicks in
max_fast_restarts=5
# flag whether a usable sleep command exists
have_sleep=1
while true
do
rm -f $safe_mysql_unix_port "$pid_file" # Some extra safety
start_time=`date +%M%S`
eval_log_error "$cmd"
if [ $want_syslog -eq 0 -a ! -f "$err_log" ]; then
touch "$err_log" # hypothetical: log was renamed but not
chown $user "$err_log" # flushed yet. we'd recreate it with
chmod "$fmode" "$err_log" # wrong owner next time we log, so set
fi # it up correctly while we can!
end_time=`date +%M%S`
if test ! -f "$pid_file" # This is removed if normal shutdown
then
break
fi
# sanity check if time reading is sane and there's sleep
if test $end_time -gt 0 -a $have_sleep -gt 0
then
# throttle down the fast restarts
if test $end_time -eq $start_time
then
fast_restart=`expr $fast_restart + 1`
if test $fast_restart -ge $max_fast_restarts
then
log_notice "The server is respawning too fast. Sleeping for 1 second."
sleep 1
sleep_state=$?
if test $sleep_state -gt 0
then
log_notice "The server is respawning too fast and no working sleep command. Turning off trottling."
have_sleep=0
fi
fast_restart=0
fi
else
fast_restart=0
fi
fi
if @TARGET_LINUX@ && test $KILL_MYSQLD -eq 1
then
# Test if one process was hanging.
# This is only a fix for Linux (running as base 3 mysqld processes)
# but should work for the rest of the servers.
# The only thing is ps x => redhat 5 gives warnings when using ps -x.
# kill -9 is used or the process won't react on the kill.
numofproces=`ps xaww | grep -v "grep" | grep "$ledir/$MYSQLD\>" | grep -c "pid-file=$pid_file"`
log_notice "Number of processes running now: $numofproces"
I=1
while test "$I" -le "$numofproces"
do
PROC=`ps xaww | grep "$ledir/$MYSQLD\>" | grep -v "grep" | grep "pid-file=$pid_file" | sed -n '$p'`
for T in $PROC
do
break
done
# echo "TEST $I - $T **"
if kill -9 $T
then
log_error "$MYSQLD process hanging, pid $T - killed"
else
break
fi
I=`expr $I + 1`
done
fi
log_notice "mysqld restarted"
done
log_notice "mysqld from pid file $pid_file ended"
|
SunguckLee/PerconaServer_TokuDB
|
scripts/mysqld_safe.sh
|
Shell
|
gpl-2.0
| 26,851 |
/**
* @file
*
* @ingroup ScoreHeap
*
* @brief Heap Handler implementation.
*/
/*
* COPYRIGHT (c) 1989-2009.
* On-Line Applications Research Corporation (OAR).
*
* The license and distribution terms for this file may be
* found in the file LICENSE in this distribution or at
* http://www.rtems.org/license/LICENSE.
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <rtems/score/heapimpl.h>
static bool _Heap_Get_information_visitor(
const Heap_Block *block __attribute__((unused)),
uintptr_t block_size,
bool block_is_used,
void *visitor_arg
)
{
Heap_Information_block *info_block = visitor_arg;
Heap_Information *info = block_is_used ?
&info_block->Used : &info_block->Free;
++info->number;
info->total += block_size;
if ( info->largest < block_size )
info->largest = block_size;
return false;
}
void _Heap_Get_information(
Heap_Control *the_heap,
Heap_Information_block *the_info
)
{
memset( the_info, 0, sizeof(*the_info) );
_Heap_Protection_free_all_delayed_blocks( the_heap );
_Heap_Iterate( the_heap, _Heap_Get_information_visitor, the_info );
}
|
88888yl/rtems-mini2440-4.11
|
cpukit/score/src/heapgetinfo.c
|
C
|
gpl-2.0
| 1,154 |
/* OpenMP directive matching and resolving.
Copyright (C) 2005-2016 Free Software Foundation, Inc.
Contributed by Jakub Jelinek
This file is part of GCC.
GCC 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, or (at your option) any later
version.
GCC 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 GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "gfortran.h"
#include "arith.h"
#include "match.h"
#include "parse.h"
#include "diagnostic.h"
#include "gomp-constants.h"
/* Match an end of OpenMP directive. End of OpenMP directive is optional
whitespace, followed by '\n' or comment '!'. */
match
gfc_match_omp_eos (void)
{
locus old_loc;
char c;
old_loc = gfc_current_locus;
gfc_gobble_whitespace ();
c = gfc_next_ascii_char ();
switch (c)
{
case '!':
do
c = gfc_next_ascii_char ();
while (c != '\n');
/* Fall through */
case '\n':
return MATCH_YES;
}
gfc_current_locus = old_loc;
return MATCH_NO;
}
/* Free an omp_clauses structure. */
void
gfc_free_omp_clauses (gfc_omp_clauses *c)
{
int i;
if (c == NULL)
return;
gfc_free_expr (c->if_expr);
gfc_free_expr (c->final_expr);
gfc_free_expr (c->num_threads);
gfc_free_expr (c->chunk_size);
gfc_free_expr (c->safelen_expr);
gfc_free_expr (c->simdlen_expr);
gfc_free_expr (c->num_teams);
gfc_free_expr (c->device);
gfc_free_expr (c->thread_limit);
gfc_free_expr (c->dist_chunk_size);
gfc_free_expr (c->async_expr);
gfc_free_expr (c->gang_num_expr);
gfc_free_expr (c->gang_static_expr);
gfc_free_expr (c->worker_expr);
gfc_free_expr (c->vector_expr);
gfc_free_expr (c->num_gangs_expr);
gfc_free_expr (c->num_workers_expr);
gfc_free_expr (c->vector_length_expr);
for (i = 0; i < OMP_LIST_NUM; i++)
gfc_free_omp_namelist (c->lists[i]);
gfc_free_expr_list (c->wait_list);
gfc_free_expr_list (c->tile_list);
free (c);
}
/* Free oacc_declare structures. */
void
gfc_free_oacc_declare_clauses (struct gfc_oacc_declare *oc)
{
struct gfc_oacc_declare *decl = oc;
do
{
struct gfc_oacc_declare *next;
next = decl->next;
gfc_free_omp_clauses (decl->clauses);
free (decl);
decl = next;
}
while (decl);
}
/* Free expression list. */
void
gfc_free_expr_list (gfc_expr_list *list)
{
gfc_expr_list *n;
for (; list; list = n)
{
n = list->next;
free (list);
}
}
/* Free an !$omp declare simd construct list. */
void
gfc_free_omp_declare_simd (gfc_omp_declare_simd *ods)
{
if (ods)
{
gfc_free_omp_clauses (ods->clauses);
free (ods);
}
}
void
gfc_free_omp_declare_simd_list (gfc_omp_declare_simd *list)
{
while (list)
{
gfc_omp_declare_simd *current = list;
list = list->next;
gfc_free_omp_declare_simd (current);
}
}
/* Free an !$omp declare reduction. */
void
gfc_free_omp_udr (gfc_omp_udr *omp_udr)
{
if (omp_udr)
{
gfc_free_omp_udr (omp_udr->next);
gfc_free_namespace (omp_udr->combiner_ns);
if (omp_udr->initializer_ns)
gfc_free_namespace (omp_udr->initializer_ns);
free (omp_udr);
}
}
static gfc_omp_udr *
gfc_find_omp_udr (gfc_namespace *ns, const char *name, gfc_typespec *ts)
{
gfc_symtree *st;
if (ns == NULL)
ns = gfc_current_ns;
do
{
gfc_omp_udr *omp_udr;
st = gfc_find_symtree (ns->omp_udr_root, name);
if (st != NULL)
{
for (omp_udr = st->n.omp_udr; omp_udr; omp_udr = omp_udr->next)
if (ts == NULL)
return omp_udr;
else if (gfc_compare_types (&omp_udr->ts, ts))
{
if (ts->type == BT_CHARACTER)
{
if (omp_udr->ts.u.cl->length == NULL)
return omp_udr;
if (ts->u.cl->length == NULL)
continue;
if (gfc_compare_expr (omp_udr->ts.u.cl->length,
ts->u.cl->length,
INTRINSIC_EQ) != 0)
continue;
}
return omp_udr;
}
}
/* Don't escape an interface block. */
if (ns && !ns->has_import_set
&& ns->proc_name && ns->proc_name->attr.if_source == IFSRC_IFBODY)
break;
ns = ns->parent;
}
while (ns != NULL);
return NULL;
}
/* Match a variable/common block list and construct a namelist from it. */
static match
gfc_match_omp_variable_list (const char *str, gfc_omp_namelist **list,
bool allow_common, bool *end_colon = NULL,
gfc_omp_namelist ***headp = NULL,
bool allow_sections = false)
{
gfc_omp_namelist *head, *tail, *p;
locus old_loc, cur_loc;
char n[GFC_MAX_SYMBOL_LEN+1];
gfc_symbol *sym;
match m;
gfc_symtree *st;
head = tail = NULL;
old_loc = gfc_current_locus;
m = gfc_match (str);
if (m != MATCH_YES)
return m;
for (;;)
{
cur_loc = gfc_current_locus;
m = gfc_match_symbol (&sym, 1);
switch (m)
{
case MATCH_YES:
gfc_expr *expr;
expr = NULL;
if (allow_sections && gfc_peek_ascii_char () == '(')
{
gfc_current_locus = cur_loc;
m = gfc_match_variable (&expr, 0);
switch (m)
{
case MATCH_ERROR:
goto cleanup;
case MATCH_NO:
goto syntax;
default:
break;
}
}
gfc_set_sym_referenced (sym);
p = gfc_get_omp_namelist ();
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = tail->next;
}
tail->sym = sym;
tail->expr = expr;
tail->where = cur_loc;
goto next_item;
case MATCH_NO:
break;
case MATCH_ERROR:
goto cleanup;
}
if (!allow_common)
goto syntax;
m = gfc_match (" / %n /", n);
if (m == MATCH_ERROR)
goto cleanup;
if (m == MATCH_NO)
goto syntax;
st = gfc_find_symtree (gfc_current_ns->common_root, n);
if (st == NULL)
{
gfc_error ("COMMON block /%s/ not found at %C", n);
goto cleanup;
}
for (sym = st->n.common->head; sym; sym = sym->common_next)
{
gfc_set_sym_referenced (sym);
p = gfc_get_omp_namelist ();
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = tail->next;
}
tail->sym = sym;
tail->where = cur_loc;
}
next_item:
if (end_colon && gfc_match_char (':') == MATCH_YES)
{
*end_colon = true;
break;
}
if (gfc_match_char (')') == MATCH_YES)
break;
if (gfc_match_char (',') != MATCH_YES)
goto syntax;
}
while (*list)
list = &(*list)->next;
*list = head;
if (headp)
*headp = list;
return MATCH_YES;
syntax:
gfc_error ("Syntax error in OpenMP variable list at %C");
cleanup:
gfc_free_omp_namelist (head);
gfc_current_locus = old_loc;
return MATCH_ERROR;
}
static match
match_oacc_expr_list (const char *str, gfc_expr_list **list,
bool allow_asterisk)
{
gfc_expr_list *head, *tail, *p;
locus old_loc;
gfc_expr *expr;
match m;
head = tail = NULL;
old_loc = gfc_current_locus;
m = gfc_match (str);
if (m != MATCH_YES)
return m;
for (;;)
{
m = gfc_match_expr (&expr);
if (m == MATCH_YES || allow_asterisk)
{
p = gfc_get_expr_list ();
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = tail->next;
}
if (m == MATCH_YES)
tail->expr = expr;
else if (gfc_match (" *") != MATCH_YES)
goto syntax;
goto next_item;
}
if (m == MATCH_ERROR)
goto cleanup;
goto syntax;
next_item:
if (gfc_match_char (')') == MATCH_YES)
break;
if (gfc_match_char (',') != MATCH_YES)
goto syntax;
}
while (*list)
list = &(*list)->next;
*list = head;
return MATCH_YES;
syntax:
gfc_error ("Syntax error in OpenACC expression list at %C");
cleanup:
gfc_free_expr_list (head);
gfc_current_locus = old_loc;
return MATCH_ERROR;
}
static match
match_oacc_clause_gwv (gfc_omp_clauses *cp, unsigned gwv)
{
match ret = MATCH_YES;
if (gfc_match (" ( ") != MATCH_YES)
return MATCH_NO;
if (gwv == GOMP_DIM_GANG)
{
/* The gang clause accepts two optional arguments, num and static.
The num argument may either be explicit (num: <val>) or
implicit without (<val> without num:). */
while (ret == MATCH_YES)
{
if (gfc_match (" static :") == MATCH_YES)
{
if (cp->gang_static)
return MATCH_ERROR;
else
cp->gang_static = true;
if (gfc_match_char ('*') == MATCH_YES)
cp->gang_static_expr = NULL;
else if (gfc_match (" %e ", &cp->gang_static_expr) != MATCH_YES)
return MATCH_ERROR;
}
else
{
if (cp->gang_num_expr)
return MATCH_ERROR;
/* The 'num' argument is optional. */
gfc_match (" num :");
if (gfc_match (" %e ", &cp->gang_num_expr) != MATCH_YES)
return MATCH_ERROR;
}
ret = gfc_match (" , ");
}
}
else if (gwv == GOMP_DIM_WORKER)
{
/* The 'num' argument is optional. */
gfc_match (" num :");
if (gfc_match (" %e ", &cp->worker_expr) != MATCH_YES)
return MATCH_ERROR;
}
else if (gwv == GOMP_DIM_VECTOR)
{
/* The 'length' argument is optional. */
gfc_match (" length :");
if (gfc_match (" %e ", &cp->vector_expr) != MATCH_YES)
return MATCH_ERROR;
}
else
gfc_fatal_error ("Unexpected OpenACC parallelism.");
return gfc_match (" )");
}
static match
gfc_match_oacc_clause_link (const char *str, gfc_omp_namelist **list)
{
gfc_omp_namelist *head = NULL;
gfc_omp_namelist *tail, *p;
locus old_loc;
char n[GFC_MAX_SYMBOL_LEN+1];
gfc_symbol *sym;
match m;
gfc_symtree *st;
old_loc = gfc_current_locus;
m = gfc_match (str);
if (m != MATCH_YES)
return m;
m = gfc_match (" (");
for (;;)
{
m = gfc_match_symbol (&sym, 0);
switch (m)
{
case MATCH_YES:
if (sym->attr.in_common)
{
gfc_error_now ("Variable at %C is an element of a COMMON block");
goto cleanup;
}
gfc_set_sym_referenced (sym);
p = gfc_get_omp_namelist ();
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = tail->next;
}
tail->sym = sym;
tail->expr = NULL;
tail->where = gfc_current_locus;
goto next_item;
case MATCH_NO:
break;
case MATCH_ERROR:
goto cleanup;
}
m = gfc_match (" / %n /", n);
if (m == MATCH_ERROR)
goto cleanup;
if (m == MATCH_NO || n[0] == '\0')
goto syntax;
st = gfc_find_symtree (gfc_current_ns->common_root, n);
if (st == NULL)
{
gfc_error ("COMMON block /%s/ not found at %C", n);
goto cleanup;
}
for (sym = st->n.common->head; sym; sym = sym->common_next)
{
gfc_set_sym_referenced (sym);
p = gfc_get_omp_namelist ();
if (head == NULL)
head = tail = p;
else
{
tail->next = p;
tail = tail->next;
}
tail->sym = sym;
tail->where = gfc_current_locus;
}
next_item:
if (gfc_match_char (')') == MATCH_YES)
break;
if (gfc_match_char (',') != MATCH_YES)
goto syntax;
}
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after !$ACC DECLARE at %C");
goto cleanup;
}
while (*list)
list = &(*list)->next;
*list = head;
return MATCH_YES;
syntax:
gfc_error ("Syntax error in !$ACC DECLARE list at %C");
cleanup:
gfc_current_locus = old_loc;
return MATCH_ERROR;
}
#define OMP_CLAUSE_PRIVATE ((uint64_t) 1 << 0)
#define OMP_CLAUSE_FIRSTPRIVATE ((uint64_t) 1 << 1)
#define OMP_CLAUSE_LASTPRIVATE ((uint64_t) 1 << 2)
#define OMP_CLAUSE_COPYPRIVATE ((uint64_t) 1 << 3)
#define OMP_CLAUSE_SHARED ((uint64_t) 1 << 4)
#define OMP_CLAUSE_COPYIN ((uint64_t) 1 << 5)
#define OMP_CLAUSE_REDUCTION ((uint64_t) 1 << 6)
#define OMP_CLAUSE_IF ((uint64_t) 1 << 7)
#define OMP_CLAUSE_NUM_THREADS ((uint64_t) 1 << 8)
#define OMP_CLAUSE_SCHEDULE ((uint64_t) 1 << 9)
#define OMP_CLAUSE_DEFAULT ((uint64_t) 1 << 10)
#define OMP_CLAUSE_ORDERED ((uint64_t) 1 << 11)
#define OMP_CLAUSE_COLLAPSE ((uint64_t) 1 << 12)
#define OMP_CLAUSE_UNTIED ((uint64_t) 1 << 13)
#define OMP_CLAUSE_FINAL ((uint64_t) 1 << 14)
#define OMP_CLAUSE_MERGEABLE ((uint64_t) 1 << 15)
#define OMP_CLAUSE_ALIGNED ((uint64_t) 1 << 16)
#define OMP_CLAUSE_DEPEND ((uint64_t) 1 << 17)
#define OMP_CLAUSE_INBRANCH ((uint64_t) 1 << 18)
#define OMP_CLAUSE_LINEAR ((uint64_t) 1 << 19)
#define OMP_CLAUSE_NOTINBRANCH ((uint64_t) 1 << 20)
#define OMP_CLAUSE_PROC_BIND ((uint64_t) 1 << 21)
#define OMP_CLAUSE_SAFELEN ((uint64_t) 1 << 22)
#define OMP_CLAUSE_SIMDLEN ((uint64_t) 1 << 23)
#define OMP_CLAUSE_UNIFORM ((uint64_t) 1 << 24)
#define OMP_CLAUSE_DEVICE ((uint64_t) 1 << 25)
#define OMP_CLAUSE_MAP ((uint64_t) 1 << 26)
#define OMP_CLAUSE_TO ((uint64_t) 1 << 27)
#define OMP_CLAUSE_FROM ((uint64_t) 1 << 28)
#define OMP_CLAUSE_NUM_TEAMS ((uint64_t) 1 << 29)
#define OMP_CLAUSE_THREAD_LIMIT ((uint64_t) 1 << 30)
#define OMP_CLAUSE_DIST_SCHEDULE ((uint64_t) 1 << 31)
/* OpenACC 2.0 clauses. */
#define OMP_CLAUSE_ASYNC ((uint64_t) 1 << 32)
#define OMP_CLAUSE_NUM_GANGS ((uint64_t) 1 << 33)
#define OMP_CLAUSE_NUM_WORKERS ((uint64_t) 1 << 34)
#define OMP_CLAUSE_VECTOR_LENGTH ((uint64_t) 1 << 35)
#define OMP_CLAUSE_COPY ((uint64_t) 1 << 36)
#define OMP_CLAUSE_COPYOUT ((uint64_t) 1 << 37)
#define OMP_CLAUSE_CREATE ((uint64_t) 1 << 38)
#define OMP_CLAUSE_PRESENT ((uint64_t) 1 << 39)
#define OMP_CLAUSE_PRESENT_OR_COPY ((uint64_t) 1 << 40)
#define OMP_CLAUSE_PRESENT_OR_COPYIN ((uint64_t) 1 << 41)
#define OMP_CLAUSE_PRESENT_OR_COPYOUT ((uint64_t) 1 << 42)
#define OMP_CLAUSE_PRESENT_OR_CREATE ((uint64_t) 1 << 43)
#define OMP_CLAUSE_DEVICEPTR ((uint64_t) 1 << 44)
#define OMP_CLAUSE_GANG ((uint64_t) 1 << 45)
#define OMP_CLAUSE_WORKER ((uint64_t) 1 << 46)
#define OMP_CLAUSE_VECTOR ((uint64_t) 1 << 47)
#define OMP_CLAUSE_SEQ ((uint64_t) 1 << 48)
#define OMP_CLAUSE_INDEPENDENT ((uint64_t) 1 << 49)
#define OMP_CLAUSE_USE_DEVICE ((uint64_t) 1 << 50)
#define OMP_CLAUSE_DEVICE_RESIDENT ((uint64_t) 1 << 51)
#define OMP_CLAUSE_HOST_SELF ((uint64_t) 1 << 52)
#define OMP_CLAUSE_OACC_DEVICE ((uint64_t) 1 << 53)
#define OMP_CLAUSE_WAIT ((uint64_t) 1 << 54)
#define OMP_CLAUSE_DELETE ((uint64_t) 1 << 55)
#define OMP_CLAUSE_AUTO ((uint64_t) 1 << 56)
#define OMP_CLAUSE_TILE ((uint64_t) 1 << 57)
#define OMP_CLAUSE_LINK ((uint64_t) 1 << 58)
/* Helper function for OpenACC and OpenMP clauses involving memory
mapping. */
static bool
gfc_match_omp_map_clause (gfc_omp_namelist **list, gfc_omp_map_op map_op)
{
gfc_omp_namelist **head = NULL;
if (gfc_match_omp_variable_list ("", list, false, NULL, &head, true)
== MATCH_YES)
{
gfc_omp_namelist *n;
for (n = *head; n; n = n->next)
n->u.map_op = map_op;
return true;
}
return false;
}
/* Match OpenMP and OpenACC directive clauses. MASK is a bitmask of
clauses that are allowed for a particular directive. */
static match
gfc_match_omp_clauses (gfc_omp_clauses **cp, uint64_t mask,
bool first = true, bool needs_space = true,
bool openacc = false)
{
gfc_omp_clauses *c = gfc_get_omp_clauses ();
locus old_loc;
*cp = NULL;
while (1)
{
if ((first || gfc_match_char (',') != MATCH_YES)
&& (needs_space && gfc_match_space () != MATCH_YES))
break;
needs_space = false;
first = false;
gfc_gobble_whitespace ();
old_loc = gfc_current_locus;
if ((mask & OMP_CLAUSE_ASYNC) && !c->async)
if (gfc_match ("async") == MATCH_YES)
{
c->async = true;
match m = gfc_match (" ( %e )", &c->async_expr);
if (m == MATCH_ERROR)
{
gfc_current_locus = old_loc;
break;
}
else if (m == MATCH_NO)
{
c->async_expr
= gfc_get_constant_expr (BT_INTEGER,
gfc_default_integer_kind,
&gfc_current_locus);
mpz_set_si (c->async_expr->value.integer, GOMP_ASYNC_NOVAL);
needs_space = true;
}
continue;
}
if ((mask & OMP_CLAUSE_GANG) && !c->gang)
if (gfc_match ("gang") == MATCH_YES)
{
c->gang = true;
match m = match_oacc_clause_gwv (c, GOMP_DIM_GANG);
if (m == MATCH_ERROR)
{
gfc_current_locus = old_loc;
break;
}
else if (m == MATCH_NO)
needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_WORKER) && !c->worker)
if (gfc_match ("worker") == MATCH_YES)
{
c->worker = true;
match m = match_oacc_clause_gwv (c, GOMP_DIM_WORKER);
if (m == MATCH_ERROR)
{
gfc_current_locus = old_loc;
break;
}
else if (m == MATCH_NO)
needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_VECTOR_LENGTH) && c->vector_length_expr == NULL
&& gfc_match ("vector_length ( %e )", &c->vector_length_expr)
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_VECTOR) && !c->vector)
if (gfc_match ("vector") == MATCH_YES)
{
c->vector = true;
match m = match_oacc_clause_gwv (c, GOMP_DIM_VECTOR);
if (m == MATCH_ERROR)
{
gfc_current_locus = old_loc;
break;
}
if (m == MATCH_NO)
needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_IF) && c->if_expr == NULL
&& gfc_match ("if ( %e )", &c->if_expr) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_FINAL) && c->final_expr == NULL
&& gfc_match ("final ( %e )", &c->final_expr) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_NUM_THREADS) && c->num_threads == NULL
&& gfc_match ("num_threads ( %e )", &c->num_threads) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_PRIVATE)
&& gfc_match_omp_variable_list ("private (",
&c->lists[OMP_LIST_PRIVATE], true)
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_FIRSTPRIVATE)
&& gfc_match_omp_variable_list ("firstprivate (",
&c->lists[OMP_LIST_FIRSTPRIVATE],
true)
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_LASTPRIVATE)
&& gfc_match_omp_variable_list ("lastprivate (",
&c->lists[OMP_LIST_LASTPRIVATE],
true)
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_COPYPRIVATE)
&& gfc_match_omp_variable_list ("copyprivate (",
&c->lists[OMP_LIST_COPYPRIVATE],
true)
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_SHARED)
&& gfc_match_omp_variable_list ("shared (",
&c->lists[OMP_LIST_SHARED], true)
== MATCH_YES)
continue;
if (mask & OMP_CLAUSE_COPYIN)
{
if (openacc)
{
if (gfc_match ("copyin ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_FORCE_TO))
continue;
}
else if (gfc_match_omp_variable_list ("copyin (",
&c->lists[OMP_LIST_COPYIN],
true) == MATCH_YES)
continue;
}
if ((mask & OMP_CLAUSE_NUM_GANGS) && c->num_gangs_expr == NULL
&& gfc_match ("num_gangs ( %e )", &c->num_gangs_expr) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_NUM_WORKERS) && c->num_workers_expr == NULL
&& gfc_match ("num_workers ( %e )", &c->num_workers_expr)
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_COPY)
&& gfc_match ("copy ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_FORCE_TOFROM))
continue;
if ((mask & OMP_CLAUSE_COPYOUT)
&& gfc_match ("copyout ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_FORCE_FROM))
continue;
if ((mask & OMP_CLAUSE_CREATE)
&& gfc_match ("create ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_FORCE_ALLOC))
continue;
if ((mask & OMP_CLAUSE_DELETE)
&& gfc_match ("delete ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_DELETE))
continue;
if ((mask & OMP_CLAUSE_PRESENT)
&& gfc_match ("present ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_FORCE_PRESENT))
continue;
if ((mask & OMP_CLAUSE_PRESENT_OR_COPY)
&& gfc_match ("present_or_copy ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_TOFROM))
continue;
if ((mask & OMP_CLAUSE_PRESENT_OR_COPY)
&& gfc_match ("pcopy ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_TOFROM))
continue;
if ((mask & OMP_CLAUSE_PRESENT_OR_COPYIN)
&& gfc_match ("present_or_copyin ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_TO))
continue;
if ((mask & OMP_CLAUSE_PRESENT_OR_COPYIN)
&& gfc_match ("pcopyin ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_TO))
continue;
if ((mask & OMP_CLAUSE_PRESENT_OR_COPYOUT)
&& gfc_match ("present_or_copyout ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_FROM))
continue;
if ((mask & OMP_CLAUSE_PRESENT_OR_COPYOUT)
&& gfc_match ("pcopyout ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_FROM))
continue;
if ((mask & OMP_CLAUSE_PRESENT_OR_CREATE)
&& gfc_match ("present_or_create ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_ALLOC))
continue;
if ((mask & OMP_CLAUSE_PRESENT_OR_CREATE)
&& gfc_match ("pcreate ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_ALLOC))
continue;
if ((mask & OMP_CLAUSE_DEVICEPTR)
&& gfc_match ("deviceptr ( ") == MATCH_YES)
{
gfc_omp_namelist **list = &c->lists[OMP_LIST_MAP];
gfc_omp_namelist **head = NULL;
if (gfc_match_omp_variable_list ("", list, true, NULL, &head, false)
== MATCH_YES)
{
gfc_omp_namelist *n;
for (n = *head; n; n = n->next)
n->u.map_op = OMP_MAP_FORCE_DEVICEPTR;
continue;
}
}
if ((mask & OMP_CLAUSE_USE_DEVICE)
&& gfc_match_omp_variable_list ("use_device (",
&c->lists[OMP_LIST_USE_DEVICE], true)
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_DEVICE_RESIDENT)
&& gfc_match_omp_variable_list ("device_resident (",
&c->lists[OMP_LIST_DEVICE_RESIDENT],
true)
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_LINK)
&& gfc_match_oacc_clause_link ("link (",
&c->lists[OMP_LIST_LINK])
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_OACC_DEVICE)
&& gfc_match ("device ( ") == MATCH_YES
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_FORCE_TO))
continue;
if ((mask & OMP_CLAUSE_HOST_SELF)
&& (gfc_match ("host ( ") == MATCH_YES
|| gfc_match ("self ( ") == MATCH_YES)
&& gfc_match_omp_map_clause (&c->lists[OMP_LIST_MAP],
OMP_MAP_FORCE_FROM))
continue;
if ((mask & OMP_CLAUSE_TILE)
&& !c->tile_list
&& match_oacc_expr_list ("tile (", &c->tile_list, true) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_SEQ) && !c->seq
&& gfc_match ("seq") == MATCH_YES)
{
c->seq = true;
needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_INDEPENDENT) && !c->independent
&& gfc_match ("independent") == MATCH_YES)
{
c->independent = true;
needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_AUTO) && !c->par_auto
&& gfc_match ("auto") == MATCH_YES)
{
c->par_auto = true;
needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_WAIT) && !c->wait
&& gfc_match ("wait") == MATCH_YES)
{
c->wait = true;
match m = match_oacc_expr_list (" (", &c->wait_list, false);
if (m == MATCH_ERROR)
{
gfc_current_locus = old_loc;
break;
}
else if (m == MATCH_NO)
needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_REDUCTION)
&& gfc_match ("reduction ( ") == MATCH_YES)
{
gfc_omp_reduction_op rop = OMP_REDUCTION_NONE;
char buffer[GFC_MAX_SYMBOL_LEN + 3];
if (gfc_match_char ('+') == MATCH_YES)
rop = OMP_REDUCTION_PLUS;
else if (gfc_match_char ('*') == MATCH_YES)
rop = OMP_REDUCTION_TIMES;
else if (gfc_match_char ('-') == MATCH_YES)
rop = OMP_REDUCTION_MINUS;
else if (gfc_match (".and.") == MATCH_YES)
rop = OMP_REDUCTION_AND;
else if (gfc_match (".or.") == MATCH_YES)
rop = OMP_REDUCTION_OR;
else if (gfc_match (".eqv.") == MATCH_YES)
rop = OMP_REDUCTION_EQV;
else if (gfc_match (".neqv.") == MATCH_YES)
rop = OMP_REDUCTION_NEQV;
if (rop != OMP_REDUCTION_NONE)
snprintf (buffer, sizeof buffer,
"operator %s", gfc_op2string ((gfc_intrinsic_op) rop));
else if (gfc_match_defined_op_name (buffer + 1, 1) == MATCH_YES)
{
buffer[0] = '.';
strcat (buffer, ".");
}
else if (gfc_match_name (buffer) == MATCH_YES)
{
gfc_symbol *sym;
const char *n = buffer;
gfc_find_symbol (buffer, NULL, 1, &sym);
if (sym != NULL)
{
if (sym->attr.intrinsic)
n = sym->name;
else if ((sym->attr.flavor != FL_UNKNOWN
&& sym->attr.flavor != FL_PROCEDURE)
|| sym->attr.external
|| sym->attr.generic
|| sym->attr.entry
|| sym->attr.result
|| sym->attr.dummy
|| sym->attr.subroutine
|| sym->attr.pointer
|| sym->attr.target
|| sym->attr.cray_pointer
|| sym->attr.cray_pointee
|| (sym->attr.proc != PROC_UNKNOWN
&& sym->attr.proc != PROC_INTRINSIC)
|| sym->attr.if_source != IFSRC_UNKNOWN
|| sym == sym->ns->proc_name)
{
sym = NULL;
n = NULL;
}
else
n = sym->name;
}
if (n == NULL)
rop = OMP_REDUCTION_NONE;
else if (strcmp (n, "max") == 0)
rop = OMP_REDUCTION_MAX;
else if (strcmp (n, "min") == 0)
rop = OMP_REDUCTION_MIN;
else if (strcmp (n, "iand") == 0)
rop = OMP_REDUCTION_IAND;
else if (strcmp (n, "ior") == 0)
rop = OMP_REDUCTION_IOR;
else if (strcmp (n, "ieor") == 0)
rop = OMP_REDUCTION_IEOR;
if (rop != OMP_REDUCTION_NONE
&& sym != NULL
&& ! sym->attr.intrinsic
&& ! sym->attr.use_assoc
&& ((sym->attr.flavor == FL_UNKNOWN
&& !gfc_add_flavor (&sym->attr, FL_PROCEDURE,
sym->name, NULL))
|| !gfc_add_intrinsic (&sym->attr, NULL)))
rop = OMP_REDUCTION_NONE;
}
else
buffer[0] = '\0';
gfc_omp_udr *udr
= (buffer[0]
? gfc_find_omp_udr (gfc_current_ns, buffer, NULL) : NULL);
gfc_omp_namelist **head = NULL;
if (rop == OMP_REDUCTION_NONE && udr)
rop = OMP_REDUCTION_USER;
if (gfc_match_omp_variable_list (" :",
&c->lists[OMP_LIST_REDUCTION],
false, NULL, &head, openacc)
== MATCH_YES)
{
gfc_omp_namelist *n;
if (rop == OMP_REDUCTION_NONE)
{
n = *head;
*head = NULL;
gfc_error_now ("!$OMP DECLARE REDUCTION %s not found "
"at %L", buffer, &old_loc);
gfc_free_omp_namelist (n);
}
else
for (n = *head; n; n = n->next)
{
n->u.reduction_op = rop;
if (udr)
{
n->udr = gfc_get_omp_namelist_udr ();
n->udr->udr = udr;
}
}
continue;
}
else
gfc_current_locus = old_loc;
}
if ((mask & OMP_CLAUSE_DEFAULT)
&& c->default_sharing == OMP_DEFAULT_UNKNOWN)
{
if (gfc_match ("default ( none )") == MATCH_YES)
c->default_sharing = OMP_DEFAULT_NONE;
else if (openacc)
/* c->default_sharing = OMP_DEFAULT_UNKNOWN */;
else if (gfc_match ("default ( shared )") == MATCH_YES)
c->default_sharing = OMP_DEFAULT_SHARED;
else if (gfc_match ("default ( private )") == MATCH_YES)
c->default_sharing = OMP_DEFAULT_PRIVATE;
else if (gfc_match ("default ( firstprivate )") == MATCH_YES)
c->default_sharing = OMP_DEFAULT_FIRSTPRIVATE;
if (c->default_sharing != OMP_DEFAULT_UNKNOWN)
continue;
}
old_loc = gfc_current_locus;
if ((mask & OMP_CLAUSE_SCHEDULE)
&& c->sched_kind == OMP_SCHED_NONE
&& gfc_match ("schedule ( ") == MATCH_YES)
{
if (gfc_match ("static") == MATCH_YES)
c->sched_kind = OMP_SCHED_STATIC;
else if (gfc_match ("dynamic") == MATCH_YES)
c->sched_kind = OMP_SCHED_DYNAMIC;
else if (gfc_match ("guided") == MATCH_YES)
c->sched_kind = OMP_SCHED_GUIDED;
else if (gfc_match ("runtime") == MATCH_YES)
c->sched_kind = OMP_SCHED_RUNTIME;
else if (gfc_match ("auto") == MATCH_YES)
c->sched_kind = OMP_SCHED_AUTO;
if (c->sched_kind != OMP_SCHED_NONE)
{
match m = MATCH_NO;
if (c->sched_kind != OMP_SCHED_RUNTIME
&& c->sched_kind != OMP_SCHED_AUTO)
m = gfc_match (" , %e )", &c->chunk_size);
if (m != MATCH_YES)
m = gfc_match_char (')');
if (m != MATCH_YES)
c->sched_kind = OMP_SCHED_NONE;
}
if (c->sched_kind != OMP_SCHED_NONE)
continue;
else
gfc_current_locus = old_loc;
}
if ((mask & OMP_CLAUSE_ORDERED) && !c->ordered
&& gfc_match ("ordered") == MATCH_YES)
{
c->ordered = needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_UNTIED) && !c->untied
&& gfc_match ("untied") == MATCH_YES)
{
c->untied = needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_MERGEABLE) && !c->mergeable
&& gfc_match ("mergeable") == MATCH_YES)
{
c->mergeable = needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_COLLAPSE) && !c->collapse)
{
gfc_expr *cexpr = NULL;
match m = gfc_match ("collapse ( %e )", &cexpr);
if (m == MATCH_YES)
{
int collapse;
const char *p = gfc_extract_int (cexpr, &collapse);
if (p)
{
gfc_error_now (p);
collapse = 1;
}
else if (collapse <= 0)
{
gfc_error_now ("COLLAPSE clause argument not"
" constant positive integer at %C");
collapse = 1;
}
c->collapse = collapse;
gfc_free_expr (cexpr);
continue;
}
}
if ((mask & OMP_CLAUSE_INBRANCH) && !c->inbranch && !c->notinbranch
&& gfc_match ("inbranch") == MATCH_YES)
{
c->inbranch = needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_NOTINBRANCH) && !c->notinbranch && !c->inbranch
&& gfc_match ("notinbranch") == MATCH_YES)
{
c->notinbranch = needs_space = true;
continue;
}
if ((mask & OMP_CLAUSE_PROC_BIND)
&& c->proc_bind == OMP_PROC_BIND_UNKNOWN)
{
if (gfc_match ("proc_bind ( master )") == MATCH_YES)
c->proc_bind = OMP_PROC_BIND_MASTER;
else if (gfc_match ("proc_bind ( spread )") == MATCH_YES)
c->proc_bind = OMP_PROC_BIND_SPREAD;
else if (gfc_match ("proc_bind ( close )") == MATCH_YES)
c->proc_bind = OMP_PROC_BIND_CLOSE;
if (c->proc_bind != OMP_PROC_BIND_UNKNOWN)
continue;
}
if ((mask & OMP_CLAUSE_SAFELEN) && c->safelen_expr == NULL
&& gfc_match ("safelen ( %e )", &c->safelen_expr) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_SIMDLEN) && c->simdlen_expr == NULL
&& gfc_match ("simdlen ( %e )", &c->simdlen_expr) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_UNIFORM)
&& gfc_match_omp_variable_list ("uniform (",
&c->lists[OMP_LIST_UNIFORM], false)
== MATCH_YES)
continue;
bool end_colon = false;
gfc_omp_namelist **head = NULL;
old_loc = gfc_current_locus;
if ((mask & OMP_CLAUSE_ALIGNED)
&& gfc_match_omp_variable_list ("aligned (",
&c->lists[OMP_LIST_ALIGNED], false,
&end_colon, &head)
== MATCH_YES)
{
gfc_expr *alignment = NULL;
gfc_omp_namelist *n;
if (end_colon
&& gfc_match (" %e )", &alignment) != MATCH_YES)
{
gfc_free_omp_namelist (*head);
gfc_current_locus = old_loc;
*head = NULL;
break;
}
for (n = *head; n; n = n->next)
if (n->next && alignment)
n->expr = gfc_copy_expr (alignment);
else
n->expr = alignment;
continue;
}
end_colon = false;
head = NULL;
old_loc = gfc_current_locus;
if ((mask & OMP_CLAUSE_LINEAR)
&& gfc_match_omp_variable_list ("linear (",
&c->lists[OMP_LIST_LINEAR], false,
&end_colon, &head)
== MATCH_YES)
{
gfc_expr *step = NULL;
if (end_colon
&& gfc_match (" %e )", &step) != MATCH_YES)
{
gfc_free_omp_namelist (*head);
gfc_current_locus = old_loc;
*head = NULL;
break;
}
else if (!end_colon)
{
step = gfc_get_constant_expr (BT_INTEGER,
gfc_default_integer_kind,
&old_loc);
mpz_set_si (step->value.integer, 1);
}
(*head)->expr = step;
continue;
}
if ((mask & OMP_CLAUSE_DEPEND)
&& gfc_match ("depend ( ") == MATCH_YES)
{
match m = MATCH_YES;
gfc_omp_depend_op depend_op = OMP_DEPEND_OUT;
if (gfc_match ("inout") == MATCH_YES)
depend_op = OMP_DEPEND_INOUT;
else if (gfc_match ("in") == MATCH_YES)
depend_op = OMP_DEPEND_IN;
else if (gfc_match ("out") == MATCH_YES)
depend_op = OMP_DEPEND_OUT;
else
m = MATCH_NO;
head = NULL;
if (m == MATCH_YES
&& gfc_match_omp_variable_list (" : ",
&c->lists[OMP_LIST_DEPEND],
false, NULL, &head, true)
== MATCH_YES)
{
gfc_omp_namelist *n;
for (n = *head; n; n = n->next)
n->u.depend_op = depend_op;
continue;
}
else
gfc_current_locus = old_loc;
}
if ((mask & OMP_CLAUSE_DIST_SCHEDULE)
&& c->dist_sched_kind == OMP_SCHED_NONE
&& gfc_match ("dist_schedule ( static") == MATCH_YES)
{
match m = MATCH_NO;
c->dist_sched_kind = OMP_SCHED_STATIC;
m = gfc_match (" , %e )", &c->dist_chunk_size);
if (m != MATCH_YES)
m = gfc_match_char (')');
if (m != MATCH_YES)
{
c->dist_sched_kind = OMP_SCHED_NONE;
gfc_current_locus = old_loc;
}
else
continue;
}
if ((mask & OMP_CLAUSE_NUM_TEAMS) && c->num_teams == NULL
&& gfc_match ("num_teams ( %e )", &c->num_teams) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_DEVICE) && c->device == NULL
&& gfc_match ("device ( %e )", &c->device) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_THREAD_LIMIT) && c->thread_limit == NULL
&& gfc_match ("thread_limit ( %e )", &c->thread_limit) == MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_MAP)
&& gfc_match ("map ( ") == MATCH_YES)
{
gfc_omp_map_op map_op = OMP_MAP_TOFROM;
if (gfc_match ("alloc : ") == MATCH_YES)
map_op = OMP_MAP_ALLOC;
else if (gfc_match ("tofrom : ") == MATCH_YES)
map_op = OMP_MAP_TOFROM;
else if (gfc_match ("to : ") == MATCH_YES)
map_op = OMP_MAP_TO;
else if (gfc_match ("from : ") == MATCH_YES)
map_op = OMP_MAP_FROM;
head = NULL;
if (gfc_match_omp_variable_list ("", &c->lists[OMP_LIST_MAP],
false, NULL, &head, true)
== MATCH_YES)
{
gfc_omp_namelist *n;
for (n = *head; n; n = n->next)
n->u.map_op = map_op;
continue;
}
else
gfc_current_locus = old_loc;
}
if ((mask & OMP_CLAUSE_TO)
&& gfc_match_omp_variable_list ("to (",
&c->lists[OMP_LIST_TO], false,
NULL, &head, true)
== MATCH_YES)
continue;
if ((mask & OMP_CLAUSE_FROM)
&& gfc_match_omp_variable_list ("from (",
&c->lists[OMP_LIST_FROM], false,
NULL, &head, true)
== MATCH_YES)
continue;
break;
}
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_free_omp_clauses (c);
return MATCH_ERROR;
}
*cp = c;
return MATCH_YES;
}
#define OACC_PARALLEL_CLAUSES \
(OMP_CLAUSE_IF | OMP_CLAUSE_ASYNC | OMP_CLAUSE_NUM_GANGS \
| OMP_CLAUSE_NUM_WORKERS | OMP_CLAUSE_VECTOR_LENGTH | OMP_CLAUSE_REDUCTION \
| OMP_CLAUSE_COPY | OMP_CLAUSE_COPYIN | OMP_CLAUSE_COPYOUT \
| OMP_CLAUSE_CREATE | OMP_CLAUSE_PRESENT | OMP_CLAUSE_PRESENT_OR_COPY \
| OMP_CLAUSE_PRESENT_OR_COPYIN | OMP_CLAUSE_PRESENT_OR_COPYOUT \
| OMP_CLAUSE_PRESENT_OR_CREATE | OMP_CLAUSE_DEVICEPTR | OMP_CLAUSE_PRIVATE \
| OMP_CLAUSE_FIRSTPRIVATE | OMP_CLAUSE_DEFAULT | OMP_CLAUSE_WAIT)
#define OACC_KERNELS_CLAUSES \
(OMP_CLAUSE_IF | OMP_CLAUSE_ASYNC | OMP_CLAUSE_DEVICEPTR \
| OMP_CLAUSE_COPY | OMP_CLAUSE_COPYIN | OMP_CLAUSE_COPYOUT \
| OMP_CLAUSE_CREATE | OMP_CLAUSE_PRESENT | OMP_CLAUSE_PRESENT_OR_COPY \
| OMP_CLAUSE_PRESENT_OR_COPYIN | OMP_CLAUSE_PRESENT_OR_COPYOUT \
| OMP_CLAUSE_PRESENT_OR_CREATE | OMP_CLAUSE_DEFAULT | OMP_CLAUSE_WAIT)
#define OACC_DATA_CLAUSES \
(OMP_CLAUSE_IF | OMP_CLAUSE_DEVICEPTR | OMP_CLAUSE_COPY \
| OMP_CLAUSE_COPYIN | OMP_CLAUSE_COPYOUT | OMP_CLAUSE_CREATE \
| OMP_CLAUSE_PRESENT | OMP_CLAUSE_PRESENT_OR_COPY \
| OMP_CLAUSE_PRESENT_OR_COPYIN | OMP_CLAUSE_PRESENT_OR_COPYOUT \
| OMP_CLAUSE_PRESENT_OR_CREATE)
#define OACC_LOOP_CLAUSES \
(OMP_CLAUSE_COLLAPSE | OMP_CLAUSE_GANG | OMP_CLAUSE_WORKER \
| OMP_CLAUSE_VECTOR | OMP_CLAUSE_SEQ | OMP_CLAUSE_INDEPENDENT \
| OMP_CLAUSE_PRIVATE | OMP_CLAUSE_REDUCTION | OMP_CLAUSE_AUTO \
| OMP_CLAUSE_TILE)
#define OACC_PARALLEL_LOOP_CLAUSES \
(OACC_LOOP_CLAUSES | OACC_PARALLEL_CLAUSES)
#define OACC_KERNELS_LOOP_CLAUSES \
(OACC_LOOP_CLAUSES | OACC_KERNELS_CLAUSES)
#define OACC_HOST_DATA_CLAUSES OMP_CLAUSE_USE_DEVICE
#define OACC_DECLARE_CLAUSES \
(OMP_CLAUSE_COPY | OMP_CLAUSE_COPYIN | OMP_CLAUSE_COPYOUT \
| OMP_CLAUSE_CREATE | OMP_CLAUSE_DEVICEPTR | OMP_CLAUSE_DEVICE_RESIDENT \
| OMP_CLAUSE_PRESENT | OMP_CLAUSE_PRESENT_OR_COPY \
| OMP_CLAUSE_PRESENT_OR_COPYIN | OMP_CLAUSE_PRESENT_OR_COPYOUT \
| OMP_CLAUSE_PRESENT_OR_CREATE | OMP_CLAUSE_LINK)
#define OACC_UPDATE_CLAUSES \
(OMP_CLAUSE_IF | OMP_CLAUSE_ASYNC | OMP_CLAUSE_HOST_SELF \
| OMP_CLAUSE_OACC_DEVICE | OMP_CLAUSE_WAIT)
#define OACC_ENTER_DATA_CLAUSES \
(OMP_CLAUSE_IF | OMP_CLAUSE_ASYNC | OMP_CLAUSE_WAIT | OMP_CLAUSE_COPYIN \
| OMP_CLAUSE_CREATE | OMP_CLAUSE_PRESENT_OR_COPYIN \
| OMP_CLAUSE_PRESENT_OR_CREATE)
#define OACC_EXIT_DATA_CLAUSES \
(OMP_CLAUSE_IF | OMP_CLAUSE_ASYNC | OMP_CLAUSE_WAIT | OMP_CLAUSE_COPYOUT \
| OMP_CLAUSE_DELETE)
#define OACC_WAIT_CLAUSES \
(OMP_CLAUSE_ASYNC)
#define OACC_ROUTINE_CLAUSES \
(OMP_CLAUSE_GANG | OMP_CLAUSE_WORKER | OMP_CLAUSE_VECTOR | OMP_CLAUSE_SEQ)
match
gfc_match_oacc_parallel_loop (void)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, OACC_PARALLEL_LOOP_CLAUSES, false, false,
true) != MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OACC_PARALLEL_LOOP;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_parallel (void)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, OACC_PARALLEL_CLAUSES, false, false, true)
!= MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OACC_PARALLEL;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_kernels_loop (void)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, OACC_KERNELS_LOOP_CLAUSES, false, false,
true) != MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OACC_KERNELS_LOOP;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_kernels (void)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, OACC_KERNELS_CLAUSES, false, false, true)
!= MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OACC_KERNELS;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_data (void)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, OACC_DATA_CLAUSES, false, false, true)
!= MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OACC_DATA;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_host_data (void)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, OACC_HOST_DATA_CLAUSES, false, false, true)
!= MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OACC_HOST_DATA;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_loop (void)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, OACC_LOOP_CLAUSES, false, false, true)
!= MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OACC_LOOP;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_declare (void)
{
gfc_omp_clauses *c;
gfc_omp_namelist *n;
gfc_namespace *ns = gfc_current_ns;
gfc_oacc_declare *new_oc;
bool module_var = false;
locus where = gfc_current_locus;
if (gfc_match_omp_clauses (&c, OACC_DECLARE_CLAUSES, false, false, true)
!= MATCH_YES)
return MATCH_ERROR;
for (n = c->lists[OMP_LIST_DEVICE_RESIDENT]; n != NULL; n = n->next)
n->sym->attr.oacc_declare_device_resident = 1;
for (n = c->lists[OMP_LIST_LINK]; n != NULL; n = n->next)
n->sym->attr.oacc_declare_link = 1;
for (n = c->lists[OMP_LIST_MAP]; n != NULL; n = n->next)
{
gfc_symbol *s = n->sym;
if (s->ns->proc_name && s->ns->proc_name->attr.proc == PROC_MODULE)
{
if (n->u.map_op != OMP_MAP_FORCE_ALLOC
&& n->u.map_op != OMP_MAP_FORCE_TO)
{
gfc_error ("Invalid clause in module with $!ACC DECLARE at %L",
&where);
return MATCH_ERROR;
}
module_var = true;
}
if (s->attr.use_assoc)
{
gfc_error ("Variable is USE-associated with $!ACC DECLARE at %L",
&where);
return MATCH_ERROR;
}
if ((s->attr.dimension || s->attr.codimension)
&& s->attr.dummy && s->as->type != AS_EXPLICIT)
{
gfc_error ("Assumed-size dummy array with $!ACC DECLARE at %L",
&where);
return MATCH_ERROR;
}
switch (n->u.map_op)
{
case OMP_MAP_FORCE_ALLOC:
s->attr.oacc_declare_create = 1;
break;
case OMP_MAP_FORCE_TO:
s->attr.oacc_declare_copyin = 1;
break;
case OMP_MAP_FORCE_DEVICEPTR:
s->attr.oacc_declare_deviceptr = 1;
break;
default:
break;
}
}
new_oc = gfc_get_oacc_declare ();
new_oc->next = ns->oacc_declare;
new_oc->module_var = module_var;
new_oc->clauses = c;
new_oc->loc = gfc_current_locus;
ns->oacc_declare = new_oc;
return MATCH_YES;
}
match
gfc_match_oacc_update (void)
{
gfc_omp_clauses *c;
locus here = gfc_current_locus;
if (gfc_match_omp_clauses (&c, OACC_UPDATE_CLAUSES, false, false, true)
!= MATCH_YES)
return MATCH_ERROR;
if (!c->lists[OMP_LIST_MAP])
{
gfc_error ("%<acc update%> must contain at least one "
"%<device%> or %<host%> or %<self%> clause at %L", &here);
return MATCH_ERROR;
}
new_st.op = EXEC_OACC_UPDATE;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_enter_data (void)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, OACC_ENTER_DATA_CLAUSES, false, false, true)
!= MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OACC_ENTER_DATA;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_exit_data (void)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, OACC_EXIT_DATA_CLAUSES, false, false, true)
!= MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OACC_EXIT_DATA;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_wait (void)
{
gfc_omp_clauses *c = gfc_get_omp_clauses ();
gfc_expr_list *wait_list = NULL, *el;
bool space = true;
match m;
m = match_oacc_expr_list (" (", &wait_list, true);
if (m == MATCH_ERROR)
return m;
else if (m == MATCH_YES)
space = false;
if (gfc_match_omp_clauses (&c, OACC_WAIT_CLAUSES, space, space, true)
== MATCH_ERROR)
return MATCH_ERROR;
if (wait_list)
for (el = wait_list; el; el = el->next)
{
if (el->expr == NULL)
{
gfc_error ("Invalid argument to $!ACC WAIT at %L",
&wait_list->expr->where);
return MATCH_ERROR;
}
if (!gfc_resolve_expr (el->expr)
|| el->expr->ts.type != BT_INTEGER || el->expr->rank != 0
|| el->expr->expr_type != EXPR_CONSTANT)
{
gfc_error ("WAIT clause at %L requires a scalar INTEGER expression",
&el->expr->where);
return MATCH_ERROR;
}
}
c->wait_list = wait_list;
new_st.op = EXEC_OACC_WAIT;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_oacc_cache (void)
{
gfc_omp_clauses *c = gfc_get_omp_clauses ();
/* The OpenACC cache directive explicitly only allows "array elements or
subarrays", which we're currently not checking here. Either check this
after the call of gfc_match_omp_variable_list, or add something like a
only_sections variant next to its allow_sections parameter. */
match m = gfc_match_omp_variable_list (" (",
&c->lists[OMP_LIST_CACHE], true,
NULL, NULL, true);
if (m != MATCH_YES)
{
gfc_free_omp_clauses(c);
return m;
}
if (gfc_current_state() != COMP_DO
&& gfc_current_state() != COMP_DO_CONCURRENT)
{
gfc_error ("ACC CACHE directive must be inside of loop %C");
gfc_free_omp_clauses(c);
return MATCH_ERROR;
}
new_st.op = EXEC_OACC_CACHE;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
/* Determine the loop level for a routine. */
static int
gfc_oacc_routine_dims (gfc_omp_clauses *clauses)
{
int level = -1;
if (clauses)
{
unsigned mask = 0;
if (clauses->gang)
level = GOMP_DIM_GANG, mask |= GOMP_DIM_MASK (level);
if (clauses->worker)
level = GOMP_DIM_WORKER, mask |= GOMP_DIM_MASK (level);
if (clauses->vector)
level = GOMP_DIM_VECTOR, mask |= GOMP_DIM_MASK (level);
if (clauses->seq)
level = GOMP_DIM_MAX, mask |= GOMP_DIM_MASK (level);
if (mask != (mask & -mask))
gfc_error ("Multiple loop axes specified for routine");
}
if (level < 0)
level = GOMP_DIM_MAX;
return level;
}
match
gfc_match_oacc_routine (void)
{
locus old_loc;
gfc_symbol *sym = NULL;
match m;
gfc_omp_clauses *c = NULL;
gfc_oacc_routine_name *n = NULL;
old_loc = gfc_current_locus;
m = gfc_match (" (");
if (gfc_current_ns->proc_name
&& gfc_current_ns->proc_name->attr.if_source == IFSRC_IFBODY
&& m == MATCH_YES)
{
gfc_error ("Only the !$ACC ROUTINE form without "
"list is allowed in interface block at %C");
goto cleanup;
}
if (m == MATCH_YES)
{
char buffer[GFC_MAX_SYMBOL_LEN + 1];
gfc_symtree *st;
m = gfc_match_name (buffer);
if (m == MATCH_YES)
{
st = gfc_find_symtree (gfc_current_ns->sym_root, buffer);
if (st)
{
sym = st->n.sym;
if (strcmp (sym->name, gfc_current_ns->proc_name->name) == 0)
sym = NULL;
}
if (st == NULL
|| (sym
&& !sym->attr.external
&& !sym->attr.function
&& !sym->attr.subroutine))
{
gfc_error ("Syntax error in !$ACC ROUTINE ( NAME ) at %C, "
"invalid function name %s",
(sym) ? sym->name : buffer);
gfc_current_locus = old_loc;
return MATCH_ERROR;
}
}
else
{
gfc_error ("Syntax error in !$ACC ROUTINE ( NAME ) at %C");
gfc_current_locus = old_loc;
return MATCH_ERROR;
}
if (gfc_match_char (')') != MATCH_YES)
{
gfc_error ("Syntax error in !$ACC ROUTINE ( NAME ) at %C, expecting"
" ')' after NAME");
gfc_current_locus = old_loc;
return MATCH_ERROR;
}
}
if (gfc_match_omp_eos () != MATCH_YES
&& (gfc_match_omp_clauses (&c, OACC_ROUTINE_CLAUSES, false, false, true)
!= MATCH_YES))
return MATCH_ERROR;
if (sym != NULL)
{
n = gfc_get_oacc_routine_name ();
n->sym = sym;
n->clauses = NULL;
n->next = NULL;
if (gfc_current_ns->oacc_routine_names != NULL)
n->next = gfc_current_ns->oacc_routine_names;
gfc_current_ns->oacc_routine_names = n;
}
else if (gfc_current_ns->proc_name)
{
if (!gfc_add_omp_declare_target (&gfc_current_ns->proc_name->attr,
gfc_current_ns->proc_name->name,
&old_loc))
goto cleanup;
gfc_current_ns->proc_name->attr.oacc_function
= gfc_oacc_routine_dims (c) + 1;
}
if (n)
n->clauses = c;
else if (gfc_current_ns->oacc_routine)
gfc_current_ns->oacc_routine_clauses = c;
new_st.op = EXEC_OACC_ROUTINE;
new_st.ext.omp_clauses = c;
return MATCH_YES;
cleanup:
gfc_current_locus = old_loc;
return MATCH_ERROR;
}
#define OMP_PARALLEL_CLAUSES \
(OMP_CLAUSE_PRIVATE | OMP_CLAUSE_FIRSTPRIVATE | OMP_CLAUSE_SHARED \
| OMP_CLAUSE_COPYIN | OMP_CLAUSE_REDUCTION | OMP_CLAUSE_IF \
| OMP_CLAUSE_NUM_THREADS | OMP_CLAUSE_DEFAULT | OMP_CLAUSE_PROC_BIND)
#define OMP_DECLARE_SIMD_CLAUSES \
(OMP_CLAUSE_SIMDLEN | OMP_CLAUSE_LINEAR | OMP_CLAUSE_UNIFORM \
| OMP_CLAUSE_ALIGNED | OMP_CLAUSE_INBRANCH | OMP_CLAUSE_NOTINBRANCH)
#define OMP_DO_CLAUSES \
(OMP_CLAUSE_PRIVATE | OMP_CLAUSE_FIRSTPRIVATE \
| OMP_CLAUSE_LASTPRIVATE | OMP_CLAUSE_REDUCTION \
| OMP_CLAUSE_SCHEDULE | OMP_CLAUSE_ORDERED | OMP_CLAUSE_COLLAPSE)
#define OMP_SECTIONS_CLAUSES \
(OMP_CLAUSE_PRIVATE | OMP_CLAUSE_FIRSTPRIVATE \
| OMP_CLAUSE_LASTPRIVATE | OMP_CLAUSE_REDUCTION)
#define OMP_SIMD_CLAUSES \
(OMP_CLAUSE_PRIVATE | OMP_CLAUSE_LASTPRIVATE | OMP_CLAUSE_REDUCTION \
| OMP_CLAUSE_COLLAPSE | OMP_CLAUSE_SAFELEN | OMP_CLAUSE_LINEAR \
| OMP_CLAUSE_ALIGNED)
#define OMP_TASK_CLAUSES \
(OMP_CLAUSE_PRIVATE | OMP_CLAUSE_FIRSTPRIVATE | OMP_CLAUSE_SHARED \
| OMP_CLAUSE_IF | OMP_CLAUSE_DEFAULT | OMP_CLAUSE_UNTIED \
| OMP_CLAUSE_FINAL | OMP_CLAUSE_MERGEABLE | OMP_CLAUSE_DEPEND)
#define OMP_TARGET_CLAUSES \
(OMP_CLAUSE_DEVICE | OMP_CLAUSE_MAP | OMP_CLAUSE_IF)
#define OMP_TARGET_DATA_CLAUSES \
(OMP_CLAUSE_DEVICE | OMP_CLAUSE_MAP | OMP_CLAUSE_IF)
#define OMP_TARGET_UPDATE_CLAUSES \
(OMP_CLAUSE_DEVICE | OMP_CLAUSE_IF | OMP_CLAUSE_TO | OMP_CLAUSE_FROM)
#define OMP_TEAMS_CLAUSES \
(OMP_CLAUSE_NUM_TEAMS | OMP_CLAUSE_THREAD_LIMIT | OMP_CLAUSE_DEFAULT \
| OMP_CLAUSE_PRIVATE | OMP_CLAUSE_FIRSTPRIVATE | OMP_CLAUSE_SHARED \
| OMP_CLAUSE_REDUCTION)
#define OMP_DISTRIBUTE_CLAUSES \
(OMP_CLAUSE_PRIVATE | OMP_CLAUSE_FIRSTPRIVATE | OMP_CLAUSE_COLLAPSE \
| OMP_CLAUSE_DIST_SCHEDULE)
static match
match_omp (gfc_exec_op op, unsigned int mask)
{
gfc_omp_clauses *c;
if (gfc_match_omp_clauses (&c, mask) != MATCH_YES)
return MATCH_ERROR;
new_st.op = op;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_omp_critical (void)
{
char n[GFC_MAX_SYMBOL_LEN+1];
if (gfc_match (" ( %n )", n) != MATCH_YES)
n[0] = '\0';
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after $OMP CRITICAL statement at %C");
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_CRITICAL;
new_st.ext.omp_name = n[0] ? xstrdup (n) : NULL;
return MATCH_YES;
}
match
gfc_match_omp_distribute (void)
{
return match_omp (EXEC_OMP_DISTRIBUTE, OMP_DISTRIBUTE_CLAUSES);
}
match
gfc_match_omp_distribute_parallel_do (void)
{
return match_omp (EXEC_OMP_DISTRIBUTE_PARALLEL_DO,
OMP_DISTRIBUTE_CLAUSES | OMP_PARALLEL_CLAUSES
| OMP_DO_CLAUSES);
}
match
gfc_match_omp_distribute_parallel_do_simd (void)
{
return match_omp (EXEC_OMP_DISTRIBUTE_PARALLEL_DO_SIMD,
(OMP_DISTRIBUTE_CLAUSES | OMP_PARALLEL_CLAUSES
| OMP_DO_CLAUSES | OMP_SIMD_CLAUSES)
& ~OMP_CLAUSE_ORDERED);
}
match
gfc_match_omp_distribute_simd (void)
{
return match_omp (EXEC_OMP_DISTRIBUTE_SIMD,
OMP_DISTRIBUTE_CLAUSES | OMP_SIMD_CLAUSES);
}
match
gfc_match_omp_do (void)
{
return match_omp (EXEC_OMP_DO, OMP_DO_CLAUSES);
}
match
gfc_match_omp_do_simd (void)
{
return match_omp (EXEC_OMP_DO_SIMD, ((OMP_DO_CLAUSES | OMP_SIMD_CLAUSES)
& ~OMP_CLAUSE_ORDERED));
}
match
gfc_match_omp_flush (void)
{
gfc_omp_namelist *list = NULL;
gfc_match_omp_variable_list (" (", &list, true);
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after $OMP FLUSH statement at %C");
gfc_free_omp_namelist (list);
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_FLUSH;
new_st.ext.omp_namelist = list;
return MATCH_YES;
}
match
gfc_match_omp_declare_simd (void)
{
locus where = gfc_current_locus;
gfc_symbol *proc_name;
gfc_omp_clauses *c;
gfc_omp_declare_simd *ods;
if (gfc_match (" ( %s ) ", &proc_name) != MATCH_YES)
return MATCH_ERROR;
if (gfc_match_omp_clauses (&c, OMP_DECLARE_SIMD_CLAUSES, true,
false) != MATCH_YES)
return MATCH_ERROR;
ods = gfc_get_omp_declare_simd ();
ods->where = where;
ods->proc_name = proc_name;
ods->clauses = c;
ods->next = gfc_current_ns->omp_declare_simd;
gfc_current_ns->omp_declare_simd = ods;
return MATCH_YES;
}
static bool
match_udr_expr (gfc_symtree *omp_sym1, gfc_symtree *omp_sym2)
{
match m;
locus old_loc = gfc_current_locus;
char sname[GFC_MAX_SYMBOL_LEN + 1];
gfc_symbol *sym;
gfc_namespace *ns = gfc_current_ns;
gfc_expr *lvalue = NULL, *rvalue = NULL;
gfc_symtree *st;
gfc_actual_arglist *arglist;
m = gfc_match (" %v =", &lvalue);
if (m != MATCH_YES)
gfc_current_locus = old_loc;
else
{
m = gfc_match (" %e )", &rvalue);
if (m == MATCH_YES)
{
ns->code = gfc_get_code (EXEC_ASSIGN);
ns->code->expr1 = lvalue;
ns->code->expr2 = rvalue;
ns->code->loc = old_loc;
return true;
}
gfc_current_locus = old_loc;
gfc_free_expr (lvalue);
}
m = gfc_match (" %n", sname);
if (m != MATCH_YES)
return false;
if (strcmp (sname, omp_sym1->name) == 0
|| strcmp (sname, omp_sym2->name) == 0)
return false;
gfc_current_ns = ns->parent;
if (gfc_get_ha_sym_tree (sname, &st))
return false;
sym = st->n.sym;
if (sym->attr.flavor != FL_PROCEDURE
&& sym->attr.flavor != FL_UNKNOWN)
return false;
if (!sym->attr.generic
&& !sym->attr.subroutine
&& !sym->attr.function)
{
if (!(sym->attr.external && !sym->attr.referenced))
{
/* ...create a symbol in this scope... */
if (sym->ns != gfc_current_ns
&& gfc_get_sym_tree (sname, NULL, &st, false) == 1)
return false;
if (sym != st->n.sym)
sym = st->n.sym;
}
/* ...and then to try to make the symbol into a subroutine. */
if (!gfc_add_subroutine (&sym->attr, sym->name, NULL))
return false;
}
gfc_set_sym_referenced (sym);
gfc_gobble_whitespace ();
if (gfc_peek_ascii_char () != '(')
return false;
gfc_current_ns = ns;
m = gfc_match_actual_arglist (1, &arglist);
if (m != MATCH_YES)
return false;
if (gfc_match_char (')') != MATCH_YES)
return false;
ns->code = gfc_get_code (EXEC_CALL);
ns->code->symtree = st;
ns->code->ext.actual = arglist;
ns->code->loc = old_loc;
return true;
}
static bool
gfc_omp_udr_predef (gfc_omp_reduction_op rop, const char *name,
gfc_typespec *ts, const char **n)
{
if (!gfc_numeric_ts (ts) && ts->type != BT_LOGICAL)
return false;
switch (rop)
{
case OMP_REDUCTION_PLUS:
case OMP_REDUCTION_MINUS:
case OMP_REDUCTION_TIMES:
return ts->type != BT_LOGICAL;
case OMP_REDUCTION_AND:
case OMP_REDUCTION_OR:
case OMP_REDUCTION_EQV:
case OMP_REDUCTION_NEQV:
return ts->type == BT_LOGICAL;
case OMP_REDUCTION_USER:
if (name[0] != '.' && (ts->type == BT_INTEGER || ts->type == BT_REAL))
{
gfc_symbol *sym;
gfc_find_symbol (name, NULL, 1, &sym);
if (sym != NULL)
{
if (sym->attr.intrinsic)
*n = sym->name;
else if ((sym->attr.flavor != FL_UNKNOWN
&& sym->attr.flavor != FL_PROCEDURE)
|| sym->attr.external
|| sym->attr.generic
|| sym->attr.entry
|| sym->attr.result
|| sym->attr.dummy
|| sym->attr.subroutine
|| sym->attr.pointer
|| sym->attr.target
|| sym->attr.cray_pointer
|| sym->attr.cray_pointee
|| (sym->attr.proc != PROC_UNKNOWN
&& sym->attr.proc != PROC_INTRINSIC)
|| sym->attr.if_source != IFSRC_UNKNOWN
|| sym == sym->ns->proc_name)
*n = NULL;
else
*n = sym->name;
}
else
*n = name;
if (*n
&& (strcmp (*n, "max") == 0 || strcmp (*n, "min") == 0))
return true;
else if (*n
&& ts->type == BT_INTEGER
&& (strcmp (*n, "iand") == 0
|| strcmp (*n, "ior") == 0
|| strcmp (*n, "ieor") == 0))
return true;
}
break;
default:
break;
}
return false;
}
gfc_omp_udr *
gfc_omp_udr_find (gfc_symtree *st, gfc_typespec *ts)
{
gfc_omp_udr *omp_udr;
if (st == NULL)
return NULL;
for (omp_udr = st->n.omp_udr; omp_udr; omp_udr = omp_udr->next)
if (omp_udr->ts.type == ts->type
|| ((omp_udr->ts.type == BT_DERIVED || omp_udr->ts.type == BT_CLASS)
&& (ts->type == BT_DERIVED || ts->type == BT_CLASS)))
{
if (omp_udr->ts.type == BT_DERIVED || omp_udr->ts.type == BT_CLASS)
{
if (strcmp (omp_udr->ts.u.derived->name, ts->u.derived->name) == 0)
return omp_udr;
}
else if (omp_udr->ts.kind == ts->kind)
{
if (omp_udr->ts.type == BT_CHARACTER)
{
if (omp_udr->ts.u.cl->length == NULL
|| ts->u.cl->length == NULL)
return omp_udr;
if (omp_udr->ts.u.cl->length->expr_type != EXPR_CONSTANT)
return omp_udr;
if (ts->u.cl->length->expr_type != EXPR_CONSTANT)
return omp_udr;
if (omp_udr->ts.u.cl->length->ts.type != BT_INTEGER)
return omp_udr;
if (ts->u.cl->length->ts.type != BT_INTEGER)
return omp_udr;
if (gfc_compare_expr (omp_udr->ts.u.cl->length,
ts->u.cl->length, INTRINSIC_EQ) != 0)
continue;
}
return omp_udr;
}
}
return NULL;
}
match
gfc_match_omp_declare_reduction (void)
{
match m;
gfc_intrinsic_op op;
char name[GFC_MAX_SYMBOL_LEN + 3];
auto_vec<gfc_typespec, 5> tss;
gfc_typespec ts;
unsigned int i;
gfc_symtree *st;
locus where = gfc_current_locus;
locus end_loc = gfc_current_locus;
bool end_loc_set = false;
gfc_omp_reduction_op rop = OMP_REDUCTION_NONE;
if (gfc_match_char ('(') != MATCH_YES)
return MATCH_ERROR;
m = gfc_match (" %o : ", &op);
if (m == MATCH_ERROR)
return MATCH_ERROR;
if (m == MATCH_YES)
{
snprintf (name, sizeof name, "operator %s", gfc_op2string (op));
rop = (gfc_omp_reduction_op) op;
}
else
{
m = gfc_match_defined_op_name (name + 1, 1);
if (m == MATCH_ERROR)
return MATCH_ERROR;
if (m == MATCH_YES)
{
name[0] = '.';
strcat (name, ".");
if (gfc_match (" : ") != MATCH_YES)
return MATCH_ERROR;
}
else
{
if (gfc_match (" %n : ", name) != MATCH_YES)
return MATCH_ERROR;
}
rop = OMP_REDUCTION_USER;
}
m = gfc_match_type_spec (&ts);
if (m != MATCH_YES)
return MATCH_ERROR;
/* Treat len=: the same as len=*. */
if (ts.type == BT_CHARACTER)
ts.deferred = false;
tss.safe_push (ts);
while (gfc_match_char (',') == MATCH_YES)
{
m = gfc_match_type_spec (&ts);
if (m != MATCH_YES)
return MATCH_ERROR;
tss.safe_push (ts);
}
if (gfc_match_char (':') != MATCH_YES)
return MATCH_ERROR;
st = gfc_find_symtree (gfc_current_ns->omp_udr_root, name);
for (i = 0; i < tss.length (); i++)
{
gfc_symtree *omp_out, *omp_in;
gfc_symtree *omp_priv = NULL, *omp_orig = NULL;
gfc_namespace *combiner_ns, *initializer_ns = NULL;
gfc_omp_udr *prev_udr, *omp_udr;
const char *predef_name = NULL;
omp_udr = gfc_get_omp_udr ();
omp_udr->name = gfc_get_string (name);
omp_udr->rop = rop;
omp_udr->ts = tss[i];
omp_udr->where = where;
gfc_current_ns = combiner_ns = gfc_get_namespace (gfc_current_ns, 1);
combiner_ns->proc_name = combiner_ns->parent->proc_name;
gfc_get_sym_tree ("omp_out", combiner_ns, &omp_out, false);
gfc_get_sym_tree ("omp_in", combiner_ns, &omp_in, false);
combiner_ns->omp_udr_ns = 1;
omp_out->n.sym->ts = tss[i];
omp_in->n.sym->ts = tss[i];
omp_out->n.sym->attr.omp_udr_artificial_var = 1;
omp_in->n.sym->attr.omp_udr_artificial_var = 1;
omp_out->n.sym->attr.flavor = FL_VARIABLE;
omp_in->n.sym->attr.flavor = FL_VARIABLE;
gfc_commit_symbols ();
omp_udr->combiner_ns = combiner_ns;
omp_udr->omp_out = omp_out->n.sym;
omp_udr->omp_in = omp_in->n.sym;
locus old_loc = gfc_current_locus;
if (!match_udr_expr (omp_out, omp_in))
{
syntax:
gfc_current_locus = old_loc;
gfc_current_ns = combiner_ns->parent;
gfc_undo_symbols ();
gfc_free_omp_udr (omp_udr);
return MATCH_ERROR;
}
if (gfc_match (" initializer ( ") == MATCH_YES)
{
gfc_current_ns = combiner_ns->parent;
initializer_ns = gfc_get_namespace (gfc_current_ns, 1);
gfc_current_ns = initializer_ns;
initializer_ns->proc_name = initializer_ns->parent->proc_name;
gfc_get_sym_tree ("omp_priv", initializer_ns, &omp_priv, false);
gfc_get_sym_tree ("omp_orig", initializer_ns, &omp_orig, false);
initializer_ns->omp_udr_ns = 1;
omp_priv->n.sym->ts = tss[i];
omp_orig->n.sym->ts = tss[i];
omp_priv->n.sym->attr.omp_udr_artificial_var = 1;
omp_orig->n.sym->attr.omp_udr_artificial_var = 1;
omp_priv->n.sym->attr.flavor = FL_VARIABLE;
omp_orig->n.sym->attr.flavor = FL_VARIABLE;
gfc_commit_symbols ();
omp_udr->initializer_ns = initializer_ns;
omp_udr->omp_priv = omp_priv->n.sym;
omp_udr->omp_orig = omp_orig->n.sym;
if (!match_udr_expr (omp_priv, omp_orig))
goto syntax;
}
gfc_current_ns = combiner_ns->parent;
if (!end_loc_set)
{
end_loc_set = true;
end_loc = gfc_current_locus;
}
gfc_current_locus = old_loc;
prev_udr = gfc_omp_udr_find (st, &tss[i]);
if (gfc_omp_udr_predef (rop, name, &tss[i], &predef_name)
/* Don't error on !$omp declare reduction (min : integer : ...)
just yet, there could be integer :: min afterwards,
making it valid. When the UDR is resolved, we'll get
to it again. */
&& (rop != OMP_REDUCTION_USER || name[0] == '.'))
{
if (predef_name)
gfc_error_now ("Redefinition of predefined %s "
"!$OMP DECLARE REDUCTION at %L",
predef_name, &where);
else
gfc_error_now ("Redefinition of predefined "
"!$OMP DECLARE REDUCTION at %L", &where);
}
else if (prev_udr)
{
gfc_error_now ("Redefinition of !$OMP DECLARE REDUCTION at %L",
&where);
gfc_error_now ("Previous !$OMP DECLARE REDUCTION at %L",
&prev_udr->where);
}
else if (st)
{
omp_udr->next = st->n.omp_udr;
st->n.omp_udr = omp_udr;
}
else
{
st = gfc_new_symtree (&gfc_current_ns->omp_udr_root, name);
st->n.omp_udr = omp_udr;
}
}
if (end_loc_set)
{
gfc_current_locus = end_loc;
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after !$OMP DECLARE REDUCTION at %C");
gfc_current_locus = where;
return MATCH_ERROR;
}
return MATCH_YES;
}
gfc_clear_error ();
return MATCH_ERROR;
}
match
gfc_match_omp_declare_target (void)
{
locus old_loc;
char n[GFC_MAX_SYMBOL_LEN+1];
gfc_symbol *sym;
match m;
gfc_symtree *st;
old_loc = gfc_current_locus;
m = gfc_match (" (");
if (gfc_current_ns->proc_name
&& gfc_current_ns->proc_name->attr.if_source == IFSRC_IFBODY
&& m == MATCH_YES)
{
gfc_error ("Only the !$OMP DECLARE TARGET form without "
"list is allowed in interface block at %C");
goto cleanup;
}
if (m == MATCH_NO
&& gfc_current_ns->proc_name
&& gfc_match_omp_eos () == MATCH_YES)
{
if (!gfc_add_omp_declare_target (&gfc_current_ns->proc_name->attr,
gfc_current_ns->proc_name->name,
&old_loc))
goto cleanup;
return MATCH_YES;
}
if (m != MATCH_YES)
return m;
for (;;)
{
m = gfc_match_symbol (&sym, 0);
switch (m)
{
case MATCH_YES:
if (sym->attr.in_common)
gfc_error_now ("OMP DECLARE TARGET on a variable at %C is an "
"element of a COMMON block");
else if (!gfc_add_omp_declare_target (&sym->attr, sym->name,
&sym->declared_at))
goto cleanup;
goto next_item;
case MATCH_NO:
break;
case MATCH_ERROR:
goto cleanup;
}
m = gfc_match (" / %n /", n);
if (m == MATCH_ERROR)
goto cleanup;
if (m == MATCH_NO || n[0] == '\0')
goto syntax;
st = gfc_find_symtree (gfc_current_ns->common_root, n);
if (st == NULL)
{
gfc_error ("COMMON block /%s/ not found at %C", n);
goto cleanup;
}
st->n.common->omp_declare_target = 1;
for (sym = st->n.common->head; sym; sym = sym->common_next)
if (!gfc_add_omp_declare_target (&sym->attr, sym->name,
&sym->declared_at))
goto cleanup;
next_item:
if (gfc_match_char (')') == MATCH_YES)
break;
if (gfc_match_char (',') != MATCH_YES)
goto syntax;
}
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after !$OMP DECLARE TARGET at %C");
goto cleanup;
}
return MATCH_YES;
syntax:
gfc_error ("Syntax error in !$OMP DECLARE TARGET list at %C");
cleanup:
gfc_current_locus = old_loc;
return MATCH_ERROR;
}
match
gfc_match_omp_threadprivate (void)
{
locus old_loc;
char n[GFC_MAX_SYMBOL_LEN+1];
gfc_symbol *sym;
match m;
gfc_symtree *st;
old_loc = gfc_current_locus;
m = gfc_match (" (");
if (m != MATCH_YES)
return m;
for (;;)
{
m = gfc_match_symbol (&sym, 0);
switch (m)
{
case MATCH_YES:
if (sym->attr.in_common)
gfc_error_now ("Threadprivate variable at %C is an element of "
"a COMMON block");
else if (!gfc_add_threadprivate (&sym->attr, sym->name, &sym->declared_at))
goto cleanup;
goto next_item;
case MATCH_NO:
break;
case MATCH_ERROR:
goto cleanup;
}
m = gfc_match (" / %n /", n);
if (m == MATCH_ERROR)
goto cleanup;
if (m == MATCH_NO || n[0] == '\0')
goto syntax;
st = gfc_find_symtree (gfc_current_ns->common_root, n);
if (st == NULL)
{
gfc_error ("COMMON block /%s/ not found at %C", n);
goto cleanup;
}
st->n.common->threadprivate = 1;
for (sym = st->n.common->head; sym; sym = sym->common_next)
if (!gfc_add_threadprivate (&sym->attr, sym->name, &sym->declared_at))
goto cleanup;
next_item:
if (gfc_match_char (')') == MATCH_YES)
break;
if (gfc_match_char (',') != MATCH_YES)
goto syntax;
}
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after OMP THREADPRIVATE at %C");
goto cleanup;
}
return MATCH_YES;
syntax:
gfc_error ("Syntax error in !$OMP THREADPRIVATE list at %C");
cleanup:
gfc_current_locus = old_loc;
return MATCH_ERROR;
}
match
gfc_match_omp_parallel (void)
{
return match_omp (EXEC_OMP_PARALLEL, OMP_PARALLEL_CLAUSES);
}
match
gfc_match_omp_parallel_do (void)
{
return match_omp (EXEC_OMP_PARALLEL_DO,
OMP_PARALLEL_CLAUSES | OMP_DO_CLAUSES);
}
match
gfc_match_omp_parallel_do_simd (void)
{
return match_omp (EXEC_OMP_PARALLEL_DO_SIMD,
(OMP_PARALLEL_CLAUSES | OMP_DO_CLAUSES | OMP_SIMD_CLAUSES)
& ~OMP_CLAUSE_ORDERED);
}
match
gfc_match_omp_parallel_sections (void)
{
return match_omp (EXEC_OMP_PARALLEL_SECTIONS,
OMP_PARALLEL_CLAUSES | OMP_SECTIONS_CLAUSES);
}
match
gfc_match_omp_parallel_workshare (void)
{
return match_omp (EXEC_OMP_PARALLEL_WORKSHARE, OMP_PARALLEL_CLAUSES);
}
match
gfc_match_omp_sections (void)
{
return match_omp (EXEC_OMP_SECTIONS, OMP_SECTIONS_CLAUSES);
}
match
gfc_match_omp_simd (void)
{
return match_omp (EXEC_OMP_SIMD, OMP_SIMD_CLAUSES);
}
match
gfc_match_omp_single (void)
{
return match_omp (EXEC_OMP_SINGLE,
OMP_CLAUSE_PRIVATE | OMP_CLAUSE_FIRSTPRIVATE);
}
match
gfc_match_omp_task (void)
{
return match_omp (EXEC_OMP_TASK, OMP_TASK_CLAUSES);
}
match
gfc_match_omp_taskwait (void)
{
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after TASKWAIT clause at %C");
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_TASKWAIT;
new_st.ext.omp_clauses = NULL;
return MATCH_YES;
}
match
gfc_match_omp_taskyield (void)
{
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after TASKYIELD clause at %C");
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_TASKYIELD;
new_st.ext.omp_clauses = NULL;
return MATCH_YES;
}
match
gfc_match_omp_target (void)
{
return match_omp (EXEC_OMP_TARGET, OMP_TARGET_CLAUSES);
}
match
gfc_match_omp_target_data (void)
{
return match_omp (EXEC_OMP_TARGET_DATA, OMP_TARGET_DATA_CLAUSES);
}
match
gfc_match_omp_target_teams (void)
{
return match_omp (EXEC_OMP_TARGET_TEAMS,
OMP_TARGET_CLAUSES | OMP_TEAMS_CLAUSES);
}
match
gfc_match_omp_target_teams_distribute (void)
{
return match_omp (EXEC_OMP_TARGET_TEAMS_DISTRIBUTE,
OMP_TARGET_CLAUSES | OMP_TEAMS_CLAUSES
| OMP_DISTRIBUTE_CLAUSES);
}
match
gfc_match_omp_target_teams_distribute_parallel_do (void)
{
return match_omp (EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO,
OMP_TARGET_CLAUSES | OMP_TEAMS_CLAUSES
| OMP_DISTRIBUTE_CLAUSES | OMP_PARALLEL_CLAUSES
| OMP_DO_CLAUSES);
}
match
gfc_match_omp_target_teams_distribute_parallel_do_simd (void)
{
return match_omp (EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD,
(OMP_TARGET_CLAUSES | OMP_TEAMS_CLAUSES
| OMP_DISTRIBUTE_CLAUSES | OMP_PARALLEL_CLAUSES
| OMP_DO_CLAUSES | OMP_SIMD_CLAUSES)
& ~OMP_CLAUSE_ORDERED);
}
match
gfc_match_omp_target_teams_distribute_simd (void)
{
return match_omp (EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_SIMD,
OMP_TARGET_CLAUSES | OMP_TEAMS_CLAUSES
| OMP_DISTRIBUTE_CLAUSES | OMP_SIMD_CLAUSES);
}
match
gfc_match_omp_target_update (void)
{
return match_omp (EXEC_OMP_TARGET_UPDATE, OMP_TARGET_UPDATE_CLAUSES);
}
match
gfc_match_omp_teams (void)
{
return match_omp (EXEC_OMP_TEAMS, OMP_TEAMS_CLAUSES);
}
match
gfc_match_omp_teams_distribute (void)
{
return match_omp (EXEC_OMP_TEAMS_DISTRIBUTE,
OMP_TEAMS_CLAUSES | OMP_DISTRIBUTE_CLAUSES);
}
match
gfc_match_omp_teams_distribute_parallel_do (void)
{
return match_omp (EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO,
OMP_TEAMS_CLAUSES | OMP_DISTRIBUTE_CLAUSES
| OMP_PARALLEL_CLAUSES | OMP_DO_CLAUSES);
}
match
gfc_match_omp_teams_distribute_parallel_do_simd (void)
{
return match_omp (EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD,
(OMP_TEAMS_CLAUSES | OMP_DISTRIBUTE_CLAUSES
| OMP_PARALLEL_CLAUSES | OMP_DO_CLAUSES
| OMP_SIMD_CLAUSES) & ~OMP_CLAUSE_ORDERED);
}
match
gfc_match_omp_teams_distribute_simd (void)
{
return match_omp (EXEC_OMP_TEAMS_DISTRIBUTE_SIMD,
OMP_TEAMS_CLAUSES | OMP_DISTRIBUTE_CLAUSES
| OMP_SIMD_CLAUSES);
}
match
gfc_match_omp_workshare (void)
{
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after $OMP WORKSHARE statement at %C");
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_WORKSHARE;
new_st.ext.omp_clauses = gfc_get_omp_clauses ();
return MATCH_YES;
}
match
gfc_match_omp_master (void)
{
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after $OMP MASTER statement at %C");
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_MASTER;
new_st.ext.omp_clauses = NULL;
return MATCH_YES;
}
match
gfc_match_omp_ordered (void)
{
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after $OMP ORDERED statement at %C");
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_ORDERED;
new_st.ext.omp_clauses = NULL;
return MATCH_YES;
}
static match
gfc_match_omp_oacc_atomic (bool omp_p)
{
gfc_omp_atomic_op op = GFC_OMP_ATOMIC_UPDATE;
int seq_cst = 0;
if (gfc_match ("% seq_cst") == MATCH_YES)
seq_cst = 1;
locus old_loc = gfc_current_locus;
if (seq_cst && gfc_match_char (',') == MATCH_YES)
seq_cst = 2;
if (seq_cst == 2
|| gfc_match_space () == MATCH_YES)
{
gfc_gobble_whitespace ();
if (gfc_match ("update") == MATCH_YES)
op = GFC_OMP_ATOMIC_UPDATE;
else if (gfc_match ("read") == MATCH_YES)
op = GFC_OMP_ATOMIC_READ;
else if (gfc_match ("write") == MATCH_YES)
op = GFC_OMP_ATOMIC_WRITE;
else if (gfc_match ("capture") == MATCH_YES)
op = GFC_OMP_ATOMIC_CAPTURE;
else
{
if (seq_cst == 2)
gfc_current_locus = old_loc;
goto finish;
}
if (!seq_cst
&& (gfc_match (", seq_cst") == MATCH_YES
|| gfc_match ("% seq_cst") == MATCH_YES))
seq_cst = 1;
}
finish:
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after $OMP ATOMIC statement at %C");
return MATCH_ERROR;
}
new_st.op = (omp_p ? EXEC_OMP_ATOMIC : EXEC_OACC_ATOMIC);
if (seq_cst)
op = (gfc_omp_atomic_op) (op | GFC_OMP_ATOMIC_SEQ_CST);
new_st.ext.omp_atomic = op;
return MATCH_YES;
}
match
gfc_match_oacc_atomic (void)
{
return gfc_match_omp_oacc_atomic (false);
}
match
gfc_match_omp_atomic (void)
{
return gfc_match_omp_oacc_atomic (true);
}
match
gfc_match_omp_barrier (void)
{
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after $OMP BARRIER statement at %C");
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_BARRIER;
new_st.ext.omp_clauses = NULL;
return MATCH_YES;
}
match
gfc_match_omp_taskgroup (void)
{
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after $OMP TASKGROUP statement at %C");
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_TASKGROUP;
return MATCH_YES;
}
static enum gfc_omp_cancel_kind
gfc_match_omp_cancel_kind (void)
{
if (gfc_match_space () != MATCH_YES)
return OMP_CANCEL_UNKNOWN;
if (gfc_match ("parallel") == MATCH_YES)
return OMP_CANCEL_PARALLEL;
if (gfc_match ("sections") == MATCH_YES)
return OMP_CANCEL_SECTIONS;
if (gfc_match ("do") == MATCH_YES)
return OMP_CANCEL_DO;
if (gfc_match ("taskgroup") == MATCH_YES)
return OMP_CANCEL_TASKGROUP;
return OMP_CANCEL_UNKNOWN;
}
match
gfc_match_omp_cancel (void)
{
gfc_omp_clauses *c;
enum gfc_omp_cancel_kind kind = gfc_match_omp_cancel_kind ();
if (kind == OMP_CANCEL_UNKNOWN)
return MATCH_ERROR;
if (gfc_match_omp_clauses (&c, OMP_CLAUSE_IF, false) != MATCH_YES)
return MATCH_ERROR;
c->cancel = kind;
new_st.op = EXEC_OMP_CANCEL;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_omp_cancellation_point (void)
{
gfc_omp_clauses *c;
enum gfc_omp_cancel_kind kind = gfc_match_omp_cancel_kind ();
if (kind == OMP_CANCEL_UNKNOWN)
return MATCH_ERROR;
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after $OMP CANCELLATION POINT statement "
"at %C");
return MATCH_ERROR;
}
c = gfc_get_omp_clauses ();
c->cancel = kind;
new_st.op = EXEC_OMP_CANCELLATION_POINT;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
match
gfc_match_omp_end_nowait (void)
{
bool nowait = false;
if (gfc_match ("% nowait") == MATCH_YES)
nowait = true;
if (gfc_match_omp_eos () != MATCH_YES)
{
gfc_error ("Unexpected junk after NOWAIT clause at %C");
return MATCH_ERROR;
}
new_st.op = EXEC_OMP_END_NOWAIT;
new_st.ext.omp_bool = nowait;
return MATCH_YES;
}
match
gfc_match_omp_end_single (void)
{
gfc_omp_clauses *c;
if (gfc_match ("% nowait") == MATCH_YES)
{
new_st.op = EXEC_OMP_END_NOWAIT;
new_st.ext.omp_bool = true;
return MATCH_YES;
}
if (gfc_match_omp_clauses (&c, OMP_CLAUSE_COPYPRIVATE) != MATCH_YES)
return MATCH_ERROR;
new_st.op = EXEC_OMP_END_SINGLE;
new_st.ext.omp_clauses = c;
return MATCH_YES;
}
static bool
oacc_is_loop (gfc_code *code)
{
return code->op == EXEC_OACC_PARALLEL_LOOP
|| code->op == EXEC_OACC_KERNELS_LOOP
|| code->op == EXEC_OACC_LOOP;
}
static void
resolve_oacc_scalar_int_expr (gfc_expr *expr, const char *clause)
{
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER || expr->rank != 0)
gfc_error ("%s clause at %L requires a scalar INTEGER expression",
clause, &expr->where);
}
static void
resolve_oacc_positive_int_expr (gfc_expr *expr, const char *clause)
{
resolve_oacc_scalar_int_expr (expr, clause);
if (expr->expr_type == EXPR_CONSTANT && expr->ts.type == BT_INTEGER
&& mpz_sgn(expr->value.integer) <= 0)
gfc_warning (0, "INTEGER expression of %s clause at %L must be positive",
clause, &expr->where);
}
/* Emits error when symbol is pointer, cray pointer or cray pointee
of derived of polymorphic type. */
static void
check_symbol_not_pointer (gfc_symbol *sym, locus loc, const char *name)
{
if (sym->ts.type == BT_DERIVED && sym->attr.pointer)
gfc_error ("POINTER object %qs of derived type in %s clause at %L",
sym->name, name, &loc);
if (sym->ts.type == BT_DERIVED && sym->attr.cray_pointer)
gfc_error ("Cray pointer object of derived type %qs in %s clause at %L",
sym->name, name, &loc);
if (sym->ts.type == BT_DERIVED && sym->attr.cray_pointee)
gfc_error ("Cray pointee object of derived type %qs in %s clause at %L",
sym->name, name, &loc);
if ((sym->ts.type == BT_ASSUMED && sym->attr.pointer)
|| (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
&& CLASS_DATA (sym)->attr.pointer))
gfc_error ("POINTER object %qs of polymorphic type in %s clause at %L",
sym->name, name, &loc);
if ((sym->ts.type == BT_ASSUMED && sym->attr.cray_pointer)
|| (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
&& CLASS_DATA (sym)->attr.cray_pointer))
gfc_error ("Cray pointer object of polymorphic type %qs in %s clause at %L",
sym->name, name, &loc);
if ((sym->ts.type == BT_ASSUMED && sym->attr.cray_pointee)
|| (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
&& CLASS_DATA (sym)->attr.cray_pointee))
gfc_error ("Cray pointee object of polymorphic type %qs in %s clause at %L",
sym->name, name, &loc);
}
/* Emits error when symbol represents assumed size/rank array. */
static void
check_array_not_assumed (gfc_symbol *sym, locus loc, const char *name)
{
if (sym->as && sym->as->type == AS_ASSUMED_SIZE)
gfc_error ("Assumed size array %qs in %s clause at %L",
sym->name, name, &loc);
if (sym->as && sym->as->type == AS_ASSUMED_RANK)
gfc_error ("Assumed rank array %qs in %s clause at %L",
sym->name, name, &loc);
if (sym->as && sym->as->type == AS_DEFERRED && sym->attr.pointer
&& !sym->attr.contiguous)
gfc_error ("Noncontiguous deferred shape array %qs in %s clause at %L",
sym->name, name, &loc);
}
static void
resolve_oacc_data_clauses (gfc_symbol *sym, locus loc, const char *name)
{
if (sym->ts.type == BT_DERIVED && sym->attr.allocatable)
gfc_error ("ALLOCATABLE object %qs of derived type in %s clause at %L",
sym->name, name, &loc);
if ((sym->ts.type == BT_ASSUMED && sym->attr.allocatable)
|| (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
&& CLASS_DATA (sym)->attr.allocatable))
gfc_error ("ALLOCATABLE object %qs of polymorphic type "
"in %s clause at %L", sym->name, name, &loc);
check_symbol_not_pointer (sym, loc, name);
check_array_not_assumed (sym, loc, name);
}
static void
resolve_oacc_deviceptr_clause (gfc_symbol *sym, locus loc, const char *name)
{
if (sym->attr.pointer
|| (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
&& CLASS_DATA (sym)->attr.class_pointer))
gfc_error ("POINTER object %qs in %s clause at %L",
sym->name, name, &loc);
if (sym->attr.cray_pointer
|| (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
&& CLASS_DATA (sym)->attr.cray_pointer))
gfc_error ("Cray pointer object %qs in %s clause at %L",
sym->name, name, &loc);
if (sym->attr.cray_pointee
|| (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
&& CLASS_DATA (sym)->attr.cray_pointee))
gfc_error ("Cray pointee object %qs in %s clause at %L",
sym->name, name, &loc);
if (sym->attr.allocatable
|| (sym->ts.type == BT_CLASS && CLASS_DATA (sym)
&& CLASS_DATA (sym)->attr.allocatable))
gfc_error ("ALLOCATABLE object %qs in %s clause at %L",
sym->name, name, &loc);
if (sym->attr.value)
gfc_error ("VALUE object %qs in %s clause at %L",
sym->name, name, &loc);
check_array_not_assumed (sym, loc, name);
}
struct resolve_omp_udr_callback_data
{
gfc_symbol *sym1, *sym2;
};
static int
resolve_omp_udr_callback (gfc_expr **e, int *, void *data)
{
struct resolve_omp_udr_callback_data *rcd
= (struct resolve_omp_udr_callback_data *) data;
if ((*e)->expr_type == EXPR_VARIABLE
&& ((*e)->symtree->n.sym == rcd->sym1
|| (*e)->symtree->n.sym == rcd->sym2))
{
gfc_ref *ref = gfc_get_ref ();
ref->type = REF_ARRAY;
ref->u.ar.where = (*e)->where;
ref->u.ar.as = (*e)->symtree->n.sym->as;
ref->u.ar.type = AR_FULL;
ref->u.ar.dimen = 0;
ref->next = (*e)->ref;
(*e)->ref = ref;
}
return 0;
}
static int
resolve_omp_udr_callback2 (gfc_expr **e, int *, void *)
{
if ((*e)->expr_type == EXPR_FUNCTION
&& (*e)->value.function.isym == NULL)
{
gfc_symbol *sym = (*e)->symtree->n.sym;
if (!sym->attr.intrinsic
&& sym->attr.if_source == IFSRC_UNKNOWN)
gfc_error ("Implicitly declared function %s used in "
"!$OMP DECLARE REDUCTION at %L ", sym->name, &(*e)->where);
}
return 0;
}
static gfc_code *
resolve_omp_udr_clause (gfc_omp_namelist *n, gfc_namespace *ns,
gfc_symbol *sym1, gfc_symbol *sym2)
{
gfc_code *copy;
gfc_symbol sym1_copy, sym2_copy;
if (ns->code->op == EXEC_ASSIGN)
{
copy = gfc_get_code (EXEC_ASSIGN);
copy->expr1 = gfc_copy_expr (ns->code->expr1);
copy->expr2 = gfc_copy_expr (ns->code->expr2);
}
else
{
copy = gfc_get_code (EXEC_CALL);
copy->symtree = ns->code->symtree;
copy->ext.actual = gfc_copy_actual_arglist (ns->code->ext.actual);
}
copy->loc = ns->code->loc;
sym1_copy = *sym1;
sym2_copy = *sym2;
*sym1 = *n->sym;
*sym2 = *n->sym;
sym1->name = sym1_copy.name;
sym2->name = sym2_copy.name;
ns->proc_name = ns->parent->proc_name;
if (n->sym->attr.dimension)
{
struct resolve_omp_udr_callback_data rcd;
rcd.sym1 = sym1;
rcd.sym2 = sym2;
gfc_code_walker (©, gfc_dummy_code_callback,
resolve_omp_udr_callback, &rcd);
}
gfc_resolve_code (copy, gfc_current_ns);
if (copy->op == EXEC_CALL && copy->resolved_isym == NULL)
{
gfc_symbol *sym = copy->resolved_sym;
if (sym
&& !sym->attr.intrinsic
&& sym->attr.if_source == IFSRC_UNKNOWN)
gfc_error ("Implicitly declared subroutine %s used in "
"!$OMP DECLARE REDUCTION at %L ", sym->name,
©->loc);
}
gfc_code_walker (©, gfc_dummy_code_callback,
resolve_omp_udr_callback2, NULL);
*sym1 = sym1_copy;
*sym2 = sym2_copy;
return copy;
}
/* OpenMP directive resolving routines. */
static void
resolve_omp_clauses (gfc_code *code, gfc_omp_clauses *omp_clauses,
gfc_namespace *ns, bool openacc = false)
{
gfc_omp_namelist *n;
gfc_expr_list *el;
int list;
static const char *clause_names[]
= { "PRIVATE", "FIRSTPRIVATE", "LASTPRIVATE", "COPYPRIVATE", "SHARED",
"COPYIN", "UNIFORM", "ALIGNED", "LINEAR", "DEPEND", "MAP",
"TO", "FROM", "REDUCTION", "DEVICE_RESIDENT", "LINK", "USE_DEVICE",
"CACHE" };
if (omp_clauses == NULL)
return;
if (omp_clauses->if_expr)
{
gfc_expr *expr = omp_clauses->if_expr;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_LOGICAL || expr->rank != 0)
gfc_error ("IF clause at %L requires a scalar LOGICAL expression",
&expr->where);
}
if (omp_clauses->final_expr)
{
gfc_expr *expr = omp_clauses->final_expr;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_LOGICAL || expr->rank != 0)
gfc_error ("FINAL clause at %L requires a scalar LOGICAL expression",
&expr->where);
}
if (omp_clauses->num_threads)
{
gfc_expr *expr = omp_clauses->num_threads;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER || expr->rank != 0)
gfc_error ("NUM_THREADS clause at %L requires a scalar "
"INTEGER expression", &expr->where);
}
if (omp_clauses->chunk_size)
{
gfc_expr *expr = omp_clauses->chunk_size;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER || expr->rank != 0)
gfc_error ("SCHEDULE clause's chunk_size at %L requires "
"a scalar INTEGER expression", &expr->where);
}
/* Check that no symbol appears on multiple clauses, except that
a symbol can appear on both firstprivate and lastprivate. */
for (list = 0; list < OMP_LIST_NUM; list++)
for (n = omp_clauses->lists[list]; n; n = n->next)
{
n->sym->mark = 0;
if (n->sym->attr.flavor == FL_VARIABLE
|| n->sym->attr.proc_pointer
|| (!code && (!n->sym->attr.dummy || n->sym->ns != ns)))
{
if (!code && (!n->sym->attr.dummy || n->sym->ns != ns))
gfc_error ("Variable %qs is not a dummy argument at %L",
n->sym->name, &n->where);
continue;
}
if (n->sym->attr.flavor == FL_PROCEDURE
&& n->sym->result == n->sym
&& n->sym->attr.function)
{
if (gfc_current_ns->proc_name == n->sym
|| (gfc_current_ns->parent
&& gfc_current_ns->parent->proc_name == n->sym))
continue;
if (gfc_current_ns->proc_name->attr.entry_master)
{
gfc_entry_list *el = gfc_current_ns->entries;
for (; el; el = el->next)
if (el->sym == n->sym)
break;
if (el)
continue;
}
if (gfc_current_ns->parent
&& gfc_current_ns->parent->proc_name->attr.entry_master)
{
gfc_entry_list *el = gfc_current_ns->parent->entries;
for (; el; el = el->next)
if (el->sym == n->sym)
break;
if (el)
continue;
}
}
gfc_error ("Object %qs is not a variable at %L", n->sym->name,
&n->where);
}
for (list = 0; list < OMP_LIST_NUM; list++)
if (list != OMP_LIST_FIRSTPRIVATE
&& list != OMP_LIST_LASTPRIVATE
&& list != OMP_LIST_ALIGNED
&& list != OMP_LIST_DEPEND
&& (list != OMP_LIST_MAP || openacc)
&& list != OMP_LIST_FROM
&& list != OMP_LIST_TO
&& (list != OMP_LIST_REDUCTION || !openacc))
for (n = omp_clauses->lists[list]; n; n = n->next)
{
if (n->sym->mark)
gfc_error ("Symbol %qs present on multiple clauses at %L",
n->sym->name, &n->where);
else
n->sym->mark = 1;
}
gcc_assert (OMP_LIST_LASTPRIVATE == OMP_LIST_FIRSTPRIVATE + 1);
for (list = OMP_LIST_FIRSTPRIVATE; list <= OMP_LIST_LASTPRIVATE; list++)
for (n = omp_clauses->lists[list]; n; n = n->next)
if (n->sym->mark)
{
gfc_error ("Symbol %qs present on multiple clauses at %L",
n->sym->name, &n->where);
n->sym->mark = 0;
}
for (n = omp_clauses->lists[OMP_LIST_FIRSTPRIVATE]; n; n = n->next)
{
if (n->sym->mark)
gfc_error ("Symbol %qs present on multiple clauses at %L",
n->sym->name, &n->where);
else
n->sym->mark = 1;
}
for (n = omp_clauses->lists[OMP_LIST_LASTPRIVATE]; n; n = n->next)
n->sym->mark = 0;
for (n = omp_clauses->lists[OMP_LIST_LASTPRIVATE]; n; n = n->next)
{
if (n->sym->mark)
gfc_error ("Symbol %qs present on multiple clauses at %L",
n->sym->name, &n->where);
else
n->sym->mark = 1;
}
for (n = omp_clauses->lists[OMP_LIST_ALIGNED]; n; n = n->next)
n->sym->mark = 0;
for (n = omp_clauses->lists[OMP_LIST_ALIGNED]; n; n = n->next)
{
if (n->sym->mark)
gfc_error ("Symbol %qs present on multiple clauses at %L",
n->sym->name, &n->where);
else
n->sym->mark = 1;
}
/* OpenACC reductions. */
if (openacc)
{
for (n = omp_clauses->lists[OMP_LIST_REDUCTION]; n; n = n->next)
n->sym->mark = 0;
for (n = omp_clauses->lists[OMP_LIST_REDUCTION]; n; n = n->next)
{
if (n->sym->mark)
gfc_error ("Symbol %qs present on multiple clauses at %L",
n->sym->name, &n->where);
else
n->sym->mark = 1;
/* OpenACC does not support reductions on arrays. */
if (n->sym->as)
gfc_error ("Array %qs is not permitted in reduction at %L",
n->sym->name, &n->where);
}
}
for (n = omp_clauses->lists[OMP_LIST_TO]; n; n = n->next)
n->sym->mark = 0;
for (n = omp_clauses->lists[OMP_LIST_FROM]; n; n = n->next)
if (n->expr == NULL)
n->sym->mark = 1;
for (n = omp_clauses->lists[OMP_LIST_TO]; n; n = n->next)
{
if (n->expr == NULL && n->sym->mark)
gfc_error ("Symbol %qs present on both FROM and TO clauses at %L",
n->sym->name, &n->where);
else
n->sym->mark = 1;
}
for (list = 0; list < OMP_LIST_NUM; list++)
if ((n = omp_clauses->lists[list]) != NULL)
{
const char *name;
if (list < OMP_LIST_NUM)
name = clause_names[list];
else
gcc_unreachable ();
switch (list)
{
case OMP_LIST_COPYIN:
for (; n != NULL; n = n->next)
{
if (!n->sym->attr.threadprivate)
gfc_error ("Non-THREADPRIVATE object %qs in COPYIN clause"
" at %L", n->sym->name, &n->where);
}
break;
case OMP_LIST_COPYPRIVATE:
for (; n != NULL; n = n->next)
{
if (n->sym->as && n->sym->as->type == AS_ASSUMED_SIZE)
gfc_error ("Assumed size array %qs in COPYPRIVATE clause "
"at %L", n->sym->name, &n->where);
if (n->sym->attr.pointer && n->sym->attr.intent == INTENT_IN)
gfc_error ("INTENT(IN) POINTER %qs in COPYPRIVATE clause "
"at %L", n->sym->name, &n->where);
}
break;
case OMP_LIST_SHARED:
for (; n != NULL; n = n->next)
{
if (n->sym->attr.threadprivate)
gfc_error ("THREADPRIVATE object %qs in SHARED clause at "
"%L", n->sym->name, &n->where);
if (n->sym->attr.cray_pointee)
gfc_error ("Cray pointee %qs in SHARED clause at %L",
n->sym->name, &n->where);
if (n->sym->attr.associate_var)
gfc_error ("ASSOCIATE name %qs in SHARED clause at %L",
n->sym->name, &n->where);
}
break;
case OMP_LIST_ALIGNED:
for (; n != NULL; n = n->next)
{
if (!n->sym->attr.pointer
&& !n->sym->attr.allocatable
&& !n->sym->attr.cray_pointer
&& (n->sym->ts.type != BT_DERIVED
|| (n->sym->ts.u.derived->from_intmod
!= INTMOD_ISO_C_BINDING)
|| (n->sym->ts.u.derived->intmod_sym_id
!= ISOCBINDING_PTR)))
gfc_error ("%qs in ALIGNED clause must be POINTER, "
"ALLOCATABLE, Cray pointer or C_PTR at %L",
n->sym->name, &n->where);
else if (n->expr)
{
gfc_expr *expr = n->expr;
int alignment = 0;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER
|| expr->rank != 0
|| gfc_extract_int (expr, &alignment)
|| alignment <= 0)
gfc_error ("%qs in ALIGNED clause at %L requires a scalar "
"positive constant integer alignment "
"expression", n->sym->name, &n->where);
}
}
break;
case OMP_LIST_DEPEND:
case OMP_LIST_MAP:
case OMP_LIST_TO:
case OMP_LIST_FROM:
case OMP_LIST_CACHE:
for (; n != NULL; n = n->next)
{
if (n->expr)
{
if (!gfc_resolve_expr (n->expr)
|| n->expr->expr_type != EXPR_VARIABLE
|| n->expr->ref == NULL
|| n->expr->ref->next
|| n->expr->ref->type != REF_ARRAY)
gfc_error ("%qs in %s clause at %L is not a proper "
"array section", n->sym->name, name,
&n->where);
else if (n->expr->ref->u.ar.codimen)
gfc_error ("Coarrays not supported in %s clause at %L",
name, &n->where);
else
{
int i;
gfc_array_ref *ar = &n->expr->ref->u.ar;
for (i = 0; i < ar->dimen; i++)
if (ar->stride[i])
{
gfc_error ("Stride should not be specified for "
"array section in %s clause at %L",
name, &n->where);
break;
}
else if (ar->dimen_type[i] != DIMEN_ELEMENT
&& ar->dimen_type[i] != DIMEN_RANGE)
{
gfc_error ("%qs in %s clause at %L is not a "
"proper array section",
n->sym->name, name, &n->where);
break;
}
else if (list == OMP_LIST_DEPEND
&& ar->start[i]
&& ar->start[i]->expr_type == EXPR_CONSTANT
&& ar->end[i]
&& ar->end[i]->expr_type == EXPR_CONSTANT
&& mpz_cmp (ar->start[i]->value.integer,
ar->end[i]->value.integer) > 0)
{
gfc_error ("%qs in DEPEND clause at %L is a "
"zero size array section",
n->sym->name, &n->where);
break;
}
}
}
else if (openacc)
{
if (list == OMP_LIST_MAP
&& n->u.map_op == OMP_MAP_FORCE_DEVICEPTR)
resolve_oacc_deviceptr_clause (n->sym, n->where, name);
else
resolve_oacc_data_clauses (n->sym, n->where, name);
}
}
if (list != OMP_LIST_DEPEND)
for (n = omp_clauses->lists[list]; n != NULL; n = n->next)
{
n->sym->attr.referenced = 1;
if (n->sym->attr.threadprivate)
gfc_error ("THREADPRIVATE object %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.cray_pointee)
gfc_error ("Cray pointee %qs in %s clause at %L",
n->sym->name, name, &n->where);
}
break;
default:
for (; n != NULL; n = n->next)
{
bool bad = false;
if (n->sym->attr.threadprivate)
gfc_error ("THREADPRIVATE object %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.cray_pointee)
gfc_error ("Cray pointee %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.associate_var)
gfc_error ("ASSOCIATE name %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (list != OMP_LIST_PRIVATE)
{
if (n->sym->attr.proc_pointer && list == OMP_LIST_REDUCTION)
gfc_error ("Procedure pointer %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.pointer && list == OMP_LIST_REDUCTION)
gfc_error ("POINTER object %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.cray_pointer && list == OMP_LIST_REDUCTION)
gfc_error ("Cray pointer %qs in %s clause at %L",
n->sym->name, name, &n->where);
}
if (code
&& (oacc_is_loop (code) || code->op == EXEC_OACC_PARALLEL))
check_array_not_assumed (n->sym, n->where, name);
else if (n->sym->as && n->sym->as->type == AS_ASSUMED_SIZE)
gfc_error ("Assumed size array %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.in_namelist && list != OMP_LIST_REDUCTION)
gfc_error ("Variable %qs in %s clause is used in "
"NAMELIST statement at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.pointer && n->sym->attr.intent == INTENT_IN)
switch (list)
{
case OMP_LIST_PRIVATE:
case OMP_LIST_LASTPRIVATE:
case OMP_LIST_LINEAR:
/* case OMP_LIST_REDUCTION: */
gfc_error ("INTENT(IN) POINTER %qs in %s clause at %L",
n->sym->name, name, &n->where);
break;
default:
break;
}
switch (list)
{
case OMP_LIST_REDUCTION:
switch (n->u.reduction_op)
{
case OMP_REDUCTION_PLUS:
case OMP_REDUCTION_TIMES:
case OMP_REDUCTION_MINUS:
if (!gfc_numeric_ts (&n->sym->ts))
bad = true;
break;
case OMP_REDUCTION_AND:
case OMP_REDUCTION_OR:
case OMP_REDUCTION_EQV:
case OMP_REDUCTION_NEQV:
if (n->sym->ts.type != BT_LOGICAL)
bad = true;
break;
case OMP_REDUCTION_MAX:
case OMP_REDUCTION_MIN:
if (n->sym->ts.type != BT_INTEGER
&& n->sym->ts.type != BT_REAL)
bad = true;
break;
case OMP_REDUCTION_IAND:
case OMP_REDUCTION_IOR:
case OMP_REDUCTION_IEOR:
if (n->sym->ts.type != BT_INTEGER)
bad = true;
break;
case OMP_REDUCTION_USER:
bad = true;
break;
default:
break;
}
if (!bad)
n->udr = NULL;
else
{
const char *udr_name = NULL;
if (n->udr)
{
udr_name = n->udr->udr->name;
n->udr->udr
= gfc_find_omp_udr (NULL, udr_name,
&n->sym->ts);
if (n->udr->udr == NULL)
{
free (n->udr);
n->udr = NULL;
}
}
if (n->udr == NULL)
{
if (udr_name == NULL)
switch (n->u.reduction_op)
{
case OMP_REDUCTION_PLUS:
case OMP_REDUCTION_TIMES:
case OMP_REDUCTION_MINUS:
case OMP_REDUCTION_AND:
case OMP_REDUCTION_OR:
case OMP_REDUCTION_EQV:
case OMP_REDUCTION_NEQV:
udr_name = gfc_op2string ((gfc_intrinsic_op)
n->u.reduction_op);
break;
case OMP_REDUCTION_MAX:
udr_name = "max";
break;
case OMP_REDUCTION_MIN:
udr_name = "min";
break;
case OMP_REDUCTION_IAND:
udr_name = "iand";
break;
case OMP_REDUCTION_IOR:
udr_name = "ior";
break;
case OMP_REDUCTION_IEOR:
udr_name = "ieor";
break;
default:
gcc_unreachable ();
}
gfc_error ("!$OMP DECLARE REDUCTION %s not found "
"for type %s at %L", udr_name,
gfc_typename (&n->sym->ts), &n->where);
}
else
{
gfc_omp_udr *udr = n->udr->udr;
n->u.reduction_op = OMP_REDUCTION_USER;
n->udr->combiner
= resolve_omp_udr_clause (n, udr->combiner_ns,
udr->omp_out,
udr->omp_in);
if (udr->initializer_ns)
n->udr->initializer
= resolve_omp_udr_clause (n,
udr->initializer_ns,
udr->omp_priv,
udr->omp_orig);
}
}
break;
case OMP_LIST_LINEAR:
if (n->sym->ts.type != BT_INTEGER)
gfc_error ("LINEAR variable %qs must be INTEGER "
"at %L", n->sym->name, &n->where);
else if (!code && !n->sym->attr.value)
gfc_error ("LINEAR dummy argument %qs must have VALUE "
"attribute at %L", n->sym->name, &n->where);
else if (n->expr)
{
gfc_expr *expr = n->expr;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER
|| expr->rank != 0)
gfc_error ("%qs in LINEAR clause at %L requires "
"a scalar integer linear-step expression",
n->sym->name, &n->where);
else if (!code && expr->expr_type != EXPR_CONSTANT)
gfc_error ("%qs in LINEAR clause at %L requires "
"a constant integer linear-step expression",
n->sym->name, &n->where);
}
break;
/* Workaround for PR middle-end/26316, nothing really needs
to be done here for OMP_LIST_PRIVATE. */
case OMP_LIST_PRIVATE:
gcc_assert (code && code->op != EXEC_NOP);
break;
case OMP_LIST_USE_DEVICE:
if (n->sym->attr.allocatable
|| (n->sym->ts.type == BT_CLASS && CLASS_DATA (n->sym)
&& CLASS_DATA (n->sym)->attr.allocatable))
gfc_error ("ALLOCATABLE object %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.pointer
|| (n->sym->ts.type == BT_CLASS && CLASS_DATA (n->sym)
&& CLASS_DATA (n->sym)->attr.class_pointer))
gfc_error ("POINTER object %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.cray_pointer)
gfc_error ("Cray pointer object %qs in %s clause at %L",
n->sym->name, name, &n->where);
if (n->sym->attr.cray_pointee)
gfc_error ("Cray pointee object %qs in %s clause at %L",
n->sym->name, name, &n->where);
/* FALLTHRU */
case OMP_LIST_DEVICE_RESIDENT:
check_symbol_not_pointer (n->sym, n->where, name);
check_array_not_assumed (n->sym, n->where, name);
break;
default:
break;
}
}
break;
}
}
if (omp_clauses->safelen_expr)
{
gfc_expr *expr = omp_clauses->safelen_expr;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER || expr->rank != 0)
gfc_error ("SAFELEN clause at %L requires a scalar "
"INTEGER expression", &expr->where);
}
if (omp_clauses->simdlen_expr)
{
gfc_expr *expr = omp_clauses->simdlen_expr;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER || expr->rank != 0)
gfc_error ("SIMDLEN clause at %L requires a scalar "
"INTEGER expression", &expr->where);
}
if (omp_clauses->num_teams)
{
gfc_expr *expr = omp_clauses->num_teams;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER || expr->rank != 0)
gfc_error ("NUM_TEAMS clause at %L requires a scalar "
"INTEGER expression", &expr->where);
}
if (omp_clauses->device)
{
gfc_expr *expr = omp_clauses->device;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER || expr->rank != 0)
gfc_error ("DEVICE clause at %L requires a scalar "
"INTEGER expression", &expr->where);
}
if (omp_clauses->dist_chunk_size)
{
gfc_expr *expr = omp_clauses->dist_chunk_size;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER || expr->rank != 0)
gfc_error ("DIST_SCHEDULE clause's chunk_size at %L requires "
"a scalar INTEGER expression", &expr->where);
}
if (omp_clauses->thread_limit)
{
gfc_expr *expr = omp_clauses->thread_limit;
if (!gfc_resolve_expr (expr)
|| expr->ts.type != BT_INTEGER || expr->rank != 0)
gfc_error ("THREAD_LIMIT clause at %L requires a scalar "
"INTEGER expression", &expr->where);
}
if (omp_clauses->async)
if (omp_clauses->async_expr)
resolve_oacc_scalar_int_expr (omp_clauses->async_expr, "ASYNC");
if (omp_clauses->num_gangs_expr)
resolve_oacc_positive_int_expr (omp_clauses->num_gangs_expr, "NUM_GANGS");
if (omp_clauses->num_workers_expr)
resolve_oacc_positive_int_expr (omp_clauses->num_workers_expr,
"NUM_WORKERS");
if (omp_clauses->vector_length_expr)
resolve_oacc_positive_int_expr (omp_clauses->vector_length_expr,
"VECTOR_LENGTH");
if (omp_clauses->gang_num_expr)
resolve_oacc_positive_int_expr (omp_clauses->gang_num_expr, "GANG");
if (omp_clauses->gang_static_expr)
resolve_oacc_positive_int_expr (omp_clauses->gang_static_expr, "GANG");
if (omp_clauses->worker_expr)
resolve_oacc_positive_int_expr (omp_clauses->worker_expr, "WORKER");
if (omp_clauses->vector_expr)
resolve_oacc_positive_int_expr (omp_clauses->vector_expr, "VECTOR");
if (omp_clauses->wait)
if (omp_clauses->wait_list)
for (el = omp_clauses->wait_list; el; el = el->next)
resolve_oacc_scalar_int_expr (el->expr, "WAIT");
}
/* Return true if SYM is ever referenced in EXPR except in the SE node. */
static bool
expr_references_sym (gfc_expr *e, gfc_symbol *s, gfc_expr *se)
{
gfc_actual_arglist *arg;
if (e == NULL || e == se)
return false;
switch (e->expr_type)
{
case EXPR_CONSTANT:
case EXPR_NULL:
case EXPR_VARIABLE:
case EXPR_STRUCTURE:
case EXPR_ARRAY:
if (e->symtree != NULL
&& e->symtree->n.sym == s)
return true;
return false;
case EXPR_SUBSTRING:
if (e->ref != NULL
&& (expr_references_sym (e->ref->u.ss.start, s, se)
|| expr_references_sym (e->ref->u.ss.end, s, se)))
return true;
return false;
case EXPR_OP:
if (expr_references_sym (e->value.op.op2, s, se))
return true;
return expr_references_sym (e->value.op.op1, s, se);
case EXPR_FUNCTION:
for (arg = e->value.function.actual; arg; arg = arg->next)
if (expr_references_sym (arg->expr, s, se))
return true;
return false;
default:
gcc_unreachable ();
}
}
/* If EXPR is a conversion function that widens the type
if WIDENING is true or narrows the type if WIDENING is false,
return the inner expression, otherwise return NULL. */
static gfc_expr *
is_conversion (gfc_expr *expr, bool widening)
{
gfc_typespec *ts1, *ts2;
if (expr->expr_type != EXPR_FUNCTION
|| expr->value.function.isym == NULL
|| expr->value.function.esym != NULL
|| expr->value.function.isym->id != GFC_ISYM_CONVERSION)
return NULL;
if (widening)
{
ts1 = &expr->ts;
ts2 = &expr->value.function.actual->expr->ts;
}
else
{
ts1 = &expr->value.function.actual->expr->ts;
ts2 = &expr->ts;
}
if (ts1->type > ts2->type
|| (ts1->type == ts2->type && ts1->kind > ts2->kind))
return expr->value.function.actual->expr;
return NULL;
}
static void
resolve_omp_atomic (gfc_code *code)
{
gfc_code *atomic_code = code;
gfc_symbol *var;
gfc_expr *expr2, *expr2_tmp;
gfc_omp_atomic_op aop
= (gfc_omp_atomic_op) (atomic_code->ext.omp_atomic & GFC_OMP_ATOMIC_MASK);
code = code->block->next;
/* resolve_blocks asserts this is initially EXEC_ASSIGN.
If it changed to EXEC_NOP, assume an error has been emitted already. */
if (code->op == EXEC_NOP)
return;
if (code->op != EXEC_ASSIGN)
{
unexpected:
gfc_error ("unexpected !$OMP ATOMIC expression at %L", &code->loc);
return;
}
if (aop != GFC_OMP_ATOMIC_CAPTURE)
{
if (code->next != NULL)
goto unexpected;
}
else
{
if (code->next == NULL)
goto unexpected;
if (code->next->op == EXEC_NOP)
return;
if (code->next->op != EXEC_ASSIGN || code->next->next)
{
code = code->next;
goto unexpected;
}
}
if (code->expr1->expr_type != EXPR_VARIABLE
|| code->expr1->symtree == NULL
|| code->expr1->rank != 0
|| (code->expr1->ts.type != BT_INTEGER
&& code->expr1->ts.type != BT_REAL
&& code->expr1->ts.type != BT_COMPLEX
&& code->expr1->ts.type != BT_LOGICAL))
{
gfc_error ("!$OMP ATOMIC statement must set a scalar variable of "
"intrinsic type at %L", &code->loc);
return;
}
var = code->expr1->symtree->n.sym;
expr2 = is_conversion (code->expr2, false);
if (expr2 == NULL)
{
if (aop == GFC_OMP_ATOMIC_READ || aop == GFC_OMP_ATOMIC_WRITE)
expr2 = is_conversion (code->expr2, true);
if (expr2 == NULL)
expr2 = code->expr2;
}
switch (aop)
{
case GFC_OMP_ATOMIC_READ:
if (expr2->expr_type != EXPR_VARIABLE
|| expr2->symtree == NULL
|| expr2->rank != 0
|| (expr2->ts.type != BT_INTEGER
&& expr2->ts.type != BT_REAL
&& expr2->ts.type != BT_COMPLEX
&& expr2->ts.type != BT_LOGICAL))
gfc_error ("!$OMP ATOMIC READ statement must read from a scalar "
"variable of intrinsic type at %L", &expr2->where);
return;
case GFC_OMP_ATOMIC_WRITE:
if (expr2->rank != 0 || expr_references_sym (code->expr2, var, NULL))
gfc_error ("expr in !$OMP ATOMIC WRITE assignment var = expr "
"must be scalar and cannot reference var at %L",
&expr2->where);
return;
case GFC_OMP_ATOMIC_CAPTURE:
expr2_tmp = expr2;
if (expr2 == code->expr2)
{
expr2_tmp = is_conversion (code->expr2, true);
if (expr2_tmp == NULL)
expr2_tmp = expr2;
}
if (expr2_tmp->expr_type == EXPR_VARIABLE)
{
if (expr2_tmp->symtree == NULL
|| expr2_tmp->rank != 0
|| (expr2_tmp->ts.type != BT_INTEGER
&& expr2_tmp->ts.type != BT_REAL
&& expr2_tmp->ts.type != BT_COMPLEX
&& expr2_tmp->ts.type != BT_LOGICAL)
|| expr2_tmp->symtree->n.sym == var)
{
gfc_error ("!$OMP ATOMIC CAPTURE capture statement must read from "
"a scalar variable of intrinsic type at %L",
&expr2_tmp->where);
return;
}
var = expr2_tmp->symtree->n.sym;
code = code->next;
if (code->expr1->expr_type != EXPR_VARIABLE
|| code->expr1->symtree == NULL
|| code->expr1->rank != 0
|| (code->expr1->ts.type != BT_INTEGER
&& code->expr1->ts.type != BT_REAL
&& code->expr1->ts.type != BT_COMPLEX
&& code->expr1->ts.type != BT_LOGICAL))
{
gfc_error ("!$OMP ATOMIC CAPTURE update statement must set "
"a scalar variable of intrinsic type at %L",
&code->expr1->where);
return;
}
if (code->expr1->symtree->n.sym != var)
{
gfc_error ("!$OMP ATOMIC CAPTURE capture statement reads from "
"different variable than update statement writes "
"into at %L", &code->expr1->where);
return;
}
expr2 = is_conversion (code->expr2, false);
if (expr2 == NULL)
expr2 = code->expr2;
}
break;
default:
break;
}
if (gfc_expr_attr (code->expr1).allocatable)
{
gfc_error ("!$OMP ATOMIC with ALLOCATABLE variable at %L",
&code->loc);
return;
}
if (aop == GFC_OMP_ATOMIC_CAPTURE
&& code->next == NULL
&& code->expr2->rank == 0
&& !expr_references_sym (code->expr2, var, NULL))
atomic_code->ext.omp_atomic
= (gfc_omp_atomic_op) (atomic_code->ext.omp_atomic
| GFC_OMP_ATOMIC_SWAP);
else if (expr2->expr_type == EXPR_OP)
{
gfc_expr *v = NULL, *e, *c;
gfc_intrinsic_op op = expr2->value.op.op;
gfc_intrinsic_op alt_op = INTRINSIC_NONE;
switch (op)
{
case INTRINSIC_PLUS:
alt_op = INTRINSIC_MINUS;
break;
case INTRINSIC_TIMES:
alt_op = INTRINSIC_DIVIDE;
break;
case INTRINSIC_MINUS:
alt_op = INTRINSIC_PLUS;
break;
case INTRINSIC_DIVIDE:
alt_op = INTRINSIC_TIMES;
break;
case INTRINSIC_AND:
case INTRINSIC_OR:
break;
case INTRINSIC_EQV:
alt_op = INTRINSIC_NEQV;
break;
case INTRINSIC_NEQV:
alt_op = INTRINSIC_EQV;
break;
default:
gfc_error ("!$OMP ATOMIC assignment operator must be binary "
"+, *, -, /, .AND., .OR., .EQV. or .NEQV. at %L",
&expr2->where);
return;
}
/* Check for var = var op expr resp. var = expr op var where
expr doesn't reference var and var op expr is mathematically
equivalent to var op (expr) resp. expr op var equivalent to
(expr) op var. We rely here on the fact that the matcher
for x op1 y op2 z where op1 and op2 have equal precedence
returns (x op1 y) op2 z. */
e = expr2->value.op.op2;
if (e->expr_type == EXPR_VARIABLE
&& e->symtree != NULL
&& e->symtree->n.sym == var)
v = e;
else if ((c = is_conversion (e, true)) != NULL
&& c->expr_type == EXPR_VARIABLE
&& c->symtree != NULL
&& c->symtree->n.sym == var)
v = c;
else
{
gfc_expr **p = NULL, **q;
for (q = &expr2->value.op.op1; (e = *q) != NULL; )
if (e->expr_type == EXPR_VARIABLE
&& e->symtree != NULL
&& e->symtree->n.sym == var)
{
v = e;
break;
}
else if ((c = is_conversion (e, true)) != NULL)
q = &e->value.function.actual->expr;
else if (e->expr_type != EXPR_OP
|| (e->value.op.op != op
&& e->value.op.op != alt_op)
|| e->rank != 0)
break;
else
{
p = q;
q = &e->value.op.op1;
}
if (v == NULL)
{
gfc_error ("!$OMP ATOMIC assignment must be var = var op expr "
"or var = expr op var at %L", &expr2->where);
return;
}
if (p != NULL)
{
e = *p;
switch (e->value.op.op)
{
case INTRINSIC_MINUS:
case INTRINSIC_DIVIDE:
case INTRINSIC_EQV:
case INTRINSIC_NEQV:
gfc_error ("!$OMP ATOMIC var = var op expr not "
"mathematically equivalent to var = var op "
"(expr) at %L", &expr2->where);
break;
default:
break;
}
/* Canonicalize into var = var op (expr). */
*p = e->value.op.op2;
e->value.op.op2 = expr2;
e->ts = expr2->ts;
if (code->expr2 == expr2)
code->expr2 = expr2 = e;
else
code->expr2->value.function.actual->expr = expr2 = e;
if (!gfc_compare_types (&expr2->value.op.op1->ts, &expr2->ts))
{
for (p = &expr2->value.op.op1; *p != v;
p = &(*p)->value.function.actual->expr)
;
*p = NULL;
gfc_free_expr (expr2->value.op.op1);
expr2->value.op.op1 = v;
gfc_convert_type (v, &expr2->ts, 2);
}
}
}
if (e->rank != 0 || expr_references_sym (code->expr2, var, v))
{
gfc_error ("expr in !$OMP ATOMIC assignment var = var op expr "
"must be scalar and cannot reference var at %L",
&expr2->where);
return;
}
}
else if (expr2->expr_type == EXPR_FUNCTION
&& expr2->value.function.isym != NULL
&& expr2->value.function.esym == NULL
&& expr2->value.function.actual != NULL
&& expr2->value.function.actual->next != NULL)
{
gfc_actual_arglist *arg, *var_arg;
switch (expr2->value.function.isym->id)
{
case GFC_ISYM_MIN:
case GFC_ISYM_MAX:
break;
case GFC_ISYM_IAND:
case GFC_ISYM_IOR:
case GFC_ISYM_IEOR:
if (expr2->value.function.actual->next->next != NULL)
{
gfc_error ("!$OMP ATOMIC assignment intrinsic IAND, IOR "
"or IEOR must have two arguments at %L",
&expr2->where);
return;
}
break;
default:
gfc_error ("!$OMP ATOMIC assignment intrinsic must be "
"MIN, MAX, IAND, IOR or IEOR at %L",
&expr2->where);
return;
}
var_arg = NULL;
for (arg = expr2->value.function.actual; arg; arg = arg->next)
{
if ((arg == expr2->value.function.actual
|| (var_arg == NULL && arg->next == NULL))
&& arg->expr->expr_type == EXPR_VARIABLE
&& arg->expr->symtree != NULL
&& arg->expr->symtree->n.sym == var)
var_arg = arg;
else if (expr_references_sym (arg->expr, var, NULL))
{
gfc_error ("!$OMP ATOMIC intrinsic arguments except one must "
"not reference %qs at %L",
var->name, &arg->expr->where);
return;
}
if (arg->expr->rank != 0)
{
gfc_error ("!$OMP ATOMIC intrinsic arguments must be scalar "
"at %L", &arg->expr->where);
return;
}
}
if (var_arg == NULL)
{
gfc_error ("First or last !$OMP ATOMIC intrinsic argument must "
"be %qs at %L", var->name, &expr2->where);
return;
}
if (var_arg != expr2->value.function.actual)
{
/* Canonicalize, so that var comes first. */
gcc_assert (var_arg->next == NULL);
for (arg = expr2->value.function.actual;
arg->next != var_arg; arg = arg->next)
;
var_arg->next = expr2->value.function.actual;
expr2->value.function.actual = var_arg;
arg->next = NULL;
}
}
else
gfc_error ("!$OMP ATOMIC assignment must have an operator or "
"intrinsic on right hand side at %L", &expr2->where);
if (aop == GFC_OMP_ATOMIC_CAPTURE && code->next)
{
code = code->next;
if (code->expr1->expr_type != EXPR_VARIABLE
|| code->expr1->symtree == NULL
|| code->expr1->rank != 0
|| (code->expr1->ts.type != BT_INTEGER
&& code->expr1->ts.type != BT_REAL
&& code->expr1->ts.type != BT_COMPLEX
&& code->expr1->ts.type != BT_LOGICAL))
{
gfc_error ("!$OMP ATOMIC CAPTURE capture statement must set "
"a scalar variable of intrinsic type at %L",
&code->expr1->where);
return;
}
expr2 = is_conversion (code->expr2, false);
if (expr2 == NULL)
{
expr2 = is_conversion (code->expr2, true);
if (expr2 == NULL)
expr2 = code->expr2;
}
if (expr2->expr_type != EXPR_VARIABLE
|| expr2->symtree == NULL
|| expr2->rank != 0
|| (expr2->ts.type != BT_INTEGER
&& expr2->ts.type != BT_REAL
&& expr2->ts.type != BT_COMPLEX
&& expr2->ts.type != BT_LOGICAL))
{
gfc_error ("!$OMP ATOMIC CAPTURE capture statement must read "
"from a scalar variable of intrinsic type at %L",
&expr2->where);
return;
}
if (expr2->symtree->n.sym != var)
{
gfc_error ("!$OMP ATOMIC CAPTURE capture statement reads from "
"different variable than update statement writes "
"into at %L", &expr2->where);
return;
}
}
}
struct fortran_omp_context
{
gfc_code *code;
hash_set<gfc_symbol *> *sharing_clauses;
hash_set<gfc_symbol *> *private_iterators;
struct fortran_omp_context *previous;
bool is_openmp;
} *omp_current_ctx;
static gfc_code *omp_current_do_code;
static int omp_current_do_collapse;
void
gfc_resolve_omp_do_blocks (gfc_code *code, gfc_namespace *ns)
{
if (code->block->next && code->block->next->op == EXEC_DO)
{
int i;
gfc_code *c;
omp_current_do_code = code->block->next;
omp_current_do_collapse = code->ext.omp_clauses->collapse;
for (i = 1, c = omp_current_do_code; i < omp_current_do_collapse; i++)
{
c = c->block;
if (c->op != EXEC_DO || c->next == NULL)
break;
c = c->next;
if (c->op != EXEC_DO)
break;
}
if (i < omp_current_do_collapse || omp_current_do_collapse <= 0)
omp_current_do_collapse = 1;
}
gfc_resolve_blocks (code->block, ns);
omp_current_do_collapse = 0;
omp_current_do_code = NULL;
}
void
gfc_resolve_omp_parallel_blocks (gfc_code *code, gfc_namespace *ns)
{
struct fortran_omp_context ctx;
gfc_omp_clauses *omp_clauses = code->ext.omp_clauses;
gfc_omp_namelist *n;
int list;
ctx.code = code;
ctx.sharing_clauses = new hash_set<gfc_symbol *>;
ctx.private_iterators = new hash_set<gfc_symbol *>;
ctx.previous = omp_current_ctx;
ctx.is_openmp = true;
omp_current_ctx = &ctx;
for (list = 0; list < OMP_LIST_NUM; list++)
switch (list)
{
case OMP_LIST_SHARED:
case OMP_LIST_PRIVATE:
case OMP_LIST_FIRSTPRIVATE:
case OMP_LIST_LASTPRIVATE:
case OMP_LIST_REDUCTION:
case OMP_LIST_LINEAR:
for (n = omp_clauses->lists[list]; n; n = n->next)
ctx.sharing_clauses->add (n->sym);
break;
default:
break;
}
switch (code->op)
{
case EXEC_OMP_PARALLEL_DO:
case EXEC_OMP_PARALLEL_DO_SIMD:
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE:
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO:
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_SIMD:
case EXEC_OMP_TEAMS_DISTRIBUTE:
case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO:
case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
case EXEC_OMP_TEAMS_DISTRIBUTE_SIMD:
gfc_resolve_omp_do_blocks (code, ns);
break;
default:
gfc_resolve_blocks (code->block, ns);
}
omp_current_ctx = ctx.previous;
delete ctx.sharing_clauses;
delete ctx.private_iterators;
}
/* Save and clear openmp.c private state. */
void
gfc_omp_save_and_clear_state (struct gfc_omp_saved_state *state)
{
state->ptrs[0] = omp_current_ctx;
state->ptrs[1] = omp_current_do_code;
state->ints[0] = omp_current_do_collapse;
omp_current_ctx = NULL;
omp_current_do_code = NULL;
omp_current_do_collapse = 0;
}
/* Restore openmp.c private state from the saved state. */
void
gfc_omp_restore_state (struct gfc_omp_saved_state *state)
{
omp_current_ctx = (struct fortran_omp_context *) state->ptrs[0];
omp_current_do_code = (gfc_code *) state->ptrs[1];
omp_current_do_collapse = state->ints[0];
}
/* Note a DO iterator variable. This is special in !$omp parallel
construct, where they are predetermined private. */
void
gfc_resolve_do_iterator (gfc_code *code, gfc_symbol *sym)
{
int i = omp_current_do_collapse;
gfc_code *c = omp_current_do_code;
if (sym->attr.threadprivate)
return;
/* !$omp do and !$omp parallel do iteration variable is predetermined
private just in the !$omp do resp. !$omp parallel do construct,
with no implications for the outer parallel constructs. */
while (i-- >= 1)
{
if (code == c)
return;
c = c->block->next;
}
if (omp_current_ctx == NULL)
return;
/* An openacc context may represent a data clause. Abort if so. */
if (!omp_current_ctx->is_openmp && !oacc_is_loop (omp_current_ctx->code))
return;
if (omp_current_ctx->is_openmp
&& omp_current_ctx->sharing_clauses->contains (sym))
return;
if (! omp_current_ctx->private_iterators->add (sym))
{
gfc_omp_clauses *omp_clauses = omp_current_ctx->code->ext.omp_clauses;
gfc_omp_namelist *p;
p = gfc_get_omp_namelist ();
p->sym = sym;
p->next = omp_clauses->lists[OMP_LIST_PRIVATE];
omp_clauses->lists[OMP_LIST_PRIVATE] = p;
}
}
static void
resolve_omp_do (gfc_code *code)
{
gfc_code *do_code, *c;
int list, i, collapse;
gfc_omp_namelist *n;
gfc_symbol *dovar;
const char *name;
bool is_simd = false;
switch (code->op)
{
case EXEC_OMP_DISTRIBUTE: name = "!$OMP DISTRIBUTE"; break;
case EXEC_OMP_DISTRIBUTE_PARALLEL_DO:
name = "!$OMP DISTRIBUTE PARALLEL DO";
break;
case EXEC_OMP_DISTRIBUTE_PARALLEL_DO_SIMD:
name = "!$OMP DISTRIBUTE PARALLEL DO SIMD";
is_simd = true;
break;
case EXEC_OMP_DISTRIBUTE_SIMD:
name = "!$OMP DISTRIBUTE SIMD";
is_simd = true;
break;
case EXEC_OMP_DO: name = "!$OMP DO"; break;
case EXEC_OMP_DO_SIMD: name = "!$OMP DO SIMD"; is_simd = true; break;
case EXEC_OMP_PARALLEL_DO: name = "!$OMP PARALLEL DO"; break;
case EXEC_OMP_PARALLEL_DO_SIMD:
name = "!$OMP PARALLEL DO SIMD";
is_simd = true;
break;
case EXEC_OMP_SIMD: name = "!$OMP SIMD"; is_simd = true; break;
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE:
name = "!$OMP TARGET TEAMS_DISTRIBUTE";
break;
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO:
name = "!$OMP TARGET TEAMS DISTRIBUTE PARALLEL DO";
break;
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
name = "!$OMP TARGET TEAMS DISTRIBUTE PARALLEL DO SIMD";
is_simd = true;
break;
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_SIMD:
name = "!$OMP TARGET TEAMS DISTRIBUTE SIMD";
is_simd = true;
break;
case EXEC_OMP_TEAMS_DISTRIBUTE: name = "!$OMP TEAMS_DISTRIBUTE"; break;
case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO:
name = "!$OMP TEAMS DISTRIBUTE PARALLEL DO";
break;
case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
name = "!$OMP TEAMS DISTRIBUTE PARALLEL DO SIMD";
is_simd = true;
break;
case EXEC_OMP_TEAMS_DISTRIBUTE_SIMD:
name = "!$OMP TEAMS DISTRIBUTE SIMD";
is_simd = true;
break;
default: gcc_unreachable ();
}
if (code->ext.omp_clauses)
resolve_omp_clauses (code, code->ext.omp_clauses, NULL);
do_code = code->block->next;
collapse = code->ext.omp_clauses->collapse;
if (collapse <= 0)
collapse = 1;
for (i = 1; i <= collapse; i++)
{
if (do_code->op == EXEC_DO_WHILE)
{
gfc_error ("%s cannot be a DO WHILE or DO without loop control "
"at %L", name, &do_code->loc);
break;
}
if (do_code->op == EXEC_DO_CONCURRENT)
{
gfc_error ("%s cannot be a DO CONCURRENT loop at %L", name,
&do_code->loc);
break;
}
gcc_assert (do_code->op == EXEC_DO);
if (do_code->ext.iterator->var->ts.type != BT_INTEGER)
gfc_error ("%s iteration variable must be of type integer at %L",
name, &do_code->loc);
dovar = do_code->ext.iterator->var->symtree->n.sym;
if (dovar->attr.threadprivate)
gfc_error ("%s iteration variable must not be THREADPRIVATE "
"at %L", name, &do_code->loc);
if (code->ext.omp_clauses)
for (list = 0; list < OMP_LIST_NUM; list++)
if (!is_simd
? (list != OMP_LIST_PRIVATE && list != OMP_LIST_LASTPRIVATE)
: code->ext.omp_clauses->collapse > 1
? (list != OMP_LIST_LASTPRIVATE)
: (list != OMP_LIST_LINEAR))
for (n = code->ext.omp_clauses->lists[list]; n; n = n->next)
if (dovar == n->sym)
{
if (!is_simd)
gfc_error ("%s iteration variable present on clause "
"other than PRIVATE or LASTPRIVATE at %L",
name, &do_code->loc);
else if (code->ext.omp_clauses->collapse > 1)
gfc_error ("%s iteration variable present on clause "
"other than LASTPRIVATE at %L",
name, &do_code->loc);
else
gfc_error ("%s iteration variable present on clause "
"other than LINEAR at %L",
name, &do_code->loc);
break;
}
if (i > 1)
{
gfc_code *do_code2 = code->block->next;
int j;
for (j = 1; j < i; j++)
{
gfc_symbol *ivar = do_code2->ext.iterator->var->symtree->n.sym;
if (dovar == ivar
|| gfc_find_sym_in_expr (ivar, do_code->ext.iterator->start)
|| gfc_find_sym_in_expr (ivar, do_code->ext.iterator->end)
|| gfc_find_sym_in_expr (ivar, do_code->ext.iterator->step))
{
gfc_error ("%s collapsed loops don't form rectangular "
"iteration space at %L", name, &do_code->loc);
break;
}
if (j < i)
break;
do_code2 = do_code2->block->next;
}
}
if (i == collapse)
break;
for (c = do_code->next; c; c = c->next)
if (c->op != EXEC_NOP && c->op != EXEC_CONTINUE)
{
gfc_error ("collapsed %s loops not perfectly nested at %L",
name, &c->loc);
break;
}
if (c)
break;
do_code = do_code->block;
if (do_code->op != EXEC_DO && do_code->op != EXEC_DO_WHILE)
{
gfc_error ("not enough DO loops for collapsed %s at %L",
name, &code->loc);
break;
}
do_code = do_code->next;
if (do_code == NULL
|| (do_code->op != EXEC_DO && do_code->op != EXEC_DO_WHILE))
{
gfc_error ("not enough DO loops for collapsed %s at %L",
name, &code->loc);
break;
}
}
}
static bool
oacc_is_parallel (gfc_code *code)
{
return code->op == EXEC_OACC_PARALLEL || code->op == EXEC_OACC_PARALLEL_LOOP;
}
static bool
oacc_is_kernels (gfc_code *code)
{
return code->op == EXEC_OACC_KERNELS || code->op == EXEC_OACC_KERNELS_LOOP;
}
static gfc_statement
omp_code_to_statement (gfc_code *code)
{
switch (code->op)
{
case EXEC_OMP_PARALLEL:
return ST_OMP_PARALLEL;
case EXEC_OMP_PARALLEL_SECTIONS:
return ST_OMP_PARALLEL_SECTIONS;
case EXEC_OMP_SECTIONS:
return ST_OMP_SECTIONS;
case EXEC_OMP_ORDERED:
return ST_OMP_ORDERED;
case EXEC_OMP_CRITICAL:
return ST_OMP_CRITICAL;
case EXEC_OMP_MASTER:
return ST_OMP_MASTER;
case EXEC_OMP_SINGLE:
return ST_OMP_SINGLE;
case EXEC_OMP_TASK:
return ST_OMP_TASK;
case EXEC_OMP_WORKSHARE:
return ST_OMP_WORKSHARE;
case EXEC_OMP_PARALLEL_WORKSHARE:
return ST_OMP_PARALLEL_WORKSHARE;
case EXEC_OMP_DO:
return ST_OMP_DO;
default:
gcc_unreachable ();
}
}
static gfc_statement
oacc_code_to_statement (gfc_code *code)
{
switch (code->op)
{
case EXEC_OACC_PARALLEL:
return ST_OACC_PARALLEL;
case EXEC_OACC_KERNELS:
return ST_OACC_KERNELS;
case EXEC_OACC_DATA:
return ST_OACC_DATA;
case EXEC_OACC_HOST_DATA:
return ST_OACC_HOST_DATA;
case EXEC_OACC_PARALLEL_LOOP:
return ST_OACC_PARALLEL_LOOP;
case EXEC_OACC_KERNELS_LOOP:
return ST_OACC_KERNELS_LOOP;
case EXEC_OACC_LOOP:
return ST_OACC_LOOP;
case EXEC_OACC_ATOMIC:
return ST_OACC_ATOMIC;
default:
gcc_unreachable ();
}
}
static void
resolve_oacc_directive_inside_omp_region (gfc_code *code)
{
if (omp_current_ctx != NULL && omp_current_ctx->is_openmp)
{
gfc_statement st = omp_code_to_statement (omp_current_ctx->code);
gfc_statement oacc_st = oacc_code_to_statement (code);
gfc_error ("The %s directive cannot be specified within "
"a %s region at %L", gfc_ascii_statement (oacc_st),
gfc_ascii_statement (st), &code->loc);
}
}
static void
resolve_omp_directive_inside_oacc_region (gfc_code *code)
{
if (omp_current_ctx != NULL && !omp_current_ctx->is_openmp)
{
gfc_statement st = oacc_code_to_statement (omp_current_ctx->code);
gfc_statement omp_st = omp_code_to_statement (code);
gfc_error ("The %s directive cannot be specified within "
"a %s region at %L", gfc_ascii_statement (omp_st),
gfc_ascii_statement (st), &code->loc);
}
}
static void
resolve_oacc_nested_loops (gfc_code *code, gfc_code* do_code, int collapse,
const char *clause)
{
gfc_symbol *dovar;
gfc_code *c;
int i;
for (i = 1; i <= collapse; i++)
{
if (do_code->op == EXEC_DO_WHILE)
{
gfc_error ("!$ACC LOOP cannot be a DO WHILE or DO without loop control "
"at %L", &do_code->loc);
break;
}
gcc_assert (do_code->op == EXEC_DO || do_code->op == EXEC_DO_CONCURRENT);
if (do_code->ext.iterator->var->ts.type != BT_INTEGER)
gfc_error ("!$ACC LOOP iteration variable must be of type integer at %L",
&do_code->loc);
dovar = do_code->ext.iterator->var->symtree->n.sym;
if (i > 1)
{
gfc_code *do_code2 = code->block->next;
int j;
for (j = 1; j < i; j++)
{
gfc_symbol *ivar = do_code2->ext.iterator->var->symtree->n.sym;
if (dovar == ivar
|| gfc_find_sym_in_expr (ivar, do_code->ext.iterator->start)
|| gfc_find_sym_in_expr (ivar, do_code->ext.iterator->end)
|| gfc_find_sym_in_expr (ivar, do_code->ext.iterator->step))
{
gfc_error ("!$ACC LOOP %s loops don't form rectangular iteration space at %L",
clause, &do_code->loc);
break;
}
if (j < i)
break;
do_code2 = do_code2->block->next;
}
}
if (i == collapse)
break;
for (c = do_code->next; c; c = c->next)
if (c->op != EXEC_NOP && c->op != EXEC_CONTINUE)
{
gfc_error ("%s !$ACC LOOP loops not perfectly nested at %L",
clause, &c->loc);
break;
}
if (c)
break;
do_code = do_code->block;
if (do_code->op != EXEC_DO && do_code->op != EXEC_DO_WHILE
&& do_code->op != EXEC_DO_CONCURRENT)
{
gfc_error ("not enough DO loops for %s !$ACC LOOP at %L",
clause, &code->loc);
break;
}
do_code = do_code->next;
if (do_code == NULL
|| (do_code->op != EXEC_DO && do_code->op != EXEC_DO_WHILE
&& do_code->op != EXEC_DO_CONCURRENT))
{
gfc_error ("not enough DO loops for %s !$ACC LOOP at %L",
clause, &code->loc);
break;
}
}
}
static void
resolve_oacc_params_in_parallel (gfc_code *code, const char *clause,
const char *arg)
{
fortran_omp_context *c;
if (oacc_is_parallel (code))
gfc_error ("!$ACC LOOP %s in PARALLEL region doesn't allow "
"%s arguments at %L", clause, arg, &code->loc);
for (c = omp_current_ctx; c; c = c->previous)
{
if (oacc_is_loop (c->code))
break;
if (oacc_is_parallel (c->code))
gfc_error ("!$ACC LOOP %s in PARALLEL region doesn't allow "
"%s arguments at %L", clause, arg, &code->loc);
}
}
static void
resolve_oacc_loop_blocks (gfc_code *code)
{
fortran_omp_context *c;
if (!oacc_is_loop (code))
return;
if (code->op == EXEC_OACC_LOOP)
for (c = omp_current_ctx; c; c = c->previous)
{
if (oacc_is_loop (c->code))
{
if (code->ext.omp_clauses->gang)
{
if (c->code->ext.omp_clauses->gang)
gfc_error ("Loop parallelized across gangs is not allowed "
"inside another loop parallelized across gangs at %L",
&code->loc);
if (c->code->ext.omp_clauses->worker)
gfc_error ("Loop parallelized across gangs is not allowed "
"inside loop parallelized across workers at %L",
&code->loc);
if (c->code->ext.omp_clauses->vector)
gfc_error ("Loop parallelized across gangs is not allowed "
"inside loop parallelized across workers at %L",
&code->loc);
}
if (code->ext.omp_clauses->worker)
{
if (c->code->ext.omp_clauses->worker)
gfc_error ("Loop parallelized across workers is not allowed "
"inside another loop parallelized across workers at %L",
&code->loc);
if (c->code->ext.omp_clauses->vector)
gfc_error ("Loop parallelized across workers is not allowed "
"inside another loop parallelized across vectors at %L",
&code->loc);
}
if (code->ext.omp_clauses->vector)
if (c->code->ext.omp_clauses->vector)
gfc_error ("Loop parallelized across vectors is not allowed "
"inside another loop parallelized across vectors at %L",
&code->loc);
}
if (oacc_is_parallel (c->code) || oacc_is_kernels (c->code))
break;
}
if (code->ext.omp_clauses->seq)
{
if (code->ext.omp_clauses->independent)
gfc_error ("Clause SEQ conflicts with INDEPENDENT at %L", &code->loc);
if (code->ext.omp_clauses->gang)
gfc_error ("Clause SEQ conflicts with GANG at %L", &code->loc);
if (code->ext.omp_clauses->worker)
gfc_error ("Clause SEQ conflicts with WORKER at %L", &code->loc);
if (code->ext.omp_clauses->vector)
gfc_error ("Clause SEQ conflicts with VECTOR at %L", &code->loc);
if (code->ext.omp_clauses->par_auto)
gfc_error ("Clause SEQ conflicts with AUTO at %L", &code->loc);
}
if (code->ext.omp_clauses->par_auto)
{
if (code->ext.omp_clauses->gang)
gfc_error ("Clause AUTO conflicts with GANG at %L", &code->loc);
if (code->ext.omp_clauses->worker)
gfc_error ("Clause AUTO conflicts with WORKER at %L", &code->loc);
if (code->ext.omp_clauses->vector)
gfc_error ("Clause AUTO conflicts with VECTOR at %L", &code->loc);
}
if (code->ext.omp_clauses->tile_list && code->ext.omp_clauses->gang
&& code->ext.omp_clauses->worker && code->ext.omp_clauses->vector)
gfc_error ("Tiled loop cannot be parallelized across gangs, workers and "
"vectors at the same time at %L", &code->loc);
if (code->ext.omp_clauses->gang
&& code->ext.omp_clauses->gang_num_expr)
resolve_oacc_params_in_parallel (code, "GANG", "num");
if (code->ext.omp_clauses->worker
&& code->ext.omp_clauses->worker_expr)
resolve_oacc_params_in_parallel (code, "WORKER", "num");
if (code->ext.omp_clauses->vector
&& code->ext.omp_clauses->vector_expr)
resolve_oacc_params_in_parallel (code, "VECTOR", "length");
if (code->ext.omp_clauses->tile_list)
{
gfc_expr_list *el;
int num = 0;
for (el = code->ext.omp_clauses->tile_list; el; el = el->next)
{
num++;
if (el->expr == NULL)
{
/* NULL expressions are used to represent '*' arguments.
Convert those to a -1 expressions. */
el->expr = gfc_get_constant_expr (BT_INTEGER,
gfc_default_integer_kind,
&code->loc);
mpz_set_si (el->expr->value.integer, -1);
}
else
{
resolve_oacc_positive_int_expr (el->expr, "TILE");
if (el->expr->expr_type != EXPR_CONSTANT)
gfc_error ("TILE requires constant expression at %L",
&code->loc);
}
}
resolve_oacc_nested_loops (code, code->block->next, num, "tiled");
}
}
void
gfc_resolve_oacc_blocks (gfc_code *code, gfc_namespace *ns)
{
fortran_omp_context ctx;
resolve_oacc_loop_blocks (code);
ctx.code = code;
ctx.sharing_clauses = NULL;
ctx.private_iterators = new hash_set<gfc_symbol *>;
ctx.previous = omp_current_ctx;
ctx.is_openmp = false;
omp_current_ctx = &ctx;
gfc_resolve_blocks (code->block, ns);
omp_current_ctx = ctx.previous;
delete ctx.private_iterators;
}
static void
resolve_oacc_loop (gfc_code *code)
{
gfc_code *do_code;
int collapse;
if (code->ext.omp_clauses)
resolve_omp_clauses (code, code->ext.omp_clauses, NULL, true);
do_code = code->block->next;
collapse = code->ext.omp_clauses->collapse;
if (collapse <= 0)
collapse = 1;
resolve_oacc_nested_loops (code, do_code, collapse, "collapsed");
}
void
gfc_resolve_oacc_declare (gfc_namespace *ns)
{
int list;
gfc_omp_namelist *n;
gfc_oacc_declare *oc;
if (ns->oacc_declare == NULL)
return;
for (oc = ns->oacc_declare; oc; oc = oc->next)
{
for (list = 0; list < OMP_LIST_NUM; list++)
for (n = oc->clauses->lists[list]; n; n = n->next)
{
n->sym->mark = 0;
if (n->sym->attr.flavor == FL_PARAMETER)
{
gfc_error ("PARAMETER object %qs is not allowed at %L",
n->sym->name, &oc->loc);
continue;
}
if (n->expr && n->expr->ref->type == REF_ARRAY)
{
gfc_error ("Array sections: %qs not allowed in"
" $!ACC DECLARE at %L", n->sym->name, &oc->loc);
continue;
}
}
for (n = oc->clauses->lists[OMP_LIST_DEVICE_RESIDENT]; n; n = n->next)
check_array_not_assumed (n->sym, oc->loc, "DEVICE_RESIDENT");
}
for (oc = ns->oacc_declare; oc; oc = oc->next)
{
for (list = 0; list < OMP_LIST_NUM; list++)
for (n = oc->clauses->lists[list]; n; n = n->next)
{
if (n->sym->mark)
{
gfc_error ("Symbol %qs present on multiple clauses at %L",
n->sym->name, &oc->loc);
continue;
}
else
n->sym->mark = 1;
}
}
for (oc = ns->oacc_declare; oc; oc = oc->next)
{
for (list = 0; list < OMP_LIST_NUM; list++)
for (n = oc->clauses->lists[list]; n; n = n->next)
n->sym->mark = 0;
}
}
void
gfc_resolve_oacc_directive (gfc_code *code, gfc_namespace *ns ATTRIBUTE_UNUSED)
{
resolve_oacc_directive_inside_omp_region (code);
switch (code->op)
{
case EXEC_OACC_PARALLEL:
case EXEC_OACC_KERNELS:
case EXEC_OACC_DATA:
case EXEC_OACC_HOST_DATA:
case EXEC_OACC_UPDATE:
case EXEC_OACC_ENTER_DATA:
case EXEC_OACC_EXIT_DATA:
case EXEC_OACC_WAIT:
case EXEC_OACC_CACHE:
resolve_omp_clauses (code, code->ext.omp_clauses, NULL, true);
break;
case EXEC_OACC_PARALLEL_LOOP:
case EXEC_OACC_KERNELS_LOOP:
case EXEC_OACC_LOOP:
resolve_oacc_loop (code);
break;
case EXEC_OACC_ATOMIC:
resolve_omp_atomic (code);
break;
default:
break;
}
}
/* Resolve OpenMP directive clauses and check various requirements
of each directive. */
void
gfc_resolve_omp_directive (gfc_code *code, gfc_namespace *ns ATTRIBUTE_UNUSED)
{
resolve_omp_directive_inside_oacc_region (code);
if (code->op != EXEC_OMP_ATOMIC)
gfc_maybe_initialize_eh ();
switch (code->op)
{
case EXEC_OMP_DISTRIBUTE:
case EXEC_OMP_DISTRIBUTE_PARALLEL_DO:
case EXEC_OMP_DISTRIBUTE_PARALLEL_DO_SIMD:
case EXEC_OMP_DISTRIBUTE_SIMD:
case EXEC_OMP_DO:
case EXEC_OMP_DO_SIMD:
case EXEC_OMP_PARALLEL_DO:
case EXEC_OMP_PARALLEL_DO_SIMD:
case EXEC_OMP_SIMD:
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE:
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO:
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
case EXEC_OMP_TARGET_TEAMS_DISTRIBUTE_SIMD:
case EXEC_OMP_TEAMS_DISTRIBUTE:
case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO:
case EXEC_OMP_TEAMS_DISTRIBUTE_PARALLEL_DO_SIMD:
case EXEC_OMP_TEAMS_DISTRIBUTE_SIMD:
resolve_omp_do (code);
break;
case EXEC_OMP_CANCEL:
case EXEC_OMP_PARALLEL_WORKSHARE:
case EXEC_OMP_PARALLEL:
case EXEC_OMP_PARALLEL_SECTIONS:
case EXEC_OMP_SECTIONS:
case EXEC_OMP_SINGLE:
case EXEC_OMP_TARGET:
case EXEC_OMP_TARGET_DATA:
case EXEC_OMP_TARGET_TEAMS:
case EXEC_OMP_TASK:
case EXEC_OMP_TEAMS:
case EXEC_OMP_WORKSHARE:
if (code->ext.omp_clauses)
resolve_omp_clauses (code, code->ext.omp_clauses, NULL);
break;
case EXEC_OMP_TARGET_UPDATE:
if (code->ext.omp_clauses)
resolve_omp_clauses (code, code->ext.omp_clauses, NULL);
if (code->ext.omp_clauses == NULL
|| (code->ext.omp_clauses->lists[OMP_LIST_TO] == NULL
&& code->ext.omp_clauses->lists[OMP_LIST_FROM] == NULL))
gfc_error ("OMP TARGET UPDATE at %L requires at least one TO or "
"FROM clause", &code->loc);
break;
case EXEC_OMP_ATOMIC:
resolve_omp_atomic (code);
break;
default:
break;
}
}
/* Resolve !$omp declare simd constructs in NS. */
void
gfc_resolve_omp_declare_simd (gfc_namespace *ns)
{
gfc_omp_declare_simd *ods;
for (ods = ns->omp_declare_simd; ods; ods = ods->next)
{
if (ods->proc_name != ns->proc_name)
gfc_error ("!$OMP DECLARE SIMD should refer to containing procedure "
"%qs at %L", ns->proc_name->name, &ods->where);
if (ods->clauses)
resolve_omp_clauses (NULL, ods->clauses, ns);
}
}
struct omp_udr_callback_data
{
gfc_omp_udr *omp_udr;
bool is_initializer;
};
static int
omp_udr_callback (gfc_expr **e, int *walk_subtrees ATTRIBUTE_UNUSED,
void *data)
{
struct omp_udr_callback_data *cd = (struct omp_udr_callback_data *) data;
if ((*e)->expr_type == EXPR_VARIABLE)
{
if (cd->is_initializer)
{
if ((*e)->symtree->n.sym != cd->omp_udr->omp_priv
&& (*e)->symtree->n.sym != cd->omp_udr->omp_orig)
gfc_error ("Variable other than OMP_PRIV or OMP_ORIG used in "
"INITIALIZER clause of !$OMP DECLARE REDUCTION at %L",
&(*e)->where);
}
else
{
if ((*e)->symtree->n.sym != cd->omp_udr->omp_out
&& (*e)->symtree->n.sym != cd->omp_udr->omp_in)
gfc_error ("Variable other than OMP_OUT or OMP_IN used in "
"combiner of !$OMP DECLARE REDUCTION at %L",
&(*e)->where);
}
}
return 0;
}
/* Resolve !$omp declare reduction constructs. */
static void
gfc_resolve_omp_udr (gfc_omp_udr *omp_udr)
{
gfc_actual_arglist *a;
const char *predef_name = NULL;
switch (omp_udr->rop)
{
case OMP_REDUCTION_PLUS:
case OMP_REDUCTION_TIMES:
case OMP_REDUCTION_MINUS:
case OMP_REDUCTION_AND:
case OMP_REDUCTION_OR:
case OMP_REDUCTION_EQV:
case OMP_REDUCTION_NEQV:
case OMP_REDUCTION_MAX:
case OMP_REDUCTION_USER:
break;
default:
gfc_error ("Invalid operator for !$OMP DECLARE REDUCTION %s at %L",
omp_udr->name, &omp_udr->where);
return;
}
if (gfc_omp_udr_predef (omp_udr->rop, omp_udr->name,
&omp_udr->ts, &predef_name))
{
if (predef_name)
gfc_error_now ("Redefinition of predefined %s "
"!$OMP DECLARE REDUCTION at %L",
predef_name, &omp_udr->where);
else
gfc_error_now ("Redefinition of predefined "
"!$OMP DECLARE REDUCTION at %L", &omp_udr->where);
return;
}
if (omp_udr->ts.type == BT_CHARACTER
&& omp_udr->ts.u.cl->length
&& omp_udr->ts.u.cl->length->expr_type != EXPR_CONSTANT)
{
gfc_error ("CHARACTER length in !$OMP DECLARE REDUCTION %s not "
"constant at %L", omp_udr->name, &omp_udr->where);
return;
}
struct omp_udr_callback_data cd;
cd.omp_udr = omp_udr;
cd.is_initializer = false;
gfc_code_walker (&omp_udr->combiner_ns->code, gfc_dummy_code_callback,
omp_udr_callback, &cd);
if (omp_udr->combiner_ns->code->op == EXEC_CALL)
{
for (a = omp_udr->combiner_ns->code->ext.actual; a; a = a->next)
if (a->expr == NULL)
break;
if (a)
gfc_error ("Subroutine call with alternate returns in combiner "
"of !$OMP DECLARE REDUCTION at %L",
&omp_udr->combiner_ns->code->loc);
}
if (omp_udr->initializer_ns)
{
cd.is_initializer = true;
gfc_code_walker (&omp_udr->initializer_ns->code, gfc_dummy_code_callback,
omp_udr_callback, &cd);
if (omp_udr->initializer_ns->code->op == EXEC_CALL)
{
for (a = omp_udr->initializer_ns->code->ext.actual; a; a = a->next)
if (a->expr == NULL)
break;
if (a)
gfc_error ("Subroutine call with alternate returns in "
"INITIALIZER clause of !$OMP DECLARE REDUCTION "
"at %L", &omp_udr->initializer_ns->code->loc);
for (a = omp_udr->initializer_ns->code->ext.actual; a; a = a->next)
if (a->expr
&& a->expr->expr_type == EXPR_VARIABLE
&& a->expr->symtree->n.sym == omp_udr->omp_priv
&& a->expr->ref == NULL)
break;
if (a == NULL)
gfc_error ("One of actual subroutine arguments in INITIALIZER "
"clause of !$OMP DECLARE REDUCTION must be OMP_PRIV "
"at %L", &omp_udr->initializer_ns->code->loc);
}
}
else if (omp_udr->ts.type == BT_DERIVED
&& !gfc_has_default_initializer (omp_udr->ts.u.derived))
{
gfc_error ("Missing INITIALIZER clause for !$OMP DECLARE REDUCTION "
"of derived type without default initializer at %L",
&omp_udr->where);
return;
}
}
void
gfc_resolve_omp_udrs (gfc_symtree *st)
{
gfc_omp_udr *omp_udr;
if (st == NULL)
return;
gfc_resolve_omp_udrs (st->left);
gfc_resolve_omp_udrs (st->right);
for (omp_udr = st->n.omp_udr; omp_udr; omp_udr = omp_udr->next)
gfc_resolve_omp_udr (omp_udr);
}
|
crtc-demos/gcc-ia16
|
gcc/fortran/openmp.c
|
C
|
gpl-2.0
| 144,028 |
<?php
/**
* This software is intended for use with Oxwall Free Community Software http://www.oxwall.org/ and is
* licensed under The BSD license.
* ---
* Copyright (c) 2013, Oxwall Foundation
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and
* the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Oxwall Foundation nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author Podyachev Evgeny <[email protected]>
* @package ow_plugins.socialsharing
* @since 1.6
*/
/* $widget = BOL_ComponentAdminService::getInstance()->addWidget('SOCIALSHARING_CMP_ProfileShareButtonsWidget', false);
$placeWidget = BOL_ComponentAdminService::getInstance()->addWidgetToPlace($widget, BOL_ComponentAdminService::PLACE_PROFILE);
BOL_ComponentAdminService::getInstance()->addWidgetToPosition($placeWidget, BOL_ComponentAdminService::SECTION_RIGHT); */
$widget = BOL_ComponentAdminService::getInstance()->addWidget('SOCIALSHARING_CMP_IndexShareButtonsWidget', false);
$placeWidget = BOL_ComponentAdminService::getInstance()->addWidgetToPlace($widget, BOL_ComponentAdminService::PLACE_INDEX);
BOL_ComponentAdminService::getInstance()->addWidgetToPosition($placeWidget, BOL_ComponentAdminService::SECTION_LEFT, 0);
|
seret/oxtebafu
|
ow_plugins/social_sharing/activate.php
|
PHP
|
gpl-2.0
| 2,550 |
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2015 Lennart Poettering
systemd 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.
systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/statvfs.h>
#include <sys/vfs.h>
#include "alloc-util.h"
#include "btrfs-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "lockfile-util.h"
#include "machine-pool.h"
#include "mkdir.h"
#include "mount-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "process-util.h"
#include "signal-util.h"
#include "stat-util.h"
#include "string-util.h"
#include "util.h"
#define VAR_LIB_MACHINES_SIZE_START (1024UL*1024UL*500UL)
#define VAR_LIB_MACHINES_FREE_MIN (1024UL*1024UL*750UL)
static int check_btrfs(void) {
struct statfs sfs;
if (statfs("/var/lib/machines", &sfs) < 0) {
if (errno != ENOENT)
return -errno;
if (statfs("/var/lib", &sfs) < 0)
return -errno;
}
return F_TYPE_EQUAL(sfs.f_type, BTRFS_SUPER_MAGIC);
}
static int setup_machine_raw(uint64_t size, sd_bus_error *error) {
_cleanup_free_ char *tmp = NULL;
_cleanup_close_ int fd = -1;
struct statvfs ss;
pid_t pid = 0;
siginfo_t si;
int r;
/* We want to be able to make use of btrfs-specific file
* system features, in particular subvolumes, reflinks and
* quota. Hence, if we detect that /var/lib/machines.raw is
* not located on btrfs, let's create a loopback file, place a
* btrfs file system into it, and mount it to
* /var/lib/machines. */
fd = open("/var/lib/machines.raw", O_RDWR|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
if (fd >= 0) {
r = fd;
fd = -1;
return r;
}
if (errno != ENOENT)
return sd_bus_error_set_errnof(error, errno, "Failed to open /var/lib/machines.raw: %m");
r = tempfn_xxxxxx("/var/lib/machines.raw", NULL, &tmp);
if (r < 0)
return r;
(void) mkdir_p_label("/var/lib", 0755);
fd = open(tmp, O_RDWR|O_CREAT|O_EXCL|O_NOCTTY|O_CLOEXEC, 0600);
if (fd < 0)
return sd_bus_error_set_errnof(error, errno, "Failed to create /var/lib/machines.raw: %m");
if (fstatvfs(fd, &ss) < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to determine free space on /var/lib/machines.raw: %m");
goto fail;
}
if (ss.f_bsize * ss.f_bavail < VAR_LIB_MACHINES_FREE_MIN) {
r = sd_bus_error_setf(error, SD_BUS_ERROR_FAILED, "Not enough free disk space to set up /var/lib/machines.");
goto fail;
}
if (ftruncate(fd, size) < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to enlarge /var/lib/machines.raw: %m");
goto fail;
}
pid = fork();
if (pid < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to fork mkfs.btrfs: %m");
goto fail;
}
if (pid == 0) {
/* Child */
(void) reset_all_signal_handlers();
(void) reset_signal_mask();
assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
fd = safe_close(fd);
execlp("mkfs.btrfs", "-Lvar-lib-machines", tmp, NULL);
if (errno == ENOENT)
return 99;
_exit(EXIT_FAILURE);
}
r = wait_for_terminate(pid, &si);
if (r < 0) {
sd_bus_error_set_errnof(error, r, "Failed to wait for mkfs.btrfs: %m");
goto fail;
}
pid = 0;
if (si.si_code != CLD_EXITED) {
r = sd_bus_error_setf(error, SD_BUS_ERROR_FAILED, "mkfs.btrfs died abnormally.");
goto fail;
}
if (si.si_status == 99) {
r = sd_bus_error_set_errnof(error, ENOENT, "Cannot set up /var/lib/machines, mkfs.btrfs is missing");
goto fail;
}
if (si.si_status != 0) {
r = sd_bus_error_setf(error, SD_BUS_ERROR_FAILED, "mkfs.btrfs failed with error code %i", si.si_status);
goto fail;
}
r = rename_noreplace(AT_FDCWD, tmp, AT_FDCWD, "/var/lib/machines.raw");
if (r < 0) {
sd_bus_error_set_errnof(error, r, "Failed to move /var/lib/machines.raw into place: %m");
goto fail;
}
r = fd;
fd = -1;
return r;
fail:
unlink_noerrno(tmp);
if (pid > 1)
kill_and_sigcont(pid, SIGKILL);
return r;
}
int setup_machine_directory(uint64_t size, sd_bus_error *error) {
_cleanup_release_lock_file_ LockFile lock_file = LOCK_FILE_INIT;
struct loop_info64 info = {
.lo_flags = LO_FLAGS_AUTOCLEAR,
};
_cleanup_close_ int fd = -1, control = -1, loop = -1;
_cleanup_free_ char* loopdev = NULL;
char tmpdir[] = "/tmp/machine-pool.XXXXXX", *mntdir = NULL;
bool tmpdir_made = false, mntdir_made = false, mntdir_mounted = false;
char buf[FORMAT_BYTES_MAX];
int r, nr = -1;
/* btrfs cannot handle file systems < 16M, hence use this as minimum */
if (size == (uint64_t) -1)
size = VAR_LIB_MACHINES_SIZE_START;
else if (size < 16*1024*1024)
size = 16*1024*1024;
/* Make sure we only set the directory up once at a time */
r = make_lock_file("/run/systemd/machines.lock", LOCK_EX, &lock_file);
if (r < 0)
return r;
r = check_btrfs();
if (r < 0)
return sd_bus_error_set_errnof(error, r, "Failed to determine whether /var/lib/machines is located on btrfs: %m");
if (r > 0) {
(void) btrfs_subvol_make_label("/var/lib/machines");
r = btrfs_quota_enable("/var/lib/machines", true);
if (r < 0)
log_warning_errno(r, "Failed to enable quota for /var/lib/machines, ignoring: %m");
r = btrfs_subvol_auto_qgroup("/var/lib/machines", 0, true);
if (r < 0)
log_warning_errno(r, "Failed to set up default quota hierarchy for /var/lib/machines, ignoring: %m");
return 1;
}
if (path_is_mount_point("/var/lib/machines", AT_SYMLINK_FOLLOW) > 0) {
log_debug("/var/lib/machines is already a mount point, not creating loopback file for it.");
return 0;
}
r = dir_is_populated("/var/lib/machines");
if (r < 0 && r != -ENOENT)
return r;
if (r > 0) {
log_debug("/var/log/machines is already populated, not creating loopback file for it.");
return 0;
}
r = mkfs_exists("btrfs");
if (r == -ENOENT) {
log_debug("mkfs.btrfs is missing, cannot create loopback file for /var/lib/machines.");
return 0;
}
if (r < 0)
return r;
fd = setup_machine_raw(size, error);
if (fd < 0)
return fd;
control = open("/dev/loop-control", O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK);
if (control < 0)
return sd_bus_error_set_errnof(error, errno, "Failed to open /dev/loop-control: %m");
nr = ioctl(control, LOOP_CTL_GET_FREE);
if (nr < 0)
return sd_bus_error_set_errnof(error, errno, "Failed to allocate loop device: %m");
if (asprintf(&loopdev, "/dev/loop%i", nr) < 0) {
r = -ENOMEM;
goto fail;
}
loop = open(loopdev, O_CLOEXEC|O_RDWR|O_NOCTTY|O_NONBLOCK);
if (loop < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to open loopback device: %m");
goto fail;
}
if (ioctl(loop, LOOP_SET_FD, fd) < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to bind loopback device: %m");
goto fail;
}
if (ioctl(loop, LOOP_SET_STATUS64, &info) < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to enable auto-clear for loopback device: %m");
goto fail;
}
/* We need to make sure the new /var/lib/machines directory
* has an access mode of 0700 at the time it is first made
* available. mkfs will create it with 0755 however. Hence,
* let's mount the directory into an inaccessible directory
* below /tmp first, fix the access mode, and move it to the
* public place then. */
if (!mkdtemp(tmpdir)) {
r = sd_bus_error_set_errnof(error, errno, "Failed to create temporary mount parent directory: %m");
goto fail;
}
tmpdir_made = true;
mntdir = strjoina(tmpdir, "/mnt");
if (mkdir(mntdir, 0700) < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to create temporary mount directory: %m");
goto fail;
}
mntdir_made = true;
if (mount(loopdev, mntdir, "btrfs", 0, NULL) < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to mount loopback device: %m");
goto fail;
}
mntdir_mounted = true;
r = btrfs_quota_enable(mntdir, true);
if (r < 0)
log_warning_errno(r, "Failed to enable quota, ignoring: %m");
r = btrfs_subvol_auto_qgroup(mntdir, 0, true);
if (r < 0)
log_warning_errno(r, "Failed to set up default quota hierarchy, ignoring: %m");
if (chmod(mntdir, 0700) < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to fix owner: %m");
goto fail;
}
(void) mkdir_p_label("/var/lib/machines", 0700);
if (mount(mntdir, "/var/lib/machines", NULL, MS_BIND, NULL) < 0) {
r = sd_bus_error_set_errnof(error, errno, "Failed to mount directory into right place: %m");
goto fail;
}
(void) syncfs(fd);
log_info("Set up /var/lib/machines as btrfs loopback file system of size %s mounted on /var/lib/machines.raw.", format_bytes(buf, sizeof(buf), size));
(void) umount2(mntdir, MNT_DETACH);
(void) rmdir(mntdir);
(void) rmdir(tmpdir);
return 1;
fail:
if (mntdir_mounted)
(void) umount2(mntdir, MNT_DETACH);
if (mntdir_made)
(void) rmdir(mntdir);
if (tmpdir_made)
(void) rmdir(tmpdir);
if (loop >= 0) {
(void) ioctl(loop, LOOP_CLR_FD);
loop = safe_close(loop);
}
if (control >= 0 && nr >= 0)
(void) ioctl(control, LOOP_CTL_REMOVE, nr);
return r;
}
static int sync_path(const char *p) {
_cleanup_close_ int fd = -1;
fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (fd < 0)
return -errno;
if (syncfs(fd) < 0)
return -errno;
return 0;
}
int grow_machine_directory(void) {
char buf[FORMAT_BYTES_MAX];
struct statvfs a, b;
uint64_t old_size, new_size, max_add;
int r;
/* Ensure the disk space data is accurate */
sync_path("/var/lib/machines");
sync_path("/var/lib/machines.raw");
if (statvfs("/var/lib/machines.raw", &a) < 0)
return -errno;
if (statvfs("/var/lib/machines", &b) < 0)
return -errno;
/* Don't grow if not enough disk space is available on the host */
if (((uint64_t) a.f_bavail * (uint64_t) a.f_bsize) <= VAR_LIB_MACHINES_FREE_MIN)
return 0;
/* Don't grow if at least 1/3th of the fs is still free */
if (b.f_bavail > b.f_blocks / 3)
return 0;
/* Calculate how much we are willing to add at most */
max_add = ((uint64_t) a.f_bavail * (uint64_t) a.f_bsize) - VAR_LIB_MACHINES_FREE_MIN;
/* Calculate the old size */
old_size = (uint64_t) b.f_blocks * (uint64_t) b.f_bsize;
/* Calculate the new size as three times the size of what is used right now */
new_size = ((uint64_t) b.f_blocks - (uint64_t) b.f_bavail) * (uint64_t) b.f_bsize * 3;
/* Always, grow at least to the start size */
if (new_size < VAR_LIB_MACHINES_SIZE_START)
new_size = VAR_LIB_MACHINES_SIZE_START;
/* If the new size is smaller than the old size, don't grow */
if (new_size < old_size)
return 0;
/* Ensure we never add more than the maximum */
if (new_size > old_size + max_add)
new_size = old_size + max_add;
r = btrfs_resize_loopback("/var/lib/machines", new_size, true);
if (r <= 0)
return r;
/* Also bump the quota, of both the subvolume leaf qgroup, as
* well as of any subtree quota group by the same id but a
* higher level, if it exists. */
(void) btrfs_qgroup_set_limit("/var/lib/machines", 0, new_size);
(void) btrfs_subvol_set_subtree_quota_limit("/var/lib/machines", 0, new_size);
log_info("Grew /var/lib/machines btrfs loopback file system to %s.", format_bytes(buf, sizeof(buf), new_size));
return 1;
}
|
rhvgoyal/systemd
|
src/shared/machine-pool.c
|
C
|
gpl-2.0
| 14,239 |
/*
* SDIO device core hardware definitions.
* sdio is a portion of the pcmcia core in core rev 3 - rev 8
*
* SDIO core support 1bit, 4 bit SDIO mode as well as SPI mode.
*
* Copyright (C) 1999-2013, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: sbsdio.h 383835 2013-02-07 23:32:39Z $
*/
#ifndef _SBSDIO_H
#define _SBSDIO_H
#define SBSDIO_NUM_FUNCTION 3 /* as of sdiod rev 0, supports 3 functions */
/* function 1 miscellaneous registers */
#define SBSDIO_SPROM_CS 0x10000 /* sprom command and status */
#define SBSDIO_SPROM_INFO 0x10001 /* sprom info register */
#define SBSDIO_SPROM_DATA_LOW 0x10002 /* sprom indirect access data byte 0 */
#define SBSDIO_SPROM_DATA_HIGH 0x10003 /* sprom indirect access data byte 1 */
#define SBSDIO_SPROM_ADDR_LOW 0x10004 /* sprom indirect access addr byte 0 */
#define SBSDIO_SPROM_ADDR_HIGH 0x10005 /* sprom indirect access addr byte 0 */
#define SBSDIO_CHIP_CTRL_DATA 0x10006 /* xtal_pu (gpio) output */
#define SBSDIO_CHIP_CTRL_EN 0x10007 /* xtal_pu (gpio) enable */
#define SBSDIO_WATERMARK 0x10008 /* rev < 7, watermark for sdio device */
#define SBSDIO_DEVICE_CTL 0x10009 /* control busy signal generation */
/* registers introduced in rev 8, some content (mask/bits) defs in sbsdpcmdev.h */
#define SBSDIO_FUNC1_SBADDRLOW 0x1000A /* SB Address Window Low (b15) */
#define SBSDIO_FUNC1_SBADDRMID 0x1000B /* SB Address Window Mid (b23:b16) */
#define SBSDIO_FUNC1_SBADDRHIGH 0x1000C /* SB Address Window High (b31:b24) */
#define SBSDIO_FUNC1_FRAMECTRL 0x1000D /* Frame Control (frame term/abort) */
#define SBSDIO_FUNC1_CHIPCLKCSR 0x1000E /* ChipClockCSR (ALP/HT ctl/status) */
#define SBSDIO_FUNC1_SDIOPULLUP 0x1000F /* SdioPullUp (on cmd, d0-d2) */
#define SBSDIO_FUNC1_WFRAMEBCLO 0x10019 /* Write Frame Byte Count Low */
#define SBSDIO_FUNC1_WFRAMEBCHI 0x1001A /* Write Frame Byte Count High */
#define SBSDIO_FUNC1_RFRAMEBCLO 0x1001B /* Read Frame Byte Count Low */
#define SBSDIO_FUNC1_RFRAMEBCHI 0x1001C /* Read Frame Byte Count High */
#define SBSDIO_FUNC1_MESBUSYCTRL 0x1001D /* MesBusyCtl at 0x1001D (rev 11) */
#define SBSDIO_FUNC1_MISC_REG_START 0x10000 /* f1 misc register start */
#define SBSDIO_FUNC1_MISC_REG_LIMIT 0x1001C /* f1 misc register end */
/* Sdio Core Rev 12 */
#define SBSDIO_FUNC1_WAKEUPCTRL 0x1001E
#define SBSDIO_FUNC1_WCTRL_ALPWAIT_MASK 0x1
#define SBSDIO_FUNC1_WCTRL_ALPWAIT_SHIFT 0
#define SBSDIO_FUNC1_WCTRL_HTWAIT_MASK 0x2
#define SBSDIO_FUNC1_WCTRL_HTWAIT_SHIFT 1
#define SBSDIO_FUNC1_SLEEPCSR 0x1001F
#define SBSDIO_FUNC1_SLEEPCSR_KSO_MASK 0x1
#define SBSDIO_FUNC1_SLEEPCSR_KSO_SHIFT 0
#define SBSDIO_FUNC1_SLEEPCSR_KSO_EN 1
#define SBSDIO_FUNC1_SLEEPCSR_DEVON_MASK 0x2
#define SBSDIO_FUNC1_SLEEPCSR_DEVON_SHIFT 1
/* SBSDIO_SPROM_CS */
#define SBSDIO_SPROM_IDLE 0
#define SBSDIO_SPROM_WRITE 1
#define SBSDIO_SPROM_READ 2
#define SBSDIO_SPROM_WEN 4
#define SBSDIO_SPROM_WDS 7
#define SBSDIO_SPROM_DONE 8
/* SBSDIO_SPROM_INFO */
#define SROM_SZ_MASK 0x03 /* SROM size, 1: 4k, 2: 16k */
#define SROM_BLANK 0x04 /* depreciated in corerev 6 */
#define SROM_OTP 0x80 /* OTP present */
/* SBSDIO_CHIP_CTRL */
#define SBSDIO_CHIP_CTRL_XTAL 0x01 /* or'd with onchip xtal_pu,
* 1: power on oscillator
* (for 4318 only)
*/
/* SBSDIO_WATERMARK */
#define SBSDIO_WATERMARK_MASK 0x7f /* number of words - 1 for sd device
* to wait before sending data to host
*/
/* SBSDIO_MESBUSYCTRL */
/* When RX FIFO has less entries than this & MBE is set
* => busy signal is asserted between data blocks.
*/
#define SBSDIO_MESBUSYCTRL_MASK 0x7f
#define SBSDIO_MESBUSYCTRL_ENAB 0x80 /* Enable busy capability for MES access */
/* SBSDIO_DEVICE_CTL */
#define SBSDIO_DEVCTL_SETBUSY 0x01 /* 1: device will assert busy signal when
* receiving CMD53
*/
#define SBSDIO_DEVCTL_SPI_INTR_SYNC 0x02 /* 1: assertion of sdio interrupt is
* synchronous to the sdio clock
*/
#define SBSDIO_DEVCTL_CA_INT_ONLY 0x04 /* 1: mask all interrupts to host
* except the chipActive (rev 8)
*/
#define SBSDIO_DEVCTL_PADS_ISO 0x08 /* 1: isolate internal sdio signals, put
* external pads in tri-state; requires
* sdio bus power cycle to clear (rev 9)
*/
#define SBSDIO_DEVCTL_EN_F2_BLK_WATERMARK 0x10 /* Enable function 2 tx for each block */
#define SBSDIO_DEVCTL_F2WM_ENAB 0x10 /* Enable F2 Watermark */
#define SBSDIO_DEVCTL_NONDAT_PADS_ISO 0x20 /* Isolate sdio clk and cmd (non-data) */
/* SBSDIO_FUNC1_CHIPCLKCSR */
#define SBSDIO_FORCE_ALP 0x01 /* Force ALP request to backplane */
#define SBSDIO_FORCE_HT 0x02 /* Force HT request to backplane */
#define SBSDIO_FORCE_ILP 0x04 /* Force ILP request to backplane */
#define SBSDIO_ALP_AVAIL_REQ 0x08 /* Make ALP ready (power up xtal) */
#define SBSDIO_HT_AVAIL_REQ 0x10 /* Make HT ready (power up PLL) */
#define SBSDIO_FORCE_HW_CLKREQ_OFF 0x20 /* Squelch clock requests from HW */
#define SBSDIO_ALP_AVAIL 0x40 /* Status: ALP is ready */
#define SBSDIO_HT_AVAIL 0x80 /* Status: HT is ready */
/* In rev8, actual avail bits followed original docs */
#define SBSDIO_Rev8_HT_AVAIL 0x40
#define SBSDIO_Rev8_ALP_AVAIL 0x80
#define SBSDIO_CSR_MASK 0x1F
#define SBSDIO_AVBITS (SBSDIO_HT_AVAIL | SBSDIO_ALP_AVAIL)
#define SBSDIO_ALPAV(regval) ((regval) & SBSDIO_AVBITS)
#define SBSDIO_HTAV(regval) (((regval) & SBSDIO_AVBITS) == SBSDIO_AVBITS)
#define SBSDIO_ALPONLY(regval) (SBSDIO_ALPAV(regval) && !SBSDIO_HTAV(regval))
#define SBSDIO_CLKAV(regval, alponly) (SBSDIO_ALPAV(regval) && \
(alponly ? 1 : SBSDIO_HTAV(regval)))
/* SBSDIO_FUNC1_SDIOPULLUP */
#define SBSDIO_PULLUP_D0 0x01 /* Enable D0/MISO pullup */
#define SBSDIO_PULLUP_D1 0x02 /* Enable D1/INT# pullup */
#define SBSDIO_PULLUP_D2 0x04 /* Enable D2 pullup */
#define SBSDIO_PULLUP_CMD 0x08 /* Enable CMD/MOSI pullup */
#define SBSDIO_PULLUP_ALL 0x0f /* All valid bits */
/* function 1 OCP space */
#define SBSDIO_SB_OFT_ADDR_MASK 0x07FFF /* sb offset addr is <= 15 bits, 32k */
#define SBSDIO_SB_OFT_ADDR_LIMIT 0x08000
#define SBSDIO_SB_ACCESS_2_4B_FLAG 0x08000 /* with b15, maps to 32-bit SB access */
/* some duplication with sbsdpcmdev.h here */
/* valid bits in SBSDIO_FUNC1_SBADDRxxx regs */
#define SBSDIO_SBADDRLOW_MASK 0x80 /* Valid bits in SBADDRLOW */
#define SBSDIO_SBADDRMID_MASK 0xff /* Valid bits in SBADDRMID */
#define SBSDIO_SBADDRHIGH_MASK 0xffU /* Valid bits in SBADDRHIGH */
#define SBSDIO_SBWINDOW_MASK 0xffff8000 /* Address bits from SBADDR regs */
/* direct(mapped) cis space */
#define SBSDIO_CIS_BASE_COMMON 0x1000 /* MAPPED common CIS address */
#ifdef BCMSPI
#define SBSDIO_CIS_SIZE_LIMIT 0x100 /* maximum bytes in one spi CIS */
#else
#define SBSDIO_CIS_SIZE_LIMIT 0x200 /* maximum bytes in one CIS */
#endif /* !BCMSPI */
#define SBSDIO_OTP_CIS_SIZE_LIMIT 0x078 /* maximum bytes OTP CIS */
#define SBSDIO_CIS_OFT_ADDR_MASK 0x1FFFF /* cis offset addr is < 17 bits */
#define SBSDIO_CIS_MANFID_TUPLE_LEN 6 /* manfid tuple length, include tuple,
* link bytes
*/
/* indirect cis access (in sprom) */
#define SBSDIO_SPROM_CIS_OFFSET 0x8 /* 8 control bytes first, CIS starts from
* 8th byte
*/
#define SBSDIO_BYTEMODE_DATALEN_MAX 64 /* sdio byte mode: maximum length of one
* data comamnd
*/
#define SBSDIO_CORE_ADDR_MASK 0x1FFFF /* sdio core function one address mask */
#endif /* _SBSDIO_H */
|
IOKP-kitkat/kernel_samsung_hlte
|
drivers/net/wireless/bcmdhd4339/include/sbsdio.h
|
C
|
gpl-2.0
| 8,594 |
/*
(c) Copyright 2000-2002 convergence integrated media GmbH.
(c) Copyright 2002-2004 convergence GmbH.
All rights reserved.
Written by Denis Oliver Kropp <[email protected]>,
Andreas Hundt <[email protected]>,
Sven Neumann <[email protected]> and
Ville Syrjälä <[email protected]>.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#ifndef __DIRECT__DIRECT_H__
#define __DIRECT__DIRECT_H__
#include <direct/types.h>
DirectResult direct_initialize();
DirectResult direct_shutdown();
#endif
|
alexrayne/uos-embedded
|
contrib/directfb/lib/direct/direct.h
|
C
|
gpl-2.0
| 1,240 |
<!DOCTYPE html>
<html>
<head>
<title>GeoExt Simple Overview Example</title>
<!-- ExtJS -->
<script type="text/javascript" src="http://cdn.sencha.com/ext/gpl/4.2.1/examples/shared/include-ext.js"></script>
<script type="text/javascript" src="http://cdn.sencha.com/ext/gpl/4.2.1/examples/shared/options-toolbar.js"></script>
<!-- Shared -->
<link rel="stylesheet" type="text/css" href="http://cdn.sencha.com/ext/gpl/4.2.1/examples/shared/example.css" />
<!-- Basic example styling -->
<link rel="stylesheet" type="text/css" href="../shared/example.css" />
<!-- You should definitely consider using a custom single-file version of OpenLayers -->
<script src="http://openlayers.org/api/2.13.1/OpenLayers.js"></script>
<link rel="stylesheet" type="text/css" href="http://openlayers.org/api/2.13.1/theme/default/style.css">
<script type="text/javascript" src="../loader.js"></script>
<script type="text/javascript" src="overview-generic.js"></script>
<style>
.gx-overview-map .olControlOverviewMapElement {
padding: 0;
background-color: rgba(0, 0, 0, 0.5)
}
</style>
</head>
<body>
<div id="desc">
<h1>GeoExt.OverviewMap Components</h1>
<p>This example shows how to work with the OverviewMap component. It inherits
from Ext.Component wrapping the OpenLayers Overview control. This means
you can place it in your applications layout as you would any other component.
The example shows the usage of an GeoExt.OverviewMap as an item of a
Ext.panel.Panel inside a vbox layout. The overviews map size is ultimately
determined by the parents dimensions.<br>
The OverviewMap component has not been configured with a map so it defaults to the
GeoExt.panel.Map guessed at runtime.<p>
<p>The js is not minified so it is readable. See
<a href="overview-generic.js">overview-generic.js</a>.</p>
</div>
</body>
</html>
|
henriquespedro/Autarquia-Livre
|
vendor/geoext2/examples/overviewmap/overview-generic.html
|
HTML
|
gpl-2.0
| 2,000 |
//
// iTermWelcomeCardActionButton.h
// iTerm2
//
// Created by George Nachman on 6/16/15.
//
//
#import <Cocoa/Cocoa.h>
typedef NS_ENUM(NSInteger, iTermTipCardActionButtonAnimationState) {
kTipCardButtonNotAnimating, // Staying put
kTipCardButtonAnimatingIn, // Staged to become visible
kTipCardButtonAnimatingOut, // Staged to hide
kTipCardButtonAnimatingOutCurrently // Moving
};
// A button in the tip-of-the-day card.
@interface iTermTipCardActionButton : NSControl
// Block called on click.
@property(nonatomic, copy) void (^block)(id);
// Used by card to perform layout on buttons that are coming or going.
@property(nonatomic, assign) iTermTipCardActionButtonAnimationState animationState;
// What the frame will be when animation is done.
@property(nonatomic, assign) NSRect postAnimationFrame;
// Is this button hidden?
@property(nonatomic, assign, getter=isCollapsed) BOOL collapsed;
// Label
@property(nonatomic, copy) NSString *title;
@property(nonatomic, copy) NSString *shortcut;
// 22x22pt icon
@property(nonatomic, retain) NSImage *icon;
// If many buttons share one row, this gives the button's index in the row.
@property(nonatomic, assign) int indexInRow;
// If many buttons share one row, this gives the number of buttons in the row.
@property(nonatomic, assign) int numberOfButtonsInRow;
// Important buttons get really loud colors.
@property(nonatomic, assign) BOOL important;
// Rotate icon 90 degrees? Animates on change.
- (void)setIconFlipped:(BOOL)isFlipped;
+ (NSColor *)blueColor;
@end
|
knu/iTerm2
|
sources/iTermTipCardActionButton.h
|
C
|
gpl-2.0
| 1,554 |
#ifndef _LRUMC_H
#define _LRUMC_H
#include <stdbool.h>
#include "pary.h"
//long long 最大值
#define L_L_MAX 9223372036854775807LL
//哈希桶稀疏度(72%是有数据的)
#define HASH_FULL_RATE 50
//key的最大长度
#define KEY_LEN 255
#define VALUE_LEN 1024
//data struct
typedef struct segment_config_s segment_config_t;
typedef struct segment_s segment_t;
typedef struct segment_item_s segment_item_t;
typedef struct lrumc_s lrumc_t;
typedef enum bucket_status_e bucket_status_t;
typedef struct bucket_s bucket_t;
typedef struct get_ret_s get_ret_t;
typedef unsigned long ulong;
//segment的配置结构
struct segment_config_s
{
int max_size;//最大容量
int buff_size;//缓冲区的大小
};
//segment的数据结构
struct segment_s
{
int max_size;//最大容量
int buff_size;//缓冲区的大小
int curr_size;//当前有多少数据
segment_item_t *item_list;//双向链表
};
//segment链表的元素结构
struct segment_item_s
{
int offset;//哈希桶的偏移值
long long weight;//权重
segment_item_t *pre;
segment_item_t *next;
};
//哈希桶的状态
enum bucket_status_e
{
BUCKET_STATUS_NULL = 0,//从未用过
BUCKET_STATUS_USED = 1,//当前在用
BUCKET_STATUS_HAD_USED = 2,//以前用过,现在无用
};
//哈希桶
struct bucket_s
{
bucket_status_t status;//状态
char *key;//key
int segment_pos;//在那一个segment
void *value;//值(pary_node_t)
long value_len;//值的长度
int bucket_offset;//相对于hash_code 处理的偏移度,越大越不好
ulong list_pos;//链表节点的地址
ulong hash_code_b;
ulong hash_code_c;
};
//lrumc总句柄
struct lrumc_s
{
int total;//一共可容纳多少个元素
int curr_num;//当前有多少个元素
int bucket_num;//哈希桶的总大小
int segment_num;//segment的数量
segment_t **segment;//segment数组(链表)
bucket_t *bucket;//哈希桶数组(顺序表)
ulong get_hits;
ulong get_misses;
ulong delete_hits;
ulong delete_misses;
ulong incr_hits;
ulong incr_misses;
ulong decr_hits;
ulong decr_misses;
ulong bytes_read;
ulong bytes_written;
ulong evictions;
ulong cmd_set;
ulong cmd_flush;
time_t start_time;
};
struct get_ret_s
{
long length;
void *data;
pary_type_t type;
};
//function
lrumc_t *init_lrumc( segment_config_t *config,int num);//初始化总句柄
void destroy_lrumc(lrumc_t *lrumc);//删除总句柄
get_ret_t *get_lrumc_data(lrumc_t *lrumc,char *key,char *path);//根据key path查找节点
bool set_lrumc_data(lrumc_t *lrumc,char *key,char *path,void *value,long value_len,pary_type_t value_type);//更新节点
bool add_lrumc_data(lrumc_t *lrumc,char *key,char *path,void *value,long value_len,pary_type_t value_type);//新增节点
bool replace_lrumc_data(lrumc_t *lrumc,char *key,char *path,void *value,long value_len,pary_type_t value_type);//更新节点
bool append_lrumc_data(lrumc_t *lrumc,char *key,char *path,void *value,long value_len);//追加内容(后面)
bool prepend_lrumc_data(lrumc_t *lrumc,char *key,char *path,void *value,long value_len);//追加内容(前面)
bool delete_lrumc_data(lrumc_t *lrumc,char *key,char *path);//删除节点
long long increment_lrumc_data(lrumc_t *lrumc,char *key,char *path,int num);//自增长
long long decrement_lrumc_data(lrumc_t *lrumc,char *key,char *path,int num);//自递减
void display_lrumc(lrumc_t *lrumc);//打印总句柄
void prepare_crypt_table();//初始化crypt_table(暴雪)
int count_lrumc_data(lrumc_t *lrumc,char *key,char *path);
long flush_all(lrumc_t *lrumc);
buff_t *list_lrumc_data(lrumc_t *lrumc,char *match_type,char *key);
buff_t *pop_lrumc_data(lrumc_t *lrumc,char *key,char *path);
buff_t *shift_lrumc_data(lrumc_t *lrumc,char *key,char *path);
bool push_lrumc_data(lrumc_t *lrumc,char *key,char *path,void *value,long value_len,pary_type_t value_type);
bool unshift_lrumc_data(lrumc_t *lrumc,char *key,char *path,void *value,long value_len,pary_type_t value_type);
buff_t *page_lrumc_data(lrumc_t *lrumc,char *key,char *path,int offset,int limit);
lrumc_t *update_lrumc(lrumc_t *lrumc,segment_config_t *config,int num);
#endif
|
johnsonzhu/irid
|
lrumc.h
|
C
|
gpl-2.0
| 4,094 |
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>systemd.netdev</title><meta name="generator" content="DocBook XSL Stylesheets V1.78.1"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><style>
a.headerlink {
color: #c60f0f;
font-size: 0.8em;
padding: 0 4px 0 4px;
text-decoration: none;
visibility: hidden;
}
a.headerlink:hover {
background-color: #c60f0f;
color: white;
}
h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, dt:hover > a.headerlink {
visibility: visible;
}
</style><a href="index.html">Index </a>·
<a href="systemd.directives.html">Directives </a>·
<a href="../python-systemd/index.html">Python </a>·
<a href="../libudev/index.html">libudev </a>·
<a href="../libudev/index.html">gudev </a><span style="float:right">systemd 215</span><hr><div class="refentry"><a name="systemd.netdev"></a><div class="titlepage"></div><div class="refnamediv"><h2>Name</h2><p>systemd.netdev — Virtual Network Device configuration</p></div><div class="refsynopsisdiv"><h2>Synopsis</h2><p><code class="filename"><em class="replaceable"><code>netdev</code></em>.netdev</code></p></div><div class="refsect1"><a name="idm214175257200"></a><h2 id="Description">Description<a class="headerlink" title="Permalink to this headline" href="#Description">¶</a></h2><p>Network setup is performed by
<a href="systemd-networkd.html"><span class="citerefentry"><span class="refentrytitle">systemd-networkd</span>(8)</span></a>.
</p><p>Virtual Network Device files must have the extension
<code class="filename">.netdev</code>; other extensions are ignored. Virtual
network devices are created as soon as networkd is started.</p><p>The <code class="filename">.netdev</code> files are read from the files located in the
system network directory <code class="filename">/usr/lib/systemd/network</code>,
the volatile runtime network directory
<code class="filename">/run/systemd/network</code> and the local administration
network directory <code class="filename">/etc/systemd/network</code>.
All configuration files are collectively sorted and processed in lexical order,
regardless of the directories in which they live. However, files with
identical filenames replace each other. Files in
<code class="filename">/etc</code> have the highest priority, files in
<code class="filename">/run</code> take precedence over files with the same
name in <code class="filename">/usr/lib</code>. This can be used to override a
system-supplied configuration file with a local file if needed; a symlink in
<code class="filename">/etc</code> with the same name as a configuration file in
<code class="filename">/usr/lib</code>, pointing to <code class="filename">/dev/null</code>,
disables the configuration file entirely.</p></div><div class="refsect1"><a name="idm214175246240"></a><h2 id="[Match] Section Options">[Match] Section Options<a class="headerlink" title="Permalink to this headline" href="#%5BMatch%5D%20Section%20Options">¶</a></h2><p>A virtual network device is only created if the
"<code class="literal">[Match]</code>" section matches the current
environment, or if the section is empty. The following keys are accepted:</p><div class="variablelist"><dl class="variablelist"><dt id="Host="><span class="term"><code class="varname">Host=</code></span><a class="headerlink" title="Permalink to this term" href="#Host=">¶</a></dt><dd><p>Matches against the hostname or machine ID of the
host. See "<code class="literal">ConditionHost=</code>" in
<a href="systemd.unit.html"><span class="citerefentry"><span class="refentrytitle">systemd.unit</span>(5)</span></a>
for details.
</p></dd><dt id="Virtualization="><span class="term"><code class="varname">Virtualization=</code></span><a class="headerlink" title="Permalink to this term" href="#Virtualization=">¶</a></dt><dd><p>Checks whether the system is executed in a virtualized
environment and optionally test whether it is a specific
implementation. See "<code class="literal">ConditionVirtualization=</code>" in
<a href="systemd.unit.html"><span class="citerefentry"><span class="refentrytitle">systemd.unit</span>(5)</span></a>
for details.
</p></dd><dt id="KernelCommandLine="><span class="term"><code class="varname">KernelCommandLine=</code></span><a class="headerlink" title="Permalink to this term" href="#KernelCommandLine=">¶</a></dt><dd><p>Checks whether a specific kernel command line option is
set (or if prefixed with the exclamation mark unset). See
"<code class="literal">ConditionKernelCommandLine=</code>" in
<a href="systemd.unit.html"><span class="citerefentry"><span class="refentrytitle">systemd.unit</span>(5)</span></a>
for details.
</p></dd><dt id="Architecture="><span class="term"><code class="varname">Architecture=</code></span><a class="headerlink" title="Permalink to this term" href="#Architecture=">¶</a></dt><dd><p>Checks whether the system is running on a specific
architecture. See "<code class="literal">ConditionArchitecture=</code>" in
<a href="systemd.unit.html"><span class="citerefentry"><span class="refentrytitle">systemd.unit</span>(5)</span></a>
for details.
</p></dd></dl></div></div><div class="refsect1"><a name="idm214179182688"></a><h2 id="[NetDev] Section Options">[NetDev] Section Options<a class="headerlink" title="Permalink to this headline" href="#%5BNetDev%5D%20Section%20Options">¶</a></h2><p>The "<code class="literal">[NetDev]</code>" section accepts the following
keys:</p><div class="variablelist"><dl class="variablelist"><dt id="Description="><span class="term"><code class="varname">Description=</code></span><a class="headerlink" title="Permalink to this term" href="#Description=">¶</a></dt><dd><p>A free-form description of the netdev.
</p></dd><dt id="Name="><span class="term"><code class="varname">Name=</code></span><a class="headerlink" title="Permalink to this term" href="#Name=">¶</a></dt><dd><p>The interface name used when creating the
netdev. This option is compulsory.</p></dd><dt id="Kind="><span class="term"><code class="varname">Kind=</code></span><a class="headerlink" title="Permalink to this term" href="#Kind=">¶</a></dt><dd><p>The netdev kind. Currently, "<code class="literal">bridge</code>",
"<code class="literal">bond</code>", "<code class="literal">vlan</code>",
"<code class="literal">macvlan</code>", "<code class="literal">vxlan</code>",
"<code class="literal">ipip</code>", "<code class="literal">gre</code>",
"<code class="literal">sit</code>", "<code class="literal">vti</code>",
"<code class="literal">veth</code>", and "<code class="literal">dummy</code>"
are supported. This option is compulsory.</p></dd><dt id="MTUBytes="><span class="term"><code class="varname">MTUBytes=</code></span><a class="headerlink" title="Permalink to this term" href="#MTUBytes=">¶</a></dt><dd><p>The maximum transmission unit in bytes to
set for the device. The usual suffixes K, M, G,
are supported and are understood to the base of
1024.</p></dd><dt id="MACAddress="><span class="term"><code class="varname">MACAddress=</code></span><a class="headerlink" title="Permalink to this term" href="#MACAddress=">¶</a></dt><dd><p>The MAC address to use for the device.
If none is given, one is generated based on
the interface name and the
<a href="machine-id.html"><span class="citerefentry"><span class="refentrytitle">machine-id</span>(5)</span></a>.
</p></dd></dl></div></div><div class="refsect1"><a name="idm214179154848"></a><h2 id="[VLAN] Section Options">[VLAN] Section Options<a class="headerlink" title="Permalink to this headline" href="#%5BVLAN%5D%20Section%20Options">¶</a></h2><p>The "<code class="literal">[VLAN]</code>" section only applies for netdevs of kind "<code class="literal">vlan</code>",
and accepts the following key:</p><div class="variablelist"><dl class="variablelist"><dt id="Id="><span class="term"><code class="varname">Id=</code></span><a class="headerlink" title="Permalink to this term" href="#Id=">¶</a></dt><dd><p>The VLAN ID to use. An integer in the range 0–4094.
This option is compulsory.</p></dd></dl></div></div><div class="refsect1"><a name="idm214179149536"></a><h2 id="[MACVLAN] Section Options">[MACVLAN] Section Options<a class="headerlink" title="Permalink to this headline" href="#%5BMACVLAN%5D%20Section%20Options">¶</a></h2><p>The "<code class="literal">[MACVLAN]</code>" section only applies for netdevs of kind
"<code class="literal">macvlan</code>", and accepts the following key:</p><div class="variablelist"><dl class="variablelist"><dt id="Mode="><span class="term"><code class="varname">Mode=</code></span><a class="headerlink" title="Permalink to this term" href="#Mode=">¶</a></dt><dd><p>The MACVLAN mode to use. The supported options are
"<code class="literal">private</code>", "<code class="literal">vepa</code>",
"<code class="literal">bridge</code>" and "<code class="literal">passthru</code>".
</p></dd></dl></div></div><div class="refsect1"><a name="idm214174175360"></a><h2 id="[VXLAN] Section Options">[VXLAN] Section Options<a class="headerlink" title="Permalink to this headline" href="#%5BVXLAN%5D%20Section%20Options">¶</a></h2><p>The "<code class="literal">[VXLAN]</code>" section only applies for netdevs of kind
"<code class="literal">vxlan</code>", and accepts the following key:</p><div class="variablelist"><dl class="variablelist"><dt id="Id="><span class="term"><code class="varname">Id=</code></span><a class="headerlink" title="Permalink to this term" href="#Id=">¶</a></dt><dd><p>The VXLAN ID to use.</p></dd><dt id="Group="><span class="term"><code class="varname">Group=</code></span><a class="headerlink" title="Permalink to this term" href="#Group=">¶</a></dt><dd><p>An assigned multicast group IP address.</p></dd><dt id="TOS="><span class="term"><code class="varname">TOS=</code></span><a class="headerlink" title="Permalink to this term" href="#TOS=">¶</a></dt><dd><p>The Type Of Service byte value for a vxlan interface.</p></dd><dt id="TTL="><span class="term"><code class="varname">TTL=</code></span><a class="headerlink" title="Permalink to this term" href="#TTL=">¶</a></dt><dd><p>A fixed Time To Live N on Virtual eXtensible Local Area Network packets.
N is a number in the range 1-255. 0 is a special value meaning that packets
inherit the TTL value.</p></dd><dt id="MacLearning="><span class="term"><code class="varname">MacLearning=</code></span><a class="headerlink" title="Permalink to this term" href="#MacLearning=">¶</a></dt><dd><p>A boolean. When true, enables dynamic MAC learning
to discover remote MAC addresses.</p></dd></dl></div></div><div class="refsect1"><a name="idm214174163584"></a><h2 id="[Tunnel] Section Options">[Tunnel] Section Options<a class="headerlink" title="Permalink to this headline" href="#%5BTunnel%5D%20Section%20Options">¶</a></h2><p>The "<code class="literal">[Tunnel]</code>" section only applies for netdevs of kind
"<code class="literal">ipip</code>", "<code class="literal">sit</code>", "<code class="literal">gre</code>" and
"<code class="literal">vti</code>" and accepts the following keys:</p><div class="variablelist"><dl class="variablelist"><dt id="Local="><span class="term"><code class="varname">Local=</code></span><a class="headerlink" title="Permalink to this term" href="#Local=">¶</a></dt><dd><p>A static local address for tunneled packets.
It must be an address on another interface of this host.</p></dd><dt id="Remote="><span class="term"><code class="varname">Remote=</code></span><a class="headerlink" title="Permalink to this term" href="#Remote=">¶</a></dt><dd><p>The remote endpoint of the tunnel.</p></dd><dt id="TOS="><span class="term"><code class="varname">TOS=</code></span><a class="headerlink" title="Permalink to this term" href="#TOS=">¶</a></dt><dd><p>The Type Of Service byte value for a tunnel interface.
For details about the TOS see the
<a class="ulink" href="http://tools.ietf.org/html/rfc1349" target="_top">
Type of Service in the Internet Protocol Suite
</a> document.
</p></dd><dt id="TTL="><span class="term"><code class="varname">TTL=</code></span><a class="headerlink" title="Permalink to this term" href="#TTL=">¶</a></dt><dd><p>A fixed Time To Live N on tunneled packets.
N is a number in the range 1-255. 0 is a special value meaning that packets
inherit the TTL value. The default value for IPv4 tunnels is: inherit.
The default value for IPv6 tunnels is: 64.</p></dd><dt id="DiscoverPathMTU="><span class="term"><code class="varname">DiscoverPathMTU=</code></span><a class="headerlink" title="Permalink to this term" href="#DiscoverPathMTU=">¶</a></dt><dd><p>A boolean. When true, enables Path MTU Discovery on the tunnel.</p></dd></dl></div></div><div class="refsect1"><a name="idm214174148736"></a><h2 id="[Peer] Section Options">[Peer] Section Options<a class="headerlink" title="Permalink to this headline" href="#%5BPeer%5D%20Section%20Options">¶</a></h2><p>The "<code class="literal">[Peer]</code>" section only applies for netdevs of kind "<code class="literal">veth</code>"
and accepts the following key:</p><div class="variablelist"><dl class="variablelist"><dt id="Name="><span class="term"><code class="varname">Name=</code></span><a class="headerlink" title="Permalink to this term" href="#Name=">¶</a></dt><dd><p>The interface name used when creating the netdev.
This option is compulsory.</p></dd><dt id="MACAddress="><span class="term"><code class="varname">MACAddress=</code></span><a class="headerlink" title="Permalink to this term" href="#MACAddress=">¶</a></dt><dd><p>The peer MACAddress, if not set it is generated in the same
way as the MAC address of the main interface.</p></dd></dl></div></div><div class="refsect1"><a name="idm214174142064"></a><h2 id="[Tun] Section Options">[Tun] Section Options<a class="headerlink" title="Permalink to this headline" href="#%5BTun%5D%20Section%20Options">¶</a></h2><p>The "<code class="literal">[Tun]</code>" section only applies for netdevs of kind
"<code class="literal">tun</code>", and accepts the following keys:</p><div class="variablelist"><dl class="variablelist"><dt id="OneQueue="><span class="term"><code class="varname">OneQueue=</code></span><a class="headerlink" title="Permalink to this term" href="#OneQueue=">¶</a></dt><dd><p>Takes a boolean argument. Configures whether
all packets are queued at the device (enabled), or a fixed number
of packets are queued at the device and the rest at the
"<code class="literal">qdisc</code>". Defaults to "<code class="literal">no</code>".</p></dd><dt id="MultiQueue="><span class="term"><code class="varname">MultiQueue=</code></span><a class="headerlink" title="Permalink to this term" href="#MultiQueue=">¶</a></dt><dd><p>Takes a boolean argument. Configures whether to
use multiple file descriptors (queues) to parallelize packets
sending and receiving. Defaults to "<code class="literal">no</code>".</p></dd><dt id="PacketInfo="><span class="term"><code class="varname">PacketInfo=</code></span><a class="headerlink" title="Permalink to this term" href="#PacketInfo=">¶</a></dt><dd><p>Takes a boolean argument. Configures whether packets
should be prepened with four extra bytes (two flag bytes and two
protocol bytes). If disabled it indicates that the packets will be
pure IP packets. Defaults to "<code class="literal">no</code>".</p></dd><dt id="User="><span class="term"><code class="varname">User=</code></span><a class="headerlink" title="Permalink to this term" href="#User=">¶</a></dt><dd><p>User to grant access to the <code class="filename">/dev/net/tun</code>
device.</p></dd><dt id="Group="><span class="term"><code class="varname">Group=</code></span><a class="headerlink" title="Permalink to this term" href="#Group=">¶</a></dt><dd><p>Group to grant access to the <code class="filename">/dev/net/tun</code>
device.</p></dd></dl></div></div><div class="refsect1"><a name="idm214174126640"></a><h2 id="[Tap] Section Options">[Tap] Section Options<a class="headerlink" title="Permalink to this headline" href="#%5BTap%5D%20Section%20Options">¶</a></h2><p>The "<code class="literal">[Tap]</code>" section only applies for netdevs of kind
"<code class="literal">tap</code>", and accepts the same keys as the
"<code class="literal">[Tun]</code>" section.</p></div><div class="refsect1"><a name="idm214174123456"></a><h2 id="Example">Example<a class="headerlink" title="Permalink to this headline" href="#Example">¶</a></h2><div class="example"><a name="idm214174122816"></a><p class="title"><b>Example 1. /etc/systemd/network/bridge.netdev</b></p><div class="example-contents"><pre class="programlisting">[NetDev]
Name=bridge0
Kind=bridge</pre></div></div><br class="example-break"><div class="example"><a name="idm214174121424"></a><p class="title"><b>Example 2. /etc/systemd/network/vlan1.netdev</b></p><div class="example-contents"><pre class="programlisting">[Match]
Virtualization=no
[NetDev]
Name=vlan1
Kind=vlan
[VLAN]
Id=1</pre></div></div><br class="example-break"><div class="example"><a name="idm214174119952"></a><p class="title"><b>Example 3. /etc/systemd/network/ipip.netdev</b></p><div class="example-contents"><pre class="programlisting">[NetDev]
Name=ipip-tun
Kind=ipip
MTUBytes=1480
[Tunnel]
Local=192.168.223.238
Remote=192.169.224.239
TTL=64</pre></div></div><br class="example-break"><div class="example"><a name="idm214174118432"></a><p class="title"><b>Example 4. /etc/systemd/network/tap.netdev</b></p><div class="example-contents"><pre class="programlisting">[NetDev]
Name=tap-test
Kind=tap
[Tap]
MultiQueue=true
PacketInfo=true</pre></div></div><br class="example-break"><div class="example"><a name="idm214174116960"></a><p class="title"><b>Example 5. /etc/systemd/network/sit.netdev</b></p><div class="example-contents"><pre class="programlisting">[NetDev]
Name=sit-tun
Kind=sit
MTUBytes=1480
[Tunnel]
Local=10.65.223.238
Remote=10.65.223.239</pre></div></div><br class="example-break"><div class="example"><a name="idm214174115456"></a><p class="title"><b>Example 6. /etc/systemd/network/gre.netdev</b></p><div class="example-contents"><pre class="programlisting">[NetDev]
Name=gre-tun
Kind=gre
MTUBytes=1480
[Tunnel]
Local=10.65.223.238
Remote=10.65.223.239</pre></div></div><br class="example-break"><div class="example"><a name="idm214174113952"></a><p class="title"><b>Example 7. /etc/systemd/network/vti.netdev</b></p><div class="example-contents"><pre class="programlisting">[NetDev]
Name=vti-tun
Kind=vti
MTUBytes=1480
[Tunnel]
Local=10.65.223.238
Remote=10.65.223.239</pre></div></div><br class="example-break"><div class="example"><a name="idm214174112448"></a><p class="title"><b>Example 8. /etc/systemd/network/veth.netdev</b></p><div class="example-contents"><pre class="programlisting">[NetDev]
Name=veth-test
Kind=veth
[Peer]
Name=veth-peer</pre></div></div><br class="example-break"><div class="example"><a name="idm214174110976"></a><p class="title"><b>Example 9. /etc/systemd/network/dummy.netdev</b></p><div class="example-contents"><pre class="programlisting">[NetDev]
Name=dummy-test
Kind=dummy
MACAddress=12:34:56:78:9a:bc</pre></div></div><br class="example-break"></div><div class="refsect1"><a name="idm214174109376"></a><h2 id="See Also">See Also<a class="headerlink" title="Permalink to this headline" href="#See%20Also">¶</a></h2><p>
<a href="systemd.html"><span class="citerefentry"><span class="refentrytitle">systemd</span>(1)</span></a>,
<a href="systemd-networkd.html"><span class="citerefentry"><span class="refentrytitle">systemd-networkd</span>(8)</span></a>,
<a href="systemd.network.html"><span class="citerefentry"><span class="refentrytitle">systemd.network</span>(5)</span></a>
</p></div></div></body></html>
|
flonatel/systemd-pne1
|
man/systemd.netdev.html
|
HTML
|
gpl-2.0
| 23,263 |
/* TUI Interpreter definitions for GDB, the GNU debugger.
Copyright (C) 2003-2016 Free Software Foundation, Inc.
This file is part of GDB.
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/>. */
#include "defs.h"
#include "cli/cli-interp.h"
#include "interps.h"
#include "top.h"
#include "event-top.h"
#include "event-loop.h"
#include "ui-out.h"
#include "cli-out.h"
#include "tui/tui-data.h"
#include "readline/readline.h"
#include "tui/tui-win.h"
#include "tui/tui.h"
#include "tui/tui-io.h"
#include "infrun.h"
#include "observer.h"
#include "gdbthread.h"
static struct ui_out *tui_ui_out (struct interp *self);
/* Set to 1 when the TUI mode must be activated when we first start
gdb. */
static int tui_start_enabled = 0;
/* Returns the INTERP if the INTERP is a TUI, and returns NULL
otherwise. */
static struct interp *
as_tui_interp (struct interp *interp)
{
if (strcmp (interp_name (interp), INTERP_TUI) == 0)
return interp;
return NULL;
}
/* Cleanup the tui before exiting. */
static void
tui_exit (void)
{
/* Disable the tui. Curses mode is left leaving the screen in a
clean state (see endwin()). */
tui_disable ();
}
/* Observers for several run control events. If the interpreter is
quiet (i.e., another interpreter is being run with
interpreter-exec), print nothing. */
/* Observer for the normal_stop notification. */
static void
tui_on_normal_stop (struct bpstats *bs, int print_frame)
{
if (!print_frame)
return;
SWITCH_THRU_ALL_UIS ()
{
struct interp *interp = top_level_interpreter ();
struct interp *tui = as_tui_interp (interp);
struct thread_info *thread;
if (tui == NULL)
continue;
thread = inferior_thread ();
if (should_print_stop_to_console (interp, thread))
print_stop_event (tui_ui_out (tui));
}
}
/* Observer for the signal_received notification. */
static void
tui_on_signal_received (enum gdb_signal siggnal)
{
SWITCH_THRU_ALL_UIS ()
{
struct interp *tui = as_tui_interp (top_level_interpreter ());
if (tui == NULL)
continue;
print_signal_received_reason (tui_ui_out (tui), siggnal);
}
}
/* Observer for the end_stepping_range notification. */
static void
tui_on_end_stepping_range (void)
{
SWITCH_THRU_ALL_UIS ()
{
struct interp *tui = as_tui_interp (top_level_interpreter ());
if (tui == NULL)
continue;
print_end_stepping_range_reason (tui_ui_out (tui));
}
}
/* Observer for the signal_exited notification. */
static void
tui_on_signal_exited (enum gdb_signal siggnal)
{
SWITCH_THRU_ALL_UIS ()
{
struct interp *tui = as_tui_interp (top_level_interpreter ());
if (tui == NULL)
continue;
print_signal_exited_reason (tui_ui_out (tui), siggnal);
}
}
/* Observer for the exited notification. */
static void
tui_on_exited (int exitstatus)
{
SWITCH_THRU_ALL_UIS ()
{
struct interp *tui = as_tui_interp (top_level_interpreter ());
if (tui == NULL)
continue;
print_exited_reason (tui_ui_out (tui), exitstatus);
}
}
/* Observer for the no_history notification. */
static void
tui_on_no_history (void)
{
SWITCH_THRU_ALL_UIS ()
{
struct interp *tui = as_tui_interp (top_level_interpreter ());
if (tui == NULL)
continue;
print_no_history_reason (tui_ui_out (tui));
}
}
/* Observer for the sync_execution_done notification. */
static void
tui_on_sync_execution_done (void)
{
struct interp *tui = as_tui_interp (top_level_interpreter ());
if (tui == NULL)
return;
display_gdb_prompt (NULL);
}
/* Observer for the command_error notification. */
static void
tui_on_command_error (void)
{
struct interp *tui = as_tui_interp (top_level_interpreter ());
if (tui == NULL)
return;
display_gdb_prompt (NULL);
}
/* Observer for the user_selected_context_changed notification. */
static void
tui_on_user_selected_context_changed (user_selected_what selection)
{
struct thread_info *tp;
/* This event is suppressed. */
if (cli_suppress_notification.user_selected_context)
return;
tp = find_thread_ptid (inferior_ptid);
SWITCH_THRU_ALL_UIS ()
{
struct interp *tui = as_tui_interp (top_level_interpreter ());
if (tui == NULL)
continue;
if (selection & USER_SELECTED_INFERIOR)
print_selected_inferior (tui_ui_out (tui));
if (tp != NULL
&& ((selection & (USER_SELECTED_THREAD | USER_SELECTED_FRAME))))
print_selected_thread_frame (tui_ui_out (tui), selection);
}
}
/* These implement the TUI interpreter. */
static void *
tui_init (struct interp *self, int top_level)
{
/* Install exit handler to leave the screen in a good shape. */
atexit (tui_exit);
tui_initialize_static_data ();
tui_initialize_io ();
tui_initialize_win ();
if (ui_file_isatty (gdb_stdout))
tui_initialize_readline ();
return NULL;
}
static int
tui_resume (void *data)
{
struct ui *ui = current_ui;
struct ui_file *stream;
/* gdb_setup_readline will change gdb_stdout. If the TUI was
previously writing to gdb_stdout, then set it to the new
gdb_stdout afterwards. */
stream = tui_old_uiout->set_stream (gdb_stdout);
if (stream != gdb_stdout)
{
tui_old_uiout->set_stream (stream);
stream = NULL;
}
gdb_setup_readline (1);
ui->input_handler = command_line_handler;
if (stream != NULL)
tui_old_uiout->set_stream (gdb_stdout);
if (tui_start_enabled)
tui_enable ();
return 1;
}
static int
tui_suspend (void *data)
{
tui_start_enabled = tui_active;
tui_disable ();
return 1;
}
static struct ui_out *
tui_ui_out (struct interp *self)
{
if (tui_active)
return tui_out;
else
return tui_old_uiout;
}
static struct gdb_exception
tui_exec (void *data, const char *command_str)
{
internal_error (__FILE__, __LINE__, _("tui_exec called"));
}
/* The TUI interpreter's vtable. */
static const struct interp_procs tui_interp_procs = {
tui_init,
tui_resume,
tui_suspend,
tui_exec,
tui_ui_out,
NULL,
cli_interpreter_pre_command_loop,
cli_interpreter_supports_command_editing,
};
/* Factory for TUI interpreters. */
static struct interp *
tui_interp_factory (const char *name)
{
return interp_new (name, &tui_interp_procs, NULL);
}
/* Provide a prototype to silence -Wmissing-prototypes. */
extern initialize_file_ftype _initialize_tui_interp;
void
_initialize_tui_interp (void)
{
interp_factory_register (INTERP_TUI, tui_interp_factory);
if (interpreter_p && strcmp (interpreter_p, INTERP_TUI) == 0)
tui_start_enabled = 1;
if (interpreter_p && strcmp (interpreter_p, INTERP_CONSOLE) == 0)
{
xfree (interpreter_p);
interpreter_p = xstrdup (INTERP_TUI);
}
/* If changing this, remember to update cli-interp.c as well. */
observer_attach_normal_stop (tui_on_normal_stop);
observer_attach_signal_received (tui_on_signal_received);
observer_attach_end_stepping_range (tui_on_end_stepping_range);
observer_attach_signal_exited (tui_on_signal_exited);
observer_attach_exited (tui_on_exited);
observer_attach_no_history (tui_on_no_history);
observer_attach_sync_execution_done (tui_on_sync_execution_done);
observer_attach_command_error (tui_on_command_error);
observer_attach_user_selected_context_changed
(tui_on_user_selected_context_changed);
}
|
phil-opp/binutils-gdb
|
gdb/tui/tui-interp.c
|
C
|
gpl-2.0
| 7,962 |
/*
* Tlf - contest logging program for amateur radio operators
* Copyright (C) 2001-2002-2003 Rein Couperus <[email protected]>
* 2011 Thomas Beierlein <[email protected]>
*
* 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
*/
/* ------------------------------------------------------------
* utilities to work with worked stations
*
*--------------------------------------------------------------*/
#include <stdbool.h>
#include <string.h>
#include "bands.h"
#include "get_time.h"
#include "getctydata.h"
#include "globalvars.h"
#include "tlf.h"
/** \brief empty collection of worked stations
*/
void init_worked(void) {
memset(worked, 0, sizeof(worked));
nr_worked = 0;
}
/** \brief lookup 'hiscall' in array of worked stations
*
* See if 'hiscall' was already worked by looking it up in worked[]
* \param hiscall callsign to lookup
* \return index in callarray where hiscall was found (-1 if not found)
*/
int lookup_worked(char *call) {
int found = -1;
int i;
for (i = 0; i < nr_worked; i++) {
if (strcmp(worked[i].call, call) == 0) {
found = i;
break;
}
}
return (found);
}
/* add a new entry for call to the collection */
static int add_new(char *call) {
int i = nr_worked;
memset(&worked[i], 0, sizeof(worked_t));
g_strlcpy(worked[i].call, call, sizeof(worked[0].call));
worked[i].ctyinfo = getctyinfo(call);
nr_worked++;
return nr_worked - 1;
}
/** Lookup given call
*
* Add new entry if not worked already.
*
* \return index to data structure */
int lookup_or_add_worked(char *call) {
int index = lookup_worked(call);
if (index == -1) {
index = add_new(call);
}
return index;
}
/* check if station was worked in the current minitest period
* it takes into account actual mode/band info
*/
bool worked_in_current_minitest_period(int found) {
if (found < 0) {
return false;
}
if (!minitest) {
return true; // minitest is off, so the answer is yes
}
long currtime = get_time();
long period_start = (currtime / minitest) * minitest;
return worked[found].qsotime[trxmode][bandinx] >= period_start;
}
bool is_dupe(char *call, int bandindex, int mode) {
int index;
index = lookup_worked(call);
if (index == -1) /* new station */
return false;
if (!qso_once /* check band only if qso_once not set */
&& ((worked[index].band & inxes[bandindex]) == 0))
return false;
if (mixedmode /* check mode only if MIXED is allowed */
&& (worked[index].qsotime[mode][bandindex] == 0))
return false;
if (!worked_in_current_minitest_period(index))
return false;
return true;
}
/* update exchange and last worked time for given station */
void update_worked(int station, struct qso_t *qso) {
if (strlen(qso->comment) > 0) {
g_strlcpy(worked[station].exchange, qso->comment,
sizeof(worked[0].exchange));
g_strchomp(worked[station].exchange);
}
worked[station].qsotime[qso->mode][qso->bandindex] = qso->timestamp;
}
|
zcsahok/tlf
|
src/searchcallarray.c
|
C
|
gpl-2.0
| 3,698 |
//$Id:$ -*- C++ -*-
/*
* DirectReader.cpp - Reader from independent files
*
* Copyright (c) 2001-2014 Ogapee. All rights reserved.
*
* [email protected]
*
* 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 "DirectReader.h"
#include <bzlib.h>
#if !defined(WIN32) && !defined(MACOS9) && !defined(PSP) && !defined(__OS2__)
#include <dirent.h>
#endif
#define IS_TWO_BYTE(x) \
( ((x) & 0xe0) == 0xe0 || ((x) & 0xe0) == 0x80 )
extern unsigned short convSJIS2UTF16( unsigned short in );
extern int convUTF16ToUTF8( unsigned char dst[4], unsigned short src );
#ifndef SEEK_END
#define SEEK_END 2
#endif
#define READ_LENGTH 4096
#define WRITE_LENGTH 5000
#define EI 8
#define EJ 4
#define P 1 /* If match length <= P then output one character */
#define N (1 << EI) /* buffer size */
#define F ((1 << EJ) + P) /* lookahead buffer size */
DirectReader::DirectReader( const char *path, const unsigned char *key_table )
{
file_full_path = NULL;
file_sub_path = NULL;
file_path_len = 0;
capital_name = new char[MAX_FILE_NAME_LENGTH*2+1];
capital_name_tmp = new char[MAX_FILE_NAME_LENGTH*3+1];
if ( path ){
archive_path = new char[ strlen(path) + 1 ];
memcpy( archive_path, path, strlen(path) + 1 );
}
else{
archive_path = new char[1];
archive_path[0] = 0;
}
int i;
if (key_table){
key_table_flag = true;
for (i=0 ; i<256 ; i++) this->key_table[i] = key_table[i];
}
else{
key_table_flag = false;
for (i=0 ; i<256 ; i++) this->key_table[i] = i;
}
read_buf = new unsigned char[READ_LENGTH];
decomp_buffer = new unsigned char[N*2];
decomp_buffer_len = N*2;
last_registered_compression_type = &root_registered_compression_type;
registerCompressionType( "NBZ", NBZ_COMPRESSION );
registerCompressionType( "SPB", SPB_COMPRESSION );
registerCompressionType( "JPG", NO_COMPRESSION );
registerCompressionType( "GIF", NO_COMPRESSION );
}
DirectReader::~DirectReader()
{
if (file_full_path) delete[] file_full_path;
if (file_sub_path) delete[] file_sub_path;
delete[] capital_name;
delete[] capital_name_tmp;
delete[] read_buf;
delete[] decomp_buffer;
last_registered_compression_type = root_registered_compression_type.next;
while ( last_registered_compression_type ){
RegisteredCompressionType *cur = last_registered_compression_type;
last_registered_compression_type = last_registered_compression_type->next;
delete cur;
}
}
FILE *DirectReader::fopen(const char *path, const char *mode)
{
size_t len = strlen(archive_path) + strlen(path) + 1;
if (file_path_len < len){
file_path_len = len;
if (file_full_path) delete[] file_full_path;
file_full_path = new char[file_path_len];
if (file_sub_path) delete[] file_sub_path;
file_sub_path = new char[file_path_len];
}
sprintf( file_full_path, "%s%s", archive_path, path );
FILE *fp = ::fopen( file_full_path, mode );
if (fp) return fp;
#if !defined(WIN32) && !defined(MACOS9) && !defined(PSP) && !defined(__OS2__)
char *cur_p = NULL;
DIR *dp = NULL;
len = strlen(archive_path);
if (len > 0) dp = opendir(archive_path);
else dp = opendir(".");
cur_p = file_full_path+len;
while(1){
if (dp == NULL) return NULL;
char *delim_p = NULL;
while(1){
delim_p = strchr( cur_p, (char)DELIMITER );
if (delim_p != cur_p) break;
cur_p++;
}
if (delim_p) len = delim_p - cur_p;
else len = strlen(cur_p);
memcpy(file_sub_path, cur_p, len);
file_sub_path[len] = '\0';
struct dirent *entp;
while ( (entp = readdir(dp)) != NULL ){
if ( !strcasecmp( file_sub_path, entp->d_name ) ){
memcpy(cur_p, entp->d_name, len);
break;
}
}
closedir( dp );
if (entp == NULL) return NULL;
if (delim_p == NULL) break;
memcpy(file_sub_path, file_full_path, delim_p-file_full_path);
file_sub_path[delim_p-file_full_path]='\0';
dp = opendir(file_sub_path);
cur_p = delim_p+1;
}
fp = ::fopen( file_full_path, mode );
#endif
return fp;
}
unsigned char DirectReader::readChar( FILE *fp )
{
unsigned char ret;
fread( &ret, 1, 1, fp );
return key_table[ret];
}
unsigned short DirectReader::readShort( FILE *fp )
{
unsigned short ret;
unsigned char buf[2];
fread( &buf, 1, 2, fp );
ret = key_table[buf[0]] << 8 | key_table[buf[1]];
return ret;
}
unsigned long DirectReader::readLong( FILE *fp )
{
unsigned long ret;
unsigned char buf[4];
fread( &buf, 1, 4, fp );
ret = key_table[buf[0]];
ret = ret << 8 | key_table[buf[1]];
ret = ret << 8 | key_table[buf[2]];
ret = ret << 8 | key_table[buf[3]];
return ret;
}
void DirectReader::writeChar( FILE *fp, unsigned char ch )
{
fwrite( &ch, 1, 1, fp );
}
void DirectReader::writeShort( FILE *fp, unsigned short ch )
{
unsigned char buf[2];
buf[0] = (ch>>8) & 0xff;
buf[1] = ch & 0xff;
fwrite( &buf, 1, 2, fp );
}
void DirectReader::writeLong( FILE *fp, unsigned long ch )
{
unsigned char buf[4];
buf[0] = (unsigned char)((ch>>24) & 0xff);
buf[1] = (unsigned char)((ch>>16) & 0xff);
buf[2] = (unsigned char)((ch>>8) & 0xff);
buf[3] = (unsigned char)(ch & 0xff);
fwrite( &buf, 1, 4, fp );
}
unsigned short DirectReader::swapShort( unsigned short ch )
{
return ((ch & 0xff00) >> 8) | ((ch & 0x00ff) << 8);
}
unsigned long DirectReader::swapLong( unsigned long ch )
{
return ((ch & 0xff000000) >> 24) | ((ch & 0x00ff0000) >> 8 ) |
((ch & 0x0000ff00) << 8) | ((ch & 0x000000ff) << 24);
}
int DirectReader::open( const char *name )
{
return 0;
}
int DirectReader::close()
{
return 0;
}
const char *DirectReader::getArchiveName() const
{
return "direct";
}
int DirectReader::getNumFiles()
{
return 0;
}
void DirectReader::registerCompressionType( const char *ext, int type )
{
last_registered_compression_type->next = new RegisteredCompressionType(ext, type);
last_registered_compression_type = last_registered_compression_type->next;
}
int DirectReader::getRegisteredCompressionType( const char *file_name )
{
const char *ext_buf = file_name + strlen(file_name);
while( *ext_buf != '.' && ext_buf != file_name ) ext_buf--;
ext_buf++;
strcpy( capital_name, ext_buf );
for ( unsigned int i=0 ; i<strlen(ext_buf)+1 ; i++ )
if ( capital_name[i] >= 'a' && capital_name[i] <= 'z' )
capital_name[i] += 'A' - 'a';
RegisteredCompressionType *reg = root_registered_compression_type.next;
while (reg){
if ( !strcmp( capital_name, reg->ext ) ) return reg->type;
reg = reg->next;
}
return NO_COMPRESSION;
}
struct DirectReader::FileInfo DirectReader::getFileByIndex( unsigned int index )
{
DirectReader::FileInfo fi;
return fi;
}
FILE *DirectReader::getFileHandle( const char *file_name, int &compression_type, size_t *length )
{
FILE *fp;
unsigned int i;
compression_type = NO_COMPRESSION;
size_t len = strlen( file_name );
if ( len > MAX_FILE_NAME_LENGTH ) len = MAX_FILE_NAME_LENGTH;
memcpy( capital_name, file_name, len );
capital_name[ len ] = '\0';
for ( i=0 ; i<len ; i++ ){
if ( capital_name[i] == '/' || capital_name[i] == '\\' ) capital_name[i] = (char)DELIMITER;
if ( (unsigned char)capital_name[i] > 0x80 ) i++;
}
#if defined(UTF8_FILESYSTEM)
convertFromSJISToUTF8(capital_name_tmp, capital_name);
strcpy(capital_name, capital_name_tmp);
len = strlen(capital_name);
#elif defined(LINUX)
convertFromSJISToEUC(capital_name);
#endif
*length = 0;
if ( (fp = fopen( capital_name, "rb" )) != NULL && len >= 3 ){
compression_type = getRegisteredCompressionType( capital_name );
if ( compression_type == NBZ_COMPRESSION || compression_type == SPB_COMPRESSION ){
*length = getDecompressedFileLength( compression_type, fp, 0 );
}
else{
fseek( fp, 0, SEEK_END );
*length = ftell( fp );
}
}
return fp;
}
size_t DirectReader::getFileLength( const char *file_name )
{
int compression_type;
size_t len;
FILE *fp = getFileHandle( file_name, compression_type, &len );
if ( fp ) fclose( fp );
return len;
}
size_t DirectReader::getFile( const char *file_name, unsigned char *buffer, int *location )
{
int compression_type;
size_t len, c, total = 0;
FILE *fp = getFileHandle( file_name, compression_type, &len );
if ( fp ){
if ( compression_type & NBZ_COMPRESSION ) return decodeNBZ( fp, 0, buffer );
else if ( compression_type & SPB_COMPRESSION ) return decodeSPB( fp, 0, buffer );
fseek( fp, 0, SEEK_SET );
total = len;
while( len > 0 ){
if ( len > READ_LENGTH ) c = READ_LENGTH;
else c = len;
len -= c;
fread( buffer, 1, c, fp );
buffer += c;
}
fclose( fp );
if ( location ) *location = ARCHIVE_TYPE_NONE;
}
return total;
}
void DirectReader::convertFromSJISToEUC( char *buf )
{
int i = 0;
while ( buf[i] ) {
if ( (unsigned char)buf[i] > 0x80 ) {
unsigned char c1, c2;
c1 = buf[i];
c2 = buf[i+1];
c1 -= (c1 <= 0x9f) ? 0x71 : 0xb1;
c1 = c1 * 2 + 1;
if (c2 > 0x9e) {
c2 -= 0x7e;
c1++;
}
else if (c2 >= 0x80) {
c2 -= 0x20;
}
else {
c2 -= 0x1f;
}
buf[i] = c1 | 0x80;
buf[i+1] = c2 | 0x80;
i++;
}
i++;
}
}
void DirectReader::convertFromSJISToUTF8( char *dst_buf, const char *src_buf )
{
int i, c;
unsigned short unicode;
unsigned char utf8_buf[4];
while(*src_buf){
if (IS_TWO_BYTE(*src_buf)){
unsigned short index = *(unsigned char*)src_buf++;
index = index << 8 | (*(unsigned char*)src_buf++);
unicode = convSJIS2UTF16( index );
c = convUTF16ToUTF8(utf8_buf, unicode);
for (i=0 ; i<c ; i++)
*dst_buf++ = utf8_buf[i];
}
else{
*dst_buf++ = *src_buf++;
}
}
*dst_buf++ = 0;
}
size_t DirectReader::decodeNBZ( FILE *fp, size_t offset, unsigned char *buf )
{
if (key_table_flag)
fprintf(stderr, "may not decode NBZ with key_table enabled.\n");
unsigned int original_length, count;
BZFILE *bfp;
void *unused;
int err, len, nunused;
fseek( fp, offset, SEEK_SET );
original_length = count = readLong( fp );
bfp = BZ2_bzReadOpen( &err, fp, 0, 0, NULL, 0 );
if ( bfp == NULL || err != BZ_OK ) return 0;
while( err == BZ_OK && count > 0 ){
if ( count >= READ_LENGTH )
len = BZ2_bzRead( &err, bfp, buf, READ_LENGTH );
else
len = BZ2_bzRead( &err, bfp, buf, count );
count -= len;
buf += len;
}
BZ2_bzReadGetUnused(&err, bfp, &unused, &nunused );
BZ2_bzReadClose( &err, bfp );
return original_length - count;
}
size_t DirectReader::encodeNBZ( FILE *fp, size_t length, unsigned char *buf )
{
unsigned int bytes_in, bytes_out;
int err;
BZFILE *bfp = BZ2_bzWriteOpen( &err, fp, 9, 0, 30 );
if ( bfp == NULL || err != BZ_OK ) return 0;
while( err == BZ_OK && length > 0 ){
if ( length >= WRITE_LENGTH ){
BZ2_bzWrite( &err, bfp, buf, WRITE_LENGTH );
buf += WRITE_LENGTH;
length -= WRITE_LENGTH;
}
else{
BZ2_bzWrite( &err, bfp, buf, length );
break;
}
}
BZ2_bzWriteClose( &err, bfp, 0, &bytes_in, &bytes_out );
return bytes_out;
}
int DirectReader::getbit( FILE *fp, int n )
{
int i, x = 0;
static int getbit_buf;
for ( i=0 ; i<n ; i++ ){
if ( getbit_mask == 0 ){
if (getbit_len == getbit_count){
getbit_len = fread(read_buf, 1, READ_LENGTH, fp);
if (getbit_len == 0) return EOF;
getbit_count = 0;
}
getbit_buf = key_table[read_buf[getbit_count++]];
getbit_mask = 128;
}
x <<= 1;
if ( getbit_buf & getbit_mask ) x++;
getbit_mask >>= 1;
}
return x;
}
size_t DirectReader::decodeSPB( FILE *fp, size_t offset, unsigned char *buf )
{
unsigned int count;
unsigned char *pbuf, *psbuf;
size_t i, j, k;
int c, n, m;
getbit_mask = 0;
getbit_len = getbit_count = 0;
fseek( fp, offset, SEEK_SET );
size_t width = readShort( fp );
size_t height = readShort( fp );
size_t width_pad = (4 - width * 3 % 4) % 4;
size_t total_size = (width * 3 + width_pad) * height + 54;
/* ---------------------------------------- */
/* Write header */
memset( buf, 0, 54 );
buf[0] = 'B'; buf[1] = 'M';
buf[2] = total_size & 0xff;
buf[3] = (total_size >> 8) & 0xff;
buf[4] = (total_size >> 16) & 0xff;
buf[5] = (total_size >> 24) & 0xff;
buf[10] = 54; // offset to the body
buf[14] = 40; // header size
buf[18] = width & 0xff;
buf[19] = (width >> 8) & 0xff;
buf[22] = height & 0xff;
buf[23] = (height >> 8) & 0xff;
buf[26] = 1; // the number of the plane
buf[28] = 24; // bpp
buf[34] = total_size - 54; // size of the body
buf += 54;
if (decomp_buffer_len < width*height+4){
if (decomp_buffer) delete[] decomp_buffer;
decomp_buffer_len = width*height+4;
decomp_buffer = new unsigned char[decomp_buffer_len];
}
for ( i=0 ; i<3 ; i++ ){
count = 0;
decomp_buffer[count++] = c = getbit( fp, 8 );
while ( count < (unsigned)(width * height) ){
n = getbit( fp, 3 );
if ( n == 0 ){
decomp_buffer[count++] = c;
decomp_buffer[count++] = c;
decomp_buffer[count++] = c;
decomp_buffer[count++] = c;
continue;
}
else if ( n == 7 ){
m = getbit( fp, 1 ) + 1;
}
else{
m = n + 2;
}
for ( j=0 ; j<4 ; j++ ){
if ( m == 8 ){
c = getbit( fp, 8 );
}
else{
k = getbit( fp, m );
if ( k & 1 ) c += (k>>1) + 1;
else c -= (k>>1);
}
decomp_buffer[count++] = c;
}
}
pbuf = buf + (width * 3 + width_pad)*(height-1) + i;
psbuf = decomp_buffer;
for ( j=0 ; j<height ; j++ ){
if ( j & 1 ){
for ( k=0 ; k<width ; k++, pbuf -= 3 ) *pbuf = *psbuf++;
pbuf -= width * 3 + width_pad - 3;
}
else{
for ( k=0 ; k<width ; k++, pbuf += 3 ) *pbuf = *psbuf++;
pbuf -= width * 3 + width_pad + 3;
}
}
}
return total_size;
}
size_t DirectReader::decodeLZSS( struct ArchiveInfo *ai, int no, unsigned char *buf )
{
unsigned int count = 0;
int i, j, k, r, c;
getbit_mask = 0;
getbit_len = getbit_count = 0;
fseek( ai->file_handle, ai->fi_list[no].offset, SEEK_SET );
memset( decomp_buffer, 0, N-F );
r = N - F;
while ( count < ai->fi_list[no].original_length ){
if ( getbit( ai->file_handle, 1 ) ) {
if ((c = getbit( ai->file_handle, 8 )) == EOF) break;
buf[ count++ ] = c;
decomp_buffer[r++] = c; r &= (N - 1);
} else {
if ((i = getbit( ai->file_handle, EI )) == EOF) break;
if ((j = getbit( ai->file_handle, EJ )) == EOF) break;
for (k = 0; k <= j + 1 ; k++) {
c = decomp_buffer[(i + k) & (N - 1)];
buf[ count++ ] = c;
decomp_buffer[r++] = c; r &= (N - 1);
}
}
}
return count;
}
size_t DirectReader::getDecompressedFileLength( int type, FILE *fp, size_t offset )
{
size_t length=0;
fseek( fp, offset, SEEK_SET );
if ( type == NBZ_COMPRESSION ){
length = readLong( fp );
}
else if ( type == SPB_COMPRESSION ){
size_t width = readShort( fp );
size_t height = readShort( fp );
size_t width_pad = (4 - width * 3 % 4) % 4;
length = (width * 3 +width_pad) * height + 54;
}
return length;
}
|
ljkgpxs/onscripter-GBK-2015
|
DirectReader.cpp
|
C++
|
gpl-2.0
| 17,639 |
static const uint32_t to_ucs4[256] = {
[0x01] = 0x0001,
[0x02] = 0x0002,
[0x03] = 0x0003,
[0x04] = 0x0004,
[0x05] = 0x0005,
[0x06] = 0x0006,
[0x07] = 0x0007,
[0x08] = 0x0008,
[0x09] = 0x0009,
[0x0a] = 0x000A,
[0x0b] = 0x000B,
[0x0c] = 0x000C,
[0x0d] = 0x000D,
[0x0e] = 0x000E,
[0x0f] = 0x000F,
[0x10] = 0x0010,
[0x11] = 0x0011,
[0x12] = 0x0012,
[0x13] = 0x0013,
[0x14] = 0x0014,
[0x15] = 0x0015,
[0x16] = 0x0016,
[0x17] = 0x0017,
[0x18] = 0x0018,
[0x19] = 0x0019,
[0x1a] = 0x001A,
[0x1b] = 0x001B,
[0x1c] = 0x001C,
[0x1d] = 0x001D,
[0x1e] = 0x001E,
[0x1f] = 0x001F,
[0x20] = 0x0020,
[0x21] = 0x0021,
[0x22] = 0x0022,
[0x23] = 0x0023,
[0x24] = 0x0024,
[0x25] = 0x0025,
[0x26] = 0x0026,
[0x27] = 0x0027,
[0x28] = 0x0028,
[0x29] = 0x0029,
[0x2a] = 0x002A,
[0x2b] = 0x002B,
[0x2c] = 0x002C,
[0x2d] = 0x002D,
[0x2e] = 0x002E,
[0x2f] = 0x002F,
[0x30] = 0x0030,
[0x31] = 0x0031,
[0x32] = 0x0032,
[0x33] = 0x0033,
[0x34] = 0x0034,
[0x35] = 0x0035,
[0x36] = 0x0036,
[0x37] = 0x0037,
[0x38] = 0x0038,
[0x39] = 0x0039,
[0x3a] = 0x003A,
[0x3b] = 0x003B,
[0x3c] = 0x003C,
[0x3d] = 0x003D,
[0x3e] = 0x003E,
[0x3f] = 0x003F,
[0x40] = 0x0040,
[0x41] = 0x0041,
[0x42] = 0x0042,
[0x43] = 0x0043,
[0x44] = 0x0044,
[0x45] = 0x0045,
[0x46] = 0x0046,
[0x47] = 0x0047,
[0x48] = 0x0048,
[0x49] = 0x0049,
[0x4a] = 0x004A,
[0x4b] = 0x004B,
[0x4c] = 0x004C,
[0x4d] = 0x004D,
[0x4e] = 0x004E,
[0x4f] = 0x004F,
[0x50] = 0x0050,
[0x51] = 0x0051,
[0x52] = 0x0052,
[0x53] = 0x0053,
[0x54] = 0x0054,
[0x55] = 0x0055,
[0x56] = 0x0056,
[0x57] = 0x0057,
[0x58] = 0x0058,
[0x59] = 0x0059,
[0x5a] = 0x005A,
[0x5b] = 0x005B,
[0x5c] = 0x005C,
[0x5d] = 0x005D,
[0x5e] = 0x005E,
[0x5f] = 0x005F,
[0x60] = 0x0060,
[0x61] = 0x0061,
[0x62] = 0x0062,
[0x63] = 0x0063,
[0x64] = 0x0064,
[0x65] = 0x0065,
[0x66] = 0x0066,
[0x67] = 0x0067,
[0x68] = 0x0068,
[0x69] = 0x0069,
[0x6a] = 0x006A,
[0x6b] = 0x006B,
[0x6c] = 0x006C,
[0x6d] = 0x006D,
[0x6e] = 0x006E,
[0x6f] = 0x006F,
[0x70] = 0x0070,
[0x71] = 0x0071,
[0x72] = 0x0072,
[0x73] = 0x0073,
[0x74] = 0x0074,
[0x75] = 0x0075,
[0x76] = 0x0076,
[0x77] = 0x0077,
[0x78] = 0x0078,
[0x79] = 0x0079,
[0x7a] = 0x007A,
[0x7b] = 0x007B,
[0x7c] = 0x007C,
[0x7d] = 0x007D,
[0x7e] = 0x007E,
[0x7f] = 0x007F,
[0x80] = 0x0410,
[0x81] = 0x0411,
[0x82] = 0x0412,
[0x83] = 0x0413,
[0x84] = 0x0414,
[0x85] = 0x0415,
[0x86] = 0x0416,
[0x87] = 0x0417,
[0x88] = 0x0418,
[0x89] = 0x0419,
[0x8a] = 0x041A,
[0x8b] = 0x041B,
[0x8c] = 0x041C,
[0x8d] = 0x041D,
[0x8e] = 0x041E,
[0x8f] = 0x041F,
[0x90] = 0x0420,
[0x91] = 0x0421,
[0x92] = 0x0422,
[0x93] = 0x0423,
[0x94] = 0x0424,
[0x95] = 0x0425,
[0x96] = 0x0426,
[0x97] = 0x0427,
[0x98] = 0x0428,
[0x99] = 0x0429,
[0x9a] = 0x042A,
[0x9b] = 0x042B,
[0x9c] = 0x042C,
[0x9d] = 0x042D,
[0x9e] = 0x042E,
[0x9f] = 0x042F,
[0xa0] = 0x0430,
[0xa1] = 0x0431,
[0xa2] = 0x0432,
[0xa3] = 0x0433,
[0xa4] = 0x0434,
[0xa5] = 0x0435,
[0xa6] = 0x0436,
[0xa7] = 0x0437,
[0xa8] = 0x0438,
[0xa9] = 0x0439,
[0xaa] = 0x043A,
[0xab] = 0x043B,
[0xac] = 0x043C,
[0xad] = 0x043D,
[0xae] = 0x043E,
[0xaf] = 0x043F,
[0xb0] = 0x2591,
[0xb1] = 0x2592,
[0xb2] = 0x2593,
[0xb3] = 0x2502,
[0xb4] = 0x2524,
[0xb5] = 0x2561,
[0xb6] = 0x2562,
[0xb7] = 0x2556,
[0xb8] = 0x2555,
[0xb9] = 0x2563,
[0xba] = 0x2551,
[0xbb] = 0x2557,
[0xbc] = 0x255D,
[0xbd] = 0x255C,
[0xbe] = 0x255B,
[0xbf] = 0x2510,
[0xc0] = 0x2514,
[0xc1] = 0x2534,
[0xc2] = 0x252C,
[0xc3] = 0x251C,
[0xc4] = 0x2500,
[0xc5] = 0x253C,
[0xc6] = 0x255E,
[0xc7] = 0x255F,
[0xc8] = 0x255A,
[0xc9] = 0x2554,
[0xca] = 0x2569,
[0xcb] = 0x2566,
[0xcc] = 0x2560,
[0xcd] = 0x2550,
[0xce] = 0x256C,
[0xcf] = 0x2567,
[0xd0] = 0x2568,
[0xd1] = 0x2564,
[0xd2] = 0x2565,
[0xd3] = 0x2559,
[0xd4] = 0x2558,
[0xd5] = 0x2552,
[0xd6] = 0x2553,
[0xd7] = 0x256B,
[0xd8] = 0x256A,
[0xd9] = 0x2518,
[0xda] = 0x250C,
[0xdb] = 0x2588,
[0xdc] = 0x2584,
[0xdd] = 0x258C,
[0xde] = 0x2590,
[0xdf] = 0x2580,
[0xe0] = 0x0440,
[0xe1] = 0x0441,
[0xe2] = 0x0442,
[0xe3] = 0x0443,
[0xe4] = 0x0444,
[0xe5] = 0x0445,
[0xe6] = 0x0446,
[0xe7] = 0x0447,
[0xe8] = 0x0448,
[0xe9] = 0x0449,
[0xea] = 0x044A,
[0xeb] = 0x044B,
[0xec] = 0x044C,
[0xed] = 0x044D,
[0xee] = 0x044E,
[0xef] = 0x044F,
[0xf0] = 0x0401,
[0xf1] = 0x0451,
[0xf2] = 0x0404,
[0xf3] = 0x0454,
[0xf4] = 0x0407,
[0xf5] = 0x0457,
[0xf6] = 0x040E,
[0xf7] = 0x045E,
[0xf8] = 0x00B0,
[0xf9] = 0x2219,
[0xfa] = 0x00B7,
[0xfb] = 0x221A,
[0xfc] = 0x2116,
[0xfd] = 0x00A4,
[0xfe] = 0x25A0,
[0xff] = 0x00A0,
};
static const struct gap from_idx[] = {
{ .start = 0x0000, .end = 0x007f, .idx = 0 },
{ .start = 0x00a0, .end = 0x00a4, .idx = -32 },
{ .start = 0x00b0, .end = 0x00b0, .idx = -43 },
{ .start = 0x00b7, .end = 0x00b7, .idx = -49 },
{ .start = 0x0401, .end = 0x0407, .idx = -890 },
{ .start = 0x040e, .end = 0x0457, .idx = -896 },
{ .start = 0x045e, .end = 0x045e, .idx = -902 },
{ .start = 0x2116, .end = 0x2116, .idx = -8253 },
{ .start = 0x2219, .end = 0x221a, .idx = -8511 },
{ .start = 0x2500, .end = 0x2502, .idx = -9252 },
{ .start = 0x250c, .end = 0x251c, .idx = -9261 },
{ .start = 0x2524, .end = 0x2524, .idx = -9268 },
{ .start = 0x252c, .end = 0x252c, .idx = -9275 },
{ .start = 0x2534, .end = 0x2534, .idx = -9282 },
{ .start = 0x253c, .end = 0x253c, .idx = -9289 },
{ .start = 0x2550, .end = 0x256c, .idx = -9308 },
{ .start = 0x2580, .end = 0x2593, .idx = -9327 },
{ .start = 0x25a0, .end = 0x25a0, .idx = -9339 },
{ .start = 0xffff, .end = 0xffff, .idx = 0 }
};
static const char from_ucs4[] = {
'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
'\x08', '\x09', '\x0a', '\x0b', '\x0c', '\x0d', '\x0e', '\x0f',
'\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17',
'\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
'\x20', '\x21', '\x22', '\x23', '\x24', '\x25', '\x26', '\x27',
'\x28', '\x29', '\x2a', '\x2b', '\x2c', '\x2d', '\x2e', '\x2f',
'\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
'\x38', '\x39', '\x3a', '\x3b', '\x3c', '\x3d', '\x3e', '\x3f',
'\x40', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47',
'\x48', '\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f',
'\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57',
'\x58', '\x59', '\x5a', '\x5b', '\x5c', '\x5d', '\x5e', '\x5f',
'\x60', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67',
'\x68', '\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f',
'\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77',
'\x78', '\x79', '\x7a', '\x7b', '\x7c', '\x7d', '\x7e', '\x7f',
'\xff', '\x00', '\x00', '\x00', '\xfd', '\xf8', '\xfa', '\xf0',
'\x00', '\x00', '\xf2', '\x00', '\x00', '\xf4', '\xf6', '\x00',
'\x80', '\x81', '\x82', '\x83', '\x84', '\x85', '\x86', '\x87',
'\x88', '\x89', '\x8a', '\x8b', '\x8c', '\x8d', '\x8e', '\x8f',
'\x90', '\x91', '\x92', '\x93', '\x94', '\x95', '\x96', '\x97',
'\x98', '\x99', '\x9a', '\x9b', '\x9c', '\x9d', '\x9e', '\x9f',
'\xa0', '\xa1', '\xa2', '\xa3', '\xa4', '\xa5', '\xa6', '\xa7',
'\xa8', '\xa9', '\xaa', '\xab', '\xac', '\xad', '\xae', '\xaf',
'\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7',
'\xe8', '\xe9', '\xea', '\xeb', '\xec', '\xed', '\xee', '\xef',
'\x00', '\xf1', '\x00', '\x00', '\xf3', '\x00', '\x00', '\xf5',
'\xf7', '\xfc', '\xf9', '\xfb', '\xc4', '\x00', '\xb3', '\xda',
'\x00', '\x00', '\x00', '\xbf', '\x00', '\x00', '\x00', '\xc0',
'\x00', '\x00', '\x00', '\xd9', '\x00', '\x00', '\x00', '\xc3',
'\xb4', '\xc2', '\xc1', '\xc5', '\xcd', '\xba', '\xd5', '\xd6',
'\xc9', '\xb8', '\xb7', '\xbb', '\xd4', '\xd3', '\xc8', '\xbe',
'\xbd', '\xbc', '\xc6', '\xc7', '\xcc', '\xb5', '\xb6', '\xb9',
'\xd1', '\xd2', '\xcb', '\xcf', '\xd0', '\xca', '\xd8', '\xd7',
'\xce', '\xdf', '\x00', '\x00', '\x00', '\xdc', '\x00', '\x00',
'\x00', '\xdb', '\x00', '\x00', '\x00', '\xdd', '\x00', '\x00',
'\x00', '\xde', '\xb0', '\xb1', '\xb2', '\xfe',
};
|
jzeng4/pemu
|
plugins/glibc-2.13-new-build/iconvdata/ibm866.h
|
C
|
gpl-2.0
| 8,380 |
/*
* HT Editor
* htpe.h
*
* Copyright (C) 1999-2002 Stefan Weyergraf
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __HTPE_H__
#define __HTPE_H__
#include "formats.h"
#include "pestruct.h"
#include "htpeexp.h"
#include "htpeil.h"
#include "htpeimp.h"
#include "htpedimp.h"
#define DESC_PE "pe - win32 portable exe"
#define DESC_PE_HEADER "pe/header"
#define DESC_PE_IMPORTS "pe/imports"
#define DESC_PE_DIMPORTS "pe/delay-imports"
#define DESC_PE_EXPORTS "pe/exports"
#define DESC_PE_RESOURCES "pe/resources"
#define DESC_PE_IMAGE "pe/image"
#define DESC_PE_IL "pe/il"
#define ATOM_PE_MACHINES 0x50450000
#define ATOM_PE_MACHINES_STR "50450000"
#define ATOM_PE_OPTIONAL_MAGICS 0x50450001
#define ATOM_PE_OPTIONAL_MAGICS_STR "50450001"
#define ATOM_PE_SUBSYSTEMS 0x50450002
#define ATOM_PE_SUBSYSTEMS_STR "50450002"
#define ATOM_PE_CHARACTERISTICS 0x50450003
#define ATOM_PE_CHARACTERISTICS_STR "50450003"
#define ATOM_PE_DLL_CHARACTERISTICS 0x50450004
#define ATOM_PE_DLL_CHARACTERISTICS_STR "50450004"
#define ATOM_PE_SECTION_CHARACTERISTICS 0x50450005
#define ATOM_PE_SECTION_CHARACTERISTICS_STR "50450005"
extern format_viewer_if htpe_if;
struct pe_section_headers {
uint section_count;
COFF_SECTION_HEADER *sections;
};
struct ht_pe_shared_data {
FileOfs header_ofs;
COFF_HEADER coffheader;
uint16 opt_magic;
union {
struct {
COFF_OPTIONAL_HEADER32 header;
PE_OPTIONAL_HEADER32_NT header_nt;
} pe32;
struct {
COFF_OPTIONAL_HEADER64 header;
PE_OPTIONAL_HEADER64_NT header_nt;
} pe64;
};
pe_section_headers sections;
ht_pe_il *il;
ht_pe_export exports;
ht_pe_import imports;
ht_pe_import dimports;
ht_format_viewer *v_header;
ht_view *v_exports;
ht_view *v_imports;
ht_view *v_dimports;
ht_view *v_resources;
ht_view *v_il;
ht_format_viewer *v_image;
};
/*
* CLASS ht_pe
*/
class ht_pe: public ht_format_group {
protected:
bool loc_enum;
public:
void init(Bounds *b, File *file, format_viewer_if **ifs, ht_format_group *format_group, FileOfs header_ofs);
virtual void done();
/* overwritten */
virtual void loc_enum_start();
virtual bool loc_enum_next(ht_format_loc *loc);
};
bool pe_rva_to_section(pe_section_headers *section_headers, RVA rva, int *section);
bool pe_rva_to_ofs(pe_section_headers *section_headers, RVA rva, FileOfs *ofs);
bool pe_rva_is_valid(pe_section_headers *section_headers, RVA rva);
bool pe_rva_is_physical(pe_section_headers *section_headers, RVA rva);
bool pe_ofs_to_rva(pe_section_headers *section_headers, FileOfs ofs, RVA *rva);
bool pe_ofs_to_section(pe_section_headers *section_headers, FileOfs ofs, int *section);
bool pe_ofs_to_rva_and_section(pe_section_headers *section_headers, FileOfs ofs, RVA *rva, int *section);
bool pe_section_name_to_section(pe_section_headers *section_headers, const char *name, int *section);
#endif /* !__HTPE_H__ */
|
tecknicaltom/HT-Editor
|
htpe.h
|
C
|
gpl-2.0
| 3,484 |
/* -*- mode: c; c-file-style: "gnu" -*-
* ccze-dump.c -- Dump internal color table
* Copyright (C) 2002, 2003 Gergely Nagy <[email protected]>
*
* This file is part of ccze.
*
* ccze 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.
*
* ccze 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
*/
#define CCZE_DUMP 1
#include <ccze.h>
#ifdef HAVE_ARGP_H
# include <argp.h>
#endif
#include "ccze-color.c"
#include "ccze-compat.h"
ccze_config_t ccze_config = {
.scroll = 1,
.convdate = 0,
.remfac = 0,
.wcol = 1,
.slookup = 1,
.rcfile = NULL,
.cssfile = NULL,
.transparent = 1,
.pluginlist_len = 0,
.pluginlist_alloc = 10,
.color_argv_len = 0,
.color_argv_alloc = 10,
.mode = CCZE_MODE_CURSES
};
const char *argp_program_name = "ccze-dump";
const char *argp_program_version = "ccze-dump (ccze 0.1." PATCHLEVEL ")";
const char *argp_program_bug_address = "<[email protected]>";
static struct argp_option options[] = {
{NULL, 0, NULL, 0, "", 1},
{"rcfile", 'F', "FILE", 0, "Read configuration from FILE", 1},
{"load", 'l', NULL, 0, "Load default configuration files", 1},
{NULL, 0, NULL, 0, NULL, 0}
};
static error_t parse_opt (int key, char *arg, struct argp_state *state);
static struct argp argp =
{options, parse_opt, 0, "ccze -- cheer up 'yer logs.", NULL, NULL, NULL};
static int ccze_loaddefs = 0;
static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
switch (key)
{
case 'F':
ccze_config.rcfile = arg;
break;
case 'l':
ccze_loaddefs = 1;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static char *
ccze_dump_color_get_attrib (int color)
{
char *str = (char *)ccze_calloc (100, sizeof (char));
if (color & A_BOLD)
strcat (str, "bold ");
if (color & A_UNDERLINE)
strcat (str, "underline ");
if (color & A_REVERSE)
strcat (str, "reverse ");
if (color & A_BLINK)
strcat (str, "blink ");
return str;
}
static char *
ccze_dump_color_to_name (int color)
{
int my_color = ccze_color_strip_attrib (color);
if (my_color < COLOR_PAIR (8))
return ccze_color_to_name_simple (my_color);
else
{
int i,j;
char *str, *cj, *ci;
j = (my_color >> 8) % 8;
i = (my_color >> 8) / 8;
cj = ccze_color_to_name_simple (COLOR_PAIR (j));
ci = ccze_color_to_name_simple (COLOR_PAIR (i));
asprintf (&str, "%s on_%s", cj, ci);
return str;
}
}
static char *
ccze_dump_color_comment (int cidx)
{
return ccze_color_keyword_map[cidx].comment;
}
static int
ccze_dump_color_hidden (int cidx)
{
return !ccze_color_keyword_map[cidx].settable;
}
static int
ccze_dump_color_to_idx (ccze_color_t color)
{
size_t cidx;
for (cidx = 0; cidx < sizeof (ccze_color_keyword_map); cidx++)
if (ccze_color_keyword_map[cidx].idx == color)
return cidx;
return 0;
}
int
main (int argc, char *argv[])
{
ccze_color_t cidx;
char line[256];
int color;
size_t llen;
argp_parse (&argp, argc, argv, 0, 0, NULL);
ccze_color_init ();
if (ccze_config.rcfile)
ccze_color_load (ccze_config.rcfile);
else if (ccze_loaddefs)
{
char *home, *homerc;
ccze_color_load (SYSCONFDIR "/colorizerc");
ccze_color_load (SYSCONFDIR "/cczerc");
home = getenv ("HOME");
if (home)
{
asprintf (&homerc, "%s/.colorizerc", home);
ccze_color_load (homerc);
free (homerc);
asprintf (&homerc, "%s/.cczerc", home);
ccze_color_load (homerc);
free (homerc);
}
}
printf ("# Configuration file for ccze\n#\n");
printf ("# Available 'pre' attributes: bold, underline, underscore, "
"blink, reverse\n");
printf ("# Available colors: black, red, green, yellow, blue, magenta, "
"cyan, white\n");
printf ("# Available bgcolors: on_black, on_red, on_green, on_yellow, "
"on_blue, on_magenta, on_cyan, on_white\n#\n");
printf ("# You can also use item names in color definition, like:\n#\n");
printf ("# default blue\n# date 'default'\n#\n");
printf ("# Here you defined default color to blue, and date color to "
"default value's color, so\n");
printf ("# your date color is blue. (You can only use predefined item "
"names!)\n\n");
printf ("# item color # comment (what is "
"color, or why it's that ;)\n\n");
/* Dump colors */
for (cidx = CCZE_COLOR_DATE; cidx < CCZE_COLOR_LAST; cidx++)
{
if (ccze_dump_color_hidden (cidx))
continue;
color = ccze_color (cidx);
strcpy (line, ccze_color_lookup_name (cidx));
llen = strlen (line);
memset (&line[llen], ' ', 16 - llen);
line[16]='\0';
strcat (line, ccze_dump_color_get_attrib (color));
strcat (line, ccze_dump_color_to_name (color));
llen = strlen (line);
memset (&line[llen], ' ', 42 - llen);
line[40]='#';
line[42]='\0';
strcat (line, ccze_dump_color_comment (ccze_dump_color_to_idx (cidx)));
printf ("%s\n", line);
}
/* CSS codes */
printf ("\n# CSS codes for the HTML output\n");
for (color = 0; color < 8; color++)
{
strcpy (line, "css");
strcat (line, ccze_colorname_map[color].name);
llen = strlen (line);
memset (&line[llen], ' ', 16 - llen);
line[16]='\0';
strcat (line, ccze_csscolor_normal_map[color]);
printf ("%s\n", line);
strcpy (line, "cssbold");
strcat (line, ccze_colorname_map[color].name);
llen = strlen (line);
memset (&line[llen], ' ', 16 - llen);
line[16]='\0';
strcat (line, ccze_csscolor_bold_map[color]);
printf ("%s\n", line);
}
strcpy (line, "cssbody");
llen = strlen (line);
memset (&line[llen], ' ', 16 - llen);
line[16]='\0';
strcat (line, ccze_cssbody_color ());
printf ("%s\n", line);
return 0;
}
|
awood/ccze
|
src/ccze-dump.c
|
C
|
gpl-2.0
| 6,457 |
/*
* AMLOGIC Audio/Video streaming port driver.
*
* 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 named License,
* or 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
*
* Author: Tim Yao <[email protected]>
*
*/
#ifndef VFRAME_H
#define VFRAME_H
#include <linux/types.h>
#ifdef CONFIG_ARCH_MESON6TV
#include <linux/tvin/tvin.h>
#else
#include <media/amlogic/656in.h>
#endif
#define VIDTYPE_PROGRESSIVE 0x0
#define VIDTYPE_INTERLACE_TOP 0x1
#define VIDTYPE_INTERLACE_BOTTOM 0x3
#define VIDTYPE_TYPEMASK 0x7
#define VIDTYPE_INTERLACE 0x1
#define VIDTYPE_INTERLACE_FIRST 0x8
#define VIDTYPE_MVC 0x10
#define VIDTYPE_NO_VIDEO_ENABLE 0x20
#define VIDTYPE_VIU_422 0x800
#define VIDTYPE_VIU_FIELD 0x1000
#define VIDTYPE_VIU_SINGLE_PLANE 0x2000
#define VIDTYPE_VIU_444 0x4000
#define VIDTYPE_VIU_NV21 0x8000
#define VIDTYPE_VSCALE_DISABLE 0x10000
#define VIDTYPE_CANVAS_TOGGLE 0x20000
#define VIDTYPE_PRE_INTERLACE 0x40000
#define VIDTYPE_HIGHRUN 0x80000
#define DISP_RATIO_FORCECONFIG 0x80000000
#define DISP_RATIO_FORCE_NORMALWIDE 0x40000000
#define DISP_RATIO_FORCE_FULL_STRETCH 0x20000000
#define DISP_RATIO_CTRL_MASK 0x00000003
#define DISP_RATIO_NO_KEEPRATIO 0x00000000
#define DISP_RATIO_KEEPRATIO 0x00000001
#define DISP_RATIO_PORTRAIT_MODE 0x00000004
#define DISP_RATIO_ASPECT_RATIO_MASK 0x0003ff00
#define DISP_RATIO_ASPECT_RATIO_BIT 8
#define DISP_RATIO_ASPECT_RATIO_MAX 0x3ff
typedef enum pixel_aspect_ratio_e {
PIXEL_ASPECT_RATIO_1_1,
PIXEL_ASPECT_RATIO_8_9,
PIXEL_ASPECT_RATIO_16_15,
} pixel_aspect_ratio_t;
/*
* If pixel_sum[21:0] == 0, then all Histogram information are invalid
*/
typedef struct vframe_hist_s
{
unsigned int luma_sum;
unsigned int chroma_sum;
unsigned int pixel_sum; // [31:30] POW [21:0] PIXEL_SUM
unsigned int height;
unsigned int width;
unsigned char luma_max;
unsigned char luma_min;
unsigned short gamma[64];
#ifdef AML_LOCAL_DIMMING
unsigned int ldim_max[100];
#endif
} vframe_hist_t;
/*
* If bottom == 0 or right == 0, then all Blackbar information are invalid
*/
typedef struct vframe_bbar_s
{
unsigned short top;
unsigned short bottom;
unsigned short left;
unsigned short right;
} vfame_bbar_t;
/*
* If vsin == 0, then all Measurement information are invalid
*/
typedef struct vframe_meas_s
{
//float frin; // Frame Rate of Video Input in the unit of Hz
unsigned int vs_span_cnt;
unsigned long long vs_cnt;
unsigned int hs_cnt0;
unsigned int hs_cnt1;
unsigned int hs_cnt2;
unsigned int hs_cnt3;
unsigned int vs_cycle;
unsigned int vs_stamp;
} vframe_meas_t;
typedef struct vframe_view_s {
int start_x;
int start_y;
unsigned int width;
unsigned int height;
} vframe_view_t;
/* vframe properties */
typedef struct vframe_prop_s
{
struct vframe_hist_s hist;
struct vframe_bbar_s bbar;
struct vframe_meas_s meas;
} vframe_prop_t;
typedef enum vframe_source_type_e {
VFRAME_SOURCE_TYPE_OTHERS = 0,
VFRAME_SOURCE_TYPE_TUNER,
VFRAME_SOURCE_TYPE_CVBS,
VFRAME_SOURCE_TYPE_COMP,
VFRAME_SOURCE_TYPE_PPMGR,
VFRAME_SOURCE_TYPE_OSD,
} vframe_source_type_t;
typedef enum vframe_source_mode_e {
VFRAME_SOURCE_MODE_OTHERS = 0,
VFRAME_SOURCE_MODE_PAL,
VFRAME_SOURCE_MODE_NTSC,
VFRAME_SOURCE_MODE_SECAM,
} vframe_source_mode_t;
typedef enum vframe_secam_phase_e {
VFRAME_PHASE_DB = 0,
VFRAME_PHASE_DR,
} vframe_secam_phase_t;
typedef struct vframe_s {
u32 index;
u32 type;
u32 type_backup;
u32 blend_mode;
u32 duration;
u32 duration_pulldown;
u32 pts;
u32 flag;
u32 canvas0Addr;
u32 canvas1Addr;
u32 bufWidth;
u32 width;
u32 height;
u32 ratio_control;
u32 orientation;
enum vframe_source_type_e source_type;
enum vframe_secam_phase_e phase;
enum vframe_source_mode_e source_mode;
tvin_sig_fmt_t sig_fmt;
#ifdef CONFIG_POST_PROCESS_MANAGER_3D_PROCESS
enum tvin_trans_fmt trans_fmt;
struct vframe_view_s left_eye;
struct vframe_view_s right_eye;
#endif
u32 mode_3d_enable ;
/* vframe extension */
int (*early_process_fun)(void* arg);
int (*process_fun)(void* arg, unsigned zoom_start_x_lines,
unsigned zoom_end_x_lines, unsigned zoom_start_y_lines, unsigned zoom_end_y_lines);
void* private_data;
#if 1
/* vframe properties */
struct vframe_prop_s prop;
#endif
struct list_head list;
struct tvafe_vga_parm_s vga_parm;
/* pixel aspect ratio */
enum pixel_aspect_ratio_e pixel_ratio;
} vframe_t;
#if 0
struct vframe_prop_s * vdin_get_vframe_prop(u32 index);
#endif
int get_curren_frame_para(int* top ,int* left , int* bottom, int* right);
u8 is_vpp_postblend(void);
#endif /* VFRAME_H */
|
wjb/mx-common
|
include/linux/amports/vframe.h
|
C
|
gpl-2.0
| 6,002 |
/*
//
// BEGIN SONGBIRD GPL
//
// This file is part of the Songbird web player.
//
// Copyright(c) 2005-2008 POTI, Inc.
// http://songbirdnest.com
//
// This file may be licensed under the terms of of the
// GNU General Public License Version 2 (the "GPL").
//
// Software distributed under the License is distributed
// on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
// express or implied. See the GPL for the specific language
// governing rights and limitations.
//
// You should have received a copy of the GPL along with this
// program. If not, go to http://www.gnu.org/licenses/gpl.html
// or write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// END SONGBIRD GPL
//
*/
/**
* \brief Test file
*/
var gComplete = 0;
function dbqCallback() {
}
dbqCallback.prototype = {
onQueryEnd: function(resultObject, dbGUID, query) {
assertEqual(resultObject.getRowCount(), 2);
gComplete++;
if(gComplete == 2)
testFinished();
}
};
dbqCallback.prototype.constructor = dbqCallback;
function runTest () {
var dbq = Cc["@songbirdnest.com/Songbird/DatabaseQuery;1"]
.createInstance(Ci.sbIDatabaseQuery);
var ios = Cc["@mozilla.org/network/io-service;1"]
.createInstance(Ci.nsIIOService);
var dir = Cc["@mozilla.org/file/directory_service;1"]
.createInstance(Ci.nsIProperties);
var testdir = dir.get("ProfD", Ci.nsIFile);
var actualdir = testdir.clone();
actualdir.append("db_tests");
if(!actualdir.exists())
{
try {
actualdir.create(Ci.nsIFile.DIRECTORY_TYPE, 0700);
} catch(e) {
//Some failures might be handled later. Some might be ignored.
throw e;
}
}
var uri = ios.newFileURI(actualdir);
dbq.databaseLocation = uri;
assertEqual(dbq.databaseLocation.spec, uri.spec);
dbq.setDatabaseGUID("test_sync");
dbq.addQuery("drop table proxy_test");
dbq.addQuery("create table proxy_test (name text, value text)");
dbq.addQuery("insert into proxy_test values ('test 0', 'testing... 0')");
dbq.addQuery("insert into proxy_test values ('test 1', 'testing... 1')");
dbq.execute();
dbq.waitForCompletion();
dbq.resetQuery();
dbq.addSimpleQueryCallback(new dbqCallback());
dbq.addSimpleQueryCallback(new dbqCallback());
dbq.addQuery("select * from proxy_test");
dbq.execute();
testPending();
return Components.results.NS_OK;
}
|
freaktechnik/nightingale-hacking
|
components/dbengine/test/test_proxy.js
|
JavaScript
|
gpl-2.0
| 2,488 |
<?php
#############################################################################
# IMDBPHP (c) Giorgos Giagas & Itzchak Rehberg #
# written by Giorgos Giagas #
# extended & maintained by Itzchak Rehberg <izzysoft AT qumran DOT org> #
# http://www.izzysoft.de/ #
# ------------------------------------------------------------------------- #
# This program is free software; you can redistribute and/or modify it #
# under the terms of the GNU General Public License (see doc/LICENSE) #
# ------------------------------------------------------------------------- #
# Show what we have in the Cache #
#############################################################################
# $Id: cache.php 253 2009-10-11 21:54:15Z izzy $
require_once("imdb.class.php");
$conf = new imdb_config;
echo "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>\n";
echo "<HTML><HEAD>\n <TITLE>IMDBPHP Cache Contents</TITLE>\n";
echo " <STYLE TYPE='text/css'>body,td,th { font-size:12px; }</STYLE>\n";
echo "</HEAD><BODY>\n";
$movie = new imdb ("0");
if ($d = opendir ($conf->cachedir)) {
echo "<TABLE ALIGN='center' BORDER='1' STYLE='border-collapse:collapse;margin-top:20px;'>\n"
. " <TR><TH STYLE='background-color:#ffb000'>Movie Details</TH><TH STYLE='background-color:#ffb000'>IMDB page</TH></TR>\n";
while (false !== ($entry = readdir ($d))) {
if (strstr ($entry, "Title")) {
$imdbid = substr ($entry, 0, 7);
$movie->setid ($imdbid);
echo " <TR><TD><a href='imdb.php?mid=${imdbid}'>".$movie->title()."</a></TD>"
. "<TD><a href=\"http://us.imdb.com/title/tt${imdbid}\">imdb page</a></TD></TR>\n";
}
}
echo "</TABLE>\n";
}
echo "</BODY></HTML>";
?>
|
Bigjoos/U-232
|
imdb/cache.php
|
PHP
|
gpl-2.0
| 1,939 |
/*
* Copyright (c) 1997-1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
_STLP_BEGIN_NAMESPACE
#define _STLP_NON_DBG_STRING_BASE _STLP_NON_DBG_NAME(str)<_CharT, _Traits, _Alloc>
template <class _CharT, class _Traits, class _Alloc>
class basic_string : private __construct_checker<_STLP_NON_DBG_STRING_BASE >
, public _STLP_NON_DBG_STRING_BASE
#if defined (_STLP_USE_PARTIAL_SPEC_WORKAROUND)
, public __stlport_class<basic_string<_CharT, _Traits, _Alloc> >
#endif
{
private:
typedef _STLP_NON_DBG_STRING_BASE _Base;
typedef basic_string<_CharT, _Traits, _Alloc> _Self;
typedef __construct_checker<_STLP_NON_DBG_STRING_BASE > _ConstructCheck;
typedef typename _Base::_DbgBase _DbgBase;
public:
__IMPORT_WITH_REVERSE_ITERATORS(_DbgBase)
typedef typename _DbgBase::_Iterator_category _Iterator_category;
typedef typename _DbgBase::traits_type traits_type;
typedef typename _DbgBase::_Reserve_t _Reserve_t;
public: // Constructor, destructor, assignment.
explicit basic_string(const allocator_type& __a = allocator_type()) :
_STLP_NON_DBG_STRING_BASE(__a) {}
basic_string(_Reserve_t __r, size_t __n,
const allocator_type& __a = allocator_type()) :
_STLP_NON_DBG_STRING_BASE(__r, __n, __a) {}
basic_string(const _Self& __s) :
_ConstructCheck(__s), _STLP_NON_DBG_STRING_BASE(__s) {}
basic_string(const _Self& __s, size_type __pos, size_type __n = _DbgBase::npos,
const allocator_type& __a = allocator_type()) :
_STLP_NON_DBG_STRING_BASE(__s, __pos, __n, __a) {}
basic_string(const _CharT* __s, size_type __n,
const allocator_type& __a = allocator_type()) :
_STLP_NON_DBG_STRING_BASE(__s, __n, __a) {}
basic_string(const _CharT* __s,
const allocator_type& __a = allocator_type()):
_STLP_NON_DBG_STRING_BASE(__s, __a) {}
basic_string(size_type __n, _CharT __c,
const allocator_type& __a = allocator_type()):
_STLP_NON_DBG_STRING_BASE(__n, __c, __a) {}
basic_string(__move_source<_Self> src):
_STLP_NON_DBG_STRING_BASE(__move_source<_Base>(src.get())) {}
#if !(defined(__MRC__)||defined(__SC__))
template <class _InputIterator>
basic_string(_InputIterator __f, _InputIterator __l,
const allocator_type & __a _STLP_ALLOCATOR_TYPE_DFL) :
_ConstructCheck(__f, __l),
_STLP_NON_DBG_STRING_BASE(__f, __l, __a) {
}
# ifdef _STLP_NEEDS_EXTRA_TEMPLATE_CONSTRUCTORS
template <class _InputIterator>
basic_string(_InputIterator __f, _InputIterator __l) :
_ConstructCheck(__f, __l),
_STLP_NON_DBG_STRING_BASE(__f, __l) {
}
# endif
#endif
// constructor from non-debug version
basic_string (const _Base& __x)
: _STLP_NON_DBG_STRING_BASE(__x) {}
_Self& operator=(const _Self& __s) {
_DbgBase::operator=(__s);
return *this;
}
_Self& operator=(const _CharT* __s) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::operator=(__s);
return *this;
}
_Self& operator=(_CharT __c) {
_DbgBase::operator=(__c);
return *this;
}
public: // Append, operator+=, push_back.
_Self& operator+=(const _Self& __s) {
_DbgBase::operator+=(__s);
return *this;
}
_Self& operator+=(const _CharT* __s) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::operator+=(__s);
return *this;
}
_Self& operator+=(_CharT __c) {
_DbgBase::operator+=(__c);
return *this;
}
_Self& append(const _Self& __s) {
_DbgBase::append(__s);
return *this;
}
_Self& append(const _Self& __s, size_type __pos, size_type __n) {
_DbgBase::append(__s, __pos, __n);
return *this;
}
_Self& append(const _CharT* __s, size_type __n) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::append(__s, __n);
return *this;
}
_Self& append(const _CharT* __s) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::append(__s);
return *this;
}
_Self& append(size_type __n, _CharT __c) {
_DbgBase::append(__n, __c);
return *this;
}
template <class _InputIter>
_Self& append(_InputIter __first, _InputIter __last) {
_STLP_DEBUG_CHECK(__check_range(__first, __last))
size_type __old_capacity = this->capacity();
_Base::append(__first, __last);
_Compare_Capacity(__old_capacity);
return *this;
}
#if !defined (_STLP_NO_METHOD_SPECIALIZATION) && !defined (_STLP_NO_EXTENSIONS)
_Self& append(const _CharT* __f, const _CharT* __l) {
_STLP_FIX_LITERAL_BUG(__f) _STLP_FIX_LITERAL_BUG(__l)
_DbgBase::append(__f, __l);
return *this;
}
_Self& append(const_iterator __f, const_iterator __l) {
_DbgBase::append(__f, __l);
return *this;
}
#endif
public: // Assign
_Self& assign(const _Self& __s) {
_DbgBase::assign(__s);
return *this;
}
_Self& assign(const _Self& __s, size_type __pos, size_type __n) {
_DbgBase::assign(__s, __pos, __n);
return *this;
}
_Self& assign(const _CharT* __s, size_type __n) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::assign(__s, __n);
return *this;
}
_Self& assign(const _CharT* __s) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::assign(__s);
return *this;
}
_Self& assign(size_type __n, _CharT __c) {
_DbgBase::assign(__n, __c);
return *this;
}
template <class _InputIter>
inline _Self& assign(_InputIter __first, _InputIter __last) {
_STLP_FIX_LITERAL_BUG(__first) _STLP_FIX_LITERAL_BUG(__last)
_STLP_DEBUG_CHECK(__check_range(__first, __last))
_Invalidate_all();
_Base::assign(__first, __last);
return *this;
}
#if !defined (_STLP_NO_METHOD_SPECIALIZATION) && !defined (_STLP_NO_EXTENSIONS)
_Self& assign(const _CharT* __f, const _CharT* __l) {
_DbgBase::assign(__f, __l);
return *this;
}
_Self& assign(const_iterator __f, const_iterator __l) {
_DbgBase::assign(__f, __l);
return *this;
}
#endif
public: // Insert
_Self& insert(size_type __pos, const _Self& __s) {
_DbgBase::insert(__pos, __s);
return *this;
}
_Self& insert(size_type __pos, const _Self& __s, size_type __beg, size_type __n) {
_DbgBase::insert(__pos, __s, __beg, __n);
return *this;
}
_Self& insert(size_type __pos, const _CharT* __s, size_type __n) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::insert(__pos, __s, __n);
return *this;
}
_Self& insert(size_type __pos, const _CharT* __s) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::insert(__pos, __s);
return *this;
}
_Self& insert(size_type __pos, size_type __n, _CharT __c) {
_DbgBase::insert(__pos, __n, __c);
return *this;
}
iterator insert(iterator __p, _CharT __c) {
return _DbgBase::insert(__p, __c);
}
void insert(iterator __p, size_t __n, _CharT __c) {
_DbgBase::insert(__p, __n, __c);
}
protected:
template <class _RandomIter>
void _M_insert_aux (iterator __p, _RandomIter __first, _RandomIter __last,
const __true_type& /*_IsIterator*/) {
_Base::insert(__p._M_iterator, __first._M_iterator, __last._M_iterator);
}
template<class _InputIter>
void _M_insert_aux (iterator __p, _InputIter __first, _InputIter __last,
const __false_type& /*_IsIterator*/) {
_Base::insert(__p._M_iterator, __first, __last);
}
public:
template <class _InputIter>
void insert(iterator __p, _InputIter __first, _InputIter __last) {
_STLP_DEBUG_CHECK(__check_if_owner(&this->_M_iter_list,__p))
_STLP_DEBUG_CHECK(__check_range(__first,__last))
typedef typename _AreSameUnCVTypes<_InputIter, iterator>::_Ret _IsNonConstIterator;
typedef typename _AreSameUnCVTypes<_InputIter, const_iterator>::_Ret _IsConstIterator;
typedef typename _Lor2<_IsNonConstIterator, _IsConstIterator>::_Ret _IsIterator;
size_type __old_capacity = this->capacity();
_M_insert_aux(__p, __first, __last, _IsIterator());
_Compare_Capacity(__old_capacity);
}
#if !defined (_STLP_NO_METHOD_SPECIALIZATION) && !defined (_STLP_NO_EXTENSIONS)
void insert(iterator __p, const_iterator __f, const_iterator __l) {
_DbgBase::insert(__p, __f, __l);
}
void insert(iterator __p, const _CharT* __f, const _CharT* __l) {
_STLP_FIX_LITERAL_BUG(__f)_STLP_FIX_LITERAL_BUG(__l)
_DbgBase::insert(__p, __f, __l);
}
#endif
public: // Erase.
_Self& erase(size_type __pos = 0, size_type __n = _DbgBase::npos) {
_DbgBase::erase(__pos, __n);
return *this;
}
iterator erase(iterator __pos) {
return _DbgBase::erase(__pos);
}
iterator erase(iterator __first, iterator __last) {
return _DbgBase::erase(__first, __last);
}
public: // Substring.
_Self substr(size_type __pos = 0, size_type __n = _DbgBase::npos) const {
return _Base::substr(__pos, __n);
}
public: // Replace. (Conceptually equivalent
// to erase followed by insert.)
_Self& replace(size_type __pos, size_type __n, const _Self& __s) {
_DbgBase::replace(__pos, __n, __s);
return *this;
}
_Self& replace(size_type __pos1, size_type __n1, const _Self& __s,
size_type __pos2, size_type __n2) {
_DbgBase::replace(__pos1, __n1, __s, __pos2, __n2);
return *this;
}
_Self& replace(size_type __pos, size_type __n1, const _CharT* __s, size_type __n2) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::replace(__pos, __n1, __s, __n2);
return *this;
}
_Self& replace(size_type __pos, size_type __n1, const _CharT* __s) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::replace(__pos, __n1, __s);
return *this;
}
_Self& replace(size_type __pos, size_type __n1, size_type __n2, _CharT __c) {
_DbgBase::replace(__pos, __n1, __n2, __c);
return *this;
}
_Self& replace(iterator __first, iterator __last, const _Self& __s) {
_DbgBase::replace(__first, __last, __s);
return *this;
}
_Self& replace(iterator __first, iterator __last, const _CharT* __s, size_type __n) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::replace(__first, __last, __s, __n);
return *this;
}
_Self& replace(iterator __first, iterator __last, const _CharT* __s) {
_STLP_FIX_LITERAL_BUG(__s)
_DbgBase::replace(__first, __last, __s);
return *this;
}
_Self& replace(iterator __first, iterator __last, size_type __n, _CharT __c) {
_DbgBase::replace(__first, __last, __n, __c);
return *this;
}
private:
template <class _RandomIter>
void _M_replace_aux(iterator __first, iterator __last,
_RandomIter __f, _RandomIter __l, __true_type const& /*_IsIterator*/) {
_Base::replace(__first._M_iterator, __last._M_iterator, __f._M_iterator, __l._M_iterator);
}
template <class _InputIter>
void _M_replace_aux(iterator __first, iterator __last,
_InputIter __f, _InputIter __l, __false_type const& /*_IsIterator*/) {
_Base::replace(__first._M_iterator, __last._M_iterator, __f, __l);
}
public:
template <class _InputIter>
_Self& replace(iterator __first, iterator __last,
_InputIter __f, _InputIter __l) {
_STLP_DEBUG_CHECK(__check_range(__first, __last, this->begin(), this->end()))
_STLP_DEBUG_CHECK(__check_range(__f, __l))
typedef typename _AreSameUnCVTypes<_InputIter, iterator>::_Ret _IsNonConstIterator;
typedef typename _AreSameUnCVTypes<_InputIter, const_iterator>::_Ret _IsConstIterator;
typedef typename _Lor2<_IsNonConstIterator, _IsConstIterator>::_Ret _IsIterator;
size_type __old_capacity = this->capacity();
_M_replace_aux(__first, __last, __f, __l, _IsIterator());
_Compare_Capacity(__old_capacity);
return *this;
}
#if !defined (_STLP_NO_METHOD_SPECIALIZATION) && !defined (_STLP_NO_EXTENSIONS)
_Self& replace(iterator __first, iterator __last,
const_iterator __f, const_iterator __l) {
_DbgBase::replace(__first, __last, __f, __l);
return *this;
}
_Self& replace(iterator __first, iterator __last,
const _CharT* __f, const _CharT __l) {
_STLP_FIX_LITERAL_BUG(__f)_STLP_FIX_LITERAL_BUG(__l)
_DbgBase::replace(__first, __last, __f, __l);
return *this;
}
#endif
public: // Other modifier member functions.
void swap(_Self& __s) {
this->_M_iter_list._Swap_owners(__s._M_iter_list);
_DbgBase::swap(__s);
}
#if defined (_STLP_USE_TEMPLATE_EXPRESSION)
# define _STLP_STRING_SUM_BASE _STLP_NON_DBG_STRING_BASE
# define _STLP_STRING_BASE_SCOPE _DbgBase::
# include <stl/_string_sum_methods.h>
# undef _STLP_STRING_BASE_SCOPE
# undef _STLP_STRING_SUM_BASE
#endif /* _STLP_USE_TEMPLATE_EXPRESSION */
};
#undef _STLP_NON_DBG_STRING_BASE
_STLP_END_NAMESPACE
// Local Variables:
// mode:C++
// End:
|
ZHAW-INES/rioxo-uClinux-dist
|
lib/STLport/stlport/stl/debug/_string_workaround.h
|
C
|
gpl-2.0
| 13,374 |
netfilter-objs := core.o nf_log.o nf_queue.o nf_sockopt.o
nf_conntrack-y := nf_conntrack_core.o nf_conntrack_standalone.o nf_conntrack_expect.o nf_conntrack_helper.o nf_conntrack_proto.o nf_conntrack_l3proto_generic.o nf_conntrack_proto_generic.o nf_conntrack_proto_tcp.o nf_conntrack_proto_udp.o
nf_conntrack-$(CONFIG_NF_CONNTRACK_EVENTS) += nf_conntrack_ecache.o
obj-$(CONFIG_NETFILTER) = netfilter.o
obj-$(CONFIG_SYSCTL) += nf_sysctl.o
obj-$(CONFIG_NETFILTER_NETLINK) += nfnetlink.o
obj-$(CONFIG_NETFILTER_NETLINK_QUEUE) += nfnetlink_queue.o
obj-$(CONFIG_NETFILTER_NETLINK_LOG) += nfnetlink_log.o
# connection tracking
obj-$(CONFIG_NF_CONNTRACK) += nf_conntrack.o
# SCTP protocol connection tracking
obj-$(CONFIG_NF_CT_PROTO_GRE) += nf_conntrack_proto_gre.o
obj-$(CONFIG_NF_CT_PROTO_SCTP) += nf_conntrack_proto_sctp.o
# netlink interface for nf_conntrack
obj-$(CONFIG_NF_CT_NETLINK) += nf_conntrack_netlink.o
# connection tracking helpers
nf_conntrack_h323-objs := nf_conntrack_h323_main.o nf_conntrack_h323_asn1.o
obj-$(CONFIG_NF_CONNTRACK_AMANDA) += nf_conntrack_amanda.o
obj-$(CONFIG_NF_CONNTRACK_FTP) += nf_conntrack_ftp.o
obj-$(CONFIG_NF_CONNTRACK_H323) += nf_conntrack_h323.o
obj-$(CONFIG_NF_CONNTRACK_IRC) += nf_conntrack_irc.o
obj-$(CONFIG_NF_CONNTRACK_NETBIOS_NS) += nf_conntrack_netbios_ns.o
obj-$(CONFIG_NF_CONNTRACK_PPTP) += nf_conntrack_pptp.o
obj-$(CONFIG_NF_CONNTRACK_SANE) += nf_conntrack_sane.o
obj-$(CONFIG_NF_CONNTRACK_SIP) += nf_conntrack_sip.o
obj-$(CONFIG_NF_CONNTRACK_TFTP) += nf_conntrack_tftp.o
obj-$(CONFIG_NF_CONNTRACK_RTSP) += nf_conntrack_rtsp.o
# generic X tables
obj-$(CONFIG_NETFILTER_XTABLES) += x_tables.o xt_tcpudp.o
# targets
obj-$(CONFIG_NETFILTER_XT_TARGET_CLASSIFY) += xt_CLASSIFY.o
obj-$(CONFIG_NETFILTER_XT_TARGET_CONNMARK) += xt_CONNMARK.o
obj-$(CONFIG_NETFILTER_XT_TARGET_DSCP) += xt_DSCP.o
obj-$(CONFIG_NETFILTER_XT_TARGET_HL) += xt_HL.o
obj-$(CONFIG_NETFILTER_XT_TARGET_MARK) += xt_MARK.o
obj-$(CONFIG_NETFILTER_XT_TARGET_NFQUEUE) += xt_NFQUEUE.o
obj-$(CONFIG_NETFILTER_XT_TARGET_NFLOG) += xt_NFLOG.o
obj-$(CONFIG_NETFILTER_XT_TARGET_NOTRACK) += xt_NOTRACK.o
obj-$(CONFIG_NETFILTER_XT_TARGET_SECMARK) += xt_SECMARK.o
obj-$(CONFIG_NETFILTER_XT_TARGET_TCPMSS) += xt_TCPMSS.o
obj-$(CONFIG_NETFILTER_XT_TARGET_CONNSECMARK) += xt_CONNSECMARK.o
# matches
obj-$(CONFIG_NETFILTER_XT_MATCH_COMMENT) += xt_comment.o
obj-$(CONFIG_NETFILTER_XT_MATCH_CONNBYTES) += xt_connbytes.o
obj-$(CONFIG_NETFILTER_XT_MATCH_CONNLIMIT) += xt_connlimit.o
obj-$(CONFIG_NETFILTER_XT_MATCH_CONNMARK) += xt_connmark.o
obj-$(CONFIG_NETFILTER_XT_MATCH_CONNTRACK) += xt_conntrack.o
obj-$(CONFIG_NETFILTER_XT_MATCH_DCCP) += xt_dccp.o
obj-$(CONFIG_NETFILTER_XT_MATCH_DSCP) += xt_dscp.o
obj-$(CONFIG_NETFILTER_XT_MATCH_ESP) += xt_esp.o
obj-$(CONFIG_NETFILTER_XT_MATCH_GEOIP) += xt_geoip.o
obj-$(CONFIG_NETFILTER_XT_MATCH_HELPER) += xt_helper.o
obj-$(CONFIG_NETFILTER_XT_MATCH_HL) += xt_hl.o
obj-$(CONFIG_NETFILTER_XT_MATCH_IPRANGE) += xt_iprange.o
obj-$(CONFIG_NETFILTER_XT_MATCH_LENGTH) += xt_length.o
obj-$(CONFIG_NETFILTER_XT_MATCH_LIMIT) += xt_limit.o
obj-$(CONFIG_NETFILTER_XT_MATCH_MAC) += xt_mac.o
obj-$(CONFIG_NETFILTER_XT_MATCH_MARK) += xt_mark.o
obj-$(CONFIG_NETFILTER_XT_MATCH_MULTIPORT) += xt_multiport.o
obj-$(CONFIG_NETFILTER_XT_MATCH_POLICY) += xt_policy.o
obj-$(CONFIG_NETFILTER_XT_MATCH_PKTTYPE) += xt_pkttype.o
obj-$(CONFIG_NETFILTER_XT_MATCH_QUOTA) += xt_quota.o
obj-$(CONFIG_NETFILTER_XT_MATCH_REALM) += xt_realm.o
obj-$(CONFIG_NETFILTER_XT_MATCH_RECENT) += xt_recent.o
obj-$(CONFIG_NETFILTER_XT_MATCH_SCTP) += xt_sctp.o
obj-$(CONFIG_NETFILTER_XT_MATCH_STATE) += xt_state.o
obj-$(CONFIG_NETFILTER_XT_MATCH_LAYER7) += xt_layer7.o
obj-$(CONFIG_NETFILTER_XT_MATCH_STATISTIC) += xt_statistic.o
obj-$(CONFIG_NETFILTER_XT_MATCH_STRING) += xt_string.o
obj-$(CONFIG_NETFILTER_XT_MATCH_WEBSTR) += xt_webstr.o
obj-$(CONFIG_NETFILTER_XT_MATCH_TIME) += xt_time.o
obj-$(CONFIG_NETFILTER_XT_MATCH_TCPMSS) += xt_tcpmss.o
obj-$(CONFIG_NETFILTER_XT_MATCH_PHYSDEV) += xt_physdev.o
obj-$(CONFIG_NETFILTER_XT_MATCH_CONDITION) += xt_condition.o
obj-$(CONFIG_NETFILTER_XT_MATCH_HASHLIMIT) += xt_hashlimit.o
|
smx-smx/dsl-n55u-bender
|
release/src-ra/linux/linux-2.6.21.x/net/netfilter/Makefile
|
Makefile
|
gpl-2.0
| 4,128 |
require 'erb'
require 'set'
require 'enumerator'
require 'stringio'
require 'rbconfig'
require 'sass/root'
require 'sass/util/subset_map'
module Sass
# A module containing various useful functions.
module Util
extend self
# An array of ints representing the Ruby version number.
# @api public
RUBY_VERSION = ::RUBY_VERSION.split(".").map {|s| s.to_i}
# The Ruby engine we're running under. Defaults to `"ruby"`
# if the top-level constant is undefined.
# @api public
RUBY_ENGINE = defined?(::RUBY_ENGINE) ? ::RUBY_ENGINE : "ruby"
# Returns the path of a file relative to the Sass root directory.
#
# @param file [String] The filename relative to the Sass root
# @return [String] The filename relative to the the working directory
def scope(file)
File.join(Sass::ROOT_DIR, file)
end
# Converts an array of `[key, value]` pairs to a hash.
#
# @example
# to_hash([[:foo, "bar"], [:baz, "bang"]])
# #=> {:foo => "bar", :baz => "bang"}
# @param arr [Array<(Object, Object)>] An array of pairs
# @return [Hash] A hash
def to_hash(arr)
Hash[arr.compact]
end
# Maps the keys in a hash according to a block.
#
# @example
# map_keys({:foo => "bar", :baz => "bang"}) {|k| k.to_s}
# #=> {"foo" => "bar", "baz" => "bang"}
# @param hash [Hash] The hash to map
# @yield [key] A block in which the keys are transformed
# @yieldparam key [Object] The key that should be mapped
# @yieldreturn [Object] The new value for the key
# @return [Hash] The mapped hash
# @see #map_vals
# @see #map_hash
def map_keys(hash)
to_hash(hash.map {|k, v| [yield(k), v]})
end
# Maps the values in a hash according to a block.
#
# @example
# map_values({:foo => "bar", :baz => "bang"}) {|v| v.to_sym}
# #=> {:foo => :bar, :baz => :bang}
# @param hash [Hash] The hash to map
# @yield [value] A block in which the values are transformed
# @yieldparam value [Object] The value that should be mapped
# @yieldreturn [Object] The new value for the value
# @return [Hash] The mapped hash
# @see #map_keys
# @see #map_hash
def map_vals(hash)
to_hash(hash.map {|k, v| [k, yield(v)]})
end
# Maps the key-value pairs of a hash according to a block.
#
# @example
# map_hash({:foo => "bar", :baz => "bang"}) {|k, v| [k.to_s, v.to_sym]}
# #=> {"foo" => :bar, "baz" => :bang}
# @param hash [Hash] The hash to map
# @yield [key, value] A block in which the key-value pairs are transformed
# @yieldparam [key] The hash key
# @yieldparam [value] The hash value
# @yieldreturn [(Object, Object)] The new value for the `[key, value]` pair
# @return [Hash] The mapped hash
# @see #map_keys
# @see #map_vals
def map_hash(hash)
# Using &block here completely hoses performance on 1.8.
to_hash(hash.map {|k, v| yield k, v})
end
# Computes the powerset of the given array.
# This is the set of all subsets of the array.
#
# @example
# powerset([1, 2, 3]) #=>
# Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]
# @param arr [Enumerable]
# @return [Set<Set>] The subsets of `arr`
def powerset(arr)
arr.inject([Set.new].to_set) do |powerset, el|
new_powerset = Set.new
powerset.each do |subset|
new_powerset << subset
new_powerset << subset + [el]
end
new_powerset
end
end
# Restricts a number to falling within a given range.
# Returns the number if it falls within the range,
# or the closest value in the range if it doesn't.
#
# @param value [Numeric]
# @param range [Range<Numeric>]
# @return [Numeric]
def restrict(value, range)
[[value, range.first].max, range.last].min
end
# Concatenates all strings that are adjacent in an array,
# while leaving other elements as they are.
#
# @example
# merge_adjacent_strings([1, "foo", "bar", 2, "baz"])
# #=> [1, "foobar", 2, "baz"]
# @param arr [Array]
# @return [Array] The enumerable with strings merged
def merge_adjacent_strings(arr)
# Optimize for the common case of one element
return arr if arr.size < 2
arr.inject([]) do |a, e|
if e.is_a?(String)
if a.last.is_a?(String)
a.last << e
else
a << e.dup
end
else
a << e
end
a
end
end
# Intersperses a value in an enumerable, as would be done with `Array#join`
# but without concatenating the array together afterwards.
#
# @param enum [Enumerable]
# @param val
# @return [Array]
def intersperse(enum, val)
enum.inject([]) {|a, e| a << e << val}[0...-1]
end
# Substitutes a sub-array of one array with another sub-array.
#
# @param ary [Array] The array in which to make the substitution
# @param from [Array] The sequence of elements to replace with `to`
# @param to [Array] The sequence of elements to replace `from` with
def substitute(ary, from, to)
res = ary.dup
i = 0
while i < res.size
if res[i...i+from.size] == from
res[i...i+from.size] = to
end
i += 1
end
res
end
# Destructively strips whitespace from the beginning and end
# of the first and last elements, respectively,
# in the array (if those elements are strings).
#
# @param arr [Array]
# @return [Array] `arr`
def strip_string_array(arr)
arr.first.lstrip! if arr.first.is_a?(String)
arr.last.rstrip! if arr.last.is_a?(String)
arr
end
# Return an array of all possible paths through the given arrays.
#
# @param arrs [Array<Array>]
# @return [Array<Arrays>]
#
# @example
# paths([[1, 2], [3, 4], [5]]) #=>
# # [[1, 3, 5],
# # [2, 3, 5],
# # [1, 4, 5],
# # [2, 4, 5]]
def paths(arrs)
arrs.inject([[]]) do |paths, arr|
flatten(arr.map {|e| paths.map {|path| path + [e]}}, 1)
end
end
# Computes a single longest common subsequence for `x` and `y`.
# If there are more than one longest common subsequences,
# the one returned is that which starts first in `x`.
#
# @param x [Array]
# @param y [Array]
# @yield [a, b] An optional block to use in place of a check for equality
# between elements of `x` and `y`.
# @yieldreturn [Object, nil] If the two values register as equal,
# this will return the value to use in the LCS array.
# @return [Array] The LCS
def lcs(x, y, &block)
x = [nil, *x]
y = [nil, *y]
block ||= proc {|a, b| a == b && a}
lcs_backtrace(lcs_table(x, y, &block), x, y, x.size-1, y.size-1, &block)
end
# Converts a Hash to an Array. This is usually identical to `Hash#to_a`,
# with the following exceptions:
#
# * In Ruby 1.8, `Hash#to_a` is not deterministically ordered, but this is.
# * In Ruby 1.9 when running tests, this is ordered in the same way it would
# be under Ruby 1.8 (sorted key order rather than insertion order).
#
# @param hash [Hash]
# @return [Array]
def hash_to_a(hash)
return hash.to_a unless ruby1_8? || defined?(Test::Unit)
return hash.sort_by {|k, v| k}
end
# Performs the equivalent of `enum.group_by.to_a`, but with a guaranteed
# order. Unlike [#hash_to_a], the resulting order isn't sorted key order;
# instead, it's the same order as `#group_by` has under Ruby 1.9 (key
# appearance order).
#
# @param enum [Enumerable]
# @return [Array<[Object, Array]>] An array of pairs.
def group_by_to_a(enum, &block)
return enum.group_by(&block).to_a unless ruby1_8?
order = {}
arr = []
enum.group_by do |e|
res = block[e]
unless order.include?(res)
order[res] = order.size
end
res
end.each do |key, vals|
arr[order[key]] = [key, vals]
end
arr
end
# Asserts that `value` falls within `range` (inclusive), leaving
# room for slight floating-point errors.
#
# @param name [String] The name of the value. Used in the error message.
# @param range [Range] The allowed range of values.
# @param value [Numeric, Sass::Script::Number] The value to check.
# @param unit [String] The unit of the value. Used in error reporting.
# @return [Numeric] `value` adjusted to fall within range, if it
# was outside by a floating-point margin.
def check_range(name, range, value, unit='')
grace = (-0.00001..0.00001)
str = value.to_s
value = value.value if value.is_a?(Sass::Script::Number)
return value if range.include?(value)
return range.first if grace.include?(value - range.first)
return range.last if grace.include?(value - range.last)
raise ArgumentError.new(
"#{name} #{str} must be between #{range.first}#{unit} and #{range.last}#{unit}")
end
# Returns whether or not `seq1` is a subsequence of `seq2`. That is, whether
# or not `seq2` contains every element in `seq1` in the same order (and
# possibly more elements besides).
#
# @param seq1 [Array]
# @param seq2 [Array]
# @return [Boolean]
def subsequence?(seq1, seq2)
i = j = 0
loop do
return true if i == seq1.size
return false if j == seq2.size
i += 1 if seq1[i] == seq2[j]
j += 1
end
end
# Returns information about the caller of the previous method.
#
# @param entry [String] An entry in the `#caller` list, or a similarly formatted string
# @return [[String, Fixnum, (String, nil)]] An array containing the filename, line, and method name of the caller.
# The method name may be nil
def caller_info(entry = nil)
# JRuby evaluates `caller` incorrectly when it's in an actual default argument.
entry ||= caller[1]
info = entry.scan(/^(.*?):(-?.*?)(?::.*`(.+)')?$/).first
info[1] = info[1].to_i
# This is added by Rubinius to designate a block, but we don't care about it.
info[2].sub!(/ \{\}\Z/, '') if info[2]
info
end
# Returns whether one version string represents a more recent version than another.
#
# @param v1 [String] A version string.
# @param v2 [String] Another version string.
# @return [Boolean]
def version_gt(v1, v2)
# Construct an array to make sure the shorter version is padded with nil
Array.new([v1.length, v2.length].max).zip(v1.split("."), v2.split(".")) do |_, p1, p2|
p1 ||= "0"
p2 ||= "0"
release1 = p1 =~ /^[0-9]+$/
release2 = p2 =~ /^[0-9]+$/
if release1 && release2
# Integer comparison if both are full releases
p1, p2 = p1.to_i, p2.to_i
next if p1 == p2
return p1 > p2
elsif !release1 && !release2
# String comparison if both are prereleases
next if p1 == p2
return p1 > p2
else
# If only one is a release, that one is newer
return release1
end
end
end
# Returns whether one version string represents the same or a more
# recent version than another.
#
# @param v1 [String] A version string.
# @param v2 [String] Another version string.
# @return [Boolean]
def version_geq(v1, v2)
version_gt(v1, v2) || !version_gt(v2, v1)
end
# Throws a NotImplementedError for an abstract method.
#
# @param obj [Object] `self`
# @raise [NotImplementedError]
def abstract(obj)
raise NotImplementedError.new("#{obj.class} must implement ##{caller_info[2]}")
end
# Silence all output to STDERR within a block.
#
# @yield A block in which no output will be printed to STDERR
def silence_warnings
the_real_stderr, $stderr = $stderr, StringIO.new
yield
ensure
$stderr = the_real_stderr
end
@@silence_warnings = false
# Silences all Sass warnings within a block.
#
# @yield A block in which no Sass warnings will be printed
def silence_sass_warnings
old_level, Sass.logger.log_level = Sass.logger.log_level, :error
yield
ensure
Sass.logger.log_level = old_level
end
# The same as `Kernel#warn`, but is silenced by \{#silence\_sass\_warnings}.
#
# @param msg [String]
def sass_warn(msg)
msg = msg + "\n" unless ruby1?
Sass.logger.warn(msg)
end
## Cross Rails Version Compatibility
# Returns the root of the Rails application,
# if this is running in a Rails context.
# Returns `nil` if no such root is defined.
#
# @return [String, nil]
def rails_root
if defined?(::Rails.root)
return ::Rails.root.to_s if ::Rails.root
raise "ERROR: Rails.root is nil!"
end
return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
return nil
end
# Returns the environment of the Rails application,
# if this is running in a Rails context.
# Returns `nil` if no such environment is defined.
#
# @return [String, nil]
def rails_env
return ::Rails.env.to_s if defined?(::Rails.env)
return RAILS_ENV.to_s if defined?(RAILS_ENV)
return nil
end
# Returns whether this environment is using ActionPack
# version 3.0.0 or greater.
#
# @return [Boolean]
def ap_geq_3?
ap_geq?("3.0.0.beta1")
end
# Returns whether this environment is using ActionPack
# of a version greater than or equal to that specified.
#
# @param version [String] The string version number to check against.
# Should be greater than or equal to Rails 3,
# because otherwise ActionPack::VERSION isn't autoloaded
# @return [Boolean]
def ap_geq?(version)
# The ActionPack module is always loaded automatically in Rails >= 3
return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
defined?(ActionPack::VERSION::STRING)
version_geq(ActionPack::VERSION::STRING, version)
end
# Returns an ActionView::Template* class.
# In pre-3.0 versions of Rails, most of these classes
# were of the form `ActionView::TemplateFoo`,
# while afterwards they were of the form `ActionView;:Template::Foo`.
#
# @param name [#to_s] The name of the class to get.
# For example, `:Error` will return `ActionView::TemplateError`
# or `ActionView::Template::Error`.
def av_template_class(name)
return ActionView.const_get("Template#{name}") if ActionView.const_defined?("Template#{name}")
return ActionView::Template.const_get(name.to_s)
end
## Cross-OS Compatibility
# Whether or not this is running on Windows.
#
# @return [Boolean]
def windows?
RbConfig::CONFIG['host_os'] =~ /mswin|windows|mingw/i
end
# Whether or not this is running on IronRuby.
#
# @return [Boolean]
def ironruby?
RUBY_ENGINE == "ironruby"
end
# Like `Dir.glob`, but works with backslash-separated paths on Windows.
#
# @param path [String]
def glob(path, &block)
path = path.gsub('\\', '/') if windows?
Dir.glob(path, &block)
end
# Prepare a value for a destructuring assignment (e.g. `a, b =
# val`). This works around a performance bug when using
# ActiveSupport, and only needs to be called when `val` is likely
# to be `nil` reasonably often.
#
# See [this bug report](http://redmine.ruby-lang.org/issues/4917).
#
# @param val [Object]
# @return [Object]
def destructure(val)
val || []
end
## Cross-Ruby-Version Compatibility
# Whether or not this is running under a Ruby version under 2.0.
#
# @return [Boolean]
def ruby1?
Sass::Util::RUBY_VERSION[0] <= 1
end
# Whether or not this is running under Ruby 1.8 or lower.
#
# Note that IronRuby counts as Ruby 1.8,
# because it doesn't support the Ruby 1.9 encoding API.
#
# @return [Boolean]
def ruby1_8?
# IronRuby says its version is 1.9, but doesn't support any of the encoding APIs.
# We have to fall back to 1.8 behavior.
ironruby? || (Sass::Util::RUBY_VERSION[0] == 1 && Sass::Util::RUBY_VERSION[1] < 9)
end
# Whether or not this is running under Ruby 1.8.6 or lower.
# Note that lower versions are not officially supported.
#
# @return [Boolean]
def ruby1_8_6?
ruby1_8? && Sass::Util::RUBY_VERSION[2] < 7
end
# Whether or not this is running under MacRuby.
#
# @return [Boolean]
def macruby?
RUBY_ENGINE == 'macruby'
end
# Checks that the encoding of a string is valid in Ruby 1.9
# and cleans up potential encoding gotchas like the UTF-8 BOM.
# If it's not, yields an error string describing the invalid character
# and the line on which it occurrs.
#
# @param str [String] The string of which to check the encoding
# @yield [msg] A block in which an encoding error can be raised.
# Only yields if there is an encoding error
# @yieldparam msg [String] The error message to be raised
# @return [String] `str`, potentially with encoding gotchas like BOMs removed
def check_encoding(str)
if ruby1_8?
return str.gsub(/\A\xEF\xBB\xBF/, '') # Get rid of the UTF-8 BOM
elsif str.valid_encoding?
# Get rid of the Unicode BOM if possible
if str.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?$/
return str.gsub(Regexp.new("\\A\uFEFF".encode(str.encoding.name)), '')
else
return str
end
end
encoding = str.encoding
newlines = Regexp.new("\r\n|\r|\n".encode(encoding).force_encoding("binary"))
str.force_encoding("binary").split(newlines).each_with_index do |line, i|
begin
line.encode(encoding)
rescue Encoding::UndefinedConversionError => e
yield <<MSG.rstrip, i + 1
Invalid #{encoding.name} character #{e.error_char.dump}
MSG
end
end
return str
end
# Like {\#check\_encoding}, but also checks for a `@charset` declaration
# at the beginning of the file and uses that encoding if it exists.
#
# The Sass encoding rules are simple.
# If a `@charset` declaration exists,
# we assume that that's the original encoding of the document.
# Otherwise, we use whatever encoding Ruby has.
# Then we convert that to UTF-8 to process internally.
# The UTF-8 end result is what's returned by this method.
#
# @param str [String] The string of which to check the encoding
# @yield [msg] A block in which an encoding error can be raised.
# Only yields if there is an encoding error
# @yieldparam msg [String] The error message to be raised
# @return [(String, Encoding)] The original string encoded as UTF-8,
# and the source encoding of the string (or `nil` under Ruby 1.8)
# @raise [Encoding::UndefinedConversionError] if the source encoding
# cannot be converted to UTF-8
# @raise [ArgumentError] if the document uses an unknown encoding with `@charset`
def check_sass_encoding(str, &block)
return check_encoding(str, &block), nil if ruby1_8?
# We allow any printable ASCII characters but double quotes in the charset decl
bin = str.dup.force_encoding("BINARY")
encoding = Sass::Util::ENCODINGS_TO_CHECK.find do |enc|
re = Sass::Util::CHARSET_REGEXPS[enc]
re && bin =~ re
end
charset, bom = $1, $2
if charset
charset = charset.force_encoding(encoding).encode("UTF-8")
if endianness = encoding[/[BL]E$/]
begin
Encoding.find(charset + endianness)
charset << endianness
rescue ArgumentError # Encoding charset + endianness doesn't exist
end
end
str.force_encoding(charset)
elsif bom
str.force_encoding(encoding)
end
str = check_encoding(str, &block)
return str.encode("UTF-8"), str.encoding
end
unless ruby1_8?
# @private
def _enc(string, encoding)
string.encode(encoding).force_encoding("BINARY")
end
# We could automatically add in any non-ASCII-compatible encodings here,
# but there's not really a good way to do that
# without manually checking that each encoding
# encodes all ASCII characters properly,
# which takes long enough to affect the startup time of the CLI.
ENCODINGS_TO_CHECK = %w[UTF-8 UTF-16BE UTF-16LE UTF-32BE UTF-32LE]
CHARSET_REGEXPS = Hash.new do |h, e|
h[e] =
begin
# /\A(?:\uFEFF)?@charset "(.*?)"|\A(\uFEFF)/
Regexp.new(/\A(?:#{_enc("\uFEFF", e)})?#{
_enc('@charset "', e)}(.*?)#{_enc('"', e)}|\A(#{
_enc("\uFEFF", e)})/)
rescue Encoding::ConverterNotFoundError => _
nil # JRuby on Java 5 doesn't support UTF-32
rescue
# /\A@charset "(.*?)"/
Regexp.new(/\A#{_enc('@charset "', e)}(.*?)#{_enc('"', e)}/)
end
end
end
# Checks to see if a class has a given method.
# For example:
#
# Sass::Util.has?(:public_instance_method, String, :gsub) #=> true
#
# Method collections like `Class#instance_methods`
# return strings in Ruby 1.8 and symbols in Ruby 1.9 and on,
# so this handles checking for them in a compatible way.
#
# @param attr [#to_s] The (singular) name of the method-collection method
# (e.g. `:instance_methods`, `:private_methods`)
# @param klass [Module] The class to check the methods of which to check
# @param method [String, Symbol] The name of the method do check for
# @return [Boolean] Whether or not the given collection has the given method
def has?(attr, klass, method)
klass.send("#{attr}s").include?(ruby1_8? ? method.to_s : method.to_sym)
end
# A version of `Enumerable#enum_with_index` that works in Ruby 1.8 and 1.9.
#
# @param enum [Enumerable] The enumerable to get the enumerator for
# @return [Enumerator] The with-index enumerator
def enum_with_index(enum)
ruby1_8? ? enum.enum_with_index : enum.each_with_index
end
# A version of `Enumerable#enum_cons` that works in Ruby 1.8 and 1.9.
#
# @param enum [Enumerable] The enumerable to get the enumerator for
# @param n [Fixnum] The size of each cons
# @return [Enumerator] The consed enumerator
def enum_cons(enum, n)
ruby1_8? ? enum.enum_cons(n) : enum.each_cons(n)
end
# A version of `Enumerable#enum_slice` that works in Ruby 1.8 and 1.9.
#
# @param enum [Enumerable] The enumerable to get the enumerator for
# @param n [Fixnum] The size of each slice
# @return [Enumerator] The consed enumerator
def enum_slice(enum, n)
ruby1_8? ? enum.enum_slice(n) : enum.each_slice(n)
end
# Destructively removes all elements from an array that match a block, and
# returns the removed elements.
#
# @param array [Array] The array from which to remove elements.
# @yield [el] Called for each element.
# @yieldparam el [*] The element to test.
# @yieldreturn [Boolean] Whether or not to extract the element.
# @return [Array] The extracted elements.
def extract!(array)
out = []
array.reject! do |e|
next false unless yield e
out << e
true
end
out
end
# Returns the ASCII code of the given character.
#
# @param c [String] All characters but the first are ignored.
# @return [Fixnum] The ASCII code of `c`.
def ord(c)
ruby1_8? ? c[0] : c.ord
end
# Flattens the first `n` nested arrays in a cross-version manner.
#
# @param arr [Array] The array to flatten
# @param n [Fixnum] The number of levels to flatten
# @return [Array] The flattened array
def flatten(arr, n)
return arr.flatten(n) unless ruby1_8_6?
return arr if n == 0
arr.inject([]) {|res, e| e.is_a?(Array) ? res.concat(flatten(e, n - 1)) : res << e}
end
# Returns the hash code for a set in a cross-version manner.
# Aggravatingly, this is order-dependent in Ruby 1.8.6.
#
# @param set [Set]
# @return [Fixnum] The order-independent hashcode of `set`
def set_hash(set)
return set.hash unless ruby1_8_6?
set.map {|e| e.hash}.uniq.sort.hash
end
# Tests the hash-equality of two sets in a cross-version manner.
# Aggravatingly, this is order-dependent in Ruby 1.8.6.
#
# @param set1 [Set]
# @param set2 [Set]
# @return [Boolean] Whether or not the sets are hashcode equal
def set_eql?(set1, set2)
return set1.eql?(set2) unless ruby1_8_6?
set1.to_a.uniq.sort_by {|e| e.hash}.eql?(set2.to_a.uniq.sort_by {|e| e.hash})
end
# Like `Object#inspect`, but preserves non-ASCII characters rather than escaping them under Ruby 1.9.2.
# This is necessary so that the precompiled Haml template can be `#encode`d into `@options[:encoding]`
# before being evaluated.
#
# @param obj {Object}
# @return {String}
def inspect_obj(obj)
return obj.inspect unless version_geq(::RUBY_VERSION, "1.9.2")
return ':' + inspect_obj(obj.to_s) if obj.is_a?(Symbol)
return obj.inspect unless obj.is_a?(String)
'"' + obj.gsub(/[\x00-\x7F]+/) {|s| s.inspect[1...-1]} + '"'
end
# Extracts the non-string vlaues from an array containing both strings and non-strings.
# These values are replaced with escape sequences.
# This can be undone using \{#inject\_values}.
#
# This is useful e.g. when we want to do string manipulation
# on an interpolated string.
#
# The precise format of the resulting string is not guaranteed.
# However, it is guaranteed that newlines and whitespace won't be affected.
#
# @param arr [Array] The array from which values are extracted.
# @return [(String, Array)] The resulting string, and an array of extracted values.
def extract_values(arr)
values = []
return arr.map do |e|
next e.gsub('{', '{{') if e.is_a?(String)
values << e
next "{#{values.count - 1}}"
end.join, values
end
# Undoes \{#extract\_values} by transforming a string with escape sequences
# into an array of strings and non-string values.
#
# @param str [String] The string with escape sequences.
# @param values [Array] The array of values to inject.
# @return [Array] The array of strings and values.
def inject_values(str, values)
return [str.gsub('{{', '{')] if values.empty?
# Add an extra { so that we process the tail end of the string
result = (str + '{{').scan(/(.*?)(?:(\{\{)|\{(\d+)\})/m).map do |(pre, esc, n)|
[pre, esc ? '{' : '', n ? values[n.to_i] : '']
end.flatten(1)
result[-2] = '' # Get rid of the extra {
merge_adjacent_strings(result).reject {|s| s == ''}
end
# Allows modifications to be performed on the string form
# of an array containing both strings and non-strings.
#
# @param arr [Array] The array from which values are extracted.
# @yield [str] A block in which string manipulation can be done to the array.
# @yieldparam str [String] The string form of `arr`.
# @yieldreturn [String] The modified string.
# @return [Array] The modified, interpolated array.
def with_extracted_values(arr)
str, vals = extract_values(arr)
str = yield str
inject_values(str, vals)
end
## Static Method Stuff
# The context in which the ERB for \{#def\_static\_method} will be run.
class StaticConditionalContext
# @param set [#include?] The set of variables that are defined for this context.
def initialize(set)
@set = set
end
# Checks whether or not a variable is defined for this context.
#
# @param name [Symbol] The name of the variable
# @return [Boolean]
def method_missing(name, *args, &block)
super unless args.empty? && block.nil?
@set.include?(name)
end
end
private
# Calculates the memoization table for the Least Common Subsequence algorithm.
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Computing_the_length_of_the_LCS)
def lcs_table(x, y)
c = Array.new(x.size) {[]}
x.size.times {|i| c[i][0] = 0}
y.size.times {|j| c[0][j] = 0}
(1...x.size).each do |i|
(1...y.size).each do |j|
c[i][j] =
if yield x[i], y[j]
c[i-1][j-1] + 1
else
[c[i][j-1], c[i-1][j]].max
end
end
end
return c
end
# Computes a single longest common subsequence for arrays x and y.
# Algorithm from [Wikipedia](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Reading_out_an_LCS)
def lcs_backtrace(c, x, y, i, j, &block)
return [] if i == 0 || j == 0
if v = yield(x[i], y[j])
return lcs_backtrace(c, x, y, i-1, j-1, &block) << v
end
return lcs_backtrace(c, x, y, i, j-1, &block) if c[i][j-1] > c[i-1][j]
return lcs_backtrace(c, x, y, i-1, j, &block)
end
end
end
require 'sass/util/multibyte_string_scanner'
|
skynet-tx/photoblog
|
wp-content/themes/videoblog/resources/lib/compass/lib/ruby/gems/1.9.1/gems/sass-3.2.5/lib/sass/util.rb
|
Ruby
|
gpl-2.0
| 29,672 |
/*
* Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.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/>.
*/
/* ScriptData
SDName: boss_illidan_stormrage
SD%Complete: 90
SDComment: Somewhat of a workaround for Parasitic Shadowfiend, unable to summon GOs for Cage Trap.
SDCategory: Black Temple
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedGossip.h"
#include "PassiveAI.h"
#include "black_temple.h"
#include "Player.h"
#include "SpellInfo.h"
// Other defines
#define CENTER_X 676.740f
#define CENTER_Y 305.297f
#define CENTER_Z 353.192f
enum Say
{
// Akama
SAY_AKAMA_BEWARE = 0,
SAY_AKAMA_LEAVE = 1,
// Illidan
SAY_ILLIDAN_MINION = 0,
SAY_ILLIDAN_KILL = 1,
SAY_ILLIDAN_TAKEOFF = 2,
SAY_ILLIDAN_SUMMONFLAMES = 3,
SAY_ILLIDAN_EYE_BLAST = 4,
SAY_ILLIDAN_MORPH = 5,
SAY_ILLIDAN_ENRAGE = 6,
SAY_ILLIDAN_TAUNT = 7,
// Maiev Shadowsong
SAY_MAIEV_SHADOWSONG_TAUNT = 0,
// Flame of Azzinoth
EMOTE_AZZINOTH_GAZE = 0
};
enum Spells
// Normal Form
{
SPELL_SHEAR = 37335, // 41032 is bugged, cannot be block/dodge/parry// Reduces Max. Health by 60% for 7 seconds. Can stack 19 times. 1.5f second cast
SPELL_FLAME_CRASH = 40832,
SPELL_DRAW_SOUL = 40904,
SPELL_PARASITIC_SHADOWFIEND = 41917,
SPELL_PARASITIC_SHADOWFIEND2 = 41914,
SPELL_SUMMON_PARASITICS = 41915,
SPELL_AGONIZING_FLAMES = 40932,
SPELL_ENRAGE = 40683,
// Flying (Phase 2)
SPELL_THROW_GLAIVE = 39635,
SPELL_THROW_GLAIVE2 = 39849, // Animation for the spell above
SPELL_GLAIVE_RETURNS = 39873,
SPELL_FIREBALL = 40598,
SPELL_DARK_BARRAGE = 40585,
// Demon Form
SPELL_DEMON_TRANSFORM_1 = 40511,
SPELL_DEMON_TRANSFORM_2 = 40398,
SPELL_DEMON_TRANSFORM_3 = 40510,
SPELL_DEMON_FORM = 40506,
SPELL_SHADOW_BLAST = 41078,
SPELL_FLAME_BURST = 41126,
SPELL_FLAME_BURST_EFFECT = 41131, // The actual damage. Have each player cast it on itself (workaround)
// Other Illidan spells
SPELL_KNEEL = 39656, // Before beginning encounter, this is how he appears (talking to skully).
SPELL_SHADOW_PRISON = 40647,
SPELL_DEATH = 41220,
SPELL_BERSERK = 45078,
SPELL_DUAL_WIELD = 42459,
SPELL_SUMMON_MAIEV = 40403,
// Phase Normal spells
SPELL_FLAME_CRASH_EFFECT = 40836,
SPELL_SUMMON_SHADOWDEMON = 41117,
SPELL_SHADOWFIEND_PASSIVE = 41913,
SPELL_SHADOW_DEMON_PASSIVE = 41079,
SPELL_CONSUME_SOUL = 41080,
SPELL_PARALYZE = 41083,
SPELL_PURPLE_BEAM = 39123,
// Phase Flight spells
SPELL_AZZINOTH_CHANNEL = 39857, // Glaives cast it on Flames. Not sure if this is the right spell.
SPELL_EYE_BLAST_TRIGGER = 40017,
SPELL_EYE_BLAST = 39908,
SPELL_BLAZE_EFFECT = 40610,
SPELL_BLAZE_SUMMON = 40637,
SPELL_DEMON_FIRE = 40029,
SPELL_FLAME_BLAST = 40631,
SPELL_CHARGE = 41581,
SPELL_FLAME_ENRAGE = 45078,
// Akama spells
SPELL_AKAMA_DOOR_CHANNEL = 41268,
SPELL_DEATHSWORN_DOOR_CHANNEL = 41269,
SPELL_AKAMA_DOOR_FAIL = 41271, // Not sure where this is really used...
SPELL_HEALING_POTION = 40535,
SPELL_CHAIN_LIGHTNING = 40536,
// Maiev spells
SPELL_CAGE_TRAP_DUMMY = 40761, // Put this in DB for cage trap GO.
SPELL_CAGED = 40695,
SPELL_CAGE_TRAP_SUMMON = 40694, // Summons a Cage Trap GO (bugged) on the ground along with a Cage Trap Disturb Trigger mob (working)
SPELL_CAGE_TRAP_BEAM = 40713,
SPELL_TELEPORT_VISUAL = 41232,
SPELL_SHADOW_STRIKE = 40685,
SPELL_THROW_DAGGER = 41152,
SPELL_FAN_BLADES = 39954 // bugged visual
};
enum Misc
{
FLAME_ENRAGE_DISTANCE = 30,
FLAME_CHARGE_DISTANCE = 50,
EQUIP_ID_MAIN_HAND = 32837,
EQUIP_ID_OFF_HAND = 32838,
EQUIP_ID_MAIN_HAND_MAIEV = 44850,
MODEL_INVISIBLE = 11686,
MODEL_ILLIDAN = 21135,
MODEL_BLADE = 21431
};
/**** Creature Summon and Recognition IDs ****/
enum CreatureEntry
{
EMPTY = 0,
AKAMA = 22990,
ILLIDAN_STORMRAGE = 22917,
BLADE_OF_AZZINOTH = 22996,
FLAME_OF_AZZINOTH = 22997,
MAIEV_SHADOWSONG = 23197,
SHADOW_DEMON = 23375,
DEMON_FIRE = 23069,
FLAME_CRASH = 23336,
ILLIDAN_DOOR_TRIGGER = 23412,
SPIRIT_OF_OLUM = 23411,
SPIRIT_OF_UDALO = 23410,
ILLIDARI_ELITE = 23226,
PARASITIC_SHADOWFIEND = 23498,
CAGE_TRAP_TRIGGER = 23292
};
/*** Phase Names ***/
enum PhaseIllidan
{
PHASE_ILLIDAN_NULL = 0,
PHASE_NORMAL = 1,
PHASE_FLIGHT = 2,
PHASE_NORMAL_2 = 3,
PHASE_DEMON = 4,
PHASE_NORMAL_MAIEV = 5,
PHASE_TALK_SEQUENCE = 6,
PHASE_FLIGHT_SEQUENCE = 7,
PHASE_TRANSFORM_SEQUENCE = 8,
PHASE_ILLIDAN_MAX = 9
}; // Maiev uses the same phase
enum PhaseAkama
{
PHASE_AKAMA_NULL = 0,
PHASE_CHANNEL = 1,
PHASE_WALK = 2,
PHASE_TALK = 3,
PHASE_FIGHT_ILLIDAN = 4,
PHASE_FIGHT_MINIONS = 5,
PHASE_RETURN = 6
};
enum EventIllidan
{
EVENT_NULL = 0,
EVENT_BERSERK = 1,
// normal phase
EVENT_TAUNT = 2,
EVENT_SHEAR = 3,
EVENT_FLAME_CRASH = 4,
EVENT_PARASITIC_SHADOWFIEND = 5,
EVENT_PARASITE_CHECK = 6,
EVENT_DRAW_SOUL = 7,
EVENT_AGONIZING_FLAMES = 8,
EVENT_TRANSFORM_NORMAL = 9,
EVENT_ENRAGE = 10,
// flight phase
EVENT_FIREBALL = 2,
EVENT_DARK_BARRAGE = 3,
EVENT_EYE_BLAST = 4,
EVENT_MOVE_POINT = 5,
// demon phase
EVENT_SHADOW_BLAST = 2,
EVENT_FLAME_BURST = 3,
EVENT_SHADOWDEMON = 4,
EVENT_TRANSFORM_DEMON = 5,
// sequence phase
EVENT_TALK_SEQUENCE = 2,
EVENT_FLIGHT_SEQUENCE = 2,
EVENT_TRANSFORM_SEQUENCE = 2
};
enum EventMaiev
{
EVENT_MAIEV_NULL = 0,
EVENT_MAIEV_STEALTH = 1,
EVENT_MAIEV_TAUNT = 2,
EVENT_MAIEV_SHADOW_STRIKE = 3,
EVENT_MAIEV_THROW_DAGGER = 4,
EVENT_MAIEV_TRAP = 4
};
static const EventIllidan MaxTimer[9] =
{
EVENT_NULL,
EVENT_DRAW_SOUL,
EVENT_MOVE_POINT,
EVENT_TRANSFORM_NORMAL,
EVENT_TRANSFORM_DEMON,
EVENT_ENRAGE,
EVENT_TALK_SEQUENCE,
EVENT_FLIGHT_SEQUENCE,
EVENT_TRANSFORM_SEQUENCE
};
/* ################## TO DO CONVERT THIS UGLINESS TO CREATURE TEXT ##################
SET @AKAMA := 23089;
SET @ILLIDAN := 22917;
SET @MAIEV := 23197;
DELETE FROM `creature_text` WHERE `entry`=@AKAMA AND `groupid` IN (2,3,4);
DELETE FROM `creature_text` WHERE `entry`=@ILLIDAN AND `groupid` IN (8,9,10,11,12,13,14);
DELETE FROM `creature_text` WHERE `entry`=@MAIEV AND `groupid` IN (1,2,3,4);
INSERT INTO `creature_text` (`entry`,`groupid`,`id`,`text`,`type`,`language`,`probability`,`emote`,`duration`,`sound`,`comment`) VALUES
(@ILLIDAN,8,0, "Akama... your duplicity is hardly surprising. I should have slaughtered you and your malformed brethren long ago.",14,0,100,0,0,11463, 'Illidan SAY_XXXXXXXXXXX'),
(@AKAMA,2,0, "We've come to end your reign, Illidan. My people and all of Outland shall be free!",14,0,100,25,0,11389, 'Akama SAY_XXXXXXXXXXX'),
(@ILLIDAN,9,0, "Boldly said. But I remain unconvinced.",14,0,100,396,0,11464, 'Illidan SAY_XXXXXXXXXXX'),
(@AKAMA,3,0, "The time has come! The moment is at hand!",14,0,100,22,0,11380, 'Akama SAY_XXXXXXXXXXX'),
(@ILLIDAN,10,0, "You are not prepared!",14,0,100,406,0,11466, 'Illidan SAY_XXXXXXXXXXX'),
(@ILLIDAN,11,0, "Is this it, mortals? Is this all the fury you can muster?",14,0,100,0,0,11476, 'Illidan SAY_XXXXXXXXXXX'),
(@MAIEV,1,0, "Their fury pales before mine, Illidan. We have some unsettled business between us.",14,0,100,5,0,11491, 'Maiev Shadowsong SAY_XXXXXXXXXXX'),
(@ILLIDAN,12,0, "Maiev... How is this even possible?",14,0,100,1,0,11477, 'Illidan SAY_XXXXXXXXXXX'),
(@MAIEV,2,0, "Ah... my long hunt is finally over. Today, Justice will be done!",14,0,100,15,0,11492, 'Maiev Shadowsong SAY_XXXXXXXXXXX'),
(@ILLIDAN,13,0, "Feel the hatred of ten thousand years!",14,0,100,396,0,11470, 'Illidan SAY_XXXXXXXXXXX'),
(@MAIEV,3,0, "Ahh... It is finished. You are beaten.",14,0,100,0,0,11496, 'Maiev Shadowsong SAY_XXXXXXXXXXX'),
(@ILLIDAN,14,0, "You have won... Maiev...but the huntress... is nothing...without the hunt... you... are nothing... without me..",14,0,100,65,0,11478, 'Illidan SAY_XXXXXXXXXXX'),
(@MAIEV,4,0, "He is right. I feel nothing... I am nothing... Farewell, champions.",14,0,100,0,0,11497, 'Maiev Shadowsong SAY_XXXXXXXXXXX'),
(@AKAMA,4,0, "The Light will fill these dismal halls once again. I swear it.",14,0,100,0,0,11387, 'Akama SAY_XXXXXXXXXXX');
*/
struct Yells
{
uint32 sound;
std::string text;
uint32 creature, timer, emote;
bool Talk;
};
static const Yells Conversation[22] =
{
{11463, "Akama... your duplicity is hardly surprising. I should have slaughtered you and your malformed brethren long ago.", ILLIDAN_STORMRAGE, 8000, 0, true},
{0, "", ILLIDAN_STORMRAGE, 5000, 396, true},
{11389, "We've come to end your reign, Illidan. My people and all of Outland shall be free!", AKAMA, 7000, 25, true},
{0, "", AKAMA, 5000, 66, true},
{11464, "Boldly said. But I remain unconvinced.", ILLIDAN_STORMRAGE, 8000, 396, true},
{11380, "The time has come! The moment is at hand!", AKAMA, 3000, 22, true},
{0, "", AKAMA, 2000, 15, true},
{11466, "You are not prepared!", ILLIDAN_STORMRAGE, 3000, 406, true},
{0, "", EMPTY, 1000, 0, true},
{0, "", EMPTY, 0, 0, false}, // 9
{11476, "Is this it, mortals? Is this all the fury you can muster?", ILLIDAN_STORMRAGE, 8000, 0, true},
{11491, "Their fury pales before mine, Illidan. We have some unsettled business between us.", MAIEV_SHADOWSONG, 8000, 5, true},
{11477, "Maiev... How is this even possible?", ILLIDAN_STORMRAGE, 5000, 1, true},
{11492, "Ah... my long hunt is finally over. Today, Justice will be done!", MAIEV_SHADOWSONG, 8000, 15, true},
{11470, "Feel the hatred of ten thousand years!", ILLIDAN_STORMRAGE, 1000, 0, false}, // 14
{11496, "Ahh... It is finished. You are beaten.", MAIEV_SHADOWSONG, 6000, 0, true}, // 15
{11478, "You have won... Maiev...but the huntress... is nothing...without the hunt... you... are nothing... without me..", ILLIDAN_STORMRAGE, 30000, 65, true}, // Emote dead for now. Kill him later
{11497, "He is right. I feel nothing... I am nothing... Farewell, champions.", MAIEV_SHADOWSONG, 9000, 0, true},
{11498, "", MAIEV_SHADOWSONG, 5000, 0, true},
{11498, "", EMPTY, 1000, 0, true}, // 19 Maiev disappear
{11387, "The Light will fill these dismal halls once again. I swear it.", AKAMA, 8000, 0, true},
{0, "", EMPTY, 1000, 0, false} // 21
};
G3D::Vector3 const HoverPosition[4]=
{
{657.0f, 340.0f, 355.0f},
{657.0f, 275.0f, 355.0f},
{705.0f, 275.0f, 355.0f},
{705.0f, 340.0f, 355.0f}
};
G3D::Vector3 const GlaivePosition[4]=
{
{695.105f, 305.303f, 354.256f},
{659.338f, 305.303f, 354.256f}, // the distance between two glaives is 36
{700.105f, 305.303f, 354.256f},
{664.338f, 305.303f, 354.256f}
};
G3D::Vector3 const EyeBlast[2]=
{
{677.0f, 350.0f, 354.0f}, // start point, pass through glaive point
{677.0f, 260.0f, 354.0f}
};
G3D::Vector3 const AkamaWP[13]=
{
{770.01f, 304.50f, 312.29f}, // Bottom of the first stairs, at the doors
{780.66f, 304.50f, 319.74f}, // Top of the first stairs
{790.13f, 319.68f, 319.76f}, // Bottom of the second stairs (left from the entrance)
{787.17f, 347.38f, 341.42f}, // Top of the second stairs
{781.34f, 350.31f, 341.44f}, // Bottom of the third stairs
{762.60f, 361.06f, 353.60f}, // Top of the third stairs
{756.35f, 360.52f, 353.27f}, // Before the door-thingy
{743.82f, 342.21f, 353.00f}, // Somewhere further
{732.69f, 305.13f, 353.00f}, // In front of Illidan - (8)
{738.11f, 365.44f, 353.00f}, // in front of the door-thingy (the other one!)
{792.18f, 366.62f, 341.42f}, // Down the first flight of stairs
{796.84f, 304.89f, 319.76f}, // Down the second flight of stairs
{782.01f, 304.55f, 319.76f} // Final location - back at the initial gates. This is where he will fight the minions! (12)
};
// 755.762f, 304.0747f, 312.1769f -- This is where Akama should be spawned
G3D::Vector3 const SpiritSpawns[2]=
{
{755.5426f, 309.9156f, 312.2129f},
{755.5426f, 298.7923f, 312.0834f}
};
struct Animation // For the demon transformation
{
uint32 aura, unaura, timer, size, displayid, phase;
bool equip;
};
static const Animation DemonTransformation[10]=
{
{SPELL_DEMON_TRANSFORM_1, 0, 1000, 0, 0, 6, true},
{SPELL_DEMON_TRANSFORM_2, SPELL_DEMON_TRANSFORM_1, 4000, 0, 0, 6, true},
{0, 0, 3000, 1073741824, 21322, 6, false}, // stunned, cannot cast demon form
{SPELL_DEMON_TRANSFORM_3, SPELL_DEMON_TRANSFORM_2, 3500, 0, 0, 6, false},
{SPELL_DEMON_FORM, SPELL_DEMON_TRANSFORM_3, 0, 0, 0, 4, false},
{SPELL_DEMON_TRANSFORM_1, 0, 1000, 0, 0, 6, false},
{SPELL_DEMON_TRANSFORM_2, SPELL_DEMON_TRANSFORM_1, 4000, 0, 0, 6, false},
{0, SPELL_DEMON_FORM, 3000, 1069547520, 21135, 6, false},
{SPELL_DEMON_TRANSFORM_3, SPELL_DEMON_TRANSFORM_2, 3500, 0, 0, 6, true},
{0, SPELL_DEMON_TRANSFORM_3, 0, 0, 0, 8, true}
};
class npc_flame_of_azzinoth : public CreatureScript
{
public:
npc_flame_of_azzinoth() : CreatureScript("npc_flame_of_azzinoth") { }
struct flame_of_azzinothAI : public ScriptedAI
{
flame_of_azzinothAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
}
void Initialize()
{
FlameBlastTimer = 15000;
CheckTimer = 5000;
GlaiveGUID.Clear();
}
void Reset() override
{
Initialize();
}
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
}
void ChargeCheck()
{
Unit* target = SelectTarget(SELECT_TARGET_FARTHEST, 0, 200, false);
if (target && (!me->IsWithinCombatRange(target, FLAME_CHARGE_DISTANCE)))
{
me->AddThreat(target, 5000000.0f);
AttackStart(target);
DoCast(target, SPELL_CHARGE);
Talk(EMOTE_AZZINOTH_GAZE);
}
}
void EnrageCheck()
{
if (Creature* glaive = ObjectAccessor::GetCreature(*me, GlaiveGUID))
{
if (!me->IsWithinDistInMap(glaive, FLAME_ENRAGE_DISTANCE))
{
glaive->InterruptNonMeleeSpells(true);
DoCast(me, SPELL_FLAME_ENRAGE, true);
DoResetThreat();
if (SelectTarget(SELECT_TARGET_RANDOM, 0))
{
me->AddThreat(me->GetVictim(), 5000000.0f);
AttackStart(me->GetVictim());
}
}
else if (!me->HasAura(SPELL_AZZINOTH_CHANNEL))
{
glaive->CastSpell(me, SPELL_AZZINOTH_CHANNEL, false);
me->RemoveAurasDueToSpell(SPELL_FLAME_ENRAGE);
}
}
}
void SetGlaiveGUID(ObjectGuid guid)
{
GlaiveGUID = guid;
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (FlameBlastTimer <= diff)
{
DoCastVictim(SPELL_BLAZE_SUMMON, true); // appear at victim
DoCastVictim(SPELL_FLAME_BLAST);
FlameBlastTimer = 15000; // 10000 is official-like?
DoZoneInCombat(); // in case someone is revived
} else FlameBlastTimer -= diff;
if (CheckTimer <= diff)
{
ChargeCheck();
EnrageCheck();
CheckTimer = 1000;
} else CheckTimer -= diff;
DoMeleeAttackIfReady();
}
private:
uint32 FlameBlastTimer;
uint32 CheckTimer;
ObjectGuid GlaiveGUID;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new flame_of_azzinothAI(creature);
}
};
/************************************** Illidan's AI* **************************************/
class boss_illidan_stormrage : public CreatureScript
{
public:
boss_illidan_stormrage() : CreatureScript("boss_illidan_stormrage") { }
struct boss_illidan_stormrageAI : public BossAI
{
boss_illidan_stormrageAI(Creature* creature) : BossAI(creature, DATA_ILLIDAN_STORMRAGE)
{
Initialize();
DoCast(me, SPELL_DUAL_WIELD, true);
}
void Initialize()
{
MaievGUID.Clear();
for (uint8 i = 0; i < 2; ++i)
{
FlameGUID[i].Clear();
GlaiveGUID[i].Clear();
}
Phase = PHASE_ILLIDAN_NULL;
Event = EVENT_NULL;
Timer[EVENT_BERSERK] = 1500000;
HoverPoint = 0;
TalkCount = 0;
FlightCount = 0;
TransformCount = 0;
}
void Reset() override;
void JustSummoned(Creature* summon) override;
void SummonedCreatureDespawn(Creature* summon) override
{
if (summon->GetCreatureTemplate()->Entry == FLAME_OF_AZZINOTH)
{
for (uint8 i = 0; i < 2; ++i)
if (summon->GetGUID() == FlameGUID[i])
FlameGUID[i].Clear();
if (!FlameGUID[0] && !FlameGUID[1] && Phase != PHASE_ILLIDAN_NULL)
{
me->InterruptNonMeleeSpells(true);
EnterPhase(PHASE_FLIGHT_SEQUENCE);
}
}
summons.Despawn(summon);
}
void MovementInform(uint32 /*MovementType*/, uint32 /*Data*/) override
{
if (FlightCount == 7) // change hover point
{
if (me->GetVictim())
{
me->SetInFront(me->GetVictim());
me->StopMoving();
}
EnterPhase(PHASE_FLIGHT);
}
else // handle flight sequence
Timer[EVENT_FLIGHT_SEQUENCE] = 1000;
}
void EnterCombat(Unit* /*who*/) override
{
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
_EnterCombat();
}
void AttackStart(Unit* who) override
{
if (!who || Phase >= PHASE_TALK_SEQUENCE)
return;
if (Phase == PHASE_FLIGHT || Phase == PHASE_DEMON)
AttackStartNoMove(who);
else
ScriptedAI::AttackStart(who);
}
void MoveInLineOfSight(Unit*) override { }
void JustDied(Unit* /*killer*/) override
{
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
_JustDied();
}
void KilledUnit(Unit* victim) override
{
if (victim->GetTypeId() != TYPEID_PLAYER)
return;
Talk(SAY_ILLIDAN_KILL);
}
void DamageTaken(Unit* done_by, uint32 &damage) override
{
if (damage >= me->GetHealth() && done_by != me)
damage = 0;
if (done_by->GetGUID() == MaievGUID)
done_by->AddThreat(me, -(3*(float)damage)/4); // do not let maiev tank him
}
void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override
{
if (spell->Id == SPELL_GLAIVE_RETURNS) // Re-equip our warglaives!
{
if (!me->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID))
SetEquipmentSlots(false, EQUIP_ID_MAIN_HAND, EQUIP_UNEQUIP, EQUIP_NO_CHANGE);
else
SetEquipmentSlots(false, EQUIP_UNEQUIP, EQUIP_ID_OFF_HAND, EQUIP_NO_CHANGE);
me->SetSheath(SHEATH_STATE_MELEE);
}
}
void DeleteFromThreatList(ObjectGuid TargetGUID)
{
ThreatContainer::StorageType threatlist = me->getThreatManager().getThreatList();
for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr)
{
if ((*itr)->getUnitGuid() == TargetGUID)
{
(*itr)->removeReference();
break;
}
}
}
void Talk(uint32 count)
{
Timer[EVENT_TALK_SEQUENCE] = Conversation[count].timer;
Creature* creature = NULL;
if (Conversation[count].creature == ILLIDAN_STORMRAGE)
creature = me;
else if (Conversation[count].creature == AKAMA)
creature = (ObjectAccessor::GetCreature((*me), AkamaGUID));
else if (Conversation[count].creature == MAIEV_SHADOWSONG)
creature = (ObjectAccessor::GetCreature((*me), MaievGUID));
if (creature)
{
if (Conversation[count].emote)
creature->HandleEmoteCommand(Conversation[count].emote); // Make the Creature do some animation!
if (Conversation[count].text.size())
creature->Yell(Conversation[count].text.c_str(), LANG_UNIVERSAL); // Have the Creature yell out some text
if (Conversation[count].sound)
DoPlaySoundToSet(creature, Conversation[count].sound); // Play some sound on the creature
}
}
void EnterPhase(PhaseIllidan NextPhase)
{
DoZoneInCombat();
switch (NextPhase)
{
case PHASE_NORMAL:
case PHASE_NORMAL_2:
case PHASE_NORMAL_MAIEV:
AttackStart(me->GetVictim());
Timer[EVENT_TAUNT] = 32000;
Timer[EVENT_SHEAR] = urand(10, 25) * 1000;
Timer[EVENT_FLAME_CRASH] = 20000;
Timer[EVENT_PARASITIC_SHADOWFIEND] = 25000;
Timer[EVENT_PARASITE_CHECK] = 0;
Timer[EVENT_DRAW_SOUL] = 30000;
if (NextPhase == PHASE_NORMAL)
break;
Timer[EVENT_AGONIZING_FLAMES] = 35000;
Timer[EVENT_TRANSFORM_NORMAL] = 60000;
if (NextPhase == PHASE_NORMAL_2)
break;
Timer[EVENT_ENRAGE] = urand(30, 40) * 1000;
break;
case PHASE_FLIGHT:
Timer[EVENT_FIREBALL] = 1000;
if (!(rand32() % 4))
Timer[EVENT_DARK_BARRAGE] = 10000;
Timer[EVENT_EYE_BLAST] = urand(10, 25) * 1000;
Timer[EVENT_MOVE_POINT] = urand(20, 40) * 1000;
break;
case PHASE_DEMON:
Timer[EVENT_SHADOW_BLAST] = 1000;
Timer[EVENT_FLAME_BURST] = 10000;
Timer[EVENT_SHADOWDEMON] = 30000;
Timer[EVENT_TRANSFORM_DEMON] = 60000;
AttackStart(me->GetVictim());
break;
case PHASE_TALK_SEQUENCE:
Timer[EVENT_TALK_SEQUENCE] = 100;
me->RemoveAllAuras();
me->InterruptNonMeleeSpells(false);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE);
me->GetMotionMaster()->Clear(false);
me->AttackStop();
break;
case PHASE_FLIGHT_SEQUENCE:
if (Phase == PHASE_NORMAL) // lift off
{
FlightCount = 1;
Timer[EVENT_FLIGHT_SEQUENCE] = 1;
me->RemoveAllAuras();
me->InterruptNonMeleeSpells(false);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->GetMotionMaster()->Clear(false);
me->AttackStop();
}
else // land
Timer[EVENT_FLIGHT_SEQUENCE] = 2000;
break;
case PHASE_TRANSFORM_SEQUENCE:
if (Phase == PHASE_DEMON)
Timer[EVENT_TRANSFORM_SEQUENCE] = 500;
else
{
TransformCount = 0;
Timer[EVENT_TRANSFORM_SEQUENCE] = 500;
Talk(SAY_ILLIDAN_MORPH);
}
me->GetMotionMaster()->Clear();
me->AttackStop();
break;
default:
break;
}
if (MaievGUID)
{
if (Creature* maiev = ObjectAccessor::GetCreature(*me, MaievGUID))
if (maiev->IsAlive())
maiev->AI()->DoAction(NextPhase);
}
Phase = NextPhase;
Event = EVENT_NULL;
}
void CastEyeBlast()
{
me->InterruptNonMeleeSpells(false);
Talk(SAY_ILLIDAN_EYE_BLAST);
float distx, disty, dist[2];
for (uint8 i = 0; i < 2; ++i)
{
distx = EyeBlast[i].x - HoverPosition[HoverPoint].x;
disty = EyeBlast[i].y - HoverPosition[HoverPoint].y;
dist[i] = distx * distx + disty * disty;
}
G3D::Vector3 initial = EyeBlast[dist[0] < dist[1] ? 0 : 1];
for (uint8 i = 0; i < 2; ++i)
{
distx = GlaivePosition[i].x - HoverPosition[HoverPoint].x;
disty = GlaivePosition[i].y - HoverPosition[HoverPoint].y;
dist[i] = distx * distx + disty * disty;
}
G3D::Vector3 final = GlaivePosition[dist[0] < dist[1] ? 0 : 1];
final.x = 2 * final.x - initial.x;
final.y = 2 * final.y - initial.y;
Creature* Trigger = me->SummonCreature(23069, initial.x, initial.y, initial.z, 0, TEMPSUMMON_TIMED_DESPAWN, 13000);
if (!Trigger)
return;
Trigger->SetSpeedRate(MOVE_WALK, 3);
Trigger->SetWalk(true);
Trigger->GetMotionMaster()->MovePoint(0, final.x, final.y, final.z);
// Trigger->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetTarget(Trigger->GetGUID());
DoCast(Trigger, SPELL_EYE_BLAST);
}
void SummonFlamesOfAzzinoth()
{
Talk(SAY_ILLIDAN_SUMMONFLAMES);
for (uint8 i = 0; i < 2; ++i)
{
if (Creature* glaive = ObjectAccessor::GetCreature(*me, GlaiveGUID[i]))
{
if (Creature* flame = me->SummonCreature(FLAME_OF_AZZINOTH, GlaivePosition[i+2].x, GlaivePosition[i+2].y, GlaivePosition[i+2].z, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 5000))
{
flame->setFaction(me->getFaction()); // Just in case the database has it as a different faction
flame->SetMeleeDamageSchool(SPELL_SCHOOL_FIRE);
FlameGUID[i] = flame->GetGUID(); // Record GUID in order to check if they're dead later on to move to the next phase
ENSURE_AI(npc_flame_of_azzinoth::flame_of_azzinothAI, flame->AI())->SetGlaiveGUID(GlaiveGUID[i]);
glaive->CastSpell(flame, SPELL_AZZINOTH_CHANNEL, false); // Glaives do some random Beam type channel on it.
}
}
}
}
void SummonMaiev()
{
DoCast(me, SPELL_SHADOW_PRISON, true);
DoCast(me, SPELL_SUMMON_MAIEV, true);
if (!MaievGUID) // If Maiev cannot be summoned, reset the encounter and post some errors to the console.
{
EnterEvadeMode();
TC_LOG_ERROR("scripts", "SD2 ERROR: Unable to summon Maiev Shadowsong (entry: 23197). Check your database to see if you have the proper SQL for Maiev Shadowsong (entry: 23197)");
}
}
void HandleTalkSequence();
void HandleFlightSequence()
{
switch (FlightCount)
{
case 1: // lift off
me->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF);
me->SetDisableGravity(true);
me->StopMoving();
Talk(SAY_ILLIDAN_TAKEOFF);
Timer[EVENT_FLIGHT_SEQUENCE] = 3000;
break;
case 2: // move to center
me->GetMotionMaster()->MovePoint(0, CENTER_X + 5, CENTER_Y, CENTER_Z); // +5, for SPELL_THROW_GLAIVE bug
Timer[EVENT_FLIGHT_SEQUENCE] = 0;
break;
case 3: // throw one glaive
{
uint8 i=1;
Creature* Glaive = me->SummonCreature(BLADE_OF_AZZINOTH, GlaivePosition[i].x, GlaivePosition[i].y, GlaivePosition[i].z, 0, TEMPSUMMON_CORPSE_DESPAWN, 0);
if (Glaive)
{
GlaiveGUID[i] = Glaive->GetGUID();
Glaive->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
Glaive->SetDisplayId(MODEL_INVISIBLE);
Glaive->setFaction(me->getFaction());
DoCast(Glaive, SPELL_THROW_GLAIVE2);
}
}
Timer[EVENT_FLIGHT_SEQUENCE] = 700;
break;
case 4: // throw another
SetEquipmentSlots(false, EQUIP_UNEQUIP, EQUIP_UNEQUIP, EQUIP_NO_CHANGE);
{
uint8 i=0;
Creature* Glaive = me->SummonCreature(BLADE_OF_AZZINOTH, GlaivePosition[i].x, GlaivePosition[i].y, GlaivePosition[i].z, 0, TEMPSUMMON_CORPSE_DESPAWN, 0);
if (Glaive)
{
GlaiveGUID[i] = Glaive->GetGUID();
Glaive->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
Glaive->SetDisplayId(MODEL_INVISIBLE);
Glaive->setFaction(me->getFaction());
DoCast(Glaive, SPELL_THROW_GLAIVE, true);
}
}
Timer[EVENT_FLIGHT_SEQUENCE] = 5000;
break;
case 5: // summon flames
SummonFlamesOfAzzinoth();
Timer[EVENT_FLIGHT_SEQUENCE] = 3000;
break;
case 6: // fly to hover point
me->GetMotionMaster()->MovePoint(0, HoverPosition[HoverPoint].x, HoverPosition[HoverPoint].y, HoverPosition[HoverPoint].z);
Timer[EVENT_FLIGHT_SEQUENCE] = 0;
break;
case 7: // return to center
me->GetMotionMaster()->MovePoint(0, CENTER_X, CENTER_Y, CENTER_Z);
Timer[EVENT_FLIGHT_SEQUENCE] = 0;
break;
case 8: // glaive return
for (uint8 i = 0; i < 2; ++i)
{
if (GlaiveGUID[i])
{
Unit* Glaive = ObjectAccessor::GetUnit(*me, GlaiveGUID[i]);
if (Glaive)
{
Glaive->CastSpell(me, SPELL_GLAIVE_RETURNS, false); // Make it look like the Glaive flies back up to us
Glaive->SetDisplayId(MODEL_INVISIBLE); // disappear but not die for now
}
}
}
Timer[EVENT_FLIGHT_SEQUENCE] = 2000;
break;
case 9: // land
me->SetDisableGravity(false);
me->StopMoving();
me->HandleEmoteCommand(EMOTE_ONESHOT_LAND);
for (uint8 i = 0; i < 2; ++i)
{
if (GlaiveGUID[i])
{
if (Creature* glaive = ObjectAccessor::GetCreature(*me, GlaiveGUID[i]))
glaive->DespawnOrUnsummon();
GlaiveGUID[i].Clear();
}
}
Timer[EVENT_FLIGHT_SEQUENCE] = 2000;
break;
case 10: // attack
DoResetThreat();
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE + UNIT_FLAG_NOT_SELECTABLE);
me->SetSheath(SHEATH_STATE_MELEE);
EnterPhase(PHASE_NORMAL_2);
break;
default:
break;
}
++FlightCount;
}
void HandleTransformSequence()
{
if (DemonTransformation[TransformCount].unaura)
me->RemoveAurasDueToSpell(DemonTransformation[TransformCount].unaura);
if (DemonTransformation[TransformCount].aura)
DoCast(me, DemonTransformation[TransformCount].aura, true);
if (DemonTransformation[TransformCount].displayid)
me->SetDisplayId(DemonTransformation[TransformCount].displayid); // It's morphin time!
if (DemonTransformation[TransformCount].equip)
{
// Requip warglaives if needed
SetEquipmentSlots(false, EQUIP_ID_MAIN_HAND, EQUIP_ID_OFF_HAND, EQUIP_NO_CHANGE);
me->SetSheath(SHEATH_STATE_MELEE);
}
else
{
// Unequip warglaives if needed
SetEquipmentSlots(false, EQUIP_UNEQUIP, EQUIP_UNEQUIP, EQUIP_NO_CHANGE);
}
switch (TransformCount)
{
case 2:
DoResetThreat();
break;
case 4:
EnterPhase(PHASE_DEMON);
break;
case 7:
DoResetThreat();
break;
case 9:
if (MaievGUID)
EnterPhase(PHASE_NORMAL_MAIEV); // Depending on whether we summoned Maiev, we switch to either phase 5 or 3
else
EnterPhase(PHASE_NORMAL_2);
break;
default:
break;
}
if (Phase == PHASE_TRANSFORM_SEQUENCE)
Timer[EVENT_TRANSFORM_SEQUENCE] = DemonTransformation[TransformCount].timer;
++TransformCount;
}
void UpdateAI(uint32 diff) override
{
if ((!UpdateVictim()) && Phase < PHASE_TALK_SEQUENCE)
return;
Event = EVENT_NULL;
for (int32 i = 1; i <= MaxTimer[Phase]; ++i)
{
if (Timer[i]) // Event is enabled
{
if (Timer[i] <= diff)
{
if (!Event) // No event with higher priority
Event = (EventIllidan)i;
}
else Timer[i] -= diff;
}
}
switch (Phase)
{
case PHASE_NORMAL:
if (HealthBelowPct(65))
EnterPhase(PHASE_FLIGHT_SEQUENCE);
break;
case PHASE_NORMAL_2:
if (HealthBelowPct(30))
EnterPhase(PHASE_TALK_SEQUENCE);
break;
case PHASE_NORMAL_MAIEV:
if (HealthBelowPct(1))
EnterPhase(PHASE_TALK_SEQUENCE);
break;
case PHASE_TALK_SEQUENCE:
if (Event == EVENT_TALK_SEQUENCE)
HandleTalkSequence();
break;
case PHASE_FLIGHT_SEQUENCE:
if (Event == EVENT_FLIGHT_SEQUENCE)
HandleFlightSequence();
break;
case PHASE_TRANSFORM_SEQUENCE:
if (Event == EVENT_TRANSFORM_SEQUENCE)
HandleTransformSequence();
break;
default:
break;
}
if (me->IsNonMeleeSpellCast(false))
return;
if (Phase == PHASE_NORMAL || Phase == PHASE_NORMAL_2 || (Phase == PHASE_NORMAL_MAIEV && !me->HasAura(SPELL_CAGED)))
{
switch (Event)
{
// PHASE_NORMAL
case EVENT_BERSERK:
Talk(SAY_ILLIDAN_ENRAGE);
DoCast(me, SPELL_BERSERK, true);
Timer[EVENT_BERSERK] = 5000; // The buff actually lasts forever.
break;
case EVENT_TAUNT:
Talk(SAY_ILLIDAN_TAUNT);
Timer[EVENT_TAUNT] = urand(25000, 35000);
break;
case EVENT_SHEAR:
// no longer exists in 3.0f.2
// DoCastVictim(SPELL_SHEAR);
Timer[EVENT_SHEAR] = 25000 + (rand32() % 16 * 1000);
break;
case EVENT_FLAME_CRASH:
DoCastVictim(SPELL_FLAME_CRASH);
Timer[EVENT_FLAME_CRASH] = urand(30000, 40000);
break;
case EVENT_PARASITIC_SHADOWFIEND:
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 200, true))
DoCast(target, SPELL_PARASITIC_SHADOWFIEND, true);
Timer[EVENT_PARASITIC_SHADOWFIEND] = urand(35000, 45000);
}
break;
case EVENT_PARASITE_CHECK:
Timer[EVENT_PARASITE_CHECK] = 0;
break;
case EVENT_DRAW_SOUL:
DoCastVictim(SPELL_DRAW_SOUL);
Timer[EVENT_DRAW_SOUL] = urand(50000, 60000);
break;
// PHASE_NORMAL_2
case EVENT_AGONIZING_FLAMES:
DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_AGONIZING_FLAMES);
Timer[EVENT_AGONIZING_FLAMES] = 0;
break;
case EVENT_TRANSFORM_NORMAL:
EnterPhase(PHASE_TRANSFORM_SEQUENCE);
break;
// PHASE_NORMAL_MAIEV
case EVENT_ENRAGE:
DoCast(me, SPELL_ENRAGE);
Timer[EVENT_ENRAGE] = 0;
break;
default:
break;
}
DoMeleeAttackIfReady();
}
if (Phase == PHASE_FLIGHT)
{
switch (Event)
{
case EVENT_FIREBALL:
DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_FIREBALL);
Timer[EVENT_FIREBALL] = 3000;
break;
case EVENT_DARK_BARRAGE:
DoCast(SelectTarget(SELECT_TARGET_RANDOM, 0), SPELL_DARK_BARRAGE);
Timer[EVENT_DARK_BARRAGE] = 0;
break;
case EVENT_EYE_BLAST:
CastEyeBlast();
Timer[EVENT_EYE_BLAST] = 0;
break;
case EVENT_MOVE_POINT:
Phase = PHASE_FLIGHT_SEQUENCE;
Timer[EVENT_FLIGHT_SEQUENCE] = 0; // do not start Event when changing hover point
HoverPoint += (rand32() % 3 + 1);
if (HoverPoint > 3)
HoverPoint -= 4;
me->GetMotionMaster()->MovePoint(0, HoverPosition[HoverPoint].x, HoverPosition[HoverPoint].y, HoverPosition[HoverPoint].z);
break;
default:
break;
}
}
if (Phase == PHASE_DEMON)
{
switch (Event)
{
case EVENT_SHADOW_BLAST:
me->GetMotionMaster()->Clear(false);
if (me->GetVictim() && (!me->IsWithinDistInMap(me->GetVictim(), 50) || !me->IsWithinLOSInMap(me->GetVictim())))
me->GetMotionMaster()->MoveChase(me->GetVictim(), 30);
else
me->GetMotionMaster()->MoveIdle();
DoCastVictim(SPELL_SHADOW_BLAST);
Timer[EVENT_SHADOW_BLAST] = 4000;
break;
case EVENT_SHADOWDEMON:
DoCast(me, SPELL_SUMMON_SHADOWDEMON);
Timer[EVENT_SHADOWDEMON] = 0;
Timer[EVENT_FLAME_BURST] += 10000;
break;
case EVENT_FLAME_BURST:
DoCast(me, SPELL_FLAME_BURST);
Timer[EVENT_FLAME_BURST] = 15000;
break;
case EVENT_TRANSFORM_DEMON:
EnterPhase(PHASE_TRANSFORM_SEQUENCE);
break;
default:
break;
}
}
}
public:
ObjectGuid AkamaGUID;
uint32 Timer[EVENT_ENRAGE + 1];
PhaseIllidan Phase;
private:
EventIllidan Event;
uint32 TalkCount;
uint32 TransformCount;
uint32 FlightCount;
uint32 HoverPoint;
ObjectGuid MaievGUID;
ObjectGuid FlameGUID[2];
ObjectGuid GlaiveGUID[2];
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<boss_illidan_stormrageAI>(creature);
}
};
/********************************** End of Illidan AI* *****************************************/
/******* Functions and vars for Maiev's AI* *****/
class boss_maiev_shadowsong : public CreatureScript
{
public:
boss_maiev_shadowsong() : CreatureScript("boss_maiev_shadowsong") { }
struct boss_maievAI : public ScriptedAI
{
boss_maievAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
}
void Initialize()
{
MaxTimer = 0;
Phase = PHASE_NORMAL_MAIEV;
IllidanGUID.Clear();
Timer[EVENT_MAIEV_STEALTH] = 0;
Timer[EVENT_MAIEV_TAUNT] = urand(22, 43) * 1000;
Timer[EVENT_MAIEV_SHADOW_STRIKE] = 30000;
}
void Reset() override
{
Initialize();
SetEquipmentSlots(false, EQUIP_ID_MAIN_HAND_MAIEV, EQUIP_UNEQUIP, EQUIP_NO_CHANGE);
me->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2, 45738);
}
void EnterCombat(Unit* /*who*/) override { }
void MoveInLineOfSight(Unit* /*who*/) override { }
void EnterEvadeMode(EvadeReason /*why*/) override { }
void GetIllidanGUID(ObjectGuid guid)
{
IllidanGUID = guid;
}
void DamageTaken(Unit* done_by, uint32 &damage) override
{
if (done_by->GetGUID() != IllidanGUID)
damage = 0;
else
{
if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID))
if (illidan->GetVictim() == me)
damage = me->CountPctFromMaxHealth(10);
if (damage >= me->GetHealth())
damage = 0;
}
}
void AttackStart(Unit* who) override
{
if (!who || Timer[EVENT_MAIEV_STEALTH])
return;
if (Phase == PHASE_TALK_SEQUENCE)
AttackStartNoMove(who);
else if (Phase == PHASE_DEMON || Phase == PHASE_TRANSFORM_SEQUENCE)
{
if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID))
if (me->IsWithinDistInMap(illidan, 25))
BlinkToPlayer(); // Do not let dread aura hurt her.
AttackStartNoMove(who);
}
else
ScriptedAI::AttackStart(who);
}
void DoAction(int32 param) override
{
if (param > PHASE_ILLIDAN_NULL && param < PHASE_ILLIDAN_MAX)
EnterPhase(PhaseIllidan(param));
}
void EnterPhase(PhaseIllidan NextPhase) // This is in fact Illidan's phase.
{
switch (NextPhase)
{
case PHASE_TALK_SEQUENCE:
if (Timer[EVENT_MAIEV_STEALTH])
{
me->SetFullHealth();
me->SetVisible(true);
Timer[EVENT_MAIEV_STEALTH] = 0;
}
me->InterruptNonMeleeSpells(false);
me->GetMotionMaster()->Clear(false);
me->AttackStop();
me->SetTarget(IllidanGUID);
MaxTimer = 0;
break;
case PHASE_TRANSFORM_SEQUENCE:
MaxTimer = 4;
Timer[EVENT_MAIEV_TAUNT] += 10000;
Timer[EVENT_MAIEV_THROW_DAGGER] = 2000;
break;
case PHASE_DEMON:
break;
case PHASE_NORMAL_MAIEV:
MaxTimer = 4;
Timer[EVENT_MAIEV_TAUNT] += 10000;
Timer[EVENT_MAIEV_TRAP] = 22000;
break;
default:
break;
}
if (Timer[EVENT_MAIEV_STEALTH])
MaxTimer = 1;
Phase = NextPhase;
}
void BlinkTo(float x, float y, float z)
{
me->AttackStop();
me->InterruptNonMeleeSpells(false);
me->GetMotionMaster()->Clear(false);
DoTeleportTo(x, y, z);
DoCast(me, SPELL_TELEPORT_VISUAL, true);
}
void BlinkToPlayer()
{
if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID))
{
Unit* target = illidan->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0);
if (!target || !me->IsWithinDistInMap(target, 80) || illidan->IsWithinDistInMap(target, 20))
{
uint8 pos = rand32() % 4;
BlinkTo(HoverPosition[pos].x, HoverPosition[pos].y, HoverPosition[pos].z);
}
else
{
float x, y, z;
target->GetPosition(x, y, z);
BlinkTo(x, y, z);
}
}
}
void UpdateAI(uint32 diff) override
{
if ((!UpdateVictim())
&& !Timer[EVENT_MAIEV_STEALTH])
return;
EventMaiev Event = EVENT_MAIEV_NULL;
for (uint8 i = 1; i <= MaxTimer; ++i)
{
if (Timer[i])
{
if (Timer[i] <= diff)
Event = (EventMaiev)i;
else Timer[i] -= diff;
}
}
switch (Event)
{
case EVENT_MAIEV_STEALTH:
{
me->SetFullHealth();
me->SetVisible(true);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
Timer[EVENT_MAIEV_STEALTH] = 0;
BlinkToPlayer();
EnterPhase(Phase);
}
break;
case EVENT_MAIEV_TAUNT:
Talk(SAY_MAIEV_SHADOWSONG_TAUNT);
Timer[EVENT_MAIEV_TAUNT] = urand(22, 43) * 1000;
break;
case EVENT_MAIEV_SHADOW_STRIKE:
DoCastVictim(SPELL_SHADOW_STRIKE);
Timer[EVENT_MAIEV_SHADOW_STRIKE] = 60000;
break;
case EVENT_MAIEV_TRAP:
if (Phase == PHASE_NORMAL_MAIEV)
{
BlinkToPlayer();
DoCast(me, SPELL_CAGE_TRAP_SUMMON);
Timer[EVENT_MAIEV_TRAP] = 22000;
}
else
{
if (!me->IsWithinDistInMap(me->GetVictim(), 40))
me->GetMotionMaster()->MoveChase(me->GetVictim(), 30);
DoCastVictim(SPELL_THROW_DAGGER);
Timer[EVENT_MAIEV_THROW_DAGGER] = 2000;
}
break;
default:
break;
}
if (HealthBelowPct(50))
{
me->SetVisible(false);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID))
ENSURE_AI(boss_illidan_stormrage::boss_illidan_stormrageAI, illidan->AI())->DeleteFromThreatList(me->GetGUID());
me->AttackStop();
Timer[EVENT_MAIEV_STEALTH] = 60000; // reappear after 1 minute
MaxTimer = 1;
}
if (Phase == PHASE_NORMAL_MAIEV)
DoMeleeAttackIfReady();
}
private:
ObjectGuid IllidanGUID;
PhaseIllidan Phase;
uint32 Timer[5];
uint32 MaxTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_maievAI(creature);
}
};
/******* Functions and vars for Akama's AI* *****/
class npc_akama_illidan : public CreatureScript
{
public:
npc_akama_illidan() : CreatureScript("npc_akama_illidan") { }
struct npc_akama_illidanAI : public ScriptedAI
{
npc_akama_illidanAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
JustCreated = true;
}
void Initialize()
{
ChannelGUID.Clear();
SpiritGUID[0].Clear();
SpiritGUID[1].Clear();
Phase = PHASE_AKAMA_NULL;
Timer = 0;
ChannelCount = 0;
TalkCount = 0;
Check_Timer = 5000;
WalkCount = 0;
}
void Reset() override
{
Initialize();
instance->SetBossState(DATA_ILLIDAN_STORMRAGE, NOT_STARTED);
IllidanGUID = instance->GetGuidData(DATA_ILLIDAN_STORMRAGE);
GateGUID = instance->GetGuidData(DATA_GO_ILLIDAN_GATE);
if (JustCreated) // close all doors at create
instance->HandleGameObject(GateGUID, false);
else // open all doors, raid wiped
{
instance->HandleGameObject(GateGUID, true);
WalkCount = 1; // skip first wp
}
KillAllElites();
me->SetUInt32Value(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_NONE); // Database sometimes has strange values..
me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
me->setActive(false);
me->SetVisible(false);
}
// Do not call reset in Akama's evade mode, as this will stop him from summoning minions after he kills the first bit
void EnterEvadeMode(EvadeReason /*why*/) override
{
me->RemoveAllAuras();
me->DeleteThreatList();
me->CombatStop(true);
}
void EnterCombat(Unit* /*who*/) override { }
void MoveInLineOfSight(Unit* /*who*/) override { }
void MovementInform(uint32 MovementType, uint32 /*Data*/) override
{
if (MovementType == POINT_MOTION_TYPE)
Timer = 1;
}
void DamageTaken(Unit* done_by, uint32 &damage) override
{
if (damage > me->GetHealth() || done_by->GetGUID() != IllidanGUID)
damage = 0;
}
void KillAllElites()
{
ThreatContainer::StorageType const &threatList = me->getThreatManager().getThreatList();
std::vector<Unit*> eliteList;
for (ThreatContainer::StorageType::const_iterator itr = threatList.begin(); itr != threatList.end(); ++itr)
{
Unit* unit = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid());
if (unit && unit->GetEntry() == ILLIDARI_ELITE)
eliteList.push_back(unit);
}
for (std::vector<Unit*>::const_iterator itr = eliteList.begin(); itr != eliteList.end(); ++itr)
(*itr)->setDeathState(JUST_DIED);
EnterEvadeMode(EVADE_REASON_OTHER);
}
void BeginTalk()
{
if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID))
{
illidan->RemoveAurasDueToSpell(SPELL_KNEEL);
me->SetInFront(illidan);
illidan->SetInFront(me);
me->GetMotionMaster()->MoveIdle();
illidan->GetMotionMaster()->MoveIdle();
ENSURE_AI(boss_illidan_stormrage::boss_illidan_stormrageAI, illidan->AI())->AkamaGUID = me->GetGUID();
ENSURE_AI(boss_illidan_stormrage::boss_illidan_stormrageAI, illidan->AI())->EnterPhase(PHASE_TALK_SEQUENCE);
}
}
void BeginChannel()
{
me->setActive(true);
me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
if (!JustCreated)
return;
float x, y, z;
if (GameObject* gate = ObjectAccessor::GetGameObject(*me, GateGUID))
gate->GetPosition(x, y, z);
else
return; // if door not spawned, don't crash server
if (Creature* Channel = me->SummonCreature(ILLIDAN_DOOR_TRIGGER, x, y, z+5, 0, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 360000))
{
ChannelGUID = Channel->GetGUID();
Channel->SetDisplayId(MODEL_INVISIBLE); // Invisible but spell visuals can still be seen.
DoCast(Channel, SPELL_AKAMA_DOOR_FAIL);
}
for (uint8 i = 0; i < 2; ++i)
if (Creature* Spirit = me->SummonCreature(i ? SPIRIT_OF_OLUM : SPIRIT_OF_UDALO, SpiritSpawns[i].x, SpiritSpawns[i].y, SpiritSpawns[i].z, 0, TEMPSUMMON_TIMED_DESPAWN, 20000))
{
Spirit->SetVisible(false);
SpiritGUID[i] = Spirit->GetGUID();
}
}
void BeginWalk()
{
me->SetWalk(false);
me->SetSpeedRate(MOVE_RUN, 1.0f);
me->GetMotionMaster()->MovePoint(0, AkamaWP[WalkCount].x, AkamaWP[WalkCount].y, AkamaWP[WalkCount].z);
}
void EnterPhase(PhaseAkama NextPhase)
{
switch (NextPhase)
{
case PHASE_CHANNEL:
BeginChannel();
Timer = 5000;
ChannelCount = 0;
break;
case PHASE_WALK:
if (Phase == PHASE_CHANNEL)
WalkCount = 0;
else if (Phase == PHASE_TALK)
{
if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID))
ENSURE_AI(boss_illidan_stormrage::boss_illidan_stormrageAI, illidan->AI())->DeleteFromThreatList(me->GetGUID());
EnterEvadeMode(EVADE_REASON_OTHER);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
++WalkCount;
}
JustCreated = false;
BeginWalk();
Timer = 0;
break;
case PHASE_TALK:
if (Phase == PHASE_WALK)
{
BeginTalk();
Timer = 0;
}
else if (Phase == PHASE_FIGHT_ILLIDAN)
{
Timer = 1;
TalkCount = 0;
}
break;
case PHASE_FIGHT_ILLIDAN:
if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID))
{
me->AddThreat(illidan, 10000000.0f);
me->GetMotionMaster()->MoveChase(illidan);
}
Timer = 30000; // chain lightning
break;
case PHASE_FIGHT_MINIONS:
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
Timer = urand(10000, 16000); // summon minion
break;
case PHASE_RETURN:
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
KillAllElites();
WalkCount = 0;
BeginWalk();
Timer = 1;
break;
default:
break;
}
Phase = NextPhase;
}
void HandleTalkSequence()
{
switch (TalkCount)
{
case 0:
if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID))
{
ENSURE_AI(boss_illidan_stormrage::boss_illidan_stormrageAI, illidan->AI())->Timer[EVENT_TAUNT] += 30000;
illidan->AI()->Talk(SAY_ILLIDAN_MINION);
}
Timer = 8000;
break;
case 1:
Talk(SAY_AKAMA_LEAVE);
Timer = 3000;
break;
case 2:
EnterPhase(PHASE_WALK);
break;
}
++TalkCount;
}
void HandleChannelSequence()
{
Unit* Channel = NULL;
Unit* Spirit[2] = { NULL, NULL };
if (ChannelCount <= 5)
{
Channel = ObjectAccessor::GetUnit(*me, ChannelGUID);
Spirit[0] = ObjectAccessor::GetUnit(*me, SpiritGUID[0]);
Spirit[1] = ObjectAccessor::GetUnit(*me, SpiritGUID[1]);
if (!Channel || !Spirit[0] || !Spirit[1])
return;
}
switch (ChannelCount)
{
case 0: // channel failed
me->InterruptNonMeleeSpells(true);
Timer = 2000;
break;
case 1: // spirit appear
Spirit[0]->SetVisible(true);
Spirit[1]->SetVisible(true);
Timer = 2000;
break;
case 2: // spirit help
DoCast(Channel, SPELL_AKAMA_DOOR_CHANNEL);
Spirit[0]->CastSpell(Channel, SPELL_DEATHSWORN_DOOR_CHANNEL, false);
Spirit[1]->CastSpell(Channel, SPELL_DEATHSWORN_DOOR_CHANNEL, false);
Timer = 5000;
break;
case 3: // open the gate
me->InterruptNonMeleeSpells(true);
Spirit[0]->InterruptNonMeleeSpells(true);
Spirit[1]->InterruptNonMeleeSpells(true);
instance->HandleGameObject(GateGUID, true);
Timer = 2000;
break;
case 4:
me->HandleEmoteCommand(EMOTE_ONESHOT_SALUTE);
Timer = 2000;
break;
case 5:
Talk(SAY_AKAMA_BEWARE);
Channel->setDeathState(JUST_DIED);
Spirit[0]->SetVisible(false);
Spirit[1]->SetVisible(false);
Timer = 3000;
break;
case 6:
EnterPhase(PHASE_WALK);
break;
default:
break;
}
++ChannelCount;
}
void HandleWalkSequence()
{
switch (WalkCount)
{
case 8:
if (Phase == PHASE_WALK)
EnterPhase(PHASE_TALK);
else
EnterPhase(PHASE_FIGHT_ILLIDAN);
break;
case 12:
EnterPhase(PHASE_FIGHT_MINIONS);
break;
}
if (Phase == PHASE_WALK)
{
Timer = 0;
++WalkCount;
me->GetMotionMaster()->MovePoint(WalkCount, AkamaWP[WalkCount].x, AkamaWP[WalkCount].y, AkamaWP[WalkCount].z);
}
}
void UpdateAI(uint32 diff) override
{
if (!me->IsVisible())
{
if (Check_Timer <= diff)
{
if (instance->GetBossState(DATA_ILLIDARI_COUNCIL) == DONE)
me->SetVisible(true);
Check_Timer = 5000;
} else Check_Timer -= diff;
}
bool Event = false;
if (Timer)
{
if (Timer <= diff)
Event = true;
else Timer -= diff;
}
if (Event)
{
switch (Phase)
{
case PHASE_CHANNEL:
if (JustCreated)
HandleChannelSequence();
else{
EnterPhase(PHASE_WALK);
}
break;
case PHASE_TALK:
HandleTalkSequence();
break;
case PHASE_WALK:
case PHASE_RETURN:
HandleWalkSequence();
break;
case PHASE_FIGHT_ILLIDAN:
{
Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID);
if (illidan && illidan->HealthBelowPct(90))
EnterPhase(PHASE_TALK);
else
{
DoCastVictim(SPELL_CHAIN_LIGHTNING);
Timer = 30000;
}
}
break;
case PHASE_FIGHT_MINIONS:
{
float x, y, z;
me->GetPosition(x, y, z);
Creature* Elite = me->SummonCreature(ILLIDARI_ELITE, x + rand32() % 10, y + rand32() % 10, z, 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 30000);
// Creature* Elite = me->SummonCreature(ILLIDARI_ELITE, x, y, z, 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 30000);
if (Elite)
{
Elite->AI()->AttackStart(me);
Elite->AddThreat(me, 1000000.0f);
AttackStart(Elite);
me->AddThreat(Elite, 1000000.0f);
}
Timer = urand(10000, 16000);
if (Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID))
if (illidan->HealthBelowPct(10))
EnterPhase(PHASE_RETURN);
}
break;
default:
break;
}
}
if (!UpdateVictim())
return;
if (HealthBelowPct(20))
DoCast(me, SPELL_HEALING_POTION);
DoMeleeAttackIfReady();
}
void sGossipSelect(Player* player, uint32 /*menuId*/, uint32 /*gossipListId*/) override
{
CloseGossipMenuFor(player);
EnterPhase(PHASE_CHANNEL);
}
private:
bool JustCreated;
InstanceScript* instance;
PhaseAkama Phase;
uint32 Timer;
ObjectGuid IllidanGUID;
ObjectGuid ChannelGUID;
ObjectGuid SpiritGUID[2];
ObjectGuid GateGUID;
uint32 ChannelCount;
uint32 WalkCount;
uint32 TalkCount;
uint32 Check_Timer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_akama_illidanAI>(creature);
}
};
void boss_illidan_stormrage::boss_illidan_stormrageAI::Reset()
{
_Reset();
if (Creature* akama = ObjectAccessor::GetCreature(*me, AkamaGUID))
{
if (!akama->IsAlive())
akama->Respawn();
else
akama->AI()->EnterEvadeMode();
}
Initialize();
me->SetDisplayId(MODEL_ILLIDAN);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
SetEquipmentSlots(false, EQUIP_UNEQUIP, EQUIP_UNEQUIP, EQUIP_NO_CHANGE);
me->SetDisableGravity(false);
me->setActive(false);
}
void boss_illidan_stormrage::boss_illidan_stormrageAI::JustSummoned(Creature* summon)
{
summons.Summon(summon);
switch (summon->GetEntry())
{
case PARASITIC_SHADOWFIEND:
{
if (Phase == PHASE_TALK_SEQUENCE)
{
summon->SetVisible(false);
summon->setDeathState(JUST_DIED);
return;
}
Unit* target = SelectTarget(SELECT_TARGET_TOPAGGRO, 0, 999, true);
if (!target || target->HasAura(SPELL_PARASITIC_SHADOWFIEND)
|| target->HasAura(SPELL_PARASITIC_SHADOWFIEND2))
target = SelectTarget(SELECT_TARGET_RANDOM, 0, 999, true);
if (target)
summon->AI()->AttackStart(target);
}
break;
case SHADOW_DEMON:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 999, true)) // only on players.
{
summon->AddThreat(target, 5000000.0f);
summon->AI()->AttackStart(target);
}
break;
case MAIEV_SHADOWSONG:
{
summon->SetVisible(false); // Leave her invisible until she has to talk
summon->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
MaievGUID = summon->GetGUID();
ENSURE_AI(boss_maiev_shadowsong::boss_maievAI, summon->AI())->GetIllidanGUID(me->GetGUID());
summon->AI()->DoAction(PHASE_TALK_SEQUENCE);
}
break;
case FLAME_OF_AZZINOTH:
{
summon->AI()->AttackStart(summon->SelectNearestTarget(999));
}
break;
default:
break;
}
}
void boss_illidan_stormrage::boss_illidan_stormrageAI::HandleTalkSequence()
{
switch (TalkCount)
{
case 0:
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
break;
case 8:
// Equip our warglaives!
SetEquipmentSlots(false, EQUIP_ID_MAIN_HAND, EQUIP_ID_OFF_HAND, EQUIP_NO_CHANGE);
me->SetSheath(SHEATH_STATE_MELEE);
me->SetWalk(false);
break;
case 9:
if (Creature* akama = ObjectAccessor::GetCreature(*me, AkamaGUID))
{
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE + UNIT_FLAG_NOT_SELECTABLE);
me->AddThreat(akama, 100.0f);
ENSURE_AI(npc_akama_illidan::npc_akama_illidanAI, akama->AI())->EnterPhase(PHASE_FIGHT_ILLIDAN);
EnterPhase(PHASE_NORMAL);
}
break;
case 10:
SummonMaiev();
break;
case 11:
if (Creature* maiev = ObjectAccessor::GetCreature(*me, MaievGUID))
{
maiev->SetVisible(true); // Maiev is now visible
maiev->CastSpell(maiev, SPELL_TELEPORT_VISUAL, true); // onoz she looks like she teleported!
maiev->SetInFront(me); // Have her face us
me->SetInFront(maiev); // Face her, so it's not rude =P
maiev->GetMotionMaster()->MoveIdle();
me->GetMotionMaster()->MoveIdle();
}
break;
case 14:
if (Creature* maiev = ObjectAccessor::GetCreature(*me, MaievGUID))
{
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE + UNIT_FLAG_NOT_SELECTABLE);
maiev->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE + UNIT_FLAG_NOT_SELECTABLE);
maiev->AddThreat(me, 10000000.0f); // Have Maiev add a lot of threat on us so that players don't pull her off if they damage her via AOE
maiev->AI()->AttackStart(me); // Force Maiev to attack us.
EnterPhase(PHASE_NORMAL_MAIEV);
}
break;
case 15:
DoCast(me, SPELL_DEATH); // Animate his kneeling + stun him
summons.DespawnAll();
break;
case 17:
if (Creature* akama = ObjectAccessor::GetCreature(*me, AkamaGUID))
{
if (!me->IsWithinDistInMap(akama, 15))
{
float x, y, z;
me->GetPosition(x, y, z);
x += 10; y += 10;
akama->GetMotionMaster()->Clear(false);
// Akama->GetMotionMaster()->MoveIdle();
akama->SetPosition(x, y, z, 0.0f);
akama->MonsterMoveWithSpeed(x, y, z, 0); // Illidan must not die until Akama arrives.
akama->GetMotionMaster()->MoveChase(me);
}
}
break;
case 19: // Make Maiev leave
if (Creature* maiev = ObjectAccessor::GetCreature(*me, MaievGUID))
{
maiev->CastSpell(maiev, SPELL_TELEPORT_VISUAL, true);
maiev->setDeathState(JUST_DIED);
me->SetUInt32Value(UNIT_FIELD_BYTES_1, UNIT_STAND_STATE_DEAD);
}
break;
case 21: // Kill ourself.
me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
break;
default:
break;
}
if (Phase == PHASE_TALK_SEQUENCE)
Talk(TalkCount); // This function does most of the talking
++TalkCount;
}
class npc_cage_trap_trigger : public CreatureScript
{
public:
npc_cage_trap_trigger() : CreatureScript("npc_cage_trap_trigger") { }
struct cage_trap_triggerAI : public ScriptedAI
{
cage_trap_triggerAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
}
void Initialize()
{
IllidanGUID.Clear();
Active = false;
SummonedBeams = false;
DespawnTimer = 0;
}
void Reset() override
{
Initialize();
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
void EnterCombat(Unit* /*who*/) override { }
void MoveInLineOfSight(Unit* who) override
{
if (!Active)
return;
if (who && (who->GetTypeId() != TYPEID_PLAYER))
{
if (who->GetEntry() == ILLIDAN_STORMRAGE) // Check if who is Illidan
{
if (!IllidanGUID && me->IsWithinDistInMap(who, 3) && (!who->HasAura(SPELL_CAGED)))
{
IllidanGUID = who->GetGUID();
who->CastSpell(who, SPELL_CAGED, true);
DespawnTimer = 5000;
if (who->HasAura(SPELL_ENRAGE))
who->RemoveAurasDueToSpell(SPELL_ENRAGE); // Dispel his enrage
// if (GameObject* CageTrap = instance->instance->GetGameObject(instance->GetGuidData(CageTrapGUID)))
// CageTrap->SetLootState(GO_JUST_DEACTIVATED);
}
}
}
}
void UpdateAI(uint32 diff) override
{
if (DespawnTimer)
{
if (DespawnTimer <= diff)
me->DealDamage(me, me->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
else DespawnTimer -= diff;
}
// if (IllidanGUID && !SummonedBeams)
// {
// if (Unit* Illidan = ObjectAccessor::GetUnit(*me, IllidanGUID)
// {
// /// @todo Find proper spells and properly apply 'caged' Illidan effect
// }
// }
}
public:
bool Active;
private:
ObjectGuid IllidanGUID;
uint32 DespawnTimer;
bool SummonedBeams;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new cage_trap_triggerAI(creature);
}
};
class gameobject_cage_trap : public GameObjectScript
{
public:
gameobject_cage_trap() : GameObjectScript("gameobject_cage_trap") { }
bool OnGossipHello(Player* player, GameObject* go) override
{
float x, y, z;
player->GetPosition(x, y, z);
// Grid search for nearest live Creature of entry 23304 within 10 yards
if (Creature* pTrigger = go->FindNearestCreature(23304, 10.0f))
ENSURE_AI(npc_cage_trap_trigger::cage_trap_triggerAI, pTrigger->AI())->Active = true;
go->SetGoState(GO_STATE_ACTIVE);
return true;
}
};
class npc_shadow_demon : public CreatureScript
{
public:
npc_shadow_demon() : CreatureScript("npc_shadow_demon") { }
struct shadow_demonAI : public ScriptedAI
{
shadow_demonAI(Creature* creature) : ScriptedAI(creature) { }
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
}
void Reset() override
{
TargetGUID.Clear();
DoCast(me, SPELL_SHADOW_DEMON_PASSIVE, true);
}
void JustDied(Unit* /*killer*/) override
{
if (Unit* target = ObjectAccessor::GetUnit(*me, TargetGUID))
target->RemoveAurasDueToSpell(SPELL_PARALYZE);
}
void UpdateAI(uint32 /*diff*/) override
{
if (!UpdateVictim() || !me->GetVictim())
return;
if (me->EnsureVictim()->GetTypeId() != TYPEID_PLAYER)
return; // Only cast the below on players.
if (!me->EnsureVictim()->HasAura(SPELL_PARALYZE))
{
TargetGUID = me->EnsureVictim()->GetGUID();
me->AddThreat(me->GetVictim(), 10000000.0f);
DoCastVictim(SPELL_PURPLE_BEAM, true);
DoCastVictim(SPELL_PARALYZE, true);
}
// Kill our target if we're very close.
if (me->IsWithinDistInMap(me->GetVictim(), 3))
DoCastVictim(SPELL_CONSUME_SOUL);
}
private:
ObjectGuid TargetGUID;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new shadow_demonAI(creature);
}
};
class npc_blade_of_azzinoth : public CreatureScript
{
public:
npc_blade_of_azzinoth() : CreatureScript("npc_blade_of_azzinoth") { }
struct blade_of_azzinothAI : public NullCreatureAI
{
blade_of_azzinothAI(Creature* creature) : NullCreatureAI(creature) { }
void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override
{
if (spell->Id == SPELL_THROW_GLAIVE2 || spell->Id == SPELL_THROW_GLAIVE)
me->SetDisplayId(MODEL_BLADE);// appear when hit by Illidan's glaive
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new blade_of_azzinothAI(creature);
}
};
class npc_parasitic_shadowfiend : public CreatureScript
{
public:
npc_parasitic_shadowfiend() : CreatureScript("npc_parasitic_shadowfiend") { }
// Shadowfiends interact with Illidan, setting more targets in Illidan's hashmap
struct npc_parasitic_shadowfiendAI : public ScriptedAI
{
npc_parasitic_shadowfiendAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
}
void Initialize()
{
CheckTimer = 5000;
}
void Reset() override
{
IllidanGUID = instance->GetGuidData(DATA_ILLIDAN_STORMRAGE);
Initialize();
DoCast(me, SPELL_SHADOWFIEND_PASSIVE, true);
}
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
}
void DoMeleeAttackIfReady()
{
if (me->isAttackReady() && me->IsWithinMeleeRange(me->GetVictim()))
{
if (!me->EnsureVictim()->HasAura(SPELL_PARASITIC_SHADOWFIEND)
&& !me->EnsureVictim()->HasAura(SPELL_PARASITIC_SHADOWFIEND2))
{
if (Creature* illidan = ObjectAccessor::GetCreature((*me), IllidanGUID))// summon only in 1. phase
if (ENSURE_AI(boss_illidan_stormrage::boss_illidan_stormrageAI, illidan->AI())->Phase == PHASE_NORMAL)
me->CastSpell(me->GetVictim(), SPELL_PARASITIC_SHADOWFIEND2, true, 0, 0, IllidanGUID); // do not stack
}
me->AttackerStateUpdate(me->GetVictim());
me->resetAttackTimer();
}
}
void UpdateAI(uint32 diff) override
{
if (!me->GetVictim())
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 999, true))
AttackStart(target);
else
{
me->DespawnOrUnsummon();
return;
}
}
if (CheckTimer <= diff)
{
Creature* illidan = ObjectAccessor::GetCreature(*me, IllidanGUID);
if (!illidan || illidan->IsInEvadeMode())
{
me->DespawnOrUnsummon();
return;
}
else
CheckTimer = 5000;
}
else
CheckTimer -= diff;
DoMeleeAttackIfReady();
}
private:
InstanceScript* instance;
ObjectGuid IllidanGUID;
uint32 CheckTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_parasitic_shadowfiendAI>(creature);
}
};
void AddSC_boss_illidan()
{
new boss_illidan_stormrage();
new npc_akama_illidan();
new boss_maiev_shadowsong();
new npc_flame_of_azzinoth();
new npc_blade_of_azzinoth();
new gameobject_cage_trap();
new npc_cage_trap_trigger();
new npc_shadow_demon();
new npc_parasitic_shadowfiend();
}
|
martial69320/cerberus
|
src/server/scripts/Outland/BlackTemple/boss_illidan.cpp
|
C++
|
gpl-2.0
| 81,773 |
<?php
namespace WpPepVN\Form\Element;
use WpPepVN\Form\Element;
use WpPepVN\Form\ElementInterface;
/**
* WpPepVN\Forms\Element\Submit
*
* Component INPUT[type=submit] for forms
*/
class Submit extends Element implements ElementInterface
{
/**
* Renders the element widget
*
* @param array attributes
* @return string
*/
public function render($attributes = null)
{
/**
* Merged passed attributes with previously defined ones
*/
return \WpPepVN\Tag::submitButton($this->prepareAttributes($attributes));
}
}
|
Bushzhao/rvbwebsite
|
wp-content/plugins/wp-optimize-by-xtraffic/libs/WpPepVN/Form/Element/Submit.php
|
PHP
|
gpl-2.0
| 540 |
/*
alignlib - a library for aligning protein sequences
$Id: ImplAlignator.cpp,v 1.3 2005/02/24 11:07:25 aheger Exp $
Copyright (C) 2004 Andreas Heger
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 <iostream>
#include "alignlib_fwd.h"
#include "alignlib_interfaces.h"
#include "AlignlibDebug.h"
#include "Alignator.h"
#include "Alignment.h"
#include "HelpersAlignment.h"
#include "Alignandum.h"
#include "AlignlibException.h"
#include "Iterator2D.h"
#include "HelpersIterator2D.h"
#include "Scorer.h"
#include "HelpersScorer.h"
#include "ImplAlignator.h"
#include <math.h>
using namespace std;
namespace alignlib
{
//----------------------------------------------------------------------------------------
ImplAlignator::ImplAlignator() : Alignator()
{
debug_func_cerr( 5 );
}
ImplAlignator::~ImplAlignator()
{
debug_func_cerr(5);
}
ImplAlignator::ImplAlignator( const ImplAlignator & src ) : Alignator(src),
mIterator(src.mIterator)
{
}
//-------------------------------------------------------------------------------------------------------------------------------
void ImplAlignator::startUp( HAlignment & ali,
const HAlignandum & row, const HAlignandum & col )
{
debug_func_cerr(5);
row->prepare();
col->prepare();
debug_cerr( 5, "starting alignment for row=" << row->getFrom() << "-" << row->getTo()
<< " col=" << col->getFrom() << "-" << col->getTo() );
mRowLength = row->getLength();
mIterator = getToolkit()->getIterator2D()->getNew( row, col );
debug_cerr( 5, "setting iterator to ranges: row="
<< *mIterator->row_begin() << "-" << *mIterator->row_end() << ":" << mIterator->row_size() << " col="
<< *mIterator->col_begin() << "-" << *mIterator->col_end() << ":" << mIterator->col_size() );
mScorer = getToolkit()->getScorer()->getNew( row, col );
ali->clear();
}
void ImplAlignator::cleanUp( HAlignment & ali,
const HAlignandum & row, const HAlignandum & col )
{
debug_func_cerr(5);
/* round score to integer. This will get rid
of ???
*/
ali->setScore( round(ali->getScore()) );
}
} // namespace alignlib
|
AndreasHeger/alignlib
|
cython/alignlib_src/ImplAlignator.cpp
|
C++
|
gpl-2.0
| 2,905 |
<!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_17) on Thu Mar 16 17:20:41 CET 2017 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.slf4j.impl.SimpleLoggerConfiguration (SLF4J 1.7.25 API)</title>
<meta name="date" content="2017-03-16">
<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="Uses of Class org.slf4j.impl.SimpleLoggerConfiguration (SLF4J 1.7.25 API)";
}
//-->
</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><a href="../../../../org/slf4j/impl/SimpleLoggerConfiguration.html" title="class in org.slf4j.impl">Class</a></li>
<li class="navBarCell1Rev">Use</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="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/slf4j/impl/class-use/SimpleLoggerConfiguration.html" target="_top">Frames</a></li>
<li><a href="SimpleLoggerConfiguration.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>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.slf4j.impl.SimpleLoggerConfiguration" class="title">Uses of Class<br>org.slf4j.impl.SimpleLoggerConfiguration</h2>
</div>
<div class="classUseContainer">No usage of org.slf4j.impl.SimpleLoggerConfiguration</div>
<!-- ======= 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><a href="../../../../org/slf4j/impl/SimpleLoggerConfiguration.html" title="class in org.slf4j.impl">Class</a></li>
<li class="navBarCell1Rev">Use</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="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/slf4j/impl/class-use/SimpleLoggerConfiguration.html" target="_top">Frames</a></li>
<li><a href="SimpleLoggerConfiguration.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>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2005–2017 <a href="http://www.qos.ch">QOS.ch</a>. All rights reserved.</small></p>
</body>
</html>
|
rickli/Java
|
src/slf4j-1.7.25/site/apidocs/org/slf4j/impl/class-use/SimpleLoggerConfiguration.html
|
HTML
|
gpl-2.0
| 4,479 |
/* -*- linux-c -*-
*
* (C) Copyright University of New Hampshire 2006
*
* 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
*
* Author(s):
* Donald A. Barre
*
* Spec: HPI-B.01.01
* Function: saHpiAlarmAcknowledge
* Description:
* If the AlarmId is SAHPI_ENTRY_UNSPECIFIED and no alarms
* are present that meet the requested Severity, this
* function will have no effect.
* Expected return: SA_OK.
* Line: P71-1:P71-2
*
*/
#include <stdio.h>
#include "saf_test.h"
/*************************************************************************
*
* Does the DAT have an alarm with the given severity?
*
*************************************************************************/
SaErrorT hasAlarmWithSeverity(SaHpiSessionIdT sessionId,
SaHpiSeverityT severity, SaHpiBoolT * found)
{
SaErrorT status;
SaHpiAlarmT alarm;
*found = SAHPI_FALSE;
alarm.AlarmId = SAHPI_FIRST_ENTRY;
status = saHpiAlarmGetNext(sessionId, severity, SAHPI_FALSE, &alarm);
if (status == SA_ERR_HPI_NOT_PRESENT) {
*found = SAHPI_FALSE;
status = SA_OK;
} else if (status == SA_OK) {
*found = SAHPI_TRUE;
} else {
e_print(saHpiAlarmGet, SA_OK | SA_ERR_HPI_NOT_PRESENT, status);
}
return status;
}
/*************************************************************************
*
* Acknowledge all alarms of a given severity.
*
*************************************************************************/
int run_test(SaHpiSessionIdT sessionId, SaHpiSeverityT severity)
{
SaErrorT status;
int retval;
status =
saHpiAlarmAcknowledge(sessionId, SAHPI_ENTRY_UNSPECIFIED, severity);
if (status == SA_OK) {
retval = SAF_TEST_PASS;
} else {
retval = SAF_TEST_FAIL;
e_print(saHpiAlarmAcknowledge, SA_OK, status);
}
return retval;
}
/*************************************************************************
*
* Try to find a severity that isn't used in the DAT and then
* acknowledge alarms with that severity.
*
*************************************************************************/
int Test_Domain(SaHpiSessionIdT sessionId)
{
SaErrorT status;
int retval;
SaHpiBoolT found;
status = hasAlarmWithSeverity(sessionId, SAHPI_MINOR, &found);
if (status != SA_OK) {
retval = SAF_TEST_UNRESOLVED;
} else if (!found) {
retval = run_test(sessionId, SAHPI_MINOR);
} else {
status = hasAlarmWithSeverity(sessionId, SAHPI_MAJOR, &found);
if (status != SA_OK) {
retval = SAF_TEST_UNRESOLVED;
} else if (!found) {
retval = run_test(sessionId, SAHPI_MAJOR);
} else {
status =
hasAlarmWithSeverity(sessionId, SAHPI_CRITICAL,
&found);
if (status != SA_OK) {
retval = SAF_TEST_UNRESOLVED;
} else if (!found) {
retval = run_test(sessionId, SAHPI_CRITICAL);
} else {
retval = SAF_TEST_NOTSUPPORT;
m_print("Could not find an Severity (minor, major, or critical) "
"that isn't being used by any of the alarms in the DAT.");
}
}
}
return retval;
}
/*************************************************************************
*
* Main Program.
*
*************************************************************************/
int main(int argc, char **argv)
{
int retval = SAF_TEST_UNKNOWN;
retval = process_all_domains(NULL, NULL, Test_Domain);
return (retval);
}
|
rajashreer7/autotest-client-tests
|
linux-tools/openhpi/openhpi2-conformancetest/src/alarm/saHpiAlarmAcknowledge/11.c
|
C
|
gpl-2.0
| 4,030 |
<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Helper;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Application\ApplicationHelper;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\LanguageHelper;
use Joomla\CMS\Language\Multilanguage;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Table\TableInterface;
use Joomla\Registry\Registry;
/**
* Base Helper class.
*
* @since 3.2
*/
class CMSHelper
{
/**
* Gets the current language
*
* @param boolean $detectBrowser Flag indicating whether to use the browser language as a fallback.
*
* @return string The language string
*
* @since 3.2
*/
public function getCurrentLanguage($detectBrowser = true)
{
$app = Factory::getApplication();
$langCode = null;
// Get the languagefilter parameters
if (Multilanguage::isEnabled())
{
$plugin = PluginHelper::getPlugin('system', 'languagefilter');
$pluginParams = new Registry($plugin->params);
if ((int) $pluginParams->get('lang_cookie', 1) === 1)
{
$langCode = $app->input->cookie->getString(ApplicationHelper::getHash('language'));
}
else
{
$langCode = $app->getSession()->get('plg_system_languagefilter.language');
}
}
// No cookie - let's try to detect browser language or use site default
if (!$langCode)
{
if ($detectBrowser)
{
$langCode = LanguageHelper::detectLanguage();
}
else
{
$langCode = ComponentHelper::getParams('com_languages')->get('site', 'en-GB');
}
}
return $langCode;
}
/**
* Gets the associated language ID
*
* @param string $langCode The language code to look up
*
* @return integer The language ID
*
* @since 3.2
*/
public function getLanguageId($langCode)
{
$db = Factory::getDbo();
$query = $db->getQuery(true)
->select('lang_id')
->from('#__languages')
->where($db->quoteName('lang_code') . ' = ' . $db->quote($langCode));
$db->setQuery($query);
return $db->loadResult();
}
/**
* Gets a row of data from a table
*
* @param TableInterface $table Table instance for a row.
*
* @return array Associative array of all columns and values for a row in a table.
*
* @since 3.2
*/
public function getRowData(TableInterface $table)
{
$fields = $table->getFields();
$data = array();
foreach ($fields as &$field)
{
$columnName = $field->Field;
$value = $table->$columnName;
$data[$columnName] = $value;
}
return $data;
}
/**
* Method to get an object containing all of the table columns and values.
*
* @param TableInterface $table Table object.
*
* @return \stdClass Contains all of the columns and values.
*
* @since 3.2
*/
public function getDataObject(TableInterface $table)
{
$fields = $table->getFields();
$dataObject = new \stdClass;
foreach ($fields as $field)
{
$fieldName = $field->Field;
$dataObject->$fieldName = $table->get($fieldName);
}
return $dataObject;
}
}
|
joomla-projects/gsoc17_expand_extension_manager
|
libraries/src/Helper/CMSHelper.php
|
PHP
|
gpl-2.0
| 3,198 |
/*
* u_smd.c - utilities for USB gadget serial over smd
*
* Copyright (c) 2011, The Linux Foundation. All rights reserved.
*
* This code also borrows from drivers/usb/gadget/u_serial.c, which is
* Copyright (C) 2000 - 2003 Al Borchers ([email protected])
* Copyright (C) 2008 David Brownell
* Copyright (C) 2008 by Nokia Corporation
* Copyright (C) 1999 - 2002 Greg Kroah-Hartman ([email protected])
* Copyright (C) 2000 Peter Berger ([email protected])
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/termios.h>
#include <mach/msm_smd.h>
#include <linux/debugfs.h>
#include "u_serial.h"
#define SMD_RX_QUEUE_SIZE 8
#define SMD_RX_BUF_SIZE 2048
#define SMD_TX_QUEUE_SIZE 8
#define SMD_TX_BUF_SIZE 2048
static struct workqueue_struct *gsmd_wq;
#define SMD_N_PORTS 2
#define CH_OPENED 0
#define CH_READY 1
struct smd_port_info {
struct smd_channel *ch;
char *name;
unsigned long flags;
};
struct smd_port_info smd_pi[SMD_N_PORTS] = {
{
.name = "DS",
},
/* used DATA2 smd channel to support at command in pcui port */
#ifndef CONFIG_HUAWEI_USB
{
.name = "UNUSED",
},
#else
{
.name = "DATA2",
},
#endif
};
struct gsmd_port {
unsigned port_num;
spinlock_t port_lock;
unsigned n_read;
struct list_head read_pool;
struct list_head read_queue;
struct work_struct push;
struct list_head write_pool;
struct work_struct pull;
struct gserial *port_usb;
struct smd_port_info *pi;
struct delayed_work connect_work;
struct work_struct disconnect_work;
/* At present, smd does not notify
* control bit change info from modem
*/
struct work_struct update_modem_ctrl_sig;
#define SMD_ACM_CTRL_DTR 0x01
#define SMD_ACM_CTRL_RTS 0x02
unsigned cbits_to_modem;
#define SMD_ACM_CTRL_DCD 0x01
#define SMD_ACM_CTRL_DSR 0x02
#define SMD_ACM_CTRL_BRK 0x04
#define SMD_ACM_CTRL_RI 0x08
unsigned cbits_to_laptop;
/* pkt counters */
unsigned long nbytes_tomodem;
unsigned long nbytes_tolaptop;
};
static struct smd_portmaster {
struct mutex lock;
struct gsmd_port *port;
struct platform_driver pdrv;
} smd_ports[SMD_N_PORTS];
static unsigned n_smd_ports;
static void gsmd_free_req(struct usb_ep *ep, struct usb_request *req)
{
kfree(req->buf);
usb_ep_free_request(ep, req);
}
static void gsmd_free_requests(struct usb_ep *ep, struct list_head *head)
{
struct usb_request *req;
while (!list_empty(head)) {
req = list_entry(head->next, struct usb_request, list);
list_del(&req->list);
gsmd_free_req(ep, req);
}
}
static struct usb_request *
gsmd_alloc_req(struct usb_ep *ep, unsigned len, gfp_t flags)
{
struct usb_request *req;
req = usb_ep_alloc_request(ep, flags);
if (!req) {
pr_err("%s: usb alloc request failed\n", __func__);
return 0;
}
req->length = len;
req->buf = kmalloc(len, flags);
if (!req->buf) {
pr_err("%s: request buf allocation failed\n", __func__);
usb_ep_free_request(ep, req);
return 0;
}
return req;
}
static int gsmd_alloc_requests(struct usb_ep *ep, struct list_head *head,
int num, int size,
void (*cb)(struct usb_ep *ep, struct usb_request *))
{
int i;
struct usb_request *req;
pr_debug("%s: ep:%p head:%p num:%d size:%d cb:%p", __func__,
ep, head, num, size, cb);
for (i = 0; i < num; i++) {
req = gsmd_alloc_req(ep, size, GFP_ATOMIC);
if (!req) {
pr_debug("%s: req allocated:%d\n", __func__, i);
return list_empty(head) ? -ENOMEM : 0;
}
req->complete = cb;
list_add(&req->list, head);
}
return 0;
}
static void gsmd_start_rx(struct gsmd_port *port)
{
struct list_head *pool;
struct usb_ep *out;
unsigned long flags;
int ret;
if (!port) {
pr_err("%s: port is null\n", __func__);
return;
}
spin_lock_irqsave(&port->port_lock, flags);
if (!port->port_usb) {
pr_debug("%s: USB disconnected\n", __func__);
goto start_rx_end;
}
pool = &port->read_pool;
out = port->port_usb->out;
while (test_bit(CH_OPENED, &port->pi->flags) && !list_empty(pool)) {
struct usb_request *req;
req = list_entry(pool->next, struct usb_request, list);
list_del(&req->list);
req->length = SMD_RX_BUF_SIZE;
spin_unlock_irqrestore(&port->port_lock, flags);
ret = usb_ep_queue(out, req, GFP_KERNEL);
spin_lock_irqsave(&port->port_lock, flags);
if (ret) {
pr_err("%s: usb ep out queue failed"
"port:%p, port#%d\n",
__func__, port, port->port_num);
list_add_tail(&req->list, pool);
break;
}
}
start_rx_end:
spin_unlock_irqrestore(&port->port_lock, flags);
}
static void gsmd_rx_push(struct work_struct *w)
{
struct gsmd_port *port = container_of(w, struct gsmd_port, push);
struct smd_port_info *pi = port->pi;
struct list_head *q;
pr_debug("%s: port:%p port#%d", __func__, port, port->port_num);
spin_lock_irq(&port->port_lock);
q = &port->read_queue;
while (pi->ch && !list_empty(q)) {
struct usb_request *req;
int avail;
req = list_first_entry(q, struct usb_request, list);
switch (req->status) {
case -ESHUTDOWN:
pr_debug("%s: req status shutdown portno#%d port:%p\n",
__func__, port->port_num, port);
goto rx_push_end;
default:
pr_warning("%s: port:%p port#%d"
" Unexpected Rx Status:%d\n", __func__,
port, port->port_num, req->status);
case 0:
/* normal completion */
break;
}
avail = smd_write_avail(pi->ch);
if (!avail)
goto rx_push_end;
if (req->actual) {
char *packet = req->buf;
unsigned size = req->actual;
unsigned n;
int count;
n = port->n_read;
if (n) {
packet += n;
size -= n;
}
count = smd_write(pi->ch, packet, size);
if (count < 0) {
pr_err("%s: smd write failed err:%d\n",
__func__, count);
goto rx_push_end;
}
if (count != size) {
port->n_read += count;
goto rx_push_end;
}
port->nbytes_tomodem += count;
}
port->n_read = 0;
list_move(&req->list, &port->read_pool);
}
rx_push_end:
spin_unlock_irq(&port->port_lock);
gsmd_start_rx(port);
}
static void gsmd_read_pending(struct gsmd_port *port)
{
int avail;
if (!port || !port->pi->ch)
return;
/* passing null buffer discards the data */
while ((avail = smd_read_avail(port->pi->ch)))
smd_read(port->pi->ch, 0, avail);
return;
}
static void gsmd_tx_pull(struct work_struct *w)
{
struct gsmd_port *port = container_of(w, struct gsmd_port, pull);
struct list_head *pool = &port->write_pool;
struct smd_port_info *pi = port->pi;
struct usb_ep *in;
pr_debug("%s: port:%p port#%d pool:%p\n", __func__,
port, port->port_num, pool);
spin_lock_irq(&port->port_lock);
if (!port->port_usb) {
pr_debug("%s: usb is disconnected\n", __func__);
spin_unlock_irq(&port->port_lock);
gsmd_read_pending(port);
return;
}
in = port->port_usb->in;
while (pi->ch && !list_empty(pool)) {
struct usb_request *req;
int avail;
int ret;
avail = smd_read_avail(pi->ch);
if (!avail)
break;
avail = avail > SMD_TX_BUF_SIZE ? SMD_TX_BUF_SIZE : avail;
req = list_entry(pool->next, struct usb_request, list);
list_del(&req->list);
req->length = smd_read(pi->ch, req->buf, avail);
spin_unlock_irq(&port->port_lock);
ret = usb_ep_queue(in, req, GFP_KERNEL);
spin_lock_irq(&port->port_lock);
if (ret) {
pr_err("%s: usb ep out queue failed"
"port:%p, port#%d err:%d\n",
__func__, port, port->port_num, ret);
/* could be usb disconnected */
if (!port->port_usb)
gsmd_free_req(in, req);
else
list_add(&req->list, pool);
goto tx_pull_end;
}
port->nbytes_tolaptop += req->length;
}
tx_pull_end:
/* TBD: Check how code behaves on USB bus suspend */
if (port->port_usb && smd_read_avail(port->pi->ch) && !list_empty(pool))
queue_work(gsmd_wq, &port->pull);
spin_unlock_irq(&port->port_lock);
return;
}
static void gsmd_read_complete(struct usb_ep *ep, struct usb_request *req)
{
struct gsmd_port *port = ep->driver_data;
pr_debug("%s: ep:%p port:%p\n", __func__, ep, port);
if (!port) {
pr_err("%s: port is null\n", __func__);
return;
}
spin_lock(&port->port_lock);
if (!test_bit(CH_OPENED, &port->pi->flags) ||
req->status == -ESHUTDOWN) {
spin_unlock(&port->port_lock);
gsmd_free_req(ep, req);
return;
}
list_add_tail(&req->list, &port->read_queue);
queue_work(gsmd_wq, &port->push);
spin_unlock(&port->port_lock);
return;
}
static void gsmd_write_complete(struct usb_ep *ep, struct usb_request *req)
{
struct gsmd_port *port = ep->driver_data;
pr_debug("%s: ep:%p port:%p\n", __func__, ep, port);
if (!port) {
pr_err("%s: port is null\n", __func__);
return;
}
spin_lock(&port->port_lock);
if (!test_bit(CH_OPENED, &port->pi->flags) ||
req->status == -ESHUTDOWN) {
spin_unlock(&port->port_lock);
gsmd_free_req(ep, req);
return;
}
if (req->status)
pr_warning("%s: port:%p port#%d unexpected %s status %d\n",
__func__, port, port->port_num,
ep->name, req->status);
list_add(&req->list, &port->write_pool);
queue_work(gsmd_wq, &port->pull);
spin_unlock(&port->port_lock);
return;
}
static void gsmd_start_io(struct gsmd_port *port)
{
int ret = -ENODEV;
pr_debug("%s: port: %p\n", __func__, port);
spin_lock(&port->port_lock);
if (!port->port_usb)
goto start_io_out;
smd_tiocmset_from_cb(port->pi->ch,
port->cbits_to_modem,
~port->cbits_to_modem);
ret = gsmd_alloc_requests(port->port_usb->out,
&port->read_pool,
SMD_RX_QUEUE_SIZE, SMD_RX_BUF_SIZE,
gsmd_read_complete);
if (ret) {
pr_err("%s: unable to allocate out requests\n",
__func__);
goto start_io_out;
}
ret = gsmd_alloc_requests(port->port_usb->in,
&port->write_pool,
SMD_TX_QUEUE_SIZE, SMD_TX_BUF_SIZE,
gsmd_write_complete);
if (ret) {
gsmd_free_requests(port->port_usb->out, &port->read_pool);
pr_err("%s: unable to allocate IN requests\n",
__func__);
goto start_io_out;
}
start_io_out:
spin_unlock(&port->port_lock);
if (ret)
return;
gsmd_start_rx(port);
}
static unsigned int convert_uart_sigs_to_acm(unsigned uart_sig)
{
unsigned int acm_sig = 0;
/* should this needs to be in calling functions ??? */
uart_sig &= (TIOCM_RI | TIOCM_CD | TIOCM_DSR);
if (uart_sig & TIOCM_RI)
acm_sig |= SMD_ACM_CTRL_RI;
if (uart_sig & TIOCM_CD)
acm_sig |= SMD_ACM_CTRL_DCD;
if (uart_sig & TIOCM_DSR)
acm_sig |= SMD_ACM_CTRL_DSR;
return acm_sig;
}
static unsigned int convert_acm_sigs_to_uart(unsigned acm_sig)
{
unsigned int uart_sig = 0;
/* should this needs to be in calling functions ??? */
acm_sig &= (SMD_ACM_CTRL_DTR | SMD_ACM_CTRL_RTS);
/* set RTS signal forcedly enven if there is no RTS or DTR
* If the host does not set RTS signal,
* Modem will not write data to share memory.
*/
#ifdef CONFIG_HUAWEI_USB
if (acm_sig & SMD_ACM_CTRL_DTR)
uart_sig |= TIOCM_DTR;
uart_sig |= TIOCM_RTS;
#else
if (acm_sig & SMD_ACM_CTRL_DTR)
uart_sig |= TIOCM_DTR;
if (acm_sig & SMD_ACM_CTRL_RTS)
uart_sig |= TIOCM_RTS;
#endif
return uart_sig;
}
static void gsmd_stop_io(struct gsmd_port *port)
{
struct usb_ep *in;
struct usb_ep *out;
unsigned long flags;
spin_lock_irqsave(&port->port_lock, flags);
if (!port->port_usb) {
spin_unlock_irqrestore(&port->port_lock, flags);
return;
}
in = port->port_usb->in;
out = port->port_usb->out;
spin_unlock_irqrestore(&port->port_lock, flags);
usb_ep_fifo_flush(in);
usb_ep_fifo_flush(out);
spin_lock(&port->port_lock);
if (port->port_usb) {
gsmd_free_requests(out, &port->read_pool);
gsmd_free_requests(out, &port->read_queue);
gsmd_free_requests(in, &port->write_pool);
port->n_read = 0;
port->cbits_to_laptop = 0;
}
if (port->port_usb->send_modem_ctrl_bits)
port->port_usb->send_modem_ctrl_bits(
port->port_usb,
port->cbits_to_laptop);
spin_unlock(&port->port_lock);
}
static void gsmd_notify(void *priv, unsigned event)
{
struct gsmd_port *port = priv;
struct smd_port_info *pi = port->pi;
int i;
switch (event) {
case SMD_EVENT_DATA:
pr_debug("%s: Event data\n", __func__);
if (smd_read_avail(pi->ch))
queue_work(gsmd_wq, &port->pull);
if (smd_write_avail(pi->ch))
queue_work(gsmd_wq, &port->push);
break;
case SMD_EVENT_OPEN:
pr_debug("%s: Event Open\n", __func__);
set_bit(CH_OPENED, &pi->flags);
gsmd_start_io(port);
break;
case SMD_EVENT_CLOSE:
pr_debug("%s: Event Close\n", __func__);
clear_bit(CH_OPENED, &pi->flags);
gsmd_stop_io(port);
break;
case SMD_EVENT_STATUS:
i = smd_tiocmget(port->pi->ch);
port->cbits_to_laptop = convert_uart_sigs_to_acm(i);
if (port->port_usb && port->port_usb->send_modem_ctrl_bits)
port->port_usb->send_modem_ctrl_bits(port->port_usb,
port->cbits_to_laptop);
break;
}
}
static void gsmd_connect_work(struct work_struct *w)
{
struct gsmd_port *port;
struct smd_port_info *pi;
int ret;
port = container_of(w, struct gsmd_port, connect_work.work);
pi = port->pi;
pr_debug("%s: port:%p port#%d\n", __func__, port, port->port_num);
if (!test_bit(CH_READY, &pi->flags))
return;
ret = smd_named_open_on_edge(pi->name, SMD_APPS_MODEM,
&pi->ch, port, gsmd_notify);
if (ret) {
if (ret == -EAGAIN) {
/* port not ready - retry */
pr_debug("%s: SMD port not ready - rescheduling:%s err:%d\n",
__func__, pi->name, ret);
queue_delayed_work(gsmd_wq, &port->connect_work,
msecs_to_jiffies(250));
} else {
pr_err("%s: unable to open smd port:%s err:%d\n",
__func__, pi->name, ret);
}
}
}
static void gsmd_disconnect_work(struct work_struct *w)
{
struct gsmd_port *port;
struct smd_port_info *pi;
port = container_of(w, struct gsmd_port, disconnect_work);
pi = port->pi;
pr_debug("%s: port:%p port#%d\n", __func__, port, port->port_num);
smd_close(port->pi->ch);
port->pi->ch = NULL;
}
static void gsmd_notify_modem(void *gptr, u8 portno, int ctrl_bits)
{
struct gsmd_port *port;
int temp;
struct gserial *gser = gptr;
if (portno >= n_smd_ports) {
pr_err("%s: invalid portno#%d\n", __func__, portno);
return;
}
if (!gser) {
pr_err("%s: gser is null\n", __func__);
return;
}
port = smd_ports[portno].port;
temp = convert_acm_sigs_to_uart(ctrl_bits);
if (temp == port->cbits_to_modem)
return;
port->cbits_to_modem = temp;
/* usb could send control signal before smd is ready */
if (!test_bit(CH_OPENED, &port->pi->flags))
return;
/* if DTR is high, update latest modem info to laptop */
if (port->cbits_to_modem & TIOCM_DTR) {
unsigned i;
i = smd_tiocmget(port->pi->ch);
port->cbits_to_laptop = convert_uart_sigs_to_acm(i);
if (gser->send_modem_ctrl_bits)
gser->send_modem_ctrl_bits(
port->port_usb,
port->cbits_to_laptop);
}
smd_tiocmset(port->pi->ch,
port->cbits_to_modem,
~port->cbits_to_modem);
}
int gsmd_connect(struct gserial *gser, u8 portno)
{
unsigned long flags;
int ret;
struct gsmd_port *port;
pr_debug("%s: gserial:%p portno:%u\n", __func__, gser, portno);
if (portno >= n_smd_ports) {
pr_err("%s: Invalid port no#%d", __func__, portno);
return -EINVAL;
}
if (!gser) {
pr_err("%s: gser is null\n", __func__);
return -EINVAL;
}
port = smd_ports[portno].port;
spin_lock_irqsave(&port->port_lock, flags);
port->port_usb = gser;
gser->notify_modem = gsmd_notify_modem;
port->nbytes_tomodem = 0;
port->nbytes_tolaptop = 0;
spin_unlock_irqrestore(&port->port_lock, flags);
ret = usb_ep_enable(gser->in);
if (ret) {
pr_err("%s: usb_ep_enable failed eptype:IN ep:%p",
__func__, gser->in);
port->port_usb = 0;
return ret;
}
gser->in->driver_data = port;
ret = usb_ep_enable(gser->out);
if (ret) {
pr_err("%s: usb_ep_enable failed eptype:OUT ep:%p",
__func__, gser->out);
port->port_usb = 0;
gser->in->driver_data = 0;
return ret;
}
gser->out->driver_data = port;
queue_delayed_work(gsmd_wq, &port->connect_work, msecs_to_jiffies(0));
return 0;
}
void gsmd_disconnect(struct gserial *gser, u8 portno)
{
unsigned long flags;
struct gsmd_port *port;
pr_debug("%s: gserial:%p portno:%u\n", __func__, gser, portno);
if (portno >= n_smd_ports) {
pr_err("%s: invalid portno#%d\n", __func__, portno);
return;
}
if (!gser) {
pr_err("%s: gser is null\n", __func__);
return;
}
port = smd_ports[portno].port;
spin_lock_irqsave(&port->port_lock, flags);
port->port_usb = 0;
spin_unlock_irqrestore(&port->port_lock, flags);
/* disable endpoints, aborting down any active I/O */
usb_ep_disable(gser->out);
gser->out->driver_data = NULL;
usb_ep_disable(gser->in);
gser->in->driver_data = NULL;
spin_lock_irqsave(&port->port_lock, flags);
gsmd_free_requests(gser->out, &port->read_pool);
gsmd_free_requests(gser->out, &port->read_queue);
gsmd_free_requests(gser->in, &port->write_pool);
port->n_read = 0;
spin_unlock_irqrestore(&port->port_lock, flags);
if (test_and_clear_bit(CH_OPENED, &port->pi->flags)) {
/* lower the dtr */
port->cbits_to_modem = 0;
smd_tiocmset(port->pi->ch,
port->cbits_to_modem,
~port->cbits_to_modem);
}
if (port->pi->ch)
queue_work(gsmd_wq, &port->disconnect_work);
}
#define SMD_CH_MAX_LEN 20
static int gsmd_ch_probe(struct platform_device *pdev)
{
struct gsmd_port *port;
struct smd_port_info *pi;
int i;
unsigned long flags;
pr_debug("%s: name:%s\n", __func__, pdev->name);
for (i = 0; i < n_smd_ports; i++) {
port = smd_ports[i].port;
pi = port->pi;
if (!strncmp(pi->name, pdev->name, SMD_CH_MAX_LEN)) {
set_bit(CH_READY, &pi->flags);
spin_lock_irqsave(&port->port_lock, flags);
if (port->port_usb)
queue_delayed_work(gsmd_wq, &port->connect_work,
msecs_to_jiffies(0));
spin_unlock_irqrestore(&port->port_lock, flags);
break;
}
}
return 0;
}
static int gsmd_ch_remove(struct platform_device *pdev)
{
struct gsmd_port *port;
struct smd_port_info *pi;
int i;
pr_debug("%s: name:%s\n", __func__, pdev->name);
for (i = 0; i < n_smd_ports; i++) {
port = smd_ports[i].port;
pi = port->pi;
if (!strncmp(pi->name, pdev->name, SMD_CH_MAX_LEN)) {
clear_bit(CH_READY, &pi->flags);
clear_bit(CH_OPENED, &pi->flags);
if (pi->ch) {
smd_close(pi->ch);
pi->ch = NULL;
}
break;
}
}
return 0;
}
static void gsmd_port_free(int portno)
{
struct gsmd_port *port = smd_ports[portno].port;
if (!port)
kfree(port);
}
static int gsmd_port_alloc(int portno, struct usb_cdc_line_coding *coding)
{
struct gsmd_port *port;
struct platform_driver *pdrv;
port = kzalloc(sizeof(struct gsmd_port), GFP_KERNEL);
if (!port)
return -ENOMEM;
port->port_num = portno;
port->pi = &smd_pi[portno];
spin_lock_init(&port->port_lock);
INIT_LIST_HEAD(&port->read_pool);
INIT_LIST_HEAD(&port->read_queue);
INIT_WORK(&port->push, gsmd_rx_push);
INIT_LIST_HEAD(&port->write_pool);
INIT_WORK(&port->pull, gsmd_tx_pull);
INIT_DELAYED_WORK(&port->connect_work, gsmd_connect_work);
INIT_WORK(&port->disconnect_work, gsmd_disconnect_work);
smd_ports[portno].port = port;
pdrv = &smd_ports[portno].pdrv;
pdrv->probe = gsmd_ch_probe;
pdrv->remove = gsmd_ch_remove;
pdrv->driver.name = port->pi->name;
pdrv->driver.owner = THIS_MODULE;
platform_driver_register(pdrv);
pr_debug("%s: port:%p portno:%d\n", __func__, port, portno);
return 0;
}
#if defined(CONFIG_DEBUG_FS)
static ssize_t debug_smd_read_stats(struct file *file, char __user *ubuf,
size_t count, loff_t *ppos)
{
struct gsmd_port *port;
struct smd_port_info *pi;
char *buf;
unsigned long flags;
int temp = 0;
int i;
int ret;
buf = kzalloc(sizeof(char) * 512, GFP_KERNEL);
if (!buf)
return -ENOMEM;
for (i = 0; i < n_smd_ports; i++) {
port = smd_ports[i].port;
pi = port->pi;
spin_lock_irqsave(&port->port_lock, flags);
temp += scnprintf(buf + temp, 512 - temp,
"###PORT:%d###\n"
"nbytes_tolaptop: %lu\n"
"nbytes_tomodem: %lu\n"
"cbits_to_modem: %u\n"
"cbits_to_laptop: %u\n"
"n_read: %u\n"
"smd_read_avail: %d\n"
"smd_write_avail: %d\n"
"CH_OPENED: %d\n"
"CH_READY: %d\n",
i, port->nbytes_tolaptop, port->nbytes_tomodem,
port->cbits_to_modem, port->cbits_to_laptop,
port->n_read,
pi->ch ? smd_read_avail(pi->ch) : 0,
pi->ch ? smd_write_avail(pi->ch) : 0,
test_bit(CH_OPENED, &pi->flags),
test_bit(CH_READY, &pi->flags));
spin_unlock_irqrestore(&port->port_lock, flags);
}
ret = simple_read_from_buffer(ubuf, count, ppos, buf, temp);
kfree(buf);
return ret;
}
static ssize_t debug_smd_reset_stats(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct gsmd_port *port;
unsigned long flags;
int i;
for (i = 0; i < n_smd_ports; i++) {
port = smd_ports[i].port;
spin_lock_irqsave(&port->port_lock, flags);
port->nbytes_tolaptop = 0;
port->nbytes_tomodem = 0;
spin_unlock_irqrestore(&port->port_lock, flags);
}
return count;
}
static int debug_smd_open(struct inode *inode, struct file *file)
{
return 0;
}
static const struct file_operations debug_gsmd_ops = {
.open = debug_smd_open,
.read = debug_smd_read_stats,
.write = debug_smd_reset_stats,
};
static void gsmd_debugfs_init(void)
{
struct dentry *dent;
dent = debugfs_create_dir("usb_gsmd", 0);
if (IS_ERR(dent))
return;
debugfs_create_file("status", 0444, dent, 0, &debug_gsmd_ops);
}
#else
static void gsmd_debugfs_init(void) {}
#endif
int gsmd_setup(struct usb_gadget *g, unsigned count)
{
struct usb_cdc_line_coding coding;
int ret;
int i;
pr_debug("%s: g:%p count: %d\n", __func__, g, count);
if (!count || count > SMD_N_PORTS) {
pr_err("%s: Invalid num of ports count:%d gadget:%p\n",
__func__, count, g);
return -EINVAL;
}
coding.dwDTERate = cpu_to_le32(9600);
coding.bCharFormat = 8;
coding.bParityType = USB_CDC_NO_PARITY;
coding.bDataBits = USB_CDC_1_STOP_BITS;
gsmd_wq = create_singlethread_workqueue("k_gsmd");
if (!gsmd_wq) {
pr_err("%s: Unable to create workqueue gsmd_wq\n",
__func__);
return -ENOMEM;
}
for (i = 0; i < count; i++) {
mutex_init(&smd_ports[i].lock);
n_smd_ports++;
ret = gsmd_port_alloc(i, &coding);
if (ret) {
n_smd_ports--;
pr_err("%s: Unable to alloc port:%d\n", __func__, i);
goto free_smd_ports;
}
}
gsmd_debugfs_init();
return 0;
free_smd_ports:
for (i = 0; i < n_smd_ports; i++)
gsmd_port_free(i);
destroy_workqueue(gsmd_wq);
return ret;
}
void gsmd_cleanup(struct usb_gadget *g, unsigned count)
{
/* TBD */
}
|
MoKee/android_kernel_huawei_msm8226
|
drivers/usb/gadget/u_smd.c
|
C
|
gpl-2.0
| 22,817 |
/*
Nord Modular Midi Protocol 3.03 Library
Copyright (C) 2003-2006 Marcus Andersson
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
*/
package net.sf.nmedit.jnmprotocol;
import net.sf.nmedit.jnmprotocol.MidiMessage;
/**
* Processes incoming messages.
*/
public interface MessageHandler
{
void processMessage(MidiMessage message);
}
|
wesen/nmedit
|
libs/jnmprotocol/src/net/sf/nmedit/jnmprotocol/MessageHandler.java
|
Java
|
gpl-2.0
| 1,032 |
/**********************************************************************
*
* ibmbits.c - bitmap bits accessing
*
* FEATURES:
*
* - up to 64 pixel-formats supported
* - fetching pixel from any pixel-formats to card(A8R8G8B8)
* - storing card(A8R8G8B8) to any pixel-formats
* - drawing scanline (copy/blend/additive) to any pixel-formats
* - blit (with/without color key) between bitmaps
* - converting between any formats to another
* - compositing with 35 operators
* - many useful macros to access/process pixels
* - all the routines can be replaced by calling **_set_**
* - using 203KB static memory for look-up-tables
*
* HISTORY:
*
* 2009.09.12 skywind create this file
* 2009.12.07 skywind optimize fetch and store
* 2009.12.30 skywind optimize 16 bits convertion using lut
* 2010.01.05 skywind implement scanline blending & additive
* 2010.03.07 skywind implement hline blending & additive
* 2010.10.25 skywind implement bliting and converting and cliping
* 2011.03.04 skywind implement card operations
* 2011.08.10 skywind implement compositing
*
**********************************************************************/
#include "ibmbits.h"
/**********************************************************************
* GLOBAL VARIABLES
**********************************************************************/
/* pixel format declare */
const struct IPIXELFMT ipixelfmt[64] =
{
{ IPIX_FMT_A8R8G8B8, 32, 1, 0, 4, "IPIX_FMT_A8R8G8B8",
0xff0000, 0xff00, 0xff, 0xff000000, 16, 8, 0, 24, 0, 0, 0, 0 },
{ IPIX_FMT_A8B8G8R8, 32, 1, 0, 4, "IPIX_FMT_A8B8G8R8",
0xff, 0xff00, 0xff0000, 0xff000000, 0, 8, 16, 24, 0, 0, 0, 0 },
{ IPIX_FMT_R8G8B8A8, 32, 1, 0, 4, "IPIX_FMT_R8G8B8A8",
0xff000000, 0xff0000, 0xff00, 0xff, 24, 16, 8, 0, 0, 0, 0, 0 },
{ IPIX_FMT_B8G8R8A8, 32, 1, 0, 4, "IPIX_FMT_B8G8R8A8",
0xff00, 0xff0000, 0xff000000, 0xff, 8, 16, 24, 0, 0, 0, 0, 0 },
{ IPIX_FMT_X8R8G8B8, 32, 0, 1, 4, "IPIX_FMT_X8R8G8B8",
0xff0000, 0xff00, 0xff, 0x0, 16, 8, 0, 0, 0, 0, 0, 8 },
{ IPIX_FMT_X8B8G8R8, 32, 0, 1, 4, "IPIX_FMT_X8B8G8R8",
0xff, 0xff00, 0xff0000, 0x0, 0, 8, 16, 0, 0, 0, 0, 8 },
{ IPIX_FMT_R8G8B8X8, 32, 0, 1, 4, "IPIX_FMT_R8G8B8X8",
0xff000000, 0xff0000, 0xff00, 0x0, 24, 16, 8, 0, 0, 0, 0, 8 },
{ IPIX_FMT_B8G8R8X8, 32, 0, 1, 4, "IPIX_FMT_B8G8R8X8",
0xff00, 0xff0000, 0xff000000, 0x0, 8, 16, 24, 0, 0, 0, 0, 8 },
{ IPIX_FMT_P8R8G8B8, 32, 1, 5, 4, "IPIX_FMT_P8R8G8B8",
0xff0000, 0xff00, 0xff, 0x0, 16, 8, 0, 0, 0, 0, 0, 8 },
{ IPIX_FMT_R8G8B8, 24, 0, 1, 3, "IPIX_FMT_R8G8B8",
0xff0000, 0xff00, 0xff, 0x0, 16, 8, 0, 0, 0, 0, 0, 8 },
{ IPIX_FMT_B8G8R8, 24, 0, 1, 3, "IPIX_FMT_B8G8R8",
0xff, 0xff00, 0xff0000, 0x0, 0, 8, 16, 0, 0, 0, 0, 8 },
{ IPIX_FMT_R5G6B5, 16, 0, 1, 2, "IPIX_FMT_R5G6B5",
0xf800, 0x7e0, 0x1f, 0x0, 11, 5, 0, 0, 3, 2, 3, 8 },
{ IPIX_FMT_B5G6R5, 16, 0, 1, 2, "IPIX_FMT_B5G6R5",
0x1f, 0x7e0, 0xf800, 0x0, 0, 5, 11, 0, 3, 2, 3, 8 },
{ IPIX_FMT_X1R5G5B5, 16, 0, 1, 2, "IPIX_FMT_X1R5G5B5",
0x7c00, 0x3e0, 0x1f, 0x0, 10, 5, 0, 0, 3, 3, 3, 8 },
{ IPIX_FMT_X1B5G5R5, 16, 0, 1, 2, "IPIX_FMT_X1B5G5R5",
0x1f, 0x3e0, 0x7c00, 0x0, 0, 5, 10, 0, 3, 3, 3, 8 },
{ IPIX_FMT_R5G5B5X1, 16, 0, 1, 2, "IPIX_FMT_R5G5B5X1",
0xf800, 0x7c0, 0x3e, 0x0, 11, 6, 1, 0, 3, 3, 3, 8 },
{ IPIX_FMT_B5G5R5X1, 16, 0, 1, 2, "IPIX_FMT_B5G5R5X1",
0x3e, 0x7c0, 0xf800, 0x0, 1, 6, 11, 0, 3, 3, 3, 8 },
{ IPIX_FMT_A1R5G5B5, 16, 1, 0, 2, "IPIX_FMT_A1R5G5B5",
0x7c00, 0x3e0, 0x1f, 0x8000, 10, 5, 0, 15, 3, 3, 3, 7 },
{ IPIX_FMT_A1B5G5R5, 16, 1, 0, 2, "IPIX_FMT_A1B5G5R5",
0x1f, 0x3e0, 0x7c00, 0x8000, 0, 5, 10, 15, 3, 3, 3, 7 },
{ IPIX_FMT_R5G5B5A1, 16, 1, 0, 2, "IPIX_FMT_R5G5B5A1",
0xf800, 0x7c0, 0x3e, 0x1, 11, 6, 1, 0, 3, 3, 3, 7 },
{ IPIX_FMT_B5G5R5A1, 16, 1, 0, 2, "IPIX_FMT_B5G5R5A1",
0x3e, 0x7c0, 0xf800, 0x1, 1, 6, 11, 0, 3, 3, 3, 7 },
{ IPIX_FMT_X4R4G4B4, 16, 0, 1, 2, "IPIX_FMT_X4R4G4B4",
0xf00, 0xf0, 0xf, 0x0, 8, 4, 0, 0, 4, 4, 4, 8 },
{ IPIX_FMT_X4B4G4R4, 16, 0, 1, 2, "IPIX_FMT_X4B4G4R4",
0xf, 0xf0, 0xf00, 0x0, 0, 4, 8, 0, 4, 4, 4, 8 },
{ IPIX_FMT_R4G4B4X4, 16, 0, 1, 2, "IPIX_FMT_R4G4B4X4",
0xf000, 0xf00, 0xf0, 0x0, 12, 8, 4, 0, 4, 4, 4, 8 },
{ IPIX_FMT_B4G4R4X4, 16, 0, 1, 2, "IPIX_FMT_B4G4R4X4",
0xf0, 0xf00, 0xf000, 0x0, 4, 8, 12, 0, 4, 4, 4, 8 },
{ IPIX_FMT_A4R4G4B4, 16, 1, 0, 2, "IPIX_FMT_A4R4G4B4",
0xf00, 0xf0, 0xf, 0xf000, 8, 4, 0, 12, 4, 4, 4, 4 },
{ IPIX_FMT_A4B4G4R4, 16, 1, 0, 2, "IPIX_FMT_A4B4G4R4",
0xf, 0xf0, 0xf00, 0xf000, 0, 4, 8, 12, 4, 4, 4, 4 },
{ IPIX_FMT_R4G4B4A4, 16, 1, 0, 2, "IPIX_FMT_R4G4B4A4",
0xf000, 0xf00, 0xf0, 0xf, 12, 8, 4, 0, 4, 4, 4, 4 },
{ IPIX_FMT_B4G4R4A4, 16, 1, 0, 2, "IPIX_FMT_B4G4R4A4",
0xf0, 0xf00, 0xf000, 0xf, 4, 8, 12, 0, 4, 4, 4, 4 },
{ IPIX_FMT_C8, 8, 0, 2, 1, "IPIX_FMT_C8",
0x0, 0x0, 0x0, 0x0, 0, 0, 0, 0, 8, 8, 8, 8 },
{ IPIX_FMT_G8, 8, 0, 3, 1, "IPIX_FMT_G8",
0x0, 0xff, 0x0, 0x0, 0, 0, 0, 0, 8, 0, 8, 8 },
{ IPIX_FMT_A8, 8, 1, 4, 1, "IPIX_FMT_A8",
0x0, 0x0, 0x0, 0xff, 0, 0, 0, 0, 8, 8, 8, 0 },
{ IPIX_FMT_R3G3B2, 8, 0, 1, 1, "IPIX_FMT_R3G3B2",
0xe0, 0x1c, 0x3, 0x0, 5, 2, 0, 0, 5, 5, 6, 8 },
{ IPIX_FMT_B2G3R3, 8, 0, 1, 1, "IPIX_FMT_B2G3R3",
0x7, 0x38, 0xc0, 0x0, 0, 3, 6, 0, 5, 5, 6, 8 },
{ IPIX_FMT_X2R2G2B2, 8, 0, 1, 1, "IPIX_FMT_X2R2G2B2",
0x30, 0xc, 0x3, 0x0, 4, 2, 0, 0, 6, 6, 6, 8 },
{ IPIX_FMT_X2B2G2R2, 8, 0, 1, 1, "IPIX_FMT_X2B2G2R2",
0x3, 0xc, 0x30, 0x0, 0, 2, 4, 0, 6, 6, 6, 8 },
{ IPIX_FMT_R2G2B2X2, 8, 0, 1, 1, "IPIX_FMT_R2G2B2X2",
0xc0, 0x30, 0xc, 0x0, 6, 4, 2, 0, 6, 6, 6, 8 },
{ IPIX_FMT_B2G2R2X2, 8, 0, 1, 1, "IPIX_FMT_B2G2R2X2",
0xc, 0x30, 0xc0, 0x0, 2, 4, 6, 0, 6, 6, 6, 8 },
{ IPIX_FMT_A2R2G2B2, 8, 1, 0, 1, "IPIX_FMT_A2R2G2B2",
0x30, 0xc, 0x3, 0xc0, 4, 2, 0, 6, 6, 6, 6, 6 },
{ IPIX_FMT_A2B2G2R2, 8, 1, 0, 1, "IPIX_FMT_A2B2G2R2",
0x3, 0xc, 0x30, 0xc0, 0, 2, 4, 6, 6, 6, 6, 6 },
{ IPIX_FMT_R2G2B2A2, 8, 1, 0, 1, "IPIX_FMT_R2G2B2A2",
0xc0, 0x30, 0xc, 0x3, 6, 4, 2, 0, 6, 6, 6, 6 },
{ IPIX_FMT_B2G2R2A2, 8, 1, 0, 1, "IPIX_FMT_B2G2R2A2",
0xc, 0x30, 0xc0, 0x3, 2, 4, 6, 0, 6, 6, 6, 6 },
{ IPIX_FMT_X4C4, 8, 0, 2, 1, "IPIX_FMT_X4C4",
0x0, 0x0, 0x0, 0x0, 0, 0, 0, 0, 8, 8, 8, 8 },
{ IPIX_FMT_X4G4, 8, 0, 3, 1, "IPIX_FMT_X4G4",
0x0, 0xf, 0x0, 0x0, 0, 0, 0, 0, 8, 4, 8, 8 },
{ IPIX_FMT_X4A4, 8, 1, 4, 1, "IPIX_FMT_X4A4",
0x0, 0x0, 0x0, 0xf, 0, 0, 0, 0, 8, 8, 8, 4 },
{ IPIX_FMT_C4X4, 8, 0, 2, 1, "IPIX_FMT_C4X4",
0x0, 0x0, 0x0, 0x0, 0, 0, 0, 0, 8, 8, 8, 8 },
{ IPIX_FMT_G4X4, 8, 0, 3, 1, "IPIX_FMT_G4X4",
0x0, 0xf0, 0x0, 0x0, 0, 4, 0, 0, 8, 4, 8, 8 },
{ IPIX_FMT_A4X4, 8, 1, 4, 1, "IPIX_FMT_A4X4",
0x0, 0x0, 0x0, 0xf0, 0, 0, 0, 4, 8, 8, 8, 4 },
{ IPIX_FMT_C4, 4, 0, 2, 0, "IPIX_FMT_C4",
0x0, 0x0, 0x0, 0x0, 0, 0, 0, 0, 8, 8, 8, 8 },
{ IPIX_FMT_G4, 4, 0, 3, 0, "IPIX_FMT_G4",
0x0, 0xf, 0x0, 0x0, 0, 0, 0, 0, 8, 4, 8, 8 },
{ IPIX_FMT_A4, 4, 1, 4, 0, "IPIX_FMT_A4",
0x0, 0x0, 0x0, 0xf, 0, 0, 0, 0, 8, 8, 8, 4 },
{ IPIX_FMT_R1G2B1, 4, 0, 1, 0, "IPIX_FMT_R1G2B1",
0x8, 0x6, 0x1, 0x0, 3, 1, 0, 0, 7, 6, 7, 8 },
{ IPIX_FMT_B1G2R1, 4, 0, 1, 0, "IPIX_FMT_B1G2R1",
0x1, 0x6, 0x8, 0x0, 0, 1, 3, 0, 7, 6, 7, 8 },
{ IPIX_FMT_A1R1G1B1, 4, 1, 0, 0, "IPIX_FMT_A1R1G1B1",
0x4, 0x2, 0x1, 0x8, 2, 1, 0, 3, 7, 7, 7, 7 },
{ IPIX_FMT_A1B1G1R1, 4, 1, 0, 0, "IPIX_FMT_A1B1G1R1",
0x1, 0x2, 0x4, 0x8, 0, 1, 2, 3, 7, 7, 7, 7 },
{ IPIX_FMT_R1G1B1A1, 4, 1, 0, 0, "IPIX_FMT_R1G1B1A1",
0x8, 0x4, 0x2, 0x1, 3, 2, 1, 0, 7, 7, 7, 7 },
{ IPIX_FMT_B1G1R1A1, 4, 1, 0, 0, "IPIX_FMT_B1G1R1A1",
0x2, 0x4, 0x8, 0x1, 1, 2, 3, 0, 7, 7, 7, 7 },
{ IPIX_FMT_X1R1G1B1, 4, 0, 1, 0, "IPIX_FMT_X1R1G1B1",
0x4, 0x2, 0x1, 0x0, 2, 1, 0, 0, 7, 7, 7, 8 },
{ IPIX_FMT_X1B1G1R1, 4, 0, 1, 0, "IPIX_FMT_X1B1G1R1",
0x1, 0x2, 0x4, 0x0, 0, 1, 2, 0, 7, 7, 7, 8 },
{ IPIX_FMT_R1G1B1X1, 4, 0, 1, 0, "IPIX_FMT_R1G1B1X1",
0x8, 0x4, 0x2, 0x0, 3, 2, 1, 0, 7, 7, 7, 8 },
{ IPIX_FMT_B1G1R1X1, 4, 0, 1, 0, "IPIX_FMT_B1G1R1X1",
0x2, 0x4, 0x8, 0x0, 1, 2, 3, 0, 7, 7, 7, 8 },
{ IPIX_FMT_C1, 1, 0, 2, 0, "IPIX_FMT_C1",
0x0, 0x0, 0x0, 0x0, 0, 0, 0, 0, 8, 8, 8, 8 },
{ IPIX_FMT_G1, 1, 0, 3, 0, "IPIX_FMT_G1",
0x0, 0x1, 0x0, 0x0, 0, 0, 0, 0, 8, 7, 8, 8 },
{ IPIX_FMT_A1, 1, 1, 4, 0, "IPIX_FMT_A1",
0x0, 0x0, 0x0, 0x1, 0, 0, 0, 0, 8, 8, 8, 7 },
};
/* lookup table for scaling 1 bit colors up to 8 bits */
const IUINT32 _ipixel_scale_1[2] = { 0, 255 };
/* lookup table for scaling 2 bit colors up to 8 bits */
const IUINT32 _ipixel_scale_2[4] = { 0, 85, 170, 255 };
/* lookup table for scaling 3 bit colors up to 8 bits */
const IUINT32 _ipixel_scale_3[8] = { 0, 36, 72, 109, 145, 182, 218, 255 };
/* lookup table for scaling 4 bit colors up to 8 bits */
const IUINT32 _ipixel_scale_4[16] =
{
0, 16, 32, 49, 65, 82, 98, 115,
139, 156, 172, 189, 205, 222, 238, 255
};
/* lookup table for scaling 5 bit colors up to 8 bits */
const IUINT32 _ipixel_scale_5[32] =
{
0, 8, 16, 24, 32, 41, 49, 57,
65, 74, 82, 90, 98, 106, 115, 123,
131, 139, 148, 156, 164, 172, 180, 189,
197, 205, 213, 222, 230, 238, 246, 255
};
/* lookup table for scaling 6 bit colors up to 8 bits */
const IUINT32 _ipixel_scale_6[64] =
{
0, 4, 8, 12, 16, 20, 24, 28,
32, 36, 40, 44, 48, 52, 56, 60,
64, 68, 72, 76, 80, 85, 89, 93,
97, 101, 105, 109, 113, 117, 121, 125,
129, 133, 137, 141, 145, 149, 153, 157,
161, 165, 170, 174, 178, 182, 186, 190,
194, 198, 202, 206, 210, 214, 218, 222,
226, 230, 234, 238, 242, 246, 250, 255
};
/* default color index */
static iColorIndex _ipixel_static_index[2];
iColorIndex *_ipixel_src_index = &_ipixel_static_index[0];
iColorIndex *_ipixel_dst_index = &_ipixel_static_index[1];
/* default palette */
IRGB _ipaletted[256];
/* 8 bits min/max saturation table */
const unsigned char IMINMAX256[770] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133,
134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,
149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193,
194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208,
209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238,
239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255,
};
const unsigned char *iclip256 = &IMINMAX256[256];
unsigned char ipixel_blend_lut[2048 * 2];
unsigned char _ipixel_mullut[256][256]; /* [x][y] = x * y / 255 */
unsigned char _ipixel_divlut[256][256]; /* [x][y] = y * 255 / x */
#if defined(__BORLANDC__) && !defined(__MSDOS__)
#pragma warn -8004
#pragma warn -8057
#endif
/**********************************************************************
* 256 PALETTE INTERFACE
**********************************************************************/
/* find best fit color */
int ibestfit_color(const IRGB *pal, int r, int g, int b, int palsize)
{
static IUINT32 diff_lookup[512 * 3] = { 0 };
long lowest = 0x7FFFFFFF, bestfit = 0;
long coldiff, i, k;
IRGB *rgb;
/* calculate color difference lookup table:
* COLOR DIFF TABLE
* table1: diff_lookup[i | i = 256->511, n=0->(+255)] = (n * 30) ^ 2
* table2: diff_lookup[i | i = 256->1, n=0->(-255)] = (n * 30) ^ 2
* result: f(n) = (n * 30) ^ 2 = diff_lookup[256 + n]
*/
if (diff_lookup[0] == 0) {
for (i = 0; i < 256; i++) {
k = i * i;
diff_lookup[ 256 + i] = diff_lookup[ 256 - i] = k * 30 * 30;
diff_lookup[ 768 + i] = diff_lookup[ 768 - i] = k * 59 * 59;
diff_lookup[1280 + i] = diff_lookup[1280 - i] = k * 11 * 11;
}
diff_lookup[0] = 1;
}
/* range correction */
r = r & 255;
g = g & 255;
b = b & 255;
/*
* vector: c1 = [r1, g1, b1], c2 = [r2, g2, b2]
* distance: dc = length(c1 - c2)
* coldiff: dc^2 = (r1 - r2)^2 + (g1 - g2)^2 + (b1 - b2)^2
*/
for (i = palsize, rgb = (IRGB*)pal; i > 0; rgb++, i--) {
coldiff = diff_lookup[ 768 + rgb->g - g];
if (coldiff >= lowest) continue;
coldiff += diff_lookup[ 256 + rgb->r - r];
if (coldiff >= lowest) continue;
coldiff += diff_lookup[1280 + rgb->b - b];
if (coldiff >= lowest) continue;
bestfit = (int)(rgb - (IRGB*)pal); /* faster than `bestfit = i;' */
if (coldiff == 0) return bestfit;
lowest = coldiff;
}
return bestfit;
}
/* convert palette to index */
int ipalette_to_index(iColorIndex *index, const IRGB *pal, int palsize)
{
IUINT32 r, g, b, a;
int i;
index->color = palsize;
for (i = 0; i < palsize; i++) {
r = pal[i].r;
g = pal[i].g;
b = pal[i].b;
a = 255;
index->rgba[i] = IRGBA_TO_PIXEL(A8R8G8B8, r, g, b, a);
}
for (i = 0; i < 0x8000; i++) {
IRGBA_FROM_PIXEL(X1R5G5B5, i, r, g, b, a);
index->ent[i] = ibestfit_color(pal, r, g, b, palsize);
}
return 0;
}
/* get raw color */
IUINT32 ipixel_assemble(int pixfmt, int r, int g, int b, int a)
{
IUINT32 c;
IRGBA_ASSEMBLE(pixfmt, c, r, g, b, a);
return c;
}
/* get r, g, b, a from color */
void ipixel_desemble(int pixfmt, IUINT32 c, IINT32 *r, IINT32 *g,
IINT32 *b, IINT32 *a)
{
IINT32 R, G, B, A;
IRGBA_DISEMBLE(pixfmt, c, R, G, B, A);
*r = R;
*g = G;
*b = B;
*a = A;
}
/**********************************************************************
* Fast 1/2 byte -> 4 byte
**********************************************************************/
void ipixel_lut_2_to_4(int sfmt, int dfmt, IUINT32 *table)
{
IUINT32 c;
if (ipixelfmt[sfmt].pixelbyte != 2 || ipixelfmt[dfmt].pixelbyte != 4) {
assert(0);
return;
}
for (c = 0; c < 256; c++) {
IUINT32 r1, g1, b1, a1;
IUINT32 r2, g2, b2, a2;
IUINT32 c1, c2;
#if IWORDS_BIG_ENDIAN
c1 = c << 8;
c2 = c;
#else
c1 = c;
c2 = c << 8;
#endif
IRGBA_DISEMBLE(sfmt, c1, r1, g1, b1, a1);
IRGBA_DISEMBLE(sfmt, c2, r2, g2, b2, a2);
IRGBA_ASSEMBLE(dfmt, c1, r1, g1, b1, a1);
IRGBA_ASSEMBLE(dfmt, c2, r2, g2, b2, a2);
table[c + 0] = c1;
table[c + 256] = c2;
}
}
void ipixel_lut_1_to_4(int sfmt, int dfmt, IUINT32 *table)
{
IUINT32 c;
if (ipixelfmt[sfmt].pixelbyte != 1 || ipixelfmt[dfmt].pixelbyte != 4) {
assert(0);
return;
}
for (c = 0; c < 256; c++) {
IUINT32 c1, r1, g1, b1, a1;
c1 = c;
IRGBA_DISEMBLE(sfmt, c1, r1, g1, b1, a1);
IRGBA_ASSEMBLE(dfmt, c1, r1, g1, b1, a1);
table[c] = c1;
}
}
void ipixel_lut_conv_2(IUINT32 *dst, const IUINT16 *src, int w,
const IUINT32 *lut)
{
const IUINT8 *input = (const IUINT8*)src;
IUINT32 c1, c2, c3, c4;
ILINS_LOOP_DOUBLE(
{
c1 = lut[*input++ + 0];
c2 = lut[*input++ + 256];
*dst++ = c1 | c2;
},
{
c1 = lut[*input++ + 0];
c2 = lut[*input++ + 256];
c3 = lut[*input++ + 0];
c4 = lut[*input++ + 256];
c1 |= c2;
c3 |= c4;
*dst++ = c1;
*dst++ = c3;
},
w);
}
void ipixel_lut_conv_1(IUINT32 *dst, const IUINT16 *src, int w,
const IUINT32 *lut)
{
const IUINT8 *input = (const IUINT8*)src;
IUINT32 c1, c2;
ILINS_LOOP_DOUBLE(
{
*dst++ = lut[*input++];
},
{
c1 = lut[*input++];
c2 = lut[*input++];
*dst++ = c1;
*dst++ = c2;
},
w);
}
/**********************************************************************
* DEFAULT FETCH PROC
**********************************************************************/
#define IFETCH_PROC(fmt, bpp) \
static void _ifetch_proc_##fmt(const void *bits, int x, \
int w, IUINT32 *buffer, const iColorIndex *_ipixel_src_index) \
{ \
IUINT32 c1, r1, g1, b1, a1, c2, r2, g2, b2, a2; \
int y = x + 1; \
ILINS_LOOP_DOUBLE( \
{ \
c1 = _ipixel_fetch(bpp, bits, x); \
x++; \
y++; \
IRGBA_FROM_PIXEL(fmt, c1, r1, g1, b1, a1); \
c1 = IRGBA_TO_PIXEL(A8R8G8B8, r1, g1, b1, a1); \
*buffer++ = c1; \
}, \
{ \
c1 = _ipixel_fetch(bpp, bits, x); \
c2 = _ipixel_fetch(bpp, bits, y); \
x += 2; \
y += 2; \
IRGBA_FROM_PIXEL(fmt, c1, r1, g1, b1, a1); \
IRGBA_FROM_PIXEL(fmt, c2, r2, g2, b2, a2); \
c1 = IRGBA_TO_PIXEL(A8R8G8B8, r1, g1, b1, a1); \
c2 = IRGBA_TO_PIXEL(A8R8G8B8, r2, g2, b2, a2); \
*buffer++ = c1; \
*buffer++ = c2; \
}, \
w); \
_ipixel_src_index = _ipixel_src_index; \
}
/**********************************************************************
* DEFAULT STORE PROC
**********************************************************************/
#define ISTORE_PROC(fmt, bpp) \
static void _istore_proc_##fmt(void *bits, const IUINT32 *values, \
int x, int w, const iColorIndex *_ipixel_dst_index) \
{ \
IUINT32 c1, r1, g1, b1, a1, c2, r2, g2, b2, a2; \
int y = x + 1; \
ILINS_LOOP_DOUBLE( \
{ \
c1 = *values++; \
IRGBA_FROM_PIXEL(A8R8G8B8, c1, r1, g1, b1, a1); \
c1 = IRGBA_TO_PIXEL(fmt, r1, g1, b1, a1); \
_ipixel_store(bpp, bits, x, c1); \
x++; \
y++; \
}, \
{ \
c1 = *values++; \
c2 = *values++; \
IRGBA_FROM_PIXEL(A8R8G8B8, c1, r1, g1, b1, a1); \
IRGBA_FROM_PIXEL(A8R8G8B8, c2, r2, g2, b2, a2); \
c1 = IRGBA_TO_PIXEL(fmt, r1, g1, b1, a1); \
c2 = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, bits, x, c1); \
_ipixel_store(bpp, bits, y, c2); \
x += 2; \
y += 2; \
}, \
w); \
_ipixel_dst_index = _ipixel_dst_index; \
}
/**********************************************************************
* DEFAULT PIXEL FETCH PROC
**********************************************************************/
#define IFETCH_PIXEL(fmt, bpp) \
static IUINT32 _ifetch_pixel_##fmt(const void *bits, \
int offset, const iColorIndex *_ipixel_src_index) \
{ \
IUINT32 c, r, g, b, a; \
c = _ipixel_fetch(bpp, bits, offset); \
IRGBA_FROM_PIXEL(fmt, c, r, g, b, a); \
return IRGBA_TO_PIXEL(A8R8G8B8, r, g, b, a); \
}
/**********************************************************************
* FETCHING PROCEDURES
**********************************************************************/
static void _ifetch_proc_A8R8G8B8(const void *bits, int x,
int w, IUINT32 *buffer, const iColorIndex *idx)
{
memcpy(buffer, (const IUINT32*)bits + x, w * sizeof(IUINT32));
}
static void _ifetch_proc_A8B8G8R8(const void *bits, int x,
int w, IUINT32 *buffer, const iColorIndex *idx)
{
const IUINT32 *pixel = (const IUINT32*)bits + x;
ILINS_LOOP_DOUBLE(
{
*buffer++ = ((*pixel & 0xff00ff00) |
((*pixel & 0xff0000) >> 16) | ((*pixel & 0xff) << 16));
pixel++;
},
{
*buffer++ = ((*pixel & 0xff00ff00) |
((*pixel & 0xff0000) >> 16) | ((*pixel & 0xff) << 16));
pixel++;
*buffer++ = ((*pixel & 0xff00ff00) |
((*pixel & 0xff0000) >> 16) | ((*pixel & 0xff) << 16));
pixel++;
},
w);
}
static void _ifetch_proc_R8G8B8A8(const void *bits, int x,
int w, IUINT32 *buffer, const iColorIndex *idx)
{
const IUINT32 *pixel = (const IUINT32*)bits + x;
ILINS_LOOP_DOUBLE(
{
*buffer++ = ((*pixel & 0xff) << 24) |
((*pixel & 0xffffff00) >> 8);
pixel++;
},
{
*buffer++ = ((*pixel & 0xff) << 24) |
((*pixel & 0xffffff00) >> 8);
pixel++;
*buffer++ = ((*pixel & 0xff) << 24) |
((*pixel & 0xffffff00) >> 8);
pixel++;
},
w);
}
IFETCH_PROC(B8G8R8A8, 32)
static void _ifetch_proc_X8R8G8B8(const void *bits, int x,
int w, IUINT32 *buffer, const iColorIndex *idx)
{
const IUINT32 *pixel = (const IUINT32*)bits + x;
ILINS_LOOP_DOUBLE(
{
*buffer++ = *pixel++ | 0xff000000;
},
{
*buffer++ = *pixel++ | 0xff000000;
*buffer++ = *pixel++ | 0xff000000;
},
w);
}
IFETCH_PROC(X8B8G8R8, 32)
static void _ifetch_proc_R8G8B8X8(const void *bits, int x,
int w, IUINT32 *buffer, const iColorIndex *idx)
{
const IUINT32 *pixel = (const IUINT32*)bits + x;
ILINS_LOOP_DOUBLE(
{
*buffer++ = (0xff000000) |
((*pixel & 0xffffff00) >> 8);
pixel++;
},
{
*buffer++ = (0xff000000) |
((*pixel & 0xffffff00) >> 8);
pixel++;
*buffer++ = (0xff000000) |
((*pixel & 0xffffff00) >> 8);
pixel++;
},
w);
}
IFETCH_PROC(B8G8R8X8, 32)
IFETCH_PROC(P8R8G8B8, 32)
static void _ifetch_proc_R8G8B8(const void *bits, int x,
int w, IUINT32 *buffer, const iColorIndex *idx)
{
const IUINT8 *pixel = (const IUINT8*)bits + x * 3;
ILINS_LOOP_DOUBLE(
{
*buffer++ = IFETCH24(pixel) | 0xff000000;
pixel += 3;
},
{
*buffer++ = IFETCH24(pixel) | 0xff000000;
pixel += 3;
*buffer++ = IFETCH24(pixel) | 0xff000000;
pixel += 3;
},
w);
}
IFETCH_PROC(B8G8R8, 24)
IFETCH_PROC(R5G6B5, 16)
IFETCH_PROC(B5G6R5, 16)
IFETCH_PROC(X1R5G5B5, 16)
IFETCH_PROC(X1B5G5R5, 16)
IFETCH_PROC(R5G5B5X1, 16)
IFETCH_PROC(B5G5R5X1, 16)
IFETCH_PROC(A1R5G5B5, 16)
IFETCH_PROC(A1B5G5R5, 16)
IFETCH_PROC(R5G5B5A1, 16)
IFETCH_PROC(B5G5R5A1, 16)
IFETCH_PROC(X4R4G4B4, 16)
IFETCH_PROC(X4B4G4R4, 16)
IFETCH_PROC(R4G4B4X4, 16)
IFETCH_PROC(B4G4R4X4, 16)
IFETCH_PROC(A4R4G4B4, 16)
IFETCH_PROC(A4B4G4R4, 16)
IFETCH_PROC(R4G4B4A4, 16)
IFETCH_PROC(B4G4R4A4, 16)
IFETCH_PROC(C8, 8)
IFETCH_PROC(G8, 8)
IFETCH_PROC(A8, 8)
IFETCH_PROC(R3G3B2, 8)
IFETCH_PROC(B2G3R3, 8)
IFETCH_PROC(X2R2G2B2, 8)
IFETCH_PROC(X2B2G2R2, 8)
IFETCH_PROC(R2G2B2X2, 8)
IFETCH_PROC(B2G2R2X2, 8)
IFETCH_PROC(A2R2G2B2, 8)
IFETCH_PROC(A2B2G2R2, 8)
IFETCH_PROC(R2G2B2A2, 8)
IFETCH_PROC(B2G2R2A2, 8)
IFETCH_PROC(X4C4, 8)
IFETCH_PROC(X4G4, 8)
IFETCH_PROC(X4A4, 8)
IFETCH_PROC(C4X4, 8)
IFETCH_PROC(G4X4, 8)
IFETCH_PROC(A4X4, 8)
IFETCH_PROC(C4, 4)
IFETCH_PROC(G4, 4)
IFETCH_PROC(A4, 4)
IFETCH_PROC(R1G2B1, 4)
IFETCH_PROC(B1G2R1, 4)
IFETCH_PROC(A1R1G1B1, 4)
IFETCH_PROC(A1B1G1R1, 4)
IFETCH_PROC(R1G1B1A1, 4)
IFETCH_PROC(B1G1R1A1, 4)
IFETCH_PROC(X1R1G1B1, 4)
IFETCH_PROC(X1B1G1R1, 4)
IFETCH_PROC(R1G1B1X1, 4)
IFETCH_PROC(B1G1R1X1, 4)
IFETCH_PROC(C1, 1)
IFETCH_PROC(G1, 1)
IFETCH_PROC(A1, 1)
/**********************************************************************
* STORING PROCEDURES
**********************************************************************/
static void _istore_proc_A8R8G8B8(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
memcpy(((IUINT32*)bits) + x, values, w * sizeof(IUINT32));
}
static void _istore_proc_A8B8G8R8(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT32 *pixel = (IUINT32*)bits + x;
ILINS_LOOP_DOUBLE(
{
*pixel++ = (values[0] & 0xff00ff00) |
((values[0] & 0xff0000) >> 16) | ((values[0] & 0xff) << 16);
values++;
},
{
*pixel++ = (values[0] & 0xff00ff00) |
((values[0] & 0xff0000) >> 16) | ((values[0] & 0xff) << 16);
values++;
*pixel++ = (values[0] & 0xff00ff00) |
((values[0] & 0xff0000) >> 16) | ((values[0] & 0xff) << 16);
values++;
},
w);
}
static void _istore_proc_R8G8B8A8(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT32 *pixel = (IUINT32*)bits + x;
ILINS_LOOP_DOUBLE(
{
*pixel++ = ((values[0] & 0xffffff) << 8) |
((values[0] & 0xff000000) >> 24);
values++;
},
{
*pixel++ = ((values[0] & 0xffffff) << 8) |
((values[0] & 0xff000000) >> 24);
values++;
*pixel++ = ((values[0] & 0xffffff) << 8) |
((values[0] & 0xff000000) >> 24);
values++;
},
w);
}
ISTORE_PROC(B8G8R8A8, 32)
static void _istore_proc_X8R8G8B8(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT32 *pixel = (IUINT32*)bits + x;
ILINS_LOOP_DOUBLE(
{
*pixel++ = values[0] & 0xffffff;
values++;
},
{
*pixel++ = values[0] & 0xffffff;
values++;
*pixel++ = values[0] & 0xffffff;
values++;
},
w);
}
ISTORE_PROC(X8B8G8R8, 32)
static void _istore_proc_R8G8B8X8(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT32 *pixel = (IUINT32*)bits + x;
ILINS_LOOP_DOUBLE(
{
*pixel++ = ((values[0] & 0xffffff) << 8);
values++;
},
{
*pixel++ = ((values[0] & 0xffffff) << 8);
values++;
*pixel++ = ((values[0] & 0xffffff) << 8);
values++;
},
w);
}
ISTORE_PROC(B8G8R8X8, 32)
ISTORE_PROC(P8R8G8B8, 32)
static void _istore_proc_R8G8B8(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT8 *pixel = (IUINT8*)bits + x * 3;
IUINT32 c;
int i;
for (i = w; i > 0; i--) {
c = *values++;
ISTORE24(pixel, c);
pixel += 3;
}
}
static void _istore_proc_B8G8R8(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT8 *pixel = (IUINT8*)bits + x * 3;
IUINT32 c;
int i;
for (i = w; i > 0; i--) {
c = *values++;
c = (c & 0x00ff00) | ((c & 0xff0000) >> 16) | ((c & 0xff) << 16);
ISTORE24(pixel, c);
pixel += 3;
}
}
static void _istore_proc_R5G6B5(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT16 *pixel = (IUINT16*)bits + x;
IUINT32 c1, c2, r1, g1, b1, r2, g2, b2;
ILINS_LOOP_DOUBLE(
{
c1 = *values++;
ISPLIT_RGB(c1, r1, g1, b1);
*pixel++ = (IUINT16) (((IUINT16)(r1 & 0xf8) << 8) |
((IUINT16)(g1 & 0xfc) << 3) |
((IUINT16)(b1 & 0xf8) >> 3));
},
{
c1 = *values++;
c2 = *values++;
ISPLIT_RGB(c1, r1, g1, b1);
ISPLIT_RGB(c2, r2, g2, b2);
*pixel++ = (IUINT16) (((IUINT16)(r1 & 0xf8) << 8) |
((IUINT16)(g1 & 0xfc) << 3) |
((IUINT16)(b1 & 0xf8) >> 3));
*pixel++ = (IUINT16) (((IUINT16)(r2 & 0xf8) << 8) |
((IUINT16)(g2 & 0xfc) << 3) |
((IUINT16)(b2 & 0xf8) >> 3));
},
w);
}
static void _istore_proc_B5G6R5(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT16 *pixel = (IUINT16*)bits + x;
IUINT32 c1, c2, r1, g1, b1, r2, g2, b2;
ILINS_LOOP_DOUBLE(
{
c1 = *values++;
ISPLIT_RGB(c1, r1, g1, b1);
*pixel++ = (IUINT16) (((IUINT16)(b1 & 0xf8) << 8) |
((IUINT16)(g1 & 0xfc) << 3) |
((IUINT16)(r1 & 0xf8) >> 3));
},
{
c1 = *values++;
c2 = *values++;
ISPLIT_RGB(c1, r1, g1, b1);
ISPLIT_RGB(c2, r2, g2, b2);
*pixel++ = (IUINT16) (((IUINT16)(b1 & 0xf8) << 8) |
((IUINT16)(g1 & 0xfc) << 3) |
((IUINT16)(r1 & 0xf8) >> 3));
*pixel++ = (IUINT16) (((IUINT16)(b2 & 0xf8) << 8) |
((IUINT16)(g2 & 0xfc) << 3) |
((IUINT16)(r2 & 0xf8) >> 3));
},
w);
}
static void _istore_proc_X1R5G5B5(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT16 *pixel = (IUINT16*)bits + x;
IUINT32 c1, c2, r1, g1, b1, r2, g2, b2;
ILINS_LOOP_DOUBLE(
{
c1 = *values++;
ISPLIT_RGB(c1, r1, g1, b1);
*pixel++ = (IUINT16) (((IUINT16)(r1 & 0xf8) << 7) |
((IUINT16)(g1 & 0xf8) << 2) |
((IUINT16)(b1 & 0xf8) >> 3));
},
{
c1 = *values++;
c2 = *values++;
ISPLIT_RGB(c1, r1, g1, b1);
ISPLIT_RGB(c2, r2, g2, b2);
*pixel++ = (IUINT16) (((IUINT16)(r1 & 0xf8) << 7) |
((IUINT16)(g1 & 0xf8) << 2) |
((IUINT16)(b1 & 0xf8) >> 3));
*pixel++ = (IUINT16) (((IUINT16)(r2 & 0xf8) << 7) |
((IUINT16)(g2 & 0xf8) << 2) |
((IUINT16)(b2 & 0xf8) >> 3));
},
w);
}
ISTORE_PROC(X1B5G5R5, 16)
ISTORE_PROC(R5G5B5X1, 16)
ISTORE_PROC(B5G5R5X1, 16)
ISTORE_PROC(A1R5G5B5, 16)
ISTORE_PROC(A1B5G5R5, 16)
ISTORE_PROC(R5G5B5A1, 16)
ISTORE_PROC(B5G5R5A1, 16)
ISTORE_PROC(X4R4G4B4, 16)
ISTORE_PROC(X4B4G4R4, 16)
ISTORE_PROC(R4G4B4X4, 16)
ISTORE_PROC(B4G4R4X4, 16)
ISTORE_PROC(A4R4G4B4, 16)
ISTORE_PROC(A4B4G4R4, 16)
static void _istore_proc_R4G4B4A4(void *bits,
const IUINT32 *values, int x, int w, const iColorIndex *idx)
{
IUINT16 *pixel = (IUINT16*)bits + x;
IUINT32 c, a, r, g, b;
int i;
for (i = w; i > 0; i--) {
c = *values++;
ISPLIT_ARGB(c, a, r, g, b);
*pixel++ = ((IUINT16)(
((IUINT16)((r) & 0xf0) << 8) |
((IUINT16)((g) & 0xf0) << 4) |
((IUINT16)((b) & 0xf0) >> 0) |
((IUINT16)((a) & 0xf0) >> 4)));
}
}
ISTORE_PROC(B4G4R4A4, 16)
ISTORE_PROC(C8, 8)
ISTORE_PROC(G8, 8)
ISTORE_PROC(A8, 8)
ISTORE_PROC(R3G3B2, 8)
ISTORE_PROC(B2G3R3, 8)
ISTORE_PROC(X2R2G2B2, 8)
ISTORE_PROC(X2B2G2R2, 8)
ISTORE_PROC(R2G2B2X2, 8)
ISTORE_PROC(B2G2R2X2, 8)
ISTORE_PROC(A2R2G2B2, 8)
ISTORE_PROC(A2B2G2R2, 8)
ISTORE_PROC(R2G2B2A2, 8)
ISTORE_PROC(B2G2R2A2, 8)
ISTORE_PROC(X4C4, 8)
ISTORE_PROC(X4G4, 8)
ISTORE_PROC(X4A4, 8)
ISTORE_PROC(C4X4, 8)
ISTORE_PROC(G4X4, 8)
ISTORE_PROC(A4X4, 8)
ISTORE_PROC(C4, 4)
ISTORE_PROC(G4, 4)
ISTORE_PROC(A4, 4)
ISTORE_PROC(R1G2B1, 4)
ISTORE_PROC(B1G2R1, 4)
ISTORE_PROC(A1R1G1B1, 4)
ISTORE_PROC(A1B1G1R1, 4)
ISTORE_PROC(R1G1B1A1, 4)
ISTORE_PROC(B1G1R1A1, 4)
ISTORE_PROC(X1R1G1B1, 4)
ISTORE_PROC(X1B1G1R1, 4)
ISTORE_PROC(R1G1B1X1, 4)
ISTORE_PROC(B1G1R1X1, 4)
ISTORE_PROC(C1, 1)
ISTORE_PROC(G1, 1)
ISTORE_PROC(A1, 1)
/**********************************************************************
* PIXEL FETCHING PROCEDURES
**********************************************************************/
static IUINT32 _ifetch_pixel_A8R8G8B8(const void *bits,
int offset, const iColorIndex *_ipixel_src_index)
{
return _ipixel_fetch(32, bits, offset);
}
static IUINT32 _ifetch_pixel_A8B8G8R8(const void *bits,
int offset, const iColorIndex *idx)
{
IUINT32 pixel = ((const IUINT32*)(bits))[offset];
return ((pixel & 0xff00ff00) | ((pixel & 0xff0000) >> 16) |
((pixel & 0xff) << 16));
}
static IUINT32 _ifetch_pixel_R8G8B8A8(const void *bits,
int offset, const iColorIndex *idx)
{
IUINT32 pixel = ((const IUINT32*)(bits))[offset];
return ((pixel & 0xff) << 24) | ((pixel & 0xffffff00) >> 8);
}
static IUINT32 _ifetch_pixel_B8G8R8A8(const void *bits,
int offset, const iColorIndex *idx)
{
IUINT32 pixel = ((const IUINT32*)(bits))[offset];
return ((pixel & 0x000000ff) << 24) |
((pixel & 0x0000ff00) << 8) |
((pixel & 0x00ff0000) >> 8) |
((pixel & 0xff000000) >> 24);
}
static IUINT32 _ifetch_pixel_X8R8G8B8(const void *bits,
int offset, const iColorIndex *idx)
{
return ((const IUINT32*)(bits))[offset] | 0xff000000;
}
static IUINT32 _ifetch_pixel_X8B8G8R8(const void *bits,
int offset, const iColorIndex *idx)
{
IUINT32 pixel = ((const IUINT32*)(bits))[offset];
return ((pixel & 0x0000ff00) | ((pixel & 0xff0000) >> 16) |
((pixel & 0xff) << 16)) | 0xff000000;
}
IFETCH_PIXEL(R8G8B8X8, 32)
IFETCH_PIXEL(B8G8R8X8, 32)
IFETCH_PIXEL(P8R8G8B8, 32)
IFETCH_PIXEL(R8G8B8, 24)
IFETCH_PIXEL(B8G8R8, 24)
IFETCH_PIXEL(R5G6B5, 16)
IFETCH_PIXEL(B5G6R5, 16)
IFETCH_PIXEL(X1R5G5B5, 16)
IFETCH_PIXEL(X1B5G5R5, 16)
IFETCH_PIXEL(R5G5B5X1, 16)
IFETCH_PIXEL(B5G5R5X1, 16)
IFETCH_PIXEL(A1R5G5B5, 16)
IFETCH_PIXEL(A1B5G5R5, 16)
IFETCH_PIXEL(R5G5B5A1, 16)
IFETCH_PIXEL(B5G5R5A1, 16)
IFETCH_PIXEL(X4R4G4B4, 16)
IFETCH_PIXEL(X4B4G4R4, 16)
IFETCH_PIXEL(R4G4B4X4, 16)
IFETCH_PIXEL(B4G4R4X4, 16)
IFETCH_PIXEL(A4R4G4B4, 16)
IFETCH_PIXEL(A4B4G4R4, 16)
IFETCH_PIXEL(R4G4B4A4, 16)
IFETCH_PIXEL(B4G4R4A4, 16)
IFETCH_PIXEL(C8, 8)
IFETCH_PIXEL(G8, 8)
IFETCH_PIXEL(A8, 8)
IFETCH_PIXEL(R3G3B2, 8)
IFETCH_PIXEL(B2G3R3, 8)
IFETCH_PIXEL(X2R2G2B2, 8)
IFETCH_PIXEL(X2B2G2R2, 8)
IFETCH_PIXEL(R2G2B2X2, 8)
IFETCH_PIXEL(B2G2R2X2, 8)
IFETCH_PIXEL(A2R2G2B2, 8)
IFETCH_PIXEL(A2B2G2R2, 8)
IFETCH_PIXEL(R2G2B2A2, 8)
IFETCH_PIXEL(B2G2R2A2, 8)
IFETCH_PIXEL(X4C4, 8)
IFETCH_PIXEL(X4G4, 8)
IFETCH_PIXEL(X4A4, 8)
IFETCH_PIXEL(C4X4, 8)
IFETCH_PIXEL(G4X4, 8)
IFETCH_PIXEL(A4X4, 8)
IFETCH_PIXEL(C4, 4)
IFETCH_PIXEL(G4, 4)
IFETCH_PIXEL(A4, 4)
IFETCH_PIXEL(R1G2B1, 4)
IFETCH_PIXEL(B1G2R1, 4)
IFETCH_PIXEL(A1R1G1B1, 4)
IFETCH_PIXEL(A1B1G1R1, 4)
IFETCH_PIXEL(R1G1B1A1, 4)
IFETCH_PIXEL(B1G1R1A1, 4)
IFETCH_PIXEL(X1R1G1B1, 4)
IFETCH_PIXEL(X1B1G1R1, 4)
IFETCH_PIXEL(R1G1B1X1, 4)
IFETCH_PIXEL(B1G1R1X1, 4)
IFETCH_PIXEL(C1, 1)
IFETCH_PIXEL(G1, 1)
IFETCH_PIXEL(A1, 1)
/**********************************************************************
* FETCHING STORING LOOK UP TABLE
**********************************************************************/
struct iPixelAccessProc
{
iFetchProc fetch, fetch_default;
iStoreProc store, store_default;
iFetchPixelProc fetchpixel, fetchpixel_default;
};
#define ITABLE_ITEM(fmt) { \
_ifetch_proc_##fmt, _ifetch_proc_##fmt, \
_istore_proc_##fmt, _istore_proc_##fmt, \
_ifetch_pixel_##fmt, _ifetch_pixel_##fmt }
/* builtin look table */
static struct iPixelAccessProc ipixel_access_proc[IPIX_FMT_COUNT] =
{
ITABLE_ITEM(A8R8G8B8),
ITABLE_ITEM(A8B8G8R8),
ITABLE_ITEM(R8G8B8A8),
ITABLE_ITEM(B8G8R8A8),
ITABLE_ITEM(X8R8G8B8),
ITABLE_ITEM(X8B8G8R8),
ITABLE_ITEM(R8G8B8X8),
ITABLE_ITEM(B8G8R8X8),
ITABLE_ITEM(P8R8G8B8),
ITABLE_ITEM(R8G8B8),
ITABLE_ITEM(B8G8R8),
ITABLE_ITEM(R5G6B5),
ITABLE_ITEM(B5G6R5),
ITABLE_ITEM(X1R5G5B5),
ITABLE_ITEM(X1B5G5R5),
ITABLE_ITEM(R5G5B5X1),
ITABLE_ITEM(B5G5R5X1),
ITABLE_ITEM(A1R5G5B5),
ITABLE_ITEM(A1B5G5R5),
ITABLE_ITEM(R5G5B5A1),
ITABLE_ITEM(B5G5R5A1),
ITABLE_ITEM(X4R4G4B4),
ITABLE_ITEM(X4B4G4R4),
ITABLE_ITEM(R4G4B4X4),
ITABLE_ITEM(B4G4R4X4),
ITABLE_ITEM(A4R4G4B4),
ITABLE_ITEM(A4B4G4R4),
ITABLE_ITEM(R4G4B4A4),
ITABLE_ITEM(B4G4R4A4),
ITABLE_ITEM(C8),
ITABLE_ITEM(G8),
ITABLE_ITEM(A8),
ITABLE_ITEM(R3G3B2),
ITABLE_ITEM(B2G3R3),
ITABLE_ITEM(X2R2G2B2),
ITABLE_ITEM(X2B2G2R2),
ITABLE_ITEM(R2G2B2X2),
ITABLE_ITEM(B2G2R2X2),
ITABLE_ITEM(A2R2G2B2),
ITABLE_ITEM(A2B2G2R2),
ITABLE_ITEM(R2G2B2A2),
ITABLE_ITEM(B2G2R2A2),
ITABLE_ITEM(X4C4),
ITABLE_ITEM(X4G4),
ITABLE_ITEM(X4A4),
ITABLE_ITEM(C4X4),
ITABLE_ITEM(G4X4),
ITABLE_ITEM(A4X4),
ITABLE_ITEM(C4),
ITABLE_ITEM(G4),
ITABLE_ITEM(A4),
ITABLE_ITEM(R1G2B1),
ITABLE_ITEM(B1G2R1),
ITABLE_ITEM(A1R1G1B1),
ITABLE_ITEM(A1B1G1R1),
ITABLE_ITEM(R1G1B1A1),
ITABLE_ITEM(B1G1R1A1),
ITABLE_ITEM(X1R1G1B1),
ITABLE_ITEM(X1B1G1R1),
ITABLE_ITEM(R1G1B1X1),
ITABLE_ITEM(B1G1R1X1),
ITABLE_ITEM(C1),
ITABLE_ITEM(G1),
ITABLE_ITEM(A1),
};
#undef ITABLE_ITEM
#undef IFETCH_PROC
#undef ISTORE_PROC
#undef IFETCH_PIXEL
/* set procedure */
void ipixel_set_proc(int pixfmt, int type, void *proc)
{
assert(pixfmt >= 0 && pixfmt < IPIX_FMT_COUNT);
if (pixfmt < 0 || pixfmt >= IPIX_FMT_COUNT) return;
if (type == IPIXEL_PROC_TYPE_FETCH) {
if (proc != NULL) {
ipixel_access_proc[pixfmt].fetch = (iFetchProc)proc;
} else {
ipixel_access_proc[pixfmt].fetch =
ipixel_access_proc[pixfmt].fetch_default;
}
}
else if (type == IPIXEL_PROC_TYPE_STORE) {
if (proc != NULL) {
ipixel_access_proc[pixfmt].store = (iStoreProc)proc;
} else {
ipixel_access_proc[pixfmt].store =
ipixel_access_proc[pixfmt].store_default;
}
}
else if (type == IPIXEL_PROC_TYPE_FETCHPIXEL) {
if (proc != NULL) {
ipixel_access_proc[pixfmt].fetchpixel = (iFetchPixelProc)proc;
} else {
ipixel_access_proc[pixfmt].fetchpixel =
ipixel_access_proc[pixfmt].fetchpixel_default;
}
}
}
/**********************************************************************
* FETCHING STORING LOOK UP TABLE
**********************************************************************/
#define IFETCH_LUT_2(sfmt) \
IUINT32 _ipixel_cvt_lut_##sfmt[256 * 2]; \
static void _ifetch_proc_lut_##sfmt(const void *bits, int x, \
int w, IUINT32 *buffer, const iColorIndex *idx) \
{ \
const IUINT8 *input = (const IUINT8*)bits + (x << 1); \
IUINT32 c1, c2, c3, c4; \
ILINS_LOOP_DOUBLE( \
{ \
c1 = _ipixel_cvt_lut_##sfmt[*input++ + 0]; \
c2 = _ipixel_cvt_lut_##sfmt[*input++ + 256]; \
*buffer++ = c1 | c2; \
}, \
{ \
c1 = _ipixel_cvt_lut_##sfmt[*input++ + 0]; \
c2 = _ipixel_cvt_lut_##sfmt[*input++ + 256]; \
c3 = _ipixel_cvt_lut_##sfmt[*input++ + 0]; \
c4 = _ipixel_cvt_lut_##sfmt[*input++ + 256]; \
c1 |= c2; \
c3 |= c4; \
*buffer++ = c1; \
*buffer++ = c3; \
}, \
w); \
} \
static IUINT32 _ifetch_pixel_lut_##sfmt(const void *bits, \
int offset, const iColorIndex *idx) \
{ \
const IUINT8 *input = (const IUINT8*)bits + (offset << 1); \
IUINT32 c1, c2; \
c1 = _ipixel_cvt_lut_##sfmt[*input++ + 0]; \
c2 = _ipixel_cvt_lut_##sfmt[*input++ + 256]; \
return c1 | c2; \
}
#define IFETCH_LUT_1(sfmt) \
IUINT32 _ipixel_cvt_lut_##sfmt[256]; \
static void _ifetch_proc_lut_##sfmt(const void *bits, int x, \
int w, IUINT32 *buffer, const iColorIndex *idx) \
{ \
const IUINT8 *input = (const IUINT8*)bits + x; \
IUINT32 c1, c2; \
ILINS_LOOP_DOUBLE( \
{ \
c1 = _ipixel_cvt_lut_##sfmt[*input++]; \
*buffer++ = c1; \
}, \
{ \
c1 = _ipixel_cvt_lut_##sfmt[*input++]; \
c2 = _ipixel_cvt_lut_##sfmt[*input++]; \
*buffer++ = c1; \
*buffer++ = c2; \
}, \
w); \
} \
static IUINT32 _ifetch_pixel_lut_##sfmt(const void *bits, \
int offset, const iColorIndex *idx) \
{ \
const IUINT8 *input = (const IUINT8*)bits + offset; \
return _ipixel_cvt_lut_##sfmt[*input]; \
}
#define IFETCH_LUT_MAIN(sfmt, nbytes) \
IFETCH_LUT_##nbytes(sfmt)
IFETCH_LUT_MAIN(R5G6B5, 2)
IFETCH_LUT_MAIN(B5G6R5, 2)
IFETCH_LUT_MAIN(X1R5G5B5, 2)
IFETCH_LUT_MAIN(X1B5G5R5, 2)
IFETCH_LUT_MAIN(R5G5B5X1, 2)
IFETCH_LUT_MAIN(B5G5R5X1, 2)
IFETCH_LUT_MAIN(A1R5G5B5, 2)
IFETCH_LUT_MAIN(A1B5G5R5, 2)
IFETCH_LUT_MAIN(R5G5B5A1, 2)
IFETCH_LUT_MAIN(B5G5R5A1, 2)
IFETCH_LUT_MAIN(X4R4G4B4, 2)
IFETCH_LUT_MAIN(X4B4G4R4, 2)
IFETCH_LUT_MAIN(R4G4B4X4, 2)
IFETCH_LUT_MAIN(B4G4R4X4, 2)
IFETCH_LUT_MAIN(A4R4G4B4, 2)
IFETCH_LUT_MAIN(A4B4G4R4, 2)
IFETCH_LUT_MAIN(R4G4B4A4, 2)
IFETCH_LUT_MAIN(B4G4R4A4, 2)
IFETCH_LUT_MAIN(R3G3B2, 1)
IFETCH_LUT_MAIN(B2G3R3, 1)
IFETCH_LUT_MAIN(X2R2G2B2, 1)
IFETCH_LUT_MAIN(X2B2G2R2, 1)
IFETCH_LUT_MAIN(R2G2B2X2, 1)
IFETCH_LUT_MAIN(B2G2R2X2, 1)
IFETCH_LUT_MAIN(A2R2G2B2, 1)
IFETCH_LUT_MAIN(A2B2G2R2, 1)
IFETCH_LUT_MAIN(R2G2B2A2, 1)
IFETCH_LUT_MAIN(B2G2R2A2, 1)
struct iPixelAccessLutTable
{
int fmt;
iFetchProc fetch;
iFetchPixelProc pixel;
};
#define ITABLE_ITEM(fmt) \
{ IPIX_FMT_##fmt, _ifetch_proc_lut_##fmt, _ifetch_pixel_lut_##fmt }
static struct iPixelAccessLutTable ipixel_access_lut[28] =
{
ITABLE_ITEM(R5G6B5),
ITABLE_ITEM(B5G6R5),
ITABLE_ITEM(X1R5G5B5),
ITABLE_ITEM(X1B5G5R5),
ITABLE_ITEM(R5G5B5X1),
ITABLE_ITEM(B5G5R5X1),
ITABLE_ITEM(A1R5G5B5),
ITABLE_ITEM(A1B5G5R5),
ITABLE_ITEM(R5G5B5A1),
ITABLE_ITEM(B5G5R5A1),
ITABLE_ITEM(X4R4G4B4),
ITABLE_ITEM(X4B4G4R4),
ITABLE_ITEM(R4G4B4X4),
ITABLE_ITEM(B4G4R4X4),
ITABLE_ITEM(A4R4G4B4),
ITABLE_ITEM(A4B4G4R4),
ITABLE_ITEM(R4G4B4A4),
ITABLE_ITEM(B4G4R4A4),
ITABLE_ITEM(R3G3B2),
ITABLE_ITEM(B2G3R3),
ITABLE_ITEM(X2R2G2B2),
ITABLE_ITEM(X2B2G2R2),
ITABLE_ITEM(R2G2B2X2),
ITABLE_ITEM(B2G2R2X2),
ITABLE_ITEM(A2R2G2B2),
ITABLE_ITEM(A2B2G2R2),
ITABLE_ITEM(R2G2B2A2),
ITABLE_ITEM(B2G2R2A2),
};
static const int ipixel_access_lut_fmt[IPIX_FMT_COUNT] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, -1, -1, -1, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1
};
#undef ITABLE_ITEM
#undef IFETCH_LUT_2
#undef IFETCH_LUT_1
#undef IFETCH_LUT_MAIN
static int ipixel_lut_inited = 0;
void ipixel_lut_init(void)
{
int i, j, k;
if (ipixel_lut_inited != 0) return;
#define IPIXEL_LUT_INIT(fmt, nbytes) \
ipixel_lut_##nbytes##_to_4(IPIX_FMT_##fmt, IPIX_FMT_A8R8G8B8, \
_ipixel_cvt_lut_##fmt)
IPIXEL_LUT_INIT(R5G6B5, 2);
IPIXEL_LUT_INIT(B5G6R5, 2);
IPIXEL_LUT_INIT(X1R5G5B5, 2);
IPIXEL_LUT_INIT(X1B5G5R5, 2);
IPIXEL_LUT_INIT(R5G5B5X1, 2);
IPIXEL_LUT_INIT(B5G5R5X1, 2);
IPIXEL_LUT_INIT(A1R5G5B5, 2);
IPIXEL_LUT_INIT(A1B5G5R5, 2);
IPIXEL_LUT_INIT(R5G5B5A1, 2);
IPIXEL_LUT_INIT(B5G5R5A1, 2);
IPIXEL_LUT_INIT(X4R4G4B4, 2);
IPIXEL_LUT_INIT(X4B4G4R4, 2);
IPIXEL_LUT_INIT(R4G4B4X4, 2);
IPIXEL_LUT_INIT(B4G4R4X4, 2);
IPIXEL_LUT_INIT(A4R4G4B4, 2);
IPIXEL_LUT_INIT(A4B4G4R4, 2);
IPIXEL_LUT_INIT(R4G4B4A4, 2);
IPIXEL_LUT_INIT(B4G4R4A4, 2);
IPIXEL_LUT_INIT(R3G3B2, 1);
IPIXEL_LUT_INIT(B2G3R3, 1);
IPIXEL_LUT_INIT(X2R2G2B2, 1);
IPIXEL_LUT_INIT(X2B2G2R2, 1);
IPIXEL_LUT_INIT(R2G2B2X2, 1);
IPIXEL_LUT_INIT(B2G2R2X2, 1);
IPIXEL_LUT_INIT(A2R2G2B2, 1);
IPIXEL_LUT_INIT(A2B2G2R2, 1);
IPIXEL_LUT_INIT(R2G2B2A2, 1);
IPIXEL_LUT_INIT(B2G2R2A2, 1);
#undef IPIXEL_LUT_INIT
for (i = 0; i < 2048; i++) {
IUINT32 da = _ipixel_scale_5[i >> 6];
IUINT32 sa = _ipixel_scale_6[i & 63];
IUINT32 FA = da + ((255 - da) * sa) / 255;
IUINT32 SA = (FA != 0)? ((sa * 255) / FA) : 0;
ipixel_blend_lut[i * 2 + 0] = (unsigned char)SA;
ipixel_blend_lut[i * 2 + 1] = (unsigned char)FA;
}
for (i = 0; i < 256; i++) {
for (j = 0; j < 256; j++) {
k = i * j;
_ipixel_mullut[i][j] = (IUINT8)_idiv_255(k);
}
}
for (i = 0; i < 256; i++) {
_ipixel_divlut[0][i] = 0;
for (j = 1; j < i; j++) {
_ipixel_divlut[i][j] = (IUINT8)((j * 255) / i);
}
for (j = i; j < 256; j++) {
_ipixel_divlut[i][j] = 255;
}
}
ipixel_lut_inited = 1;
}
/* get color fetching procedure */
iFetchProc ipixel_get_fetch(int pixfmt, int access_mode)
{
assert(pixfmt >= 0 && pixfmt < IPIX_FMT_COUNT);
if (pixfmt < 0 || pixfmt >= IPIX_FMT_COUNT) return NULL;
if (access_mode == IPIXEL_ACCESS_MODE_NORMAL) {
int id = ipixel_access_lut_fmt[pixfmt];
if (ipixel_lut_inited == 0) ipixel_lut_init();
if (id >= 0) return ipixel_access_lut[id].fetch;
return ipixel_access_proc[pixfmt].fetch;
}
if (access_mode == IPIXEL_ACCESS_MODE_ACCURATE) {
return ipixel_access_proc[pixfmt].fetch;
}
return ipixel_access_proc[pixfmt].fetch_default;
}
/* get color storing procedure */
iStoreProc ipixel_get_store(int pixfmt, int access_mode)
{
assert(pixfmt >= 0 && pixfmt < IPIX_FMT_COUNT);
if (pixfmt < 0 || pixfmt >= IPIX_FMT_COUNT) return NULL;
if (access_mode == IPIXEL_ACCESS_MODE_NORMAL) {
if (ipixel_lut_inited == 0) ipixel_lut_init();
return ipixel_access_proc[pixfmt].store;
}
if (access_mode == IPIXEL_ACCESS_MODE_ACCURATE) {
return ipixel_access_proc[pixfmt].store;
}
return ipixel_access_proc[pixfmt].store_default;
}
/* get color pixel fetching procedure */
iFetchPixelProc ipixel_get_fetchpixel(int pixfmt, int access_mode)
{
assert(pixfmt >= 0 && pixfmt < IPIX_FMT_COUNT);
if (pixfmt < 0 || pixfmt >= IPIX_FMT_COUNT) return NULL;
if (access_mode == IPIXEL_ACCESS_MODE_NORMAL) {
int id = ipixel_access_lut_fmt[pixfmt];
if (ipixel_lut_inited == 0) ipixel_lut_init();
if (id >= 0) return ipixel_access_lut[id].pixel;
return ipixel_access_proc[pixfmt].fetchpixel;
}
if (access_mode == IPIXEL_ACCESS_MODE_ACCURATE) {
return ipixel_access_proc[pixfmt].fetchpixel;
}
return ipixel_access_proc[pixfmt].fetchpixel_default;
}
/* returns pixel format names */
const char *ipixelfmt_name(int fmt)
{
return ipixelfmt[fmt].name;
}
/**********************************************************************
* SPAN DRAWING
**********************************************************************/
/* span blending for 8, 16, 24, 32 bits */
#define IPIXEL_SPAN_DRAW_PROC_N(fmt, bpp, nbytes, mode) \
static void ipixel_span_draw_proc_##fmt##_0(void *bits, \
int offset, int w, const IUINT32 *card, const IUINT8 *cover, \
const iColorIndex *_ipixel_src_index) \
{ \
unsigned char *dst = ((unsigned char*)bits) + offset * nbytes; \
IUINT32 cc, r1, g1, b1, a1, r2, g2, b2, a2, inc; \
if (cover == NULL) { \
for (inc = w; inc > 0; inc--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
if (a1 == 255) { \
cc = IRGBA_TO_PIXEL(fmt, r1, g1, b1, 255); \
_ipixel_store(bpp, dst, 0, cc); \
} \
else if (a1 > 0) { \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
card++; \
dst += nbytes; \
} \
} else { \
for (inc = w; inc > 0; inc--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
cc = *cover++; \
r2 = a1 + cc; \
if (r2 == 510) { \
cc = IRGBA_TO_PIXEL(fmt, r1, g1, b1, 255); \
_ipixel_store(bpp, dst, 0, cc); \
} \
else if (r2 > 0 && cc > 0) { \
a1 = _imul_y_div_255(a1, cc); \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
card++; \
dst += nbytes; \
} \
} \
} \
static void ipixel_span_draw_proc_##fmt##_1(void *bits, \
int offset, int w, const IUINT32 *card, const IUINT8 *cover, \
const iColorIndex *_ipixel_src_index) \
{ \
unsigned char *dst = ((unsigned char*)bits) + offset * nbytes; \
IUINT32 cc, r1, g1, b1, a1, r2, g2, b2, a2, inc; \
if (cover == NULL) { \
for (inc = w; inc > 0; inc--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
if (a1 > 0) { \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
card++; \
dst += nbytes; \
} \
} else { \
for (inc = w; inc > 0; inc--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
cc = *cover++; \
if (a1 > 0 && cc > 0) { \
a1 = _imul_y_div_255(a1, cc); \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
card++; \
dst += nbytes; \
} \
} \
}
/* span blending for 8 bits without palette */
#define IPIXEL_SPAN_DRAW_PROC_1(fmt, bpp, nbytes, mode) \
static void ipixel_span_draw_proc_##fmt##_0(void *bits, \
int offset, int w, const IUINT32 *card, const IUINT8 *cover, \
const iColorIndex *_ipixel_src_index) \
{ \
unsigned char *dst = ((unsigned char*)bits) + (offset); \
IUINT32 cc, r1, g1, b1, a1, r2, g2, b2, a2, inc; \
if (cover == NULL) { \
for (inc = w; inc > 0; inc--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
if (a1 == 255) { \
cc = IRGBA_TO_PIXEL(fmt, r1, g1, b1, 255); \
_ipixel_store(bpp, dst, 0, cc); \
} \
else if (a1 > 0) { \
r1 = dst[0]; \
cc = _ipixel_cvt_lut_##fmt[r1]; \
IRGBA_FROM_PIXEL(A8R8G8B8, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
card++; \
dst++; \
} \
} else { \
for (inc = w; inc > 0; inc--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
cc = *cover++; \
r2 = a1 + cc; \
if (r2 == 510) { \
cc = IRGBA_TO_PIXEL(fmt, r1, g1, b1, 255); \
_ipixel_store(bpp, dst, 0, cc); \
} \
else if (r2 > 0 && cc > 0) { \
a1 = _imul_y_div_255(a1, cc); \
r1 = dst[0]; \
cc = _ipixel_cvt_lut_##fmt[r1]; \
IRGBA_FROM_PIXEL(A8R8G8B8, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
card++; \
dst++; \
} \
} \
} \
static void ipixel_span_draw_proc_##fmt##_1(void *bits, \
int offset, int w, const IUINT32 *card, const IUINT8 *cover, \
const iColorIndex *_ipixel_src_index) \
{ \
unsigned char *dst = ((unsigned char*)bits) + (offset); \
IUINT32 cc, r1, g1, b1, a1, r2, g2, b2, a2, inc; \
if (cover == NULL) { \
for (inc = w; inc > 0; inc--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
if (a1 > 0) { \
r1 = dst[0]; \
cc = _ipixel_cvt_lut_##fmt[r1]; \
IRGBA_FROM_PIXEL(A8R8G8B8, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
card++; \
dst++; \
} \
} else { \
for (inc = w; inc > 0; inc--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
cc = *cover++; \
if (a1 > 0 && cc > 0) { \
a1 = _imul_y_div_255(a1, cc); \
r1 = dst[0]; \
cc = _ipixel_cvt_lut_##fmt[r1]; \
IRGBA_FROM_PIXEL(A8R8G8B8, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
card++; \
dst++; \
} \
} \
}
/* span blending for 8/4/1 bits with or without palette */
#define IPIXEL_SPAN_DRAW_PROC_X(fmt, bpp, nbytes, mode, init) \
static void ipixel_span_draw_proc_##fmt##_0(void *bits, \
int offset, int w, const IUINT32 *card, const IUINT8 *cover, \
const iColorIndex *_ipixel_src_index) \
{ \
IUINT32 cc, r1, g1, b1, a1, r2, g2, b2, a2, inc; \
unsigned char *dst = (unsigned char*)bits; \
init; \
if (cover == NULL) { \
for (inc = offset; w > 0; inc++, w--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
if (a1 == 255) { \
cc = IRGBA_TO_PIXEL(fmt, r1, g1, b1, 255); \
_ipixel_store(bpp, dst, inc, cc); \
} \
else if (a1 > 0) { \
cc = _ipixel_fetch(bpp, dst, inc); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, inc, cc); \
} \
card++; \
} \
} else { \
for (inc = offset; w > 0; inc++, w--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
cc = *cover++; \
r2 = a1 + cc; \
if (r2 == 510) { \
cc = IRGBA_TO_PIXEL(fmt, r1, g1, b1, 255); \
_ipixel_store(bpp, dst, inc, cc); \
} \
else if (r2 > 0 && cc > 0) { \
a1 = _imul_y_div_255(a1, cc); \
cc = _ipixel_fetch(bpp, dst, inc); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, inc, cc); \
} \
card++; \
} \
} \
} \
static void ipixel_span_draw_proc_##fmt##_1(void *bits, \
int offset, int w, const IUINT32 *card, const IUINT8 *cover, \
const iColorIndex *_ipixel_src_index) \
{ \
IUINT32 cc, r1, g1, b1, a1, r2, g2, b2, a2, inc; \
unsigned char *dst = (unsigned char*)bits; \
init; \
if (cover == NULL) { \
for (inc = offset; w > 0; inc++, w--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
if (a1 > 0) { \
cc = _ipixel_fetch(bpp, dst, inc); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, inc, cc); \
} \
card++; \
} \
} else { \
for (inc = offset; w > 0; inc++, w--) { \
_ipixel_load_card(card, r1, g1, b1, a1); \
cc = *cover++; \
if (r1 > 0 && cc > 0) { \
a1 = _imul_y_div_255(a1, cc); \
cc = _ipixel_fetch(bpp, dst, inc); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, inc, cc); \
} \
card++; \
} \
} \
}
/* span blending for 4/1 bits without palette */
#define IPIXEL_SPAN_DRAW_PROC_BITS(fmt, bpp, nbytes, mode) \
IPIXEL_SPAN_DRAW_PROC_X(fmt, bpp, nbytes, mode, {})
/* span blending for 8/4/1 bits with palette */
#define IPIXEL_SPAN_DRAW_PROC_PAL(fmt, bpp, nbytes, mode) \
IPIXEL_SPAN_DRAW_PROC_X(fmt, bpp, nbytes, mode, \
const iColorIndex *_ipixel_dst_index = _ipixel_src_index)
/* span blending main */
#define IPIXEL_SPAN_DRAW_MAIN(type, fmt, bpp, nbytes, mode) \
IPIXEL_SPAN_DRAW_PROC_##type(fmt, bpp, nbytes, mode)
/* span blending procedures declare */
IPIXEL_SPAN_DRAW_MAIN(N, A8R8G8B8, 32, 4, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, A8B8G8R8, 32, 4, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, R8G8B8A8, 32, 4, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, B8G8R8A8, 32, 4, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, X8R8G8B8, 32, 4, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, X8B8G8R8, 32, 4, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, R8G8B8X8, 32, 4, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, B8G8R8X8, 32, 4, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, P8R8G8B8, 32, 4, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, R8G8B8, 24, 3, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, B8G8R8, 24, 3, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, R5G6B5, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, B5G6R5, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, X1R5G5B5, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, X1B5G5R5, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, R5G5B5X1, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, B5G5R5X1, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, A1R5G5B5, 16, 2, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, A1B5G5R5, 16, 2, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, R5G5B5A1, 16, 2, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, B5G5R5A1, 16, 2, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, X4R4G4B4, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, X4B4G4R4, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, R4G4B4X4, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, B4G4R4X4, 16, 2, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, A4R4G4B4, 16, 2, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, A4B4G4R4, 16, 2, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, R4G4B4A4, 16, 2, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(N, B4G4R4A4, 16, 2, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(PAL, C8, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, G8, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, A8, 8, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(1, R3G3B2, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(1, B2G3R3, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(1, X2R2G2B2, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(1, X2B2G2R2, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(1, R2G2B2X2, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(1, B2G2R2X2, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(1, A2R2G2B2, 8, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(1, A2B2G2R2, 8, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(1, R2G2B2A2, 8, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(1, B2G2R2A2, 8, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(PAL, X4C4, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, X4G4, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, X4A4, 8, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(PAL, C4X4, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, G4X4, 8, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(N, A4X4, 8, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(PAL, C4, 4, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(BITS, G4, 4, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(BITS, A4, 4, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(BITS, R1G2B1, 4, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(BITS, B1G2R1, 4, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(BITS, A1R1G1B1, 4, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(BITS, A1B1G1R1, 4, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(BITS, R1G1B1A1, 4, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(BITS, B1G1R1A1, 4, 1, NORMAL_FAST)
IPIXEL_SPAN_DRAW_MAIN(BITS, X1R1G1B1, 4, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(BITS, X1B1G1R1, 4, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(BITS, R1G1B1X1, 4, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(BITS, B1G1R1X1, 4, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(PAL, C1, 1, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(BITS, G1, 1, 1, STATIC)
IPIXEL_SPAN_DRAW_MAIN(BITS, A1, 1, 1, NORMAL_FAST)
/* draw span over in A8R8G8B8 or X8R8G8B8 */
static void ipixel_span_draw_proc_over_32(void *bits,
int offset, int w, const IUINT32 *card, const IUINT8 *cover,
const iColorIndex *_ipixel_src_index)
{
IUINT32 *dst = ((IUINT32*)bits) + offset;
IUINT32 alpha, cc;
int inc;
if (cover == NULL) {
for (inc = w; inc > 0; inc--) {
alpha = card[0] >> 24;
if (alpha == 255) {
dst[0] = card[0];
}
else if (alpha > 0) {
IBLEND_PARGB(dst[0], card[0]);
}
card++;
dst++;
}
} else {
for (inc = w; inc > 0; inc--) {
alpha = card[0] >> 24;
cc = cover[0];
if (cc + alpha == 510) {
dst[0] = card[0];
}
else if (cc && alpha) {
IBLEND_PARGB_COVER(dst[0], card[0], cc);
}
card++;
dst++;
cover++;
}
}
}
#undef IPIXEL_SPAN_DRAW_MAIN
#undef IPIXEL_SPAN_DRAW_PROC_N
#undef IPIXEL_SPAN_DRAW_PROC_X
#undef IPIXEL_SPAN_DRAW_PROC_1
#undef IPIXEL_SPAN_DRAW_PROC_BITS
#undef IPIXEL_SPAN_DRAW_PROC_PAL
struct iPixelSpanDrawProc
{
iSpanDrawProc blend, additive, blend_default, additive_default;
};
#define ITABLE_ITEM(fmt) { \
ipixel_span_draw_proc_##fmt##_0, ipixel_span_draw_proc_##fmt##_1, \
ipixel_span_draw_proc_##fmt##_0, ipixel_span_draw_proc_##fmt##_1 }
static struct iPixelSpanDrawProc ipixel_span_proc_list[IPIX_FMT_COUNT] =
{
ITABLE_ITEM(A8R8G8B8),
ITABLE_ITEM(A8B8G8R8),
ITABLE_ITEM(R8G8B8A8),
ITABLE_ITEM(B8G8R8A8),
ITABLE_ITEM(X8R8G8B8),
ITABLE_ITEM(X8B8G8R8),
ITABLE_ITEM(R8G8B8X8),
ITABLE_ITEM(B8G8R8X8),
ITABLE_ITEM(P8R8G8B8),
ITABLE_ITEM(R8G8B8),
ITABLE_ITEM(B8G8R8),
ITABLE_ITEM(R5G6B5),
ITABLE_ITEM(B5G6R5),
ITABLE_ITEM(X1R5G5B5),
ITABLE_ITEM(X1B5G5R5),
ITABLE_ITEM(R5G5B5X1),
ITABLE_ITEM(B5G5R5X1),
ITABLE_ITEM(A1R5G5B5),
ITABLE_ITEM(A1B5G5R5),
ITABLE_ITEM(R5G5B5A1),
ITABLE_ITEM(B5G5R5A1),
ITABLE_ITEM(X4R4G4B4),
ITABLE_ITEM(X4B4G4R4),
ITABLE_ITEM(R4G4B4X4),
ITABLE_ITEM(B4G4R4X4),
ITABLE_ITEM(A4R4G4B4),
ITABLE_ITEM(A4B4G4R4),
ITABLE_ITEM(R4G4B4A4),
ITABLE_ITEM(B4G4R4A4),
ITABLE_ITEM(C8),
ITABLE_ITEM(G8),
ITABLE_ITEM(A8),
ITABLE_ITEM(R3G3B2),
ITABLE_ITEM(B2G3R3),
ITABLE_ITEM(X2R2G2B2),
ITABLE_ITEM(X2B2G2R2),
ITABLE_ITEM(R2G2B2X2),
ITABLE_ITEM(B2G2R2X2),
ITABLE_ITEM(A2R2G2B2),
ITABLE_ITEM(A2B2G2R2),
ITABLE_ITEM(R2G2B2A2),
ITABLE_ITEM(B2G2R2A2),
ITABLE_ITEM(X4C4),
ITABLE_ITEM(X4G4),
ITABLE_ITEM(X4A4),
ITABLE_ITEM(C4X4),
ITABLE_ITEM(G4X4),
ITABLE_ITEM(A4X4),
ITABLE_ITEM(C4),
ITABLE_ITEM(G4),
ITABLE_ITEM(A4),
ITABLE_ITEM(R1G2B1),
ITABLE_ITEM(B1G2R1),
ITABLE_ITEM(A1R1G1B1),
ITABLE_ITEM(A1B1G1R1),
ITABLE_ITEM(R1G1B1A1),
ITABLE_ITEM(B1G1R1A1),
ITABLE_ITEM(X1R1G1B1),
ITABLE_ITEM(X1B1G1R1),
ITABLE_ITEM(R1G1B1X1),
ITABLE_ITEM(B1G1R1X1),
ITABLE_ITEM(C1),
ITABLE_ITEM(G1),
ITABLE_ITEM(A1),
};
#undef ITABLE_ITEM
static iSpanDrawProc ipixel_span_draw_over = ipixel_span_draw_proc_over_32;
iSpanDrawProc ipixel_get_span_proc(int fmt, int isadditive, int usedefault)
{
assert(fmt >= 0 && fmt < IPIX_FMT_COUNT);
if (fmt < -1 || fmt >= IPIX_FMT_COUNT) {
abort();
return NULL;
}
if (ipixel_lut_inited == 0) ipixel_lut_init();
if (usedefault) {
if (fmt < 0) return ipixel_span_draw_proc_over_32;
if (isadditive == 0) return ipixel_span_proc_list[fmt].blend_default;
else return ipixel_span_proc_list[fmt].additive_default;
} else {
if (fmt < 0) return ipixel_span_draw_over;
if (isadditive == 0) return ipixel_span_proc_list[fmt].blend;
else return ipixel_span_proc_list[fmt].additive;
}
}
void ipixel_set_span_proc(int fmt, int isadditive, iSpanDrawProc proc)
{
assert(fmt >= 0 && fmt < IPIX_FMT_COUNT);
if (fmt < -1 || fmt >= IPIX_FMT_COUNT) {
abort();
return;
}
if (ipixel_lut_inited == 0) ipixel_lut_init();
if (fmt < 0) {
if (proc != NULL) {
ipixel_span_draw_over = proc;
} else {
ipixel_span_draw_over = ipixel_span_draw_proc_over_32;
}
} else {
if (isadditive == 0) {
if (proc != NULL) {
ipixel_span_proc_list[fmt].blend = proc;
} else {
ipixel_span_proc_list[fmt].blend =
ipixel_span_proc_list[fmt].blend_default;
}
} else {
if (proc != NULL) {
ipixel_span_proc_list[fmt].additive = proc;
} else {
ipixel_span_proc_list[fmt].additive =
ipixel_span_proc_list[fmt].additive_default;
}
}
}
}
/**********************************************************************
* CARD operations
**********************************************************************/
/* reverse card */
void ipixel_card_reverse(IUINT32 *card, int size)
{
IUINT32 *p1, *p2;
IUINT32 value;
for (p1 = card, p2 = card + size - 1; p1 < p2; p1++, p2--) {
value = *p1;
*p1 = *p2;
*p2 = value;
}
}
/* multi card */
void ipixel_card_multi_default(IUINT32 *card, int size, IUINT32 color)
{
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2, f;
IRGBA_FROM_A8R8G8B8(color, r1, g1, b1, a1);
if ((color & 0xffffff) == 0xffffff) f = 1;
else f = 0;
if (color == 0xffffffff) {
return;
}
else if (color == 0) {
memset(card, 0, sizeof(IUINT32) * size);
}
else if (f) {
IUINT8 *src = (IUINT8*)card;
if (a1 == 0) {
for (; size > 0; size--) {
#if IWORDS_BIG_ENDIAN
src[0] = 0;
#else
src[3] = 0;
#endif
src += sizeof(IUINT32);
}
return;
}
a1 = _ipixel_norm(a1);
for (; size > 0; size--) {
#if IWORDS_BIG_ENDIAN
a2 = src[0];
src[0] = (IUINT8)((a2 * a1) >> 8);
#else
a2 = src[3];
src[3] = (IUINT8)((a2 * a1) >> 8);
#endif
src += sizeof(IUINT32);
}
}
else {
IUINT8 *src = (IUINT8*)card;
a1 = _ipixel_norm(a1);
r1 = _ipixel_norm(r1);
g1 = _ipixel_norm(g1);
b1 = _ipixel_norm(b1);
for (; size > 0; src += sizeof(IUINT32), size--) {
_ipixel_load_card(src, r2, g2, b2, a2);
r2 = (r1 * r2) >> 8;
g2 = (g1 * g2) >> 8;
b2 = (b1 * b2) >> 8;
a2 = (a1 * a2) >> 8;
*((IUINT32*)src) = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
}
void (*ipixel_card_multi_proc)(IUINT32 *card, int size, IUINT32 color) =
ipixel_card_multi_default;
/* multi card */
void ipixel_card_multi(IUINT32 *card, int size, IUINT32 color)
{
ipixel_card_multi_proc(card, size, color);
}
/* mask card */
void ipixel_card_mask_default(IUINT32 *card, int size, const IUINT32 *mask)
{
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2;
for (; size > 0; card++, mask++, size--) {
_ipixel_load_card(mask, r1, g1, b1, a1);
_ipixel_load_card(card, r2, g2, b2, a2);
r2 = _imul_y_div_255(r2, r1);
g2 = _imul_y_div_255(g2, g1);
b2 = _imul_y_div_255(b2, b1);
a2 = _imul_y_div_255(a2, a1);
*card = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
void (*ipixel_card_mask_proc)(IUINT32 *card, int size, const IUINT32 *mask) =
ipixel_card_mask_default;
/* mask card */
void ipixel_card_mask(IUINT32 *card, int size, const IUINT32 *mask)
{
ipixel_card_mask_proc(card, size, mask);
}
/* cover multi */
void ipixel_card_cover_default(IUINT32 *card, int size, const IUINT8 *cover)
{
IINT32 cc, aa;
for (; size > 0; card++, size--) {
cc = *cover++;
if (cc == 0) {
((IUINT8*)card)[_ipixel_card_alpha] = 0;
}
else {
aa = ((IUINT8*)card)[_ipixel_card_alpha];
if (aa == 0) continue;
aa *= cc;
((IUINT8*)card)[_ipixel_card_alpha] = (IUINT8)_idiv_255(aa);
}
}
}
void (*ipixel_card_cover_proc)(IUINT32 *card, int size, const IUINT8 *cover)
= ipixel_card_cover_default;
/* mask cover */
void ipixel_card_cover(IUINT32 *card, int size, const IUINT8 *cover)
{
ipixel_card_cover_proc(card, size, cover);
}
void ipixel_card_over_default(IUINT32 *dst, int size, const IUINT32 *card,
const IUINT8 *cover)
{
IUINT32 *endup = dst + size;
if (cover == NULL) {
for (; dst < endup; card++, dst++) {
IBLEND_PARGB(dst[0], card[0]);
}
} else {
for (; dst < endup; cover++, card++, dst++) {
IBLEND_PARGB_COVER(dst[0], card[0], cover[0]);
}
}
}
void (*ipixel_card_over_proc)(IUINT32*, int, const IUINT32*, const IUINT8*) =
ipixel_card_over_default;
/* card composite: src over */
void ipixel_card_over(IUINT32 *dst, int size, const IUINT32 *card,
const IUINT8 *cover)
{
ipixel_card_over_proc(dst, size, card, cover);
}
/* card proc set */
void ipixel_card_set_proc(int id, void *proc)
{
if (id == 0) {
if (proc == NULL) ipixel_card_multi_proc = ipixel_card_multi_default;
else {
ipixel_card_multi_proc =
(void (*)(IUINT32 *, int, IUINT32))proc;
}
}
else if (id == 1) {
if (proc == NULL) ipixel_card_mask_proc = ipixel_card_mask_default;
else {
ipixel_card_mask_proc =
(void (*)(IUINT32 *, int, const IUINT32 *))proc;
}
}
else if (id == 2) {
if (proc == NULL) ipixel_card_cover_proc = ipixel_card_cover_default;
else {
ipixel_card_cover_proc =
(void (*)(IUINT32 *, int, const IUINT8 *))proc;
}
}
else if (id == 3) {
if (proc == NULL) ipixel_card_over_proc = ipixel_card_over_default;
else {
ipixel_card_over_proc =
(void (*)(IUINT32*, int, const IUINT32*, const IUINT8*))proc;
}
}
}
/**********************************************************************
* MACRO: HLINE ROUTINE
**********************************************************************/
/* hline filling: 8/16/24/32 bits without palette */
#define IPIXEL_HLINE_DRAW_PROC_N(fmt, bpp, nbytes, mode) \
static void ipixel_hline_draw_proc_##fmt##_0(void *bits, \
int offset, int w, IUINT32 color, const IUINT8 *cover, \
const iColorIndex *idx) \
{ \
unsigned char *dst = ((unsigned char*)bits) + offset * nbytes; \
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2, cc, cx, cz; \
IRGBA_FROM_A8R8G8B8(color, r1, g1, b1, a1); \
if (a1 == 0) return; \
cz = IRGBA_TO_PIXEL(fmt, r1, g1, b1, a1); \
if (cover == NULL) { \
if (a1 == 255) { \
_ipixel_fill(bpp, dst, 0, w, cz); \
} \
else if (a1 > 0) { \
for (; w > 0; dst += nbytes, w--) { \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
} \
} else { \
if (a1 == 255) { \
for (; w > 0; dst += nbytes, w--) { \
a1 = *cover++; \
if (a1 == 255) { \
_ipixel_store(bpp, dst, 0, cz); \
} \
else if (a1 > 0) { \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
} \
} \
else if (a1 > 0) { \
a1 = _ipixel_norm(a1); \
for (; w > 0; dst += nbytes, w--) { \
cx = *cover++; \
if (cx > 0) { \
cx = (cx * a1) >> 8; \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, cx, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
} \
} \
} \
} \
static void ipixel_hline_draw_proc_##fmt##_1(void *bits, \
int offset, int w, IUINT32 color, const IUINT8 *cover, \
const iColorIndex *idx) \
{ \
unsigned char *dst = ((unsigned char*)bits) + offset * nbytes; \
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2, cc, cx; \
IRGBA_FROM_A8R8G8B8(color, r1, g1, b1, a1); \
if (a1 == 0) return; \
if (cover == NULL) { \
r2 = g2 = b2 = a2 = 0; \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, a2, b2); \
r1 = r2; g1 = g2; b1 = b2; a1 = a2; \
for (; w > 0; dst += nbytes, w--) { \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
r2 = ICLIP_256(r1 + r2); \
g2 = ICLIP_256(g1 + g2); \
b2 = ICLIP_256(b1 + b2); \
a2 = ICLIP_256(a1 + a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
} else { \
if (a1 == 255) { \
for (; w > 0; dst += nbytes, w--) { \
a1 = *cover++; \
if (a1 > 0) { \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
} \
} \
else if (a1 > 0) { \
a1 = _ipixel_norm(a1); \
for (; w > 0; dst += nbytes, w--) { \
cx = *cover++; \
if (cx > 0) { \
cx = (cx * a1) >> 8; \
cc = _ipixel_fetch(bpp, dst, 0); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, cx, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, 0, cc); \
} \
} \
} \
} \
}
/* hline filling: 8/4/1 bits with or without palette */
#define IPIXEL_HLINE_DRAW_PROC_X(fmt, bpp, nbytes, mode, init) \
static void ipixel_hline_draw_proc_##fmt##_0(void *bits, \
int offset, int w, IUINT32 col, const IUINT8 *cover, \
const iColorIndex *_ipixel_src_index) \
{ \
unsigned char *dst = ((unsigned char*)bits); \
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2, cc, cx, cz; \
init; \
IRGBA_FROM_A8R8G8B8(col, r1, g1, b1, a1); \
if (a1 == 0) return; \
cz = IRGBA_TO_PIXEL(fmt, r1, g1, b1, a1); \
if (cover == NULL) { \
if (a1 == 255) { \
_ipixel_fill(bpp, dst, offset, w, cz); \
} \
else if (a1 > 0) { \
for (; w > 0; offset++, w--) { \
cc = _ipixel_fetch(bpp, dst, offset); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, offset, cc); \
} \
} \
} else { \
if (a1 == 255) { \
for (; w > 0; offset++, w--) { \
a1 = *cover++; \
if (a1 == 255) { \
_ipixel_store(bpp, dst, offset, cz); \
} \
else if (a1 > 0) { \
cc = _ipixel_fetch(bpp, dst, offset); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, offset, cc); \
} \
} \
} \
else if (a1 > 0) { \
a1 = _ipixel_norm(a1); \
for (; w > 0; offset++, w--) { \
cx = (*cover++ * a1) >> 8; \
if (cx == 255) { \
cc = IRGBA_TO_PIXEL(fmt, r1, g1, b1, 255); \
_ipixel_store(bpp, dst, offset, cc); \
} \
else if (cx > 0) { \
cc = _ipixel_fetch(bpp, dst, offset); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_##mode(r1, g1, b1, cx, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r1, g1, b1, 255); \
_ipixel_store(bpp, dst, offset, cc); \
} \
} \
} \
} \
} \
static void ipixel_hline_draw_proc_##fmt##_1(void *bits, \
int offset, int w, IUINT32 col, const IUINT8 *cover, \
const iColorIndex *_ipixel_src_index) \
{ \
unsigned char *dst = ((unsigned char*)bits); \
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2, cc, cx; \
init; \
IRGBA_FROM_A8R8G8B8(col, r1, g1, b1, a1); \
if (a1 == 0) return; \
if (cover == NULL) { \
r2 = g2 = b2 = a2 = 0; \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, a2, b2); \
r1 = r2; g1 = g2; b1 = b2; a1 = a2; \
for (; w > 0; dst += nbytes, w--) { \
cc = _ipixel_fetch(bpp, dst, offset); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
r2 = ICLIP_256(r1 + r2); \
g2 = ICLIP_256(g1 + g2); \
b2 = ICLIP_256(b1 + b2); \
a2 = ICLIP_256(a1 + a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, offset, cc); \
} \
} else { \
if (a1 == 255) { \
for (; w > 0; offset++, w--) { \
a1 = *cover++; \
if (a1 > 0) { \
cc = _ipixel_fetch(bpp, dst, offset); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, a1, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r2, g2, b2, a2); \
_ipixel_store(bpp, dst, offset, cc); \
} \
} \
} \
else if (a1 > 0) { \
a1 = _ipixel_norm(a1); \
for (; w > 0; offset++, w--) { \
cx = *cover++; \
if (cx > 0) { \
cx = (cx * a1) >> 8; \
cc = _ipixel_fetch(bpp, dst, offset); \
IRGBA_FROM_PIXEL(fmt, cc, r2, g2, b2, a2); \
IBLEND_ADDITIVE(r1, g1, b1, cx, r2, g2, b2, a2); \
cc = IRGBA_TO_PIXEL(fmt, r1, g1, b1, 255); \
_ipixel_store(bpp, dst, offset, cc); \
} \
} \
} \
} \
}
/* hline filling: 8/4/1 bits without palette */
#define IPIXEL_HLINE_DRAW_PROC_BITS(fmt, bpp, nbytes, mode) \
IPIXEL_HLINE_DRAW_PROC_X(fmt, bpp, nbytes, mode, {})
/* hline filling: 8/4/1 bits with palette */
#define IPIXEL_HLINE_DRAW_PROC_PAL(fmt, bpp, nbytes, mode) \
IPIXEL_HLINE_DRAW_PROC_X(fmt, bpp, nbytes, mode, \
const iColorIndex *_ipixel_dst_index = _ipixel_src_index)
/* hline filling: main macro */
#define IPIXEL_HLINE_DRAW_MAIN(type, fmt, bpp, nbytes, mode) \
IPIXEL_HLINE_DRAW_PROC_##type(fmt, bpp, nbytes, mode)
#if 1
IPIXEL_HLINE_DRAW_MAIN(N, A8R8G8B8, 32, 4, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, A8B8G8R8, 32, 4, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, R8G8B8A8, 32, 4, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, B8G8R8A8, 32, 4, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, X8R8G8B8, 32, 4, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, X8B8G8R8, 32, 4, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, R8G8B8X8, 32, 4, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, B8G8R8X8, 32, 4, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, P8R8G8B8, 32, 4, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, R8G8B8, 24, 3, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, B8G8R8, 24, 3, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, R5G6B5, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, B5G6R5, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, X1R5G5B5, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, X1B5G5R5, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, R5G5B5X1, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, B5G5R5X1, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, A1R5G5B5, 16, 2, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, A1B5G5R5, 16, 2, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, R5G5B5A1, 16, 2, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, B5G5R5A1, 16, 2, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, X4R4G4B4, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, X4B4G4R4, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, R4G4B4X4, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, B4G4R4X4, 16, 2, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, A4R4G4B4, 16, 2, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, A4B4G4R4, 16, 2, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, R4G4B4A4, 16, 2, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, B4G4R4A4, 16, 2, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(PAL, C8, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, G8, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, A8, 8, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, R3G3B2, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, B2G3R3, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, X2R2G2B2, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, X2B2G2R2, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, R2G2B2X2, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, B2G2R2X2, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, A2R2G2B2, 8, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, A2B2G2R2, 8, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, R2G2B2A2, 8, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(N, B2G2R2A2, 8, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(PAL, X4C4, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, X4G4, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, X4A4, 8, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(PAL, C4X4, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, G4X4, 8, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(N, A4X4, 8, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(PAL, C4, 4, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(BITS, G4, 4, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(BITS, A4, 4, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(BITS, R1G2B1, 4, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(BITS, B1G2R1, 4, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(BITS, A1R1G1B1, 4, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(BITS, A1B1G1R1, 4, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(BITS, R1G1B1A1, 4, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(BITS, B1G1R1A1, 4, 1, NORMAL_FAST)
IPIXEL_HLINE_DRAW_MAIN(BITS, X1R1G1B1, 4, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(BITS, X1B1G1R1, 4, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(BITS, R1G1B1X1, 4, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(BITS, B1G1R1X1, 4, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(PAL, C1, 1, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(BITS, G1, 1, 1, STATIC)
IPIXEL_HLINE_DRAW_MAIN(BITS, A1, 1, 1, NORMAL_FAST)
#endif
#undef IPIXEL_HLINE_DRAW_MAIN
#undef IPIXEL_HLINE_DRAW_PROC_PAL
#undef IPIXEL_HLINE_DRAW_PROC_BITS
#undef IPIXEL_HLINE_DRAW_PROC_X
#undef IPIXEL_HLINE_DRAW_PROC_N
struct iPixelHLineDrawProc
{
iHLineDrawProc blend, additive, blend_default, additive_default;
};
#define ITABLE_ITEM(fmt) { \
ipixel_hline_draw_proc_##fmt##_0, ipixel_hline_draw_proc_##fmt##_1, \
ipixel_hline_draw_proc_##fmt##_0, ipixel_hline_draw_proc_##fmt##_1 }
static struct iPixelHLineDrawProc ipixel_hline_proc_list[IPIX_FMT_COUNT] =
{
ITABLE_ITEM(A8R8G8B8),
ITABLE_ITEM(A8B8G8R8),
ITABLE_ITEM(R8G8B8A8),
ITABLE_ITEM(B8G8R8A8),
ITABLE_ITEM(X8R8G8B8),
ITABLE_ITEM(X8B8G8R8),
ITABLE_ITEM(R8G8B8X8),
ITABLE_ITEM(B8G8R8X8),
ITABLE_ITEM(P8R8G8B8),
ITABLE_ITEM(R8G8B8),
ITABLE_ITEM(B8G8R8),
ITABLE_ITEM(R5G6B5),
ITABLE_ITEM(B5G6R5),
ITABLE_ITEM(X1R5G5B5),
ITABLE_ITEM(X1B5G5R5),
ITABLE_ITEM(R5G5B5X1),
ITABLE_ITEM(B5G5R5X1),
ITABLE_ITEM(A1R5G5B5),
ITABLE_ITEM(A1B5G5R5),
ITABLE_ITEM(R5G5B5A1),
ITABLE_ITEM(B5G5R5A1),
ITABLE_ITEM(X4R4G4B4),
ITABLE_ITEM(X4B4G4R4),
ITABLE_ITEM(R4G4B4X4),
ITABLE_ITEM(B4G4R4X4),
ITABLE_ITEM(A4R4G4B4),
ITABLE_ITEM(A4B4G4R4),
ITABLE_ITEM(R4G4B4A4),
ITABLE_ITEM(B4G4R4A4),
ITABLE_ITEM(C8),
ITABLE_ITEM(G8),
ITABLE_ITEM(A8),
ITABLE_ITEM(R3G3B2),
ITABLE_ITEM(B2G3R3),
ITABLE_ITEM(X2R2G2B2),
ITABLE_ITEM(X2B2G2R2),
ITABLE_ITEM(R2G2B2X2),
ITABLE_ITEM(B2G2R2X2),
ITABLE_ITEM(A2R2G2B2),
ITABLE_ITEM(A2B2G2R2),
ITABLE_ITEM(R2G2B2A2),
ITABLE_ITEM(B2G2R2A2),
ITABLE_ITEM(X4C4),
ITABLE_ITEM(X4G4),
ITABLE_ITEM(X4A4),
ITABLE_ITEM(C4X4),
ITABLE_ITEM(G4X4),
ITABLE_ITEM(A4X4),
ITABLE_ITEM(C4),
ITABLE_ITEM(G4),
ITABLE_ITEM(A4),
ITABLE_ITEM(R1G2B1),
ITABLE_ITEM(B1G2R1),
ITABLE_ITEM(A1R1G1B1),
ITABLE_ITEM(A1B1G1R1),
ITABLE_ITEM(R1G1B1A1),
ITABLE_ITEM(B1G1R1A1),
ITABLE_ITEM(X1R1G1B1),
ITABLE_ITEM(X1B1G1R1),
ITABLE_ITEM(R1G1B1X1),
ITABLE_ITEM(B1G1R1X1),
ITABLE_ITEM(C1),
ITABLE_ITEM(G1),
ITABLE_ITEM(A1),
};
#undef ITABLE_ITEM
/* get a hline drawing function with given pixel format */
iHLineDrawProc ipixel_get_hline_proc(int fmt, int isadditive, int usedefault)
{
assert(fmt >= 0 && fmt < IPIX_FMT_COUNT);
if (fmt < 0 || fmt >= IPIX_FMT_COUNT) {
abort();
return NULL;
}
if (ipixel_lut_inited == 0) ipixel_lut_init();
if (usedefault) {
if (isadditive == 0)
return ipixel_hline_proc_list[fmt].blend_default;
else
return ipixel_hline_proc_list[fmt].additive_default;
} else {
if (isadditive == 0)
return ipixel_hline_proc_list[fmt].blend;
else
return ipixel_hline_proc_list[fmt].additive;
}
}
/* set a hline drawing function */
void ipixel_set_hline_proc(int fmt, int isadditive, iHLineDrawProc proc)
{
assert(fmt >= 0 && fmt < IPIX_FMT_COUNT);
if (fmt < 0 || fmt >= IPIX_FMT_COUNT) {
abort();
return;
}
if (ipixel_lut_inited == 0) ipixel_lut_init();
if (isadditive == 0) {
if (proc != NULL) {
ipixel_hline_proc_list[fmt].blend = proc;
} else {
ipixel_hline_proc_list[fmt].blend =
ipixel_hline_proc_list[fmt].blend_default;
}
} else {
if (proc != NULL) {
ipixel_hline_proc_list[fmt].additive = proc;
} else {
ipixel_hline_proc_list[fmt].additive =
ipixel_hline_proc_list[fmt].additive_default;
}
}
}
/* ipixel_blend - blend between two formats
* you must provide a working memory pointer to workmem. if workmem eq NULL,
* this function will do nothing but returns how many bytes needed in workmem
* dfmt - dest pixel format
* dbits - dest pixel buffer
* dpitch - dest row stride
* dx - dest x offset
* sfmt - source pixel format
* sbits - source pixel buffer
* spitch - source row stride
* sx - source x offset
* w - width
* h - height
* color - const color
* op - blending operator (IPIXEL_BLEND_OP_BLEND, ADD, COPY)
* flip - flip (IPIXEL_FLIP_NONE, HFLIP, VFLIP)
* dindex - dest index
* sindex - source index
* workmem - working memory
* this function need some memory to work with. to avoid allocating,
* you must provide a memory block whose size is (w * 4) to it.
*/
long ipixel_blend(int dfmt, void *dbits, long dpitch, int dx, int sfmt,
const void *sbits, long spitch, int sx, int w, int h, IUINT32 color,
int op, int flip, const iColorIndex *dindex,
const iColorIndex *sindex, void *workmem)
{
IUINT32 *buffer = (IUINT32*)workmem;
IUINT8 *dline = (IUINT8*)dbits;
const IUINT8 *sline = (const IUINT8*)sbits;
iSpanDrawProc drawspan = NULL;
iFetchProc fetch;
iStoreProc store;
int k;
if (workmem == NULL) {
return w * sizeof(IUINT32);
}
fetch = ipixel_get_fetch(sfmt, IPIXEL_ACCESS_MODE_NORMAL);
store = ipixel_get_store(dfmt, IPIXEL_ACCESS_MODE_NORMAL);
if (op == IPIXEL_BLEND_OP_BLEND) {
drawspan = ipixel_get_span_proc(dfmt, 0, 0);
}
else if (op == IPIXEL_BLEND_OP_ADD) {
drawspan = ipixel_get_span_proc(dfmt, 1, 0);
}
if ((flip & IPIXEL_FLIP_VFLIP) != 0) {
sline = sline + spitch * (h - 1);
spitch = -spitch;
}
if (sfmt == IPIX_FMT_P8R8G8B8 && dfmt == IPIX_FMT_P8R8G8B8) {
if (op == IPIXEL_BLEND_OP_BLEND && color == 0xffffffff) {
sfmt = IPIX_FMT_A8R8G8B8;
dfmt = IPIX_FMT_A8R8G8B8;
drawspan = ipixel_get_span_proc(-1, 0, 0);
}
}
if (sfmt == IPIX_FMT_A8R8G8B8 && (flip & IPIXEL_FLIP_HFLIP) == 0 &&
color == 0xffffffff) {
if (drawspan != NULL) {
for (k = 0; k < h; sline += spitch, dline += dpitch, k++) {
const IUINT32 *src = ((const IUINT32*)sline) + sx;
IUINT32 *dst = ((IUINT32*)dline);
drawspan(dst, dx, w, src, NULL, dindex);
}
} else {
for (k = 0; k < h; sline += spitch, dline += dpitch, k++) {
const IUINT32 *src = ((const IUINT32*)sline) + sx;
IUINT32 *dst = ((IUINT32*)dline);
store(dst, src, dx, w, dindex);
}
}
return 0;
}
#define IPIXEL_BLEND_LOOP(work) do { \
for (k = 0; k < h; sline += spitch, dline += dpitch, k++) { \
const IUINT32 *src = ((const IUINT32*)sline); \
IUINT32 *dst = ((IUINT32*)dline); \
fetch(src, sx, w, buffer, sindex); \
work; \
} \
} while (0)
if ((flip & IPIXEL_FLIP_HFLIP) == 0) {
if (drawspan != NULL) {
if (color == 0xffffffff) {
IPIXEL_BLEND_LOOP( {
drawspan(dst, dx, w, buffer, NULL, dindex);
});
} else {
IPIXEL_BLEND_LOOP( {
ipixel_card_multi_proc(buffer, w, color);
drawspan(dst, dx, w, buffer, NULL, dindex);
});
}
} else {
if (color == 0xffffffff) {
IPIXEL_BLEND_LOOP( {
store(dst, buffer, dx, w, dindex);
});
} else {
IPIXEL_BLEND_LOOP( {
ipixel_card_multi_proc(buffer, w, color);
store(dst, buffer, dx, w, dindex);
});
}
}
} else {
if (drawspan != NULL) {
if (color == 0xffffffff) {
IPIXEL_BLEND_LOOP( {
ipixel_card_reverse(buffer, w);
drawspan(dst, dx, w, buffer, NULL, dindex);
});
} else {
IPIXEL_BLEND_LOOP( {
ipixel_card_reverse(buffer, w);
ipixel_card_multi_proc(buffer, w, color);
drawspan(dst, dx, w, buffer, NULL, dindex);
});
}
} else {
if (color == 0xffffffff) {
IPIXEL_BLEND_LOOP( {
ipixel_card_reverse(buffer, w);
store(dst, buffer, dx, w, dindex);
});
} else {
IPIXEL_BLEND_LOOP( {
ipixel_card_reverse(buffer, w);
ipixel_card_multi_proc(buffer, w, color);
store(dst, buffer, dx, w, dindex);
});
}
}
}
#undef IPIXEL_BLEND_LOOP
return 0;
}
/**********************************************************************
* MACRO: BLITING ROUTINE
**********************************************************************/
/* normal blit in 32/16/8 bits */
#define IPIXEL_BLIT_PROC_N(nbits, nbytes, INTTYPE) \
static int ipixel_blit_proc_##nbits(void *dbits, long dpitch, int dx, \
const void *sbits, long spitch, int sx, int w, int h, IUINT32 mask, \
int flip) \
{ \
int y, x; \
if (flip & IPIXEL_FLIP_VFLIP) { \
sbits = (const IUINT8*)sbits + spitch * (h - 1); \
spitch = -spitch; \
} \
if ((flip & IPIXEL_FLIP_HFLIP) == 0) { \
long size = w * nbytes; \
for (y = 0; y < h; y++) { \
memcpy((INTTYPE*)dbits + dx, (const INTTYPE*)sbits + sx, size); \
dbits = (IUINT8*)dbits + dpitch; \
sbits = (const IUINT8*)sbits + spitch; \
} \
} else { \
for (y = 0; y < h; y++) { \
const INTTYPE *src = (const INTTYPE*)sbits + sx + w - 1; \
INTTYPE *dst = (INTTYPE*)dbits + dx; \
for (x = w; x > 0; x--) *dst++ = *src--; \
dbits = (IUINT8*)dbits + dpitch; \
sbits = (const IUINT8*)sbits + spitch; \
} \
} \
return 0; \
}
/* normal blit in 24/4/1 bits */
#define IPIXEL_BLIT_PROC_BITS(nbits) \
static int ipixel_blit_proc_##nbits(void *dbits, long dpitch, int dx, \
const void *sbits, long spitch, int sx, int w, int h, IUINT32 mask, \
int flip) \
{ \
int y, x1, x2, sx0, sxd, endx; \
if (flip & IPIXEL_FLIP_VFLIP) { \
sbits = (const IUINT8*)sbits + spitch * (h - 1); \
spitch = -spitch; \
} \
if (flip & IPIXEL_FLIP_HFLIP) { \
sx0 = sx + w - 1; \
sxd = -1; \
} else { \
sx0 = sx; \
sxd = 1; \
} \
endx = dx + w; \
for (y = 0; y < h; y++) { \
IUINT32 cc; \
for (x1 = dx, x2 = sx0; x1 < endx; x1++, x2 += sxd) { \
cc = _ipixel_fetch(nbits, sbits, x2); \
_ipixel_store(nbits, dbits, x1, cc); \
} \
dbits = (IUINT8*)dbits + dpitch; \
sbits = (const IUINT8*)sbits + spitch; \
} \
return 0; \
}
/* mask blit in 32/16/8 bits */
#define IPIXEL_BLIT_MASK_PROC_N(nbits, nbytes, INTTYPE) \
static int ipixel_blit_mask_proc_##nbits(void *dbits, long dpitch, \
int dx, const void *sbits, long spitch, int sx, int w, int h, \
IUINT32 mask, int flip) \
{ \
INTTYPE cmask = (INTTYPE)mask; \
int y; \
if (flip & IPIXEL_FLIP_VFLIP) { \
sbits = (const IUINT8*)sbits + spitch * (h - 1); \
spitch = -spitch; \
} \
if ((flip & IPIXEL_FLIP_HFLIP) == 0) { \
for (y = 0; y < h; y++) { \
const INTTYPE *src = (const INTTYPE*)sbits + sx; \
INTTYPE *dst = (INTTYPE*)dbits + dx; \
INTTYPE *dstend = dst + w; \
for (; dst < dstend; src++, dst++) { \
if (src[0] != cmask) dst[0] = src[0]; \
} \
dbits = (IUINT8*)dbits + dpitch; \
sbits = (const IUINT8*)sbits + spitch; \
} \
} else { \
for (y = 0; y < h; y++) { \
const INTTYPE *src = (const INTTYPE*)sbits + sx + w - 1; \
INTTYPE *dst = (INTTYPE*)dbits + dx; \
INTTYPE *dstend = dst + w; \
for (; dst < dstend; src--, dst++) { \
if (src[0] != cmask) dst[0] = src[0]; \
} \
dbits = (IUINT8*)dbits + dpitch; \
sbits = (const IUINT8*)sbits + spitch; \
} \
} \
return 0; \
}
/* mask blit in 24/4/1 bits */
#define IPIXEL_BLIT_MASK_PROC_BITS(nbits) \
static int ipixel_blit_mask_proc_##nbits(void *dbits, long dpitch, \
int dx, const void *sbits, long spitch, int sx, int w, int h, \
IUINT32 mask, int flip) \
{ \
int y, x1, x2, sx0, sxd, endx; \
if (flip & IPIXEL_FLIP_VFLIP) { \
sbits = (const IUINT8*)sbits + spitch * (h - 1); \
spitch = -spitch; \
} \
if (flip & IPIXEL_FLIP_HFLIP) { \
sx0 = sx + w - 1; \
sxd = -1; \
} else { \
sx0 = sx; \
sxd = 1; \
} \
endx = dx + w; \
for (y = 0; y < h; y++) { \
IUINT32 cc; \
for (x1 = dx, x2 = sx0; x1 < endx; x1++, x2 += sxd) { \
cc = _ipixel_fetch(nbits, sbits, x2); \
if (cc != mask) _ipixel_store(nbits, dbits, x1, cc); \
} \
dbits = (IUINT8*)dbits + dpitch; \
sbits = (const IUINT8*)sbits + spitch; \
} \
return 0; \
}
/* normal bliter */
IPIXEL_BLIT_PROC_N(32, 4, IUINT32);
IPIXEL_BLIT_PROC_N(16, 2, IUINT16);
IPIXEL_BLIT_PROC_N(8, 1, IUINT8);
IPIXEL_BLIT_PROC_BITS(24);
IPIXEL_BLIT_PROC_BITS(4);
IPIXEL_BLIT_PROC_BITS(1);
/* mask bliter */
IPIXEL_BLIT_MASK_PROC_N(32, 4, IUINT32);
IPIXEL_BLIT_MASK_PROC_N(16, 2, IUINT16);
IPIXEL_BLIT_MASK_PROC_N(8, 1, IUINT8);
IPIXEL_BLIT_MASK_PROC_BITS(24);
IPIXEL_BLIT_MASK_PROC_BITS(4);
IPIXEL_BLIT_MASK_PROC_BITS(1);
#undef IPIXEL_BLIT_PROC_N
#undef IPIXEL_BLIT_PROC_BITS
#undef IPIXEL_BLIT_MASK_PROC_N
#undef IPIXEL_BLIT_MASK_PROC_BITS
/* blit driver desc */
struct iPixelBlitProc
{
iBlitProc normal, normal_default;
iBlitProc mask, mask_default;
};
#define ITABLE_ITEM(bpp) { \
ipixel_blit_proc_##bpp, ipixel_blit_proc_##bpp, \
ipixel_blit_mask_proc_##bpp, ipixel_blit_mask_proc_##bpp }
/* blit procedure look up table */
static struct iPixelBlitProc ipixel_blit_proc_list[6] =
{
ITABLE_ITEM(32),
ITABLE_ITEM(24),
ITABLE_ITEM(16),
ITABLE_ITEM(8),
ITABLE_ITEM(4),
ITABLE_ITEM(1),
};
static const int ipixel_lookup_bpp[33] = {
-1, 5, -1, -1, 4, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1,
2, 2, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1,
-1, -1, 0,
};
/* get normal blit procedure */
/* if ismask equals to zero, returns normal bliter */
/* if ismask doesn't equal to zero, returns transparent bliter */
iBlitProc ipixel_blit_get(int bpp, int istransparent, int isdefault)
{
int index;
if (bpp < 0 || bpp > 32) return NULL;
index = ipixel_lookup_bpp[bpp];
if (index < 0) return NULL;
if (isdefault) {
if (istransparent) return ipixel_blit_proc_list[index].mask_default;
return ipixel_blit_proc_list[index].normal_default;
}
if (istransparent) return ipixel_blit_proc_list[index].mask;
return ipixel_blit_proc_list[index].normal;
}
/* set normal blit procedure */
/* if ismask equals to zero, set normal bliter */
/* if ismask doesn't equal to zero, set transparent bliter */
void ipixel_set_blit_proc(int bpp, int istransparent, iBlitProc proc)
{
int index;
if (bpp < 0 || bpp > 32) return;
index = ipixel_lookup_bpp[bpp];
if (index < 0) return;
if (istransparent == 0) {
if (proc != NULL) {
ipixel_blit_proc_list[index].normal = proc;
} else {
ipixel_blit_proc_list[index].normal =
ipixel_blit_proc_list[index].normal_default;
}
} else {
if (proc != NULL) {
ipixel_blit_proc_list[index].mask = proc;
} else {
ipixel_blit_proc_list[index].mask =
ipixel_blit_proc_list[index].mask_default;
}
}
}
/* ipixel_blit - bliting (copy pixel from one rectangle to another)
* it will only copy pixels in the same depth (1/4/8/16/24/32).
* no color format will be convert (using ipixel_convert to do it)
* bpp - color depth of the two bitmap
* dst - dest bits
* dpitch - dest pitch (row stride)
* dx - dest x offset
* src - source bits
* spitch - source pitch (row stride)
* sx - source x offset
* w - width
* h - height
* mask - mask color (colorkey), no effect without IPIXEL_BLIT_MASK
* mode - IPIXEL_FLIP_HFLIP | IPIXEL_FLIP_VFLIP | IPIXEL_BLIT_MASK ..
* for transparent bliting, set mode with IPIXEL_BLIT_MASK, bliter will
* skip the colors equal to 'mask' parameter.
*/
void ipixel_blit(int bpp, void *dst, long dpitch, int dx, const void *src,
long spitch, int sx, int w, int h, IUINT32 mask, int mode)
{
int transparent, flip, index, retval;
iBlitProc bliter;
transparent = (mask & IPIXEL_BLIT_MASK)? 1 : 0;
flip = mode & (IPIXEL_FLIP_HFLIP | IPIXEL_FLIP_VFLIP);
assert(bpp >= 0 && bpp <= 32);
index = ipixel_lookup_bpp[bpp];
if (transparent) bliter = ipixel_blit_proc_list[index].mask;
else bliter = ipixel_blit_proc_list[index].normal;
/* using current bliter */
bliter = ipixel_blit_get(bpp, transparent, 0);
if (bliter) {
retval = bliter(dst, dpitch, dx, src, spitch, sx, w, h, mask, flip);
if (retval == 0) return; /* return for success */
}
/* using default bliter */
if (transparent) bliter = ipixel_blit_proc_list[index].mask_default;
else bliter = ipixel_blit_proc_list[index].normal_default;
bliter(dst, dpitch, dx, src, spitch, sx, w, h, mask, flip);
}
/**********************************************************************
* CONVERTING
**********************************************************************/
static iPixelCvt ipixel_cvt_table[IPIX_FMT_COUNT][IPIX_FMT_COUNT][8];
static int ipixel_cvt_inited = 0;
/* initialize converting procedure table */
static void ipixel_cvt_init(void)
{
int dfmt, sfmt, i;
if (ipixel_cvt_inited) return;
for (dfmt = 0; dfmt < IPIX_FMT_COUNT; dfmt++) {
for (sfmt = 0; sfmt < IPIX_FMT_COUNT; sfmt++) {
for (i = 0; i < 8; i++) ipixel_cvt_table[dfmt][sfmt][i] = NULL;
}
}
ipixel_cvt_inited = 1;
}
/* get converting procedure */
iPixelCvt ipixel_cvt_get(int dfmt, int sfmt, int index)
{
if (ipixel_cvt_inited == 0) ipixel_cvt_init();
if (dfmt < 0 || dfmt >= IPIX_FMT_COUNT) return NULL;
if (sfmt < 0 || sfmt >= IPIX_FMT_COUNT) return NULL;
if (index < 0 || index >= 8) return NULL;
return ipixel_cvt_table[dfmt][sfmt][index];
}
/* set converting procedure */
void ipixel_cvt_set(int dfmt, int sfmt, int index, iPixelCvt proc)
{
if (ipixel_cvt_inited == 0) ipixel_cvt_init();
if (dfmt < 0 || dfmt >= IPIX_FMT_COUNT) return;
if (sfmt < 0 || sfmt >= IPIX_FMT_COUNT) return;
if (index < 0 || index >= 8) return;
ipixel_cvt_table[dfmt][sfmt][index] = proc;
}
/* ipixel_slow: default slow converter */
long ipixel_cvt_slow(int dfmt, void *dbits, long dpitch, int dx, int sfmt,
const void *sbits, long spitch, int sx, int w, int h, IUINT32 mask,
int mode, const iColorIndex *dindex, const iColorIndex *sindex)
{
const iColorIndex *_ipixel_dst_index = dindex;
const iColorIndex *_ipixel_src_index = sindex;
int flip, sbpp, dbpp, i, j;
int transparent;
flip = mode & (IPIXEL_FLIP_HFLIP | IPIXEL_FLIP_VFLIP);
transparent = (mode & IPIXEL_BLIT_MASK)? 1 : 0;
sbpp = ipixelfmt[sfmt].bpp;
dbpp = ipixelfmt[dfmt].bpp;
if (flip & IPIXEL_FLIP_VFLIP) {
sbits = (const IUINT8*)sbits + spitch * (h - 1);
spitch = -spitch;
}
for (j = 0; j < h; j++) {
IUINT32 cc = 0, r, g, b, a;
int incx, x1, x2 = dx;
if ((flip & IPIXEL_FLIP_HFLIP) == 0) x1 = sx, incx = 1;
else x1 = sx + w - 1, incx = -1;
for (i = w; i > 0; x1 += incx, x2++, i--) {
switch (sbpp) {
case 1: cc = _ipixel_fetch(1, sbits, x1); break;
case 4: cc = _ipixel_fetch(4, sbits, x1); break;
case 8: cc = _ipixel_fetch(8, sbits, x1); break;
case 16: cc = _ipixel_fetch(16, sbits, x1); break;
case 24: cc = _ipixel_fetch(24, sbits, x1); break;
case 32: cc = _ipixel_fetch(32, sbits, x1); break;
}
if (transparent && cc == mask)
continue;
IRGBA_DISEMBLE(sfmt, cc, r, g, b, a);
IRGBA_ASSEMBLE(dfmt, cc, r, g, b, a);
switch (dbpp) {
case 1: _ipixel_store(1, dbits, x2, cc); break;
case 4: _ipixel_store(4, dbits, x2, cc); break;
case 8: _ipixel_store(8, dbits, x2, cc); break;
case 16: _ipixel_store(16, dbits, x2, cc); break;
case 24: _ipixel_store(24, dbits, x2, cc); break;
case 32: _ipixel_store(32, dbits, x2, cc); break;
}
}
sbits = (const IUINT8*)sbits + spitch;
dbits = (IUINT8*)dbits + dpitch;
}
return 0;
}
/* ipixel_convert: convert pixel format
* you must provide a working memory pointer to mem. if mem eq NULL,
* this function will do nothing but returns how many bytes needed in mem
* dfmt - dest color format
* dbits - dest bits
* dpitch - dest pitch (row stride)
* dx - dest x offset
* sfmt - source color format
* sbits - source bits
* spitch - source pitch (row stride)
* sx - source x offset
* w - width
* h - height
* mask - mask color (colorkey), no effect without IPIXEL_BLIT_MASK
* mode - IPIXEL_FLIP_HFLIP | IPIXEL_FLIP_VFLIP | IPIXEL_BLIT_MASK ..
* didx - dest color index
* sidx - source color index
* mem - work memory
* for transparent converting, set mode with IPIXEL_BLIT_MASK, it will
* skip the colors equal to 'mask' parameter.
*/
long ipixel_convert(int dfmt, void *dbits, long dpitch, int dx, int sfmt,
const void *sbits, long spitch, int sx, int w, int h, IUINT32 mask,
int mode, const iColorIndex *didx, const iColorIndex *sidx, void *mem)
{
iPixelCvt cvt = NULL;
int flip, index;
if (mem == NULL) {
return w * sizeof(IUINT32);
}
if (ipixel_cvt_inited == 0) ipixel_cvt_init();
assert(dfmt >= 0 && dfmt < IPIX_FMT_COUNT);
assert(sfmt >= 0 && sfmt < IPIX_FMT_COUNT);
flip = mode & (IPIXEL_FLIP_HFLIP | IPIXEL_FLIP_VFLIP);
index = (mode & IPIXEL_BLIT_MASK)? 1 : 0;
if (didx == NULL) didx = _ipixel_dst_index;
if (sidx == NULL) sidx = _ipixel_src_index;
cvt = ipixel_cvt_table[dfmt][sfmt][index];
/* using converting procedure */
if (cvt != NULL) {
int retval = cvt(dbits, dpitch, dx, sbits, spitch, sx, w, h,
mask, flip, didx, sidx);
if (retval == 0) return 0;
}
/* using bliting procedure when no convertion needed */
if (sfmt == dfmt && ipixelfmt[sfmt].type != IPIX_FMT_TYPE_INDEX) {
ipixel_blit(ipixelfmt[sfmt].bpp, dbits, dpitch, dx, sbits,
spitch, sx, w, h, mask, mode);
return 0;
}
/* without transparent color key using ipixel_blend */
if ((mode & IPIXEL_BLIT_MASK) == 0) {
return ipixel_blend(dfmt, dbits, dpitch, dx, sfmt, sbits, spitch, sx,
w, h, 0xffffffff, IPIXEL_BLEND_OP_COPY, flip, didx, sidx, mem);
}
/* using ipixel_cvt_slow to proceed other convertion */
ipixel_cvt_slow(dfmt, dbits, dpitch, dx, sfmt, sbits, spitch, sx,
w, h, mask, mode, didx, sidx);
return 0;
}
/**********************************************************************
* CLIPING
**********************************************************************/
/*
* ipixel_clip - clip the rectangle from the src clip and dst clip then
* caculate a new rectangle which is shared between dst and src cliprect:
* clipdst - dest clip array (left, top, right, bottom)
* clipsrc - source clip array (left, top, right, bottom)
* (x, y) - dest position
* rectsrc - source rect
* mode - check IPIXEL_FLIP_HFLIP or IPIXEL_FLIP_VFLIP
* return zero for successful, return non-zero if there is no shared part
*/
int ipixel_clip(const int *clipdst, const int *clipsrc, int *x, int *y,
int *rectsrc, int mode)
{
int dcl = clipdst[0]; /* dest clip: left */
int dct = clipdst[1]; /* dest clip: top */
int dcr = clipdst[2]; /* dest clip: right */
int dcb = clipdst[3]; /* dest clip: bottom */
int scl = clipsrc[0]; /* source clip: left */
int sct = clipsrc[1]; /* source clip: top */
int scr = clipsrc[2]; /* source clip: right */
int scb = clipsrc[3]; /* source clip: bottom */
int dx = *x; /* dest x position */
int dy = *y; /* dest y position */
int sl = rectsrc[0]; /* source rectangle: left */
int st = rectsrc[1]; /* source rectangle: top */
int sr = rectsrc[2]; /* source rectangle: right */
int sb = rectsrc[3]; /* source rectangle: bottom */
int hflip, vflip;
int w, h, d;
hflip = (mode & IPIXEL_FLIP_HFLIP)? 1 : 0;
vflip = (mode & IPIXEL_FLIP_VFLIP)? 1 : 0;
if (dcr <= dcl || dcb <= dct || scr <= scl || scb <= sct)
return -1;
if (sr <= scl || sb <= sct || sl >= scr || st >= scb)
return -2;
/* check dest clip: left */
if (dx < dcl) {
d = dcl - dx;
dx = dcl;
if (!hflip) sl += d;
else sr -= d;
}
/* check dest clip: top */
if (dy < dct) {
d = dct - dy;
dy = dct;
if (!vflip) st += d;
else sb -= d;
}
w = sr - sl;
h = sb - st;
if (w < 0 || h < 0)
return -3;
/* check dest clip: right */
if (dx + w > dcr) {
d = dx + w - dcr;
if (!hflip) sr -= d;
else sl += d;
}
/* check dest clip: bottom */
if (dy + h > dcb) {
d = dy + h - dcb;
if (!vflip) sb -= d;
else st += d;
}
if (sl >= sr || st >= sb)
return -4;
/* check source clip: left */
if (sl < scl) {
d = scl - sl;
sl = scl;
if (!hflip) dx += d;
}
/* check source clip: top */
if (st < sct) {
d = sct - st;
st = sct;
if (!vflip) dy += d;
}
if (sl >= sr || st >= sb)
return -5;
/* check source clip: right */
if (sr > scr) {
d = sr - scr;
sr = scr;
if (hflip) dx += d;
}
/* check source clip: bottom */
if (sb > scb) {
d = sb - scb;
sb = scb;
if (vflip) dy += d;
}
if (sl >= sr || st >= sb)
return -6;
*x = dx;
*y = dy;
rectsrc[0] = sl;
rectsrc[1] = st;
rectsrc[2] = sr;
rectsrc[3] = sb;
return 0;
}
/**********************************************************************
* COMPOSITE
**********************************************************************/
static iPixelComposite ipixel_composite_table[40][2];
static int ipixel_composite_inited = 0;
static void ipixel_comp_src(IUINT32 *dst, const IUINT32 *src, int w)
{
memcpy(dst, src, w * sizeof(IUINT32));
}
static void ipixel_comp_dst(IUINT32 *dst, const IUINT32 *src, int w)
{
}
static void ipixel_comp_clear(IUINT32 *dst, const IUINT32 *src, int w)
{
memset(dst, 0, sizeof(IUINT32) * w);
}
static void ipixel_comp_blend(IUINT32 *dst, const IUINT32 *src, int w)
{
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2;
for (; w > 0; dst++, src++, w--) {
a1 = ((const IUINT8*)src)[_ipixel_card_alpha];
if (a1 == 0) continue;
else if (a1 == 255) dst[0] = src[0];
else {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
IBLEND_NORMAL_FAST(r1, g1, b1, a1, r2, g2, b2, a2);
dst[0] = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
}
static void ipixel_comp_add(IUINT32 *dst, const IUINT32 *src, int w)
{
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2;
for (; w > 0; dst++, src++, w--) {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
r2 = ICLIP_256(r1 + r2);
g2 = ICLIP_256(g1 + g2);
b2 = ICLIP_256(b1 + b2);
a2 = ICLIP_256(a1 + a2);
dst[0] = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
static void ipixel_comp_sub(IUINT32 *dst, const IUINT32 *src, int w)
{
IINT32 r1, g1, b1, a1, r2, g2, b2, a2;
for (; w > 0; dst++, src++, w--) {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
r2 = ICLIP_256(r2 - r1);
g2 = ICLIP_256(g2 - g1);
b2 = ICLIP_256(b2 - b1);
a2 = ICLIP_256(a2 - a1);
dst[0] = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
static void ipixel_comp_sub_inv(IUINT32 *dst, const IUINT32 *src, int w)
{
IINT32 r1, g1, b1, a1, r2, g2, b2, a2;
for (; w > 0; dst++, src++, w--) {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
r2 = ICLIP_256(r1 - r2);
g2 = ICLIP_256(g1 - g2);
b2 = ICLIP_256(b1 - b2);
a2 = ICLIP_256(a1 - a2);
dst[0] = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
#define IPIXEL_COMPOSITE_NORMAL(name, opname) \
static void ipixel_comp_##name(IUINT32 *dst, const IUINT32 *src, int w)\
{ \
IUINT32 sr, sg, sb, sa, dr, dg, db, da; \
for (; w > 0; dst++, src++, w--) { \
_ipixel_load_card(src, sr, sg, sb, sa); \
_ipixel_load_card(dst, dr, dg, db, da); \
sr = _ipixel_mullut[sa][sr]; \
sg = _ipixel_mullut[sa][sg]; \
sb = _ipixel_mullut[sa][sb]; \
dr = _ipixel_mullut[da][dr]; \
dg = _ipixel_mullut[da][dg]; \
db = _ipixel_mullut[da][db]; \
IBLEND_OP_##opname(sr, sg, sb, sa, dr, dg, db, da); \
dr = _ipixel_divlut[da][dr]; \
dg = _ipixel_divlut[da][dg]; \
db = _ipixel_divlut[da][db]; \
dst[0] = IRGBA_TO_A8R8G8B8(dr, dg, db, da); \
} \
}
#define IPIXEL_COMPOSITE_PREMUL(name, opname) \
static void ipixel_comp_##name(IUINT32 *dst, const IUINT32 *src, int w)\
{ \
IUINT32 sr, sg, sb, sa, dr, dg, db, da; \
for (; w > 0; dst++, src++, w--) { \
_ipixel_load_card(src, sr, sg, sb, sa); \
_ipixel_load_card(dst, dr, dg, db, da); \
IBLEND_OP_##opname(sr, sg, sb, sa, dr, dg, db, da); \
dst[0] = IRGBA_TO_A8R8G8B8(dr, dg, db, da); \
} \
}
IPIXEL_COMPOSITE_NORMAL(xor, XOR);
IPIXEL_COMPOSITE_NORMAL(plus, PLUS);
IPIXEL_COMPOSITE_NORMAL(src_atop, SRC_ATOP);
IPIXEL_COMPOSITE_NORMAL(src_in, SRC_IN);
IPIXEL_COMPOSITE_NORMAL(src_out, SRC_OUT);
IPIXEL_COMPOSITE_NORMAL(src_over, SRC_OVER);
IPIXEL_COMPOSITE_NORMAL(dst_atop, DST_ATOP);
IPIXEL_COMPOSITE_NORMAL(dst_in, DST_IN);
IPIXEL_COMPOSITE_NORMAL(dst_out, DST_OUT);
IPIXEL_COMPOSITE_NORMAL(dst_over, DST_OVER);
IPIXEL_COMPOSITE_PREMUL(pre_xor, XOR);
IPIXEL_COMPOSITE_PREMUL(pre_plus, PLUS);
IPIXEL_COMPOSITE_PREMUL(pre_src_atop, SRC_ATOP);
IPIXEL_COMPOSITE_PREMUL(pre_src_in, SRC_IN);
IPIXEL_COMPOSITE_PREMUL(pre_src_out, SRC_OUT);
IPIXEL_COMPOSITE_PREMUL(pre_src_over, SRC_OVER);
IPIXEL_COMPOSITE_PREMUL(pre_dst_atop, DST_ATOP);
IPIXEL_COMPOSITE_PREMUL(pre_dst_in, DST_IN);
IPIXEL_COMPOSITE_PREMUL(pre_dst_out, DST_OUT);
IPIXEL_COMPOSITE_PREMUL(pre_dst_over, DST_OVER);
#undef IPIXEL_COMPOSITE_NORMAL
#undef IPIXEL_COMPOSITE_PREMUL
static void ipixel_comp_preblend(IUINT32 *dst, const IUINT32 *src, int w)
{
IUINT32 c1, c2, a;
for (; w > 0; dst++, src++, w--) {
c1 = src[0];
a = src[0] >> 24;
if (a == 255) {
dst[0] = src[0];
}
else if (a > 0) {
c2 = dst[0];
IBLEND_PARGB(c2, c1);
dst[0] = c2;
}
}
}
static void ipixel_comp_allanon(IUINT32 *dst, const IUINT32 *src, int w)
{
IUINT32 c1, c2, c3, c4;
for (; w > 0; dst++, src++, w--) {
if ((src[0] >> 24) != 0) {
c1 = src[0] & 0x00ff00ff;
c2 = (src[0] >> 8) & 0x00ff00ff;
c3 = dst[0] & 0x00ff00ff;
c4 = (dst[0] >> 8) & 0x00ff00ff;
c1 = (c1 + c3) >> 1;
c2 = (c2 + c4) >> 1;
dst[0] = (c1 & 0x00ff00ff) | ((c2 & 0x00ff00ff) << 8);
}
}
}
static void ipixel_comp_tint(IUINT32 *dst, const IUINT32 *src, int w)
{
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2;
for (; w > 0; dst++, src++, w--) {
if ((src[0] >> 24) != 0) {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
r1 = r1 * r2;
g1 = g1 * g2;
b1 = b1 * b2;
r1 = _idiv_255(r1);
g1 = _idiv_255(g1);
b1 = _idiv_255(b1);
dst[0] = IRGBA_TO_A8R8G8B8(r1, g1, b1, a2);
}
}
}
static void ipixel_comp_diff(IUINT32 *dst, const IUINT32 *src, int w)
{
IINT32 r1, g1, b1, a1, r2, g2, b2, a2;
for (; w > 0; dst++, src++, w--) {
if ((src[0] >> 24) != 0) {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
r1 -= r2;
g1 -= g2;
b1 -= b2;
r2 = (r1 < 0)? -r1 : r1;
g2 = (g1 < 0)? -g1 : g1;
b2 = (b1 < 0)? -b1 : b1;
if (a1 > a2) a2 = a1;
dst[0] = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
}
static void ipixel_comp_darken(IUINT32 *dst, const IUINT32 *src, int w)
{
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2;
for (; w > 0; dst++, src++, w--) {
if ((src[0] >> 24) != 0) {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
if (a1 < a2) a2 = a1;
if (r1 < r2) r2 = r1;
if (g1 < g2) g2 = g1;
if (b1 < b2) b2 = b1;
dst[0] = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
}
static void ipixel_comp_lighten(IUINT32 *dst, const IUINT32 *src, int w)
{
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2;
for (; w > 0; dst++, src++, w--) {
if ((src[0] >> 24) != 0) {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
if (a1 > a2) a2 = a1;
if (r1 > r2) r2 = r1;
if (g1 > g2) g2 = g1;
if (b1 > b2) b2 = b1;
dst[0] = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
}
static void ipixel_comp_screen(IUINT32 *dst, const IUINT32 *src, int w)
{
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2, res1, res2;
for (; w > 0; dst++, src++, w--) {
if ((src[0] >> 24) != 0) {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
#define IPIXEL_SCREEN_VALUE(b, t) do { \
res1 = 0xFF - b; res2 = 0xff - t; \
res1 = 0xff - ((res1 * res2) >> 8); \
b = res1; } while (0)
IPIXEL_SCREEN_VALUE(r2, r1);
IPIXEL_SCREEN_VALUE(g2, g1);
IPIXEL_SCREEN_VALUE(b2, b1);
#undef IPIXEL_SCREEN_VALUE
if (a1 > a2) a2 = a1;
dst[0] = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
}
static void ipixel_comp_overlay(IUINT32 *dst, const IUINT32 *src, int w)
{
IUINT32 r1, g1, b1, a1, r2, g2, b2, a2, tmp_screen, tmp_mult, res;
for (; w > 0; dst++, src++, w--) {
if ((src[0] >> 24) != 0) {
_ipixel_load_card(src, r1, g1, b1, a1);
_ipixel_load_card(dst, r2, g2, b2, a2);
#define IPIXEL_OVERLAY_VALUE(b, t) do { \
tmp_screen = 0xff - (((0xff - (int)b) * (0xff - t)) >> 8); \
tmp_mult = (b * t) >> 8; \
res = (b * tmp_screen + (0xff - b) * tmp_mult) >> 8; \
b = res; \
} while (0)
IPIXEL_OVERLAY_VALUE(r2, r1);
IPIXEL_OVERLAY_VALUE(g2, g1);
IPIXEL_OVERLAY_VALUE(b2, b1);
#undef IPIXEL_OVERLAY_VALUE
if (a1 > a2) a2 = a1;
dst[0] = IRGBA_TO_A8R8G8B8(r2, g2, b2, a2);
}
}
}
/* initialize compositors */
static void ipixel_composite_init(void)
{
if (ipixel_composite_inited) return;
#define ipixel_composite_install(opname, name) do { \
ipixel_composite_table[IPIXEL_OP_##opname][0] = ipixel_comp_##name; \
ipixel_composite_table[IPIXEL_OP_##opname][1] = ipixel_comp_##name; \
} while (0)
ipixel_composite_install(SRC, src);
ipixel_composite_install(DST, dst);
ipixel_composite_install(CLEAR, clear);
ipixel_composite_install(BLEND, blend);
ipixel_composite_install(ADD, add);
ipixel_composite_install(SUB, sub);
ipixel_composite_install(SUB_INV, sub_inv);
ipixel_composite_install(XOR, xor);
ipixel_composite_install(PLUS, plus);
ipixel_composite_install(SRC_ATOP, src_atop);
ipixel_composite_install(SRC_IN, src_in);
ipixel_composite_install(SRC_OUT, src_out);
ipixel_composite_install(SRC_OVER, src_over);
ipixel_composite_install(DST_ATOP, dst_atop);
ipixel_composite_install(DST_IN, dst_in);
ipixel_composite_install(DST_OUT, dst_out);
ipixel_composite_install(DST_OVER, dst_over);
ipixel_composite_install(PREMUL_XOR, pre_xor);
ipixel_composite_install(PREMUL_PLUS, pre_plus);
ipixel_composite_install(PREMUL_SRC_ATOP, pre_src_atop);
ipixel_composite_install(PREMUL_SRC_IN, pre_src_in);
ipixel_composite_install(PREMUL_SRC_OUT, pre_src_out);
ipixel_composite_install(PREMUL_SRC_OVER, pre_src_over);
ipixel_composite_install(PREMUL_DST_ATOP, pre_dst_atop);
ipixel_composite_install(PREMUL_DST_IN, pre_dst_in);
ipixel_composite_install(PREMUL_DST_OUT, pre_dst_out);
ipixel_composite_install(PREMUL_DST_OVER, pre_dst_over);
ipixel_composite_install(PREMUL_BLEND, preblend);
ipixel_composite_install(ALLANON, allanon);
ipixel_composite_install(TINT, tint);
ipixel_composite_install(DIFF, diff);
ipixel_composite_install(DARKEN, darken);
ipixel_composite_install(LIGHTEN, lighten);
ipixel_composite_install(SCREEN, screen);
ipixel_composite_install(OVERLAY, overlay);
#undef ipixel_composite_install
ipixel_lut_init();
ipixel_composite_inited = 1;
}
/* get compositor */
iPixelComposite ipixel_composite_get(int op, int isdefault)
{
if (ipixel_composite_inited == 0) ipixel_composite_init();
if (op < 0 || op > IPIXEL_OP_OVERLAY) return NULL;
return ipixel_composite_table[op][isdefault ? 1 : 0];
}
/* set compositor */
void ipixel_composite_set(int op, iPixelComposite composite)
{
if (ipixel_composite_inited == 0) ipixel_composite_init();
if (op < 0 || op > IPIXEL_OP_OVERLAY) return;
if (composite == NULL) composite = ipixel_composite_table[op][1];
ipixel_composite_table[op][0] = composite;
}
/* composite operator names */
const char *ipixel_composite_opnames[] = {
"IPIXEL_OP_SRC",
"IPIXEL_OP_DST",
"IPIXEL_OP_CLEAR",
"IPIXEL_OP_BLEND",
"IPIXEL_OP_ADD",
"IPIXEL_OP_SUB",
"IPIXEL_OP_SUB_INV",
"IPIXEL_OP_XOR",
"IPIXEL_OP_PLUS",
"IPIXEL_OP_SRC_ATOP",
"IPIXEL_OP_SRC_IN",
"IPIXEL_OP_SRC_OUT",
"IPIXEL_OP_SRC_OVER",
"IPIXEL_OP_DST_ATOP",
"IPIXEL_OP_DST_IN",
"IPIXEL_OP_DST_OUT",
"IPIXEL_OP_DST_OVER",
"IPIXEL_OP_PREMUL_XOR",
"IPIXEL_OP_PREMUL_PLUS",
"IPIXEL_OP_PREMUL_SRC_OVER",
"IPIXEL_OP_PREMUL_SRC_IN",
"IPIXEL_OP_PREMUL_SRC_OUT",
"IPIXEL_OP_PREMUL_SRC_ATOP",
"IPIXEL_OP_PREMUL_DST_OVER",
"IPIXEL_OP_PREMUL_DST_IN",
"IPIXEL_OP_PREMUL_DST_OUT",
"IPIXEL_OP_PREMUL_DST_ATOP",
"IPIXEL_OP_PREMUL_BLEND",
"IPIXEL_OP_ALLANON",
"IPIXEL_OP_TINT",
"IPIXEL_OP_DIFF",
"IPIXEL_OP_DARKEN",
"IPIXEL_OP_LIGHTEN",
"IPIXEL_OP_SCREEN",
"IPIXEL_OP_OVERLAY",
};
/* get composite operator names */
const char *ipixel_composite_opname(int op)
{
if (op < 0 || op > IPIXEL_OP_OVERLAY) return "UNKNOW";
return ipixel_composite_opnames[op];
}
/**********************************************************************
* Palette
**********************************************************************/
/* fetch card from IPIX_FMT_C8 */
void ipixel_palette_fetch(const unsigned char *src, int w, IUINT32 *card,
const IRGB *palette)
{
IUINT32 r, g, b;
for (; w > 0; src++, card++, w--) {
r = palette[*src].r;
g = palette[*src].g;
b = palette[*src].b;
card[0] = IRGBA_TO_A8R8G8B8(r, g, b, 255);
}
}
/* store card into IPIX_FMT_C8 */
void ipixel_palette_store(unsigned char *dst, int w, const IUINT32 *card,
const IRGB *palette, int palsize)
{
IUINT32 r, g, b;
for (; w > 0; dst++, card++, w--) {
ISPLIT_RGB(card[0], r, g, b);
dst[0] = ibestfit_color(palette, r, g, b, palsize);
}
}
|
Beabel2/pixellib
|
pixellib/ibmbits.c
|
C
|
gpl-2.0
| 118,349 |
<?php
/**
* start.php
*
* This mod adds some javascript to thewire/all page on the elgg site. It works with the GCAPI mod to check if there are new wire posts and adds the new posts directly to the DOM through ajax
*
* @author Nick github.com/piet0024
* @author Ilia github.com/phanoix
**/
elgg_register_event_handler('init', 'system', 'gc_streaming_init');
function gc_streaming_init(){
elgg_require_js("stream_wire");
elgg_require_js("stream_newsfeed");
elgg_extend_view('css/elgg', 'css/css');
elgg_register_ajax_view('ajax/wire_posts');
elgg_register_ajax_view('ajax/newsfeed_items');
elgg_register_ajax_view('ajax/newsfeed_check');
elgg_register_page_handler('thewire', 'streaming_wire_page');
// live stream wire widget
elgg_register_widget_type('stream_wire_index',elgg_echo ('custom_index_widgets:stream_wire_index'),elgg_echo ('custom_index_widgets:stream_wire_index'), array("custom_index_widgets"), true);
if(elgg_is_logged_in()){
$newsfeed_title = elgg_echo('newsfeed:title');
}else{
$newsfeed_title = elgg_echo('newsfeed:titlenolog');
}
elgg_register_widget_type('stream_newsfeed_index', $newsfeed_title, elgg_echo ('custom_index_widgets:stream_newsfeed_index'), array("custom_index_widgets"), true);
}
function streaming_wire_page($page){
$base_dir = elgg_get_plugins_path() . 'thewire/pages/thewire';
//The wire/all page is overwritten in this theme
$stream_dir = elgg_get_plugins_path() .'gc_streaming_content/pages/thewire';
if (!isset($page[0])) {
$page = array('all');
}
switch ($page[0]) {
case "all":
include "$stream_dir/everyone.php";
break;
case "friends":
include "$base_dir/friends.php";
break;
case "owner":
include "$base_dir/owner.php";
break;
case "view":
if (isset($page[1])) {
set_input('guid', $page[1]);
}
include "$base_dir/view.php";
break;
case "thread":
if (isset($page[1])) {
set_input('thread_id', $page[1]);
}
include "$base_dir/thread.php";
break;
case "reply":
if (isset($page[1])) {
set_input('guid', $page[1]);
}
include "$base_dir/reply.php";
break;
case "tag":
if (isset($page[1])) {
set_input('tag', $page[1]);
}
include "$base_dir/tag.php";
break;
case "previous":
if (isset($page[1])) {
set_input('guid', $page[1]);
}
include "$base_dir/previous.php";
break;
default:
return false;
}
return true;
}
|
pscrevs/gcconnex
|
mod/gc_streaming_content/start.php
|
PHP
|
gpl-2.0
| 2,489 |
<?php
/**
* The WordPress version string
*
* @global string $wp_version
*/
$wp_version = '4.6';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.
*
* @global int $wp_db_version
*/
$wp_db_version = 37965;
/**
* Holds the TinyMCE version
*
* @global string $tinymce_version
*/
$tinymce_version = '4401-20160726';
/**
* Holds the required PHP version
*
* @global string $required_php_version
*/
$required_php_version = '5.2.4';
/**
* Holds the required MySQL version
*
* @global string $required_mysql_version
*/
$required_mysql_version = '5.0';
$wp_local_package = 'pt_BR';
|
israelcidade/futurus02
|
wp-includes/version.php
|
PHP
|
gpl-2.0
| 647 |
<?php
/**
* @version $Id: extension.php 18035 2010-07-06 08:04:10Z pasamio $
* @copyright Copyright (C) 2005 - 2010 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access
defined('JPATH_BASE') or die;
/**
* Extension object
*
* @package Joomla.Framework
* @subpackage Installer
* @since 1.6
*/
class JExtension extends JObject
{
/** @var string $filename Filename of the extension */
var $filename = '';
/** @var string $type Type of the extension */
var $type = '';
/** @var string $id Unique Identifier for the extension */
var $id = '';
/** @var boolean $published The status of the extension */
var $published = false; // published status
/** @var string $client String representation of client. Valid for modules, templates and languages */
var $client = 'site'; // valid for modules, templates and languages; set by default
/** @var string $group The group name of the plugin. Not used for other known extension types */
var $group = ''; // valid for plugins
/** @var Object $manifest_cache An object representation of the manifest file */
var $manifest_cache = null; // manifest cache; stored metadata
/** @var Object $params An object representation of the extension params */
var $params = null; // extension params
/**
* Constructor
* @param JXMLElement $element a JXMLElement from which to load data from
*/
function __construct(JXMLElement $element = null)
{
if ($element && is_a($element, 'JXMLElement'))
{
$this->type = (string)$element->attributes()->type;
$this->id = (string)$element->attributes()->id;
switch($this->type)
{
case 'component':
// by default a component doesn't have anything
break;
case 'module':
case 'template':
case 'language':
$this->client = (string)$element->attributes()->client;
$tmp_client_id = JApplicationHelper::getClientInfo($this->client, 1);
if($tmp_client_id == null) {
JError::raiseWarning(100, JText::_('JLIB_INSTALLER_ERROR_EXTENSION_INVALID_CLIENT_IDENTIFIER'));
} else {
$this->client_id = $tmp_client_id->id;
}
break;
case 'plugin':
$this->group = (string)$element->attributes()->group;
break;
default:
// catch all
// get and set client and group if we don't recognise the extension
if ($client = (string)$element->attributes()->client)
{
$this->client_id = JApplicationHelper::getClientInfo($this->client, 1);
$this->client_id = $this->client_id->id;
}
if ($group = (string)$element->attributes()->group) {
$this->group = (string)$element->attributes()->group;
}
break;
}
$this->filename = (string)$element;
}
}
}
|
dbxdnl/GitHub
|
libraries/joomla/installer/extension.php
|
PHP
|
gpl-2.0
| 2,776 |
<?php
/**
* Provides functionality for XML files
*
* This class is implemented to use the UTF-8 character encoding. Please see
* http://flourishlib.com/docs/UTF-8 for more information.
*
* @copyright Copyright (c) 2007-2011 Will Bond, others
* @author Will Bond [wb] <[email protected]>
* @author Craig Ruksznis [cr-imarc] <[email protected]>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fXML
*
* @version 1.0.0b8
* @changes 1.0.0b8 Fixed a method signature [wb, 2011-08-24]
* @changes 1.0.0b7 Added a workaround for iconv having issues in MAMP 1.9.4+ [wb, 2011-07-26]
* @changes 1.0.0b6 Updated class to use fCore::startErrorCapture() instead of `error_reporting()` [wb, 2010-08-09]
* @changes 1.0.0b5 Added the `$fix_entities_encoding` parameter to ::__construct() [cr-imarc+wb, 2010-08-08]
* @changes 1.0.0b4 Updated the class to automatically add a `__` prefix for the default namespace and to use that for attribute and child element access [wb, 2010-04-06]
* @changes 1.0.0b3 Added the `$http_timeout` parameter to ::__construct() [wb, 2009-09-16]
* @changes 1.0.0b2 Added instance functionality for reading of XML files [wb, 2009-09-01]
* @changes 1.0.0b The initial implementation [wb, 2008-01-13]
*/
class fXML implements ArrayAccess
{
// The following constants allow for nice looking callbacks to static methods
const encode = 'fXML::encode';
const sendHeader = 'fXML::sendHeader';
/**
* Encodes content for display in a UTF-8 encoded XML document
*
* @param string $content The content to encode
* @return string The encoded content
*/
static public function encode($content)
{
return htmlspecialchars(html_entity_decode($content, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
/**
* This works around a bug in MAMP 1.9.4+ and PHP 5.3 where iconv()
* does not seem to properly assign the return value to a variable, but
* does work when returning the value.
*
* @param string $in_charset The incoming character encoding
* @param string $out_charset The outgoing character encoding
* @param string $string The string to convert
* @return string The converted string
*/
static private function iconv($in_charset, $out_charset, $string)
{
return iconv($in_charset, $out_charset, $string);
}
/**
* Sets the proper `Content-Type` HTTP header for a UTF-8 XML file
*
* @return void
*/
static public function sendHeader()
{
header('Content-Type: text/xml; charset=utf-8');
}
/**
* Custom prefix => namespace URI mappings
*
* @var array
*/
protected $__custom_prefixes;
/**
* The dom element for this XML
*
* @var DOMElement
*/
protected $__dom;
/**
* An XPath object for performing xpath lookups
*
* @var DOMXPath
*/
protected $__xpath;
/**
* The XML string for serialization
*
* @var string
*/
protected $__xml;
/**
* Create the XML object from a string, fFile or URL
*
* The `$default_namespace` will be used for any sort of methods calls,
* member access or array access when the element or attribute name does
* not include a `:`.
*
* @throws fValidationException When the source XML is invalid or does not exist
*
* @param fFile|string $source The source of the XML, either an fFile object, a string of XML, a file path or a URL
* @param numeric $http_timeout The timeout to use in seconds when requesting an XML file from a URL
* @param boolean $fix_entities_encoding This will fix two common XML authoring errors and should only be used when experiencing decoding issues - HTML entities that haven't been encoded as XML, and XML content published in ISO-8859-1 or Windows-1252 encoding without an explicit encoding attribute
* @param fFile|string |$source
* @param boolean |$fix_entities_encoding
* @return fXML
*/
public function __construct($source, $http_timeout=NULL, $fix_entities_encoding=NULL)
{
if (is_bool($http_timeout)) {
$fix_entities_encoding = $http_timeout;
$http_timeout = NULL;
}
// Prevent spitting out errors to we can throw exceptions
$old_setting = libxml_use_internal_errors(TRUE);
$exception_message = NULL;
try {
if ($source instanceof fFile && $fix_entities_encoding) {
$source = $source->read();
}
if ($source instanceof DOMElement) {
$this->__dom = $source;
$xml = TRUE;
} elseif ($source instanceof fFile) {
$xml = simplexml_load_file($source->getPath());
// This handles URLs specially by adding a reasonable timeout
} elseif (preg_match('#^(?P<protocol>http(s)?)://#', $source, $matches)) {
if ($http_timeout === NULL) {
$http_timeout = ini_get('default_socket_timeout');
}
// We use the appropriate protocol here so PHP can supress IIS https:// warnings
$context = stream_context_create(array(
$matches['protocol'] => array('timeout' => $http_timeout)
));
// If the URL is not loaded in time, this supresses the file_get_contents() warning
fCore::startErrorCapture(E_WARNING);
$xml = file_get_contents($source, 0, $context);
fCore::stopErrorCapture();
if (!$xml) {
throw new fExpectedException('The URL specified, %s, could not be loaded', $source);
}
if ($fix_entities_encoding) {
$xml = $this->fixEntitiesEncoding($xml);
}
$xml = new SimpleXMLElement($xml);
} else {
$is_path = $source && !preg_match('#^\s*<#', $source);
if ($fix_entities_encoding) {
if ($is_path) {
$source = file_get_contents($source);
$is_path = FALSE;
}
$source = $this->fixEntitiesEncoding($source);
}
$xml = new SimpleXMLElement($source, 0, $is_path);
}
} catch (Exception $e) {
$exception_message = $e->getMessage();
$xml = FALSE;
}
// We want it to be clear when XML parsing issues occur
if ($xml === FALSE) {
$errors = libxml_get_errors();
foreach ($errors as $error) {
$exception_message .= "\n" . rtrim($error->message);
}
// If internal errors were off before, turn them back off
if (!$old_setting) {
libxml_use_internal_errors(FALSE);
}
throw new fValidationException(str_replace('%', '%%', $exception_message));
}
if (!$old_setting) {
libxml_use_internal_errors(FALSE);
}
if (!$this->__dom) {
$this->__dom = dom_import_simplexml($xml);
}
if ($this->__dom->namespaceURI && $this->__dom->prefix == '') {
$this->addCustomPrefix('__', $this->__dom->namespaceURI);
}
}
/**
* Allows access to the text content of a child tag
*
* The child element name (`$name`) may start with a namespace prefix and a
* `:` to indicate what namespace it is part of. A blank namespace prefix
* (i.e. an element name starting with `:`) is treated as the XML default
* namespace.
*
* @internal
*
* @param string $name The child element to retrieve
* @return fXML|NULL The child element requested
*/
public function __get($name)
{
// Handle nice callback syntax
static $methods = array(
'__construct' => TRUE,
'__get' => TRUE,
'__isset' => TRUE,
'__sleep' => TRUE,
'__toString' => TRUE,
'__wakeup' => TRUE,
'addCustomPrefix' => TRUE,
'getName' => TRUE,
'getNamespace' => TRUE,
'getPrefix' => TRUE,
'getText' => TRUE,
'offsetExists' => TRUE,
'offsetGet' => TRUE,
'offsetSet' => TRUE,
'offsetUnset' => TRUE,
'toXML' => TRUE,
'xpath' => TRUE
);
if (isset($methods[$name])) {
return array($this, $name);
}
if ($this->__dom->namespaceURI && $this->__dom->prefix == '' && strpos($name, ':') === FALSE) {
$name = '__:' . $name;
}
$first_child = $this->query($name . '[1]');
if ($first_child->length) {
return $first_child->item(0)->textContent;
}
return NULL;
}
/**
* The child element name (`$name`) may start with a namespace prefix and a
* `:` to indicate what namespace it is part of. A blank namespace prefix
* (i.e. an element name starting with `:`) is treated as the XML default
* namespace.
*
* @internal
*
* @param string $name The child element to check - see method description for details about namespaces
* @return boolean If the child element is set
*/
public function __isset($name)
{
if ($this->__dom->namespaceURI && $this->__dom->prefix == '' && strpos($name, ':') === FALSE) {
$name = '__:' . $name;
}
return (boolean) $this->query($name . '[1]')->length;
}
/**
* Prevents users from trying to set elements
*
* @internal
*
* @param string $name The element to set
* @param mixed $value The value to set
* @return void
*/
public function __set($name, $value)
{
throw new fProgrammerException('The %s class does not support modifying XML', __CLASS__);
}
/**
* The XML needs to be made into a string before being serialized
*
* @internal
*
* @return array The members to serialize
*/
public function __sleep()
{
$this->__xml = $this->toXML();
return array('__custom_prefixes', '__xml');
}
/**
* Gets the string inside the root XML element
*
* @return string The text inside the root element
*/
public function __toString()
{
return (string) $this->__dom->textContent;
}
/**
* Prevents users from trying to unset elements
*
* @internal
*
* @param string $name The element to unset
* @return void
*/
public function __unset($name)
{
throw new fProgrammerException('The %s class does not support modifying XML', __CLASS__);
}
/**
* The XML needs to be made into a DOMElement when woken up
*
* @internal
*
* @return void
*/
public function __wakeup()
{
$this->__dom = dom_import_simplexml(new SimpleXMLElement($this->__xml));
$this->__xml = NULL;
}
/**
* Adds a custom namespace prefix to full namespace mapping
*
* This namespace prefix will be valid for any operation on this object,
* including calls to ::xpath().
*
* @param string $ns_prefix The custom namespace prefix
* @param string $namespace The full namespace it maps to
* @return void
*/
public function addCustomPrefix($ns_prefix, $namespace)
{
if (!$this->__custom_prefixes) {
$this->__custom_prefixes = array();
}
$this->__custom_prefixes[$ns_prefix] = $namespace;
if ($this->__xpath) {
$this->__xpath->registerNamespace($ns_prefix, $namespace);
}
}
/**
* Fixes HTML entities that aren't XML encoded and fixes ISO-8859-1/Windows-1252 encoded content that does not have an encoding attribute
*
* @param string $xml The XML to fix
* @return string The fixed XML
*/
private function fixEntitiesEncoding($xml)
{
preg_match('#^<\?xml.*? encoding="([^"]+)".*?\?>#i', $xml, $match);
$encoding = empty($match[1]) ? NULL : $match[1];
// Try to detect the encoding via the BOM
if ($encoding === NULL) {
if (substr($xml, 0, 3) == "\x0\x0\xFE\xFF") {
$encoding = 'UTF-32BE';
} elseif (substr($xml, 0, 3) == "\xFF\xFE\x0\x0") {
$encoding = 'UTF-32LE';
} elseif (substr($xml, 0, 2) == "\xFE\xFF") {
$encoding = 'UTF-16BE';
} elseif (substr($xml, 0, 2) == "\xFF\xFE") {
$encoding = 'UTF-16LE';
} else {
$encoding = 'UTF-8';
}
}
// This fixes broken encodings where the XML author puts ISO-8859-1 or
// Windows-1252 into an XML file without an encoding or UTF-8 encoding
if (preg_replace('#[^a-z0-9]#', '', strtolower($encoding)) == 'utf8') {
// Remove the UTF-8 BOM if present
$xml = preg_replace("#^\xEF\xBB\xBF#", '', $xml);
fCore::startErrorCapture(E_NOTICE);
$cleaned = self::iconv('UTF-8', 'UTF-8', $xml);
if ($cleaned != $xml) {
$xml = self::iconv('Windows-1252', 'UTF-8', $xml);
}
fCore::stopErrorCapture();
}
$num_matches = preg_match_all('#&(?!gt|lt|amp|quot|apos)\w+;#', $xml, $matches, PREG_SET_ORDER);
if ($num_matches) {
// We convert non-UTF-* content to UTF-8 because some character sets
// don't have characters for all HTML entities
if (substr(strtolower($encoding), 0, 3) != 'utf') {
$xml = self::iconv($encoding, 'UTF-8', $xml);
$xml = preg_replace('#^(<\?xml.*?) encoding="[^"]+"(.*?\?>)#', '\1 encoding="UTF-8"\2', $xml);
$encoding = 'UTF-8';
}
$entities = array();
foreach ($matches as $match) {
$entities[$match[0]] = html_entity_decode($match[0], ENT_COMPAT, $encoding);
}
$xml = strtr($xml, $entities);
}
return $xml;
}
/**
* Returns the name of the current element
*
* @return string The name of the current element
*/
public function getName()
{
return $this->__dom->localName;
}
/**
* Returns the namespace of the current element
*
* @return string The namespace of the current element
*/
public function getNamespace()
{
return $this->__dom->namespaceURI;
}
/**
* Returns the namespace prefix of the current element
*
* @return string The namespace prefix of the current element
*/
public function getPrefix()
{
return $this->__dom->prefix;
}
/**
* Returns the string text of the current element
*
* @return string The string text of the current element
*/
public function getText()
{
return (string) $this->__dom->textContent;
}
/**
* Provides functionality for isset() and empty() (required by arrayaccess interface)
*
* Offsets refers to an attribute name. Attribute may start with a namespace
* prefix and a `:` to indicate what namespace the attribute is part of. A
* blank namespace prefix (i.e. an offset starting with `:`) is treated as
* the XML default namespace.
*
* @internal
*
* @param string $offset The offset to check
* @return boolean If the offset exists
*/
public function offsetExists($offset)
{
return (boolean) $this->query('@' . $offset . '[1]')->length;
}
/**
* Provides functionality for get [index] syntax (required by ArrayAccess interface)
*
* Offsets refers to an attribute name. Attribute may start with a namespace
* prefix and a `:` to indicate what namespace the attribute is part of. A
* blank namespace prefix (i.e. an offset starting with `:`) is treated as
* the XML default namespace.
*
* @internal
*
* @param string $offset The attribute to retrieve the value for
* @return string The value of the offset
*/
public function offsetGet($offset)
{
$attribute = $this->query('@' . $offset . '[1]');
if ($attribute->length) {
return $attribute->item(0)->nodeValue;
}
return NULL;
}
/**
* Required by ArrayAccess interface
*
* @internal
*
* @param integer|string $offset The offset to set
* @return void
*/
public function offsetSet($offset, $value)
{
throw new fProgrammerException('The %s class does not support modifying XML', __CLASS__);
}
/**
* Required by ArrayAccess interface
*
* @internal
*
* @param integer|string $offset The offset to unset
* @return void
*/
public function offsetUnset($offset)
{
throw new fProgrammerException('The %s class does not support modifying XML', __CLASS__);
}
/**
* Performs an XPath query on the current element, returning the raw results
*
* @param string $path The XPath path to query
* @return array The matching elements
*/
protected function query($path)
{
if (!$this->__xpath) {
$this->__xpath = new DOMXPath($this->__dom->ownerDocument);
if ($this->__custom_prefixes) {
foreach ($this->__custom_prefixes as $prefix => $namespace) {
$this->__xpath->registerNamespace($prefix, $namespace);
}
}
}
// Prevent spitting out errors to we can throw exceptions
$old_setting = libxml_use_internal_errors(TRUE);
$result = $this->__xpath->query($path, $this->__dom);
// We want it to be clear when XML parsing issues occur
if ($result === FALSE) {
$errors = libxml_get_errors();
$exception_message = '';
foreach ($errors as $error) {
$exception_message .= "\n" . $error->message;
}
// If internal errors were off before, turn them back off
if (!$old_setting) {
libxml_use_internal_errors(FALSE);
}
throw new fProgrammerException(str_replace('%', '%%', trim($exception_message)));
}
if (!$old_setting) {
libxml_use_internal_errors(FALSE);
}
return $result;
}
/**
* Returns a well-formed XML string from the current element
*
* @return string The XML
*/
public function toXML()
{
return $this->__dom->ownerDocument->saveXML($this->__dom->parentNode === $this->__dom->ownerDocument ? $this->__dom->parentNode : $this->__dom);
}
/**
* Executes an XPath query on the current element, returning an array of matching elements
*
* @param string $path The XPath path to query
* @param boolean $first_only If only the first match should be returned
* @return array|string|fXML An array of matching elements, or a string or fXML object if `$first_only` is `TRUE`
*/
public function xpath($path, $first_only=FALSE)
{
$result = $this->query($path);
if ($first_only) {
if (!$result->length) { return NULL; }
$result = array($result->item(0));
} else {
if (!$result->length) { return array(); }
}
$keys_to_remove = array();
$output = array();
foreach ($result as $element) {
if ($element instanceof DOMElement) {
$child = new fXML($element);
$child->__custom_prefixes = $this->__custom_prefixes;
if ($child->__dom->namespaceURI && $child->__dom->prefix == '') {
$child->addCustomPrefix('__', $child->__dom->namespaceURI);
}
$output[] = $child;
} elseif ($element instanceof DOMCharacterData) {
$output[] = $element->data;
} elseif ($element instanceof DOMAttr) {
$key = $element->name;
if ($element->prefix) {
$key = $element->prefix . ':' . $key;
}
// We will create an attrname and attrname[0] key for each
// attribute and if more than one is found we remove the
// key attrname. If only one is found we remove attrname[0].
$key_1 = $key . '[1]';
if (isset($output[$key_1])) {
$i = 1;
while (isset($output[$key . '[' . $i . ']'])) {
$i++;
}
// This removes the key without the array index if more than one was found
unset($output[$key]);
unset($keys_to_remove[$key_1]);
$key = $key . '[' . $i . ']';
} else {
$output[$key_1] = $element->nodeValue;
$keys_to_remove[$key_1] = TRUE;
}
$output[$key] = $element->nodeValue;
}
}
foreach ($keys_to_remove as $key => $trash) {
unset($output[$key]);
}
if ($first_only) {
return current($output);
}
return $output;
}
}
/**
* Copyright (c) 2007-2011 Will Bond <[email protected]>, others
*
* 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.
*/
|
pmanterys/wp-mw-newsletter
|
wp-content/plugins/wp-testing/vendor/flourish/flourish/fXML.php
|
PHP
|
gpl-2.0
| 19,923 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>CmdMessenger: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">CmdMessenger
 <span id="projectnumber">3.0</span>
</div>
<div id="projectbrief">CmdMessenger is a serial port messaging library for the Arduino</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.5 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespace_send_and_receive_arguments.html">SendAndReceiveArguments</a></li><li class="navelem"><a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">SendAndReceiveArguments.SendAndReceiveArguments Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments.SendAndReceiveArguments</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Exit</b>() (defined in <a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments.SendAndReceiveArguments</a>)</td><td class="entry"><a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments.SendAndReceiveArguments</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>Loop</b>() (defined in <a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments.SendAndReceiveArguments</a>)</td><td class="entry"><a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments.SendAndReceiveArguments</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>RunLoop</b> (defined in <a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments.SendAndReceiveArguments</a>)</td><td class="entry"><a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments.SendAndReceiveArguments</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>Setup</b>() (defined in <a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments.SendAndReceiveArguments</a>)</td><td class="entry"><a class="el" href="class_send_and_receive_arguments_1_1_send_and_receive_arguments.html">SendAndReceiveArguments.SendAndReceiveArguments</a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Sep 4 2013 21:46:38 for CmdMessenger by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.5
</small></address>
</body>
</html>
|
jgrizou/robot_2WD
|
arduino/libraries/CmdMessenger/Documentation/Arduino/html/class_send_and_receive_arguments_1_1_send_and_receive_arguments-members.html
|
HTML
|
gpl-2.0
| 4,789 |
/*
* Copyright (C) 2012, Samsung Electronics Co. Ltd. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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.
*
*/
#include "ssp.h"
/*************************************************************************/
/* factory Sysfs */
/*************************************************************************/
#define VENDOR "INVENSENSE"
#define CHIP_ID "MPU6500"
#define CALIBRATION_FILE_PATH "/efs/FactoryApp/calibration_data"
#define CALIBRATION_DATA_AMOUNT 20
#define MAX_ACCEL_1G 8192
#define MAX_ACCEL_2G 16384
#define MIN_ACCEL_2G -16383
#define MAX_ACCEL_4G 32768
static ssize_t accel_vendor_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", VENDOR);
}
static ssize_t accel_name_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", CHIP_ID);
}
int accel_open_calibration(struct ssp_data *data)
{
int iRet = 0;
mm_segment_t old_fs;
struct file *cal_filp = NULL;
old_fs = get_fs();
set_fs(KERNEL_DS);
cal_filp = filp_open(CALIBRATION_FILE_PATH, O_RDONLY, 0666);
if (IS_ERR(cal_filp)) {
set_fs(old_fs);
iRet = PTR_ERR(cal_filp);
data->accelcal.x = 0;
data->accelcal.y = 0;
data->accelcal.z = 0;
return iRet;
}
iRet = cal_filp->f_op->read(cal_filp, (char *)&data->accelcal,
3 * sizeof(int), &cal_filp->f_pos);
if (iRet != 3 * sizeof(int))
iRet = -EIO;
filp_close(cal_filp, current->files);
set_fs(old_fs);
ssp_dbg("[SSP]: open accel calibration %d, %d, %d\n",
data->accelcal.x, data->accelcal.y, data->accelcal.z);
if ((data->accelcal.x == 0) && (data->accelcal.y == 0)
&& (data->accelcal.z == 0))
return ERROR;
return iRet;
}
int set_accel_cal(struct ssp_data *data)
{
int iRet = 0;
struct ssp_msg *msg;
s16 accel_cal[3];
if (!(data->uSensorState & (1 << ACCELEROMETER_SENSOR))) {
pr_info("[SSP]: %s - Skip this function!!!"\
", accel sensor is not connected(0x%x)\n",
__func__, data->uSensorState);
return iRet;
}
accel_cal[0] = data->accelcal.x;
accel_cal[1] = data->accelcal.y;
accel_cal[2] = data->accelcal.z;
msg = kzalloc(sizeof(*msg), GFP_KERNEL);
if (msg == NULL) {
pr_err("[SSP] %s, failed to alloc memory for ssp_msg\n", __func__);
return -ENOMEM;
}
msg->cmd = MSG2SSP_AP_MCU_SET_ACCEL_CAL;
msg->length = 6;
msg->options = AP2HUB_WRITE;
msg->buffer = (char*) kzalloc(6, GFP_KERNEL);
msg->free_buffer = 1;
memcpy(msg->buffer, accel_cal, 6);
iRet = ssp_spi_async(data, msg);
if (iRet != SUCCESS) {
pr_err("[SSP]: %s - i2c fail %d\n", __func__, iRet);
iRet = ERROR;
}
pr_info("[SSP] Set accel cal data %d, %d, %d\n", accel_cal[0], accel_cal[1], accel_cal[2]);
return iRet;
}
static int enable_accel_for_cal(struct ssp_data *data)
{
u8 uBuf[4] = { 0, };
s32 dMsDelay = get_msdelay(data->adDelayBuf[ACCELEROMETER_SENSOR]);
memcpy(&uBuf[0], &dMsDelay, 4);
if (atomic_read(&data->aSensorEnable) & (1 << ACCELEROMETER_SENSOR)) {
if (get_msdelay(data->adDelayBuf[ACCELEROMETER_SENSOR]) != 10) {
send_instruction(data, CHANGE_DELAY,
ACCELEROMETER_SENSOR, uBuf, 4);
return SUCCESS;
}
} else {
send_instruction(data, ADD_SENSOR,
ACCELEROMETER_SENSOR, uBuf, 4);
}
return FAIL;
}
static void disable_accel_for_cal(struct ssp_data *data, int iDelayChanged)
{
u8 uBuf[4] = { 0, };
s32 dMsDelay = get_msdelay(data->adDelayBuf[ACCELEROMETER_SENSOR]);
memcpy(&uBuf[0], &dMsDelay, 4);
if (atomic_read(&data->aSensorEnable) & (1 << ACCELEROMETER_SENSOR)) {
if (iDelayChanged)
send_instruction(data, CHANGE_DELAY,
ACCELEROMETER_SENSOR, uBuf, 4);
} else {
send_instruction(data, REMOVE_SENSOR,
ACCELEROMETER_SENSOR, uBuf, 4);
}
}
static int accel_do_calibrate(struct ssp_data *data, int iEnable)
{
int iSum[3] = { 0, };
int iRet = 0, iCount;
struct file *cal_filp = NULL;
mm_segment_t old_fs;
if (iEnable) {
data->accelcal.x = 0;
data->accelcal.y = 0;
data->accelcal.z = 0;
set_accel_cal(data);
iRet = enable_accel_for_cal(data);
msleep(300);
for (iCount = 0; iCount < CALIBRATION_DATA_AMOUNT; iCount++) {
iSum[0] += data->buf[ACCELEROMETER_SENSOR].x;
iSum[1] += data->buf[ACCELEROMETER_SENSOR].y;
iSum[2] += data->buf[ACCELEROMETER_SENSOR].z;
mdelay(10);
}
disable_accel_for_cal(data, iRet);
data->accelcal.x = (iSum[0] / CALIBRATION_DATA_AMOUNT);
data->accelcal.y = (iSum[1] / CALIBRATION_DATA_AMOUNT);
data->accelcal.z = (iSum[2] / CALIBRATION_DATA_AMOUNT);
if (data->accelcal.z > 0)
data->accelcal.z -= MAX_ACCEL_1G;
else if (data->accelcal.z < 0)
data->accelcal.z += MAX_ACCEL_1G;
} else {
data->accelcal.x = 0;
data->accelcal.y = 0;
data->accelcal.z = 0;
}
ssp_dbg("[SSP]: do accel calibrate %d, %d, %d\n",
data->accelcal.x, data->accelcal.y, data->accelcal.z);
old_fs = get_fs();
set_fs(KERNEL_DS);
cal_filp = filp_open(CALIBRATION_FILE_PATH,
O_CREAT | O_TRUNC | O_WRONLY, 0666);
if (IS_ERR(cal_filp)) {
pr_err("[SSP]: %s - Can't open calibration file\n", __func__);
set_fs(old_fs);
iRet = PTR_ERR(cal_filp);
return iRet;
}
iRet = cal_filp->f_op->write(cal_filp, (char *)&data->accelcal,
3 * sizeof(int), &cal_filp->f_pos);
if (iRet != 3 * sizeof(int)) {
pr_err("[SSP]: %s - Can't write the accelcal to file\n",
__func__);
iRet = -EIO;
}
filp_close(cal_filp, current->files);
set_fs(old_fs);
set_accel_cal(data);
return iRet;
}
static ssize_t accel_calibration_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int iRet;
int iCount = 0;
struct ssp_data *data = dev_get_drvdata(dev);
iRet = accel_open_calibration(data);
if (iRet < 0)
pr_err("[SSP]: %s - calibration open failed(%d)\n", __func__, iRet);
ssp_dbg("[SSP] Cal data : %d %d %d - %d\n",
data->accelcal.x, data->accelcal.y, data->accelcal.z, iRet);
iCount = sprintf(buf, "%d %d %d %d\n", iRet, data->accelcal.x,
data->accelcal.y, data->accelcal.z);
return iCount;
}
static ssize_t accel_calibration_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
int iRet;
int64_t dEnable;
struct ssp_data *data = dev_get_drvdata(dev);
iRet = kstrtoll(buf, 10, &dEnable);
if (iRet < 0)
return iRet;
iRet = accel_do_calibrate(data, (int)dEnable);
if (iRet < 0)
pr_err("[SSP]: %s - accel_do_calibrate() failed\n", __func__);
return size;
}
static ssize_t raw_data_read(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ssp_data *data = dev_get_drvdata(dev);
return snprintf(buf, PAGE_SIZE, "%d,%d,%d\n",
data->buf[ACCELEROMETER_SENSOR].x,
data->buf[ACCELEROMETER_SENSOR].y,
data->buf[ACCELEROMETER_SENSOR].z);
}
static ssize_t accel_reactive_alert_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
int iRet = 0;
char chTempBuf = 1;
struct ssp_data *data = dev_get_drvdata(dev);
struct ssp_msg *msg;
if (sysfs_streq(buf, "1"))
ssp_dbg("[SSP]: %s - on\n", __func__);
else if (sysfs_streq(buf, "0"))
ssp_dbg("[SSP]: %s - off\n", __func__);
else if (sysfs_streq(buf, "2")) {
ssp_dbg("[SSP]: %s - factory\n", __func__);
data->bAccelAlert = 0;
msg = kzalloc(sizeof(*msg), GFP_KERNEL);
if (msg == NULL) {
pr_err("[SSP] %s, failed to alloc memory for ssp_msg\n", __func__);
return -ENOMEM;
}
msg->cmd = ACCELEROMETER_FACTORY;
msg->length = 1;
msg->options = AP2HUB_READ;
msg->data = chTempBuf;
msg->buffer = &chTempBuf;
msg->free_buffer = 0;
iRet = ssp_spi_sync(data, msg, 3000);
data->bAccelAlert = chTempBuf;
if (iRet != SUCCESS) {
pr_err("[SSP]: %s - accel Selftest Timeout!!\n", __func__);
goto exit;
}
ssp_dbg("[SSP]: %s factory test success!\n", __func__);
} else {
pr_err("[SSP]: %s - invalid value %d\n", __func__, *buf);
return -EINVAL;
}
exit:
return size;
}
static ssize_t accel_reactive_alert_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
bool bSuccess = false;
struct ssp_data *data = dev_get_drvdata(dev);
if (data->bAccelAlert == true)
bSuccess = true;
else
bSuccess = false;
data->bAccelAlert = false;
return sprintf(buf, "%u\n", bSuccess);
}
static ssize_t accel_hw_selftest_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
char chTempBuf[8] = { 2, 0, };
s8 init_status = 0, result = -1;
s16 shift_ratio[3] = { 0, };
int iRet;
struct ssp_data *data = dev_get_drvdata(dev);
struct ssp_msg *msg;
msg = kzalloc(sizeof(*msg), GFP_KERNEL);
if (msg == NULL) {
pr_err("[SSP] %s, failed to alloc memory for ssp_msg\n", __func__);
goto exit;
}
msg->cmd = ACCELEROMETER_FACTORY;
msg->length = 8;
msg->options = AP2HUB_READ;
msg->data = chTempBuf[0];
msg->buffer = chTempBuf;
msg->free_buffer = 0;
iRet = ssp_spi_sync(data, msg, 7000);
if (iRet != SUCCESS) {
pr_err("[SSP] %s - accel hw selftest Timeout!!\n", __func__);
goto exit;
}
init_status = chTempBuf[0];
shift_ratio[0] = (s16)((chTempBuf[2] << 8) + chTempBuf[1]);
shift_ratio[1] = (s16)((chTempBuf[4] << 8) + chTempBuf[3]);
shift_ratio[2] = (s16)((chTempBuf[6] << 8) + chTempBuf[5]);
result = chTempBuf[7];
pr_info("[SSP] %s - %d, %d, %d, %d, %d\n", __func__,
init_status, result, shift_ratio[0], shift_ratio[1], shift_ratio[2]);
return sprintf(buf, "%d,%d.%d,%d.%d,%d.%d\n", result,
shift_ratio[0] / 10, shift_ratio[0] % 10,
shift_ratio[1] / 10, shift_ratio[1] % 10,
shift_ratio[2] / 10, shift_ratio[2] % 10);
exit:
return sprintf(buf, "%d,%d,%d,%d\n", -5, 0, 0, 0);
}
static ssize_t accel_lowpassfilter_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
int iRet = 0, new_enable = 1;
struct ssp_data *data = dev_get_drvdata(dev);
struct ssp_msg *msg = kzalloc(sizeof(*msg), GFP_KERNEL);
if (msg == NULL) {
pr_err("[SSP] %s, failed to alloc memory\n", __func__);
goto exit;
}
if (sysfs_streq(buf, "1"))
new_enable = 1;
else if (sysfs_streq(buf, "0"))
new_enable = 0;
else
ssp_dbg("[SSP]: %s - invalid value!\n", __func__);
msg->cmd = MSG2SSP_AP_SENSOR_LPF;
msg->length = 1;
msg->options = AP2HUB_WRITE;
msg->buffer = (char*) kzalloc(1, GFP_KERNEL);
if (msg->buffer == NULL) {
pr_err("[SSP] %s, failed to alloc memory\n", __func__);
kfree(msg);
goto exit;
}
*msg->buffer = new_enable;
msg->free_buffer = 1;
iRet = ssp_spi_async(data, msg);
if (iRet != SUCCESS)
pr_err("[SSP] %s - fail %d\n", __func__, iRet);
else
pr_info("[SSP] %s - %d\n", __func__, new_enable);
exit:
return size;
}
static DEVICE_ATTR(name, S_IRUGO, accel_name_show, NULL);
static DEVICE_ATTR(vendor, S_IRUGO, accel_vendor_show, NULL);
static DEVICE_ATTR(calibration, S_IRUGO | S_IWUSR | S_IWGRP,
accel_calibration_show, accel_calibration_store);
static DEVICE_ATTR(raw_data, S_IRUGO, raw_data_read, NULL);
static DEVICE_ATTR(reactive_alert, S_IRUGO | S_IWUSR | S_IWGRP,
accel_reactive_alert_show, accel_reactive_alert_store);
static DEVICE_ATTR(selftest, S_IRUGO, accel_hw_selftest_show, NULL);
static DEVICE_ATTR(lowpassfilter, S_IWUSR | S_IWGRP,
NULL, accel_lowpassfilter_store);
static struct device_attribute *acc_attrs[] = {
&dev_attr_name,
&dev_attr_vendor,
&dev_attr_calibration,
&dev_attr_raw_data,
&dev_attr_reactive_alert,
&dev_attr_selftest,
&dev_attr_lowpassfilter,
NULL,
};
void initialize_accel_factorytest(struct ssp_data *data)
{
sensors_register(data->acc_device, data, acc_attrs,
"accelerometer_sensor");
}
void remove_accel_factorytest(struct ssp_data *data)
{
sensors_unregister(data->acc_device, acc_attrs);
}
|
mythos234/cmkernel_zeroltexx
|
drivers/sensorhub/brcm/accel_mpu6500.c
|
C
|
gpl-2.0
| 12,034 |
# -*- coding: utf-8 -*-
#
# Copyright 2009 Mozilla Corporation, Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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.
#
# translate 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/>.
"""Convert PHP format .po files to Python format .po files.
"""
import re
from translate.misc.multistring import multistring
from translate.storage import po
class phppo2pypo:
def convertstore(self, inputstore):
"""Converts a given .po file (PHP Format) to a Python format .po file,
the difference being how variable substitutions work. PHP uses a %1$s
format, and Python uses a {0} format (zero indexed). This method will
convert, e.g.:
I have %2$s apples and %1$s oranges
to
I have {1} apples and {0} oranges
This method ignores strings with %s as both languages will recognize that.
"""
thetargetfile = po.pofile()
for unit in inputstore.units:
newunit = self.convertunit(unit)
thetargetfile.addunit(newunit)
return thetargetfile
def convertunit(self, unit):
developer_notes = unit.getnotes(origin="developer")
translator_notes = unit.getnotes(origin="translator")
unit.removenotes()
unit.addnote(self.convertstrings(developer_notes))
unit.addnote(self.convertstrings(translator_notes))
unit.source = self.convertstrings(unit.source)
unit.target = self.convertstrings(unit.target)
return unit
def convertstring(self, input):
return re.sub('%(\d)\$s', lambda x: "{%d}" % (int(x.group(1)) - 1), input)
def convertstrings(self, input):
if isinstance(input, multistring):
strings = input.strings
elif isinstance(input, list):
strings = input
else:
return self.convertstring(input)
for index, string in enumerate(strings):
strings[index] = re.sub('%(\d)\$s', lambda x: "{%d}" % (int(x.group(1)) - 1), string)
return multistring(strings)
def convertphp2py(inputfile, outputfile, template=None):
"""Converts from PHP .po format to Python .po format
:param inputfile: file handle of the source
:param outputfile: file handle to write to
:param template: unused
"""
convertor = phppo2pypo()
inputstore = po.pofile(inputfile)
outputstore = convertor.convertstore(inputstore)
if outputstore.isempty():
return False
outputstore.serialize(outputfile)
return True
def main(argv=None):
"""Converts PHP .po files to Python .po files."""
from translate.convert import convert
formats = {"po": ("po", convertphp2py)}
parser = convert.ConvertOptionParser(formats, description=__doc__)
parser.run(argv)
if __name__ == '__main__':
main()
|
phlax/translate
|
translate/tools/phppo2pypo.py
|
Python
|
gpl-2.0
| 3,396 |
# -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2016 CERN.
#
# INSPIRE 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.
#
# INSPIRE 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 INSPIRE; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Results class to wrap a query and allow for searching."""
import json
from flask import current_app
try:
from functools import lru_cache
except ImportError:
from functools32 import lru_cache
def dotter(d, key, dots):
""" Given a json schema dictionary (d argument) returns all the properties
in a dotted notation.
e.g
author
author.full_name
author.affiliation
etc...
"""
if isinstance(d, dict):
if 'items' in d:
dots.append(key)
dotter(d['items'], key, dots)
elif 'properties' in d:
dotter(d['properties'], key, dots)
else:
for k in d:
dotter(d[k], key + '.' + k, dots)
else:
dots.append(key)
return dots
def get_dotted_keys(d, key, dots):
"""Removes undesirable information from extracted keywords."""
dotted_keys = dotter(d, key, dots)
return set(dotted_key[1:].rsplit('.', 1)[0] for dotted_key in dotted_keys)
@lru_cache(maxsize=1000)
def generate_valid_keywords():
"""Parses all sources that contain valid search keywords to a list."""
valid_keywords = []
keyword_mapping = current_app.config['SEARCH_ELASTIC_KEYWORD_MAPPING']
# Get keywords from configuration file
keywords = keyword_mapping.keys()
for k in keyword_mapping.values():
if isinstance(k, dict):
keywords += k.keys()
# Get keywords from the json schema
for path in current_app.extensions['invenio-jsonschemas'].list_schemas():
data = current_app.extensions['invenio-jsonschemas'].get_schema(path)
data = data.get('properties')
dotted_keywords = get_dotted_keys(data, '', [])
keywords += dotted_keywords
# Get keywords from elasticsearch mapping
for name, path in current_app.extensions['invenio-search'].mappings.iteritems():
with open(path) as data_file:
data = json.load(data_file)
data = data.get('mappings').get(name.split('-')[-1]).get('properties')
dotted_keywords = get_dotted_keys(data, '', [])
keywords += dotted_keywords
cleaned_keywords = list(set([k for k in keywords if k is not None]))
# Sort by longest string descending
cleaned_keywords.sort(key=len, reverse=True)
return cleaned_keywords
|
jacenkow/inspire-next
|
inspirehep/modules/search/utils.py
|
Python
|
gpl-2.0
| 3,296 |
//===============================================================================
// Microsoft patterns & practices
// CompositeUI Application Block
//===============================================================================
// Copyright © Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.Practices.CompositeUI.Utility
{
/// <summary>
/// Represents a set of items. Adding an item to a set twice will only yield one instance
/// in the collection.
/// </summary>
/// <typeparam name="TItem">The type of items to be stored in the <see cref="Set{TItem}"/>.</typeparam>
public class Set<TItem> : ICollection<TItem>
{
bool isReadOnly;
Dictionary<TItem, object> dictionary;
/// <summary>
///
/// </summary>
public Set()
{
dictionary = new Dictionary<TItem, object>();
isReadOnly = false;
}
private Set(Set<TItem> innerSet)
{
dictionary = innerSet.dictionary;
isReadOnly = true;
}
/// <summary>
/// See <see cref="ICollection{T}.Add"/> for more information.
/// </summary>
public void Add(TItem item)
{
if (IsReadOnly)
throw new NotSupportedException();
dictionary[item] = String.Empty;
}
/// <summary>
/// Returns a read-only wrapper around the <see cref="Set{TItem}"/>.
/// </summary>
public Set<TItem> AsReadOnly()
{
return new Set<TItem>(this);
}
/// <summary>
/// See <see cref="ICollection{T}.Clear"/> for more information.
/// </summary>
public void Clear()
{
if (IsReadOnly)
throw new NotSupportedException();
dictionary.Clear();
}
/// <summary>
/// See <see cref="ICollection{T}.Contains"/> for more information.
/// </summary>
public bool Contains(TItem item)
{
return dictionary.ContainsKey(item);
}
/// <summary>
/// See <see cref="ICollection{T}.CopyTo"/> for more information.
/// </summary>
public void CopyTo(TItem[] array, int arrayIndex)
{
throw new NotImplementedException();
}
/// <summary>
/// See <see cref="ICollection{T}.Count"/> for more information.
/// </summary>
public int Count
{
get { return dictionary.Count; }
}
/// <summary>
/// See <see cref="ICollection{T}.IsReadOnly"/> for more information.
/// </summary>
public bool IsReadOnly
{
get { return isReadOnly; }
}
/// <summary>
/// See <see cref="ICollection{T}.Remove"/> for more information.
/// </summary>
public bool Remove(TItem item)
{
if (IsReadOnly)
throw new NotSupportedException();
return dictionary.Remove(item);
}
/// <summary>
/// See <see cref="IEnumerable{T}.GetEnumerator"/> for more information.
/// </summary>
public IEnumerator<TItem> GetEnumerator()
{
return dictionary.Keys.GetEnumerator();
}
/// <summary>
/// See <see cref="IEnumerable.GetEnumerator"/> for more information.
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
tws67/uniframework
|
sources/cab/CompositeUI/Utility/Set.cs
|
C#
|
gpl-2.0
| 3,431 |
<?php
/* SVN FILE: $Id: SassMediaNode.php 49 2010-04-04 10:51:24Z chris.l.yates $ */
/**
* SassMediaNode class file.
* @author Richard Lyon
* @copyright none
* @license http://phamlp.googlecode.com/files/license.txt
* @package PHamlP
* @subpackage Sass.tree
*/
/**
* SassMediaNode class.
* Represents a CSS @media directive
* @package PHamlP
* @subpackage Sass.tree
*/
class SassMediaNode extends SassNode
{
const IDENTIFIER = '@';
const MATCH = '/^@(media)\s+(.+?)\s*;?$/';
const MEDIA = 1;
public $token;
/**
* @var string
*/
private $media;
/**
* @var array parameters for the message;
* only used by internal warning messages
*/
private $params;
/**
* @var boolean true if this is a warning
*/
private $warning;
/**
* SassMediaNode.
* @param object $token source token
* @param mixed string: an internally generated warning message about the
* source
* boolean: the source token is a @Media or @warn directive containing the
* message; True if this is a @warn directive
* @return SassMediaNode
*/
public function __construct($token)
{
parent::__construct($token);
preg_match(self::MATCH, $token->source, $matches);
$this->token = $token;
$this->media = $matches[self::MEDIA];
}
/**
* Parse this node.
* This raises an error.
* @return array An empty array
*/
public function parse($context)
{
// If we are in a loop, function or mixin then the parent isn't what should
// go inside the media node. Walk up the parent tree to find the rule node
// to put inside the media node or the root node if the media node should be
// at the root.
$parent = $this->parent;
while (!($parent instanceOf SassRuleNode) && !($parent instanceOf SassRootNode)) {
$parent = $parent->parent;
}
// Make a copy of the token before parsing in case we are in a loop and it contains variables
$token = clone $this->token;
$token->source = SassDirectiveNode::interpolate_nonstrict($token->source, $context);
$node = new SassRuleNode($token, $context);
$node->root = $parent->root;
$rule = clone $parent;
$rule->root = $node->root;
$rule->children = $this->children;
$try = $rule->parse($context);
if (is_array($try)) {
$rule->children = $try;
}
// Tests were failing with this, but I'm not sure if we cover every case.
//else if (is_object($try) && method_exists($try, 'render')) {
// $rule = $try;
//}
$node->children = array(new SassString($rule->render($context)));
return array($node);
}
}
|
vhinrich/vhinandrich2
|
sites/all/libraries/phpsass/tree/SassMediaNode.php
|
PHP
|
gpl-2.0
| 2,638 |
/*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2003-2007 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.ba.ch;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import edu.umd.cs.findbugs.ba.XClass;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.graph.AbstractVertex;
/**
* Vertex class - represents a class or interface in the InheritanceGraph. Edges
* connect subtypes to supertypes.
*
* @author David Hovemeyer
*/
class ClassVertex extends AbstractVertex<InheritanceEdge, ClassVertex> {
private static final int FINISHED = 1;
private static final int APPLICATION_CLASS = 2;
private static final int INTERFACE = 4;
private final ClassDescriptor classDescriptor;
private final @CheckForNull
XClass xclass;
private int flags;
private ClassVertex directSuperclass;
@Override
public String toString() {
return classDescriptor.toString();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ClassVertex))
return false;
return classDescriptor.equals(((ClassVertex) o).classDescriptor);
}
@Override
public int hashCode() {
return classDescriptor.hashCode();
}
private ClassVertex(ClassDescriptor classDescriptor, XClass xclass) {
this.classDescriptor = classDescriptor;
this.xclass = xclass;
this.flags = 0;
if (xclass.isInterface()) {
setInterface();
}
}
private ClassVertex(ClassDescriptor classDescriptor, boolean isInterfaceEdge) {
this.classDescriptor = classDescriptor;
this.xclass = null;
this.flags = 0;
if (isInterfaceEdge) {
setInterface();
}
}
/**
* Factory method for resolved ClassVertex objects.
*
* @param classDescriptor
* ClassDescriptor naming the class or interface
* @param xclass
* object containing information about a class or interface
* @return ClassVertex
*/
public static ClassVertex createResolvedClassVertex(ClassDescriptor classDescriptor, XClass xclass) {
return new ClassVertex(classDescriptor, xclass);
}
/**
* Factory method for ClassVertex objects representing missing classes.
*
* @param classDescriptor
* ClassDescriptor naming the missing class or interface
* @param isInterface
* true if missing class is an interface, false otherwise
* @return ClassVertex
*/
public static ClassVertex createMissingClassVertex(ClassDescriptor classDescriptor, boolean isInterface) {
return new ClassVertex(classDescriptor, isInterface);
}
/**
* @return Returns the classDescriptor.
*/
public ClassDescriptor getClassDescriptor() {
return classDescriptor;
}
/**
* @return Returns the xClass.
*/
public @Nullable
XClass getXClass() {
return xclass;
}
/**
* Return true if this ClassVertex corresponds to a resolved class, or false
* if the class could not be found.
*/
public boolean isResolved() {
return xclass != null;
}
/**
* @param finished
* The finished to set.
*/
public void setFinished(boolean finished) {
setFlag(FINISHED, finished);
}
/**
* @return Returns the finished.
*/
public boolean isFinished() {
return isFlagSet(FINISHED);
}
/**
* Mark this ClassVertex as representing an application class.
*/
public void markAsApplicationClass() {
setFlag(APPLICATION_CLASS, true);
}
/**
* @return true if this ClassVertex represents an application class, false
* otherwise
*/
public boolean isApplicationClass() {
return isFlagSet(APPLICATION_CLASS);
}
/**
* Mark this ClassVertex as representing an interface.
*/
private void setInterface() {
setFlag(INTERFACE, true);
}
/**
* @return true if this ClassVertex represents an interface, false otherwise
*/
public boolean isInterface() {
return isFlagSet(INTERFACE);
}
/**
* Set the ClassVertex representing the direct superclass.
*
* @param target
* ClassVertex representing the direct superclass.
*/
public void setDirectSuperclass(ClassVertex target) {
this.directSuperclass = target;
}
/**
* @return Returns the directSuperclass.
*/
public ClassVertex getDirectSuperclass() {
return directSuperclass;
}
private void setFlag(int flag, boolean enable) {
if (enable) {
flags |= flag;
} else {
flags &= ~flag;
}
}
private boolean isFlagSet(int flag) {
return (flags & flag) != 0;
}
}
|
jesusaplsoft/FindAllBugs
|
findbugs/src/java/edu/umd/cs/findbugs/ba/ch/ClassVertex.java
|
Java
|
gpl-2.0
| 5,686 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_content
*
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
use Joomla\CMS\Dispatcher\Dispatcher;
/**
* Dispatcher class for com_cpanel
*
* @since __DEPLOY_VERSION__
*/
class CpanelDispatcher extends Dispatcher
{
/**
* The extension namespace
*
* @var string
*
* @since __DEPLOY_VERSION__
*/
protected $namespace = 'Joomla\\Component\\Cpanel';
/**
* com_cpanel does not require check permission, so we override checkAccess method and have it empty
*
* @return void
*/
protected function checkAccess()
{
}
}
|
Supun94/gsoc17_js_tests
|
administrator/components/com_cpanel/dispatcher.php
|
PHP
|
gpl-2.0
| 764 |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'format', 'lt', {
label: 'Šrifto formatas',
panelTitle: 'Šrifto formatas',
tag_address: 'Kreipinio',
tag_div: 'Normalus (DIV)',
tag_h1: 'Antraštinis 1',
tag_h2: 'Antraštinis 2',
tag_h3: 'Antraštinis 3',
tag_h4: 'Antraštinis 4',
tag_h5: 'Antraštinis 5',
tag_h6: 'Antraštinis 6',
tag_p: 'Normalus',
tag_pre: 'Formuotas'
} );
|
eastoncat/cm.eastoncat
|
sites/all/modules/contrib/civicrm/packages/ckeditor/plugins/format/lang/lt.js
|
JavaScript
|
gpl-2.0
| 533 |
<?php
error_reporting(E_ALL);
$local_path = dirname(__FILE__);
class UserAgentParser_test extends \PHPUnit_Framework_TestCase {
function test_parse_user_agent() {
global $local_path;
$uas = json_decode(file_get_contents($local_path . '/user_agents.json'), true);
foreach($uas as $ua => $expected_result) {
$result = parse_user_agent($ua);
$this->assertEquals($expected_result, $result, $ua . " failed!" );
}
}
function test_pase_user_agent_empty() {
$expected = array(
'platform' => null,
'browser' => null,
'version' => null,
);
$result = parse_user_agent('');
$this->assertEquals($result, $expected);
// $result = parse_user_agent('asdjkakljasdkljasdlkj');
// $this->assertEquals($result, $expected);
$result = parse_user_agent('Mozilla (asdjkakljasdkljasdlkj) BlahBlah');
$this->assertEquals($result, $expected);
}
/**
* @expectedException \InvalidArgumentException
*/
function test_no_user_agent_exception() {
unset($_SERVER['HTTP_USER_AGENT']);
parse_user_agent();
}
}
|
kennyfans/news.hcmfifa
|
wp-content/plugins/wp-statistics/vendor/donatj/phpuseragentparser/Tests/UserAgentParserTest.php
|
PHP
|
gpl-2.0
| 1,039 |
/***************************************************************************
* Copyright (C) 2007 by Dominik Seichter *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This 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 Library 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 "PdfMemStream.h"
#include "PdfArray.h"
#include "PdfEncrypt.h"
#include "PdfFilter.h"
#include "PdfObject.h"
#include "PdfOutputDevice.h"
#include "PdfOutputStream.h"
#include "PdfVariant.h"
#include "PdfDefinesPrivate.h"
#include <stdlib.h>
namespace PoDoFo {
PdfMemStream::PdfMemStream( PdfObject* pParent )
: PdfStream( pParent ), m_pStream( NULL ), m_pBufferStream( NULL ), m_lLength( 0 )
{
}
PdfMemStream::PdfMemStream( const PdfMemStream & rhs )
: PdfStream( NULL ), m_pStream( NULL ), m_pBufferStream( NULL ), m_lLength( 0 )
{
operator=(rhs);
}
PdfMemStream::~PdfMemStream()
{
}
void PdfMemStream::BeginAppendImpl( const TVecFilters & vecFilters )
{
m_buffer = PdfRefCountedBuffer();
m_lLength = 0;
if( vecFilters.size() )
{
m_pBufferStream = new PdfBufferOutputStream( &m_buffer );
m_pStream = PdfFilterFactory::CreateEncodeStream( vecFilters, m_pBufferStream );
}
else
m_pStream = new PdfBufferOutputStream( &m_buffer );
}
void PdfMemStream::AppendImpl( const char* pszString, size_t lLen )
{
m_pStream->Write( pszString, lLen );
}
void PdfMemStream::EndAppendImpl()
{
if( m_pStream )
{
m_pStream->Close();
if( !m_pBufferStream )
m_lLength = dynamic_cast<PdfBufferOutputStream*>(m_pStream)->GetLength();
delete m_pStream;
m_pStream = NULL;
}
if( m_pBufferStream )
{
m_pBufferStream->Close();
m_lLength = m_pBufferStream->GetLength();
delete m_pBufferStream;
m_pBufferStream = NULL;
}
if( m_pParent )
m_pParent->GetDictionary().AddKey( PdfName::KeyLength, PdfVariant(static_cast<pdf_int64>(m_lLength) ) );
}
void PdfMemStream::GetCopy( char** pBuffer, pdf_long* lLen ) const
{
if( !pBuffer || !lLen )
{
PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
}
*pBuffer = static_cast<char*>(malloc( sizeof( char ) * m_lLength ));
*lLen = m_lLength;
if( !*pBuffer )
{
PODOFO_RAISE_ERROR( ePdfError_OutOfMemory );
}
memcpy( *pBuffer, m_buffer.GetBuffer(), m_lLength );
}
void PdfMemStream::GetCopy(PdfOutputStream * pStream) const
{
if( !pStream)
{
PODOFO_RAISE_ERROR( ePdfError_InvalidHandle );
}
pStream->Write(m_buffer.GetBuffer(), m_lLength);
}
void PdfMemStream::FlateCompress()
{
PdfObject* pObj;
PdfVariant vFilter( PdfName("FlateDecode" ) );
PdfVariant vFilterList;
PdfArray tFilters;
PdfArray::const_iterator tciFilters;
if( !m_lLength )
return; // ePdfError_ErrOk
// TODO: Handle DecodeParms
if( m_pParent->GetDictionary().HasKey( "Filter" ) )
{
pObj = m_pParent->GetIndirectKey( "Filter" );
if( pObj->IsName() )
{
if( pObj->GetName() != "DCTDecode" && pObj->GetName() != "FlateDecode" )
{
tFilters.push_back( vFilter );
tFilters.push_back( *pObj );
}
}
else if( pObj->IsArray() )
{
tciFilters = pObj->GetArray().begin();
while( tciFilters != pObj->GetArray().end() )
{
if( (*tciFilters).IsName() )
{
// do not compress DCTDecoded are already FlateDecoded streams again
if( (*tciFilters).GetName() == "DCTDecode" || (*tciFilters).GetName() == "FlateDecode" )
{
return;
}
}
++tciFilters;
}
tFilters.push_back( vFilter );
tciFilters = pObj->GetArray().begin();
while( tciFilters != pObj->GetArray().end() )
{
tFilters.push_back( (*tciFilters) );
++tciFilters;
}
}
else
return;
vFilterList = PdfVariant( tFilters );
m_pParent->GetDictionary().AddKey( "Filter", vFilterList );
FlateCompressStreamData(); // throws an exception on error
}
else
{
m_pParent->GetDictionary().AddKey( "Filter", PdfName( "FlateDecode" ) );
FlateCompressStreamData();
}
}
void PdfMemStream::Uncompress()
{
pdf_long lLen;
char* pBuffer = NULL;
TVecFilters vecEmpty;
if( m_pParent && m_pParent->IsDictionary() && m_pParent->GetDictionary().HasKey( "Filter" ) && m_lLength )
{
try {
this->GetFilteredCopy( &pBuffer, &lLen );
} catch( PdfError & e ) {
if( pBuffer )
free( pBuffer );
throw e;
}
this->Set( pBuffer, lLen, vecEmpty );
// free the memory allocated by GetFilteredCopy again.
podofo_free( pBuffer );
m_pParent->GetDictionary().RemoveKey( "Filter" );
if( m_pParent->GetDictionary().HasKey( "DecodeParms" ) )
{
m_pParent->GetDictionary().RemoveKey( "DecodeParms" );
}
}
}
void PdfMemStream::FlateCompressStreamData()
{
char* pBuffer;
pdf_long lLen;
if( !m_lLength )
return;
std::auto_ptr<PdfFilter> pFilter = PdfFilterFactory::Create( ePdfFilter_FlateDecode );
if( pFilter.get() )
{
pFilter->Encode( m_buffer.GetBuffer(), m_buffer.GetSize(), &pBuffer, &lLen );
this->Set( pBuffer, lLen );
}
else
{
PODOFO_RAISE_ERROR( ePdfError_UnsupportedFilter );
}
}
const PdfStream & PdfMemStream::operator=( const PdfStream & rhs )
{
const PdfMemStream* pStream = dynamic_cast<const PdfMemStream*>(&rhs);
if( pStream )
m_buffer = pStream->m_buffer;
else
return PdfStream::operator=( rhs );
m_lLength = rhs.GetLength();
if( m_pParent )
m_pParent->GetDictionary().AddKey( PdfName::KeyLength, PdfVariant( static_cast<pdf_int64>(m_lLength) ) );
return *this;
}
void PdfMemStream::Write( PdfOutputDevice* pDevice, PdfEncrypt* pEncrypt )
{
pDevice->Print( "stream\n" );
if( pEncrypt )
{
char* pBuffer;
pdf_long lLen;
this->GetCopy( &pBuffer, &lLen );
pdf_long nOutputLen = pEncrypt->CalculateStreamLength(lLen);
pdf_long nOffset = pEncrypt->CalculateStreamOffset();
char *pOutputBuffer = new char[nOutputLen+1];
memset(pOutputBuffer, 0, nOffset);
memcpy(&pOutputBuffer[nOffset], pBuffer, lLen);
pEncrypt->Encrypt( reinterpret_cast<unsigned char*>(pOutputBuffer), lLen );
pDevice->Write( pOutputBuffer, nOutputLen );
delete[] pOutputBuffer;
free( pBuffer );
}
else
{
pDevice->Write( this->Get(), this->GetLength() );
}
pDevice->Print( "\nendstream\n" );
}
pdf_long PdfMemStream::GetLength() const
{
return m_lLength;
}
};
|
mekentosj/podofo
|
src/base/PdfMemStream.cpp
|
C++
|
gpl-2.0
| 8,380 |
<?php
/**
* Meta API
*
* plugin api for getting and setting Shopp object meta data
*
* @author Jonathan Davis, John Dillick
* @version 1.0
* @copyright Ingenesis Limited, June 23, 2011
* @license GNU GPL version 3 (or later) {@see license.txt}
* @package shopp
* @since 1.0
* @subpackage shopp
**/
/**
* shopp_product_meta - get a product meta entry by product id, type, and name
*
* @author John Dillick
* @since 1.2
*
* @param int $product product id
* @param string $name the name of the meta data
* @param string $type (default: meta) the meta data type
* @return array of stdClass Object meta values, with parent, type, name, and value properties
**/
function shopp_product_meta ( $product = false, $name = false, $type = 'meta' ) {
return shopp_meta( $product, 'product', $name, $type );
}
/**
* shopp_product_has_meta - check for named meta data for a product.
*
* @author John Dillick
* @since 1.2
*
* @param int $product (required) the product id
* @param string $name (required) the name of the meta entry
* @param string $type (optional default: meta) the type of meta entry
* @return bool returns true if meta data exists on the product, false if not
**/
function shopp_product_has_meta ( $product = false, $name = false, $type = 'meta' ) {
if ( ! $name || ! $product ) return false;
$meta = shopp_meta($product, 'product', $name, $type);
return ( ! empty($meta) );
}
/**
* shopp_product_meta_list - get an array of meta values on the product
*
* @author John Dillick
* @since 1.2
*
* @param type $var Description...
* @return array list of values keyed by name, false on failure
**/
function shopp_product_meta_list ( $product = false, $type = 'meta' ) {
if ( ! $product ) {
if(SHOPP_DEBUG) new ShoppError(__FUNCTION__.' failed: product id required', 'shopp_product_meta_list', SHOPP_DEBUG_ERR);
return false;
}
$metas = shopp_product_meta ( $product, false, $type );
$results = array();
foreach ( (array) $metas as $id => $meta ) {
if ( is_object($meta) ) {
$results[$meta->name] = $meta->value;
} else if ( ! empty($meta) ) {
$results[$id] = $meta;
}
}
return $results;
}
/**
* shopp_product_meta_count - number of meta entries associated with a product
*
* @author John Dillick
* @since 1.2
*
* @param int $product (required) the product id
* @param type $type (optional default: meta) the meta type to count
* @return int count of meta entries, false on failure
**/
function shopp_product_meta_count ( $product = false, $type = 'meta' ) {
if ( ! $product ) {
if(SHOPP_DEBUG) new ShoppError(__FUNCTION__.' failed: product id required', 'shopp_product_meta_count', SHOPP_DEBUG_ERR);
return false;
}
$meta = shopp_product_meta ( $product, false, $type );
return count( $meta );
}
/**
* shopp_set_product_meta - create or update a new product meta record
*
* @author John Dillick
* @since 1.2
*
* @param int $product (required on creation/update) product object to create/update the meta record on
* @param string $name (required on update) the name of the meta entry, more specific than type
* @param mixed $value (optional default: false) the value stored to the meta entry
* @param string $type (optional default: meta) the type or classification of the meta data
* @param string $valuetype (optional default: 'value') 'numeral' or 'value', if the value is numeric, 'numeric' will store in numeric field.
* @return bool true on successful save or update, fail on failure
**/
function shopp_set_product_meta ( $product = false, $name = false, $value = false, $type = 'meta', $valuetype = 'value' ) {
return shopp_set_meta ( $product, 'product', $name, $value, $type, $valuetype );
}
/**
* shopp_rmv_product_meta - remove a meta entry by product id and name
*
* @author John Dillick
* @since 1.2
*
* @param int $product (required) - product id of meta entry to remove
* @param string $name (required with parent object context) - the meta name
* @param string $type (optional default: meta) - the meta type
* @return bool true if the meta entry was removed, false on failure
**/
function shopp_rmv_product_meta ( $product = false, $name = false, $type = 'meta') {
if ( ! $product && ! $name ) {
if(SHOPP_DEBUG) new ShoppError(__FUNCTION__.' failed: product and name parameters required.',__FUNCTION__,SHOPP_DEBUG_ERR);
return false;
}
return shopp_rmv_meta ( $product, 'product', $name, $type );
}
/**
* shopp_meta - Returns meta data assigned to an object.
*
* @author John Dillick
* @since 1.2
*
* @param int $id (optional) of the meta entry, or object id of the object the Shopp meta is attached to
* @param string $context (optional) the object type that the object id refers to.
* @param string $name (optional) the name of the meta data
* @param string $type (optional default: meta) the data type of meta data (examples meta, spec, download, image, yourdatatype )
* @return array of stdClass Object meta values, with parent, type, name, and value properties
*
* Usage Examples:
* shopp_meta(<id>) - meta record by id
* shopp_meta([id], [context], [name], [type]) - pick one or more, id is the id of the parent contextual object if context is specified
*
* shopp_meta(1) loads meta record 1
* shopp_meta(5,'product','Producer','spec') loads spec named Producer of product id 5
* shopp_meta(false, 'product','mydownload.zip','downloads') load the meta record for mydownload.zip product download
* shopp_meta(5, 'product', false, 'downloads') load all product download meta records for product id 5
* shopp_meta(false, 'price') loads all meta data associated with variants
*
**/
function shopp_meta ( $id = false, $context = false, $name = false, $type = 'meta' ) {
$values = array();
if ( ! ( $id || $context || $name ) ) {
if(SHOPP_DEBUG) new ShoppError(__FUNCTION__.' failed: No parameters specified.', 'shopp_meta',SHOPP_DEBUG_ERR);
return;
}
// Load meta by id
if ( $id && false === $context ) {
$meta = new MetaObject();
$meta->load($id);
if ( empty($meta->id) ) {
if(SHOPP_DEBUG) new ShoppError(__FUNCTION__." failed: No such meta with id $id or missing context.",__FUNCTION__,SHOPP_DEBUG_ERR);
}
return $meta->value;
}
// Load one or more meta
$loading = array();
if ( $id && $context ) $loading['parent'] = $id; // if context is specified, id will always be parent object
if ( $context ) $loading['context'] = $context;
if ( $type ) $loading['type'] = $type;
if ( $name ) $loading['name'] = $name;
$Meta = new ObjectMeta();
$Meta->load( $loading );
if ( empty($Meta->meta) ) return array();
foreach ( $Meta->meta as $meta ) {
if( ! isset($values[$meta->id]) ) $values[$meta->id] = new stdClass;
$values[$meta->id]->parent = $meta->parent;
$values[$meta->id]->type = $meta->type;
$values[$meta->id]->name = $meta->name;
if ( empty($meta->value) && $meta->numeral > 0 ) $meta->value = $meta->numeral;
$values[$meta->id]->value = $meta->value;
}
if ( $id && $context && $type && $name and 1 == count($values)) {
return reset($values)->value;
}
return $values;
}
/**
* shopp_meta_exists - Determine if one or more meta records exist based on some combination of context, and/or type, and/or name of the metadata
*
* @author John Dillick
* @since 1.2
*
* @param string $name (optional) name of the meta entry
* @param string $context (optional) object context of the meta entry
* @param string $type (optional default: meta) type of the meta entry
* @return bool true if one or more meta entries exist
*
* One or more of the parameters must be specified.
*
**/
function shopp_meta_exists ( $name = false, $context = false, $type = 'meta' ) {
if ( ! ( $name || $context ) ) return false;
$meta = shopp_meta(false, $context, $name, $type);
return (bool)( $meta );
}
/**
* shopp_set_meta - create or update a new meta record
*
* @author John Dillick
* @since 1.2
*
* @param int $id (required on creation/update) id of an existing meta entry, or with context the parent object of a new meta entry
* @param string $context (required on update) the parent object type of the meta entry (example product, price, and more)
* @param string $name (required on update) the name of the meta entry, more specific than type
* @param mixed $value (optional default: false) the value stored to the meta entry
* @param string $type (optional default: meta) the type or classification of the meta data
* @param string $valuetype (optional default: 'value') 'numeral' or 'value', if the value is numeric, 'numeric' will store in numeric field.
* @return bool true on successful save or update, fail on failure
**/
function shopp_set_meta ( $id = false, $context = false, $name = false, $value = false, $type = 'meta', $valuetype = 'value' ) {
if ( ! ( $id || $id && $context ) ) {
if(SHOPP_DEBUG) new ShoppError(__FUNCTION__." failed: Must specify at least a meta id or parent id and context.",__FUNCTION__,SHOPP_DEBUG_ERR);
return false;
}
$record = array();
if ( $context ) $record['context'] = $context;
if ( $type ) $record['type'] = $type;
if ( $name ) $record['name'] = $name;
$valuefield = array();
$valuefield[( 'numeral' == $valuetype && is_numeric($value) ? 'numeral' : 'value' )] = $value;
// save existing meta record by meta id
if ( $id && ! $context ) {
$meta = new MetaObject();
$meta->load($id);
if ( ! empty($meta->id) ) {
$meta->updates( array_merge($record, $valuefield) );
$meta->save();
return true;
} else {
if(SHOPP_DEBUG) new ShoppError(__FUNCTION__." failed: No metadata with id $id.",__FUNCTION__,SHOPP_DEBUG_ERR);
return false;
}
}
// fully spec'd meta entry
if ( $id && $context && $type && $name ) {
$meta = new MetaObject();
$meta->load( array_merge( $record, array( 'parent'=>$id, 'context'=>$context ) ) );
$meta->updates( array_merge(array( 'parent'=>$id, 'context'=>$context ), $record, $valuefield) );
$meta->save();
return true;
}
if(SHOPP_DEBUG) new ShoppError(__FUNCTION__.' failed: id, context, type, and name are required parameters for this context.',__FUNCTION__,SHOPP_DEBUG_ERR);
return false;
}
/**
* shopp_rmv_meta - remove a meta entry by meta id, or parent id, context, type, and name
*
* @author John Dillick
* @since 1.2
*
* @param int $id (required) - meta entry id or, with context, the parent object id
* @param int $context (required for parent object id) - the parent object context
* @param string $name (required with parent object context) - the meta name
* @param string $type (optional default: meta) - the meta type
* @return bool true if the meta entry was removed, false on failure
**/
function shopp_rmv_meta ( $id = false, $context = false, $name = false, $type = 'meta' ) {
if ( ! ( $id || $id && $context ) ) {
if(SHOPP_DEBUG) new ShoppError(__FUNCTION__." failed: Must specify at least a meta id or parent id and context.",__FUNCTION__,SHOPP_DEBUG_ERR);
return false;
}
// save existing meta record by meta id
if ( $id && ! $context ) {
$meta = new MetaObject();
$meta->load($id);
if ( $meta->id ) $meta->delete();
return true;
}
// fully spec'd meta entry
if ( $id && $context && $type && $name ) {
$meta = new MetaObject();
$meta->load( array( 'parent'=>$id, 'context'=>$context, 'type' => $type, 'name' => $name ) );
if ( $meta->id ) $meta->delete();
return true;
}
// general meta entries
if ( $id && $context ) {
$table = DatabaseObject::tablename(MetaObject::$table);
$id = db::escape($id);
$context = db::escape($context);
$name = db::escape($name);
$type = db::escape($type);
$where = "parent=$id AND context='$context'";
$where .= ( $type && ! empty($type) ? " AND type='$type'" : "" );
$where .= ( $name && ! empty($name) ? " AND type='$name'" : "" );
return db::query("DELETE FROM $table WHERE $where");
}
}
?>
|
sharpmachine/connielofgreen.com
|
wp-content/plugins/shopp/api/meta.php
|
PHP
|
gpl-2.0
| 11,860 |
/* $OpenBSD: kern_sysctl.c,v 1.104 2004/02/29 12:14:05 weingart Exp $ */
/* $NetBSD: kern_sysctl.c,v 1.17 1996/05/20 17:49:05 mrg Exp $ */
/*-
* Copyright (c) 1982, 1986, 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Mike Karels at Berkeley Software Design, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)kern_sysctl.c 8.4 (Berkeley) 4/14/94
*/
/*
* sysctl system call.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <sys/resourcevar.h>
#include <sys/file.h>
#include <sys/vnode.h>
#include <sys/unistd.h>
#include <sys/buf.h>
#include <sys/ioctl.h>
#include <sys/tty.h>
#include <sys/disklabel.h>
#include <sys/disk.h>
#include <uvm/uvm_extern.h>
#include <sys/sysctl.h>
#include <sys/msgbuf.h>
#include <sys/dkstat.h>
#include <sys/vmmeter.h>
#include <sys/namei.h>
#include <sys/exec.h>
#include <sys/mbuf.h>
#include <sys/sensors.h>
#include <sys/mount.h>
#include <sys/syscallargs.h>
#include <dev/rndvar.h>
#ifdef DDB
#include <ddb/db_var.h>
#endif
#ifdef SYSVMSG
#include <sys/msg.h>
#endif
#ifdef SYSVSEM
#include <sys/sem.h>
#endif
#ifdef SYSVSHM
#include <sys/shm.h>
#endif
#define PTRTOINT64(_x) ((u_int64_t)(u_long)(_x))
extern struct forkstat forkstat;
extern struct nchstats nchstats;
extern int nselcoll, fscale;
extern struct disklist_head disklist;
extern fixpt_t ccpu;
extern long numvnodes;
int sysctl_diskinit(int, struct proc *);
int sysctl_proc_args(int *, u_int, void *, size_t *, struct proc *);
int sysctl_intrcnt(int *, u_int, void *, size_t *);
int sysctl_sensors(int *, u_int, void *, size_t *, void *, size_t);
int sysctl_emul(int *, u_int, void *, size_t *, void *, size_t);
int (*cpu_cpuspeed)(int *);
int (*cpu_setperf)(int);
/*
* Lock to avoid too many processes vslocking a large amount of memory
* at the same time.
*/
struct lock sysctl_lock, sysctl_disklock;
#if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES)
struct lock sysctl_kmemlock;
#endif
void
sysctl_init()
{
lockinit(&sysctl_lock, PLOCK|PCATCH, "sysctl", 0, 0);
lockinit(&sysctl_disklock, PLOCK|PCATCH, "sysctl_disklock", 0, 0);
#if defined(KMEMSTATS) || defined(DIAGNOSTIC) || defined(FFS_SOFTUPDATES)
lockinit(&sysctl_kmemlock, PLOCK|PCATCH, "sysctl_kmemlock", 0, 0);
#endif
}
int
sys___sysctl(p, v, retval)
struct proc *p;
void *v;
register_t *retval;
{
register struct sys___sysctl_args /* {
syscallarg(int *) name;
syscallarg(u_int) namelen;
syscallarg(void *) old;
syscallarg(size_t *) oldlenp;
syscallarg(void *) new;
syscallarg(size_t) newlen;
} */ *uap = v;
int error, dolock = 1;
size_t savelen = 0, oldlen = 0;
sysctlfn *fn;
int name[CTL_MAXNAME];
if (SCARG(uap, new) != NULL &&
(error = suser(p, 0)))
return (error);
/*
* all top-level sysctl names are non-terminal
*/
if (SCARG(uap, namelen) > CTL_MAXNAME || SCARG(uap, namelen) < 2)
return (EINVAL);
error = copyin(SCARG(uap, name), name,
SCARG(uap, namelen) * sizeof(int));
if (error)
return (error);
switch (name[0]) {
case CTL_KERN:
fn = kern_sysctl;
if (name[1] == KERN_VNODE) /* XXX */
dolock = 0;
break;
case CTL_HW:
fn = hw_sysctl;
break;
case CTL_VM:
fn = uvm_sysctl;
break;
case CTL_NET:
fn = net_sysctl;
break;
case CTL_FS:
fn = fs_sysctl;
break;
case CTL_VFS:
fn = vfs_sysctl;
break;
case CTL_MACHDEP:
fn = cpu_sysctl;
break;
#ifdef DEBUG
case CTL_DEBUG:
fn = debug_sysctl;
break;
#endif
#ifdef DDB
case CTL_DDB:
fn = ddb_sysctl;
break;
#endif
default:
return (EOPNOTSUPP);
}
if (SCARG(uap, oldlenp) &&
(error = copyin(SCARG(uap, oldlenp), &oldlen, sizeof(oldlen))))
return (error);
if (SCARG(uap, old) != NULL) {
if ((error = lockmgr(&sysctl_lock, LK_EXCLUSIVE, NULL, p)) != 0)
return (error);
if (dolock) {
error = uvm_vslock(p, SCARG(uap, old), oldlen,
VM_PROT_READ|VM_PROT_WRITE);
if (error) {
lockmgr(&sysctl_lock, LK_RELEASE, NULL, p);
return (error);
}
}
savelen = oldlen;
}
error = (*fn)(&name[1], SCARG(uap, namelen) - 1, SCARG(uap, old),
&oldlen, SCARG(uap, new), SCARG(uap, newlen), p);
if (SCARG(uap, old) != NULL) {
if (dolock)
uvm_vsunlock(p, SCARG(uap, old), savelen);
lockmgr(&sysctl_lock, LK_RELEASE, NULL, p);
}
if (error)
return (error);
if (SCARG(uap, oldlenp))
error = copyout(&oldlen, SCARG(uap, oldlenp), sizeof(oldlen));
return (error);
}
/*
* Attributes stored in the kernel.
*/
char hostname[MAXHOSTNAMELEN];
int hostnamelen;
char domainname[MAXHOSTNAMELEN];
int domainnamelen;
long hostid;
char *disknames = NULL;
struct diskstats *diskstats = NULL;
#ifdef INSECURE
int securelevel = -1;
#else
int securelevel;
#endif
/*
* kernel related system variables.
*/
int
kern_sysctl(name, namelen, oldp, oldlenp, newp, newlen, p)
int *name;
u_int namelen;
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
struct proc *p;
{
int error, level, inthostid, stackgap;
extern int somaxconn, sominconn;
extern int usermount, nosuidcoredump;
extern long cp_time[CPUSTATES];
extern int stackgap_random;
#ifdef CRYPTO
extern int usercrypto;
extern int userasymcrypto;
extern int cryptodevallowsoft;
#endif
/* all sysctl names at this level are terminal except a ton of them */
if (namelen != 1) {
switch (name[0]) {
case KERN_PROC:
case KERN_PROC2:
case KERN_PROF:
case KERN_MALLOCSTATS:
case KERN_TTY:
case KERN_POOL:
case KERN_PROC_ARGS:
case KERN_SYSVIPC_INFO:
case KERN_SEMINFO:
case KERN_SHMINFO:
case KERN_INTRCNT:
case KERN_WATCHDOG:
case KERN_EMUL:
break;
default:
return (ENOTDIR); /* overloaded */
}
}
switch (name[0]) {
case KERN_OSTYPE:
return (sysctl_rdstring(oldp, oldlenp, newp, ostype));
case KERN_OSRELEASE:
return (sysctl_rdstring(oldp, oldlenp, newp, osrelease));
case KERN_OSREV:
return (sysctl_rdint(oldp, oldlenp, newp, OpenBSD));
case KERN_OSVERSION:
return (sysctl_rdstring(oldp, oldlenp, newp, osversion));
case KERN_VERSION:
return (sysctl_rdstring(oldp, oldlenp, newp, version));
case KERN_MAXVNODES:
return(sysctl_int(oldp, oldlenp, newp, newlen, &desiredvnodes));
case KERN_MAXPROC:
return (sysctl_int(oldp, oldlenp, newp, newlen, &maxproc));
case KERN_MAXFILES:
return (sysctl_int(oldp, oldlenp, newp, newlen, &maxfiles));
case KERN_NFILES:
return (sysctl_rdint(oldp, oldlenp, newp, nfiles));
case KERN_TTYCOUNT:
return (sysctl_rdint(oldp, oldlenp, newp, tty_count));
case KERN_NUMVNODES:
return (sysctl_rdint(oldp, oldlenp, newp, numvnodes));
case KERN_ARGMAX:
return (sysctl_rdint(oldp, oldlenp, newp, ARG_MAX));
case KERN_NSELCOLL:
return (sysctl_rdint(oldp, oldlenp, newp, nselcoll));
case KERN_SECURELVL:
level = securelevel;
if ((error = sysctl_int(oldp, oldlenp, newp, newlen, &level)) ||
newp == NULL)
return (error);
if ((securelevel > 0 || level < -1) &&
level < securelevel && p->p_pid != 1)
return (EPERM);
securelevel = level;
return (0);
case KERN_HOSTNAME:
error = sysctl_tstring(oldp, oldlenp, newp, newlen,
hostname, sizeof(hostname));
if (newp && !error)
hostnamelen = newlen;
return (error);
case KERN_DOMAINNAME:
error = sysctl_tstring(oldp, oldlenp, newp, newlen,
domainname, sizeof(domainname));
if (newp && !error)
domainnamelen = newlen;
return (error);
case KERN_HOSTID:
inthostid = hostid; /* XXX assumes sizeof long <= sizeof int */
error = sysctl_int(oldp, oldlenp, newp, newlen, &inthostid);
hostid = inthostid;
return (error);
case KERN_CLOCKRATE:
return (sysctl_clockrate(oldp, oldlenp));
case KERN_BOOTTIME:
return (sysctl_rdstruct(oldp, oldlenp, newp, &boottime,
sizeof(struct timeval)));
case KERN_VNODE:
return (sysctl_vnode(oldp, oldlenp, p));
case KERN_PROC:
case KERN_PROC2:
return (sysctl_doproc(name, namelen, oldp, oldlenp));
case KERN_PROC_ARGS:
return (sysctl_proc_args(name + 1, namelen - 1, oldp, oldlenp,
p));
case KERN_FILE:
return (sysctl_file(oldp, oldlenp));
case KERN_MBSTAT:
return (sysctl_rdstruct(oldp, oldlenp, newp, &mbstat,
sizeof(mbstat)));
#ifdef GPROF
case KERN_PROF:
return (sysctl_doprof(name + 1, namelen - 1, oldp, oldlenp,
newp, newlen));
#endif
case KERN_POSIX1:
return (sysctl_rdint(oldp, oldlenp, newp, _POSIX_VERSION));
case KERN_NGROUPS:
return (sysctl_rdint(oldp, oldlenp, newp, NGROUPS_MAX));
case KERN_JOB_CONTROL:
return (sysctl_rdint(oldp, oldlenp, newp, 1));
case KERN_SAVED_IDS:
#ifdef _POSIX_SAVED_IDS
return (sysctl_rdint(oldp, oldlenp, newp, 1));
#else
return (sysctl_rdint(oldp, oldlenp, newp, 0));
#endif
case KERN_MAXPARTITIONS:
return (sysctl_rdint(oldp, oldlenp, newp, MAXPARTITIONS));
case KERN_RAWPARTITION:
return (sysctl_rdint(oldp, oldlenp, newp, RAW_PART));
case KERN_SOMAXCONN:
return (sysctl_int(oldp, oldlenp, newp, newlen, &somaxconn));
case KERN_SOMINCONN:
return (sysctl_int(oldp, oldlenp, newp, newlen, &sominconn));
case KERN_USERMOUNT:
return (sysctl_int(oldp, oldlenp, newp, newlen, &usermount));
case KERN_RND:
return (sysctl_rdstruct(oldp, oldlenp, newp, &rndstats,
sizeof(rndstats)));
case KERN_ARND:
return (sysctl_rdint(oldp, oldlenp, newp, arc4random()));
case KERN_NOSUIDCOREDUMP:
return (sysctl_int(oldp, oldlenp, newp, newlen, &nosuidcoredump));
case KERN_FSYNC:
return (sysctl_rdint(oldp, oldlenp, newp, 1));
case KERN_SYSVMSG:
#ifdef SYSVMSG
return (sysctl_rdint(oldp, oldlenp, newp, 1));
#else
return (sysctl_rdint(oldp, oldlenp, newp, 0));
#endif
case KERN_SYSVSEM:
#ifdef SYSVSEM
return (sysctl_rdint(oldp, oldlenp, newp, 1));
#else
return (sysctl_rdint(oldp, oldlenp, newp, 0));
#endif
case KERN_SYSVSHM:
#ifdef SYSVSHM
return (sysctl_rdint(oldp, oldlenp, newp, 1));
#else
return (sysctl_rdint(oldp, oldlenp, newp, 0));
#endif
case KERN_MSGBUFSIZE:
/*
* deal with cases where the message buffer has
* become corrupted.
*/
if (!msgbufp || msgbufp->msg_magic != MSG_MAGIC)
return (ENXIO);
return (sysctl_rdint(oldp, oldlenp, newp, msgbufp->msg_bufs));
case KERN_MSGBUF:
/* see note above */
if (!msgbufp || msgbufp->msg_magic != MSG_MAGIC)
return (ENXIO);
return (sysctl_rdstruct(oldp, oldlenp, newp, msgbufp,
msgbufp->msg_bufs + offsetof(struct msgbuf, msg_bufc)));
case KERN_MALLOCSTATS:
return (sysctl_malloc(name + 1, namelen - 1, oldp, oldlenp,
newp, newlen, p));
case KERN_CPTIME:
return (sysctl_rdstruct(oldp, oldlenp, newp, &cp_time,
sizeof(cp_time)));
case KERN_NCHSTATS:
return (sysctl_rdstruct(oldp, oldlenp, newp, &nchstats,
sizeof(struct nchstats)));
case KERN_FORKSTAT:
return (sysctl_rdstruct(oldp, oldlenp, newp, &forkstat,
sizeof(struct forkstat)));
case KERN_TTY:
return (sysctl_tty(name + 1, namelen - 1, oldp, oldlenp,
newp, newlen));
case KERN_FSCALE:
return (sysctl_rdint(oldp, oldlenp, newp, fscale));
case KERN_CCPU:
return (sysctl_rdint(oldp, oldlenp, newp, ccpu));
case KERN_NPROCS:
return (sysctl_rdint(oldp, oldlenp, newp, nprocs));
case KERN_POOL:
return (sysctl_dopool(name + 1, namelen - 1, oldp, oldlenp));
case KERN_STACKGAPRANDOM:
stackgap = stackgap_random;
error = sysctl_int(oldp, oldlenp, newp, newlen, &stackgap);
if (error)
return (error);
/*
* Safety harness.
*/
if ((stackgap < ALIGNBYTES && stackgap != 0) ||
!powerof2(stackgap) || stackgap >= 256 * 1024 * 1024)
return (EINVAL);
stackgap_random = stackgap;
return (0);
#if defined(SYSVMSG) || defined(SYSVSEM) || defined(SYSVSHM)
case KERN_SYSVIPC_INFO:
return (sysctl_sysvipc(name + 1, namelen - 1, oldp, oldlenp));
#endif
#ifdef CRYPTO
case KERN_USERCRYPTO:
return (sysctl_int(oldp, oldlenp, newp, newlen, &usercrypto));
case KERN_USERASYMCRYPTO:
return (sysctl_int(oldp, oldlenp, newp, newlen,
&userasymcrypto));
case KERN_CRYPTODEVALLOWSOFT:
return (sysctl_int(oldp, oldlenp, newp, newlen,
&cryptodevallowsoft));
#endif
case KERN_SPLASSERT:
return (sysctl_int(oldp, oldlenp, newp, newlen,
&splassert_ctl));
#ifdef SYSVSEM
case KERN_SEMINFO:
return (sysctl_sysvsem(name + 1, namelen - 1, oldp, oldlenp,
newp, newlen));
#endif
#ifdef SYSVSHM
case KERN_SHMINFO:
return (sysctl_sysvshm(name + 1, namelen - 1, oldp, oldlenp,
newp, newlen));
#endif
case KERN_INTRCNT:
return (sysctl_intrcnt(name + 1, namelen - 1, oldp, oldlenp));
#ifndef SMALL_KERNEL
case KERN_WATCHDOG:
return (sysctl_wdog(name + 1, namelen - 1, oldp, oldlenp,
newp, newlen));
#endif
case KERN_EMUL:
return (sysctl_emul(name + 1, namelen - 1, oldp, oldlenp,
newp, newlen));
default:
return (EOPNOTSUPP);
}
/* NOTREACHED */
}
/*
* hardware related system variables.
*/
int
hw_sysctl(name, namelen, oldp, oldlenp, newp, newlen, p)
int *name;
u_int namelen;
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
struct proc *p;
{
extern char machine[], cpu_model[];
int err;
int cpuspeed;
static int perflevel = 100;
int operflevel;
/* all sysctl names at this level except sensors are terminal */
if (name[0] != HW_SENSORS && namelen != 1)
return (ENOTDIR); /* overloaded */
switch (name[0]) {
case HW_MACHINE:
return (sysctl_rdstring(oldp, oldlenp, newp, machine));
case HW_MODEL:
return (sysctl_rdstring(oldp, oldlenp, newp, cpu_model));
case HW_NCPU:
return (sysctl_rdint(oldp, oldlenp, newp, 1)); /* XXX */
case HW_BYTEORDER:
return (sysctl_rdint(oldp, oldlenp, newp, BYTE_ORDER));
case HW_PHYSMEM:
return (sysctl_rdint(oldp, oldlenp, newp, ctob(physmem)));
case HW_USERMEM:
return (sysctl_rdint(oldp, oldlenp, newp,
ctob(physmem - uvmexp.wired)));
case HW_PAGESIZE:
return (sysctl_rdint(oldp, oldlenp, newp, PAGE_SIZE));
case HW_DISKNAMES:
err = sysctl_diskinit(0, p);
if (err)
return err;
if (disknames)
return (sysctl_rdstring(oldp, oldlenp, newp,
disknames));
else
return (sysctl_rdstring(oldp, oldlenp, newp, ""));
case HW_DISKSTATS:
err = sysctl_diskinit(1, p);
if (err)
return err;
return (sysctl_rdstruct(oldp, oldlenp, newp, diskstats,
disk_count * sizeof(struct diskstats)));
case HW_DISKCOUNT:
return (sysctl_rdint(oldp, oldlenp, newp, disk_count));
case HW_SENSORS:
return (sysctl_sensors(name + 1, namelen - 1, oldp, oldlenp,
newp, newlen));
case HW_CPUSPEED:
if (!cpu_cpuspeed)
return (EOPNOTSUPP);
err = cpu_cpuspeed(&cpuspeed);
if (err)
return err;
return (sysctl_rdint(oldp, oldlenp, newp, cpuspeed));
case HW_SETPERF:
if (!cpu_setperf)
return (EOPNOTSUPP);
operflevel = perflevel;
err = sysctl_int(oldp, oldlenp, newp, newlen, &perflevel);
if (err)
return err;
if (perflevel == operflevel)
return (0);
if (perflevel > 100)
perflevel = 100;
if (perflevel < 0)
perflevel = 0;
return (cpu_setperf(perflevel));
default:
return (EOPNOTSUPP);
}
/* NOTREACHED */
}
#ifdef DEBUG
/*
* Debugging related system variables.
*/
extern struct ctldebug debug0, debug1;
struct ctldebug debug2, debug3, debug4;
struct ctldebug debug5, debug6, debug7, debug8, debug9;
struct ctldebug debug10, debug11, debug12, debug13, debug14;
struct ctldebug debug15, debug16, debug17, debug18, debug19;
static struct ctldebug *debugvars[CTL_DEBUG_MAXID] = {
&debug0, &debug1, &debug2, &debug3, &debug4,
&debug5, &debug6, &debug7, &debug8, &debug9,
&debug10, &debug11, &debug12, &debug13, &debug14,
&debug15, &debug16, &debug17, &debug18, &debug19,
};
int
debug_sysctl(name, namelen, oldp, oldlenp, newp, newlen, p)
int *name;
u_int namelen;
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
struct proc *p;
{
struct ctldebug *cdp;
/* all sysctl names at this level are name and field */
if (namelen != 2)
return (ENOTDIR); /* overloaded */
cdp = debugvars[name[0]];
if (cdp->debugname == 0)
return (EOPNOTSUPP);
switch (name[1]) {
case CTL_DEBUG_NAME:
return (sysctl_rdstring(oldp, oldlenp, newp, cdp->debugname));
case CTL_DEBUG_VALUE:
return (sysctl_int(oldp, oldlenp, newp, newlen, cdp->debugvar));
default:
return (EOPNOTSUPP);
}
/* NOTREACHED */
}
#endif /* DEBUG */
/*
* Validate parameters and get old / set new parameters
* for an integer-valued sysctl function.
*/
int
sysctl_int(oldp, oldlenp, newp, newlen, valp)
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
int *valp;
{
int error = 0;
if (oldp && *oldlenp < sizeof(int))
return (ENOMEM);
if (newp && newlen != sizeof(int))
return (EINVAL);
*oldlenp = sizeof(int);
if (oldp)
error = copyout(valp, oldp, sizeof(int));
if (error == 0 && newp)
error = copyin(newp, valp, sizeof(int));
return (error);
}
/*
* As above, but read-only.
*/
int
sysctl_rdint(oldp, oldlenp, newp, val)
void *oldp;
size_t *oldlenp;
void *newp;
int val;
{
int error = 0;
if (oldp && *oldlenp < sizeof(int))
return (ENOMEM);
if (newp)
return (EPERM);
*oldlenp = sizeof(int);
if (oldp)
error = copyout((caddr_t)&val, oldp, sizeof(int));
return (error);
}
/*
* Array of integer values.
*/
int
sysctl_int_arr(valpp, name, namelen, oldp, oldlenp, newp, newlen)
int **valpp;
int *name;
u_int namelen;
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
{
if (namelen > 1)
return (ENOTDIR);
if (name[0] < 0 || valpp[name[0]] == NULL)
return (EOPNOTSUPP);
return (sysctl_int(oldp, oldlenp, newp, newlen, valpp[name[0]]));
}
/*
* Validate parameters and get old / set new parameters
* for an integer-valued sysctl function.
*/
int
sysctl_quad(oldp, oldlenp, newp, newlen, valp)
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
int64_t *valp;
{
int error = 0;
if (oldp && *oldlenp < sizeof(int64_t))
return (ENOMEM);
if (newp && newlen != sizeof(int64_t))
return (EINVAL);
*oldlenp = sizeof(int64_t);
if (oldp)
error = copyout(valp, oldp, sizeof(int64_t));
if (error == 0 && newp)
error = copyin(newp, valp, sizeof(int64_t));
return (error);
}
/*
* As above, but read-only.
*/
int
sysctl_rdquad(oldp, oldlenp, newp, val)
void *oldp;
size_t *oldlenp;
void *newp;
int64_t val;
{
int error = 0;
if (oldp && *oldlenp < sizeof(int64_t))
return (ENOMEM);
if (newp)
return (EPERM);
*oldlenp = sizeof(int64_t);
if (oldp)
error = copyout((caddr_t)&val, oldp, sizeof(int64_t));
return (error);
}
/*
* Validate parameters and get old / set new parameters
* for a string-valued sysctl function.
*/
int
sysctl_string(oldp, oldlenp, newp, newlen, str, maxlen)
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
char *str;
int maxlen;
{
return sysctl__string(oldp, oldlenp, newp, newlen, str, maxlen, 0);
}
int
sysctl_tstring(oldp, oldlenp, newp, newlen, str, maxlen)
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
char *str;
int maxlen;
{
return sysctl__string(oldp, oldlenp, newp, newlen, str, maxlen, 1);
}
int
sysctl__string(oldp, oldlenp, newp, newlen, str, maxlen, trunc)
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
char *str;
int maxlen;
int trunc;
{
int len, error = 0;
char c;
len = strlen(str) + 1;
if (oldp && *oldlenp < len) {
if (trunc == 0 || *oldlenp == 0)
return (ENOMEM);
}
if (newp && newlen >= maxlen)
return (EINVAL);
if (oldp) {
if (trunc && *oldlenp < len) {
/* save & zap NUL terminator while copying */
c = str[*oldlenp-1];
str[*oldlenp-1] = '\0';
error = copyout(str, oldp, *oldlenp);
str[*oldlenp-1] = c;
} else {
*oldlenp = len;
error = copyout(str, oldp, len);
}
}
if (error == 0 && newp) {
error = copyin(newp, str, newlen);
str[newlen] = 0;
}
return (error);
}
/*
* As above, but read-only.
*/
int
sysctl_rdstring(oldp, oldlenp, newp, str)
void *oldp;
size_t *oldlenp;
void *newp;
const char *str;
{
int len, error = 0;
len = strlen(str) + 1;
if (oldp && *oldlenp < len)
return (ENOMEM);
if (newp)
return (EPERM);
*oldlenp = len;
if (oldp)
error = copyout(str, oldp, len);
return (error);
}
/*
* Validate parameters and get old / set new parameters
* for a structure oriented sysctl function.
*/
int
sysctl_struct(oldp, oldlenp, newp, newlen, sp, len)
void *oldp;
size_t *oldlenp;
void *newp;
size_t newlen;
void *sp;
int len;
{
int error = 0;
if (oldp && *oldlenp < len)
return (ENOMEM);
if (newp && newlen > len)
return (EINVAL);
if (oldp) {
*oldlenp = len;
error = copyout(sp, oldp, len);
}
if (error == 0 && newp)
error = copyin(newp, sp, len);
return (error);
}
/*
* Validate parameters and get old parameters
* for a structure oriented sysctl function.
*/
int
sysctl_rdstruct(oldp, oldlenp, newp, sp, len)
void *oldp;
size_t *oldlenp;
void *newp;
const void *sp;
int len;
{
int error = 0;
if (oldp && *oldlenp < len)
return (ENOMEM);
if (newp)
return (EPERM);
*oldlenp = len;
if (oldp)
error = copyout(sp, oldp, len);
return (error);
}
/*
* Get file structures.
*/
int
sysctl_file(where, sizep)
char *where;
size_t *sizep;
{
int buflen, error;
struct file *fp;
char *start = where;
buflen = *sizep;
if (where == NULL) {
/*
* overestimate by 10 files
*/
*sizep = sizeof(filehead) + (nfiles + 10) * sizeof(struct file);
return (0);
}
/*
* first copyout filehead
*/
if (buflen < sizeof(filehead)) {
*sizep = 0;
return (0);
}
error = copyout((caddr_t)&filehead, where, sizeof(filehead));
if (error)
return (error);
buflen -= sizeof(filehead);
where += sizeof(filehead);
/*
* followed by an array of file structures
*/
LIST_FOREACH(fp, &filehead, f_list) {
if (buflen < sizeof(struct file)) {
*sizep = where - start;
return (ENOMEM);
}
error = copyout((caddr_t)fp, where, sizeof (struct file));
if (error)
return (error);
buflen -= sizeof(struct file);
where += sizeof(struct file);
}
*sizep = where - start;
return (0);
}
/*
* try over estimating by 5 procs
*/
#define KERN_PROCSLOP (5 * sizeof (struct kinfo_proc))
int
sysctl_doproc(name, namelen, where, sizep)
int *name;
u_int namelen;
char *where;
size_t *sizep;
{
struct kinfo_proc2 kproc2;
struct eproc eproc;
struct proc *p;
char *dp;
int arg, buflen, doingzomb, elem_size, elem_count;
int error, needed, type, op;
dp = where;
buflen = where != NULL ? *sizep : 0;
needed = error = 0;
type = name[0];
if (type == KERN_PROC) {
if (namelen != 3 && !(namelen == 2 &&
(name[1] == KERN_PROC_ALL || name[1] == KERN_PROC_KTHREAD)))
return (EINVAL);
op = name[1];
arg = op == KERN_PROC_ALL ? 0 : name[2];
elem_size = elem_count = 0;
} else /* if (type == KERN_PROC2) */ {
if (namelen != 5 || name[3] < 0 || name[4] < 0)
return (EINVAL);
op = name[1];
arg = name[2];
elem_size = name[3];
elem_count = name[4];
}
p = LIST_FIRST(&allproc);
doingzomb = 0;
again:
for (; p != 0; p = LIST_NEXT(p, p_list)) {
/*
* Skip embryonic processes.
*/
if (p->p_stat == SIDL)
continue;
/*
* TODO - make more efficient (see notes below).
*/
switch (op) {
case KERN_PROC_PID:
/* could do this with just a lookup */
if (p->p_pid != (pid_t)arg)
continue;
break;
case KERN_PROC_PGRP:
/* could do this by traversing pgrp */
if (p->p_pgrp->pg_id != (pid_t)arg)
continue;
break;
case KERN_PROC_SESSION:
if (p->p_session->s_leader == NULL ||
p->p_session->s_leader->p_pid != (pid_t)arg)
continue;
break;
case KERN_PROC_TTY:
if ((p->p_flag & P_CONTROLT) == 0 ||
p->p_session->s_ttyp == NULL ||
p->p_session->s_ttyp->t_dev != (dev_t)arg)
continue;
break;
case KERN_PROC_UID:
if (p->p_ucred->cr_uid != (uid_t)arg)
continue;
break;
case KERN_PROC_RUID:
if (p->p_cred->p_ruid != (uid_t)arg)
continue;
break;
case KERN_PROC_ALL:
if (p->p_flag & P_SYSTEM)
continue;
break;
case KERN_PROC_KTHREAD:
/* no filtering */
break;
default:
return (EINVAL);
}
if (type == KERN_PROC) {
if (buflen >= sizeof(struct kinfo_proc)) {
fill_eproc(p, &eproc);
error = copyout((caddr_t)p,
&((struct kinfo_proc *)dp)->kp_proc,
sizeof(struct proc));
if (error)
return (error);
error = copyout((caddr_t)&eproc,
&((struct kinfo_proc *)dp)->kp_eproc,
sizeof(eproc));
if (error)
return (error);
dp += sizeof(struct kinfo_proc);
buflen -= sizeof(struct kinfo_proc);
}
needed += sizeof(struct kinfo_proc);
} else /* if (type == KERN_PROC2) */ {
if (buflen >= elem_size && elem_count > 0) {
fill_kproc2(p, &kproc2);
/*
* Copy out elem_size, but not larger than
* the size of a struct kinfo_proc2.
*/
error = copyout(&kproc2, dp,
min(sizeof(kproc2), elem_size));
if (error)
return (error);
dp += elem_size;
buflen -= elem_size;
elem_count--;
}
needed += elem_size;
}
}
if (doingzomb == 0) {
p = LIST_FIRST(&zombproc);
doingzomb++;
goto again;
}
if (where != NULL) {
*sizep = dp - where;
if (needed > *sizep)
return (ENOMEM);
} else {
needed += KERN_PROCSLOP;
*sizep = needed;
}
return (0);
}
/*
* Fill in an eproc structure for the specified process.
*/
void
fill_eproc(struct proc *p, struct eproc *ep)
{
struct tty *tp;
ep->e_paddr = p;
ep->e_sess = p->p_pgrp->pg_session;
ep->e_pcred = *p->p_cred;
ep->e_ucred = *p->p_ucred;
if (p->p_stat == SIDL || P_ZOMBIE(p)) {
ep->e_vm.vm_rssize = 0;
ep->e_vm.vm_tsize = 0;
ep->e_vm.vm_dsize = 0;
ep->e_vm.vm_ssize = 0;
bzero(&ep->e_pstats, sizeof(ep->e_pstats));
ep->e_pstats_valid = 0;
} else {
struct vmspace *vm = p->p_vmspace;
PHOLD(p); /* need for pstats */
ep->e_vm.vm_rssize = vm_resident_count(vm);
ep->e_vm.vm_tsize = vm->vm_tsize;
ep->e_vm.vm_dsize = vm->vm_dsize;
ep->e_vm.vm_ssize = vm->vm_ssize;
ep->e_pstats = *p->p_stats;
ep->e_pstats_valid = 1;
PRELE(p);
}
if (p->p_pptr)
ep->e_ppid = p->p_pptr->p_pid;
else
ep->e_ppid = 0;
ep->e_pgid = p->p_pgrp->pg_id;
ep->e_jobc = p->p_pgrp->pg_jobc;
if ((p->p_flag & P_CONTROLT) &&
(tp = ep->e_sess->s_ttyp)) {
ep->e_tdev = tp->t_dev;
ep->e_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
ep->e_tsess = tp->t_session;
} else
ep->e_tdev = NODEV;
ep->e_flag = ep->e_sess->s_ttyvp ? EPROC_CTTY : 0;
if (SESS_LEADER(p))
ep->e_flag |= EPROC_SLEADER;
strncpy(ep->e_wmesg, p->p_wmesg ? p->p_wmesg : "", WMESGLEN);
ep->e_wmesg[WMESGLEN] = '\0';
ep->e_xsize = ep->e_xrssize = 0;
ep->e_xccount = ep->e_xswrss = 0;
strncpy(ep->e_login, ep->e_sess->s_login, MAXLOGNAME-1);
ep->e_login[MAXLOGNAME-1] = '\0';
strncpy(ep->e_emul, p->p_emul->e_name, EMULNAMELEN);
ep->e_emul[EMULNAMELEN] = '\0';
ep->e_maxrss = p->p_rlimit ? p->p_rlimit[RLIMIT_RSS].rlim_cur : 0;
}
/*
* Fill in a kproc2 structure for the specified process.
*/
void
fill_kproc2(struct proc *p, struct kinfo_proc2 *ki)
{
struct tty *tp;
struct timeval ut, st;
bzero(ki, sizeof(*ki));
ki->p_paddr = PTRTOINT64(p);
ki->p_fd = PTRTOINT64(p->p_fd);
ki->p_stats = PTRTOINT64(p->p_stats);
ki->p_limit = PTRTOINT64(p->p_limit);
ki->p_vmspace = PTRTOINT64(p->p_vmspace);
ki->p_sigacts = PTRTOINT64(p->p_sigacts);
ki->p_sess = PTRTOINT64(p->p_session);
ki->p_tsess = 0; /* may be changed if controlling tty below */
ki->p_ru = PTRTOINT64(p->p_ru);
ki->p_eflag = 0;
ki->p_exitsig = p->p_exitsig;
ki->p_flag = p->p_flag;
ki->p_pid = p->p_pid;
if (p->p_pptr)
ki->p_ppid = p->p_pptr->p_pid;
else
ki->p_ppid = 0;
if (p->p_session->s_leader)
ki->p_sid = p->p_session->s_leader->p_pid;
else
ki->p_sid = 0;
ki->p__pgid = p->p_pgrp->pg_id;
ki->p_tpgid = -1; /* may be changed if controlling tty below */
ki->p_uid = p->p_ucred->cr_uid;
ki->p_ruid = p->p_cred->p_ruid;
ki->p_gid = p->p_ucred->cr_gid;
ki->p_rgid = p->p_cred->p_rgid;
ki->p_svuid = p->p_cred->p_svuid;
ki->p_svgid = p->p_cred->p_svgid;
memcpy(ki->p_groups, p->p_cred->pc_ucred->cr_groups,
min(sizeof(ki->p_groups), sizeof(p->p_cred->pc_ucred->cr_groups)));
ki->p_ngroups = p->p_cred->pc_ucred->cr_ngroups;
ki->p_jobc = p->p_pgrp->pg_jobc;
if ((p->p_flag & P_CONTROLT) && (tp = p->p_session->s_ttyp)) {
ki->p_tdev = tp->t_dev;
ki->p_tpgid = tp->t_pgrp ? tp->t_pgrp->pg_id : -1;
ki->p_tsess = PTRTOINT64(tp->t_session);
} else {
ki->p_tdev = NODEV;
}
ki->p_estcpu = p->p_estcpu;
ki->p_rtime_sec = p->p_rtime.tv_sec;
ki->p_rtime_usec = p->p_rtime.tv_usec;
ki->p_cpticks = p->p_cpticks;
ki->p_pctcpu = p->p_pctcpu;
ki->p_uticks = p->p_uticks;
ki->p_sticks = p->p_sticks;
ki->p_iticks = p->p_iticks;
ki->p_tracep = PTRTOINT64(p->p_tracep);
ki->p_traceflag = p->p_traceflag;
ki->p_siglist = p->p_siglist;
ki->p_sigmask = p->p_sigmask;
ki->p_sigignore = p->p_sigignore;
ki->p_sigcatch = p->p_sigcatch;
ki->p_stat = p->p_stat;
ki->p_nice = p->p_nice;
ki->p_xstat = p->p_xstat;
ki->p_acflag = p->p_acflag;
strlcpy(ki->p_emul, p->p_emul->e_name, sizeof(ki->p_emul));
strlcpy(ki->p_comm, p->p_comm, sizeof(ki->p_comm));
strncpy(ki->p_login, p->p_session->s_login,
min(sizeof(ki->p_login) - 1, sizeof(p->p_session->s_login)));
if (p->p_stat == SIDL || P_ZOMBIE(p)) {
ki->p_vm_rssize = 0;
ki->p_vm_tsize = 0;
ki->p_vm_dsize = 0;
ki->p_vm_ssize = 0;
} else {
struct vmspace *vm = p->p_vmspace;
ki->p_vm_rssize = vm_resident_count(vm);
ki->p_vm_tsize = vm->vm_tsize;
ki->p_vm_dsize = vm->vm_dsize;
ki->p_vm_ssize = vm->vm_ssize;
ki->p_forw = PTRTOINT64(p->p_forw);
ki->p_back = PTRTOINT64(p->p_back);
ki->p_addr = PTRTOINT64(p->p_addr);
ki->p_stat = p->p_stat;
ki->p_swtime = p->p_swtime;
ki->p_slptime = p->p_slptime;
ki->p_schedflags = p->p_schedflags;
ki->p_holdcnt = p->p_holdcnt;
ki->p_priority = p->p_priority;
ki->p_usrpri = p->p_usrpri;
if (p->p_wmesg)
strlcpy(ki->p_wmesg, p->p_wmesg, sizeof(ki->p_wmesg));
ki->p_wchan = PTRTOINT64(p->p_wchan);
}
if (p->p_session->s_ttyvp)
ki->p_eflag |= EPROC_CTTY;
if (SESS_LEADER(p))
ki->p_eflag |= EPROC_SLEADER;
if (p->p_rlimit)
ki->p_rlim_rss_cur = p->p_rlimit[RLIMIT_RSS].rlim_cur;
/* XXX Is this double check necessary? */
if (P_ZOMBIE(p)) {
ki->p_uvalid = 0;
} else {
ki->p_uvalid = 1;
PHOLD(p); /* need for pstats */
ki->p_ustart_sec = p->p_stats->p_start.tv_sec;
ki->p_ustart_usec = p->p_stats->p_start.tv_usec;
calcru(p, &ut, &st, 0);
ki->p_uutime_sec = ut.tv_sec;
ki->p_uutime_usec = ut.tv_usec;
ki->p_ustime_sec = st.tv_sec;
ki->p_ustime_usec = st.tv_usec;
ki->p_uru_maxrss = p->p_stats->p_ru.ru_maxrss;
ki->p_uru_ixrss = p->p_stats->p_ru.ru_ixrss;
ki->p_uru_idrss = p->p_stats->p_ru.ru_idrss;
ki->p_uru_isrss = p->p_stats->p_ru.ru_isrss;
ki->p_uru_minflt = p->p_stats->p_ru.ru_minflt;
ki->p_uru_majflt = p->p_stats->p_ru.ru_majflt;
ki->p_uru_nswap = p->p_stats->p_ru.ru_nswap;
ki->p_uru_inblock = p->p_stats->p_ru.ru_inblock;
ki->p_uru_oublock = p->p_stats->p_ru.ru_oublock;
ki->p_uru_msgsnd = p->p_stats->p_ru.ru_msgsnd;
ki->p_uru_msgrcv = p->p_stats->p_ru.ru_msgrcv;
ki->p_uru_nsignals = p->p_stats->p_ru.ru_nsignals;
ki->p_uru_nvcsw = p->p_stats->p_ru.ru_nvcsw;
ki->p_uru_nivcsw = p->p_stats->p_ru.ru_nivcsw;
timeradd(&p->p_stats->p_cru.ru_utime,
&p->p_stats->p_cru.ru_stime, &ut);
ki->p_uctime_sec = ut.tv_sec;
ki->p_uctime_usec = ut.tv_usec;
PRELE(p);
}
}
int
sysctl_proc_args(int *name, u_int namelen, void *oldp, size_t *oldlenp,
struct proc *cp)
{
struct proc *vp;
pid_t pid;
int op;
struct ps_strings pss;
struct iovec iov;
struct uio uio;
int error;
size_t limit;
int cnt;
char **rargv, **vargv; /* reader vs. victim */
char *rarg, *varg;
char *buf;
if (namelen > 2)
return (ENOTDIR);
if (namelen < 2)
return (EINVAL);
pid = name[0];
op = name[1];
switch (op) {
case KERN_PROC_ARGV:
case KERN_PROC_NARGV:
case KERN_PROC_ENV:
case KERN_PROC_NENV:
break;
default:
return (EOPNOTSUPP);
}
if ((vp = pfind(pid)) == NULL)
return (ESRCH);
if (P_ZOMBIE(vp) || (vp->p_flag & P_SYSTEM))
return (EINVAL);
/* Exiting - don't bother, it will be gone soon anyway */
if ((vp->p_flag & P_WEXIT))
return (ESRCH);
/* Execing - danger. */
if ((vp->p_flag & P_INEXEC))
return (EBUSY);
vp->p_vmspace->vm_refcnt++; /* XXX */
buf = malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
iov.iov_base = &pss;
iov.iov_len = sizeof(pss);
uio.uio_iov = &iov;
uio.uio_iovcnt = 1;
uio.uio_offset = (off_t)PS_STRINGS;
uio.uio_resid = sizeof(pss);
uio.uio_segflg = UIO_SYSSPACE;
uio.uio_rw = UIO_READ;
uio.uio_procp = cp;
if ((error = uvm_io(&vp->p_vmspace->vm_map, &uio)) != 0)
goto out;
if (op == KERN_PROC_NARGV) {
error = sysctl_rdint(oldp, oldlenp, NULL, pss.ps_nargvstr);
goto out;
}
if (op == KERN_PROC_NENV) {
error = sysctl_rdint(oldp, oldlenp, NULL, pss.ps_nenvstr);
goto out;
}
if (op == KERN_PROC_ARGV) {
cnt = pss.ps_nargvstr;
vargv = pss.ps_argvstr;
} else {
cnt = pss.ps_nenvstr;
vargv = pss.ps_envstr;
}
/* -1 to have space for a terminating NUL */
limit = *oldlenp - 1;
*oldlenp = 0;
if (limit > 8 * PAGE_SIZE) {
/* Don't allow a denial of service. */
error = E2BIG;
goto out;
}
rargv = oldp;
/*
* *oldlenp - number of bytes copied out into readers buffer.
* limit - maximal number of bytes allowed into readers buffer.
* rarg - pointer into readers buffer where next arg will be stored.
* rargv - pointer into readers buffer where the next rarg pointer
* will be stored.
* vargv - pointer into victim address space where the next argument
* will be read.
*/
/* space for cnt pointers and a NULL */
rarg = (char *)(rargv + cnt + 1);
*oldlenp += (cnt + 1) * sizeof(char **);
while (cnt > 0 && *oldlenp < limit) {
size_t len, vstrlen;
/* Write to readers argv */
if ((error = copyout(&rarg, rargv, sizeof(rarg))) != 0)
goto out;
/* read the victim argv */
iov.iov_base = &varg;
iov.iov_len = sizeof(varg);
uio.uio_iov = &iov;
uio.uio_iovcnt = 1;
uio.uio_offset = (off_t)(vaddr_t)vargv;
uio.uio_resid = sizeof(varg);
uio.uio_segflg = UIO_SYSSPACE;
uio.uio_rw = UIO_READ;
uio.uio_procp = cp;
if ((error = uvm_io(&vp->p_vmspace->vm_map, &uio)) != 0)
goto out;
if (varg == NULL)
break;
/*
* read the victim arg. We must jump through hoops to avoid
* crossing a page boundary too much and returning an error.
*/
more:
len = PAGE_SIZE - (((vaddr_t)varg) & PAGE_MASK);
/* leave space for the terminating NUL */
iov.iov_base = buf;
iov.iov_len = len;
uio.uio_iov = &iov;
uio.uio_iovcnt = 1;
uio.uio_offset = (off_t)(vaddr_t)varg;
uio.uio_resid = len;
uio.uio_segflg = UIO_SYSSPACE;
uio.uio_rw = UIO_READ;
uio.uio_procp = cp;
if ((error = uvm_io(&vp->p_vmspace->vm_map, &uio)) != 0)
goto out;
for (vstrlen = 0; vstrlen < len; vstrlen++) {
if (buf[vstrlen] == '\0')
break;
}
/* Don't overflow readers buffer. */
if (*oldlenp + vstrlen + 1 >= limit) {
error = ENOMEM;
goto out;
}
if ((error = copyout(buf, rarg, vstrlen)) != 0)
goto out;
*oldlenp += vstrlen;
rarg += vstrlen;
/* The string didn't end in this page? */
if (vstrlen == len) {
varg += vstrlen;
goto more;
}
/* End of string. Terminate it with a NUL */
buf[0] = '\0';
if ((error = copyout(buf, rarg, 1)) != 0)
goto out;
*oldlenp += 1;
rarg += 1;
vargv++;
rargv++;
cnt--;
}
if (*oldlenp >= limit) {
error = ENOMEM;
goto out;
}
/* Write the terminating null */
rarg = NULL;
error = copyout(&rarg, rargv, sizeof(rarg));
out:
uvmspace_free(vp->p_vmspace);
free(buf, M_TEMP);
return (error);
}
/*
* Initialize disknames/diskstats for export by sysctl. If update is set,
* then we simply update the disk statistics information.
*/
int
sysctl_diskinit(update, p)
int update;
struct proc *p;
{
struct diskstats *sdk;
struct disk *dk;
int i, tlen, l;
if ((i = lockmgr(&sysctl_disklock, LK_EXCLUSIVE, NULL, p)) != 0)
return i;
if (disk_change) {
for (dk = TAILQ_FIRST(&disklist), tlen = 0; dk;
dk = TAILQ_NEXT(dk, dk_link))
tlen += strlen(dk->dk_name) + 1;
tlen++;
if (disknames)
free(disknames, M_SYSCTL);
if (diskstats)
free(diskstats, M_SYSCTL);
diskstats = NULL;
disknames = NULL;
diskstats = malloc(disk_count * sizeof(struct diskstats),
M_SYSCTL, M_WAITOK);
disknames = malloc(tlen, M_SYSCTL, M_WAITOK);
disknames[0] = '\0';
for (dk = TAILQ_FIRST(&disklist), i = 0, l = 0; dk;
dk = TAILQ_NEXT(dk, dk_link), i++) {
snprintf(disknames + l, tlen - l, "%s,",
dk->dk_name ? dk->dk_name : "");
l += strlen(disknames + l);
sdk = diskstats + i;
strlcpy(sdk->ds_name, dk->dk_name,
sizeof(sdk->ds_name));
sdk->ds_busy = dk->dk_busy;
sdk->ds_rxfer = dk->dk_rxfer;
sdk->ds_wxfer = dk->dk_wxfer;
sdk->ds_seek = dk->dk_seek;
sdk->ds_rbytes = dk->dk_rbytes;
sdk->ds_wbytes = dk->dk_wbytes;
sdk->ds_attachtime = dk->dk_attachtime;
sdk->ds_timestamp = dk->dk_timestamp;
sdk->ds_time = dk->dk_time;
}
/* Eliminate trailing comma */
if (l != 0)
disknames[l - 1] = '\0';
disk_change = 0;
} else if (update) {
/* Just update, number of drives hasn't changed */
for (dk = TAILQ_FIRST(&disklist), i = 0; dk;
dk = TAILQ_NEXT(dk, dk_link), i++) {
sdk = diskstats + i;
strlcpy(sdk->ds_name, dk->dk_name,
sizeof(sdk->ds_name));
sdk->ds_busy = dk->dk_busy;
sdk->ds_rxfer = dk->dk_rxfer;
sdk->ds_wxfer = dk->dk_wxfer;
sdk->ds_seek = dk->dk_seek;
sdk->ds_rbytes = dk->dk_rbytes;
sdk->ds_wbytes = dk->dk_wbytes;
sdk->ds_attachtime = dk->dk_attachtime;
sdk->ds_timestamp = dk->dk_timestamp;
sdk->ds_time = dk->dk_time;
}
}
lockmgr(&sysctl_disklock, LK_RELEASE, NULL, p);
return 0;
}
#if defined(SYSVMSG) || defined(SYSVSEM) || defined(SYSVSHM)
int
sysctl_sysvipc(name, namelen, where, sizep)
int *name;
u_int namelen;
void *where;
size_t *sizep;
{
#ifdef SYSVMSG
struct msg_sysctl_info *msgsi;
#endif
#ifdef SYSVSEM
struct sem_sysctl_info *semsi;
#endif
#ifdef SYSVSHM
struct shm_sysctl_info *shmsi;
#endif
size_t infosize, dssize, tsize, buflen;
int i, nds, error, ret;
void *buf;
if (namelen != 1)
return (EINVAL);
buflen = *sizep;
switch (*name) {
case KERN_SYSVIPC_MSG_INFO:
#ifdef SYSVMSG
infosize = sizeof(msgsi->msginfo);
nds = msginfo.msgmni;
dssize = sizeof(msgsi->msgids[0]);
break;
#else
return (EOPNOTSUPP);
#endif
case KERN_SYSVIPC_SEM_INFO:
#ifdef SYSVSEM
infosize = sizeof(semsi->seminfo);
nds = seminfo.semmni;
dssize = sizeof(semsi->semids[0]);
break;
#else
return (EOPNOTSUPP);
#endif
case KERN_SYSVIPC_SHM_INFO:
#ifdef SYSVSHM
infosize = sizeof(shmsi->shminfo);
nds = shminfo.shmmni;
dssize = sizeof(shmsi->shmids[0]);
break;
#else
return (EOPNOTSUPP);
#endif
default:
return (EINVAL);
}
tsize = infosize + (nds * dssize);
/* Return just the total size required. */
if (where == NULL) {
*sizep = tsize;
return (0);
}
/* Not enough room for even the info struct. */
if (buflen < infosize) {
*sizep = 0;
return (ENOMEM);
}
buf = malloc(min(tsize, buflen), M_TEMP, M_WAITOK);
bzero(buf, min(tsize, buflen));
switch (*name) {
#ifdef SYSVMSG
case KERN_SYSVIPC_MSG_INFO:
msgsi = (struct msg_sysctl_info *)buf;
msgsi->msginfo = msginfo;
break;
#endif
#ifdef SYSVSEM
case KERN_SYSVIPC_SEM_INFO:
semsi = (struct sem_sysctl_info *)buf;
semsi->seminfo = seminfo;
break;
#endif
#ifdef SYSVSHM
case KERN_SYSVIPC_SHM_INFO:
shmsi = (struct shm_sysctl_info *)buf;
shmsi->shminfo = shminfo;
break;
#endif
}
buflen -= infosize;
ret = 0;
if (buflen > 0) {
/* Fill in the IPC data structures. */
for (i = 0; i < nds; i++) {
if (buflen < dssize) {
ret = ENOMEM;
break;
}
switch (*name) {
#ifdef SYSVMSG
case KERN_SYSVIPC_MSG_INFO:
bcopy(&msqids[i], &msgsi->msgids[i], dssize);
break;
#endif
#ifdef SYSVSEM
case KERN_SYSVIPC_SEM_INFO:
if (sema[i] != NULL)
bcopy(sema[i], &semsi->semids[i],
dssize);
else
bzero(&semsi->semids[i], dssize);
break;
#endif
#ifdef SYSVSHM
case KERN_SYSVIPC_SHM_INFO:
if (shmsegs[i] != NULL)
bcopy(shmsegs[i], &shmsi->shmids[i],
dssize);
else
bzero(&shmsi->shmids[i], dssize);
break;
#endif
}
buflen -= dssize;
}
}
*sizep -= buflen;
error = copyout(buf, where, *sizep);
free(buf, M_TEMP);
/* If copyout succeeded, use return code set earlier. */
return (error ? error : ret);
}
#endif /* SYSVMSG || SYSVSEM || SYSVSHM */
int
sysctl_intrcnt(int *name, u_int namelen, void *oldp, size_t *oldlenp)
{
extern int intrcnt[], eintrcnt[];
extern char intrnames[], eintrnames[];
char *intrname;
int nintr, i;
nintr = (off_t)(eintrcnt - intrcnt);
if (name[0] != KERN_INTRCNT_NUM) {
if (namelen != 2)
return (ENOTDIR);
if (name[1] < 0 || name[1] >= nintr)
return (EINVAL);
i = name[1];
}
switch (name[0]) {
case KERN_INTRCNT_NUM:
return (sysctl_rdint(oldp, oldlenp, NULL, nintr));
break;
case KERN_INTRCNT_CNT:
return (sysctl_rdint(oldp, oldlenp, NULL, intrcnt[i]));
case KERN_INTRCNT_NAME:
intrname = intrnames;
while (i > 0) {
intrname += strlen(intrname) + 1;
i--;
if (intrname > eintrnames)
return (EINVAL);
}
return (sysctl_rdstring(oldp, oldlenp, NULL, intrname));
default:
return (EOPNOTSUPP);
}
}
int nsensors = 0;
struct sensors_head sensors = SLIST_HEAD_INITIALIZER(&sensors);
int
sysctl_sensors(int *name, u_int namelen, void *oldp, size_t *oldlenp,
void *newp, size_t newlen)
{
struct sensor *s = NULL;
int num;
if (namelen != 1)
return (ENOTDIR);
num = name[0];
if (num >= nsensors)
return (ENXIO);
SLIST_FOREACH(s, &sensors, list)
if (s->num == num)
break;
return (sysctl_rdstruct(oldp, oldlenp, newp, s, sizeof(struct sensor)));
}
int
sysctl_emul(int *name, u_int namelen, void *oldp, size_t *oldlenp,
void *newp, size_t newlen)
{
int enabled, error;
struct emul *e;
if (name[0] == KERN_EMUL_NUM) {
if (namelen != 1)
return (ENOTDIR);
return (sysctl_rdint(oldp, oldlenp, newp, nemuls));
}
if (namelen != 2)
return (ENOTDIR);
if (name[0] > nemuls || name[0] < 0)
return (EINVAL);
e = emulsw[name[0] - 1];
switch (name[1]) {
case KERN_EMUL_NAME:
return (sysctl_rdstring(oldp, oldlenp, newp, e->e_name));
case KERN_EMUL_ENABLED:
enabled = (e->e_flags & EMUL_ENABLED);
error = sysctl_int(oldp, oldlenp, newp, newlen,
&enabled);
e->e_flags = (enabled & EMUL_ENABLED);
return (error);
default:
return (EINVAL);
}
}
|
binhqnguyen/lena
|
nsc/openbsd3/kern/kern_sysctl.c
|
C
|
gpl-2.0
| 44,050 |
\text{First\ line}\text{Second\ line}
|
timtylin/scholdoc-texmath
|
tests/writers/mspace-01.tex
|
TeX
|
gpl-2.0
| 38 |
/* vi: set sw=4 ts=4: */
/*
* Mini touch implementation for busybox
*
* Copyright (C) 1999-2004 by Erik Andersen <[email protected]>
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
/* BB_AUDIT SUSv3 _NOT_ compliant -- options -a, -m, -r, -t not supported. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/touch.html */
/* Mar 16, 2003 Manuel Novoa III ([email protected])
*
* Previous version called open() and then utime(). While this will be
* be necessary to implement -r and -t, it currently only makes things bigger.
* Also, exiting on a failure was a bug. All args should be processed.
*/
#include "libbb.h"
/* This is a NOFORK applet. Be very careful! */
/* coreutils implements:
* -a change only the access time
* -c, --no-create
* do not create any files
* -d, --date=STRING
* parse STRING and use it instead of current time
* -f (ignored, BSD compat)
* -m change only the modification time
* -r, --reference=FILE
* use this file's times instead of current time
* -t STAMP
* use [[CC]YY]MMDDhhmm[.ss] instead of current time
* --time=WORD
* change the specified time: WORD is access, atime, or use
*/
int touch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int touch_main(int argc UNUSED_PARAM, char **argv)
{
#if ENABLE_DESKTOP
struct utimbuf timebuf;
char *reference_file = NULL;
#else
#define reference_file NULL
#define timebuf (*(struct utimbuf*)NULL)
#endif
int fd;
int status = EXIT_SUCCESS;
int flags = getopt32(argv, "c" USE_DESKTOP("r:")
/*ignored:*/ "fma"
USE_DESKTOP(, &reference_file));
flags &= 1; /* only -c bit is left */
argv += optind;
if (!*argv) {
bb_show_usage();
}
if (reference_file) {
struct stat stbuf;
xstat(reference_file, &stbuf);
timebuf.actime = stbuf.st_atime;
timebuf.modtime = stbuf.st_mtime;
}
do {
if (utime(*argv, reference_file ? &timebuf : NULL)) {
if (errno == ENOENT) { /* no such file */
if (flags) { /* creation is disabled, so ignore */
continue;
}
/* Try to create the file. */
fd = open(*argv, O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
);
if ((fd >= 0) && !close(fd)) {
if (reference_file)
utime(*argv, &timebuf);
continue;
}
}
status = EXIT_FAILURE;
bb_simple_perror_msg(*argv);
}
} while (*++argv);
return status;
}
|
scs/uclinux
|
user/busybox/busybox-1.13.4/coreutils/touch.c
|
C
|
gpl-2.0
| 2,457 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
Description
Abstract base class for finite area calculus convection schemes.
\*---------------------------------------------------------------------------*/
#include "faConvectionScheme.H"
#include "fa.H"
#include "HashTable.H"
#include "linearEdgeInterpolation.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace fa
{
// * * * * * * * * * * * * * * * * * Selectors * * * * * * * * * * * * * * * //
template<class Type>
tmp<convectionScheme<Type> > convectionScheme<Type>::New
(
const faMesh& mesh,
const edgeScalarField& faceFlux,
Istream& schemeData
)
{
if (fa::debug)
{
Info<< "convectionScheme<Type>::New"
"(const faMesh&, const edgeScalarField&, Istream&) : "
"constructing convectionScheme<Type>"
<< endl;
}
if (schemeData.eof())
{
FatalIOErrorIn
(
"convectionScheme<Type>::New"
"(const faMesh&, const edgeScalarField&, Istream&)",
schemeData
) << "Convection scheme not specified" << endl << endl
<< "Valid convection schemes are :" << endl
<< IstreamConstructorTablePtr_->toc()
<< exit(FatalIOError);
}
word schemeName(schemeData);
typename IstreamConstructorTable::iterator cstrIter =
IstreamConstructorTablePtr_->find(schemeName);
if (cstrIter == IstreamConstructorTablePtr_->end())
{
FatalIOErrorIn
(
"convectionScheme<Type>::New"
"(const faMesh&, const edgeScalarField&, Istream&)",
schemeData
) << "unknown convection scheme " << schemeName << endl << endl
<< "Valid convection schemes are :" << endl
<< IstreamConstructorTablePtr_->toc()
<< exit(FatalIOError);
}
return cstrIter()(mesh, faceFlux, schemeData);
}
// * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * //
template<class Type>
convectionScheme<Type>::~convectionScheme()
{}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace fa
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
|
martinep/foam-extend-3.0
|
src/finiteArea/finiteArea/convectionSchemes/faConvectionScheme/faConvectionScheme.C
|
C++
|
gpl-2.0
| 3,596 |
define("dojox/grid/_Layout", [
"dojo/_base/kernel",
"../main",
"dojo/_base/declare",
"dojo/_base/array",
"dojo/_base/lang",
"dojo/dom-geometry",
"./cells",
"./_RowSelector"
], function(dojo, dojox, declare, array, lang, domGeometry){
return declare("dojox.grid._Layout", null, {
// summary:
// Controls grid cell layout. Owned by grid and used internally.
constructor: function(inGrid){
this.grid = inGrid;
},
// flat array of grid cells
cells: [],
// structured array of grid cells
structure: null,
// default cell width
defaultWidth: '6em',
// methods
moveColumn: function(sourceViewIndex, destViewIndex, cellIndex, targetIndex, before){
var source_cells = this.structure[sourceViewIndex].cells[0];
var dest_cells = this.structure[destViewIndex].cells[0];
var cell = null;
var cell_ri = 0;
var target_ri = 0;
for(var i=0, c; c=source_cells[i]; i++){
if(c.index == cellIndex){
cell_ri = i;
break;
}
}
cell = source_cells.splice(cell_ri, 1)[0];
cell.view = this.grid.views.views[destViewIndex];
for(i=0, c=null; c=dest_cells[i]; i++){
if(c.index == targetIndex){
target_ri = i;
break;
}
}
if(!before){
target_ri += 1;
}
dest_cells.splice(target_ri, 0, cell);
var sortedCell = this.grid.getCell(this.grid.getSortIndex());
if(sortedCell){
sortedCell._currentlySorted = this.grid.getSortAsc();
}
this.cells = [];
cellIndex = 0;
var v;
for(i=0; v=this.structure[i]; i++){
for(var j=0, cs; cs=v.cells[j]; j++){
for(var k=0; c=cs[k]; k++){
c.index = cellIndex;
this.cells.push(c);
if("_currentlySorted" in c){
var si = cellIndex + 1;
si *= c._currentlySorted ? 1 : -1;
this.grid.sortInfo = si;
delete c._currentlySorted;
}
cellIndex++;
}
}
}
//Fix #9481 - reset idx in cell markup
array.forEach(this.cells, function(c){
var marks = c.markup[2].split(" ");
var oldIdx = parseInt(marks[1].substring(5));//get old "idx"
if(oldIdx != c.index){
marks[1] = "idx=\"" + c.index + "\"";
c.markup[2] = marks.join(" ");
}
});
this.grid.setupHeaderMenu();
//this.grid.renderOnIdle();
},
setColumnVisibility: function(columnIndex, visible){
var cell = this.cells[columnIndex];
if(cell.hidden == visible){
cell.hidden = !visible;
var v = cell.view, w = v.viewWidth;
if(w && w != "auto"){
v._togglingColumn = domGeometry.getMarginBox(cell.getHeaderNode()).w || 0;
}
v.update();
return true;
}else{
return false;
}
},
addCellDef: function(inRowIndex, inCellIndex, inDef){
var self = this;
var getCellWidth = function(inDef){
var w = 0;
if(inDef.colSpan > 1){
w = 0;
}else{
w = inDef.width || self._defaultCellProps.width || self.defaultWidth;
if(!isNaN(w)){
w = w + "em";
}
}
return w;
};
var props = {
grid: this.grid,
subrow: inRowIndex,
layoutIndex: inCellIndex,
index: this.cells.length
};
if(inDef && inDef instanceof dojox.grid.cells._Base){
var new_cell = lang.clone(inDef);
props.unitWidth = getCellWidth(new_cell._props);
new_cell = lang.mixin(new_cell, this._defaultCellProps, inDef._props, props);
return new_cell;
}
var cell_type = inDef.type || inDef.cellType || this._defaultCellProps.type || this._defaultCellProps.cellType || dojox.grid.cells.Cell;
if(lang.isString(cell_type)){
cell_type = lang.getObject(cell_type);
}
props.unitWidth = getCellWidth(inDef);
return new cell_type(lang.mixin({}, this._defaultCellProps, inDef, props));
},
addRowDef: function(inRowIndex, inDef){
var result = [];
var relSum = 0, pctSum = 0, doRel = true;
for(var i=0, def, cell; (def=inDef[i]); i++){
cell = this.addCellDef(inRowIndex, i, def);
result.push(cell);
this.cells.push(cell);
// Check and calculate the sum of all relative widths
if(doRel && cell.relWidth){
relSum += cell.relWidth;
}else if(cell.width){
var w = cell.width;
if(typeof w == "string" && w.slice(-1) == "%"){
pctSum += window.parseInt(w, 10);
}else if(w == "auto"){
// relative widths doesn't play nice with auto - since we
// don't have a way of knowing how much space the auto is
// supposed to take up.
doRel = false;
}
}
}
if(relSum && doRel){
// We have some kind of relWidths specified - so change them to %
array.forEach(result, function(cell){
if(cell.relWidth){
cell.width = cell.unitWidth = ((cell.relWidth / relSum) * (100 - pctSum)) + "%";
}
});
}
return result;
},
addRowsDef: function(inDef){
var result = [];
if(lang.isArray(inDef)){
if(lang.isArray(inDef[0])){
for(var i=0, row; inDef && (row=inDef[i]); i++){
result.push(this.addRowDef(i, row));
}
}else{
result.push(this.addRowDef(0, inDef));
}
}
return result;
},
addViewDef: function(inDef){
this._defaultCellProps = inDef.defaultCell || {};
if(inDef.width && inDef.width == "auto"){
delete inDef.width;
}
return lang.mixin({}, inDef, {cells: this.addRowsDef(inDef.rows || inDef.cells)});
},
setStructure: function(inStructure){
this.fieldIndex = 0;
this.cells = [];
var s = this.structure = [];
if(this.grid.rowSelector){
var sel = { type: dojox._scopeName + ".grid._RowSelector" };
if(lang.isString(this.grid.rowSelector)){
var width = this.grid.rowSelector;
if(width == "false"){
sel = null;
}else if(width != "true"){
sel['width'] = width;
}
}else{
if(!this.grid.rowSelector){
sel = null;
}
}
if(sel){
s.push(this.addViewDef(sel));
}
}
var isCell = function(def){
return ("name" in def || "field" in def || "get" in def);
};
var isRowDef = function(def){
if(lang.isArray(def)){
if(lang.isArray(def[0]) || isCell(def[0])){
return true;
}
}
return false;
};
var isView = function(def){
return (def !== null && lang.isObject(def) &&
("cells" in def || "rows" in def || ("type" in def && !isCell(def))));
};
if(lang.isArray(inStructure)){
var hasViews = false;
for(var i=0, st; (st=inStructure[i]); i++){
if(isView(st)){
hasViews = true;
break;
}
}
if(!hasViews){
s.push(this.addViewDef({ cells: inStructure }));
}else{
for(i=0; (st=inStructure[i]); i++){
if(isRowDef(st)){
s.push(this.addViewDef({ cells: st }));
}else if(isView(st)){
s.push(this.addViewDef(st));
}
}
}
}else if(isView(inStructure)){
// it's a view object
s.push(this.addViewDef(inStructure));
}
this.cellCount = this.cells.length;
this.grid.setupHeaderMenu();
}
});
});
|
hariomkumarmth/champaranexpress
|
wp-content/plugins/dojo/dojox/grid/_Layout.js.uncompressed.js
|
JavaScript
|
gpl-2.0
| 6,952 |
//# tMArrayUtil.cc: test program for MArrayUtil
//# Copyright (C) 2012
//# Associated Universities, Inc. Washington DC, USA.
//#
//# This library is free software; you can redistribute it and/or modify it
//# under the terms of the GNU Library General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or (at your
//# option) any later version.
//#
//# This library is distributed in the hope that it will be useful, but WITHOUT
//# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
//# License for more details.
//#
//# You should have received a copy of the GNU Library General Public License
//# along with this library; if not, write to the Free Software Foundation,
//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//#
//# Correspondence concerning AIPS++ should be addressed as follows:
//# Internet email: [email protected].
//# Postal address: AIPS++ Project Office
//# National Radio Astronomy Observatory
//# 520 Edgemont Road
//# Charlottesville, VA 22903-2475 USA
//#
//# $Id: tMArrayUtil.cc 21273 2012-10-31 15:25:10Z gervandiepen $
#include <casacore/tables/TaQL/MArray.h>
#include <casacore/tables/TaQL/MArrayUtil.h>
#include <casacore/casa/Arrays/ArrayMath.h>
#include <casacore/casa/Arrays/ArrayLogical.h>
#include <iostream>
using namespace casacore;
using namespace std;
int main()
{
// Create and fill an array and mask.
Array<Int> arr(IPosition(4,2,3,4,5));
indgen(arr);
Array<Bool> mask(arr.shape());
mask = True;
mask(arr%7==0) = False;
// Create an unmasked array from it, reorder it, and check the result.
MArray<Int> marr1(arr);
MArray<Int> res1 = reorderArray (marr1, IPosition(2,1,3));
AlwaysAssertExit (! res1.hasMask());
for (int i4=0; i4<5; ++i4) {
for (int i3=0; i3<4; ++i3) {
for (int i2=0; i2<3; ++i2) {
for (int i1=0; i1<2; ++i1) {
Int v = res1.array()(IPosition(4,i2,i4,i1,i3));
AlwaysAssertExit (v == arr(IPosition(4,i1,i2,i3,i4)));
}
}
}
}
// Create a masked array from it, reorder it, and check the result.
MArray<Int> marr2(arr, mask);
MArray<Int> res2 = reorderArray (marr2, IPosition(2,3,1));
AlwaysAssertExit (res2.hasMask());
for (int i4=0; i4<5; ++i4) {
for (int i3=0; i3<4; ++i3) {
for (int i2=0; i2<3; ++i2) {
for (int i1=0; i1<2; ++i1) {
Int v = res2.array()(IPosition(4,i4,i2,i1,i3));
AlwaysAssertExit (v == arr(IPosition(4,i1,i2,i3,i4)));
Bool m = res2.mask()(IPosition(4,i4,i2,i1,i3));
AlwaysAssertExit (m == mask(IPosition(4,i1,i2,i3,i4)));
}
}
}
}
// Now reorder without actually changing the order.
// Check that no copy is made if told so.
MArray<Int> res3 = reorderArray (marr2, IPosition(4,0,1,2,3), False);
AlwaysAssertExit (res3.hasMask());
AlwaysAssertExit (arr.data() == res3.array().data());
AlwaysAssertExit (mask.data() == res3.mask().data());
// The same but, now with a copy.
MArray<Int> res4 = reorderArray (marr2, IPosition(4,0,1,2,3), True);
AlwaysAssertExit (res4.hasMask());
AlwaysAssertExit (arr.data() != res4.array().data());
AlwaysAssertExit (mask.data() != res4.mask().data());
// Check if a reordered null array is null.
AlwaysAssertExit (reorderArray (MArray<Int>(), IPosition()).isNull());
return 0;
}
|
indebetouw/casacore
|
tables/TaQL/test/tMArrayUtil.cc
|
C++
|
gpl-2.0
| 3,522 |
/*
* Server.cpp
*
* Created on: Dec 22, 2013
* Author: Alberto Paganelli
*/
#include <Ice/Ice.h>
#include "AstroI.h"
using namespace std;
class AstroServer : public Ice::Application
{
virtual int run(int, char*[]);
};
int main(int argc, char **argv) {
AstroServer app;
return app.main(argc, argv, "config.server");
}
int AstroServer::run(int argc, char*[]){
if(argc > 1)
{
cerr << appName() << ": too many arguments" << endl;
return EXIT_FAILURE;
}
Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("Astro");
Astro::AgileCtsMapGenPtr astro = new Astro::AgileCtsMapGenI;
adapter->add(astro, communicator()->stringToIdentity("astro"));
adapter->activate();
communicator()->waitForShutdown();
return EXIT_SUCCESS;
}
|
ASTRO-EDU/gtCtsMapGen5
|
code/Server.cpp
|
C++
|
gpl-2.0
| 767 |
<?php
require_once 'class.file.php';
/**
* Description of class
*
* @author Srdjan
*
* $HeadURL: http://plugins.svn.wordpress.org/types/tags/1.6.5/embedded/common/toolset-forms/classes/class.audio.php $
* $LastChangedDate: 2014-11-18 06:47:25 +0000 (Tue, 18 Nov 2014) $
* $LastChangedRevision: 1027712 $
* $LastChangedBy: iworks $
*
*/
class WPToolset_Field_Audio extends WPToolset_Field_File
{
protected $_settings = array('min_wp_version' => '3.6');
public function metaform()
{
$validation = $this->getValidationData();
$validation = self::addTypeValidation($validation);
$this->setValidationData($validation);
return parent::metaform();
}
public static function addTypeValidation($validation) {
$validation['extension'] = array(
'args' => array(
'extension',
'16svx|2sf|8svx|aac|aif|aifc|aiff|amr|ape|asf|ast|au|aup|band|brstm|bwf|cdda|cust|dsf|dwd|flac|gsf|gsm|gym|it|jam|la|ly|m4a|m4p|mid|minipsf|mng|mod|mp1|mp2|mp3|mp4|mpc|mscz|mt2|mus|niff|nsf|off|ofr|ofs|ogg|ots|pac|psf|psf2|psflib|ptb|qsf|ra|raw|rka|rm|rmj|s3m|shn|sib|sid|smp|spc|spx|ssf|swa|tta|txm|usf|vgm|voc|vox|vqf|wav|wma|wv|xm|ym',
),
'message' => __( 'You can add only audio.', 'wpv-views' ),
);
return $validation;
}
}
|
kirillbakun/wordpress
|
wp-content/plugins/types/embedded/common/toolset-forms/classes/class.audio.php
|
PHP
|
gpl-2.0
| 1,364 |
/*
* Wrapper functions for accessing the file_struct fd array.
*/
#ifndef __LINUX_FILE_H
#define __LINUX_FILE_H
#include <asm/atomic.h>
#include <linux/posix_types.h>
#include <linux/compiler.h>
#include <linux/spinlock.h>
#include <linux/rcupdate.h>
/*
* The default fd array needs to be at least BITS_PER_LONG,
* as this is the granularity returned by copy_fdset().
*/
#define NR_OPEN_DEFAULT BITS_PER_LONG
struct fdtable {
unsigned int max_fds;
int max_fdset;
int next_fd;
struct file ** fd; /* current fd array */
fd_set *close_on_exec;
fd_set *open_fds;
struct rcu_head rcu;
struct files_struct *free_files;
struct fdtable *next;
};
/*
* Open file table structure
*/
struct files_struct {
atomic_t count;
struct fdtable *fdt;
struct fdtable fdtab;
fd_set close_on_exec_init;
fd_set open_fds_init;
struct file * fd_array[NR_OPEN_DEFAULT];
spinlock_t file_lock; /* Protects concurrent writers. Nests inside tsk->alloc_lock */
};
#define files_fdtable(files) (rcu_dereference((files)->fdt))
extern void FASTCALL(__fput(struct file *));
extern void FASTCALL(fput(struct file *));
static inline void fput_light(struct file *file, int fput_needed)
{
if (unlikely(fput_needed))
fput(file);
}
extern struct file * FASTCALL(fget(unsigned int fd));
extern struct file * FASTCALL(fget_light(unsigned int fd, int *fput_needed));
extern void FASTCALL(set_close_on_exec(unsigned int fd, int flag));
extern void put_filp(struct file *);
extern int get_unused_fd(void);
extern void FASTCALL(put_unused_fd(unsigned int fd));
struct kmem_cache;
extern struct file ** alloc_fd_array(int);
extern void free_fd_array(struct file **, int);
extern fd_set *alloc_fdset(int);
extern void free_fdset(fd_set *, int);
extern int expand_files(struct files_struct *, int nr);
extern void free_fdtable(struct fdtable *fdt);
extern void __init files_defer_init(void);
static inline struct file * fcheck_files(struct files_struct *files, unsigned int fd)
{
struct file * file = NULL;
struct fdtable *fdt = files_fdtable(files);
if (fd < fdt->max_fds)
file = rcu_dereference(fdt->fd[fd]);
return file;
}
/*
* Check whether the specified fd has an open file.
*/
#define fcheck(fd) fcheck_files(current->files, fd)
extern void FASTCALL(fd_install(unsigned int fd, struct file * file));
struct task_struct;
struct files_struct *get_files_struct(struct task_struct *);
void FASTCALL(put_files_struct(struct files_struct *fs));
#endif /* __LINUX_FILE_H */
|
odit/rv042
|
linux/kernel_2.6/linux/include/linux/file.h
|
C
|
gpl-2.0
| 2,485 |
/*
* Tiny Code Generator for QEMU
*
* Copyright (c) 2008 Fabrice Bellard
*
* 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.
*/
#define TCG_TARGET_PPC64 1
#define TCG_TARGET_REG_BITS 64
#define TCG_TARGET_WORDS_BIGENDIAN
#define TCG_TARGET_NB_REGS 32
enum {
TCG_REG_R0 = 0,
TCG_REG_R1,
TCG_REG_R2,
TCG_REG_R3,
TCG_REG_R4,
TCG_REG_R5,
TCG_REG_R6,
TCG_REG_R7,
TCG_REG_R8,
TCG_REG_R9,
TCG_REG_R10,
TCG_REG_R11,
TCG_REG_R12,
TCG_REG_R13,
TCG_REG_R14,
TCG_REG_R15,
TCG_REG_R16,
TCG_REG_R17,
TCG_REG_R18,
TCG_REG_R19,
TCG_REG_R20,
TCG_REG_R21,
TCG_REG_R22,
TCG_REG_R23,
TCG_REG_R24,
TCG_REG_R25,
TCG_REG_R26,
TCG_REG_R27,
TCG_REG_R28,
TCG_REG_R29,
TCG_REG_R30,
TCG_REG_R31
};
/* used for function call generation */
#define TCG_REG_CALL_STACK TCG_REG_R1
#define TCG_TARGET_STACK_ALIGN 16
#define TCG_TARGET_CALL_STACK_OFFSET 48
/* optional instructions */
#define TCG_TARGET_HAS_neg_i32
#define TCG_TARGET_HAS_div_i32
#define TCG_TARGET_HAS_neg_i64
#define TCG_TARGET_HAS_div_i64
#define TCG_TARGET_HAS_ext8s_i32
#define TCG_TARGET_HAS_ext16s_i32
#define TCG_TARGET_HAS_ext8s_i64
#define TCG_TARGET_HAS_ext16s_i64
#define TCG_TARGET_HAS_ext32s_i64
#define TCG_AREG0 TCG_REG_R27
#define TCG_AREG1 TCG_REG_R24
#define TCG_AREG2 TCG_REG_R25
#define TCG_AREG3 TCG_REG_R26
/* taken directly from tcg-dyngen.c */
#define MIN_CACHE_LINE_SIZE 8 /* conservative value */
static inline void flush_icache_range(unsigned long start, unsigned long stop)
{
unsigned long p;
start &= ~(MIN_CACHE_LINE_SIZE - 1);
stop = (stop + MIN_CACHE_LINE_SIZE - 1) & ~(MIN_CACHE_LINE_SIZE - 1);
for (p = start; p < stop; p += MIN_CACHE_LINE_SIZE) {
asm volatile ("dcbst 0,%0" : : "r"(p) : "memory");
}
asm volatile ("sync" : : : "memory");
for (p = start; p < stop; p += MIN_CACHE_LINE_SIZE) {
asm volatile ("icbi 0,%0" : : "r"(p) : "memory");
}
asm volatile ("sync" : : : "memory");
asm volatile ("isync" : : : "memory");
}
|
yajin/qemu-omap3
|
tcg/ppc64/tcg-target.h
|
C
|
gpl-2.0
| 3,111 |
/*
Copyright (C) 2016- The University of Notre Dame
This software is distributed under the GNU General Public License.
See the file COPYING for details.
*/
/*
* File: makeflow_catalog_reporter.h
* Author: Kyle D. Sweeney
*
* Created on July 20, 2016, 10:51 AM
* Modified on Nov 30, 2020, 04:46 PM by Thanh Son Phung
*/
#ifndef MAKEFLOW_CATALOG_REPORTER_H
#define MAKEFLOW_CATALOG_REPORTER_H
/**
* Creates a summary of the status of makeflow and sends it to the catalog server.
* @param d the DAG maintained by makeflow
* @param name the name of the project
* @return 1 if everything went well, 0 if not
*/
int makeflow_catalog_summary(struct dag* d, char* name, batch_queue_type_t type, timestamp_t start);
/**
* Creates a summary of the status of makeflow and prints it out to a html file.
* @param d the DAG maintained by makeflow
* @param name the name of the project
* @param tpye the batch queue type
* @param status_file_name the name of the status file, user configured
* @return 1 if everything went well, 0 if not
*/
int makeflow_file_summary(struct dag* d, char* name, batch_queue_type_t type, timestamp_t start, char *status_file_name);
#endif /* MAKEFLOW_CATALOG_REPORTER_H */
|
dthain/cctools
|
makeflow/src/makeflow_catalog_reporter.h
|
C
|
gpl-2.0
| 1,217 |
/**
* o------------------------------------------------------------------------------o
* | This file is part of the RGraph package - you can learn more at: |
* | |
* | http://www.rgraph.net |
* | |
* | This package is licensed under the RGraph license. For all kinds of business |
* | purposes there is a small one-time licensing fee to pay and for non |
* | commercial purposes it is free to use. You can read the full license here: |
* | |
* | http://www.rgraph.net/LICENSE.txt |
* o------------------------------------------------------------------------------o
*/
/**
* Initialise the various objects
*/
if (typeof(RGraph) == 'undefined') RGraph = {isRGraph:true,type:'common'};
RGraph.Registry = {};
RGraph.Registry.store = [];
RGraph.Registry.store['chart.event.handlers'] = [];
RGraph.Registry.store['__rgraph_event_listeners__'] = []; // Used in the new system for tooltips
RGraph.background = {};
RGraph.objects = [];
RGraph.Resizing = {};
RGraph.events = [];
RGraph.cursor = [];
RGraph.DOM2Events = {};
RGraph.ObjectRegistry = {};
RGraph.ObjectRegistry.objects = {};
RGraph.ObjectRegistry.objects.byUID = [];
RGraph.ObjectRegistry.objects.byCanvasID = [];
/**
* Some "constants"
*/
HALFPI = (Math.PI / 2);
PI = Math.PI;
TWOPI = PI * 2;
/**
* Returns five values which are used as a nice scale
*
* @param max int The maximum value of the graph
* @param obj object The graph object
* @return array An appropriate scale
*/
RGraph.getScale = function (max, obj)
{
/**
* Special case for 0
*/
if (max == 0) {
return ['0.2', '0.4', '0.6', '0.8', '1.0'];
}
var original_max = max;
/**
* Manually do decimals
*/
if (max <= 1) {
if (max > 0.5) {
return [0.2,0.4,0.6,0.8, Number(1).toFixed(1)];
} else if (max >= 0.1) {
return obj.Get('chart.scale.round') ? [0.2,0.4,0.6,0.8,1] : [0.1,0.2,0.3,0.4,0.5];
} else {
var tmp = max;
var exp = 0;
while (tmp < 1.01) {
exp += 1;
tmp *= 10;
}
var ret = ['2e-' + exp, '4e-' + exp, '6e-' + exp, '8e-' + exp, '10e-' + exp];
if (max <= ('5e-' + exp)) {
ret = ['1e-' + exp, '2e-' + exp, '3e-' + exp, '4e-' + exp, '5e-' + exp];
}
return ret;
}
}
// Take off any decimals
if (String(max).indexOf('.') > 0) {
max = String(max).replace(/\.\d+$/, '');
}
var interval = Math.pow(10, Number(String(Number(max)).length - 1));
var topValue = interval;
while (topValue < max) {
topValue += (interval / 2);
}
// Handles cases where the max is (for example) 50.5
if (Number(original_max) > Number(topValue)) {
topValue += (interval / 2);
}
// Custom if the max is greater than 5 and less than 10
if (max < 10) {
topValue = (Number(original_max) <= 5 ? 5 : 10);
}
/**
* Added 02/11/2010 to create "nicer" scales
*/
if (obj && typeof(obj.Get('chart.scale.round')) == 'boolean' && obj.Get('chart.scale.round')) {
topValue = 10 * interval;
}
return [topValue * 0.2, topValue * 0.4, topValue * 0.6, topValue * 0.8, topValue];
}
/**
* Returns the maximum numeric value which is in an array
*
* @param array arr The array (can also be a number, in which case it's returned as-is)
* @param int Whether to ignore signs (ie negative/positive)
* @return int The maximum value in the array
*/
RGraph.array_max = function (arr)
{
var max = null;
if (typeof(arr) == 'number') {
return arr;
}
for (var i=0; i<arr.length; ++i) {
if (typeof(arr[i]) == 'number') {
var val = arguments[1] ? Math.abs(arr[i]) : arr[i];
if (typeof(max) == 'number') {
max = Math.max(max, val);
} else {
max = val;
}
}
}
return max;
}
/**
* Returns the maximum value which is in an array
*
* @param array arr The array
* @param int len The length to pad the array to
* @param mixed The value to use to pad the array (optional)
*/
RGraph.array_pad = function (arr, len)
{
if (arr.length < len) {
var val = arguments[2] ? arguments[2] : null;
for (var i=arr.length; i<len; ++i) {
arr[i] = val;
}
}
return arr;
}
/**
* An array sum function
*
* @param array arr The array to calculate the total of
* @return int The summed total of the arrays elements
*/
RGraph.array_sum = function (arr)
{
// Allow integers
if (typeof(arr) == 'number') {
return arr;
}
var i, sum;
var len = arr.length;
for(i=0,sum=0;i<len;sum+=arr[i++]);
return sum;
}
/**
* Takes any number of arguments and adds them to one big linear array
* which is then returned
*
* @param ... mixed The data to linearise. You can strings, booleans, numbers or arrays
*/
RGraph.array_linearize = function ()
{
var arr = [];
for (var i=0; i<arguments.length; ++i) {
if (typeof(arguments[i]) == 'object' && arguments[i]) {
for (var j=0; j<arguments[i].length; ++j) {
var sub = RGraph.array_linearize(arguments[i][j]);
for (var k=0; k<sub.length; ++k) {
arr.push(sub[k]);
}
}
} else {
arr.push(arguments[i]);
}
}
return arr;
}
/**
* This is a useful function which is basically a shortcut for drawing left, right, top and bottom alligned text.
*
* @param object context The context
* @param string font The font
* @param int size The size of the text
* @param int x The X coordinate
* @param int y The Y coordinate
* @param string text The text to draw
* @parm string The vertical alignment. Can be null. "center" gives center aligned text, "top" gives top aligned text.
* Anything else produces bottom aligned text. Default is bottom.
* @param string The horizontal alignment. Can be null. "center" gives center aligned text, "right" gives right aligned text.
* Anything else produces left aligned text. Default is left.
* @param bool Whether to show a bounding box around the text. Defaults not to
* @param int The angle that the text should be rotate at (IN DEGREES)
* @param string Background color for the text
* @param bool Whether the text is bold or not
* @param bool Whether the bounding box has a placement indicator
*/
RGraph.Text = function (context, font, size, x, y, text)
{
// Handle undefined - change it to an empty string
if ((typeof(text) != 'string' && typeof(text) != 'number') || text == 'undefined') {
return;
}
/**
* Adjust the vertical Y coord if it should be vertically centered
*/
if (typeof(text) == 'string') {
if (text.indexOf('\r\n') > 0 && arguments[6] == 'center') {
var line_count = text.split('\r\n').length;
y = y - ((line_count - 1.5) * size);
} else if (text.indexOf('\r\n') > 0 && arguments[6] == 'bottom') {
var line_count = text.split('\r\n').length;
y = y - ((line_count - 0.5) * size);
}
}
/**
* This calls the text function recursively to accommodate multi-line text
*/
if (typeof(text) == 'string' && text.match(/\r\n/)) {
var arr = text.split('\r\n');
text = arr[0];
arr = RGraph.array_shift(arr);
var nextline = arr.join('\r\n')
RGraph.Text(context,
font,
size,
arguments[9] == -90 ? (x + (size * 1.5)) : x,
y + (size * 1.5),
nextline,
arguments[6] ? arguments[6] : null,
arguments[7],
arguments[8],
arguments[9],
arguments[10],
arguments[11],
arguments[12]);
}
// Accommodate MSIE
if (RGraph.isOld()) {
y += 2;
}
context.font = (arguments[11] ? 'Bold ': '') + size + 'pt ' + font;
var i;
var origX = x;
var origY = y;
var originalFillStyle = context.fillStyle;
var originalLineWidth = context.lineWidth;
// Need these now the angle can be specified, ie defaults for the former two args
if (typeof(arguments[6]) == null) arguments[6] = 'bottom'; // Vertical alignment. Default to bottom/baseline
if (typeof(arguments[7]) == null) arguments[7] = 'left'; // Horizontal alignment. Default to left
if (typeof(arguments[8]) == null) arguments[8] = null; // Show a bounding box. Useful for positioning during development. Defaults to false
if (typeof(arguments[9]) == null) arguments[9] = 0; // Angle (IN DEGREES) that the text should be drawn at. 0 is middle right, and it goes clockwise
if (typeof(arguments[12]) == null) arguments[12] = true; // Whether the bounding box has the placement indicator
// The alignment is recorded here for purposes of Opera compatibility
if (navigator.userAgent.indexOf('Opera') != -1) {
context.canvas.__rgraph_valign__ = arguments[6];
context.canvas.__rgraph_halign__ = arguments[7];
}
// First, translate to x/y coords
context.save();
context.canvas.__rgraph_originalx__ = x;
context.canvas.__rgraph_originaly__ = y;
context.translate(x, y);
x = 0;
y = 0;
// Rotate the canvas if need be
if (arguments[9]) {
context.rotate(arguments[9] / 57.3);
}
// Vertical alignment - defaults to bottom
if (arguments[6]) {
var vAlign = arguments[6];
if (vAlign == 'center') {
context.translate(0, size / 2);
} else if (vAlign == 'top') {
context.translate(0, size);
}
}
// Hoeizontal alignment - defaults to left
if (arguments[7]) {
var hAlign = arguments[7];
var width = context.measureText(text).width;
if (hAlign) {
if (hAlign == 'center') {
context.translate(-1 * (width / 2), 0)
} else if (hAlign == 'right') {
context.translate(-1 * width, 0)
}
}
}
context.fillStyle = originalFillStyle;
/**
* Draw a bounding box if requested
*/
context.save();
context.fillText(text,0,0);
context.lineWidth = 1;
if (arguments[8]) {
var width = context.measureText(text).width;
var ieOffset = RGraph.isIE8() ? 2 : 0;
context.translate(x, y);
context.strokeRect(AA(context.canvas.__object__, - 3), AA(context.canvas.__object__, 0 - 3 - size - ieOffset), width + 6, 0 + size + 6);
/**
* If requested, draw a background for the text
*/
if (arguments[10]) {
var offset = 3;
var ieOffset = RGraph.isIE8() ? 2 : 0;
var width = context.measureText(text).width
//context.strokeStyle = 'gray';
context.fillStyle = arguments[10];
context.fillRect(AA(context.canvas.__object__, x - offset),
AA(context.canvas.__object__, y - size - offset - ieOffset),
width + (2 * offset),
size + (2 * offset));
//context.strokeRect(x - offset, y - size - offset - ieOffset, width + (2 * offset), size + (2 * offset));
}
/**
* Do the actual drawing of the text
*/
context.fillStyle = originalFillStyle;
//if (arguments[6] = 'center') {
// context.ttextBaseline = 'middle';
//}
context.fillText(text,0,0);
if (arguments[12]) {
context.fillRect(
arguments[7] == 'left' ? 0 : (arguments[7] == 'center' ? width / 2 : width ) - 2,
arguments[6] == 'bottom' ? 0 : (arguments[6] == 'center' ? (0 - size) / 2 : 0 - size) - 2,
4,
4
);
}
}
context.restore();
// Reset the lineWidth
context.lineWidth = originalLineWidth;
context.restore();
}
/**
* Clears the canvas by setting the width. You can specify a colour if you wish.
*
* @param object canvas The canvas to clear
*/
RGraph.Clear = function (canvas)
{
if (!canvas) {
return;
}
RGraph.FireCustomEvent(canvas.__object__, 'onbeforeclear');
var context = canvas.getContext('2d');
var color = arguments[1];
if (RGraph.isIE8() && !color) {
color = 'white';
}
/**
* Can now clear the canvas back to fully transparent
*/
if (!color || (color && color == 'transparent')) {
context.clearRect(0,0,canvas.width, canvas.height);
// Reset the globalCompositeOperation
context.globalCompositeOperation = 'source-over';
} else {
context.fillStyle = color;
context = canvas.getContext('2d');
context.beginPath();
if (RGraph.isIE8()) {
context.fillRect(0,0,canvas.width,canvas.height);
} else {
context.fillRect(-10,-10,canvas.width + 20,canvas.height + 20);
}
context.fill();
}
if (RGraph.ClearAnnotations) {
//RGraph.ClearAnnotations(canvas.id);
}
/**
* This removes any background image that may be present
*/
if (RGraph.Registry.Get('chart.background.image.' + canvas.id)) {
var img = RGraph.Registry.Get('chart.background.image.' + canvas.id);
img.style.position = 'absolute';
img.style.left = '-10000px';
img.style.top = '-10000px';
}
/**
* This hides the tooltip that is showing IF it has the same canvas ID as
* that which is being cleared
*/
if (RGraph.Registry.Get('chart.tooltip')) {
RGraph.HideTooltip();
//RGraph.Redraw();
}
/**
* Set the cursor to default
*/
canvas.style.cursor = 'default';
RGraph.FireCustomEvent(canvas.__object__, 'onclear');
}
/**
* Draws the title of the graph
*
* @param object canvas The canvas object
* @param string text The title to write
* @param integer gutter The size of the gutter
* @param integer The center X point (optional - if not given it will be generated from the canvas width)
* @param integer Size of the text. If not given it will be 14
*/
RGraph.DrawTitle = function (obj, text, gutterTop)
{
var canvas = obj.canvas;
var context = obj.context;
var gutterLeft = obj.Get('chart.gutter.left');
var gutterRight = obj.Get('chart.gutter.right');
var gutterBottom = obj.Get('chart.gutter.bottom');
var size = arguments[4] ? arguments[4] : 12;
var bold = obj.Get('chart.title.bold');
var centerx = (arguments[3] ? arguments[3] : ((obj.canvas.width - gutterLeft - gutterRight) / 2) + gutterLeft);
var keypos = obj.Get('chart.key.position');
var vpos = obj.Get('chart.title.vpos');
var hpos = obj.Get('chart.title.hpos');
var bgcolor = obj.Get('chart.title.background');
// Account for 3D effect by faking the key position
if (obj.type == 'bar' && obj.Get('chart.variant') == '3d') {
keypos = 'gutter';
}
context.beginPath();
context.fillStyle = obj.Get('chart.text.color') ? obj.Get('chart.text.color') : 'black';
/**
* Vertically center the text if the key is not present
*/
if (keypos && keypos != 'gutter') {
var vCenter = 'center';
} else if (!keypos) {
var vCenter = 'center';
} else {
var vCenter = 'bottom';
}
// if chart.title.vpos does not equal 0.5, use that
if (typeof(obj.Get('chart.title.vpos')) == 'number') {
vpos = obj.Get('chart.title.vpos') * gutterTop;
if (obj.Get('chart.xaxispos') == 'top') {
vpos = obj.Get('chart.title.vpos') * gutterBottom + gutterTop + (obj.canvas.height - gutterTop - gutterBottom);
}
} else {
vpos = gutterTop - size - 5;
if (obj.Get('chart.xaxispos') == 'top') {
vpos = obj.canvas.height - gutterBottom + size + 5;
}
}
// if chart.title.hpos is a number, use that. It's multiplied with the (entire) canvas width
if (typeof(hpos) == 'number') {
centerx = hpos * canvas.width;
}
// Set the colour
if (typeof(obj.Get('chart.title.color') != null)) {
var oldColor = context.fillStyle
var newColor = obj.Get('chart.title.color')
context.fillStyle = newColor ? newColor : 'black';
}
/**
* Default font is Verdana
*/
var font = obj.Get('chart.text.font');
/**
* Override the default font with chart.title.font
*/
if (typeof(obj.Get('chart.title.font')) == 'string') {
font = obj.Get('chart.title.font');
}
/**
* Draw the title itself
*/
RGraph.Text(context, font, size, centerx, vpos, text, vCenter, 'center', bgcolor != null, null, bgcolor, bold);
// Reset the fill colour
context.fillStyle = oldColor;
}
/**
* This function returns the mouse position in relation to the canvas
*
* @param object e The event object.
*
RGraph.getMouseXY = function (e)
{
var el = ((RGraph.isIE8() || RGraph.isIE7()) ? event.srcElement : e.target);
var x;
var y;
// ???
var paddingLeft = el.style.paddingLeft ? parseInt(el.style.paddingLeft) : 0;
var paddingTop = el.style.paddingTop ? parseInt(el.style.paddingTop) : 0;
var borderLeft = el.style.borderLeftWidth ? parseInt(el.style.borderLeftWidth) : 0;
var borderTop = el.style.borderTopWidth ? parseInt(el.style.borderTopWidth) : 0;
if (RGraph.isIE8()) e = event;
// Browser with offsetX and offsetY
if (typeof(e.offsetX) == 'number' && typeof(e.offsetY) == 'number') {
x = e.offsetX;
y = e.offsetY;
// FF and other
} else {
x = 0;
y = 0;
while (el != document.body && el) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
}
x = e.pageX - x;
y = e.pageY - y;
}
return [x, y];
}*/
RGraph.getMouseXY = function(e)
{
var el = e.target;
var ca = el;
var offsetX = 0;
var offsetY = 0;
var x;
var y;
// Add padding and border style widths to offset
var additionalX = (parseInt(ca.style.borderLeftWidth) || 0) + (parseInt(ca.style.paddingLeft) || 0);
var additionalY = (parseInt(ca.style.borderTopWidth) || 0) + (parseInt(ca.style.paddingTop) || 0);
if (typeof(e.offsetX) == 'number' && typeof(e.offsetY) == 'number') {
x = e.offsetX - additionalX;
y = e.offsetY - additionalY;
} else {
if (typeof(el.offsetParent) != 'undefined') {
do {
offsetX += el.offsetLeft;
offsetY += el.offsetTop;
} while ((el = el.offsetParent));
}
x = e.pageX - offsetX - additionalX;
y = e.pageY - offsetY - additionalY;
}
// We return a simple javascript object (a hash) with x and y defined
return [x, y];
}
/**
* This function returns a two element array of the canvas x/y position in
* relation to the page
*
* @param object canvas
*/
RGraph.getCanvasXY = function (canvas)
{
var x = 0;
var y = 0;
var obj = canvas;
do {
x += obj.offsetLeft;
y += obj.offsetTop;
obj = obj.offsetParent;
} while (obj && obj.tagName.toLowerCase() != 'body');
var paddingLeft = canvas.style.paddingLeft ? parseInt(canvas.style.paddingLeft) : 0;
var paddingTop = canvas.style.paddingTop ? parseInt(canvas.style.paddingTop) : 0;
var borderLeft = canvas.style.borderLeftWidth ? parseInt(canvas.style.borderLeftWidth) : 0;
var borderTop = canvas.style.borderTopWidth ? parseInt(canvas.style.borderTopWidth) : 0;
return [x + paddingLeft + borderLeft, y + paddingTop + borderTop];
}
/**
* Registers a graph object (used when the canvas is redrawn)
*
* @param object obj The object to be registered
*/
RGraph.Register = function (obj)
{
// Checking this property ensures the object is only registered once
if (!obj.Get('chart.noregister')) {
// As of 21st/1/2012 the object registry is now used
RGraph.ObjectRegistry.Add(obj);
obj.Set('chart.noregister', true);
}
}
/**
* Causes all registered objects to be redrawn
*
* @param string An optional color to use to clear the canvas
*/
RGraph.Redraw = function ()
{
var objectRegistry = RGraph.ObjectRegistry.objects.byCanvasID;
// Get all of the canvas tags on the page
var tags = document.getElementsByTagName('canvas');
for (var i=0; i<tags.length; ++i) {
if (tags[i].__object__ && tags[i].__object__.isRGraph) {
RGraph.Clear(tags[i], arguments[0] ? arguments[0] : null);
}
}
// Go through the object registry and redraw *all* of the canvas'es that have been registered
for (var i=0; i<objectRegistry.length; ++i) {
if (objectRegistry[i]) {
var id = objectRegistry[i][0];
objectRegistry[i][1].Draw();
}
}
}
/**
* Causes all registered objects ON THE GIVEN CANVAS to be redrawn
*
* @param canvas object The canvas object to redraw
* @param bool Optional boolean which defaults to true and determines whether to clear the canvas
*/
RGraph.RedrawCanvas = function (canvas)
{
var objects = RGraph.ObjectRegistry.getObjectsByCanvasID(canvas.id);
/**
* First clear the canvas
*/
if (!arguments[1] || (typeof(arguments[1]) == 'boolean' && !arguments[1] == false) ) {
RGraph.Clear(canvas);
}
/**
* Now redraw all the charts associated with that canvas
*/
for (var i=0; i<objects.length; ++i) {
if (objects[i]) {
if (objects[i] && objects[i].isRGraph) { // Is it an RGraph object ??
objects[i].Draw();
}
}
}
}
/**
* This function draws the background for the bar chart, line chart and scatter chart.
*
* @param object obj The graph object
*/
RGraph.background.Draw = function (obj)
{
var canvas = obj.canvas;
var context = obj.context;
var height = 0;
var gutterLeft = obj.Get('chart.gutter.left');
var gutterRight = obj.Get('chart.gutter.right');
var gutterTop = obj.Get('chart.gutter.top');
var gutterBottom = obj.Get('chart.gutter.bottom');
var variant = obj.Get('chart.variant');
context.fillStyle = obj.Get('chart.text.color');
// If it's a bar and 3D variant, translate
if (variant == '3d') {
context.save();
context.translate(10, -5);
}
// X axis title
if (typeof(obj.Get('chart.title.xaxis')) == 'string' && obj.Get('chart.title.xaxis').length) {
var size = obj.Get('chart.text.size') + 2;
var font = obj.Get('chart.text.font');
var bold = obj.Get('chart.title.xaxis.bold');
if (typeof(obj.Get('chart.title.xaxis.size')) == 'number') {
size = obj.Get('chart.title.xaxis.size');
}
if (typeof(obj.Get('chart.title.xaxis.font')) == 'string') {
font = obj.Get('chart.title.xaxis.font');
}
var hpos = ((obj.canvas.width - obj.gutterLeft - obj.gutterRight) / 2) + obj.gutterLeft;
var vpos = obj.canvas.height - obj.Get('chart.gutter.bottom') + 25;
if (typeof(obj.Get('chart.title.xaxis.pos')) == 'number') {
vpos = obj.canvas.height - (gutterBottom * obj.Get('chart.title.xaxis.pos'));
}
context.beginPath();
RGraph.Text(context,
font,
size,
hpos,
vpos,
obj.Get('chart.title.xaxis'),
'center',
'center',
false,
false,
false,
bold);
context.fill();
}
// Y axis title
if (typeof(obj.Get('chart.title.yaxis')) == 'string' && obj.Get('chart.title.yaxis').length) {
var size = obj.Get('chart.text.size') + 2;
var font = obj.Get('chart.text.font');
var angle = 270;
var bold = obj.Get('chart.title.yaxis.bold');
var color = obj.Get('chart.title.yaxis.color');
if (typeof(obj.Get('chart.title.yaxis.pos')) == 'number') {
var yaxis_title_pos = obj.Get('chart.title.yaxis.pos') * obj.Get('chart.gutter.left');
} else {
var yaxis_title_pos = ((obj.Get('chart.gutter.left') - 25) / obj.Get('chart.gutter.left')) * obj.Get('chart.gutter.left');
}
if (typeof(obj.Get('chart.title.yaxis.size')) == 'number') {
size = obj.Get('chart.title.yaxis.size');
}
if (typeof(obj.Get('chart.title.yaxis.font')) == 'string') {
font = obj.Get('chart.title.yaxis.font');
}
if (obj.Get('chart.title.yaxis.align') == 'right' || obj.Get('chart.title.yaxis.position') == 'right') {
angle = 90;
yaxis_title_pos = obj.Get('chart.title.yaxis.pos') ? (obj.canvas.width - obj.Get('chart.gutter.right')) + (obj.Get('chart.title.yaxis.pos') * obj.Get('chart.gutter.right')) :
obj.canvas.width - obj.Get('chart.gutter.right') + obj.Get('chart.text.size') + 5;
} else {
yaxis_title_pos = yaxis_title_pos;
}
context.beginPath();
context.fillStyle = color;
RGraph.Text(context,
font,
size,
yaxis_title_pos,
((obj.canvas.height - obj.gutterTop - obj.gutterBottom) / 2) + obj.gutterTop,
obj.Get('chart.title.yaxis'),
'center',
'center',
false,
angle,
false,
bold);
context.fill();
}
obj.context.beginPath();
// Draw the horizontal bars
context.fillStyle = obj.Get('chart.background.barcolor1');
height = (obj.canvas.height - gutterBottom);
for (var i=gutterTop; i < height ; i+=80) {
obj.context.fillRect(gutterLeft, i, RGraph.GetWidth(obj) - gutterLeft - gutterRight, Math.min(40, RGraph.GetHeight(obj) - gutterBottom - i) );
}
context.fillStyle = obj.Get('chart.background.barcolor2');
height = (RGraph.GetHeight(obj) - gutterBottom);
for (var i= (40 + gutterTop); i < height; i+=80) {
obj.context.fillRect(gutterLeft, i, RGraph.GetWidth(obj) - gutterLeft - gutterRight, i + 40 > (RGraph.GetHeight(obj) - gutterBottom) ? RGraph.GetHeight(obj) - (gutterBottom + i) : 40);
}
context.stroke();
// Draw the background grid
if (obj.Get('chart.background.grid')) {
// If autofit is specified, use the .numhlines and .numvlines along with the width to work
// out the hsize and vsize
if (obj.Get('chart.background.grid.autofit')) {
/**
* Align the grid to the tickmarks
*/
if (obj.Get('chart.background.grid.autofit.align')) {
// Align the horizontal lines
obj.Set('chart.background.grid.autofit.numhlines', obj.Get('chart.ylabels.count'));
// Align the vertical lines for the line
if (obj.type == 'line') {
if (obj.Get('chart.labels') && obj.Get('chart.labels').length) {
obj.Set('chart.background.grid.autofit.numvlines', obj.Get('chart.labels').length - 1);
} else {
obj.Set('chart.background.grid.autofit.numvlines', obj.data[0].length - 1);
}
// Align the vertical lines for the bar
} else if (obj.type == 'bar' && obj.Get('chart.labels') && obj.Get('chart.labels').length) {
obj.Set('chart.background.grid.autofit.numvlines', obj.Get('chart.labels').length);
}
}
var vsize = ((obj.canvas.width - gutterLeft - gutterRight)) / obj.Get('chart.background.grid.autofit.numvlines');
var hsize = (obj.canvas.height - gutterTop - gutterBottom) / obj.Get('chart.background.grid.autofit.numhlines');
obj.Set('chart.background.grid.vsize', vsize);
obj.Set('chart.background.grid.hsize', hsize);
}
context.beginPath();
context.lineWidth = obj.Get('chart.background.grid.width') ? obj.Get('chart.background.grid.width') : 1;
context.strokeStyle = obj.Get('chart.background.grid.color');
// Draw the horizontal lines
if (obj.Get('chart.background.grid.hlines')) {
height = (RGraph.GetHeight(obj) - gutterBottom)
for (y=gutterTop; y<height; y+=obj.Get('chart.background.grid.hsize')) {
context.moveTo(gutterLeft, AA(this, y));
context.lineTo(RGraph.GetWidth(obj) - gutterRight, AA(this, y));
}
}
if (obj.Get('chart.background.grid.vlines')) {
// Draw the vertical lines
var width = (obj.canvas.width - gutterRight)
for (x=gutterLeft; x<=width; x+=obj.Get('chart.background.grid.vsize')) {
context.moveTo(AA(this, x), gutterTop);
context.lineTo(AA(this, x), obj.canvas.height - gutterBottom);
}
}
if (obj.Get('chart.background.grid.border')) {
// Make sure a rectangle, the same colour as the grid goes around the graph
context.strokeStyle = obj.Get('chart.background.grid.color');
context.strokeRect(AA(this, gutterLeft), AA(this, gutterTop), RGraph.GetWidth(obj) - gutterLeft - gutterRight, RGraph.GetHeight(obj) - gutterTop - gutterBottom);
}
}
context.stroke();
// If it's a bar and 3D variant, translate
if (variant == '3d') {
context.restore();
}
// Draw the title if one is set
if ( typeof(obj.Get('chart.title')) == 'string') {
if (obj.type == 'gantt') {
gutterTop -= 10;
}
RGraph.DrawTitle(obj,
obj.Get('chart.title'),
gutterTop,
null,
obj.Get('chart.title.size') ? obj.Get('chart.title.size') : obj.Get('chart.text.size') + 2);
}
context.stroke();
}
/**
* Returns the day number for a particular date. Eg 1st February would be 32
*
* @param object obj A date object
* @return int The day number of the given date
*/
RGraph.GetDays = function (obj)
{
var year = obj.getFullYear();
var days = obj.getDate();
var month = obj.getMonth();
if (month == 0) return days;
if (month >= 1) days += 31;
if (month >= 2) days += 28;
// Leap years. Crude, but it functions
if (year >= 2008 && year % 4 == 0) days += 1;
if (month >= 3) days += 31;
if (month >= 4) days += 30;
if (month >= 5) days += 31;
if (month >= 6) days += 30;
if (month >= 7) days += 31;
if (month >= 8) days += 31;
if (month >= 9) days += 30;
if (month >= 10) days += 31;
if (month >= 11) days += 30;
return days;
}
/**
* Makes a clone of an object
*
* @param obj val The object to clone
*/
RGraph.array_clone = function (obj)
{
if(obj == null || typeof(obj) != 'object') {
return obj;
}
var temp = [];
for (var i=0;i<obj.length; ++i) {
if (typeof(obj[i]) == 'number') {
temp[i] = (function (arg) {return Number(arg);})(obj[i]);
} else if (typeof(obj[i]) == 'string') {
temp[i] = (function (arg) {return String(arg);})(obj[i]);
} else if (typeof(obj[i]) == 'function') {
temp[i] = obj[i];
} else {
temp[i] = RGraph.array_clone(obj[i]);
}
}
return temp;
}
/**
* Formats a number with thousand seperators so it's easier to read
*
* @param integer obj The chart object
* @param integer num The number to format
* @param string The (optional) string to prepend to the string
* @param string The (optional) string to append to the string
* @return string The formatted number
*/
RGraph.number_format = function (obj, num)
{
var i;
var prepend = arguments[2] ? String(arguments[2]) : '';
var append = arguments[3] ? String(arguments[3]) : '';
var output = '';
var decimal = '';
var decimal_seperator = obj.Get('chart.scale.point') ? obj.Get('chart.scale.point') : '.';
var thousand_seperator = obj.Get('chart.scale.thousand') ? obj.Get('chart.scale.thousand') : ',';
RegExp.$1 = '';
var i,j;
if (typeof(obj.Get('chart.scale.formatter')) == 'function') {
return obj.Get('chart.scale.formatter')(obj, num);
}
// Ignore the preformatted version of "1e-2"
if (String(num).indexOf('e') > 0) {
return String(prepend + String(num) + append);
}
// We need then number as a string
num = String(num);
// Take off the decimal part - we re-append it later
if (num.indexOf('.') > 0) {
var tmp = num;
num = num.replace(/\.(.*)/, ''); // The front part of the number
decimal = tmp.replace(/(.*)\.(.*)/, '$2'); // The decimal part of the number
}
// Thousand seperator
//var seperator = arguments[1] ? String(arguments[1]) : ',';
var seperator = thousand_seperator;
/**
* Work backwards adding the thousand seperators
*/
var foundPoint;
for (i=(num.length - 1),j=0; i>=0; j++,i--) {
var character = num.charAt(i);
if ( j % 3 == 0 && j != 0) {
output += seperator;
}
/**
* Build the output
*/
output += character;
}
/**
* Now need to reverse the string
*/
var rev = output;
output = '';
for (i=(rev.length - 1); i>=0; i--) {
output += rev.charAt(i);
}
// Tidy up
//output = output.replace(/^-,/, '-');
if (output.indexOf('-' + obj.Get('chart.scale.thousand')) == 0) {
output = '-' + output.substr(('-' + obj.Get('chart.scale.thousand')).length);
}
// Reappend the decimal
if (decimal.length) {
output = output + decimal_seperator + decimal;
decimal = '';
RegExp.$1 = '';
}
// Minor bugette
if (output.charAt(0) == '-') {
output = output.replace(/-/, '');
prepend = '-' + prepend;
}
return prepend + output + append;
}
/**
* Draws horizontal coloured bars on something like the bar, line or scatter
*/
RGraph.DrawBars = function (obj)
{
var hbars = obj.Get('chart.background.hbars');
/**
* Draws a horizontal bar
*/
obj.context.beginPath();
for (i=0; i<hbars.length; ++i) {
// If null is specified as the "height", set it to the upper max value
if (hbars[i][1] == null) {
hbars[i][1] = obj.max;
// If the first index plus the second index is greater than the max value, adjust accordingly
} else if (hbars[i][0] + hbars[i][1] > obj.max) {
hbars[i][1] = obj.max - hbars[i][0];
}
// If height is negative, and the abs() value is greater than .max, use a negative max instead
if (Math.abs(hbars[i][1]) > obj.max) {
hbars[i][1] = -1 * obj.max;
}
// If start point is greater than max, change it to max
if (Math.abs(hbars[i][0]) > obj.max) {
hbars[i][0] = obj.max;
}
// If start point plus height is less than negative max, use the negative max plus the start point
if (hbars[i][0] + hbars[i][1] < (-1 * obj.max) ) {
hbars[i][1] = -1 * (obj.max + hbars[i][0]);
}
// If the X axis is at the bottom, and a negative max is given, warn the user
if (obj.Get('chart.xaxispos') == 'bottom' && (hbars[i][0] < 0 || (hbars[i][1] + hbars[i][1] < 0)) ) {
alert('[' + obj.type.toUpperCase() + ' (ID: ' + obj.id + ') BACKGROUND HBARS] You have a negative value in one of your background hbars values, whilst the X axis is in the center');
}
var ystart = (obj.grapharea - (((hbars[i][0] - obj.min) / (obj.max - obj.min)) * obj.grapharea));
var height = (Math.min(hbars[i][1], obj.max - hbars[i][0]) / (obj.max - obj.min)) * obj.grapharea;
// Account for the X axis being in the center
if (obj.Get('chart.xaxispos') == 'center') {
ystart /= 2;
height /= 2;
}
ystart += obj.Get('chart.gutter.top')
var x = obj.Get('chart.gutter.left');
var y = ystart - height;
var w = obj.canvas.width - obj.Get('chart.gutter.left') - obj.Get('chart.gutter.right');
var h = height;
// Accommodate Opera :-/
if (navigator.userAgent.indexOf('Opera') != -1 && obj.Get('chart.xaxispos') == 'center' && h < 0) {
h *= -1;
y = y - h;
}
/**
* Account for X axis at the top
*/
if (obj.Get('chart.xaxispos') == 'top') {
y = obj.canvas.height - y;
h *= -1;
}
obj.context.fillStyle = hbars[i][2];
obj.context.fillRect(x, y, w, h);
}
obj.context.fill();
}
/**
* Draws in-graph labels.
*
* @param object obj The graph object
*/
RGraph.DrawInGraphLabels = function (obj)
{
var canvas = obj.canvas;
var context = obj.context;
var labels = obj.Get('chart.labels.ingraph');
var labels_processed = [];
// Defaults
var fgcolor = 'black';
var bgcolor = 'white';
var direction = 1;
if (!labels) {
return;
}
/**
* Preprocess the labels array. Numbers are expanded
*/
for (var i=0; i<labels.length; ++i) {
if (typeof(labels[i]) == 'number') {
for (var j=0; j<labels[i]; ++j) {
labels_processed.push(null);
}
} else if (typeof(labels[i]) == 'string' || typeof(labels[i]) == 'object') {
labels_processed.push(labels[i]);
} else {
labels_processed.push('');
}
}
/**
* Turn off any shadow
*/
RGraph.NoShadow(obj);
if (labels_processed && labels_processed.length > 0) {
for (var i=0; i<labels_processed.length; ++i) {
if (labels_processed[i]) {
var coords = obj.coords[i];
if (coords && coords.length > 0) {
var x = (obj.type == 'bar' ? coords[0] + (coords[2] / 2) : coords[0]);
var y = (obj.type == 'bar' ? coords[1] + (coords[3] / 2) : coords[1]);
var length = typeof(labels_processed[i][4]) == 'number' ? labels_processed[i][4] : 25;
context.beginPath();
context.fillStyle = 'black';
context.strokeStyle = 'black';
if (obj.type == 'bar') {
/**
* X axis at the top
*/
if (obj.Get('chart.xaxispos') == 'top') {
length *= -1;
}
if (obj.Get('chart.variant') == 'dot') {
context.moveTo(AA(obj, x), obj.coords[i][1] - 5);
context.lineTo(AA(obj, x), obj.coords[i][1] - 5 - length);
var text_x = AA(obj, x);
var text_y = obj.coords[i][1] - 5 - length;
} else if (obj.Get('chart.variant') == 'arrow') {
context.moveTo(AA(obj, x), obj.coords[i][1] - 5);
context.lineTo(AA(obj, x), obj.coords[i][1] - 5 - length);
var text_x = AA(obj, x);
var text_y = obj.coords[i][1] - 5 - length;
} else {
context.arc(AA(obj, x), y, 2.5, 0, 6.28, 0);
context.moveTo(AA(obj, x), y);
context.lineTo(AA(obj, x), y - length);
var text_x = AA(obj, x);
var text_y = y - length;
}
context.stroke();
context.fill();
} else if (obj.type == 'line') {
if (
typeof(labels_processed[i]) == 'object' &&
typeof(labels_processed[i][3]) == 'number' &&
labels_processed[i][3] == -1
) {
context.moveTo(AA(obj, x), y + 5);
context.lineTo(AA(obj, x), y + 5 + length);
context.stroke();
context.beginPath();
// This draws the arrow
context.moveTo(AA(obj, x), y + 5);
context.lineTo(AA(obj, x) - 3, y + 10);
context.lineTo(AA(obj, x) + 3, y + 10);
context.closePath();
var text_x = x;
var text_y = y + 5 + length;
} else {
var text_x = x;
var text_y = y - 5 - length;
context.moveTo(AA(obj, x), y - 5);
context.lineTo(AA(obj, x), y - 5 - length);
context.stroke();
context.beginPath();
// This draws the arrow
context.moveTo(AA(obj, x), y - 5);
context.lineTo(AA(obj, x) - 3, y - 10);
context.lineTo(AA(obj, x) + 3, y - 10);
context.closePath();
}
context.fill();
}
// Taken out on the 10th Nov 2010 - unnecessary
//var width = context.measureText(labels[i]).width;
context.beginPath();
// Fore ground color
context.fillStyle = (typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][1]) == 'string') ? labels_processed[i][1] : 'black';
RGraph.Text(context,
obj.Get('chart.text.font'),
obj.Get('chart.text.size'),
text_x,
text_y,
(typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][0]) == 'string') ? labels_processed[i][0] : labels_processed[i],
'bottom',
'center',
true,
null,
(typeof(labels_processed[i]) == 'object' && typeof(labels_processed[i][2]) == 'string') ? labels_processed[i][2] : 'white');
context.fill();
}
}
}
}
}
/**
* This function "fills in" key missing properties that various implementations lack
*
* @param object e The event object
*/
RGraph.FixEventObject = function (e)
{
if (RGraph.isIE8() || RGraph.isIE7()) {
var e = event;
e.pageX = (event.clientX + document.body.scrollLeft);
e.pageY = (event.clientY + document.body.scrollTop);
e.target = event.srcElement;
if (!document.body.scrollTop && document.documentElement.scrollTop) {
e.pageX += parseInt(document.documentElement.scrollLeft);
e.pageY += parseInt(document.documentElement.scrollTop);
}
}
// This is mainly for FF which doesn't provide offsetX
if (typeof(e.offsetX) == 'undefined' && typeof(e.offsetY) == 'undefined') {
var coords = RGraph.getMouseXY(e);
e.offsetX = coords[0];
e.offsetY = coords[1];
}
// Any browser that doesn't implement stopPropagation() (MSIE)
if (!e.stopPropagation) {
e.stopPropagation = function () {window.event.cancelBubble = true;}
}
return e;
}
/**
* Thisz function hides the crosshairs coordinates
*/
RGraph.HideCrosshairCoords = function ()
{
var div = RGraph.Registry.Get('chart.coordinates.coords.div');
if ( div
&& div.style.opacity == 1
&& div.__object__.Get('chart.crosshairs.coords.fadeout')
) {
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.9;}, 50);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.8;}, 100);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.7;}, 150);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.6;}, 200);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.5;}, 250);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.4;}, 300);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.3;}, 350);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.2;}, 400);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0.1;}, 450);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.opacity = 0;}, 500);
setTimeout(function() {RGraph.Registry.Get('chart.coordinates.coords.div').style.display = 'none';}, 550);
}
}
/**
* Draws the3D axes/background
*/
RGraph.Draw3DAxes = function (obj)
{
var gutterLeft = obj.Get('chart.gutter.left');
var gutterRight = obj.Get('chart.gutter.right');
var gutterTop = obj.Get('chart.gutter.top');
var gutterBottom = obj.Get('chart.gutter.bottom');
var context = obj.context;
var canvas = obj.canvas;
context.strokeStyle = '#aaa';
context.fillStyle = '#ddd';
// Draw the vertical left side
context.beginPath();
context.moveTo(gutterLeft, gutterTop);
context.lineTo(gutterLeft + 10, gutterTop - 5);
context.lineTo(gutterLeft + 10, canvas.height - gutterBottom - 5);
context.lineTo(gutterLeft, canvas.height - gutterBottom);
context.closePath();
context.stroke();
context.fill();
// Draw the bottom floor
context.beginPath();
context.moveTo(gutterLeft, canvas.height - gutterBottom);
context.lineTo(gutterLeft + 10, canvas.height - gutterBottom - 5);
context.lineTo(canvas.width - gutterRight + 10, canvas.height - gutterBottom - 5);
context.lineTo(canvas.width - gutterRight, canvas.height - gutterBottom);
context.closePath();
context.stroke();
context.fill();
}
/**
* This function attempts to "fill in" missing functions from the canvas
* context object. Only two at the moment - measureText() nd fillText().
*
* @param object context The canvas 2D context
*/
RGraph.OldBrowserCompat = function (context)
{
if (!context) {
return;
}
if (!context.measureText) {
// This emulates the measureText() function
context.measureText = function (text)
{
var textObj = document.createElement('DIV');
textObj.innerHTML = text;
textObj.style.position = 'absolute';
textObj.style.top = '-100px';
textObj.style.left = 0;
document.body.appendChild(textObj);
var width = {width: textObj.offsetWidth};
textObj.style.display = 'none';
return width;
}
}
if (!context.fillText) {
// This emulates the fillText() method
context.fillText = function (text, targetX, targetY)
{
return false;
}
}
// If IE8, add addEventListener()
if (!context.canvas.addEventListener) {
window.addEventListener = function (ev, func, bubble)
{
return this.attachEvent('on' + ev, func);
}
context.canvas.addEventListener = function (ev, func, bubble)
{
return this.attachEvent('on' + ev, func);
}
}
}
/**
* Draws a rectangle with curvy corners
*
* @param context object The context
* @param x number The X coordinate (top left of the square)
* @param y number The Y coordinate (top left of the square)
* @param w number The width of the rectangle
* @param h number The height of the rectangle
* @param number The radius of the curved corners
* @param boolean Whether the top left corner is curvy
* @param boolean Whether the top right corner is curvy
* @param boolean Whether the bottom right corner is curvy
* @param boolean Whether the bottom left corner is curvy
*/
RGraph.strokedCurvyRect = function (context, x, y, w, h)
{
// The corner radius
var r = arguments[5] ? arguments[5] : 3;
// The corners
var corner_tl = (arguments[6] || arguments[6] == null) ? true : false;
var corner_tr = (arguments[7] || arguments[7] == null) ? true : false;
var corner_br = (arguments[8] || arguments[8] == null) ? true : false;
var corner_bl = (arguments[9] || arguments[9] == null) ? true : false;
context.beginPath();
// Top left side
context.moveTo(x + (corner_tl ? r : 0), y);
context.lineTo(x + w - (corner_tr ? r : 0), y);
// Top right corner
if (corner_tr) {
context.arc(x + w - r, y + r, r, PI + HALFPI, TWOPI, false);
}
// Top right side
context.lineTo(x + w, y + h - (corner_br ? r : 0) );
// Bottom right corner
if (corner_br) {
context.arc(x + w - r, y - r + h, r, TWOPI, HALFPI, false);
}
// Bottom right side
context.lineTo(x + (corner_bl ? r : 0), y + h);
// Bottom left corner
if (corner_bl) {
context.arc(x + r, y - r + h, r, HALFPI, PI, false);
}
// Bottom left side
context.lineTo(x, y + (corner_tl ? r : 0) );
// Top left corner
if (corner_tl) {
context.arc(x + r, y + r, r, PI, PI + HALFPI, false);
}
context.stroke();
}
/**
* Draws a filled rectangle with curvy corners
*
* @param context object The context
* @param x number The X coordinate (top left of the square)
* @param y number The Y coordinate (top left of the square)
* @param w number The width of the rectangle
* @param h number The height of the rectangle
* @param number The radius of the curved corners
* @param boolean Whether the top left corner is curvy
* @param boolean Whether the top right corner is curvy
* @param boolean Whether the bottom right corner is curvy
* @param boolean Whether the bottom left corner is curvy
*/
RGraph.filledCurvyRect = function (context, x, y, w, h)
{
// The corner radius
var r = arguments[5] ? arguments[5] : 3;
// The corners
var corner_tl = (arguments[6] || arguments[6] == null) ? true : false;
var corner_tr = (arguments[7] || arguments[7] == null) ? true : false;
var corner_br = (arguments[8] || arguments[8] == null) ? true : false;
var corner_bl = (arguments[9] || arguments[9] == null) ? true : false;
context.beginPath();
// First draw the corners
// Top left corner
if (corner_tl) {
context.moveTo(x + r, y + r);
context.arc(x + r, y + r, r, PI, PI + HALFPI, false);
} else {
context.fillRect(x, y, r, r);
}
// Top right corner
if (corner_tr) {
context.moveTo(x + w - r, y + r);
context.arc(x + w - r, y + r, r, PI + HALFPI, 0, false);
} else {
context.moveTo(x + w - r, y);
context.fillRect(x + w - r, y, r, r);
}
// Bottom right corner
if (corner_br) {
context.moveTo(x + w - r, y + h - r);
context.arc(x + w - r, y - r + h, r, 0, HALFPI, false);
} else {
context.moveTo(x + w - r, y + h - r);
context.fillRect(x + w - r, y + h - r, r, r);
}
// Bottom left corner
if (corner_bl) {
context.moveTo(x + r, y + h - r);
context.arc(x + r, y - r + h, r, HALFPI, PI, false);
} else {
context.moveTo(x, y + h - r);
context.fillRect(x, y + h - r, r, r);
}
// Now fill it in
context.fillRect(x + r, y, w - r - r, h);
context.fillRect(x, y + r, r + 1, h - r - r);
context.fillRect(x + w - r - 1, y + r, r + 1, h - r - r);
context.fill();
}
/**
* Hides the zoomed canvas
*/
RGraph.HideZoomedCanvas = function ()
{
var interval = 15;
var frames = 10;
if (typeof(__zoomedimage__) == 'object') {
obj = __zoomedimage__.obj;
} else {
return;
}
if (obj.Get('chart.zoom.fade.out')) {
for (var i=frames,j=1; i>=0; --i, ++j) {
if (typeof(__zoomedimage__) == 'object') {
setTimeout("__zoomedimage__.style.opacity = " + String(i / 10), j * interval);
}
}
if (typeof(__zoomedbackground__) == 'object') {
setTimeout("__zoomedbackground__.style.opacity = " + String(i / frames), j * interval);
}
}
if (typeof(__zoomedimage__) == 'object') {
setTimeout("__zoomedimage__.style.display = 'none'", obj.Get('chart.zoom.fade.out') ? (frames * interval) + 10 : 0);
}
if (typeof(__zoomedbackground__) == 'object') {
setTimeout("__zoomedbackground__.style.display = 'none'", obj.Get('chart.zoom.fade.out') ? (frames * interval) + 10 : 0);
}
}
/**
* Adds an event handler
*
* @param object obj The graph object
* @param string event The name of the event, eg ontooltip
* @param object func The callback function
*/
RGraph.AddCustomEventListener = function (obj, name, func)
{
if (typeof(RGraph.events[obj.uid]) == 'undefined') {
RGraph.events[obj.uid] = [];
}
RGraph.events[obj.uid].push([obj, name, func]);
return RGraph.events[obj.uid].length - 1;
}
/**
* Used to fire one of the RGraph custom events
*
* @param object obj The graph object that fires the event
* @param string event The name of the event to fire
*/
RGraph.FireCustomEvent = function (obj, name)
{
if (obj && obj.isRGraph) {
// New style of adding custom events
if (obj[name]) {
(obj[name])(obj);
}
var uid = obj.uid;
if ( typeof(uid) == 'string'
&& typeof(RGraph.events) == 'object'
&& typeof(RGraph.events[uid]) == 'object'
&& RGraph.events[uid].length > 0) {
for(var j=0; j<RGraph.events[uid].length; ++j) {
if (RGraph.events[uid][j] && RGraph.events[uid][j][1] == name) {
RGraph.events[uid][j][2](obj);
}
}
}
}
}
/**
* This function suggests a gutter size based on the widest left label. Given that the bottom
* labels may be longer, this may be a little out.
*
* @param object obj The graph object
* @param array data An array of graph data
* @return int A suggested gutter setting
*/
RGraph.getGutterSuggest = function (obj, data)
{
/**
* Calculate the minimum value
*/
var min = 0;
for (var i=0; i<data.length; ++i) {
min = Math.min(min, data[i]);
}
var min = Math.abs(min);
var str = RGraph.number_format(obj, RGraph.array_max(RGraph.getScale(Math.max(min, RGraph.array_max(data)), obj)), obj.Get('chart.units.pre'), obj.Get('chart.units.post'));
// Take into account the HBar
if (obj.type == 'hbar') {
var str = '';
var len = 0;
for (var i=0; i<obj.Get('chart.labels').length; ++i) {
str = (obj.Get('chart.labels').length > str.length ? obj.Get('chart.labels')[i] : str);
}
}
obj.context.font = obj.Get('chart.text.size') + 'pt ' + obj.Get('chart.text.font');
len = obj.context.measureText(str).width + 5;
return (obj.type == 'hbar' ? len / 3 : len);
}
/**
* If you prefer, you can use the SetConfig() method to set the configuration information
* for your chart. You may find that setting the configuration this way eases reuse.
*
* @param object obj The graph object
* @param object config The graph configuration information
*/
RGraph.SetConfig = function (obj, c)
{
for (i in c) {
if (typeof(i) == 'string') {
obj.Set(i, c[i]);
}
}
return obj;
}
/**
* Clears all the custom event listeners that have been registered
*
* @param string Limits the clearing to this object ID
*/
RGraph.RemoveAllCustomEventListeners = function ()
{
var id = arguments[0];
if (id && RGraph.events[id]) {
RGraph.events[id] = [];
} else {
RGraph.events = [];
}
}
/**
* Clears a particular custom event listener
*
* @param object obj The graph object
* @param number i This is the index that is return by .AddCustomEventListener()
*/
RGraph.RemoveCustomEventListener = function (obj, i)
{
if ( typeof(RGraph.events) == 'object'
&& typeof(RGraph.events[obj.id]) == 'object'
&& typeof(RGraph.events[obj.id][i]) == 'object') {
RGraph.events[obj.id][i] = null;
}
}
/**
* This draws the background
*
* @param object obj The graph object
*/
RGraph.DrawBackgroundImage = function (obj)
{
if (typeof(obj.Get('chart.background.image')) == 'string') {
if (typeof(obj.canvas.__rgraph_background_image__) == 'undefined') {
var img = new Image();
img.__object__ = obj;
img.__canvas__ = obj.canvas;
img.__context__ = obj.context;
img.src = obj.Get('chart.background.image');
obj.canvas.__rgraph_background_image__ = img;
} else {
img = obj.canvas.__rgraph_background_image__;
}
// When the image has loaded - redraw the canvas
img.onload = function ()
{
RGraph.Clear(obj.canvas);
RGraph.RedrawCanvas(obj.canvas);
}
var gutterLeft = obj.Get('chart.gutter.left');
var gutterRight = obj.Get('chart.gutter.right');
var gutterTop = obj.Get('chart.gutter.top');
var gutterBottom = obj.Get('chart.gutter.bottom');
var stretch = obj.Get('chart.background.image.stretch');
var align = obj.Get('chart.background.image.align');
// Handle chart.background.image.align
if (typeof(align) == 'string') {
if (align.indexOf('right') != -1) {
var x = obj.canvas.width - img.width - gutterRight;
} else {
var x = gutterLeft;
}
if (align.indexOf('bottom') != -1) {
var y = obj.canvas.height - img.height - gutterBottom;
} else {
var y = gutterTop;
}
} else {
var x = gutterLeft;
var y = gutterTop;
}
// X/Y coords take precedence over the align
var x = typeof(obj.Get('chart.background.image.x')) == 'number' ? obj.Get('chart.background.image.x') : x;
var y = typeof(obj.Get('chart.background.image.y')) == 'number' ? obj.Get('chart.background.image.y') : y;
var w = stretch ? obj.canvas.width - gutterLeft - gutterRight : img.width;
var h = stretch ? obj.canvas.height - gutterTop - gutterBottom : img.height;
/**
* You can now specify the width and height of the image
*/
if (typeof(obj.Get('chart.background.image.w')) == 'number') w = obj.Get('chart.background.image.w');
if (typeof(obj.Get('chart.background.image.h')) == 'number') h = obj.Get('chart.background.image.h');
obj.context.drawImage(img,x,y,w, h);
}
}
/**
* This function determines wshether an object has tooltips or not
*
* @param object obj The chart object
*/
RGraph.hasTooltips = function (obj)
{
if (typeof(obj.Get('chart.tooltips')) == 'object' && obj.Get('chart.tooltips')) {
for (var i=0; i<obj.Get('chart.tooltips').length; ++i) {
if (!RGraph.is_null(obj.Get('chart.tooltips')[i])) {
return true;
}
}
} else if (typeof(obj.Get('chart.tooltips')) == 'function') {
return true;
}
return false;
}
/**
* This function creates a (G)UID which can be used to identify objects.
*
* @return string (g)uid The (G)UID
*/
RGraph.CreateUID = function ()
{
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)
{
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
/**
* This is the new object registry, used to facilitate multiple objects per canvas.
*
* @param object obj The object to register
*/
RGraph.ObjectRegistry.Add = function (obj)
{
var uid = obj.uid;
var canvasID = obj.canvas.id;
/**
* Index the objects by UID
*/
RGraph.ObjectRegistry.objects.byUID.push([uid, obj]);
/**
* Index the objects by the canvas that they're drawn on
*/
RGraph.ObjectRegistry.objects.byCanvasID.push([canvasID, obj]);
}
/**
* Remove an object from the object registry
*
* @param object obj The object to remove.
*/
RGraph.ObjectRegistry.Remove = function (obj)
{
var id = obj.id;
var uid = obj.uid;
for (var i=0; i<RGraph.ObjectRegistry.objects.byUID.length; ++i) {
if (RGraph.ObjectRegistry.objects.byUID[i] && RGraph.ObjectRegistry.objects.byUID[i][1].uid == uid) {
RGraph.ObjectRegistry.objects.byUID[i] = null;
}
}
// RGraph.ObjectRegistry.objects.byCanvasID.push([canvasID, obj]);
for (var i=0; i<RGraph.ObjectRegistry.objects.byCanvasID.length; ++i) {
if (RGraph.ObjectRegistry.objects.byCanvasID[i] && RGraph.ObjectRegistry.objects.byCanvasID[i][0] == id) {
RGraph.ObjectRegistry.objects.byCanvasID[i] = null;
}
}
}
/**
* Removes all objects from the ObjectRegistry. If either the ID of a canvas is supplied,
* or the canvas itself, then only objects pertaining to that canvas are cleared.
*
* @param mixed Either a canvas object (as returned by document.getElementById()
* or the ID of a canvas (ie a string)
*/
RGraph.ObjectRegistry.Clear = function ()
{
// If an ID is supplied restrict the learing to that
if (arguments[0]) {
var id = (typeof(arguments[0]) == 'object' ? arguments[0].id : arguments[0]);
var objects = RGraph.ObjectRegistry.getObjectsByCanvasID(id);
for (var i=0; i<objects.length; ++i) {
RGraph.ObjectRegistry.Remove(objects[i]);
}
} else {
RGraph.ObjectRegistry.objects = {};
RGraph.ObjectRegistry.objects.byUID = [];
RGraph.ObjectRegistry.objects.byCanvasID = [];
}
}
/**
* Retrieves all objects for a given canvas id
*
* @patarm id string The canvas ID to get objects for.
*/
RGraph.ObjectRegistry.getObjectsByCanvasID = function (id)
{
var store = RGraph.ObjectRegistry.objects.byCanvasID;
var ret = [];
// Loop through all of the objects and return the appropriate ones
for (var i=0; i<store.length; ++i) {
if (store[i] && store[i][0] == id ) {
ret.push(store[i][1]);
}
}
return ret;
}
/**
* Retrieves the relevant object based on the X/Y position.
*
* @param object e The event object
* @return object The applicable (if any) object
*/
RGraph.ObjectRegistry.getFirstObjectByXY =
RGraph.ObjectRegistry.getObjectByXY = function (e)
{
var canvas = e.target;
var ret = null;
var objects = RGraph.ObjectRegistry.getObjectsByCanvasID(canvas.id);
for (var i=(objects.length - 1); i>=0; --i) {
var obj = objects[i].getObjectByXY(e);
if (obj) {
return obj;
}
}
}
/**
* Retrieves the relevant objects based on the X/Y position.
* NOTE This function returns an array of objects
*
* @param object e The event object
* @return An array of pertinent objects. Note the there may be only one object
*/
RGraph.ObjectRegistry.getObjectsByXY = function (e)
{
var canvas = e.target;
var ret = [];
var objects = RGraph.ObjectRegistry.getObjectsByCanvasID(canvas.id);
// Retrieve objects "front to back"
for (var i=(objects.length - 1); i>=0; --i) {
var obj = objects[i].getObjectByXY(e);
if (obj) {
ret.push(obj);
}
}
return ret;
}
/**
* Retrieves the object with the corresponding UID
*
* @param string uid The UID to get the relevant object for
*/
RGraph.ObjectRegistry.getObjectByUID = function (uid)
{
var objects = RGraph.ObjectRegistry.objects.byUID;
for (var i=0; i<objects.length; ++i) {
if (objects[i] && objects[i][1].uid == uid) {
return objects[i][1];
}
}
}
/**
* Retrieves the objects that are the given type
*
* @param mixed canvas The canvas to check. It can either be the canvas object itself or just the ID
* @param string type The type to look for
* @return array An array of one or more objects
*/
RGraph.ObjectRegistry.getObjectsByType = function (canvas, type)
{
if (typeof(canvas) == 'string') {
canvas = document.getElementById(canvas);
}
var objects = RGraph.ObjectRegistry.getObjectsByCanvasID(canvas.id);
var ret = [];
for (var i=0; i<objects.length; ++i) {
if (objects[i] && objects[i].type && objects[i].type == type) {
ret.push(objects[i]);
}
}
return ret;
}
/**
* Retrieves the FIRST object that matches the given type
*
* @param mixed canvas The type to look for
* @param string type The type of object to look for
* @return object The FIRST object that matches the given type
*/
RGraph.ObjectRegistry.getFirstObjectByType = function (canvas, type)
{
var objects = RGraph.ObjectRegistry.getObjectsByType(canvas, type);
return objects.length > 0 ? objects[0] : null;
}
/**
* This takes centerx, centery, x and y coordinates and returns the
* appropriate angle relative to the canvas angle system. Remember
* that the canvas angle system starts at the EAST axis
*
* @param number cx The centerx coordinate
* @param number cy The centery coordinate
* @param number x The X coordinate (eg the mouseX if coming from a click)
* @param number y The Y coordinate (eg the mouseY if coming from a click)
* @return number The relevant angle (measured in in RADIANS)
*/
RGraph.getAngleByXY = function (cx, cy, x, y)
{
var angle = Math.atan((y - cy) / (x - cx));
angle = Math.abs(angle)
if (x >= cx && y >= cy) {
angle += TWOPI;
} else if (x >= cx && y < cy) {
angle = (HALFPI - angle) + (PI + HALFPI);
} else if (x < cx && y < cy) {
angle += PI;
} else {
angle = PI - angle;
}
/**
* Upper and lower limit checking
*/
if (angle > TWOPI) {
angle -= TWOPI;
}
return angle;
}
/**
* This function returns the distance between two points. In effect the
* radius of an imaginary circle that is centered on x1 and y1. The name
* of this function is derived from the word "Hypoteneuse", which in
* trigonmetry is the longest side of a triangle
*
* @param number x1 The original X coordinate
* @param number y1 The original Y coordinate
* @param number x2 The target X coordinate
* @param number y2 The target Y coordinate
*/
RGraph.getHypLength = function (x1, y1, x2, y2)
{
var ret = Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
return ret;
}
/**
* This function gets the end point (X/Y coordinates) of a given radius.
* You pass it the center X/Y and the radius and this function will return
* the endpoint X/Y coordinates.
*
* @param number cx The center X coord
* @param number cy The center Y coord
* @param number r The lrngth of the radius
*/
RGraph.getRadiusEndPoint = function (cx, cy, angle, radius)
{
var x = cx + (Math.cos(angle) * radius);
var y = cy + (Math.sin(angle) * radius);
return [x, y];
}
/**
* This installs all of the event listeners
*
* @param object obj The chart object
*/
RGraph.InstallEventListeners = function (obj)
{
/**
* Don't attempt to install event listeners for older versions of MSIE
*/
if (RGraph.isOld()) {
return;
}
/**
* If this function exists, then the dynamic file has been included.
*/
if (RGraph.InstallCanvasClickListener) {
RGraph.InstallWindowMousedownListener(obj);
RGraph.InstallWindowMouseupListener(obj);
RGraph.InstallCanvasMousemoveListener(obj);
RGraph.InstallCanvasMouseupListener(obj);
RGraph.InstallCanvasMousedownListener(obj);
RGraph.InstallCanvasClickListener(obj);
} else if ( RGraph.hasTooltips(obj)
|| obj.Get('chart.adjustable')
|| obj.Get('chart.annotatable')
|| obj.Get('chart.contextmenu')
|| obj.Get('chart.resizable')
|| obj.Get('chart.key.interactive')
|| obj.Get('chart.events.click')
|| obj.Get('chart.events.mousemove')
) {
alert('[RGRAPH] You appear to have used dynamic features but not included the file: RGraph.common.dynamic.js');
}
}
/**
* Loosly mimicks the PHP function print_r();
*/
RGraph.pr = function (obj)
{
var str = '';
var indent = (arguments[2] ? arguments[2] : '');
switch (typeof(obj)) {
case 'number':
if (indent == '') {
str+= 'Number: '
}
str += String(obj);
break;
case 'string':
if (indent == '') {
str+= 'String (' + obj.length + '):'
}
str += '"' + String(obj) + '"';
break;
case 'object':
// In case of null
if (obj == null) {
str += 'null';
break;
}
str += 'Object\n' + indent + '(\n';
for (var i in obj) {
if (typeof(i) == 'string' || typeof(i) == 'number') {
str += indent + ' ' + i + ' => ' + RGraph.pr(obj[i], true, indent + ' ') + '\n';
}
}
var str = str + indent + ')';
break;
case 'function':
str += obj;
break;
case 'boolean':
str += 'Boolean: ' + (obj ? 'true' : 'false');
break;
}
/**
* Finished, now either return if we're in a recursed call, or alert()
* if we're not.
*/
if (arguments[1]) {
return str;
} else {
alert(str);
}
}
/**
* Produces a dashed line
*
* @param
*/
RGraph.DashedLine = function(context, x1, y1, x2, y2)
{
/**
* This is the size of the dashes
*/
var size = 5;
/**
* The optional fifth argument can be the size of the dashes
*/
if (typeof(arguments[5]) == 'number') {
size = arguments[5];
}
var dx = x2 - x1;
var dy = y2 - y1;
var num = Math.floor(Math.sqrt((dx * dx) + (dy * dy)) / size);
var xLen = dx / num;
var yLen = dy / num;
var count = 0;
do {
(count % 2 == 0 && count > 0) ? context.lineTo(x1, y1) : context.moveTo(x1, y1);
x1 += xLen;
y1 += yLen;
} while(count++ <= num);
}
/**
* Makes an AJAX call. It calls the given callback (a function) when ready
*
* @param string url The URL to retrieve
* @param function callback A function that is called when the response is ready, there's an example below
* called "myCallback".
*/
RGraph.AJAX = function (url, callback)
{
// Mozilla, Safari, ...
if (window.XMLHttpRequest) {
var httpRequest = new XMLHttpRequest();
// MSIE
} else if (window.ActiveXObject) {
var httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200) {
this.__user_callback__ = callback;
this.__user_callback__();
}
}
httpRequest.open('GET', url, true);
httpRequest.send();
}
/**
* Rotates the canvas
*
* @param object canvas The canvas to rotate
* @param int x The X coordinate about which to rotate the canvas
* @param int y The Y coordinate about which to rotate the canvas
* @param int angle The angle(in RADIANS) to rotate the canvas by
*/
RGraph.RotateCanvas = function (canvas, x, y, angle)
{
var context = canvas.getContext('2d');
context.translate(x, y);
context.rotate(angle);
context.translate(0 - x, 0 - y);
}
/**
* This draws an extra set of axes
*
* @param object obj The chart object
* @param object prop An assoc array of options:
* axis.x REQUIRED
* axis.min Minimum value - default is 0
* axis.max Maximum value - REQUIRED
* axis.color Color - default is black
* axis.title Title - default is nothing
* axis.title.color The color of the title text, default is black
* axis.font The font that the text is rendered in, default is Arial
* axis.text.size The default is 12 (ish)
* axis.numticks The number of tickmarks, default is 10
* axis.numylabels The number of Y labels
* axis.align This determines which side of the axis that the labels are draswn on.
* It can be left or right
* axis.scale.formatter This should be a function which accepts two arguments - the chart
* object and the value. The function should then format the number
* as required and then return it.
*/
RGraph.DrawAxes = function (obj, prop)
{
var gutterTop = obj.gutterTop;
var gutterBottom = obj.gutterBottom;
var context = obj.context;
var x = prop['axis.x'];
var y = obj.properties['chart.gutter.top'];
var min = prop['axis.min'] ? prop['axis.min'] : 0;
var max = prop['axis.max'];
var color = prop['axis.color'] ? prop['axis.color'] : 'black';
var title = prop['axis.title'] ? prop['axis.title'] : '';
var title_color = prop['axis.title.color'] ? prop['axis.title.color'] : color;
var label_color = prop['axis.text.color'] ? prop['axis.color'] : color;
var height = obj.canvas.height - obj.gutterBottom - obj.gutterTop;
var numticks = prop['axis.numticks'] ? prop['axis.numticks'] : 10;
var numlabels = prop['axis.numlabels'] ? prop['axis.numlabels'] : 5;
var gap = height / numticks;
var font = prop['axis.font'] ? prop['axis.font'] : 'Arial';
var size = prop['axis.text.size'] ? prop['axis.text.size'] : 10;
var align = typeof(prop['axis.align']) == 'string'? prop['axis.align'] : 'left';
var formatter = prop['axis.scale.formatter'];
var decimals = prop['axis.scale.decimals'];
var units_pre = prop['axis.units.pre'];
var units_post = prop['axis.units.post'];
/**
* Set the color
*/
context.strokeStyle = color;
/**
* Draw the main vertical line
*/
context = obj.context;
context.beginPath();
context.moveTo(AA(obj, x), y);
context.lineTo(AA(obj, x), y + height);
context.stroke();
/**
* Draw the axes tickmarks
*/
context.beginPath();
for (var i=0; i<=numticks; ++i) {
context.moveTo(align == 'right' ? x + 3 : x - 3,AA(obj, y + (gap *i)));
context.lineTo(x,AA(obj, y + (gap *i)));
}
context.stroke();
/**
* Draw the scale for the axes
*/
context.fillStyle = label_color;
context.beginPath();
var text_len = 0;
for (var i=0; i<=numlabels; ++i) {
var original = ((max - min) * ((numlabels-i) / numlabels)) + min;
var text = RGraph.number_format(obj, original.toFixed(decimals), units_pre, units_post);
var text = String(typeof(formatter) == 'function' ? formatter(obj, original) : text);
var text_len = Math.max(text_len, context.measureText(text).width);
RGraph.Text(
context,
font,
size,
x - (align == 'right' ? -5 : 5),
gutterTop + ((height / numlabels)*i),
text,
'center',
align == 'right' ? 'left' : 'right'
);
}
context.stroke();
/**
* Draw the title for the axes
*/
if (title) {
context.beginPath();
context.fillStyle = title_color
RGraph.Text(context, font, size + 2,
align == 'right' ? x + size + text_len + 2 : x - size - text_len - 2,
height / 2 + gutterTop, title, 'center', 'center', null, align == 'right' ? 90 : -90);
context.stroke();
}
}
/**
* Measures text by creating a DIV in the document and adding the relevant text to it.
* Then checking the .offsetWidth and .offsetHeight.
*
* @param string text The text to measure
* @param bool bold Whether the text is bold or not
* @param string font The font to use
* @param size number The size of the text (in pts)
* @return array A two element array of the width and height of the text
*/
RGraph.MeasureText = function (text, bold, font, size)
{
var div = document.createElement('DIV');
div.innerHTML = text;
div.style.position = 'absolute';
div.style.top = '-100px';
div.style.left = '-100px';
div.style.color = 'rgba(0,0,0,0)';
div.style.fontFamily = font;
div.style.fontWeight = bold ? 'bold' : 'normal';
div.style.fontSize = size + 'pt';
document.body.appendChild(div);
var size = [div.offsetWidth, div.offsetHeight];
document.body.removeChild(div);
return size;
}
/**
* If the effects library isn't included already this prevents an unknown function error
*/
if (!RGraph.AddEffects) {
RGraph.AddEffects = function (obj) {}
}
// Some other functions. Because they're rarely changed - they're hand minified
function AA(obj,value){var value=String(value).replace(/^(\d+)\.\d+/,'$1');var newvalue=Number(value)+0.5;return(newvalue-value)>=0?newvalue:Math.floor(value);}
RGraph.LinearGradient=function(obj,x1,y1,x2,y2,color1,color2){var gradient=obj.context.createLinearGradient(x1,y1,x2,y2);var numColors=arguments.length-5;for (var i=5;i<arguments.length;++i){var color=arguments[i];var stop=(i-5)/(numColors-1);gradient.addColorStop(stop,color);}return gradient;}
RGraph.RadialGradient=function(obj,x1,y1,r1,x2,y2,r2,color1,color2){var gradient=obj.context.createRadialGradient(x1,y1,r1,x2,y2,r2);var numColors=arguments.length-7;for(var i=7;i<arguments.length; ++i){var color=arguments[i];var stop=(i-7)/(numColors-1);gradient.addColorStop(stop,color);}return gradient;}
RGraph.array_shift=function(arr){var ret=[];for(var i=1;i<arr.length;++i){ret.push(arr[i]);}return ret;}
RGraph.AddEventListener=function(id,e,func){var type=arguments[3]?arguments[3]:'unknown';RGraph.Registry.Get('chart.event.handlers').push([id,e,func,type]);}
RGraph.ClearEventListeners=function(id){if(id&&id=='window'){window.removeEventListener('mousedown',window.__rgraph_mousedown_event_listener_installed__,false);window.removeEventListener('mouseup',window.__rgraph_mouseup_event_listener_installed__,false);}else{var canvas = document.getElementById(id);canvas.removeEventListener('mouseup',canvas.__rgraph_mouseup_event_listener_installed__,false);canvas.removeEventListener('mousemove',canvas.__rgraph_mousemove_event_listener_installed__,false);canvas.removeEventListener('mousedown',canvas.__rgraph_mousedown_event_listener_installed__,false);canvas.removeEventListener('click',canvas.__rgraph_click_event_listener_installed__,false);}}
RGraph.HidePalette=function(){var div=RGraph.Registry.Get('palette');if(typeof(div)=='object'&&div){div.style.visibility='hidden';div.style.display='none';RGraph.Registry.Set('palette',null);}}
RGraph.random=function(min,max){var dp=arguments[2]?arguments[2]:0;var r=Math.random();return Number((((max - min) * r) + min).toFixed(dp));}
RGraph.NoShadow=function(obj){obj.context.shadowColor='rgba(0,0,0,0)';obj.context.shadowBlur=0;obj.context.shadowOffsetX=0;obj.context.shadowOffsetY=0;}
RGraph.SetShadow=function(obj,color,offsetx,offsety,blur){obj.context.shadowColor=color;obj.context.shadowOffsetX=offsetx;obj.context.shadowOffsetY=offsety;obj.context.shadowBlur=blur;}
RGraph.array_reverse=function(arr){var newarr=[];for(var i=arr.length-1;i>=0;i--){newarr.push(arr[i]);}return newarr;}
RGraph.Registry.Set=function(name,value){RGraph.Registry.store[name]=value;return value;}
RGraph.Registry.Get=function(name){return RGraph.Registry.store[name];}
RGraph.degrees2Radians=function(degrees){return degrees*(PI/180);}
RGraph.is_array=function(obj){return obj!=null&&obj.constructor.toString().indexOf('Array')!=-1;}
RGraph.trim=function(str){return RGraph.ltrim(RGraph.rtrim(str));}
RGraph.ltrim=function(str){return str.replace(/^(\s|\0)+/, '');}
RGraph.rtrim=function(str){return str.replace(/(\s|\0)+$/, '');}
RGraph.GetHeight=function(obj){return obj.canvas.height;}
RGraph.GetWidth=function(obj){return obj.canvas.width;}
RGraph.is_null=function(arg){if(arg==null||(typeof(arg))=='object'&&!arg){return true;}return false;}
RGraph.Timer=function(label){var d=new Date();console.log(label+': '+d.getSeconds()+'.'+d.getMilliseconds());}
RGraph.Async=function(func){return setTimeout(func,arguments[1]?arguments[1]:1);}
RGraph.isIE7=function(){return navigator.userAgent.indexOf('MSIE 7')>0;}
RGraph.isIE8=function(){return navigator.userAgent.indexOf('MSIE 8')>0;}
RGraph.isIE9=function(){return navigator.userAgent.indexOf('MSIE 9')>0;}
RGraph.isIE9up=function(){navigator.userAgent.match(/MSIE (\d+)/);return Number(RegExp.$1)>=9;}
RGraph.isOld=function(){return RGraph.isIE7()||RGraph.isIE8();}
RGraph.Reset=function(canvas){canvas.width=canvas.width;}
function pd(variable){RGraph.pr(variable);}
function p(variable){RGraph.pr(variable);}
function a(variable){alert(variable);}
function cl(variable){return console.log(variable);}
|
leclercj/cagette
|
www/js/rgraph/RGraph.common.core.js
|
JavaScript
|
gpl-2.0
| 94,666 |
/* packet-dvbci.c
* Routines for DVB-CI (Common Interface) dissection
* Copyright 2011-2014, Martin Kaiser <[email protected]>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* 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.
*/
/* This dissector supports DVB-CI as defined in EN50221 and
* CI+ (www.ci-plus.com).
* For more details, see http://wiki.wireshark.org/DVB-CI.
*
* The pcap input format for this dissector is documented at
* http://www.kaiser.cx/pcap-dvbci.html.
*/
#include "config.h"
#include <glib.h>
#include <epan/addr_resolv.h>
#include <epan/circuit.h>
#include <epan/dvb_chartbl.h>
#include <epan/packet.h>
#include <epan/exported_pdu.h>
#include <epan/reassemble.h>
#include <epan/prefs.h>
#include <epan/tap.h>
#include <epan/expert.h>
#include <epan/asn1.h>
#include <epan/dissectors/packet-dvbci.h>
#include <epan/dissectors/packet-mpeg-descriptor.h>
#include <epan/dissectors/packet-mpeg-sect.h>
#include <epan/dissectors/packet-mpeg-pmt.h>
#include <epan/dissectors/packet-x509af.h>
#include <epan/dissectors/packet-x509ce.h>
#include "packet-ber.h"
#ifdef HAVE_LIBGCRYPT
#include <wsutil/wsgcrypt.h>
#endif
void proto_register_dvbci(void);
void proto_reg_handoff_dvbci(void);
#define AES_BLOCK_LEN 16
#define AES_KEY_LEN 16
#define EXPORTED_SAC_MSG_PROTO "CI+ SAC message"
#define IS_DATA_TRANSFER(e) (e==DVBCI_EVT_DATA_CAM_TO_HOST || e==DVBCI_EVT_DATA_HOST_TO_CAM)
/* direction of data transfer in [as]pdu_info_t and elsewhere */
#define DATA_CAM_TO_HOST DVBCI_EVT_DATA_CAM_TO_HOST
#define DATA_HOST_TO_CAM DVBCI_EVT_DATA_HOST_TO_CAM
#define DIRECTION_ANY 0x0
/* source/destination address field */
#define ADDR_HOST "Host"
#define ADDR_CAM "CAM"
/* hardware event */
#define CAM_IN 0x01
#define CAM_OUT 0x02
#define POWER_ON 0x03
#define POWER_OFF 0x04
#define TS_ROUTE 0x05
#define TS_BYPASS 0x06
#define RESET_H 0x07
#define RESET_L 0x08
#define READY_H 0x09
#define READY_L 0x0A
/* Card Information Structure (CIS) */
/* tuples */
#define CISTPL_NO_LINK 0x14
#define CISTPL_VERS_1 0x15
#define CISTPL_CONFIG 0x1A
#define CISTPL_CFTABLE_ENTRY 0x1B
#define CISTPL_DEVICE_OC 0x1C
#define CISTPL_DEVICE_OA 0x1D
#define CISTPL_MANFID 0x20
#define CISTPL_END 0xFF
/* subtuple */
#define CCSTPL_CIF 0xC0
/* interface types */
#define TPCE_IF_TYPE_MEM 0
#define TPCE_IF_TYPE_IO_MEM 1
#define TPCE_IF_TYPE_CUST0 4
#define TPCE_IF_TYPE_CUST1 5
#define TPCE_IF_TYPE_CUST2 6
#define TPCE_IF_TYPE_CUST3 7
/* link layer */
#define ML_MORE 0x80
#define ML_LAST 0x00
/* base values of sequence ids for reassembly of fragmented tpdus
if there's two open transport connections, their tpdu fragments may be
interleaved, we must add the tcid to the base value in order to
distinguish between different transport connections
TPDU_SEQ_ID_BASE and SPDU_SEQ_ID_BASE can be arbitrary 32bit values, they
must be more than 256 apart since we add the 8bit tcid */
#define TPDU_SEQ_ID_BASE 123
/* same as above, the spdu fragments are also demultiplexed based on the
t_c_id field */
#define SPDU_SEQ_ID_BASE 2417
/* transport layer */
#define NO_TAG 0x00
#define T_SB 0x80
#define T_RCV 0x81
#define T_CREATE_T_C 0x82
#define T_C_T_C_REPLY 0x83
#define T_DELETE_T_C 0x84
#define T_D_T_C_REPLY 0x85
#define T_REQUEST_T_C 0x86
#define T_NEW_T_C 0x87
#define T_T_C_ERROR 0x88
#define T_DATA_LAST 0xA0
#define T_DATA_MORE 0xA1
#define SB_VAL_MSG_AVAILABLE 0x80
#define SB_VAL_NO_MSG_AVAILABLE 0x00
/* session layer */
#define T_SESSION_NUMBER 0x90
#define T_OPEN_SESSION_REQUEST 0x91
#define T_OPEN_SESSION_RESPONSE 0x92
#define T_CREATE_SESSION 0x93
#define T_CREATE_SESSION_RESPONSE 0x94
#define T_CLOSE_SESSION_REQUEST 0x95
#define T_CLOSE_SESSION_RESPONSE 0x96
/* status for open/create session */
#define SESS_OPENED 0x00
#define SESS_NOT_OPENED_RES_NON_EXIST 0xF0
#define SESS_NOT_OPENED_RES_UNAVAIL 0xF1
#define SESS_NOT_OPENED_RES_VER_LOWER 0xF2
#define SESS_NOT_OPENED_RES_BUSY 0xF3
/* status for close session */
#define SESS_CLOSED 0x00
#define SESS_NB_NOT_ALLOC 0xF0
/* circuit id from session number (16bit) and transport connection id * (8bit) */
#define CT_ID(s,t) ((guint32)(s<<8|t))
/* resource id */
#define RES_ID_TYPE_MASK 0xC0000000
#define RES_CLASS_MASK 0x3FFF0000
#define RES_TYPE_MASK 0x0000FFC0
#define RES_VER_MASK 0x0000003F
/* resource class */
#define RES_CLASS_RM 0x01
#define RES_CLASS_AP 0x02
#define RES_CLASS_CA 0x03
#define RES_CLASS_AUT 0x10
#define RES_CLASS_HC 0x20
#define RES_CLASS_DT 0x24
#define RES_CLASS_MMI 0x40
#define RES_CLASS_AMI 0x41
#define RES_CLASS_LSC 0x60
#define RES_CLASS_CC 0x8C
#define RES_CLASS_HLC 0x8D
#define RES_CLASS_CUP 0x8E
#define RES_CLASS_OPP 0x8F
#define RES_CLASS_SAS 0x96
#define RES_ID_LEN 4 /* bytes */
#define RES_CLASS(_res_id) (_res_id & RES_CLASS_MASK) >> 16
#define RES_VER(_res_id) (_res_id & RES_VER_MASK)
/* appinfo resource */
#define APP_TYPE_CA 0x1
#define APP_TYPE_EPG 0x2
#define DATA_RATE_72 0x0
#define DATA_RATE_96 0x1
/* ca resource */
#define LIST_MGMT_MORE 0x0
#define LIST_MGMT_FIRST 0x1
#define LIST_MGMT_LAST 0x2
#define LIST_MGMT_ONLY 0x3
#define LIST_MGMT_ADD 0x4
#define LIST_MGMT_UPDATE 0x5
#define CMD_ID_OK_DESCR 0x1
#define CMD_ID_OK_MMI 0x2
#define CMD_ID_QUERY 0x3
#define CMD_ID_NOT_SELECTED 0x4
#define CA_DESC_TAG 0x9
#define CA_ENAB_DESC_OK 0x01
#define CA_ENAB_DESC_OK_PURCHASE 0x02
#define CA_ENAB_DESC_OK_TECH 0x03
#define CA_ENAB_DESC_NG_ENTITLEMENT 0x71
#define CA_ENAB_DESC_NG_TECH 0x73
/* host control resource */
#define HC_STAT_OK 0x0
#define HC_STAT_ERR_DLVRY 0x1
#define HC_STAT_ERR_LOCK 0x2
#define HC_STAT_ERR_BUSY 0x3
#define HC_STAT_ERR_PARAM 0x4
#define HC_STAT_ERR_NOT_FOUND 0x5
#define HC_STAT_ERR_UNKNOWN 0x6
#define HC_RELEASE_OK 0x0
#define HC_RELEASE_REFUSED 0x1
/* mmi resource */
#define CLOSE_MMI_CMD_ID_IMMEDIATE 0x0
#define CLOSE_MMI_CMD_ID_DELAY 0x1
/* only commands and parameters for high-level mmi are supported */
#define DISP_CMD_SET_MMI_MODE 1
#define DISP_CMD_GET_DISP_TBL 2
#define DISP_CMD_GET_INP_TBL 3
#define MMI_MODE_HIGH 1
#define DISP_REP_ID_MMI_MODE_ACK 0x01
#define DISP_REP_ID_DISP_CHAR_TBL 0x02
#define DISP_REP_ID_INP_CHAR_TBL 0x03
#define DISP_REP_ID_UNKNOWN_CMD 0xF0
#define DISP_REP_ID_UNKNOWN_MMI_MODE 0xF1
#define DISP_REP_ID_UNKNOWN_CHAR_TBL 0xF2
#define VISIBLE_ANS 0
#define BLIND_ANS 1
#define ANSW_ID_CANCEL 0x00
#define ANSW_ID_ANSWER 0x01
/* used for answer_text_length, choice_nb and item_nb */
#define NB_UNKNOWN 0xFF
/* cam upgrade resource */
#define CUP_DELAYED 0x0
#define CUP_IMMEDIATE 0x1
#define CUP_ANS_NO 0x0
#define CUP_ANS_YES 0x1
#define CUP_ANS_ASK 0x2
#define CUP_RESET_PCMCIA 0x0
#define CUP_RESET_CMDIF 0x1
#define CUP_RESET_NONE 0x2
/* content control resource */
#define CC_ID_HOST_ID 0x05
#define CC_ID_CICAM_ID 0x06
#define CC_ID_HOST_BRAND_CERT 0x07
#define CC_ID_CICAM_BRAND_CERT 0x08
#define CC_ID_KP 0x0C
#define CC_ID_DHPH 0x0D
#define CC_ID_DHPM 0x0E
#define CC_ID_HOST_DEV_CERT 0x0F
#define CC_ID_CICAM_DEV_CERT 0x10
#define CC_ID_SIG_A 0x11
#define CC_ID_SIG_B 0x12
#define CC_ID_AUTH_NONCE 0x13
#define CC_ID_NS_HOST 0x14
#define CC_ID_NS_MODULE 0x15
#define CC_ID_AKH 0x16
#define CC_ID_URI 0x19
#define CC_ID_PROG_NUM 0x1A
#define CC_ID_URI_CNF 0x1B
#define CC_ID_KEY_REGISTER 0x1C
#define CC_ID_URI_VERSIONS 0x1D
#define CC_ID_STATUS_FIELD 0x1E
#define CC_ID_SRM_DATA 0x1F
#define CC_ID_SRM_CONFIRM 0x20
#define CC_ID_CICAM_LICENSE 0x21
#define CC_ID_LICENSE_STATUS 0x22
#define CC_ID_LICENSE_RCV_STATUS 0x23
#define CC_ID_HOST_LICENSE 0x24
#define CC_ID_PLAY_COUNT 0x25
#define CC_ID_OPERATING_MODE 0x26
#define CC_ID_PINCODE_DATA 0x27
#define CC_ID_REC_START_STATUS 0x28
#define CC_ID_MODE_CHG_STATUS 0x29
#define CC_ID_REC_STOP_STATUS 0x2A
#define CC_EMI_FREE 0x00
#define CC_EMI_NO_MORE 0x01
#define CC_EMI_ONCE 0x02
#define CC_EMI_NEVER 0x03
#define CC_KEY_EVEN 0x0
#define CC_KEY_ODD 0x1
#define CC_STATUS_OK 0x0
#define CC_STATUS_NO_CC_SUPPORT 0x1
#define CC_STATUS_HOST_BUSY 0x2
#define CC_STATUS_AUTH_FAILED_OR_NO_SRM 0x3
#define CC_STATUS_CICAM_BUSY 0x4
#define CC_STATUS_REC_MODE_ERR 0x5
#define SAC_MSG_HDR_LEN 8
#define CC_SAC_AUTH_AES128_XCBC_MAC 0x0
#define CC_SAC_ENC_AES128_CBC 0x0
#define CC_CAP_NONE 0x0
#define CC_CAP_CAS_PIN 0x1
#define CC_CAP_CAS_FTA_PIN 0x2
#define CC_CAP_CAS_PIN_CACHED 0x3
#define CC_CAP_CAS_FTA_PIN_CACHED 0x4
/* length of DVB-SI utc time field in bytes */
#define UTC_TIME_LEN 5
#define CC_PIN_BAD 0x0
#define CC_PIN_CAM_BUSY 0x1
#define CC_PIN_OK 0x2
#define CC_PIN_UNCONFIRMED 0x3
#define CC_PIN_VB_NOT_REQ 0x4
#define CC_PIN_CSA 0x5
#define CC_OP_MODE_WATCH_BUFFER 0x0
#define CC_OP_MODE_TIMESHIFT 0x1
#define CC_OP_MODE_UNATTENDED 0x2
/* application mmi resource */
#define ACK_CODE_OK 0x1
#define ACK_CODE_WRONG_API 0x2
#define ACK_CODE_API_BUSY 0x3
#define REQ_TYPE_FILE 0x0
#define REQ_TYPE_DATA 0x1
#define REQ_TYPE_FILE_HASH 0x2
#define REQ_TYPE_REQ 0x3
/* lsc resource */
#define COMMS_CMD_ID_CONNECT_ON_CHANNEL 1
#define COMMS_CMD_ID_DISCONNECT_ON_CHANNEL 2
#define COMMS_CMD_ID_SET_PARAMS 3
#define COMMS_CMD_ID_ENQUIRE_STATUS 4
#define COMMS_CMD_ID_GET_NEXT_BUFFER 5
#define CONN_DESC_TEL 1
#define CONN_DESC_CABLE 2
#define CONN_DESC_IP 3
#define CONN_DESC_HOSTNAME 4
#define LSC_DESC_IP 0xCF
#define LSC_DESC_HOSTNAME 0xCD
#define LSC_IPV4 1
#define LSC_IPV6 2
#define LSC_TCP 1
#define LSC_UDP 2
#define COMMS_REP_ID_CONNECT_ACK 1
#define COMMS_REP_ID_DISCONNECT_ACK 2
#define COMMS_REP_ID_SET_PARAMS_ACK 3
#define COMMS_REP_ID_STATUS_REPLY 4
#define COMMS_REP_ID_GET_NEXT_BUFFER_ACK 5
#define COMMS_REP_ID_SEND_ACK 6
#define LSC_RET_OK 0
#define LSC_RET_DISCONNECTED 0
#define LSC_RET_CONNECTED 1
#define LSC_RET_TOO_BIG 0xFE
/* operator profile resource */
#define TABLE_ID_CICAM_NIT 0x40 /* CICAM NIT must be a NIT actual */
#define OPP_REF_REG_FLG_NONE 0
#define OPP_REF_REG_FLG_ADV 1
#define OPP_REF_REG_FLG_URG 2
#define OPP_REF_REG_FLG_SCHED 3
#define OPP_ERR_FLG_OK 0
#define OPP_ERR_FLG_PROF 1
#define OPP_ERR_FLG_UNSUPPORTED 2
#define OPP_ERR_FLG_CANCELLED 3
/* EIT p/f, EIT schedule usage */
#define OPP_EIT_ABSENT 0
#define OPP_EIT_NOT_X 1
#define OPP_EIT_FULL_X 2
#define OPP_EIT_BARKER 3
#define OPP_EPG_APP 4
#define OPP_EXT_EVT_DIFF 0
#define OPP_EXT_EVT_ADD 1
/* these values match the delivery system descriptor tags */
#define OPP_DLV_CAP_S 0x43
#define OPP_DLV_CAP_C 0x44
#define OPP_DLV_CAP_T 0x5A
#define OPP_DLV_CAP_S2 0x79
#define OPP_TUNE_OK 0
#define OPP_TUNE_UNSUPPORTED 1
#define OPP_TUNE_INVALID 2
#define OPP_TUNE_ERR 3
#define OPP_NO_MORE_DESC 0xFF
/* sas resource */
#define SAS_SESS_STATE_CONNECTED 0
#define SAS_SESS_STATE_NOT_FOUND 1
#define SAS_SESS_STATE_DENIED 2
/* application layer */
#define APDU_TAG_SIZE 3
/* "don't care" value for min_len_field and len_field (this can't be 0) */
#define LEN_FIELD_ANY G_MAXUINT32
static GHashTable *apdu_table = NULL;
typedef struct _apdu_info_t {
guint32 tag;
/* the minimum length required for this apdu */
guint32 min_len_field;
/* if the apdu has a well-known length, we enforce it here
* (otherwise, we set this to LEN_FIELD_ANY) */
guint32 len_field;
guint8 direction;
guint16 res_class;
guint8 res_min_ver;
void (*dissect_payload)(guint32, gint,
tvbuff_t *, gint, circuit_t *, packet_info *, proto_tree *);
} apdu_info_t;
static void
dissect_dvbci_payload_rm(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_ap(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_ca(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_aut(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo _U_, proto_tree *tree);
static void
dissect_dvbci_payload_hc(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_dt(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_mmi(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_hlc(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_cup(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_cc(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_ami(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_lsc(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_opp(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree);
static void
dissect_dvbci_payload_sas(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit,
packet_info *pinfo, proto_tree *tree);
/* apdu defines */
#define T_PROFILE_ENQ 0x9F8010
#define T_PROFILE 0x9F8011
#define T_PROFILE_CHANGE 0x9F8012
#define T_APP_INFO_ENQ 0x9F8020
#define T_APP_INFO 0x9F8021
#define T_ENTER_MENU 0x9F8022
#define T_REQUEST_CICAM_RESET 0x9F8023
#define T_DATARATE_INFO 0x9F8024
#define T_CA_INFO_ENQ 0x9F8030
#define T_CA_INFO 0x9F8031
#define T_CA_PMT 0x9F8032
#define T_CA_PMT_REPLY 0x9F8033
#define T_AUTH_REQ 0x9F8200
#define T_AUTH_RESP 0x9F8201
#define T_TUNE 0x9F8400
#define T_REPLACE 0x9F8401
#define T_CLEAR_REPLACE 0x9F8402
#define T_ASK_RELEASE 0x9F8403
#define T_TUNE_BROADCAST_REQ 0x9F8404
#define T_TUNE_REPLY 0x9F8405
#define T_ASK_RELEASE_REPLY 0x9F8406
#define T_DATE_TIME_ENQ 0x9F8440
#define T_DATE_TIME 0x9F8441
#define T_CLOSE_MMI 0x9F8800
#define T_DISPLAY_CONTROL 0x9F8801
#define T_DISPLAY_REPLY 0x9F8802
#define T_ENQ 0x9F8807
#define T_ANSW 0x9F8808
#define T_MENU_LAST 0x9F8809
#define T_MENU_MORE 0x9F880A
#define T_MENU_ANSW 0x9F880B
#define T_LIST_LAST 0x9F880C
#define T_LIST_MORE 0x9F880D
#define T_HOST_COUNTRY_ENQ 0x9F8100
#define T_HOST_COUNTRY 0x9F8101
#define T_HOST_LANGUAGE_ENQ 0x9F8110
#define T_HOST_LANGUAGE 0x9F8111
#define T_CAM_FIRMWARE_UPGRADE 0x9F9D01
#define T_CAM_FIRMWARE_UPGRADE_REPLY 0x9F9D02
#define T_CAM_FIRMWARE_UPGRADE_PROGRESS 0x9F9D03
#define T_CAM_FIRMWARE_UPGRADE_COMPLETE 0x9F9D04
#define T_CC_OPEN_REQ 0x9F9001
#define T_CC_OPEN_CNF 0x9F9002
#define T_CC_DATA_REQ 0x9F9003
#define T_CC_DATA_CNF 0x9F9004
#define T_CC_SYNC_REQ 0x9F9005
#define T_CC_SYNC_CNF 0x9F9006
#define T_CC_SAC_DATA_REQ 0x9F9007
#define T_CC_SAC_DATA_CNF 0x9F9008
#define T_CC_SAC_SYNC_REQ 0x9F9009
#define T_CC_SAC_SYNC_CNF 0x9F9010
#define T_CC_PIN_CAPABILITIES_REQ 0x9F9011
#define T_CC_PIN_CAPABILITIES_REPLY 0x9F9012
#define T_CC_PIN_CMD 0x9F9013
#define T_CC_PIN_REPLY 0x9F9014
#define T_CC_PIN_EVENT 0x9F9015
#define T_CC_PIN_PLAYBACK 0x9F9016
#define T_CC_PIN_MMI_REQ 0x9F9017
#define T_REQUEST_START 0x9F8000
#define T_REQUEST_START_ACK 0x9F8001
#define T_FILE_REQUEST 0x9F8002
#define T_FILE_ACKNOWLEDGE 0x9F8003
#define T_APP_ABORT_REQUEST 0x9F8004
#define T_APP_ABORT_ACK 0x9F8005
#define T_COMMS_CMD 0x9F8C00
#define T_COMMS_REPLY 0x9F8C02
#define T_COMMS_SEND_LAST 0x9F8C03
#define T_COMMS_SEND_MORE 0x9F8C04
#define T_COMMS_RCV_LAST 0x9F8C05
#define T_COMMS_RCV_MORE 0x9F8C06
#define T_OPERATOR_STATUS_REQ 0x9F9C00
#define T_OPERATOR_STATUS 0x9F9C01
#define T_OPERATOR_NIT_REQ 0x9F9C02
#define T_OPERATOR_NIT 0x9F9C03
#define T_OPERATOR_INFO_REQ 0x9F9C04
#define T_OPERATOR_INFO 0x9F9C05
#define T_OPERATOR_SEARCH_START 0x9F9C06
#define T_OPERATOR_SEARCH_STATUS 0x9F9C07
#define T_OPERATOR_EXIT 0x9F9C08
#define T_OPERATOR_TUNE 0x9F9C09
#define T_OPERATOR_TUNE_STATUS 0x9F9C0A
#define T_OPERATOR_ENTITLEMENT_ACK 0x9F9C0B
#define T_OPERATOR_SEARCH_CANCEL 0x9F9C0C
#define T_SAS_CONNECT_RQST 0x9F9A00
#define T_SAS_CONNECT_CNF 0x9F9A01
#define T_SAS_ASYNC_MSG 0x9F9A07
/* these are no real apdus, they just use the same format */
#define T_TEXT_LAST 0x9F8803
#define T_TEXT_MORE 0x9F8804
#define T_CONNECTION_DESCRIPTOR 0x9F8C01
#define IS_MENU_APDU(t) (t==T_MENU_MORE || t==T_MENU_LAST)
static const apdu_info_t apdu_info[] = {
{T_PROFILE_ENQ, 0, 0, DIRECTION_ANY, RES_CLASS_RM, 1, NULL},
{T_PROFILE, 0, LEN_FIELD_ANY, DIRECTION_ANY, RES_CLASS_RM, 1, dissect_dvbci_payload_rm},
{T_PROFILE_CHANGE, 0, 0, DIRECTION_ANY, RES_CLASS_RM, 1, NULL},
{T_APP_INFO_ENQ, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_AP, 1, NULL},
{T_APP_INFO, 6, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_AP, 1, dissect_dvbci_payload_ap},
{T_ENTER_MENU, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_AP, 1, NULL},
{T_REQUEST_CICAM_RESET, 0, 0, DATA_CAM_TO_HOST, RES_CLASS_AP, 3, NULL},
{T_DATARATE_INFO, 0, 1, DATA_HOST_TO_CAM, RES_CLASS_AP, 3, dissect_dvbci_payload_ap},
{T_CA_INFO_ENQ, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_CA, 1, NULL},
{T_CA_INFO, 0, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_CA, 1, dissect_dvbci_payload_ca},
{T_CA_PMT, 6, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_CA, 1, dissect_dvbci_payload_ca},
{T_CA_PMT_REPLY, 8, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_CA, 1, dissect_dvbci_payload_ca},
{T_AUTH_REQ, 2, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_AUT, 1, dissect_dvbci_payload_aut},
{T_AUTH_RESP, 2, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_AUT, 1, dissect_dvbci_payload_aut},
{T_TUNE, 0, 8, DATA_CAM_TO_HOST, RES_CLASS_HC, 1, dissect_dvbci_payload_hc},
{T_REPLACE, 0, 5, DATA_CAM_TO_HOST, RES_CLASS_HC, 1, dissect_dvbci_payload_hc},
{T_CLEAR_REPLACE, 0, 1, DATA_CAM_TO_HOST, RES_CLASS_HC, 1, dissect_dvbci_payload_hc},
{T_ASK_RELEASE, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_HC, 1, NULL},
{T_TUNE_BROADCAST_REQ, 5, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_HC, 2, dissect_dvbci_payload_hc},
{T_TUNE_REPLY, 1, 1, DATA_HOST_TO_CAM, RES_CLASS_HC, 2, dissect_dvbci_payload_hc},
{T_ASK_RELEASE_REPLY, 1, 1, DATA_CAM_TO_HOST, RES_CLASS_HC, 2, dissect_dvbci_payload_hc},
{T_DATE_TIME_ENQ, 0, 1, DATA_CAM_TO_HOST, RES_CLASS_DT, 1, dissect_dvbci_payload_dt},
{T_DATE_TIME, 5, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_DT, 1, dissect_dvbci_payload_dt},
{T_CLOSE_MMI, 1, LEN_FIELD_ANY, DIRECTION_ANY, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_DISPLAY_CONTROL, 1, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_DISPLAY_REPLY, 1, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_ENQ, 2, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_ANSW, 1, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_MENU_LAST, 13, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_MENU_MORE, 13, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_MENU_ANSW, 0, 1, DATA_HOST_TO_CAM, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_LIST_LAST, 13, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_LIST_MORE, 13, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_MMI, 1, dissect_dvbci_payload_mmi},
{T_HOST_COUNTRY_ENQ, 0, 0, DATA_CAM_TO_HOST, RES_CLASS_HLC, 1, NULL},
{T_HOST_COUNTRY, 0, 3, DATA_HOST_TO_CAM, RES_CLASS_HLC, 1, dissect_dvbci_payload_hlc},
{T_HOST_LANGUAGE_ENQ, 0, 0, DATA_CAM_TO_HOST, RES_CLASS_HLC, 1, NULL},
{T_HOST_LANGUAGE, 0, 3, DATA_HOST_TO_CAM, RES_CLASS_HLC, 1, dissect_dvbci_payload_hlc},
{T_CAM_FIRMWARE_UPGRADE, 0, 3, DATA_CAM_TO_HOST, RES_CLASS_CUP, 1, dissect_dvbci_payload_cup},
{T_CAM_FIRMWARE_UPGRADE_REPLY, 0, 1, DATA_HOST_TO_CAM, RES_CLASS_CUP, 1, dissect_dvbci_payload_cup},
{T_CAM_FIRMWARE_UPGRADE_PROGRESS, 0, 1, DATA_CAM_TO_HOST, RES_CLASS_CUP, 1, dissect_dvbci_payload_cup},
{T_CAM_FIRMWARE_UPGRADE_COMPLETE, 0, 1, DATA_CAM_TO_HOST, RES_CLASS_CUP, 1, dissect_dvbci_payload_cup},
{T_CC_OPEN_REQ, 0, 0, DATA_CAM_TO_HOST, RES_CLASS_CC, 1, NULL},
{T_CC_OPEN_CNF, 0, 1, DATA_HOST_TO_CAM, RES_CLASS_CC, 1, dissect_dvbci_payload_cc},
{T_CC_DATA_REQ, 3, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_CC, 1, dissect_dvbci_payload_cc},
{T_CC_DATA_CNF, 2, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_CC, 1, dissect_dvbci_payload_cc},
{T_CC_SYNC_REQ, 0, 0, DATA_CAM_TO_HOST, RES_CLASS_CC, 1, NULL},
{T_CC_SYNC_CNF, 0, 1, DATA_HOST_TO_CAM, RES_CLASS_CC, 1, dissect_dvbci_payload_cc},
{T_CC_SAC_DATA_REQ, 8, LEN_FIELD_ANY, DIRECTION_ANY, RES_CLASS_CC, 1, dissect_dvbci_payload_cc},
{T_CC_SAC_DATA_CNF, 8, LEN_FIELD_ANY, DIRECTION_ANY, RES_CLASS_CC, 1, dissect_dvbci_payload_cc},
{T_CC_SAC_SYNC_REQ, 8, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_CC, 1, dissect_dvbci_payload_cc},
{T_CC_SAC_SYNC_CNF, 8, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_CC, 1, dissect_dvbci_payload_cc},
{T_CC_PIN_CAPABILITIES_REQ, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_CC, 2, NULL},
{T_CC_PIN_CAPABILITIES_REPLY, 7, 7, DATA_CAM_TO_HOST, RES_CLASS_CC, 2, dissect_dvbci_payload_cc},
{T_CC_PIN_CMD, 1, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_CC, 2, dissect_dvbci_payload_cc},
{T_CC_PIN_REPLY, 1, 1, DATA_CAM_TO_HOST, RES_CLASS_CC, 2, dissect_dvbci_payload_cc},
{T_CC_PIN_EVENT, 25, 25, DATA_CAM_TO_HOST, RES_CLASS_CC, 2, dissect_dvbci_payload_cc},
{T_CC_PIN_PLAYBACK, 16, 16, DATA_HOST_TO_CAM, RES_CLASS_CC, 2, dissect_dvbci_payload_cc},
{T_CC_PIN_MMI_REQ, 1, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_CC, 2, dissect_dvbci_payload_cc},
{T_REQUEST_START, 2, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_AMI, 1, dissect_dvbci_payload_ami},
{T_REQUEST_START_ACK, 0, 1, DATA_HOST_TO_CAM, RES_CLASS_AMI, 1, dissect_dvbci_payload_ami},
{T_FILE_REQUEST, 1, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_AMI, 1, dissect_dvbci_payload_ami},
{T_FILE_ACKNOWLEDGE, 2, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_AMI, 1, dissect_dvbci_payload_ami},
{T_APP_ABORT_REQUEST, 0, LEN_FIELD_ANY, DIRECTION_ANY, RES_CLASS_AMI, 1, dissect_dvbci_payload_ami},
{T_APP_ABORT_ACK, 0, LEN_FIELD_ANY, DIRECTION_ANY, RES_CLASS_AMI, 1, dissect_dvbci_payload_ami},
{T_COMMS_CMD, 1, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_LSC, 1, dissect_dvbci_payload_lsc},
{T_COMMS_REPLY, 0, 2, DATA_HOST_TO_CAM, RES_CLASS_LSC, 1, dissect_dvbci_payload_lsc},
{T_COMMS_SEND_LAST, 2, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_LSC, 1, dissect_dvbci_payload_lsc},
{T_COMMS_SEND_MORE, 2, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_LSC, 1, dissect_dvbci_payload_lsc},
{T_COMMS_RCV_LAST, 2, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_LSC, 1, dissect_dvbci_payload_lsc},
{T_COMMS_RCV_MORE, 2, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_LSC, 1, dissect_dvbci_payload_lsc},
{T_OPERATOR_STATUS_REQ, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_OPP, 1, NULL},
{T_OPERATOR_STATUS, 0, 6, DATA_CAM_TO_HOST, RES_CLASS_OPP, 1, dissect_dvbci_payload_opp},
{T_OPERATOR_NIT_REQ, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_OPP, 1, NULL},
{T_OPERATOR_NIT, 2, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_OPP, 1, dissect_dvbci_payload_opp},
{T_OPERATOR_INFO_REQ, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_OPP, 1, NULL},
{T_OPERATOR_INFO, 1, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_OPP, 1, dissect_dvbci_payload_opp},
{T_OPERATOR_SEARCH_START, 3, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_OPP, 1, dissect_dvbci_payload_opp},
{T_OPERATOR_SEARCH_STATUS, 0, 6, DATA_CAM_TO_HOST, RES_CLASS_OPP, 1, dissect_dvbci_payload_opp},
{T_OPERATOR_EXIT, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_OPP, 1, NULL},
{T_OPERATOR_TUNE, 2, LEN_FIELD_ANY, DATA_CAM_TO_HOST, RES_CLASS_OPP, 1, dissect_dvbci_payload_opp},
{T_OPERATOR_TUNE_STATUS, 5, LEN_FIELD_ANY, DATA_HOST_TO_CAM, RES_CLASS_OPP, 1, dissect_dvbci_payload_opp},
{T_OPERATOR_ENTITLEMENT_ACK, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_OPP, 1, NULL},
{T_OPERATOR_SEARCH_CANCEL, 0, 0, DATA_HOST_TO_CAM, RES_CLASS_OPP, 1, NULL},
{T_SAS_CONNECT_RQST, 0, 8, DATA_HOST_TO_CAM, RES_CLASS_SAS, 1, dissect_dvbci_payload_sas},
{T_SAS_CONNECT_CNF, 0, 9, DATA_CAM_TO_HOST, RES_CLASS_SAS, 1, dissect_dvbci_payload_sas},
{T_SAS_ASYNC_MSG, 3, LEN_FIELD_ANY, DIRECTION_ANY, RES_CLASS_SAS, 1, dissect_dvbci_payload_sas}
};
static const value_string dvbci_apdu_tag[] = {
{ T_PROFILE_ENQ, "Profile enquiry" },
{ T_PROFILE, "Profile information" },
{ T_PROFILE_CHANGE, "Profile change notification" },
{ T_APP_INFO_ENQ, "Application info enquiry" },
{ T_APP_INFO, "Application info" },
{ T_ENTER_MENU, "Enter menu" },
{ T_REQUEST_CICAM_RESET, "Request CICAM reset" },
{ T_DATARATE_INFO, "Datarate info" },
{ T_CA_INFO_ENQ, "CA info enquiry" },
{ T_CA_INFO, "CA info" },
{ T_CA_PMT, "CA PMT" },
{ T_CA_PMT_REPLY, "CA PMT reply" },
{ T_AUTH_REQ, "Authentication request" },
{ T_AUTH_RESP, "Authentication response" },
{ T_TUNE, "Tune" },
{ T_REPLACE, "Replace" },
{ T_CLEAR_REPLACE, "Clear replace" },
{ T_ASK_RELEASE, "Ask release" },
{ T_TUNE_BROADCAST_REQ, "Tune broadcast request" },
{ T_TUNE_REPLY, "Tune reply" },
{ T_ASK_RELEASE_REPLY, "Ask release reply" },
{ T_DATE_TIME_ENQ, "Date-Time enquiry" },
{ T_DATE_TIME, "Date-Time" },
{ T_CLOSE_MMI, "Close MMI" },
{ T_DISPLAY_CONTROL, "Display control" },
{ T_DISPLAY_REPLY, "Display reply" },
{ T_TEXT_LAST, "Text last" },
{ T_TEXT_MORE, "Text more" },
{ T_ENQ, "Enquiry" },
{ T_ANSW, "Answer" },
{ T_MENU_LAST, "Menu last" },
{ T_MENU_MORE, "Menu more" },
{ T_MENU_ANSW, "Menu answer" },
{ T_LIST_LAST, "List last" },
{ T_LIST_MORE, "List more" },
{ T_HOST_COUNTRY_ENQ, "Host country enquiry" },
{ T_HOST_COUNTRY, "Host country" },
{ T_HOST_LANGUAGE_ENQ, "Host language enquiry" },
{ T_HOST_LANGUAGE, "Host language" },
{ T_CAM_FIRMWARE_UPGRADE, "CAM firmware upgrade" },
{ T_CAM_FIRMWARE_UPGRADE_REPLY, "CAM firmware upgrade reply" },
{ T_CAM_FIRMWARE_UPGRADE_PROGRESS, "CAM firmware upgrade progress" },
{ T_CAM_FIRMWARE_UPGRADE_COMPLETE, "CAM firmware upgrade complete" },
{ T_CC_OPEN_REQ, "CC open request" },
{ T_CC_OPEN_CNF, "CC open confirm" },
{ T_CC_DATA_REQ, "CC data request" },
{ T_CC_DATA_CNF, "CC data confirm" },
{ T_CC_SYNC_REQ, "CC sync request" },
{ T_CC_SYNC_CNF, "CC sync confirm" },
{ T_CC_SAC_DATA_REQ, "CC SAC data request" },
{ T_CC_SAC_DATA_CNF, "CC SAC data confirm" },
{ T_CC_SAC_SYNC_REQ, "CC SAC sync request" },
{ T_CC_SAC_SYNC_CNF, "CC SAC sync confirm" },
{ T_CC_PIN_CAPABILITIES_REQ, "CC PIN capabilities request" },
{ T_CC_PIN_CAPABILITIES_REPLY, "CC PIN capabilities reply" },
{ T_CC_PIN_CMD, "CC PIN command" },
{ T_CC_PIN_REPLY, "CC PIN reply" },
{ T_CC_PIN_EVENT, "CC PIN event" },
{ T_CC_PIN_PLAYBACK, "CC PIN playback" },
{ T_CC_PIN_MMI_REQ, "CC PIN MMI request" },
{ T_REQUEST_START, "Request start" },
{ T_REQUEST_START_ACK, "Request start ack" },
{ T_FILE_REQUEST, "File request" },
{ T_FILE_ACKNOWLEDGE, "File acknowledge" },
{ T_APP_ABORT_REQUEST, "App abort request" },
{ T_APP_ABORT_ACK, "App abort ack" },
{ T_COMMS_CMD, "Comms command" },
{ T_COMMS_REPLY, "Comms reply" },
{ T_CONNECTION_DESCRIPTOR, "Connection descriptor" },
{ T_COMMS_SEND_LAST, "Comms send last" },
{ T_COMMS_SEND_MORE, "Comms send more" },
{ T_COMMS_RCV_LAST, "Comms receive last" },
{ T_COMMS_RCV_MORE, "Comms receive more" },
{ T_OPERATOR_STATUS_REQ, "Operator status request" },
{ T_OPERATOR_STATUS, "Operator status" },
{ T_OPERATOR_NIT_REQ, "Operator NIT request" },
{ T_OPERATOR_NIT, "Operator NIT" },
{ T_OPERATOR_INFO_REQ, "Operator info request" },
{ T_OPERATOR_INFO, "Operator info" },
{ T_OPERATOR_SEARCH_START, "Operator search start" },
{ T_OPERATOR_SEARCH_STATUS, "Operator search status" },
{ T_OPERATOR_EXIT, "Operator exit" },
{ T_OPERATOR_TUNE, "Operator tune" },
{ T_OPERATOR_TUNE_STATUS, "Operator tune status" },
{ T_OPERATOR_ENTITLEMENT_ACK, "Operator entitlement acknowledge" },
{ T_OPERATOR_SEARCH_CANCEL, "Operator search cancel" },
{ T_SAS_CONNECT_RQST, "SAS connect request" },
{ T_SAS_CONNECT_CNF, "SAS connect confirm" },
{ T_SAS_ASYNC_MSG, "SAS async message" },
{ 0, NULL }
};
static int proto_dvbci = -1;
static const gchar *dvbci_sek = NULL;
static const gchar *dvbci_siv = NULL;
static gboolean dvbci_dissect_lsc_msg = FALSE;
/* the output of pref_key_string_to_bin() applied to dvbci_sek and _siv */
static unsigned char *dvbci_sek_bin = NULL;
static unsigned char *dvbci_siv_bin = NULL;
static dissector_handle_t data_handle;
static dissector_handle_t mpeg_pmt_handle;
static dissector_handle_t dvb_nit_handle;
static dissector_handle_t png_handle;
static dissector_table_t tcp_dissector_table;
static dissector_table_t udp_dissector_table;
static gint exported_pdu_tap = -1;
static gint ett_dvbci = -1;
static gint ett_dvbci_hdr = -1;
static gint ett_dvbci_cis = -1;
static gint ett_dvbci_cis_tpl = -1;
static gint ett_dvbci_cis_subtpl = -1;
static gint ett_dvbci_link = -1;
static gint ett_dvbci_link_frag = -1;
static gint ett_dvbci_link_frags = -1;
static gint ett_dvbci_transport = -1;
static gint ett_dvbci_transport_frag = -1;
static gint ett_dvbci_transport_frags = -1;
static gint ett_dvbci_session = -1;
static gint ett_dvbci_res = -1;
static gint ett_dvbci_application = -1;
static gint ett_dvbci_es = -1;
static gint ett_dvbci_ca_desc = -1;
static gint ett_dvbci_text = -1;
static gint ett_dvbci_cc_item = -1;
static gint ett_dvbci_sac_msg_body = -1;
static gint ett_dvbci_ami_req_types = -1;
static gint ett_dvbci_lsc_conn_desc = -1;
static gint ett_dvbci_opp_cap_loop = -1;
static gint ett_dvbci_dlv_sys_hint = -1;
static int hf_dvbci_event = -1;
static int hf_dvbci_hw_event = -1;
static int hf_dvbci_cor_addr = -1;
static int hf_dvbci_cor_val = -1;
static int hf_dvbci_cis_tpl_code = -1;
static int hf_dvbci_cis_tpl_len = -1;
static int hf_dvbci_cis_tpl_data = -1;
static int hf_dvbci_cis_tpll_v1_major = -1;
static int hf_dvbci_cis_tpll_v1_minor = -1;
static int hf_dvbci_cis_tpll_v1_info_manuf = -1;
static int hf_dvbci_cis_tpll_v1_info_name = -1;
static int hf_dvbci_cis_tpll_v1_info_additional = -1;
static int hf_dvbci_cis_tpll_v1_end = -1;
static int hf_dvbci_cis_tpcc_rfsz = -1;
static int hf_dvbci_cis_tpcc_rmsz = -1;
static int hf_dvbci_cis_tpcc_rasz = -1;
static int hf_dvbci_cis_tpcc_last = -1;
static int hf_dvbci_cis_tpcc_radr = -1;
static int hf_dvbci_cis_tpcc_rmsk = -1;
static int hf_dvbci_cis_st_code = -1;
static int hf_dvbci_cis_st_len = -1;
static int hf_dvbci_cis_stci_ifn_size = -1;
static int hf_dvbci_cis_stci_ifn = -1;
static int hf_dvbci_cis_stci_str = -1;
static int hf_dvbci_cis_tpce_indx_intface = -1;
static int hf_dvbci_cis_tpce_indx_default = -1;
static int hf_dvbci_cis_tpce_indx_cnf_entry = -1;
static int hf_dvbci_cis_tpce_if_type = -1;
static int hf_dvbci_cis_tpce_fs_mem_space = -1;
static int hf_dvbci_cis_tpce_fs_irq = -1;
static int hf_dvbci_cis_tpce_fs_io = -1;
static int hf_dvbci_cis_tplmid_manf = -1;
static int hf_dvbci_cis_tplmid_card = -1;
static int hf_dvbci_buf_size = -1;
static int hf_dvbci_tcid = -1;
static int hf_dvbci_ml = -1;
static int hf_dvbci_l_frags = -1;
static int hf_dvbci_l_frag = -1;
static int hf_dvbci_l_frag_overlap = -1;
static int hf_dvbci_l_frag_overlap_conflicts = -1;
static int hf_dvbci_l_frag_multiple_tails = -1;
static int hf_dvbci_l_frag_too_long_frag = -1;
static int hf_dvbci_l_frag_err = -1;
static int hf_dvbci_l_frag_cnt = -1;
static int hf_dvbci_l_reass_in = -1;
static int hf_dvbci_l_reass_len = -1;
static int hf_dvbci_c_tpdu_tag = -1;
static int hf_dvbci_r_tpdu_tag = -1;
static int hf_dvbci_t_c_id = -1;
static int hf_dvbci_sb_value = -1;
static int hf_dvbci_t_frags = -1;
static int hf_dvbci_t_frag = -1;
static int hf_dvbci_t_frag_overlap = -1;
static int hf_dvbci_t_frag_overlap_conflicts = -1;
static int hf_dvbci_t_frag_multiple_tails = -1;
static int hf_dvbci_t_frag_too_long_frag = -1;
static int hf_dvbci_t_frag_err = -1;
static int hf_dvbci_t_frag_cnt = -1;
static int hf_dvbci_t_reass_in = -1;
static int hf_dvbci_t_reass_len = -1;
static int hf_dvbci_spdu_tag = -1;
static int hf_dvbci_sess_status = -1;
static int hf_dvbci_sess_nb = -1;
static int hf_dvbci_close_sess_status = -1;
static int hf_dvbci_res_id_type = -1;
static int hf_dvbci_res_class = -1;
static int hf_dvbci_res_type = -1;
static int hf_dvbci_res_ver = -1;
static int hf_dvbci_apdu_tag = -1;
static int hf_dvbci_app_type = -1;
static int hf_dvbci_app_manf = -1;
static int hf_dvbci_manf_code = -1;
static int hf_dvbci_menu_str_len = -1;
static int hf_dvbci_ap_char_tbl = -1;
static int hf_dvbci_menu_str = -1;
static int hf_dvbci_data_rate = -1;
static int hf_dvbci_ca_sys_id = -1;
static int hf_dvbci_ca_pmt_list_mgmt = -1;
static int hf_dvbci_prog_num = -1;
static int hf_dvbci_prog_info_len = -1;
static int hf_dvbci_stream_type = -1;
static int hf_dvbci_es_pid = -1;
static int hf_dvbci_es_info_len = -1;
static int hf_dvbci_ca_pmt_cmd_id = -1;
static int hf_dvbci_descr_len = -1;
static int hf_dvbci_ca_pid = -1;
static int hf_dvbci_ca_enable_flag = -1;
static int hf_dvbci_ca_enable = -1;
static int hf_dvbci_auth_proto_id = -1;
static int hf_dvbci_auth_req_bytes = -1;
static int hf_dvbci_auth_resp_bytes = -1;
static int hf_dvbci_network_id = -1;
static int hf_dvbci_original_network_id = -1;
static int hf_dvbci_transport_stream_id = -1;
static int hf_dvbci_service_id = -1;
static int hf_dvbci_replacement_ref = -1;
static int hf_dvbci_replaced_pid = -1;
static int hf_dvbci_replacement_pid = -1;
static int hf_dvbci_pmt_flag = -1;
static int hf_dvbci_hc_desc_loop_len = -1;
static int hf_dvbci_hc_status = -1;
static int hf_dvbci_hc_release_reply = -1;
static int hf_dvbci_resp_intv = -1;
static int hf_dvbci_utc_time = -1;
static int hf_dvbci_local_offset = -1;
static int hf_dvbci_close_mmi_cmd_id = -1;
static int hf_dvbci_close_mmi_delay = -1;
static int hf_dvbci_disp_ctl_cmd = -1;
static int hf_dvbci_mmi_mode = -1;
static int hf_dvbci_disp_rep_id = -1;
static int hf_dvbci_mmi_char_tbl = -1;
static int hf_dvbci_blind_ans = -1;
static int hf_dvbci_ans_txt_len = -1;
static int hf_dvbci_enq = -1;
static int hf_dvbci_ans_id = -1;
static int hf_dvbci_ans = -1;
static int hf_dvbci_choice_nb = -1;
static int hf_dvbci_choice_ref = -1;
static int hf_dvbci_item_nb = -1;
static int hf_dvbci_title = -1;
static int hf_dvbci_subtitle = -1;
static int hf_dvbci_bottom = -1;
static int hf_dvbci_item = -1;
static int hf_dvbci_host_country = -1;
static int hf_dvbci_host_language = -1;
static int hf_dvbci_cup_type = -1;
static int hf_dvbci_cup_download_time = -1;
static int hf_dvbci_cup_answer = -1;
static int hf_dvbci_cup_progress = -1;
static int hf_dvbci_cup_reset = -1;
static int hf_dvbci_cc_sys_id_bitmask = -1;
static int hf_dvbci_cc_dat_id = -1;
static int hf_dvbci_brand_cert = -1;
static int hf_dvbci_dev_cert = -1;
static int hf_dvbci_uri_ver = -1;
static int hf_dvbci_uri_aps = -1;
static int hf_dvbci_uri_emi = -1;
static int hf_dvbci_uri_ict = -1;
static int hf_dvbci_uri_rct = -1;
static int hf_dvbci_uri_dot = -1;
static int hf_dvbci_uri_rl = -1;
static int hf_dvbci_cc_key_register = -1;
static int hf_dvbci_cc_status_field = -1;
static int hf_dvbci_cc_op_mode = -1;
static int hf_dvbci_cc_data = -1;
static int hf_dvbci_sac_msg_ctr = -1;
static int hf_dvbci_sac_proto_ver = -1;
static int hf_dvbci_sac_auth_cip = -1;
static int hf_dvbci_sac_payload_enc = -1;
static int hf_dvbci_sac_enc_cip = -1;
static int hf_dvbci_sac_payload_len = -1;
static int hf_dvbci_sac_enc_body = -1;
static int hf_dvbci_sac_padding = -1;
static int hf_dvbci_sac_signature = -1;
static int hf_dvbci_rating = -1;
static int hf_dvbci_capability_field = -1;
static int hf_dvbci_pin_chg_time = -1;
static int hf_dvbci_pincode_status = -1;
static int hf_dvbci_cc_prog_num = -1;
static int hf_dvbci_pin_evt_time = -1;
static int hf_dvbci_pin_evt_cent = -1;
static int hf_dvbci_cc_priv_data = -1;
static int hf_dvbci_pincode = -1;
static int hf_dvbci_app_dom_id = -1;
static int hf_dvbci_init_obj = -1;
static int hf_dvbci_ack_code = -1;
static int hf_dvbci_req_type = -1;
static int hf_dvbci_file_hash = -1;
static int hf_dvbci_file_name = -1;
static int hf_dvbci_ami_priv_data = -1;
static int hf_dvbci_req_ok = -1;
static int hf_dvbci_file_ok = -1;
static int hf_dvbci_file_data = -1;
static int hf_dvbci_abort_req_code = -1;
static int hf_dvbci_abort_ack_code = -1;
static int hf_dvbci_phase_id = -1;
static int hf_dvbci_comms_rep_id = -1;
static int hf_dvbci_lsc_buf_size = -1;
static int hf_dvbci_lsc_ret_val = -1;
static int hf_dvbci_comms_cmd_id = -1;
static int hf_dvbci_conn_desc_type = -1;
static int hf_dvbci_lsc_media_tag = -1;
static int hf_dvbci_lsc_media_len = -1;
static int hf_dvbci_lsc_ip_ver = -1;
static int hf_dvbci_lsc_ipv4_addr = -1;
static int hf_dvbci_lsc_ipv6_addr = -1;
static int hf_dvbci_lsc_dst_port = -1;
static int hf_dvbci_lsc_proto = -1;
static int hf_dvbci_lsc_hostname = -1;
static int hf_dvbci_lsc_retry_count = -1;
static int hf_dvbci_lsc_timeout = -1;
static int hf_dvbci_info_ver_op_status = -1;
static int hf_dvbci_nit_ver = -1;
static int hf_dvbci_pro_typ = -1;
static int hf_dvbci_init_flag = -1;
static int hf_dvbci_ent_chg_flag = -1;
static int hf_dvbci_ent_val_flag = -1;
static int hf_dvbci_ref_req_flag = -1;
static int hf_dvbci_err_flag = -1;
static int hf_dvbci_dlv_sys_hint = -1;
static int hf_dvbci_dlv_sys_hint_t = -1;
static int hf_dvbci_dlv_sys_hint_s = -1;
static int hf_dvbci_dlv_sys_hint_c = -1;
static int hf_dvbci_refr_req_date = -1;
static int hf_dvbci_refr_req_time = -1;
static int hf_dvbci_nit_loop_len = -1;
static int hf_dvbci_info_valid = -1;
static int hf_dvbci_info_ver_op_info = -1;
static int hf_dvbci_cicam_onid = -1;
static int hf_dvbci_cicam_id = -1;
static int hf_dvbci_opp_char_tbl = -1;
static int hf_dvbci_sdt_rst_trusted = -1;
static int hf_dvbci_eit_rst_trusted = -1;
static int hf_dvbci_eit_pf_usage = -1;
static int hf_dvbci_eit_sch_usage = -1;
static int hf_dvbci_ext_evt_usage = -1;
static int hf_dvbci_sdt_oth_trusted = -1;
static int hf_dvbci_eit_evt_trigger = -1;
static int hf_dvbci_opp_lang_code = -1;
static int hf_dvbci_prof_name = -1;
static int hf_dvbci_unattended = -1;
static int hf_dvbci_opp_srv_type = -1;
static int hf_dvbci_dlv_cap_byte = -1;
static int hf_dvbci_app_cap_bytes = -1;
static int hf_dvbci_desc_num = -1;
static int hf_dvbci_sig_strength = -1;
static int hf_dvbci_sig_qual = -1;
static int hf_dvbci_opp_tune_status = -1;
static int hf_dvbci_opp_desc_loop_len = -1;
static int hf_dvbci_sas_app_id = -1;
static int hf_dvbci_sas_sess_state = -1;
static int hf_dvbci_sas_msg_nb = -1;
static int hf_dvbci_sas_msg_len = -1;
static const int *dvbci_opp_dlv_sys_hint_fields[] = {
&hf_dvbci_dlv_sys_hint_t,
&hf_dvbci_dlv_sys_hint_s,
&hf_dvbci_dlv_sys_hint_c,
NULL
};
static expert_field ei_dvbci_spdu_tag = EI_INIT;
static expert_field ei_dvbci_sac_payload_enc = EI_INIT;
static expert_field ei_dvbci_buf_size = EI_INIT;
static expert_field ei_dvbci_cicam_nit_table_id = EI_INIT;
static expert_field ei_dvbci_c_tpdu_tag = EI_INIT;
static expert_field ei_dvbci_res_class = EI_INIT;
static expert_field ei_dvbci_bad_length = EI_INIT;
static expert_field ei_dvbci_apdu_not_supported = EI_INIT;
static expert_field ei_dvbci_not_text_more_or_text_last = EI_INIT;
static expert_field ei_dvbci_apu_cam_to_host = EI_INIT;
static expert_field ei_dvbci_ca_pmt_cmd_id = EI_INIT;
static expert_field ei_dvbci_ml = EI_INIT;
static expert_field ei_dvbci_cup_progress = EI_INIT;
static expert_field ei_dvbci_sb_value = EI_INIT;
static expert_field ei_dvbci_spdu_cam_to_host = EI_INIT;
static expert_field ei_dvbci_spdu_host_to_cam = EI_INIT;
static expert_field ei_dvbci_network_id = EI_INIT;
static expert_field ei_dvbci_invalid_char_tbl = EI_INIT;
static expert_field ei_dvbci_t_c_id = EI_INIT;
static expert_field ei_dvbci_tpdu_status_tag = EI_INIT;
static expert_field ei_dvbci_r_tpdu_tag = EI_INIT;
static expert_field ei_dvbci_cor_addr = EI_INIT;
static expert_field ei_dvbci_pin_evt_cent = EI_INIT;
static expert_field ei_dvbci_res_ver = EI_INIT;
static expert_field ei_dvbci_apdu_tag = EI_INIT;
static expert_field ei_dvbci_r_tpdu_status_mandatory = EI_INIT;
static expert_field ei_dvbci_apu_host_to_cam = EI_INIT;
static expert_field ei_dvbci_sig_qual = EI_INIT;
static dissector_table_t sas_msg_dissector_table;
static reassembly_table tpdu_reassembly_table;
static reassembly_table spdu_reassembly_table;
static const fragment_items tpdu_frag_items = {
&ett_dvbci_link_frag,
&ett_dvbci_link_frags,
&hf_dvbci_l_frags,
&hf_dvbci_l_frag,
&hf_dvbci_l_frag_overlap,
&hf_dvbci_l_frag_overlap_conflicts,
&hf_dvbci_l_frag_multiple_tails,
&hf_dvbci_l_frag_too_long_frag,
&hf_dvbci_l_frag_err,
&hf_dvbci_l_frag_cnt,
&hf_dvbci_l_reass_in,
&hf_dvbci_l_reass_len,
/* Reassembled data field */
NULL,
"Tpdu fragments"
};
static const fragment_items spdu_frag_items = {
&ett_dvbci_transport_frag,
&ett_dvbci_transport_frags,
&hf_dvbci_t_frags,
&hf_dvbci_t_frag,
&hf_dvbci_t_frag_overlap,
&hf_dvbci_t_frag_overlap_conflicts,
&hf_dvbci_t_frag_multiple_tails,
&hf_dvbci_t_frag_too_long_frag,
&hf_dvbci_t_frag_err,
&hf_dvbci_t_frag_cnt,
&hf_dvbci_t_reass_in,
&hf_dvbci_t_reass_len,
/* Reassembled data field */
NULL,
"Spdu fragments"
};
typedef struct _spdu_info_t {
guint8 tag;
guint8 direction;
guint8 len_field;
} spdu_info_t;
static const value_string dvbci_hw_event[] = {
{ CAM_IN, "CI Module is inserted" },
{ CAM_OUT, "CI Module is removed" },
{ POWER_ON, "CI slot power on" },
{ POWER_OFF, "CI slot power off" },
{ TS_ROUTE, "Transport stream routed through the CI Module" },
{ TS_BYPASS, "Transport stream bypasses the CI Module" },
{ RESET_H, "Reset pin is high" },
{ RESET_L, "Reset pin is low" },
{ READY_H, "Ready pin is high" },
{ READY_L, "Ready pin is low" },
{ 0, NULL }
};
static const value_string dvbci_cis_tpl_code[] = {
{ CISTPL_NO_LINK, "No-link tuple" },
{ CISTPL_VERS_1, "Level 1 version/product information" },
{ CISTPL_CONFIG, "Configuration for a 16bit PC-Card" },
{ CISTPL_CFTABLE_ENTRY, "Configuration-table entry" },
{ CISTPL_DEVICE_OC, "Device information for Common Memory" },
{ CISTPL_DEVICE_OA, "Device information for Attribute Memory" },
{ CISTPL_MANFID, "Manufacturer indentification string" },
{ CISTPL_END, "End of chain" },
{ 0, NULL }
};
static const value_string dvbci_cis_subtpl_code[] = {
{ CCSTPL_CIF, "Custom interface subtuple" },
{ 0, NULL }
};
static const value_string dvbci_cis_tpce_if_type[] = {
{ TPCE_IF_TYPE_MEM, "Memory" },
{ TPCE_IF_TYPE_IO_MEM, "I/O and Memory" },
{ TPCE_IF_TYPE_CUST0, "Custom Interface 0" },
{ TPCE_IF_TYPE_CUST1, "Custom Interface 1" },
{ TPCE_IF_TYPE_CUST2, "Custom Interface 2" },
{ TPCE_IF_TYPE_CUST3, "Custom Interface 3" },
{ 0, NULL }
};
static const value_string dvbci_ml[] = {
{ ML_MORE, "more TPDU fragments pending" },
{ ML_LAST, "last TPDU fragment" },
{ 0, NULL }
};
static const value_string dvbci_c_tpdu[] = {
{ T_RCV, "T_RCV" },
{ T_CREATE_T_C, "T_create_t_c" },
{ T_DELETE_T_C, "T_delete_t_c" },
{ T_D_T_C_REPLY, "T_d_t_c_reply" },
{ T_NEW_T_C, "T_new_t_c" },
{ T_T_C_ERROR, "T_t_c_error" },
{ T_DATA_LAST, "T_data_last" },
{ T_DATA_MORE, "T_data_more" },
{ 0, NULL }
};
static const value_string dvbci_r_tpdu[] = {
{ T_C_T_C_REPLY, "T_c_tc_reply" },
{ T_DELETE_T_C, "T_delete_t_c" },
{ T_D_T_C_REPLY, "T_d_t_c_reply" },
{ T_REQUEST_T_C, "T_request_t_c" },
{ T_DATA_LAST, "T_data_last" },
{ T_DATA_MORE, "T_data_more" },
{ 0, NULL }
};
static const value_string dvbci_sb_value[] = {
{ SB_VAL_MSG_AVAILABLE, "message available" },
{ SB_VAL_NO_MSG_AVAILABLE, "no message available" },
{ 0, NULL }
};
static const value_string dvbci_spdu_tag[] = {
{ T_SESSION_NUMBER, "Session Number (payload data)" },
{ T_OPEN_SESSION_REQUEST, "Open Session Request" },
{ T_OPEN_SESSION_RESPONSE, "Open Session Response" },
{ T_CREATE_SESSION, "Create Session" },
{ T_CREATE_SESSION_RESPONSE, "Create Session Response" },
{ T_CLOSE_SESSION_REQUEST, "Close Session Request" },
{ T_CLOSE_SESSION_RESPONSE, "Close Session Response" },
{ 0, NULL }
};
static GHashTable *spdu_table = NULL;
static const spdu_info_t spdu_info[] = {
{ T_SESSION_NUMBER, DIRECTION_ANY, 2 },
{ T_OPEN_SESSION_REQUEST, DATA_CAM_TO_HOST, 4 },
{ T_OPEN_SESSION_RESPONSE, DATA_HOST_TO_CAM, 7 },
{ T_CREATE_SESSION, DATA_HOST_TO_CAM, 6 },
{ T_CREATE_SESSION_RESPONSE, DATA_CAM_TO_HOST, 7 },
{ T_CLOSE_SESSION_REQUEST, DIRECTION_ANY, 2 },
{ T_CLOSE_SESSION_RESPONSE, DIRECTION_ANY, 3 }
};
static const value_string dvbci_sess_status[] = {
{ SESS_OPENED,
"Session opened" },
{ SESS_NOT_OPENED_RES_NON_EXIST,
"Resource does not exist" },
{ SESS_NOT_OPENED_RES_UNAVAIL,
"Resource exists but it's unavailable" },
{ SESS_NOT_OPENED_RES_VER_LOWER,
"Existing resource's version is lower than requested version" },
{ SESS_NOT_OPENED_RES_BUSY,
"Resource is busy" },
{ 0, NULL }
};
static const value_string dvbci_close_sess_status[] = {
{ SESS_CLOSED, "Session closed" },
{ SESS_NB_NOT_ALLOC, "Session number not allocated" },
{ 0, NULL }
};
static const value_string dvbci_res_class[] = {
{ RES_CLASS_RM, "Resource Manager" },
{ RES_CLASS_AP, "Application Info" },
{ RES_CLASS_CA, "Conditional Access" },
{ RES_CLASS_AUT, "Authentication" },
{ RES_CLASS_HC, "Host Control" },
{ RES_CLASS_DT, "Date-Time" },
{ RES_CLASS_MMI, "Man-machine interface (MMI)" },
{ RES_CLASS_AMI, "Application MMI" },
{ RES_CLASS_LSC, "Low-Speed Communication" },
{ RES_CLASS_CC, "Content Control" },
{ RES_CLASS_HLC, "Host Language & Country" },
{ RES_CLASS_CUP, "CAM Upgrade" },
{ RES_CLASS_OPP, "Operator Profile" },
{ RES_CLASS_SAS, "Specific Application Support" },
{ 0, NULL }
};
static const value_string dvbci_app_type[] = {
{ APP_TYPE_CA, "Conditional Access" },
{ APP_TYPE_EPG, "Electronic Progam Guide" },
{ 0, NULL }
};
static const value_string dvbci_data_rate[] = {
{ DATA_RATE_72, "72 Mbit/s" },
{ DATA_RATE_96, "96 Mbit/s" },
{ 0, NULL }
};
static const value_string dvbci_ca_pmt_list_mgmt[] = {
{ LIST_MGMT_MORE, "more" },
{ LIST_MGMT_FIRST, "first" },
{ LIST_MGMT_LAST, "last" },
{ LIST_MGMT_ONLY, "only" },
{ LIST_MGMT_ADD, "add" },
{ LIST_MGMT_UPDATE, "update" },
{ 0, NULL }
};
static const value_string dvbci_ca_pmt_cmd_id[] = {
{ CMD_ID_OK_DESCR, "ok descrambling" },
{ CMD_ID_OK_MMI, "ok mmi" },
{ CMD_ID_QUERY, "query" },
{ CMD_ID_NOT_SELECTED, "not selected" },
{ 0, NULL }
};
static const value_string dvbci_ca_enable[] = {
{ CA_ENAB_DESC_OK, "descrambling possible" },
{ CA_ENAB_DESC_OK_PURCHASE,
"descrambling possible under conditions (purchase dialogue)" },
{ CA_ENAB_DESC_OK_TECH,
"descrambling possible under conditions (technical dialogue)" },
{ CA_ENAB_DESC_NG_ENTITLEMENT,
"descrambling not possible (because no entitlement)" },
{ CA_ENAB_DESC_NG_TECH,
"descrambling not possible (for technical reasons)" },
{ 0, NULL }
};
static const value_string dvbci_hc_status[] = {
{ HC_STAT_OK, "ok" },
{ HC_STAT_ERR_DLVRY, "unsupported delivery system descriptor" },
{ HC_STAT_ERR_LOCK, "tuner not locking" },
{ HC_STAT_ERR_BUSY, "tuner busy" },
{ HC_STAT_ERR_PARAM, "bad or missing parameters" },
{ HC_STAT_ERR_NOT_FOUND, "service not found" },
{ HC_STAT_ERR_UNKNOWN, "unknown error" },
{ 0, NULL }
};
static const value_string dvbci_hc_release_reply[] = {
{ HC_RELEASE_OK, "Host regains control of the tuner" },
{ HC_RELEASE_REFUSED, "CICAM retains control of the tuner" },
{ 0, NULL }
};
static const value_string dvbci_close_mmi_cmd_id[] = {
{ CLOSE_MMI_CMD_ID_IMMEDIATE, "immediate close" },
{ CLOSE_MMI_CMD_ID_DELAY, "delayed close" },
{ 0, NULL }
};
static const value_string dvbci_disp_ctl_cmd[] = {
{ DISP_CMD_SET_MMI_MODE, "set MMI mode" },
{ DISP_CMD_GET_DISP_TBL, "get display character tables" },
{ DISP_CMD_GET_INP_TBL, "get input character tables" },
{ 0, NULL }
};
static const value_string dvbci_mmi_mode[] = {
{ MMI_MODE_HIGH, "High-level MMI" },
{ 0, NULL }
};
static const value_string dvbci_disp_rep_id[] = {
{ DISP_REP_ID_MMI_MODE_ACK, "MMI mode acknowledge" },
{ DISP_REP_ID_DISP_CHAR_TBL, "list display character tables" },
{ DISP_REP_ID_INP_CHAR_TBL, "list input character tables" },
{ DISP_REP_ID_UNKNOWN_CMD, "unknown display control command" },
{ DISP_REP_ID_UNKNOWN_MMI_MODE, "unknown MMI mode" },
{ DISP_REP_ID_UNKNOWN_CHAR_TBL, "unknown character table" },
{ 0, NULL }
};
static const value_string dvbci_blind_ans[] = {
{ VISIBLE_ANS, "visible" },
{ BLIND_ANS, "blind" },
{ 0, NULL }
};
static const value_string dvbci_ans_id[] = {
{ ANSW_ID_CANCEL, "cancel" },
{ ANSW_ID_ANSWER, "answer" },
{ 0, NULL }
};
static const value_string dvbci_cup_type[] = {
{ CUP_DELAYED, "delayed" },
{ CUP_IMMEDIATE, "immediate" },
{ 0, NULL }
};
static const value_string dvbci_cup_answer[] = {
{ CUP_ANS_NO, "upgrade denied" },
{ CUP_ANS_YES, "upgrade allowed" },
{ CUP_ANS_ASK, "ask the user for permission" },
{ 0, NULL }
};
static const value_string dvbci_cup_reset[] = {
{ CUP_RESET_PCMCIA, "PCMCIA reset" },
{ CUP_RESET_CMDIF, "CI command interface reset" },
{ CUP_RESET_NONE, "no reset" },
{ 0, NULL }
};
static const value_string dvbci_cc_dat_id[] = {
{ CC_ID_HOST_ID, "Host ID" },
{ CC_ID_CICAM_ID, "Cicam ID" },
{ CC_ID_HOST_BRAND_CERT, "Host brand certificate" },
{ CC_ID_CICAM_BRAND_CERT, "Cicam brand certificate" },
{ CC_ID_KP, "Key precursor for CCK" },
{ CC_ID_DHPH, "Host Diffie-Hellman public key" },
{ CC_ID_DHPM, "Cicam Diffie-Hellman public key" },
{ CC_ID_HOST_DEV_CERT, "Host device certificate" },
{ CC_ID_CICAM_DEV_CERT, "Cicam device certificate" },
{ CC_ID_SIG_A, "Signature of host Diffie-Hellman public key" },
{ CC_ID_SIG_B, "Signature of cicam Diffie-Hellman public key" },
{ CC_ID_NS_HOST, "Host nonce" },
{ CC_ID_AUTH_NONCE, "Nonce for authentication" },
{ CC_ID_NS_MODULE, "Cicam nonce" },
{ CC_ID_AKH, "Host authentication key" },
{ CC_ID_URI, "URI" },
{ CC_ID_PROG_NUM, "Program number" },
{ CC_ID_URI_CNF, "URI confirmation" },
{ CC_ID_KEY_REGISTER, "Key register" },
{ CC_ID_URI_VERSIONS, "Supported URI versions" },
{ CC_ID_STATUS_FIELD, "Status field" },
{ CC_ID_SRM_DATA, "SRM for HDCP" },
{ CC_ID_SRM_CONFIRM, "SRM confirmation hash" },
{ CC_ID_CICAM_LICENSE, "License received from the cicam" },
{ CC_ID_LICENSE_STATUS, "Current status of the license" },
{ CC_ID_LICENSE_RCV_STATUS, "Status of the license exchange" },
{ CC_ID_HOST_LICENSE,
"License for which the host requests the current status" },
{ CC_ID_PLAY_COUNT, "Play count" },
{ CC_ID_OPERATING_MODE, "Operating mode" },
{ CC_ID_PINCODE_DATA, "Pincode data" },
{ CC_ID_REC_START_STATUS, "Record start status" },
{ CC_ID_MODE_CHG_STATUS, "Change operating mode status" },
{ CC_ID_REC_STOP_STATUS, "Record stop status" },
{ 0, NULL }
};
static const value_string dvbci_cc_uri_emi[] = {
{ CC_EMI_FREE, "Copy free" },
{ CC_EMI_NO_MORE, "Copy no more" },
{ CC_EMI_ONCE, "Copy once" },
{ CC_EMI_NEVER, "Copy never" },
{ 0, NULL }
};
static const value_string dvbci_cc_key_register[] = {
{ CC_KEY_EVEN, "Even" },
{ CC_KEY_ODD, "Odd" },
{ 0, NULL }
};
static const value_string dvbci_cc_status[] = {
{ CC_STATUS_OK, "Ok" },
{ CC_STATUS_NO_CC_SUPPORT, "No CC support" },
{ CC_STATUS_HOST_BUSY, "Host busy" },
{ CC_STATUS_AUTH_FAILED_OR_NO_SRM, "Authentication failed / SRM not required" },
{ CC_STATUS_CICAM_BUSY, "CICAM busy" },
{ CC_STATUS_REC_MODE_ERR, "Recording mode error" },
{ 0, NULL }
};
static const value_string dvbci_cc_sac_auth[] = {
{ CC_SAC_AUTH_AES128_XCBC_MAC, "AES 128 XCBC MAC" },
{ 0, NULL }
};
static const value_string dvbci_cc_sac_enc[] = {
{ CC_SAC_ENC_AES128_CBC, "AES 128 CBC" },
{ 0, NULL }
};
static const value_string dvbci_cc_cap[] = {
{ CC_CAP_NONE,
"No PIN handling capability" },
{ CC_CAP_CAS_PIN,
"CAM can do PIN handling on CAS services" },
{ CC_CAP_CAS_FTA_PIN,
"CAM can do PIN handling on CAS and free services" },
{ CC_CAP_CAS_PIN_CACHED,
"CAM can do PIN handling on CAS services and supports PIN caching" },
{ CC_CAP_CAS_FTA_PIN_CACHED,
"CAM can do PIN handling on CAS and free services, supports PIN caching" },
{ 0, NULL }
};
static const value_string dvbci_pincode_status[] = {
{ CC_PIN_BAD, "Bad pin code" },
{ CC_PIN_CAM_BUSY, "CAM busy" },
{ CC_PIN_OK, "Pin code correct" },
{ CC_PIN_UNCONFIRMED, "Pin code unconfirmed" },
{ CC_PIN_VB_NOT_REQ, "Video blanking not required" },
{ CC_PIN_CSA, "Content still CSA scrambled" },
{ 0, NULL }
};
static const value_string dvbci_cc_op_mode[] = {
{ CC_OP_MODE_WATCH_BUFFER, "Watch and buffer" },
{ CC_OP_MODE_TIMESHIFT, "Timeshift" },
{ CC_OP_MODE_UNATTENDED, "Unattended recording" },
{ 0, NULL }
};
static const value_string dvbci_ack_code[] = {
{ ACK_CODE_OK, "Ok" },
{ ACK_CODE_WRONG_API, "Application Domain unsupported" },
{ ACK_CODE_API_BUSY, "Application Domain currently unavailable" },
{ 0, NULL }
};
static const value_string dvbci_req_type[] = {
{ REQ_TYPE_FILE, "File" },
{ REQ_TYPE_DATA, "Data" },
{ REQ_TYPE_FILE_HASH, "FileHash" },
{ REQ_TYPE_REQ, "List supported request types" },
{ 0, NULL }
};
static const value_string dvbci_comms_cmd_id[] = {
{ COMMS_CMD_ID_CONNECT_ON_CHANNEL, "connect on channel" },
{ COMMS_CMD_ID_DISCONNECT_ON_CHANNEL, "disconnect on channel" },
{ COMMS_CMD_ID_SET_PARAMS, "set parameters" },
{ COMMS_CMD_ID_ENQUIRE_STATUS, "status enquiry" },
{ COMMS_CMD_ID_GET_NEXT_BUFFER, "get next buffer" },
{ 0, NULL }
};
static const value_string dvbci_conn_desc_type[] = {
{ CONN_DESC_TEL, "DVB-SI telephone descriptor" },
{ CONN_DESC_CABLE, "cable return channel" },
{ CONN_DESC_IP, "IP descriptor" },
{ CONN_DESC_HOSTNAME, "hostname descriptor" },
{ 0, NULL }
};
static const value_string dvbci_lsc_desc_tag[] = {
{ LSC_DESC_IP, "IP descriptor" },
{ LSC_DESC_HOSTNAME, "hostname descriptor" },
{ 0, NULL }
};
static const value_string dvbci_lsc_ip_ver[] = {
{ LSC_IPV4, "IPv4" },
{ LSC_IPV6, "IPv6" },
{ 0, NULL }
};
static const value_string dvbci_lsc_proto[] = {
{ LSC_TCP, "TCP" },
{ LSC_UDP, "UDP" },
{ 0, NULL }
};
static const value_string dvbci_comms_rep_id[] = {
{ COMMS_REP_ID_CONNECT_ACK, "connect ack" },
{ COMMS_REP_ID_DISCONNECT_ACK, "disconnect ack" },
{ COMMS_REP_ID_SET_PARAMS_ACK, "set parameters ack" },
{ COMMS_REP_ID_STATUS_REPLY, "status reply" },
{ COMMS_REP_ID_GET_NEXT_BUFFER_ACK, "get next buffer ack" },
{ COMMS_REP_ID_SEND_ACK, "send ack" },
{ 0, NULL }
};
static const value_string dvbci_lsc_ret_val[] = {
{ LSC_RET_OK, "ok" },
{ 0, NULL }
};
static const value_string dvbci_lsc_ret_val_connect[] = {
{ LSC_RET_DISCONNECTED, "disconnected" },
{ LSC_RET_CONNECTED, "connected" },
{ 0, NULL }
};
static const value_string dvbci_lsc_ret_val_params[] = {
{ LSC_RET_OK, "ok" },
{ LSC_RET_TOO_BIG, "buffer size too big" },
{ 0, NULL }
};
static const value_string dvbci_opp_ref_req_flag[] = {
{ OPP_REF_REG_FLG_NONE, "none" },
{ OPP_REF_REG_FLG_ADV, "advance warning" },
{ OPP_REF_REG_FLG_URG, "urgent" },
{ OPP_REF_REG_FLG_SCHED, "scheduled" },
{ 0, NULL }
};
static const value_string dvbci_opp_err_flag[] = {
{ OPP_ERR_FLG_OK, "no error" },
{ OPP_ERR_FLG_PROF, "CICAM can't acquire the profile" },
{ OPP_ERR_FLG_UNSUPPORTED, "unsupported delivery system" },
{ OPP_ERR_FLG_CANCELLED, "operator search was cancelled" },
{ 0, NULL }
};
static const value_string dvbci_opp_eit_pf_usage[] = {
{ OPP_EIT_ABSENT, "no EIT present" },
{ OPP_EIT_NOT_X, "EIT is not fully ross-carried" },
{ OPP_EIT_FULL_X, "EIT is fully cross-carried" },
{ 0, NULL }
};
static const value_string dvbci_opp_eit_sch_usage[] = {
{ OPP_EIT_ABSENT, "no EIT present" },
{ OPP_EIT_NOT_X, "EIT is not fully ross-carried" },
{ OPP_EIT_FULL_X, "EIT is fully cross-carried" },
{ OPP_EIT_BARKER, "EIT is available from a barker channel" },
{ OPP_EPG_APP, "EPG is delivered using an application" },
{ 0, NULL }
};
static const value_string dvbci_opp_ext_evt[] = {
{ OPP_EXT_EVT_DIFF, "extended event info is different from short event" },
{ OPP_EXT_EVT_ADD, "extended event info includes short event" },
{ 0, NULL }
};
static const value_string dvbci_opp_dlv_cap[] = {
{ OPP_DLV_CAP_S, "DVB-S" },
{ OPP_DLV_CAP_C, "DVB-C" },
{ OPP_DLV_CAP_T, "DVB-T" },
{ OPP_DLV_CAP_S2, "DVB-S2" },
{ 0, NULL }
};
static const value_string dvbci_opp_tune_stat[] = {
{ OPP_TUNE_OK, "success" },
{ OPP_TUNE_UNSUPPORTED, "unsupported delivery system descriptor" },
{ OPP_TUNE_INVALID, "invalid delivery system descriptor" },
{ OPP_TUNE_ERR, "failed" },
{ 0, NULL }
};
static const value_string dvbci_sas_sess_state[] = {
{ SAS_SESS_STATE_CONNECTED, "connected" },
{ SAS_SESS_STATE_NOT_FOUND, "application not found" },
{ SAS_SESS_STATE_DENIED, "denied, no more connections available" },
{ 0, NULL }
};
static guint16 buf_size_cam; /* buffer size proposal by the CAM */
/* buffer size proposal by the host == negotiated buffer size */
static guint16 buf_size_host;
gint
dvbci_set_addrs(guint8 event, packet_info *pinfo)
{
if (!IS_DATA_TRANSFER(event))
return -1;
if (event == DVBCI_EVT_DATA_HOST_TO_CAM) {
SET_ADDRESS(&pinfo->src, AT_STRINGZ,
(int)strlen(ADDR_HOST)+1, ADDR_HOST);
SET_ADDRESS(&pinfo->dst, AT_STRINGZ,
(int)strlen(ADDR_CAM)+1 , ADDR_CAM);
}
else {
SET_ADDRESS(&pinfo->src, AT_STRINGZ,
(int)strlen(ADDR_CAM)+1 , ADDR_CAM);
SET_ADDRESS(&pinfo->dst, AT_STRINGZ,
(int)strlen(ADDR_HOST)+1, ADDR_HOST);
}
return 1;
}
guint8
dvbci_get_evt_from_addrs(packet_info *pinfo)
{
/* this should be working from C89 on */
static const address a_cam = { AT_STRINGZ, -1, sizeof(ADDR_CAM), ADDR_CAM };
static const address a_host = { AT_STRINGZ, -1, sizeof(ADDR_HOST), ADDR_HOST };
if ( ADDRESSES_EQUAL(&(pinfo->src), &a_cam) &&
ADDRESSES_EQUAL(&(pinfo->dst), &a_host) ) {
return DVBCI_EVT_DATA_CAM_TO_HOST;
}
else if ( ADDRESSES_EQUAL(&(pinfo->src), &a_host) &&
ADDRESSES_EQUAL(&(pinfo->dst), &a_cam) ) {
return DVBCI_EVT_DATA_HOST_TO_CAM;
}
else
return DVBCI_EVT_INVALID_EVT;
}
/* this must be a function, not a macro,
so that we can enforce the return type */
static inline gint16 two_comp_to_int16(guint16 x)
{
return (x&0x8000) ? -~(x-1) : x;
}
/* initialize/reset per capture state data */
static void
dvbci_init(void)
{
buf_size_cam = 0;
buf_size_host = 0;
reassembly_table_init(&tpdu_reassembly_table,
&addresses_reassembly_table_functions);
reassembly_table_init(&spdu_reassembly_table,
&addresses_reassembly_table_functions);
}
/* dissect a delivery system descriptor loop
and the preceding length field
(used for host control and operator profile)
return the number of bytes dissected */
static gint
dissect_desc_loop(int len_hf,
tvbuff_t *tvb, gint offset, packet_info *pinfo _U_, proto_tree *tree)
{
gint offset_start;
guint16 desc_loop_len;
guint desc_len;
offset_start = offset;
desc_loop_len = tvb_get_ntohs(tvb, offset) & 0x0FFF;
proto_tree_add_item(tree, len_hf, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
while (offset-offset_start < 2+desc_loop_len) {
desc_len = proto_mpeg_descriptor_dissect(tvb, offset, tree);
if (desc_len==0)
break;
offset += desc_len;
}
return offset-offset_start;
}
/* dissect operator profile's status body, return its length */
static gint
dissect_opp_status_body(tvbuff_t *tvb, gint offset,
packet_info *pinfo _U_, proto_tree *tree)
{
gint offset_start;
offset_start = offset;
proto_tree_add_item(tree, hf_dvbci_info_ver_op_status,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_nit_ver,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_pro_typ,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_init_flag,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_ent_chg_flag,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_ent_val_flag,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_ref_req_flag,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_err_flag,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_bitmask(tree, tvb, offset,
hf_dvbci_dlv_sys_hint, ett_dvbci_dlv_sys_hint,
dvbci_opp_dlv_sys_hint_fields, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_refr_req_date,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_dvbci_refr_req_time,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
return offset-offset_start;
}
/* dissect a capability loop in an operator_search_start apdu */
static gint
dissect_opp_cap_loop(guint8 cap_loop_len, const gchar *title,
int item_hf, guint item_len,
tvbuff_t *tvb, gint offset,
packet_info *pinfo _U_, proto_tree *tree)
{
proto_tree *loop_tree = NULL;
guint i;
if (!title)
return -1;
if (item_len==0)
return -1;
if (tree && cap_loop_len>0) {
loop_tree = proto_tree_add_subtree(tree, tvb, offset, cap_loop_len, ett_dvbci_opp_cap_loop, NULL, title);
}
for (i=0; i<item_len*cap_loop_len; i+=item_len) {
proto_tree_add_item(loop_tree, item_hf,
tvb, offset+i, item_len, ENC_BIG_ENDIAN);
}
return cap_loop_len;
}
/* dissect age rating byte encoded as defined in
DVB-SI parental rating descriptor
returns rating's length in bytes or -1 for error */
static gint
dissect_rating(tvbuff_t *tvb, gint offset,
packet_info *pinfo _U_, proto_tree *tree)
{
guint8 rating;
rating = tvb_get_guint8(tvb, offset);
if (1<=rating && rating<=0x0F) {
proto_tree_add_uint_format(tree, hf_dvbci_rating,
tvb, offset, 1, rating,
"Rating is %d years (%d+3)", rating+3, rating);
} else {
proto_tree_add_uint_format(tree, hf_dvbci_rating,
tvb, offset, 1, rating,
"Rating is unknown/undefined (%d)", rating);
}
return 1;
}
/* if there's a dissector for the protocol and target port of our
lsc connection, store it in the lsc session's circuit */
static void
store_lsc_msg_dissector(circuit_t *circuit, guint8 ip_proto, guint16 port)
{
dissector_handle_t msg_handle = NULL;
if (!circuit)
return;
if (ip_proto==LSC_TCP)
msg_handle = dissector_get_uint_handle(tcp_dissector_table, port);
else if (ip_proto==LSC_UDP)
msg_handle = dissector_get_uint_handle(udp_dissector_table, port);
circuit_set_dissector(circuit, msg_handle);
}
/* dissect a connection_descriptor for the lsc resource
returns its length or -1 for error */
static gint
dissect_conn_desc(tvbuff_t *tvb, gint offset, circuit_t *circuit,
packet_info *pinfo, proto_tree *tree)
{
proto_item *ti;
proto_tree *conn_desc_tree = NULL;
guint32 tag;
gint offset_start, offset_body;
gint len_field;
guint8 conn_desc_type;
guint8 ip_ver, ip_proto;
guint16 port;
proto_item *port_item = NULL;
gint hostname_len;
offset_start = offset;
tag = tvb_get_ntoh24(tvb, offset);
if (tag!= T_CONNECTION_DESCRIPTOR)
return 0;
conn_desc_tree = proto_tree_add_subtree(tree, tvb,
offset_start, -1, ett_dvbci_lsc_conn_desc, &ti, "Connection descriptor");
proto_tree_add_item(conn_desc_tree, hf_dvbci_apdu_tag,
tvb, offset, APDU_TAG_SIZE, ENC_BIG_ENDIAN);
offset += APDU_TAG_SIZE;
offset = dissect_ber_length(pinfo, conn_desc_tree,
tvb, offset, &len_field, NULL);
offset_body = offset;
conn_desc_type = tvb_get_guint8(tvb, offset);
proto_tree_add_item(conn_desc_tree, hf_dvbci_conn_desc_type,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
if (conn_desc_type == CONN_DESC_IP) {
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_media_tag,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_media_len,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
ip_ver = tvb_get_guint8(tvb, offset);
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_ip_ver,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
if (ip_ver == LSC_IPV4) {
offset += FT_IPv6_LEN-FT_IPv4_LEN;
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_ipv4_addr,
tvb, offset, FT_IPv4_LEN, ENC_BIG_ENDIAN);
offset += FT_IPv4_LEN;
}
else if (ip_ver == LSC_IPV6) {
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_ipv6_addr,
tvb, offset, FT_IPv6_LEN, ENC_NA);
offset += FT_IPv6_LEN;
}
else
offset += FT_IPv6_LEN;
port = tvb_get_ntohs(tvb, offset);
port_item = proto_tree_add_item(conn_desc_tree,
hf_dvbci_lsc_dst_port, tvb, offset, 2, ENC_BIG_ENDIAN);
offset +=2;
ip_proto = tvb_get_guint8(tvb, offset);
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_proto,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset ++;
if (port_item) {
if (ip_proto==LSC_TCP && ep_tcp_port_to_display(port)) {
proto_item_append_text(port_item, " (%s)",
ep_tcp_port_to_display(port));
}
else if (ip_proto==LSC_UDP && ep_udp_port_to_display(port)) {
proto_item_append_text(port_item, " (%s)",
ep_udp_port_to_display(port));
}
}
store_lsc_msg_dissector(circuit, ip_proto, port);
} else if (conn_desc_type == CONN_DESC_HOSTNAME) {
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_media_tag,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_media_len,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
ip_proto = tvb_get_guint8(tvb, offset);
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_proto,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset ++;
port = tvb_get_ntohs(tvb, offset);
port_item = proto_tree_add_item(conn_desc_tree,
hf_dvbci_lsc_dst_port, tvb, offset, 2, ENC_BIG_ENDIAN);
offset +=2;
if (port_item) {
if (ip_proto==LSC_TCP && ep_tcp_port_to_display(port)) {
proto_item_append_text(port_item, " (%s)",
ep_tcp_port_to_display(port));
}
else if (ip_proto==LSC_UDP && ep_udp_port_to_display(port)) {
proto_item_append_text(port_item, " (%s)",
ep_udp_port_to_display(port));
}
}
store_lsc_msg_dissector(circuit, ip_proto, port);
/* everything from here to the descriptor's end is a hostname */
hostname_len = (offset_body+len_field)-offset;
proto_tree_add_item(conn_desc_tree, hf_dvbci_lsc_hostname,
tvb, offset, hostname_len, ENC_ASCII|ENC_NA);
offset += hostname_len;
} else {
proto_tree_add_text(conn_desc_tree, tvb,
offset, len_field-1, "media specific data");
offset += len_field-1;
}
proto_item_set_len(ti, offset-offset_start);
return offset-offset_start;
}
/* check if the given CC resource item may appear in the clear
as part of an exported PDU */
static inline gboolean
is_cc_item_exportable(guint8 dat_id)
{
/* the CCK precursor value does not contain sensitive information as such
nevertheless, it is safer to prevent people from exporting this value
accidentially */
if (dat_id == CC_ID_KP)
return FALSE;
/* we could add some more items here which do not appear in SAC messages
normally: CC_ID_DHPH, CC_ID_DHPM */
return TRUE;
}
/* dissect the URI, return the number of bytes processed or -1 for error */
static gint
dissect_uri(tvbuff_t *tvb, gint offset, packet_info *pinfo, proto_tree *tree)
{
gint offset_start;
guint8 uri_ver, emi, rl;
proto_item *rl_item;
offset_start = offset;
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "URI");
uri_ver = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_uri_ver,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_uri_aps,
tvb, offset, 1, ENC_BIG_ENDIAN);
emi = (tvb_get_guint8(tvb, offset) & 0x30) >> 4;
proto_tree_add_item(tree, hf_dvbci_uri_emi,
tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "%s",
val_to_str_const(emi, dvbci_cc_uri_emi, "unknown"));
proto_tree_add_item(tree, hf_dvbci_uri_ict,
tvb, offset, 1, ENC_BIG_ENDIAN);
if (emi==CC_EMI_FREE) {
proto_tree_add_item(tree, hf_dvbci_uri_rct,
tvb, offset, 1, ENC_BIG_ENDIAN);
}
if (uri_ver>=2 && emi==CC_EMI_NEVER) {
proto_tree_add_item(tree, hf_dvbci_uri_dot,
tvb, offset, 1, ENC_BIG_ENDIAN);
}
offset++;
if (emi==CC_EMI_NEVER) {
if (uri_ver==1)
rl = tvb_get_guint8(tvb, offset) & 0x3F;
else
rl = tvb_get_guint8(tvb, offset);
rl_item = proto_tree_add_uint(tree, hf_dvbci_uri_rl,
tvb, offset, 1, rl);
if (rl==0x00)
proto_item_append_text(rl_item, " (90 minutes)");
else if (rl==0x01)
proto_item_append_text(rl_item, " (6 hours)");
else if (rl==0x02)
proto_item_append_text(rl_item, " (12 hours)");
else if (uri_ver>=2 && rl==0xFF)
proto_item_append_text(rl_item, " (unlimited)");
else {
/* no need for a range check, rl 0x3F mask was applied above */
proto_item_append_text(rl_item, " (%d days)", rl-2);
}
}
return offset-offset_start;
}
/* dissect an item from cc_(sac_)data_req/cc_(sac_)data_cnf,
returns its length or -1 for error
if dat_id_ptr is not NULL, fill in the datatype id */
static gint
dissect_cc_item(tvbuff_t *tvb, gint offset,
packet_info *pinfo, proto_tree *tree, guint8 *dat_id_ptr)
{
proto_item *ti;
proto_tree *cc_item_tree = NULL;
gint offset_start;
guint16 dat_len;
guint8 dat_id;
asn1_ctx_t asn1_ctx;
int hf_cert_index;
guint16 prog_num;
guint8 status;
offset_start = offset;
dat_id = tvb_get_guint8(tvb, offset);
if (dat_id_ptr)
*dat_id_ptr = dat_id;
cc_item_tree = proto_tree_add_subtree_format(tree, tvb, offset_start, -1, ett_dvbci_cc_item, &ti,
"CC data item: %s", val_to_str_const(dat_id, dvbci_cc_dat_id, "unknown"));
proto_tree_add_item(cc_item_tree, hf_dvbci_cc_dat_id,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
dat_len = tvb_get_ntohs(tvb, offset);
proto_tree_add_text(cc_item_tree, tvb, offset, 2, "Length: %d", dat_len);
offset += 2;
switch (dat_id) {
case CC_ID_HOST_BRAND_CERT:
case CC_ID_CICAM_BRAND_CERT:
case CC_ID_HOST_DEV_CERT:
case CC_ID_CICAM_DEV_CERT:
asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);
hf_cert_index = (dat_id==CC_ID_HOST_BRAND_CERT ||
dat_id==CC_ID_CICAM_BRAND_CERT) ?
hf_dvbci_brand_cert : hf_dvbci_dev_cert;
/* enable dissection of CI+ specific X.509 extensions
only for our certificates */
x509ce_enable_ciplus();
dissect_x509af_Certificate(FALSE, tvb, offset,
&asn1_ctx, cc_item_tree, hf_cert_index);
x509ce_disable_ciplus();
break;
case CC_ID_URI:
dissect_uri(tvb, offset, pinfo, cc_item_tree);
break;
case CC_ID_PROG_NUM:
prog_num = tvb_get_ntohs(tvb, offset);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
"Program number 0x%x", prog_num);
proto_tree_add_item(cc_item_tree, hf_dvbci_cc_prog_num,
tvb, offset, 2, ENC_BIG_ENDIAN);
break;
case CC_ID_KEY_REGISTER:
proto_tree_add_item(cc_item_tree, hf_dvbci_cc_key_register,
tvb, offset, 1, ENC_BIG_ENDIAN);
break;
case CC_ID_STATUS_FIELD:
case CC_ID_REC_START_STATUS:
case CC_ID_MODE_CHG_STATUS:
case CC_ID_REC_STOP_STATUS:
status = tvb_get_guint8(tvb, offset);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "Status: %s",
val_to_str_const(status, dvbci_cc_status, "unknown"));
proto_tree_add_item(cc_item_tree, hf_dvbci_cc_status_field,
tvb, offset, 1, ENC_BIG_ENDIAN);
break;
case CC_ID_OPERATING_MODE:
proto_tree_add_item(cc_item_tree, hf_dvbci_cc_op_mode,
tvb, offset, 1, ENC_BIG_ENDIAN);
break;
default:
proto_tree_add_item(cc_item_tree, hf_dvbci_cc_data,
tvb, offset, dat_len, ENC_NA);
break;
}
offset += dat_len;
proto_item_set_len(ti, offset-offset_start);
return offset-offset_start;
}
/* add the CC protocol name and step to the info column */
static void
add_cc_protocol_name_step(packet_info *pinfo,
guint64 snd_dat_ids, guint64 req_dat_ids)
{
gboolean chk_snd_ids = FALSE;
switch (req_dat_ids) {
case CC_ID_DHPH<<24|CC_ID_SIG_A<<16|CC_ID_HOST_DEV_CERT<<8|CC_ID_HOST_BRAND_CERT:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Authentication Step 1)");
break;
case CC_ID_STATUS_FIELD:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Authentication Step 3)");
break;
case CC_ID_AKH:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(AuthKey Step 1)");
break;
case CC_ID_HOST_ID<<8|CC_ID_STATUS_FIELD:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(CC key calculation Step 1)");
break;
case CC_ID_HOST_ID<<8|CC_ID_NS_HOST:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(SAC key calculation Step 1)");
break;
case CC_ID_URI_CNF:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(URI transmission Step 1)");
break;
case CC_ID_URI_VERSIONS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(URI version negotiation Step 1)");
break;
case CC_ID_LICENSE_RCV_STATUS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(CICAM to Host License Exchange Step 1)");
break;
case CC_ID_PROG_NUM<<24|CC_ID_LICENSE_STATUS<<16|CC_ID_URI<<8|CC_ID_CICAM_LICENSE:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Playback License Exchange Step 1)");
break;
case CC_ID_LICENSE_STATUS<<8|CC_ID_PLAY_COUNT:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(License Check Exchange Step 1)");
break;
case CC_ID_REC_START_STATUS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Record Start Step 1)");
break;
case CC_ID_MODE_CHG_STATUS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Change Operating Mode Step 1)");
break;
case CC_ID_REC_STOP_STATUS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Record Stop Step 1)");
break;
case CC_ID_STATUS_FIELD<<8|CC_ID_SRM_CONFIRM:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(SRM Transmission Step 1)");
break;
default:
/* unable to determine the protocol from the requested ids
check the sent ids as well */
chk_snd_ids = TRUE;
break;
}
if (!chk_snd_ids)
return;
switch (snd_dat_ids) {
case CC_ID_DHPH<<24|CC_ID_SIG_A<<16|CC_ID_HOST_DEV_CERT<<8|CC_ID_HOST_BRAND_CERT:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Authentication Step 2)");
break;
case CC_ID_STATUS_FIELD:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Authentication Step 4)");
break;
case CC_ID_AKH:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(AuthKey Step 2)");
break;
case CC_ID_HOST_ID<<8|CC_ID_STATUS_FIELD:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(CC key calculation Step 2)");
break;
case CC_ID_HOST_ID<<8|CC_ID_NS_HOST:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(SAC key calculation Step 2)");
break;
case CC_ID_URI_CNF:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(URI transmission Step 2)");
break;
case CC_ID_URI_VERSIONS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(URI version negotiation Step 2)");
break;
case CC_ID_LICENSE_RCV_STATUS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(CICAM to Host License Exchange Step 2)");
break;
case CC_ID_PROG_NUM<<24|CC_ID_LICENSE_STATUS<<16|CC_ID_URI<<8|CC_ID_CICAM_LICENSE:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Playback License Exchange Step 2)");
break;
case CC_ID_LICENSE_STATUS<<8|CC_ID_PLAY_COUNT:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(License Check Exchange Step 2)");
break;
case CC_ID_REC_START_STATUS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Record Start Step 2)");
break;
case CC_ID_MODE_CHG_STATUS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Change Operating Mode Step 2)");
break;
case CC_ID_REC_STOP_STATUS:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(Record Stop Step 2)");
break;
case CC_ID_STATUS_FIELD<<8|CC_ID_SRM_CONFIRM:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"(SRM Transmission Step 2)");
break;
}
}
/* dissect the payload of a cc message that contains data items
if not NULL, set exportable_flag to TRUE if the message contains no
sensitive data and can be passed to the export PDU mechanism */
static gint
dissect_cc_data_payload(guint32 tag, tvbuff_t *tvb, gint offset,
packet_info *pinfo, proto_tree *tree, gboolean *exportable_flag)
{
gint offset_start;
guint8 i, snd_dat_nbr, req_dat_nbr;
guint8 dat_id;
gint item_len;
/* the last 8 sent/requested datatype ids */
guint64 snd_dat_ids=0, req_dat_ids=0;
/* we only export cc_sac_data_req and cc_sac_data_cnf
the only meta info in the exported PDU is the data transfer
direction, if we only ever export cc_sac_data_req and
cc_sac_data_cnf, this info is enough to recover the apdu tag from the
direction
cc_sac_sync req and cc_sac_sync_cnf contain no interesting data */
if (exportable_flag)
*exportable_flag = (tag==T_CC_SAC_DATA_REQ || tag==T_CC_SAC_DATA_CNF);
offset_start = offset;
proto_tree_add_item(
tree, hf_dvbci_cc_sys_id_bitmask, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
snd_dat_nbr = tvb_get_guint8(tvb, offset);
proto_tree_add_text(tree, tvb, offset, 1,
"Number of sent data items: %d", snd_dat_nbr);
offset++;
for(i=0; i<snd_dat_nbr &&
tvb_reported_length_remaining(tvb, offset)>0; i++) {
item_len = dissect_cc_item(tvb, offset, pinfo, tree, &dat_id);
if (item_len < 0)
return -1;
offset += item_len;
/* for more than 8 sent datatype ids, some ids might get lost by
* the shift, that's ok, we're only using the last 8 ids for
* protocol detection */
snd_dat_ids = snd_dat_ids<<8|dat_id;
if (!exportable_flag || *exportable_flag==FALSE)
continue;
if (!is_cc_item_exportable(dat_id))
*exportable_flag = FALSE;
}
if (tag==T_CC_DATA_REQ || tag==T_CC_SAC_DATA_REQ) {
req_dat_nbr = tvb_get_guint8(tvb, offset);
proto_tree_add_text(tree, tvb, offset, 1,
"Number of requested data items: %d", req_dat_nbr);
offset++;
for(i=0; i<req_dat_nbr &&
tvb_reported_length_remaining(tvb, offset)>0; i++) {
dat_id = tvb_get_guint8(tvb, offset);
req_dat_ids = req_dat_ids<<8|dat_id;
proto_tree_add_item(
tree, hf_dvbci_cc_dat_id, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
}
}
add_cc_protocol_name_step(pinfo, snd_dat_ids, req_dat_ids);
return offset-offset_start;
}
#ifdef HAVE_LIBGCRYPT
/* convert a 0-terminated preference key_string that contains a hex number
* into its binary representation
* e.g. key_string "abcd" will be converted into two bytes 0xab, 0xcd
* return the number of binary bytes or -1 for error */
static gint
pref_key_string_to_bin(const gchar *key_string, unsigned char **key_bin)
{
int key_string_len;
int i, j;
char input[3];
if (!key_string || !key_bin)
return -1;
key_string_len = (int)strlen(key_string);
if (key_string_len != 2*AES_KEY_LEN)
return -1;
*key_bin = (unsigned char*)g_malloc(key_string_len/2);
input[2] = '\0';
j=0;
for (i=0; i<key_string_len-1; i+=2) {
input[0] = key_string[0+i];
input[1] = key_string[1+i];
/* attention, brackets are required */
(*key_bin)[j++] = (unsigned char)strtoul((const char*)&input, NULL, 16);
}
return key_string_len/2;
}
static tvbuff_t *
decrypt_sac_msg_body(
guint8 enc_cip, tvbuff_t *encrypted_tvb, gint offset, gint len)
{
gboolean opened = FALSE;
gcry_cipher_hd_t cipher;
gcry_error_t err;
gint clear_len;
unsigned char *clear_data = NULL;
tvbuff_t *clear_tvb = NULL;
if (enc_cip != CC_SAC_ENC_AES128_CBC)
goto end;
if (len%AES_BLOCK_LEN != 0)
goto end;
if (!dvbci_sek_bin || !dvbci_siv_bin)
goto end;
err = gcry_cipher_open(&cipher, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
if (gcry_err_code (err))
goto end;
opened = TRUE;
err = gcry_cipher_setkey (cipher, dvbci_sek_bin, AES_KEY_LEN);
if (gcry_err_code (err))
goto end;
err = gcry_cipher_setiv (cipher, dvbci_siv_bin, AES_BLOCK_LEN);
if (gcry_err_code (err))
goto end;
clear_len = len;
clear_data = (unsigned char *)g_malloc(clear_len);
err = gcry_cipher_decrypt (cipher, clear_data, clear_len,
tvb_memdup(wmem_packet_scope(), encrypted_tvb, offset, len), len);
if (gcry_err_code (err))
goto end;
clear_tvb = tvb_new_child_real_data(encrypted_tvb,
(const guint8 *)clear_data, clear_len, clear_len);
tvb_set_free_cb(clear_tvb, g_free);
end:
if (opened)
gcry_cipher_close (cipher);
if (!clear_tvb && clear_data)
g_free(clear_data);
return clear_tvb;
}
#else
/* HAVE_LIBGRYPT is not set */
static gint
pref_key_string_to_bin(const gchar *key_string _U_, unsigned char **key_bin _U_)
{
return 0;
}
static tvbuff_t *
decrypt_sac_msg_body(guint8 enc_cip _U_,
tvbuff_t *encrypted_tvb _U_, gint offset _U_, gint len _U_)
{
return NULL;
}
#endif
/* dissect a text string that is encoded according to DVB-SI (EN 300 468) */
static void
dissect_si_string(tvbuff_t *tvb, gint offset, gint str_len,
packet_info *pinfo, proto_tree *tree, int hf, const gchar *title,
gboolean show_col_info)
{
guint enc_len;
dvb_encoding_e encoding;
guint8 *si_str = NULL;
if (!title) /* we always have a title for our strings */
return;
/* str_len==-1 is not supported, we need an actual length */
if (str_len<=0)
return;
enc_len = dvb_analyze_string_charset(tvb, offset, str_len, &encoding);
dvb_add_chartbl(tree, hf_dvbci_mmi_char_tbl, tvb, offset, enc_len, encoding);
offset += enc_len;
str_len -= enc_len;
si_str = tvb_get_string_enc(wmem_packet_scope(),
tvb, offset, str_len, dvb_enc_to_item_enc(encoding));
if (!si_str)
return;
proto_tree_add_string_format(tree, hf,
tvb, offset, str_len, si_str, "%s: %s", title, si_str);
if (show_col_info)
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ", "%s", si_str);
}
/* dissect ca_enable_flag and ca_enable fields in the ca_pmt_reply
* return true if descrambling is possible, false otherwise */
static gboolean
dissect_ca_enable(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_,
proto_tree *tree)
{
gboolean desc_ok = FALSE;
guint8 byte, ca_enab;
byte = tvb_get_guint8(tvb,offset);
proto_tree_add_item(tree, hf_dvbci_ca_enable_flag, tvb, offset, 1, ENC_BIG_ENDIAN);
if (byte&0x80) {
ca_enab = byte & ~0x80;
proto_tree_add_item(tree, hf_dvbci_ca_enable, tvb, offset, 1, ENC_BIG_ENDIAN);
if (ca_enab==CA_ENAB_DESC_OK ||
ca_enab==CA_ENAB_DESC_OK_PURCHASE ||
ca_enab==CA_ENAB_DESC_OK_TECH) {
desc_ok = TRUE;
}
}
return desc_ok;
}
/* dissect a ca descriptor in the ca_pmt */
static gint
dissect_ca_desc(tvbuff_t *tvb, gint offset, packet_info *pinfo,
proto_tree *tree)
{
gint offset_start;
guint8 tag, len_byte;
proto_item *ti;
proto_tree *ca_desc_tree = NULL;
offset_start = offset;
tag = tvb_get_guint8(tvb,offset);
if (tag != CA_DESC_TAG) {
/* we could skip unknown descriptors and make this a warning */
proto_tree_add_expert(tree, pinfo, &ei_dvbci_ca_pmt_cmd_id, tvb, offset, 1);
return 0;
}
ca_desc_tree = proto_tree_add_subtree(
tree, tvb, offset_start, -1, ett_dvbci_ca_desc, &ti, "Conditional Access descriptor");
offset++;
len_byte = tvb_get_guint8(tvb,offset);
proto_tree_add_item(
ca_desc_tree, hf_dvbci_descr_len, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(
ca_desc_tree, hf_dvbci_ca_sys_id, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item(
ca_desc_tree, hf_dvbci_ca_pid, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
if ((len_byte-4) != 0) {
proto_tree_add_text(
ca_desc_tree, tvb, offset, len_byte-4, "private data");
offset += (len_byte-4);
}
proto_item_set_len(ti, offset-offset_start);
return offset-offset_start;
}
/* dissect an elementary stream entry in the ca_pmt */
static gint
dissect_es(tvbuff_t *tvb, gint offset,
packet_info *pinfo, proto_tree *tree, gboolean *scrambled)
{
proto_item *ti;
proto_tree *es_tree = NULL;
gint offset_start, ca_desc_len;
gint es_info_len, all_len;
offset_start = offset;
if (scrambled) {
/* default to free service until we found a ca descriptor
(we could have es info len > 0 and no ca descriptors) */
*scrambled = FALSE;
}
es_tree = proto_tree_add_subtree(tree, tvb, offset_start, -1, ett_dvbci_application, &ti, "Elementary Stream");
proto_tree_add_item(
es_tree, hf_dvbci_stream_type, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(
es_tree, hf_dvbci_es_pid, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
es_info_len = tvb_get_ntohs(tvb, offset) & 0x0FFF;
/* the definition of hf_dvbci_es_info_len also applies the mask */
proto_tree_add_item(
es_tree, hf_dvbci_es_info_len, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
if (es_info_len>0) {
all_len = offset + es_info_len;
proto_tree_add_item(
es_tree, hf_dvbci_ca_pmt_cmd_id, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
while (offset < all_len) {
ca_desc_len = dissect_ca_desc(tvb, offset, pinfo, es_tree);
if (ca_desc_len <= 0)
return -1;
offset += ca_desc_len;
if (scrambled)
*scrambled = TRUE;
}
}
else {
proto_tree_add_text(
es_tree, tvb, 0, 0,
"No CA descriptors for this elementary stream");
}
proto_item_set_len(ti, offset-offset_start);
return offset-offset_start;
}
/* dissect a text pseudo-apdu */
static gint
dissect_dvbci_text(const gchar *title, tvbuff_t *tvb, gint offset,
packet_info *pinfo, proto_tree *tree, int hf)
{
proto_item *ti;
proto_tree *text_tree;
guint32 tag;
gint offset_start;
gint len_field;
offset_start = offset;
if (!title)
return 0;
/* check the tag before setting up the tree */
tag = tvb_get_ntoh24(tvb, offset);
if (tag!=T_TEXT_LAST && tag!=T_TEXT_MORE)
return 0;
text_tree = proto_tree_add_subtree(tree, tvb, offset_start, -1, ett_dvbci_text, &ti, title);
proto_tree_add_item(text_tree, hf_dvbci_apdu_tag,
tvb, offset, APDU_TAG_SIZE, ENC_BIG_ENDIAN);
offset += APDU_TAG_SIZE;
offset = dissect_ber_length(pinfo, text_tree, tvb, offset, &len_field, NULL);
dissect_si_string(tvb, offset, len_field, pinfo, text_tree,
hf, "Text", FALSE);
offset += len_field;
proto_item_set_len(ti, offset-offset_start);
return (offset-offset_start);
}
static proto_item *
dissect_res_id(tvbuff_t *tvb, gint offset, packet_info *pinfo,
proto_tree *tree, guint32 res_id, gboolean show_col_info)
{
proto_item *ti = NULL;
proto_tree *res_tree = NULL;
gint tvb_data_len;
/* there's two possible inputs for this function
the resource id is either in a tvbuff_t (tvb!=NULL, res_id==0)
or in a guint32 (tvb==NULL, res_id!=0) */
if (tvb) {
/* resource id comes in via tvbuff */
if (res_id!=0)
return NULL;
res_id = tvb_get_ntohl(tvb, offset);
tvb_data_len = RES_ID_LEN;
}
else {
/* resource id comes in via guint32 */
if (res_id==0)
return NULL;
/* we'll call proto_tree_add_...( tvb==NULL, offset==0, length==0 )
this creates a filterable item without any reference to a tvb */
offset = 0;
tvb_data_len = 0;
}
if (show_col_info) {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "%s Version %d",
val_to_str_const(RES_CLASS(res_id), dvbci_res_class,
"Invalid Resource class"),
RES_VER(res_id));
}
res_tree = proto_tree_add_subtree_format(tree, tvb, offset, tvb_data_len,
ett_dvbci_res, &ti, "Resource ID: 0x%04x", res_id);
/* parameter "value" == complete resource id,
RES_..._MASK will be applied by the hf definition */
proto_tree_add_uint(res_tree, hf_dvbci_res_id_type,
tvb, offset, tvb_data_len, res_id);
proto_tree_add_uint(res_tree, hf_dvbci_res_class,
tvb, offset, tvb_data_len, res_id);
proto_tree_add_uint(res_tree, hf_dvbci_res_type,
tvb, offset, tvb_data_len, res_id);
proto_tree_add_uint(res_tree, hf_dvbci_res_ver,
tvb, offset, tvb_data_len, res_id);
return ti;
}
/* dissect the body of a resource manager apdu */
static void
dissect_dvbci_payload_rm(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
const gchar *tag_str;
if (tag==T_PROFILE) {
if (len_field % RES_ID_LEN) {
tag_str = val_to_str(tag, dvbci_apdu_tag, "Unknown: %d");
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb, 0, APDU_TAG_SIZE,
"Invalid APDU length field, %s must be a multiple of 4 bytes",
tag_str);
return;
}
while (tvb_reported_length_remaining(tvb, offset) > 0) {
dissect_res_id(tvb, offset, pinfo, tree, 0, FALSE);
offset += RES_ID_LEN;
}
}
}
static void
dissect_dvbci_payload_ap(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
guint8 menu_str_len;
guint enc_len;
dvb_encoding_e encoding;
guint8 *menu_string;
guint8 data_rate;
if (tag==T_APP_INFO) {
proto_tree_add_item(tree, hf_dvbci_app_type, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(
tree, hf_dvbci_app_manf, tvb, offset, 2, ENC_BIG_ENDIAN);
offset+=2;
proto_tree_add_item(
tree, hf_dvbci_manf_code, tvb, offset, 2, ENC_BIG_ENDIAN);
offset+=2;
menu_str_len = tvb_get_guint8(tvb,offset);
proto_tree_add_item(
tree, hf_dvbci_menu_str_len, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
if (menu_str_len > 0) {
enc_len = dvb_analyze_string_charset(
tvb, offset, menu_str_len, &encoding);
dvb_add_chartbl(
tree, hf_dvbci_ap_char_tbl, tvb, offset, enc_len, encoding);
offset += enc_len;
menu_str_len -= enc_len;
menu_string = tvb_get_string_enc(wmem_packet_scope(),
tvb, offset, menu_str_len, dvb_enc_to_item_enc(encoding));
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
"Module name %s", menu_string);
proto_tree_add_string_format(tree, hf_dvbci_menu_str,
tvb, offset, menu_str_len, menu_string,
"Menu string: %s", menu_string);
}
}
else if (tag== T_DATARATE_INFO) {
data_rate = tvb_get_guint8(tvb, offset);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s",
val_to_str(data_rate, dvbci_data_rate, "unknown (0x%x)"));
proto_tree_add_item(tree, hf_dvbci_data_rate, tvb, offset, 1, ENC_BIG_ENDIAN);
}
}
static void
dissect_dvbci_payload_ca(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
const gchar *tag_str;
guint16 prog_num;
guint8 byte;
guint prog_info_len;
gint es_info_len, all_len;
gint ca_desc_len;
gboolean scrambled = FALSE;
gboolean es_scrambled = FALSE;
proto_tree *es_tree = NULL;
gboolean desc_ok = FALSE;
if (tag==T_CA_INFO) {
if (len_field % 2) {
tag_str = val_to_str(tag, dvbci_apdu_tag, "Unknown: %d");
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb, 0, APDU_TAG_SIZE,
"Invalid APDU length field, %s must be a multiple of 2 bytes",
tag_str);
return;
}
while (tvb_reported_length_remaining(tvb, offset) > 0) {
proto_tree_add_item(
tree, hf_dvbci_ca_sys_id, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
}
}
else if (tag==T_CA_PMT) {
proto_tree_add_item(
tree, hf_dvbci_ca_pmt_list_mgmt, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
prog_num = tvb_get_ntohs(tvb, offset);
col_append_sep_fstr(
pinfo->cinfo, COL_INFO, NULL, "Program number %x", prog_num);
proto_tree_add_item(
tree, hf_dvbci_prog_num, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
byte = tvb_get_guint8(tvb,offset);
proto_tree_add_text(tree, tvb, offset, 1,
"Version number: 0x%x, Current-next indicator: 0x%x",
(byte&0x3E) >> 1, byte&0x01);
offset++;
prog_info_len = tvb_get_ntohs(tvb, offset) & 0x0FFF;
/* the definition of hf_dvbci_prog_info_len also applies the mask */
proto_tree_add_item(
tree, hf_dvbci_prog_info_len, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
if (prog_info_len != 0) {
all_len = offset + prog_info_len;
proto_tree_add_item(
tree, hf_dvbci_ca_pmt_cmd_id, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
while (offset < all_len) {
ca_desc_len = dissect_ca_desc(tvb, offset, pinfo, tree);
if (ca_desc_len <= 0)
return;
offset += ca_desc_len;
/* set this only if we've seen at least one valid ca descriptor */
scrambled = TRUE;
}
}
else {
proto_tree_add_text(
tree, tvb, 0, 0, "No CA descriptors at program level");
}
while (tvb_reported_length_remaining(tvb, offset) > 0) {
es_info_len = dissect_es(tvb, offset, pinfo, tree, &es_scrambled);
if (es_info_len <= 0)
return;
offset += es_info_len;
if (es_scrambled)
scrambled = TRUE;
}
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
scrambled ? "scrambled service" : "free service");
}
else if (tag==T_CA_PMT_REPLY) {
prog_num = tvb_get_ntohs(tvb, offset);
col_append_sep_fstr(
pinfo->cinfo, COL_INFO, NULL, "Program number %x", prog_num);
proto_tree_add_item(
tree, hf_dvbci_prog_num, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
byte = tvb_get_guint8(tvb,offset);
proto_tree_add_text(tree, tvb, offset, 1,
"Version number: 0x%x, Current-next indicator: 0x%x",
(byte&0x3E) >> 1, byte&0x01);
offset++;
desc_ok |= dissect_ca_enable(tvb, offset, pinfo, tree);
offset++;
while (tvb_reported_length_remaining(tvb, offset) > 0) {
/* there's no need to check for tree==NULL */
es_tree = proto_tree_add_subtree(tree, tvb, offset, 3, ett_dvbci_application, NULL, "Elementary Stream");
proto_tree_add_item(es_tree, hf_dvbci_es_pid,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
desc_ok |= dissect_ca_enable(tvb, offset, pinfo, es_tree);
offset++;
}
if (desc_ok) {
col_append_sep_fstr(
pinfo->cinfo, COL_INFO, NULL, "descrambling possible");
}
}
}
static void
dissect_dvbci_payload_aut(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo _U_, proto_tree *tree)
{
gint bytes_len;
proto_tree_add_item(tree, hf_dvbci_auth_proto_id,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
bytes_len = tvb_reported_length_remaining(tvb, offset);
if (bytes_len <= 0)
return;
if (tag==T_AUTH_REQ) {
proto_tree_add_item(tree, hf_dvbci_auth_req_bytes,
tvb, offset, bytes_len, ENC_NA);
}
else if (tag==T_AUTH_RESP) {
proto_tree_add_item(tree, hf_dvbci_auth_resp_bytes,
tvb, offset, bytes_len, ENC_NA);
}
}
static void
dissect_dvbci_payload_hc(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
proto_item *pi;
guint16 nid, onid, tsid, svcid;
guint8 ref;
guint16 old_pid, new_pid;
gboolean pmt_flag;
gint desc_loop_len;
tvbuff_t *pmt_tvb = NULL;
guint8 status;
switch (tag) {
case T_TUNE:
nid = tvb_get_ntohs(tvb, offset);
pi = proto_tree_add_item(
tree, hf_dvbci_network_id, tvb, offset, 2, ENC_BIG_ENDIAN);
if (nid) {
expert_add_info(pinfo, pi, &ei_dvbci_network_id);
}
offset += 2;
onid = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_original_network_id,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
tsid = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_transport_stream_id,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
svcid = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(
tree, hf_dvbci_service_id, tvb, offset, 2, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"nid 0x%x, onid 0x%x, tsid 0x%x, svcid 0x%x",
nid, onid, tsid, svcid);
break;
case T_REPLACE:
ref = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_replacement_ref,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
old_pid = tvb_get_ntohs(tvb, offset) & 0x1FFF;
proto_tree_add_item(tree, hf_dvbci_replaced_pid,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
new_pid = tvb_get_ntohs(tvb, offset) & 0x1FFF;
proto_tree_add_item( tree, hf_dvbci_replacement_pid,
tvb, offset, 2, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"ref 0x%x, 0x%x -> 0x%x", ref, old_pid, new_pid);
break;
case T_CLEAR_REPLACE:
ref = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_replacement_ref,
tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "ref 0x%x", ref);
break;
case T_TUNE_BROADCAST_REQ:
pmt_flag = ((tvb_get_guint8(tvb, offset) & 0x01) == 0x01);
proto_tree_add_item(tree, hf_dvbci_pmt_flag,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(
tree, hf_dvbci_service_id, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
desc_loop_len = dissect_desc_loop(hf_dvbci_hc_desc_loop_len,
tvb, offset, pinfo, tree);
if (desc_loop_len<0)
break;
offset += desc_loop_len;
if (pmt_flag) {
pmt_tvb = tvb_new_subset_remaining(tvb, offset);
if (mpeg_pmt_handle) {
col_append_str(pinfo->cinfo, COL_INFO, ", ");
/* prevent mpeg_pmt dissector from clearing col_info */
col_set_fence(pinfo->cinfo, COL_INFO);
call_dissector(mpeg_pmt_handle, pmt_tvb, pinfo, tree);
}
else
call_dissector(data_handle, pmt_tvb, pinfo, tree);
}
break;
case T_TUNE_REPLY:
status = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_hc_status,
tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
(status == HC_STAT_OK ? "ok" : "error"));
break;
case T_ASK_RELEASE_REPLY:
proto_tree_add_item(tree, hf_dvbci_hc_release_reply,
tvb, offset, 1, ENC_BIG_ENDIAN);
break;
default:
break;
}
}
static void
dissect_dvbci_payload_dt(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
nstime_t resp_intv;
proto_item *pi = NULL;
const gchar *tag_str;
gint time_field_len;
nstime_t utc_time;
gint16 local_offset; /* field in the apdu */
if (tag==T_DATE_TIME_ENQ) {
nstime_set_zero(&resp_intv);
resp_intv.secs = tvb_get_guint8(tvb, offset);
pi = proto_tree_add_time(tree, hf_dvbci_resp_intv,
tvb, offset, 1, &resp_intv);
if (resp_intv.secs==0) {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "individual query");
if (pi)
proto_item_append_text(pi, " (individual query)");
}
else {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
"update every %s", rel_time_to_str(wmem_packet_scope(), &resp_intv));
}
}
else if (tag==T_DATE_TIME) {
if (len_field!=5 && len_field!=7) {
tag_str = val_to_str_const(tag, dvbci_apdu_tag, "unknown");
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb, APDU_TAG_SIZE, offset-APDU_TAG_SIZE,
"Invalid APDU length field, %s must be 5 or 7 bytes", tag_str);
return;
}
time_field_len = packet_mpeg_sect_mjd_to_utc_time(tvb, offset, &utc_time);
if (time_field_len<0) {
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb, offset, 5,
"Invalid UTC time field, 2 bytes MJD, 3 bytes BCD time hhmmss");
return;
}
proto_tree_add_time(tree, hf_dvbci_utc_time,
tvb, offset, time_field_len, &utc_time);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s UTC",
abs_time_to_str(wmem_packet_scope(), &utc_time, ABSOLUTE_TIME_UTC, FALSE));
offset += time_field_len;
if (len_field==7) {
local_offset = two_comp_to_int16(tvb_get_ntohs(tvb, offset));
proto_tree_add_int_format(tree, hf_dvbci_local_offset,
tvb, offset, 2, local_offset,
"offset between UTC and local time is %d minutes",
local_offset);
}
else {
proto_tree_add_text(tree, tvb, 0, 0,
"Offset between UTC and local time is unknown");
}
}
}
static void
dissect_dvbci_payload_mmi(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
gint offset_start;
guint8 close_mmi_cmd_id;
guint8 disp_ctl_cmd, disp_rep_id;
const gchar *disp_ctl_cmd_str = NULL, *disp_rep_id_str = NULL;
gint msg_len;
guint enc_len;
dvb_encoding_e encoding;
guint8 ans_txt_len;
guint8 ans_id;
guint8 choice_or_item_nb;
gint text_len;
guint8 choice_ref;
offset_start = offset;
switch(tag) {
case T_CLOSE_MMI:
close_mmi_cmd_id = tvb_get_guint8(tvb,offset);
proto_tree_add_item(tree, hf_dvbci_close_mmi_cmd_id,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
/* apdu layer len field checks are sufficient for "immediate" */
if (close_mmi_cmd_id == CLOSE_MMI_CMD_ID_DELAY) {
if (len_field != 2) {
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb,
APDU_TAG_SIZE, offset_start-APDU_TAG_SIZE,
"Length field must be 2");
return;
}
proto_tree_add_item(tree, hf_dvbci_close_mmi_delay, tvb,
offset, 1, ENC_BIG_ENDIAN);
}
break;
case T_DISPLAY_CONTROL:
disp_ctl_cmd = tvb_get_guint8(tvb,offset);
disp_ctl_cmd_str = val_to_str_const(disp_ctl_cmd,
dvbci_disp_ctl_cmd, "unknown command");
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"%s", disp_ctl_cmd_str);
proto_tree_add_item(tree, hf_dvbci_disp_ctl_cmd, tvb,
offset, 1, ENC_BIG_ENDIAN);
offset++;
if (disp_ctl_cmd == DISP_CMD_SET_MMI_MODE)
{
proto_tree_add_item(tree, hf_dvbci_mmi_mode, tvb,
offset, 1, ENC_BIG_ENDIAN);
if (len_field != 2) {
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb,
APDU_TAG_SIZE, offset_start-APDU_TAG_SIZE,
"Length field must be 2");
return;
}
}
break;
case T_DISPLAY_REPLY:
disp_rep_id = tvb_get_guint8(tvb,offset);
disp_rep_id_str = val_to_str_const(disp_rep_id,
dvbci_disp_rep_id, "unknown command");
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"%s", disp_rep_id_str);
proto_tree_add_item(tree, hf_dvbci_disp_rep_id,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
if (disp_rep_id == DISP_REP_ID_MMI_MODE_ACK) {
proto_tree_add_item(tree, hf_dvbci_mmi_mode,
tvb, offset, 1, ENC_BIG_ENDIAN);
}
else if (disp_rep_id == DISP_REP_ID_DISP_CHAR_TBL ||
disp_rep_id == DISP_REP_ID_INP_CHAR_TBL) {
while ((msg_len=tvb_reported_length_remaining(tvb, offset)) > 0) {
enc_len = dvb_analyze_string_charset(
tvb, offset, msg_len, &encoding);
if (enc_len==0) {
proto_tree_add_expert(tree, pinfo,
&ei_dvbci_invalid_char_tbl, tvb, offset, msg_len);
break;
}
dvb_add_chartbl(tree, hf_dvbci_mmi_char_tbl,
tvb, offset, enc_len, encoding);
offset += enc_len;
}
}
break;
case T_ENQ:
proto_tree_add_item(tree, hf_dvbci_blind_ans,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
ans_txt_len = tvb_get_guint8(tvb,offset);
if (ans_txt_len == NB_UNKNOWN) {
proto_tree_add_text(tree, tvb, offset, 1,
"Length of expected answer is unknown");
}
else
proto_tree_add_item(tree, hf_dvbci_ans_txt_len,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
dissect_si_string(tvb, offset,
tvb_reported_length_remaining(tvb, offset),
pinfo, tree, hf_dvbci_enq, "Enquiry string", FALSE);
break;
case T_ANSW:
ans_id = tvb_get_guint8(tvb,offset);
proto_tree_add_item(tree, hf_dvbci_ans_id, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
if (ans_id == ANSW_ID_ANSWER) {
dissect_si_string(tvb, offset,
tvb_reported_length_remaining(tvb, offset),
pinfo, tree, hf_dvbci_ans, "Answer", TRUE);
}
break;
case T_MENU_LAST:
case T_MENU_MORE:
case T_LIST_LAST:
case T_LIST_MORE:
choice_or_item_nb = tvb_get_guint8(tvb,offset);
if (choice_or_item_nb == NB_UNKNOWN)
{
proto_tree_add_text(tree, tvb, offset, 1,
"Number of items is unknown");
}
else
{
if (IS_MENU_APDU(tag)) {
proto_tree_add_item(
tree, hf_dvbci_choice_nb, tvb, offset, 1, ENC_BIG_ENDIAN);
}
else {
proto_tree_add_item(
tree, hf_dvbci_item_nb, tvb, offset, 1, ENC_BIG_ENDIAN);
}
}
offset++;
text_len = dissect_dvbci_text("Title", tvb, offset,
pinfo, tree, hf_dvbci_title);
offset += text_len;
text_len = dissect_dvbci_text("Sub-title", tvb, offset,
pinfo, tree, hf_dvbci_subtitle);
offset += text_len;
text_len = dissect_dvbci_text("Bottom line", tvb, offset,
pinfo, tree, hf_dvbci_bottom);
offset += text_len;
while (tvb_reported_length_remaining(tvb, offset) > 0) {
text_len = dissect_dvbci_text("Item", tvb, offset, pinfo, tree, hf_dvbci_item);
/* minimum is apdu tag + 1 byte len field */
if (text_len<APDU_TAG_SIZE+1) {
proto_tree_add_expert(tree, pinfo, &ei_dvbci_not_text_more_or_text_last, tvb, offset, -1);
return;
}
offset += text_len;
}
break;
case T_MENU_ANSW:
choice_ref = tvb_get_guint8(tvb,offset);
if (choice_ref == 0x0) {
proto_tree_add_text(tree, tvb, offset, 1,
"Selection was cancelled.");
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"cancelled");
}
else {
proto_tree_add_item(
tree, hf_dvbci_choice_ref, tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"Item %d", choice_ref);
}
break;
default:
break;
}
}
static void
dissect_dvbci_payload_hlc(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
guint8 *str;
if (tag==T_HOST_COUNTRY) {
proto_tree_add_item(tree, hf_dvbci_host_country,
tvb, offset, tvb_reported_length_remaining(tvb, offset),
ENC_ISO_8859_1|ENC_NA);
}
else if (tag==T_HOST_LANGUAGE) {
proto_tree_add_item(tree, hf_dvbci_host_language,
tvb, offset, tvb_reported_length_remaining(tvb, offset),
ENC_ISO_8859_1|ENC_NA);
}
/* both apdus' body is only a country code, this can be shared */
str = tvb_get_string_enc(wmem_packet_scope(), tvb, offset,
tvb_reported_length_remaining(tvb, offset),
ENC_ISO_8859_1|ENC_NA);
if (str)
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s", str);
}
static void
dissect_dvbci_payload_cup(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
guint8 upgrade_type;
guint16 download_time;
guint8 answer, progress;
switch(tag) {
case T_CAM_FIRMWARE_UPGRADE:
upgrade_type = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_cup_type, tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ", "(%s)",
val_to_str_const(upgrade_type, dvbci_cup_type, "unknown"));
offset++;
download_time = tvb_get_ntohs(tvb, offset);
if (download_time == 0) {
proto_tree_add_uint_format(tree, hf_dvbci_cup_download_time,
tvb, offset, 2, download_time,
"estimated download time is unknown");
}
else {
proto_tree_add_uint_format(tree, hf_dvbci_cup_download_time,
tvb, offset, 2, download_time,
"estimated download time is %d seconds",
download_time);
}
break;
case T_CAM_FIRMWARE_UPGRADE_REPLY:
answer = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_cup_answer, tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s",
val_to_str_const(answer, dvbci_cup_answer, "unknown"));
break;
case T_CAM_FIRMWARE_UPGRADE_PROGRESS:
progress = tvb_get_guint8(tvb, offset);
if (progress > 100) {
proto_tree_add_expert(tree, pinfo, &ei_dvbci_cup_progress, tvb, offset, 1);
}
else {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%d%%", progress);
proto_tree_add_uint_format(tree, hf_dvbci_cup_progress,
tvb, offset, 1, progress,
"download progress %d%%", progress);
}
break;
case T_CAM_FIRMWARE_UPGRADE_COMPLETE:
proto_tree_add_item(tree, hf_dvbci_cup_reset, tvb, offset, 1, ENC_BIG_ENDIAN);
break;
default:
break;
}
}
static void
dissect_sac_msg(guint32 tag, tvbuff_t *tvb, gint offset,
packet_info *pinfo, proto_tree *tree, gboolean exported)
{
gint offset_start;
guint32 msg_ctr;
guint8 enc_flag, enc_cip;
proto_item *enc_flag_pi;
guint16 sac_payload_len; /* payload data and padding */
gint sac_payload_data_len = 0; /* just payload data */
tvbuff_t *clear_sac_body_tvb;
proto_tree *sac_tree = NULL;
gboolean is_exportable = FALSE;
offset_start = offset;
/* it's not useful to move sac header dissection to a separate
function, we need enc/auth cipher etc here to handle the body */
msg_ctr = tvb_get_ntohl(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_sac_msg_ctr,
tvb, offset, 4, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
"message #%d", msg_ctr);
offset += 4;
proto_tree_add_item(tree, hf_dvbci_sac_proto_ver,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_sac_auth_cip,
tvb, offset, 1, ENC_BIG_ENDIAN);
enc_flag = tvb_get_guint8(tvb, offset) & 0x1;
enc_flag_pi = proto_tree_add_item(tree, hf_dvbci_sac_payload_enc,
tvb, offset, 1, ENC_BIG_ENDIAN);
if (exported && enc_flag) {
expert_add_info(pinfo, enc_flag_pi, &ei_dvbci_sac_payload_enc);
enc_flag = 0;
}
offset++;
enc_cip = (tvb_get_guint8(tvb, offset)&0xE0) >> 5;
proto_tree_add_item(tree, hf_dvbci_sac_enc_cip,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
sac_payload_len = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_sac_payload_len,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
if (tvb_reported_length_remaining(tvb, offset) < 0)
return;
if (enc_flag) {
clear_sac_body_tvb = decrypt_sac_msg_body(enc_cip,
tvb, offset, tvb_reported_length_remaining(tvb, offset));
}
else {
clear_sac_body_tvb = tvb_new_subset_remaining(tvb, offset);
}
if (!clear_sac_body_tvb) {
/* we could not decrypt (or access) the clear sac message body */
proto_tree_add_item(tree, hf_dvbci_sac_enc_body, tvb, offset,
tvb_reported_length_remaining(tvb, offset), ENC_NA);
return;
}
if (enc_flag)
add_new_data_source(pinfo, clear_sac_body_tvb, "Clear SAC message body");
if (sac_payload_len>0) {
sac_tree = proto_tree_add_subtree(tree, clear_sac_body_tvb, 0, sac_payload_len,
ett_dvbci_sac_msg_body, NULL, "SAC message payload");
if (tag==T_CC_SAC_DATA_REQ || tag==T_CC_SAC_DATA_CNF) {
sac_payload_data_len = dissect_cc_data_payload(tag,
clear_sac_body_tvb, 0, pinfo, sac_tree, &is_exportable);
}
else if (tag==T_CC_SAC_SYNC_REQ) {
sac_payload_data_len = 0;
}
else if (tag==T_CC_SAC_SYNC_CNF) {
proto_tree_add_item(sac_tree, hf_dvbci_cc_status_field,
clear_sac_body_tvb, 0, 1, ENC_BIG_ENDIAN);
sac_payload_data_len = 1;
}
if (sac_payload_data_len < 0)
return;
if (sac_payload_len > sac_payload_data_len) {
proto_tree_add_item(sac_tree, hf_dvbci_sac_padding,
clear_sac_body_tvb, sac_payload_data_len,
sac_payload_len-sac_payload_data_len, ENC_NA);
}
}
proto_tree_add_item(tree, hf_dvbci_sac_signature,
clear_sac_body_tvb, sac_payload_len,
tvb_reported_length_remaining(clear_sac_body_tvb,
sac_payload_len), ENC_NA);
/* we call this function also to dissect exported SAC messages,
dont' try to export them a second time */
if (!exported && is_exportable && have_tap_listener(exported_pdu_tap)) {
tvbuff_t *clear_sac_msg_tvb;
exp_pdu_data_t *exp_pdu_data;
guint8 tags[2];
clear_sac_msg_tvb = tvb_new_composite();
tvb_composite_append(clear_sac_msg_tvb,
tvb_clone_offset_len(tvb, offset_start, SAC_MSG_HDR_LEN));
tvb_composite_append(clear_sac_msg_tvb, clear_sac_body_tvb);
tvb_composite_finalize(clear_sac_msg_tvb);
tags[0] = 0;
tags[1] = EXP_PDU_TAG_DVBCI_EVT_BIT;
exp_pdu_data = load_export_pdu_tags(
pinfo, EXPORTED_SAC_MSG_PROTO, -1, tags, 2);
exp_pdu_data->tvb_captured_length = tvb_captured_length(clear_sac_msg_tvb);
exp_pdu_data->tvb_reported_length = tvb_reported_length(clear_sac_msg_tvb);
exp_pdu_data->pdu_tvb = clear_sac_msg_tvb;
tap_queue_packet(exported_pdu_tap, pinfo, exp_pdu_data);
}
}
static int
dissect_dvbci_exported_sac_msg(
tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
{
guint8 evt;
guint32 tag;
evt = dvbci_get_evt_from_addrs(pinfo);
if (!IS_DATA_TRANSFER(evt))
return 0;
col_append_sep_fstr(pinfo->cinfo, COL_PROTOCOL, NULL, EXPORTED_SAC_MSG_PROTO);
col_clear(pinfo->cinfo, COL_INFO);
/* we only export cc_sac_data_req and _cnf, therefore, the tag can be
derived from the direction of the transfer */
if (evt== DVBCI_EVT_DATA_CAM_TO_HOST)
tag = T_CC_SAC_DATA_REQ;
else
tag = T_CC_SAC_DATA_CNF;
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "%s",
val_to_str_const(tag, dvbci_apdu_tag, "unknown"));
dissect_sac_msg(tag, tvb, 0, pinfo, tree, TRUE);
return tvb_reported_length(tvb);
}
static void
dissect_dvbci_payload_cc(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
guint8 status;
proto_item *pi;
nstime_t utc_time;
guint8 pin_stat;
guint8 evt_cent;
switch(tag) {
case T_CC_OPEN_CNF:
proto_tree_add_item(tree, hf_dvbci_cc_sys_id_bitmask,
tvb, offset, 1, ENC_BIG_ENDIAN);
break;
case T_CC_DATA_REQ:
case T_CC_DATA_CNF:
dissect_cc_data_payload(tag, tvb, offset, pinfo, tree, NULL);
break;
case T_CC_SYNC_CNF:
status = tvb_get_guint8(tvb, offset);
proto_tree_add_item(
tree, hf_dvbci_cc_status_field, tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s",
val_to_str_const(status, dvbci_cc_status, "unknown"));
break;
case T_CC_SAC_DATA_REQ:
case T_CC_SAC_DATA_CNF:
case T_CC_SAC_SYNC_REQ:
case T_CC_SAC_SYNC_CNF:
dissect_sac_msg(tag, tvb, offset, pinfo, tree, FALSE);
break;
case T_CC_PIN_CAPABILITIES_REPLY:
proto_tree_add_item(tree, hf_dvbci_capability_field,
tvb, offset, 1 , ENC_BIG_ENDIAN);
offset++;
/* we can't packet_mpeg_sect_mjd_to_utc_time()
and check with nstime_is_zero() */
if (tvb_get_ntoh40(tvb, offset) == 0) {
proto_tree_add_text(tree, tvb, offset, UTC_TIME_LEN,
"CICAM PIN has never been changed");
}
else {
if (packet_mpeg_sect_mjd_to_utc_time(tvb, offset, &utc_time) < 0) {
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb, offset, UTC_TIME_LEN,
"Invalid UTC time field, 2 bytes MJD, 3 bytes BCD time hhmmss");
break;
}
else {
/* abs_time_to_ep_str() never returns NULL */
proto_tree_add_time(tree, hf_dvbci_pin_chg_time,
tvb, offset, UTC_TIME_LEN, &utc_time);
}
}
offset += UTC_TIME_LEN;
dissect_rating(tvb, offset, pinfo, tree);
break;
case T_CC_PIN_REPLY:
pin_stat = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_pincode_status,
tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s",
val_to_str_const(pin_stat, dvbci_pincode_status, "unknown"));
break;
case T_CC_PIN_EVENT:
proto_tree_add_item(tree, hf_dvbci_cc_prog_num,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_dvbci_pincode_status,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
dissect_rating(tvb, offset, pinfo, tree);
offset++;
if (packet_mpeg_sect_mjd_to_utc_time(tvb, offset, &utc_time) < 0) {
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb, offset, UTC_TIME_LEN,
"Invalid UTC time field, 2 bytes MJD, 3 bytes BCD time hhmmss");
break;
}
else {
proto_tree_add_time(tree, hf_dvbci_pin_evt_time,
tvb, offset, UTC_TIME_LEN, &utc_time);
}
offset += UTC_TIME_LEN;
evt_cent = tvb_get_guint8(tvb, offset);
pi = proto_tree_add_item(tree, hf_dvbci_pin_evt_cent,
tvb, offset, 1, ENC_BIG_ENDIAN);
if (evt_cent > 100) {
expert_add_info(pinfo, pi, &ei_dvbci_pin_evt_cent);
}
offset++;
/* length field was already checked by the caller */
proto_tree_add_item(tree, hf_dvbci_cc_priv_data, tvb, offset,
tvb_reported_length_remaining(tvb, offset), ENC_NA);
break;
case T_CC_PIN_PLAYBACK:
dissect_rating(tvb, offset, pinfo, tree);
offset++;
/* length field was already checked by the caller */
proto_tree_add_item(tree, hf_dvbci_cc_priv_data, tvb, offset,
tvb_reported_length_remaining(tvb, offset), ENC_NA);
break;
case T_CC_PIN_CMD:
case T_CC_PIN_MMI_REQ:
proto_tree_add_item(tree, hf_dvbci_pincode, tvb, offset,
tvb_reported_length_remaining(tvb, offset),
ENC_ASCII|ENC_NA);
break;
default:
break;
}
}
static void
dissect_dvbci_ami_file_ack(tvbuff_t *tvb, gint offset,
packet_info *pinfo, proto_tree *tree)
{
guint8 req_type;
gboolean req_ok = FALSE, file_ok;
guint8 file_name_len;
guint8 *file_name_str;
guint32 file_data_len;
tvbuff_t *png_file_tvb = NULL;
proto_tree *req_tree;
req_type = tvb_get_guint8(tvb, offset+1);
if (req_type==REQ_TYPE_FILE_HASH) {
req_ok = ((tvb_get_guint8(tvb, offset) & 0x02) == 0x02);
proto_tree_add_item(tree, hf_dvbci_req_ok,
tvb, offset, 1, ENC_BIG_ENDIAN);
}
file_ok = ((tvb_get_guint8(tvb, offset) & 0x01) == 0x01);
proto_tree_add_item(tree, hf_dvbci_file_ok, tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_req_type, tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s",
val_to_str_const(req_type, dvbci_req_type, "unknown"));
offset++;
if (req_type==REQ_TYPE_FILE || req_type==REQ_TYPE_FILE_HASH) {
file_name_len = tvb_get_guint8(tvb, offset);
proto_tree_add_text(tree, tvb, offset, 1,
"File name length %d", file_name_len);
offset++;
file_name_str = tvb_get_string_enc(wmem_packet_scope(),
tvb, offset, file_name_len, ENC_ASCII);
if (!file_name_str)
return;
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"%s", file_name_str);
proto_tree_add_string_format_value(tree, hf_dvbci_file_name,
tvb, offset, file_name_len, file_name_str,
"%s", file_name_str);
offset += file_name_len;
file_data_len = tvb_get_ntohl(tvb, offset);
proto_tree_add_text(tree, tvb, offset, 4,
"File data length %d", file_data_len);
offset += 4;
if (file_data_len > 0) {
if (file_name_len>4) {
gchar *suffix_lo;
suffix_lo = wmem_ascii_strdown(wmem_packet_scope(),
&file_name_str[file_name_len-4], -1);
if (g_strcmp0(suffix_lo, ".png")==0) {
png_file_tvb = tvb_new_subset_length(
tvb, offset, file_data_len);
}
}
if (png_handle && png_file_tvb) {
col_set_fence(pinfo->cinfo, COL_PROTOCOL);
col_set_fence(pinfo->cinfo, COL_INFO);
call_dissector(png_handle, png_file_tvb, pinfo, tree);
}
else {
proto_tree_add_item(tree, hf_dvbci_file_data,
tvb, offset, file_data_len, ENC_NA);
}
}
}
else if (req_type==REQ_TYPE_DATA) {
if (tvb_reported_length_remaining(tvb, offset) <= 0)
return;
proto_tree_add_item(tree, hf_dvbci_ami_priv_data, tvb, offset,
tvb_reported_length_remaining(tvb, offset), ENC_NA);
}
else if (req_type==REQ_TYPE_REQ) {
req_tree = proto_tree_add_subtree(tree, tvb,
offset, tvb_reported_length_remaining(tvb, offset),
ett_dvbci_ami_req_types, NULL, "Supported request types");
while (tvb_reported_length_remaining(tvb, offset) > 0) {
proto_tree_add_item(req_tree, hf_dvbci_req_type,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
}
}
if (req_type==REQ_TYPE_FILE_HASH && req_ok && !file_ok) {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
"cached copy is valid");
}
}
static void
dissect_dvbci_payload_ami(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
guint8 app_dom_id_len, init_obj_len;
guint8 *app_dom_id;
guint8 ack_code;
guint8 req_type;
guint8 *req_str;
switch(tag) {
case T_REQUEST_START:
/* no filter for length items */
app_dom_id_len = tvb_get_guint8(tvb, offset);
proto_tree_add_text(tree, tvb, offset, 1,
"Application Domain Identifier length %d", app_dom_id_len);
offset++;
init_obj_len = tvb_get_guint8(tvb, offset);
proto_tree_add_text(tree, tvb, offset, 1,
"Initial Object length %d", init_obj_len);
offset++;
proto_tree_add_item(tree, hf_dvbci_app_dom_id,
tvb, offset, app_dom_id_len, ENC_ASCII|ENC_NA);
app_dom_id = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, app_dom_id_len, ENC_ASCII);
if (app_dom_id) {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ",
"for %s", app_dom_id);
}
offset += app_dom_id_len;
proto_tree_add_item(tree, hf_dvbci_init_obj,
tvb, offset, init_obj_len, ENC_ASCII|ENC_NA);
break;
case T_REQUEST_START_ACK:
ack_code = tvb_get_guint8(tvb, offset);
proto_tree_add_item(
tree, hf_dvbci_ack_code, tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s",
val_to_str_const(ack_code, dvbci_ack_code, "unknown"));
break;
case T_FILE_REQUEST:
req_type = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_req_type, tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s",
val_to_str_const(req_type, dvbci_req_type, "unknown"));
offset++;
if (req_type==REQ_TYPE_FILE_HASH) {
proto_tree_add_item(tree, hf_dvbci_file_hash,
tvb, offset, 16, ENC_NA);
offset += 16;
}
if (tvb_reported_length_remaining(tvb, offset) <= 0)
break;
if (req_type==REQ_TYPE_FILE || req_type==REQ_TYPE_FILE_HASH) {
req_str = tvb_get_string_enc(wmem_packet_scope(), tvb, offset,
tvb_reported_length_remaining(tvb, offset), ENC_ASCII);
if (!req_str)
break;
col_append_sep_fstr(pinfo->cinfo, COL_INFO, " ", "%s", req_str);
proto_tree_add_string_format_value(tree, hf_dvbci_file_name,
tvb, offset, tvb_reported_length_remaining(tvb, offset),
req_str, "%s", req_str);
}
else if (req_type==REQ_TYPE_DATA) {
proto_tree_add_item(tree, hf_dvbci_ami_priv_data, tvb, offset,
tvb_reported_length_remaining(tvb, offset), ENC_NA);
}
break;
case T_FILE_ACKNOWLEDGE:
dissect_dvbci_ami_file_ack(tvb, offset, pinfo, tree);
break;
case T_APP_ABORT_REQUEST:
if (tvb_reported_length_remaining(tvb, offset) > 0) {
proto_tree_add_item(tree, hf_dvbci_abort_req_code, tvb, offset,
tvb_reported_length_remaining(tvb, offset), ENC_NA);
}
break;
case T_APP_ABORT_ACK:
if (tvb_reported_length_remaining(tvb, offset) > 0) {
proto_tree_add_item(tree, hf_dvbci_abort_ack_code, tvb, offset,
tvb_reported_length_remaining(tvb, offset), ENC_NA);
}
break;
default:
break;
}
}
static void
dissect_dvbci_payload_lsc(guint32 tag, gint len_field,
tvbuff_t *tvb, gint offset, circuit_t *circuit,
packet_info *pinfo, proto_tree *tree)
{
gint offset_start;
guint8 id, timeout, ret_val, phase_id;
gint conn_desc_len, param_len;
guint16 buf_size;
proto_item *pi = NULL;
const gchar *ret_val_str = NULL;
gint msg_len;
tvbuff_t *msg_tvb;
dissector_handle_t msg_handle;
offset_start = offset;
switch(tag) {
case T_COMMS_CMD:
proto_tree_add_item(tree, hf_dvbci_comms_cmd_id,
tvb, offset, 1, ENC_BIG_ENDIAN);
id = tvb_get_guint8(tvb, offset);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s",
val_to_str(id, dvbci_comms_cmd_id, "Unknown: %d"));
offset++;
switch(id) {
case COMMS_CMD_ID_CONNECT_ON_CHANNEL:
conn_desc_len = dissect_conn_desc(tvb, offset,
circuit, pinfo, tree);
if (conn_desc_len < 0)
break;
offset += conn_desc_len;
proto_tree_add_item(tree, hf_dvbci_lsc_retry_count,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
timeout = tvb_get_guint8(tvb, offset);
if (timeout==0) {
proto_tree_add_uint_format(tree, hf_dvbci_lsc_timeout,
tvb, offset, 1, timeout, "Infinite timeout");
} else {
proto_tree_add_uint_format(tree, hf_dvbci_lsc_timeout,
tvb, offset, 1, timeout,
"Timeout is %d seconds", timeout);
}
break;
case COMMS_CMD_ID_DISCONNECT_ON_CHANNEL:
case COMMS_CMD_ID_ENQUIRE_STATUS:
/* len_field == 1 -> only id, no further parameters */
if (len_field != 1) {
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb,
APDU_TAG_SIZE, offset_start-APDU_TAG_SIZE,
"Length field must be 1");
}
break;
case COMMS_CMD_ID_SET_PARAMS:
param_len = tvb_reported_length_remaining(tvb, offset);
if (param_len == 2)
buf_size = (guint16)tvb_get_guint8(tvb, offset);
else if (param_len == 3)
buf_size = tvb_get_ntohs(tvb, offset);
else {
/* length field == 1 byte id + param_len */
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb,
APDU_TAG_SIZE, offset_start-APDU_TAG_SIZE,
"Length field must be 3 or 4");
break;
}
proto_tree_add_uint_format(tree, hf_dvbci_lsc_buf_size,
tvb, offset, param_len-1, buf_size,
"buffer size %d bytes", buf_size);
offset += param_len-1;
timeout = tvb_get_guint8(tvb, offset);
proto_tree_add_uint_format(tree, hf_dvbci_lsc_timeout,
tvb, offset, 1, timeout,
"timeout is %d milliseconds", timeout*10);
break;
case COMMS_CMD_ID_GET_NEXT_BUFFER:
phase_id = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_phase_id,
tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
"received #%d", phase_id);
break;
default:
break;
}
break;
case T_COMMS_REPLY:
proto_tree_add_item(tree, hf_dvbci_comms_rep_id,
tvb, offset, 1, ENC_BIG_ENDIAN);
id = tvb_get_guint8(tvb,offset);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "%s",
val_to_str(id, dvbci_comms_rep_id, "Unknown: %d"));
offset++;
ret_val = tvb_get_guint8(tvb,offset);
pi = proto_tree_add_item(tree, hf_dvbci_lsc_ret_val,
tvb, offset, 1, ENC_BIG_ENDIAN);
switch (id) {
case COMMS_REP_ID_SEND_ACK:
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"sent #%d", ret_val);
if (pi)
proto_item_append_text(pi, " (sent #%d)", ret_val);
break;
case COMMS_REP_ID_SET_PARAMS_ACK:
ret_val_str = val_to_str_const(ret_val,
dvbci_lsc_ret_val_params, "unknown/error");
break;
case COMMS_REP_ID_STATUS_REPLY:
ret_val_str = val_to_str_const(ret_val,
dvbci_lsc_ret_val_connect, "unknown/error");
break;
default:
ret_val_str = val_to_str_const(ret_val,
dvbci_lsc_ret_val, "unknown/error");
break;
}
if (ret_val_str) {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"%s", ret_val_str);
if (pi)
proto_item_append_text(pi, " (%s)", ret_val_str);
}
break;
case T_COMMS_SEND_LAST:
case T_COMMS_SEND_MORE:
case T_COMMS_RCV_LAST:
case T_COMMS_RCV_MORE:
phase_id = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_phase_id,
tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"Phase ID %d", phase_id);
offset++;
msg_len = tvb_reported_length_remaining(tvb, offset);
if (msg_len<=0)
break;
msg_tvb = tvb_new_subset_remaining(tvb, offset);
if (!msg_tvb)
break;
if (dvbci_dissect_lsc_msg && circuit && circuit->dissector_handle) {
msg_handle = circuit->dissector_handle;
col_append_str(pinfo->cinfo, COL_INFO, ", ");
col_set_fence(pinfo->cinfo, COL_INFO);
col_append_str(pinfo->cinfo, COL_PROTOCOL, ", ");
col_set_fence(pinfo->cinfo, COL_PROTOCOL);
}
else {
msg_handle = data_handle;
}
if (msg_handle)
call_dissector(msg_handle, msg_tvb, pinfo, tree);
break;
default:
break;
}
}
static void
dissect_dvbci_payload_opp(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit _U_,
packet_info *pinfo, proto_tree *tree)
{
guint16 nit_loop_len, nit_loop_offset;
tvbuff_t *nit_loop_tvb, *nit_loop_partial_tvb;
guint dvb_nit_bytes;
guint8 table_id;
guint8 cap_loop_len;
gboolean info_valid;
guint enc_len;
dvb_encoding_e encoding;
guint8 desc_num;
guint8 sig_strength, sig_qual;
proto_item *pi;
switch(tag) {
case T_OPERATOR_STATUS:
case T_OPERATOR_SEARCH_STATUS:
dissect_opp_status_body(tvb, offset, pinfo, tree);
break;
case T_OPERATOR_NIT:
nit_loop_len = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_nit_loop_len,
tvb, offset, 2, ENC_BIG_ENDIAN);
if (nit_loop_len==0)
break;
offset += 2;
nit_loop_tvb = tvb_new_subset_length(
tvb, offset, nit_loop_len);
nit_loop_offset = 0;
if (!dvb_nit_handle) {
call_dissector(data_handle, nit_loop_tvb, pinfo, tree);
break;
}
/* prevent dvb_nit dissector from clearing the dvb-ci infos */
col_append_str(pinfo->cinfo, COL_INFO, ", ");
col_set_fence(pinfo->cinfo, COL_INFO);
do {
table_id = tvb_get_guint8(nit_loop_tvb, nit_loop_offset);
if (table_id != TABLE_ID_CICAM_NIT) {
proto_tree_add_expert(tree, pinfo, &ei_dvbci_cicam_nit_table_id,
nit_loop_tvb, nit_loop_offset, 1);
}
nit_loop_partial_tvb =
tvb_new_subset_remaining(nit_loop_tvb, nit_loop_offset);
dvb_nit_bytes = call_dissector(
dvb_nit_handle, nit_loop_partial_tvb, pinfo, tree);
nit_loop_offset += dvb_nit_bytes;
/* offsets go from 0 to nit_loop_len-1 */
} while (dvb_nit_bytes>0 && nit_loop_offset<nit_loop_len-1);
break;
case T_OPERATOR_INFO:
info_valid = ((tvb_get_guint8(tvb, offset) & 0x08) == 0x08);
proto_tree_add_item(tree, hf_dvbci_info_valid,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_info_ver_op_info,
tvb, offset, 1, ENC_BIG_ENDIAN);
if (!info_valid)
break;
offset++;
proto_tree_add_item(tree, hf_dvbci_cicam_onid,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_dvbci_cicam_id,
tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
enc_len = dvb_analyze_string_charset(tvb, offset,
tvb_reported_length_remaining(tvb, offset), &encoding);
if (enc_len==0) {
proto_tree_add_expert(tree, pinfo,
&ei_dvbci_invalid_char_tbl, tvb, offset,
tvb_reported_length_remaining(tvb, offset));
break;
}
dvb_add_chartbl(tree, hf_dvbci_opp_char_tbl,
tvb, offset, enc_len, encoding);
offset += enc_len;
proto_tree_add_item(tree, hf_dvbci_sdt_rst_trusted,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_eit_rst_trusted,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_eit_pf_usage,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_eit_sch_usage,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_ext_evt_usage,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_sdt_oth_trusted,
tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_eit_evt_trigger,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_opp_lang_code,
tvb, offset, 3, ENC_ASCII|ENC_NA);
offset += 3;
/* hf_dvbci_prof_name is an FT_UINT_STRING, one leading len byte */
proto_tree_add_item(tree, hf_dvbci_prof_name,
tvb, offset, 1, ENC_ASCII|ENC_NA);
break;
case T_OPERATOR_SEARCH_START:
proto_tree_add_item(tree, hf_dvbci_unattended,
tvb, offset, 1, ENC_BIG_ENDIAN);
/* no filters for the loop lengths, one is 7bit, others are 8bit */
cap_loop_len = tvb_get_guint8(tvb, offset) & 0x7F;
proto_tree_add_text(tree, tvb, offset, 1,
"Service type loop length: %d", cap_loop_len);
offset++;
/* no need for error checking, we continue anyway */
dissect_opp_cap_loop(cap_loop_len, "Service type loop",
hf_dvbci_opp_srv_type, 1, tvb, offset, pinfo, tree);
offset += cap_loop_len;
cap_loop_len = tvb_get_guint8(tvb, offset);
proto_tree_add_text(tree, tvb, offset, 1,
"Delivery system capabilities loop length: %d",
cap_loop_len);
offset++;
/* XXX - handle multi-byte delivery capabilities */
dissect_opp_cap_loop(cap_loop_len,
"Delivery system capabilities loop",
hf_dvbci_dlv_cap_byte, 1,
tvb, offset, pinfo, tree);
offset += cap_loop_len;
cap_loop_len = tvb_get_guint8(tvb, offset);
proto_tree_add_text(tree, tvb, offset, 1,
"Application capabilities loop length: %d", cap_loop_len);
offset++;
dissect_opp_cap_loop(cap_loop_len,
"Application capabilities loop",
hf_dvbci_app_cap_bytes, 2,
tvb, offset, pinfo, tree);
break;
case T_OPERATOR_TUNE_STATUS:
desc_num = tvb_get_guint8(tvb, offset);
pi = proto_tree_add_item(tree, hf_dvbci_desc_num,
tvb, offset, 1, ENC_BIG_ENDIAN);
if (desc_num==OPP_NO_MORE_DESC)
proto_item_append_text(pi, " (all descriptors were processed)");
offset++;
sig_strength = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_sig_strength,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
sig_qual = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_sig_qual,
tvb, offset, 1, ENC_BIG_ENDIAN);
if (sig_strength>100 || sig_qual>100) {
pi = proto_tree_add_text(tree, tvb, offset, 1,
"Invalid value for signal strength / signal quality");
expert_add_info(pinfo, pi, &ei_dvbci_sig_qual);
}
offset++;
proto_tree_add_item(tree, hf_dvbci_opp_tune_status,
tvb, offset, 1, ENC_BIG_ENDIAN);
dissect_desc_loop(hf_dvbci_opp_desc_loop_len,
tvb, offset, pinfo, tree);
break;
case T_OPERATOR_TUNE:
dissect_desc_loop(hf_dvbci_opp_desc_loop_len,
tvb, offset, pinfo, tree);
break;
default:
break;
}
}
static void
dissect_dvbci_payload_sas(guint32 tag, gint len_field _U_,
tvbuff_t *tvb, gint offset, circuit_t *circuit,
packet_info *pinfo, proto_tree *tree)
{
gchar app_id_str[2+16+1]; /* "0x", string of 16 hex digits, trailing 0 */
guint8 sas_status;
dissector_handle_t msg_handle;
guint8 msg_nb;
guint16 msg_len;
tvbuff_t *msg_tvb;
switch(tag) {
case T_SAS_CONNECT_RQST:
case T_SAS_CONNECT_CNF:
g_snprintf(app_id_str, sizeof(app_id_str),
"0x%016" G_GINT64_MODIFIER "x", tvb_get_ntoh64(tvb, offset));
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s", app_id_str);
proto_tree_add_item(tree, hf_dvbci_sas_app_id,
tvb, offset, 8, ENC_BIG_ENDIAN);
offset += 8;
if (tag == T_SAS_CONNECT_CNF) {
sas_status = tvb_get_guint8(tvb, offset);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
(sas_status == SAS_SESS_STATE_CONNECTED ?
"Ok" : "Error"));
proto_tree_add_item(tree, hf_dvbci_sas_sess_state,
tvb, offset, 1, ENC_BIG_ENDIAN);
if (!circuit)
break;
if (sas_status == SAS_SESS_STATE_CONNECTED) {
msg_handle = dissector_get_string_handle(
sas_msg_dissector_table, app_id_str);
/* this clears the dissector for msg_handle==NULL */
circuit_set_dissector(circuit, msg_handle);
}
else
circuit_set_dissector(circuit, NULL);
}
break;
case T_SAS_ASYNC_MSG:
msg_nb = tvb_get_guint8(tvb, offset);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"Message #%d ", msg_nb);
proto_tree_add_item(tree, hf_dvbci_sas_msg_nb,
tvb, offset, 1, ENC_BIG_ENDIAN);
offset++;
msg_len = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(tree, hf_dvbci_sas_msg_len,
tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
msg_tvb = tvb_new_subset_length(tvb, offset, msg_len);
msg_handle = (circuit && circuit->dissector_handle) ?
circuit->dissector_handle : data_handle;
call_dissector(msg_handle, msg_tvb, pinfo, tree);
break;
default:
break;
}
}
static void
dissect_dvbci_apdu(tvbuff_t *tvb, circuit_t *circuit,
packet_info *pinfo, proto_tree *tree, guint8 direction)
{
proto_tree *app_tree;
guint32 apdu_len, tag, len_field;
const gchar *tag_str;
gint offset;
proto_item *pi;
apdu_info_t *ai;
guint32 apdu_res_id;
const gchar *ai_res_class_str;
apdu_len = tvb_reported_length(tvb);
app_tree = proto_tree_add_subtree(tree, tvb, 0, apdu_len, ett_dvbci_application, NULL, "Application Layer");
tag = tvb_get_ntoh24(tvb, 0);
tag_str = try_val_to_str(tag, dvbci_apdu_tag);
offset = APDU_TAG_SIZE;
col_set_str(pinfo->cinfo, COL_INFO,
val_to_str_const(tag, dvbci_apdu_tag, "Unknown/invalid APDU"));
pi = proto_tree_add_item(
app_tree, hf_dvbci_apdu_tag, tvb, 0, APDU_TAG_SIZE, ENC_BIG_ENDIAN);
if (tag_str == NULL) {
expert_add_info(pinfo, pi, &ei_dvbci_apdu_tag);
return;
}
offset = dissect_ber_length(pinfo, app_tree, tvb, offset, &len_field, NULL);
if ((offset+len_field) != apdu_len) {
proto_tree_add_expert_format(app_tree, pinfo, &ei_dvbci_bad_length, tvb,
APDU_TAG_SIZE, offset-APDU_TAG_SIZE,
"Length field is different from the number of apdu payload bytes");
/* we need len_field bytes of apdu payload to call
ai->dissect_payload() and continue dissecting */
if (apdu_len < offset+len_field)
return;
}
ai = (apdu_info_t *)g_hash_table_lookup(apdu_table,
GUINT_TO_POINTER((guint)tag));
if (!ai) {
proto_tree_add_expert(app_tree, pinfo, &ei_dvbci_apdu_not_supported, tvb, 0, APDU_TAG_SIZE);
return;
}
if (ai->direction!=DIRECTION_ANY && ai->direction!=direction) {
if (ai->direction==DATA_HOST_TO_CAM) {
proto_tree_add_expert(app_tree, pinfo, &ei_dvbci_apu_host_to_cam, tvb, 0, APDU_TAG_SIZE);
}
else {
proto_tree_add_expert(app_tree, pinfo, &ei_dvbci_apu_cam_to_host, tvb, 0, APDU_TAG_SIZE);
}
/* don't return, we can continue dissecting the APDU */
}
if (ai->min_len_field!=LEN_FIELD_ANY && len_field<ai->min_len_field) {
proto_tree_add_expert_format(app_tree, pinfo, &ei_dvbci_bad_length, tvb, 0, APDU_TAG_SIZE,
"Invalid APDU length field, minimum length field for %s is %d", tag_str, ai->min_len_field);
return;
}
if (ai->len_field!=LEN_FIELD_ANY && len_field!=ai->len_field) {
proto_tree_add_expert_format(app_tree, pinfo, &ei_dvbci_bad_length, tvb, 0, APDU_TAG_SIZE,
"Invalid APDU length field, length field for %s must be %d", tag_str, ai->len_field);
return;
}
if (circuit) {
apdu_res_id = GPOINTER_TO_UINT(
(gpointer)circuit_get_proto_data(circuit, proto_dvbci));
ai_res_class_str = val_to_str_const(ai->res_class, dvbci_res_class, "Unknown");
if(RES_CLASS(apdu_res_id) != ai->res_class) {
proto_tree_add_expert_format(app_tree, pinfo, &ei_dvbci_res_class, tvb, 0, APDU_TAG_SIZE,
"Invalid resource class for this apdu, %s can only be sent on a %s session",
tag_str, ai_res_class_str);
}
if(RES_VER(apdu_res_id) < ai->res_min_ver) {
proto_tree_add_expert_format(app_tree, pinfo, &ei_dvbci_res_ver, tvb, 0, APDU_TAG_SIZE,
"Invalid resource version for this apdu, %s apdu requires at least %s version %d",
tag_str, ai_res_class_str, ai->res_min_ver);
}
/* don't return, we can continue dissecting the APDU */
}
if (ai->len_field!=0) {
if (!ai->dissect_payload) {
/* don't display an error, getting here means we have illegal
* data in apdu_info[] */
return;
}
ai->dissect_payload(
tag, len_field, tvb, offset, circuit, pinfo, app_tree);
}
}
static void
dissect_dvbci_spdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
guint8 direction, guint8 tcid)
{
guint32 spdu_len;
proto_item *ti;
proto_tree *sess_tree;
guint8 tag;
const gchar *tag_str;
circuit_t *circuit = NULL;
proto_item *pi;
gint offset;
guint32 len_field;
const spdu_info_t *si;
proto_item *res_id_it = NULL;
guint32 res_id;
guint16 ssnb = 0; /* session numbers start with 1, 0 is invalid */
guint8 sess_stat;
tvbuff_t *payload_tvb = NULL;
spdu_len = tvb_reported_length(tvb);
sess_tree = proto_tree_add_subtree(tree, tvb, 0, -1, ett_dvbci_session, &ti, "Session Layer");
tag = tvb_get_guint8(tvb,0);
tag_str = try_val_to_str(tag, dvbci_spdu_tag);
col_set_str(pinfo->cinfo, COL_INFO,
val_to_str_const(tag, dvbci_spdu_tag, "Invalid SPDU"));
pi = proto_tree_add_item(sess_tree, hf_dvbci_spdu_tag, tvb, 0, 1, ENC_BIG_ENDIAN);
if (tag_str == NULL) {
expert_add_info(pinfo, pi, &ei_dvbci_spdu_tag);
return;
}
offset = dissect_ber_length(pinfo, sess_tree, tvb, 1, &len_field, NULL);
si = (spdu_info_t *)g_hash_table_lookup(spdu_table,
GUINT_TO_POINTER((guint)tag));
if (!si)
return;
if (si->direction!=0 && si->direction!=direction) {
if (si->direction==DATA_HOST_TO_CAM) {
proto_tree_add_expert(sess_tree, pinfo, &ei_dvbci_spdu_host_to_cam, tvb, 0, 1);
}
else {
proto_tree_add_expert(sess_tree, pinfo, &ei_dvbci_spdu_cam_to_host, tvb, 0, 1);
}
}
if (si->len_field != len_field) {
/* offset points to 1st byte after the length field */
proto_tree_add_expert_format(sess_tree, pinfo, &ei_dvbci_bad_length, tvb, 1, offset-1,
"Invalid SPDU length field, correct length field for %s is %d", tag_str, si->len_field);
return;
}
switch(tag)
{
case T_OPEN_SESSION_REQUEST:
res_id_it = dissect_res_id(tvb, offset, pinfo, sess_tree, 0, TRUE);
break;
case T_CREATE_SESSION:
res_id_it = dissect_res_id(tvb, offset, pinfo, sess_tree, 0, TRUE);
/* DVB-CI uses network byte order == big endian */
ssnb = tvb_get_ntohs(tvb, offset+RES_ID_LEN);
proto_tree_add_item(sess_tree, hf_dvbci_sess_nb,
tvb, offset+RES_ID_LEN, 2, ENC_BIG_ENDIAN);
break;
case T_OPEN_SESSION_RESPONSE:
case T_CREATE_SESSION_RESPONSE:
sess_stat = tvb_get_guint8(tvb, offset);
proto_tree_add_item(sess_tree, hf_dvbci_sess_status,
tvb, offset, 1, ENC_BIG_ENDIAN);
res_id = tvb_get_ntohl(tvb, offset+1);
res_id_it = dissect_res_id(tvb, offset+1, pinfo, sess_tree, 0, TRUE);
ssnb = tvb_get_ntohs(tvb, offset+1+RES_ID_LEN);
proto_tree_add_item(sess_tree, hf_dvbci_sess_nb, tvb,
offset+1+RES_ID_LEN, 2, ENC_BIG_ENDIAN);
if (sess_stat != SESS_OPENED) {
col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Error");
break;
}
col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Session opened");
circuit = circuit_new(CT_DVBCI, CT_ID(ssnb, tcid), pinfo->fd->num);
if (circuit) {
/* we always add the resource id immediately after the circuit
was created */
circuit_add_proto_data(
circuit, proto_dvbci, GUINT_TO_POINTER(res_id));
}
break;
case T_CLOSE_SESSION_REQUEST:
ssnb = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(
sess_tree, hf_dvbci_sess_nb, tvb,
offset, 2, ENC_BIG_ENDIAN);
break;
case T_CLOSE_SESSION_RESPONSE:
sess_stat = tvb_get_guint8(tvb, offset);
proto_tree_add_item(
sess_tree, hf_dvbci_close_sess_status, tvb,
offset, 1, ENC_BIG_ENDIAN);
col_append_sep_str(pinfo->cinfo, COL_INFO, NULL,
sess_stat==SESS_CLOSED ? "Session closed" : "Error");
ssnb = tvb_get_ntohs(tvb, offset+1);
proto_tree_add_item(sess_tree, hf_dvbci_sess_nb,
tvb, offset+1, 2, ENC_BIG_ENDIAN);
circuit = find_circuit(CT_DVBCI, CT_ID(ssnb, tcid), pinfo->fd->num);
if (circuit)
close_circuit(circuit, pinfo->fd->num);
break;
case T_SESSION_NUMBER:
ssnb = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(
sess_tree, hf_dvbci_sess_nb, tvb,
offset, 2, ENC_BIG_ENDIAN);
payload_tvb =
tvb_new_subset_remaining(tvb, offset+2);
break;
default:
break;
}
if (ssnb && !circuit)
circuit = find_circuit(CT_DVBCI, CT_ID(ssnb, tcid), pinfo->fd->num);
/* if the packet contains no resource id, we add the cached id from
the circuit so that each packet has a resource id that can be
used for filtering */
if (circuit && !res_id_it) {
/* when a circuit is found, it always contains a valid resource id */
res_id = GPOINTER_TO_UINT(
(gpointer)circuit_get_proto_data(circuit, proto_dvbci));
res_id_it = dissect_res_id(NULL, 0, pinfo, sess_tree, res_id, TRUE);
PROTO_ITEM_SET_GENERATED(res_id_it);
}
if (payload_tvb) {
proto_item_set_len(ti, spdu_len-tvb_reported_length(payload_tvb));
dissect_dvbci_apdu(payload_tvb, circuit, pinfo, tree, direction);
}
else {
proto_item_set_len(ti, spdu_len);
}
}
/* dissect the status of an r_tpdu, return its length or -1 for error */
static gint
dissect_dvbci_tpdu_status(tvbuff_t *tvb, gint offset,
packet_info *pinfo, proto_tree *tree,
guint8 lpdu_tcid, guint8 r_tpdu_tag)
{
gint offset_new, len_start_offset;
guint8 tag;
guint32 len_field;
guint8 t_c_id, sb_value;
const gchar *sb_str;
proto_item *pi;
offset_new = offset;
tag = tvb_get_guint8(tvb, offset_new);
if (tag!=T_SB) {
proto_tree_add_expert(tree, pinfo, &ei_dvbci_tpdu_status_tag, tvb, offset_new, 1);
return -1;
}
col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "T_SB");
proto_tree_add_text(tree, tvb, offset_new, 1, "Response TPDU status");
offset_new++;
len_start_offset = offset_new;
offset_new = dissect_ber_length(
pinfo, tree, tvb, offset_new, &len_field, NULL);
if (len_field != 2) {
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb, len_start_offset, offset_new-len_start_offset,
"Invalid status length field, this must always be 2");
return -1;
}
t_c_id = tvb_get_guint8(tvb, offset_new);
proto_tree_add_item(tree, hf_dvbci_t_c_id, tvb, offset_new, 1, ENC_BIG_ENDIAN);
/* tcid in transport header and link layer must only match for data
* transmission commands */
if (t_c_id!=lpdu_tcid) {
if (r_tpdu_tag==NO_TAG ||
r_tpdu_tag==T_DATA_MORE || r_tpdu_tag==T_DATA_LAST) {
pi = proto_tree_add_text(tree, tvb, offset_new, 1,
"Transport Connection ID mismatch");
expert_add_info_format(pinfo, pi, &ei_dvbci_t_c_id, "Transport Connection ID mismatch, tcid is %d in the transport layer and %d in the link layer", t_c_id, lpdu_tcid);
return -1;
}
}
offset_new++;
sb_value = tvb_get_guint8(tvb, offset_new);
sb_str = try_val_to_str(sb_value, dvbci_sb_value);
pi = proto_tree_add_item(tree, hf_dvbci_sb_value, tvb,
offset_new, 1, ENC_BIG_ENDIAN);
if (sb_str) {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "%s", sb_str);
}
else {
proto_tree_add_text(tree, tvb, offset_new, 1,
"Invalid SB_value");
expert_add_info(pinfo, pi, &ei_dvbci_sb_value);
}
offset_new++;
return offset_new-offset;
}
/* dissect the header of a c_tpdu or r_tpdu
return the length of the header (tag, len_field, t_c_id) or -1 for error */
static gint
dissect_dvbci_tpdu_hdr(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
guint8 direction, guint8 lpdu_tcid, guint32 tpdu_len,
guint8 *hdr_tag, guint32 *body_len)
{
guint8 c_tpdu_tag, r_tpdu_tag, *tag = NULL;
const gchar *c_tpdu_str, *r_tpdu_str;
proto_item *pi;
gint offset;
guint32 len_field;
guint8 t_c_id;
if (direction==DATA_HOST_TO_CAM) {
c_tpdu_tag = tvb_get_guint8(tvb, 0);
tag = &c_tpdu_tag;
c_tpdu_str = try_val_to_str(c_tpdu_tag, dvbci_c_tpdu);
pi = proto_tree_add_item(tree, hf_dvbci_c_tpdu_tag, tvb, 0, 1, ENC_BIG_ENDIAN);
if (c_tpdu_str) {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "%s", c_tpdu_str);
}
else {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
"Invalid Command-TPDU tag");
expert_add_info(pinfo, pi, &ei_dvbci_c_tpdu_tag);
return -1;
}
}
else {
r_tpdu_tag = tvb_get_guint8(tvb, 0);
tag = &r_tpdu_tag;
r_tpdu_str = try_val_to_str(r_tpdu_tag, dvbci_r_tpdu);
pi = proto_tree_add_item(tree, hf_dvbci_r_tpdu_tag, tvb, 0, 1, ENC_BIG_ENDIAN);
if (r_tpdu_str) {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "%s", r_tpdu_str);
}
else {
if (r_tpdu_tag == T_SB) {
/* we have an r_tpdu without header and body,
it contains only the status part */
if (hdr_tag)
*hdr_tag = NO_TAG;
if (body_len)
*body_len = 0;
return 0;
}
else {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
"Invalid Response-TPDU tag");
expert_add_info(pinfo, pi, &ei_dvbci_r_tpdu_tag);
return -1;
}
}
}
offset = dissect_ber_length(pinfo, tree, tvb, 1, &len_field, NULL);
/* len_field must be at least 1 for the following t_c_id
c_tpdu's len_field must match tvbuff exactly
r_tpdu's len_field does not include the status part after the body */
if (len_field==0 ||
((direction==DATA_HOST_TO_CAM) && ((offset+len_field)!=tpdu_len)) ||
((direction==DATA_CAM_TO_HOST) && ((offset+len_field)>tpdu_len))) {
/* offset points to 1st byte after the length field */
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_bad_length, tvb, 1, offset-1,
len_field==0 ? "Invalid length field, length field must be at least 1" :
"Invalid length field, length field mismatch");
return -1;
}
t_c_id = tvb_get_guint8(tvb, offset);
pi = proto_tree_add_item(tree, hf_dvbci_t_c_id, tvb, offset, 1, ENC_BIG_ENDIAN);
/* tcid in transport header and link layer must only match for
* data transmission commands */
if (t_c_id!=lpdu_tcid) {
if (tag && (*tag==T_RCV || *tag==T_DATA_MORE || *tag==T_DATA_LAST)) {
expert_add_info_format(pinfo, pi, &ei_dvbci_t_c_id, "Transport Connection ID mismatch, tcid is %d in the transport layer and %d in the link layer",
t_c_id, lpdu_tcid);
}
}
else {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "tcid %d", t_c_id);
}
offset++;
if (hdr_tag && tag)
*hdr_tag = *tag;
if (body_len)
*body_len = len_field-1; /* -1 for t_c_id */
return offset;
}
static void
dissect_dvbci_tpdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
guint8 direction, guint8 lpdu_tcid)
{
guint32 tpdu_len, body_len;
proto_item *ti;
proto_tree *trans_tree;
gint offset, status_len;
guint8 hdr_tag = NO_TAG;
tvbuff_t *body_tvb, *payload_tvb = NULL;
fragment_head *frag_msg = NULL;
tpdu_len = tvb_reported_length(tvb);
col_clear(pinfo->cinfo, COL_INFO);
trans_tree = proto_tree_add_subtree(tree, tvb, 0, -1, ett_dvbci_transport, &ti, "Transport Layer");
offset = dissect_dvbci_tpdu_hdr(tvb, pinfo, trans_tree, direction,
lpdu_tcid, tpdu_len, &hdr_tag, &body_len);
if (offset==-1)
return;
proto_item_set_len(ti, offset);
if ((offset>0) && (body_len!=0)) {
/* for unfragmented data, the reassembly api behaviour is unclear
if we put the body part of the tvb into fragment_add_seq_next(),
process_reassembled_data() returns the remainder of the tvb
which is body|status part
if there's more than one fragment, payload_tvb contains only
the reassembled bodies as expected
to work around this issue, we use a dedicated body_tvb as
input to reassembly routines */
body_tvb = tvb_new_subset_length(tvb, offset, body_len);
/* dissect_dvbci_tpdu_hdr() checked that lpdu_tcid==t_c_id */
frag_msg = fragment_add_seq_next(&spdu_reassembly_table,
body_tvb, 0, pinfo, SPDU_SEQ_ID_BASE+lpdu_tcid, NULL,
body_len,
hdr_tag == T_DATA_MORE ? 1 : 0);
payload_tvb = process_reassembled_data(body_tvb, 0, pinfo,
"Reassembled SPDU", frag_msg, &spdu_frag_items,
NULL, trans_tree);
if (!payload_tvb) {
if (hdr_tag == T_DATA_MORE) {
pinfo->fragmented = TRUE;
col_append_str(pinfo->cinfo, COL_INFO, " (Message fragment)");
} else {
payload_tvb = body_tvb;
}
}
offset += body_len;
}
if (direction==DATA_CAM_TO_HOST) {
/* minimum length of an rtpdu status is 4 bytes */
if (tpdu_len-offset < 4) {
proto_tree_add_expert(trans_tree, pinfo, &ei_dvbci_r_tpdu_status_mandatory, tvb, 0, 0);
return;
}
status_len = dissect_dvbci_tpdu_status(
tvb, offset, pinfo, trans_tree, lpdu_tcid, hdr_tag);
if (status_len<0)
return;
proto_tree_set_appendix(trans_tree, tvb, offset, status_len);
}
if (payload_tvb)
dissect_dvbci_spdu(payload_tvb, pinfo, tree, direction, lpdu_tcid);
}
static void
dissect_dvbci_lpdu(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
guint8 direction)
{
proto_tree *link_tree;
guint32 payload_len;
guint8 tcid, more_last;
proto_item *pi;
tvbuff_t *payload_tvb;
fragment_head *frag_msg;
payload_len = tvb_reported_length(tvb);
col_set_str(pinfo->cinfo, COL_INFO, "LPDU");
link_tree = proto_tree_add_subtree(tree, tvb, 0, 2, ett_dvbci_link, NULL, "Link Layer");
tcid = tvb_get_guint8(tvb, 0);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ", "tcid %d", tcid);
proto_tree_add_item(link_tree, hf_dvbci_tcid, tvb, 0, 1, ENC_BIG_ENDIAN);
more_last = tvb_get_guint8(tvb, 1);
pi = proto_tree_add_item(link_tree, hf_dvbci_ml, tvb, 1, 1, ENC_BIG_ENDIAN);
if (try_val_to_str(more_last, dvbci_ml) == NULL) {
expert_add_info(pinfo, pi, &ei_dvbci_ml);
}
/* buf_size_host==0 -> we did not capture the buffer size negotiation */
if (buf_size_host!=0 && payload_len>buf_size_host) {
proto_tree_add_expert_format(link_tree, pinfo, &ei_dvbci_bad_length, tvb, 2, payload_len,
"Payload too large, maximum payload length is the negotiated buffer size (%d bytes)", buf_size_host);
}
frag_msg = fragment_add_seq_next(&tpdu_reassembly_table,
tvb, 2, pinfo, TPDU_SEQ_ID_BASE+tcid, NULL,
tvb_reported_length_remaining(tvb, 2),
more_last == ML_MORE ? 1 : 0);
payload_tvb = process_reassembled_data(tvb, 2, pinfo,
"Reassembled TPDU", frag_msg, &tpdu_frag_items,
NULL, link_tree);
if (!payload_tvb) {
if (more_last == ML_MORE) {
pinfo->fragmented = TRUE;
col_append_str(pinfo->cinfo, COL_INFO, " (Message fragment)");
} else
payload_tvb = tvb_new_subset_remaining(tvb, 2);
}
if (payload_tvb)
dissect_dvbci_tpdu(payload_tvb, pinfo, tree, direction, tcid);
}
/* dissect DVB-CI buffer size negotiation */
static void
dissect_dvbci_buf_neg(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
guint8 direction)
{
guint16 buf_size;
proto_item *pi;
buf_size = tvb_get_ntohs(tvb, 0);
col_add_fstr(pinfo->cinfo, COL_INFO, "%s: %u bytes",
direction == DATA_HOST_TO_CAM ?
"negotiated buffer size" : "buffer size proposal",
buf_size);
if (direction == DATA_HOST_TO_CAM) {
buf_size_host = buf_size;
pi = proto_tree_add_uint_format(tree, hf_dvbci_buf_size, tvb,
0, 2, buf_size,
"Negotiated buffer size: %u bytes", buf_size);
if (buf_size_host > buf_size_cam) {
/* ATTENTION:
wireshark may run through each packet multiple times
if we didn't check the direction, we'd get the error when
wireshark runs through the initial CAM packet for the 2nd time
*/
expert_add_info_format(pinfo, pi, &ei_dvbci_buf_size, "Illegal buffer size command. Host shall not request a buffer size larger than the CAM proposal");
}
}
else if (direction == DATA_CAM_TO_HOST) {
buf_size_cam = buf_size;
proto_tree_add_uint_format(tree, hf_dvbci_buf_size, tvb,
0, 2, buf_size,
"Buffer size proposal by the CAM: %u bytes", buf_size);
}
if (buf_size < 16) {
proto_tree_add_expert_format(tree, pinfo, &ei_dvbci_buf_size, tvb, 0, 2,
"Illegal buffer size, minimum buffer size is 16 bytes");
}
}
/* dissect Level 1 version/product information tuple's payload
data_tvb is a separate tvb for the tuple payload (without tag and len)
return the number of dissected bytes or -1 for error */
static gint
dissect_dvbci_cis_payload_tpll_v1(tvbuff_t *data_tvb,
packet_info *pinfo _U_, proto_tree *tree)
{
gint offset=0, offset_str_end;
/* the CIS is defined by PCMCIA, all multi-byte values are little endian
(the rest of DVB-CI is a big-endian protocol) */
proto_tree_add_item(tree, hf_dvbci_cis_tpll_v1_major,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_cis_tpll_v1_minor,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
/* manufacturer, name and additional infos are 0-terminated strings */
offset_str_end = tvb_find_guint8(data_tvb, offset, -1, 0x0);
if (offset_str_end<offset) /* offset_str_end==offset is ok */
return offset;
proto_tree_add_item(tree, hf_dvbci_cis_tpll_v1_info_manuf,
data_tvb, offset, offset_str_end-offset, ENC_ASCII|ENC_NA);
offset = offset_str_end+1; /* +1 for 0 termination */
offset_str_end = tvb_find_guint8(data_tvb, offset, -1, 0x0);
if (offset_str_end<offset)
return offset;
proto_tree_add_item(tree, hf_dvbci_cis_tpll_v1_info_name,
data_tvb, offset, offset_str_end-offset, ENC_ASCII|ENC_NA);
offset = offset_str_end+1;
/* the pc-card spec mentions two additional info strings,
it's unclear if both are mandatory
>1 because the last byte is the tuple end marker */
while (tvb_reported_length_remaining(data_tvb, offset)>1) {
offset_str_end = tvb_find_guint8(data_tvb, offset, -1, 0x0);
if (offset_str_end<offset)
break;
proto_tree_add_item(tree, hf_dvbci_cis_tpll_v1_info_additional,
data_tvb, offset, offset_str_end-offset, ENC_ASCII|ENC_NA);
offset = offset_str_end+1;
}
proto_tree_add_item(tree, hf_dvbci_cis_tpll_v1_end,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
return offset;
}
static gint
dissect_dvbci_cis_payload_config(tvbuff_t *data_tvb,
packet_info *pinfo _U_, proto_tree *tree)
{
gint offset = 0;
/* these are the actual sizes, the CIS stores rmsz-1 and rasz-1 */
guint8 rfsz, rmsz, rasz;
guint8 st_code, st_len;
const gchar *st_code_str;
proto_item *st_item = NULL;
proto_tree *st_tree = NULL;
guint8 stci_ifn_size; /* actual size, see comment above */
rfsz = (tvb_get_guint8(data_tvb, offset)&0xC0) >> 6;
proto_tree_add_item(tree, hf_dvbci_cis_tpcc_rfsz,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
rmsz = ((tvb_get_guint8(data_tvb, offset)&0x3C) >> 2) + 1;
proto_tree_add_item(tree, hf_dvbci_cis_tpcc_rmsz,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
rasz = (tvb_get_guint8(data_tvb, offset)&0x03) + 1;
proto_tree_add_item(tree, hf_dvbci_cis_tpcc_rasz,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_cis_tpcc_last,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
proto_tree_add_item(tree, hf_dvbci_cis_tpcc_radr,
data_tvb, offset, rasz, ENC_LITTLE_ENDIAN);
offset += rasz;
proto_tree_add_item(tree, hf_dvbci_cis_tpcc_rmsk,
data_tvb, offset, rmsz, ENC_NA);
offset += rmsz;
offset += rfsz; /* skip reserved bytes */
while (tvb_reported_length_remaining(data_tvb, offset) > 0) {
st_code = tvb_get_guint8(data_tvb, offset);
st_code_str = val_to_str_const(st_code, dvbci_cis_subtpl_code, "unknown");
st_tree = proto_tree_add_subtree_format(tree, data_tvb, offset, -1,
ett_dvbci_cis_subtpl, &st_item, "Subtuple: %s (0x%x)", st_code_str, st_code);
proto_tree_add_item(st_tree, hf_dvbci_cis_st_code,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
st_len = tvb_get_guint8(data_tvb, offset);
proto_item_set_len(st_item, 2+st_len); /* tag, len byte, body */
proto_tree_add_item(st_tree, hf_dvbci_cis_st_len,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
if (st_code == CCSTPL_CIF) {
stci_ifn_size = ((tvb_get_guint8(data_tvb, offset) & 0xC0)>>6)+1;
proto_tree_add_item(st_tree, hf_dvbci_cis_stci_ifn_size,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
/* don't increment offset,
size and actual value's LSB share the same byte */
proto_tree_add_item(st_tree, hf_dvbci_cis_stci_ifn,
data_tvb, offset, stci_ifn_size, ENC_LITTLE_ENDIAN);
offset += stci_ifn_size;
/* the stci_str field could consist of multiple strings,
this case is not supported for now */
proto_tree_add_item(st_tree, hf_dvbci_cis_stci_str,
data_tvb, offset, st_len-stci_ifn_size, ENC_ASCII|ENC_NA);
offset += st_len-stci_ifn_size;
}
else {
/* skip unknown subtuple's content */
offset += st_len;
}
}
return offset;
}
static gint
dissect_dvbci_cis_payload_cftable_entry(tvbuff_t *data_tvb,
packet_info *pinfo _U_, proto_tree *tree)
{
gint offset = 0;
gboolean intface_flag;
intface_flag = ((tvb_get_guint8(data_tvb, offset) & 0x80) == 0x80);
/* tpce_indx byte */
proto_tree_add_item(tree, hf_dvbci_cis_tpce_indx_intface,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_cis_tpce_indx_default,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_cis_tpce_indx_cnf_entry,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
if (intface_flag) {
/* tpce_if byte */
proto_tree_add_item(tree, hf_dvbci_cis_tpce_if_type,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
/* XXX parse other components of tpce_if */
offset++;
}
/* tpce_fs byte: this is present in any case */
proto_tree_add_item(tree, hf_dvbci_cis_tpce_fs_mem_space,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_cis_tpce_fs_irq,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_dvbci_cis_tpce_fs_io,
data_tvb, offset, 1, ENC_LITTLE_ENDIAN);
/* XXX parse other components of tpce_fs */
offset++;
return offset;
}
static void
dissect_dvbci_cis(tvbuff_t *tvb, gint offset,
packet_info *pinfo, proto_tree *tree)
{
gint offset_start;
proto_tree *cis_tree = NULL, *tpl_tree = NULL;
proto_item *ti_main, *ti_tpl;
guint8 tpl_code;
const gchar *tpl_code_str = NULL;
guint8 len_field;
tvbuff_t *tpl_data_tvb;
offset_start = offset;
cis_tree = proto_tree_add_subtree(tree, tvb, offset, -1,
ett_dvbci_cis, &ti_main, "Card Information Structure (CIS)");
do {
tpl_code = tvb_get_guint8(tvb, offset);
tpl_code_str = val_to_str_const(tpl_code, dvbci_cis_tpl_code, "unknown");
tpl_tree = proto_tree_add_subtree_format(cis_tree,
tvb, offset, -1, ett_dvbci_cis_tpl, &ti_tpl, "CIS tuple: %s", tpl_code_str);
proto_tree_add_uint_format(tpl_tree, hf_dvbci_cis_tpl_code,
tvb, offset, 1, tpl_code, "Tuple code: %s (0x%x)",
tpl_code_str, tpl_code);
offset++;
if (tpl_code == CISTPL_END) {
proto_item_set_len(ti_tpl, 1); /* only tag (no len and content) */
break;
}
len_field = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tpl_tree, hf_dvbci_cis_tpl_len,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
tpl_data_tvb = tvb_new_subset_length(tvb, offset, len_field);
switch (tpl_code) {
case CISTPL_VERS_1:
dissect_dvbci_cis_payload_tpll_v1(
tpl_data_tvb, pinfo, tpl_tree);
offset += len_field;
break;
case CISTPL_CONFIG:
dissect_dvbci_cis_payload_config(tpl_data_tvb, pinfo, tpl_tree);
offset += len_field;
break;
case CISTPL_CFTABLE_ENTRY:
dissect_dvbci_cis_payload_cftable_entry(
tpl_data_tvb, pinfo, tpl_tree);
offset += len_field;
break;
case CISTPL_MANFID:
proto_tree_add_item(tpl_tree, hf_dvbci_cis_tplmid_manf,
tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset+=2;
proto_tree_add_item(tpl_tree, hf_dvbci_cis_tplmid_card,
tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset+=2;
break;
default:
if (len_field>0) {
proto_tree_add_item(tpl_tree, hf_dvbci_cis_tpl_data,
tvb, offset, len_field, ENC_NA);
}
offset += len_field;
break;
}
proto_item_set_len(ti_tpl, 2+len_field); /* tag, len byte, content */
} while (tvb_reported_length_remaining(tvb, offset) > 0);
proto_item_set_len(ti_main, offset-offset_start);
}
static int
dissect_dvbci(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
{
gint packet_len, offset = 0, offset_ver, offset_evt, offset_len_field;
guint8 version, event;
const gchar *event_str;
guint16 len_field;
proto_item *ti;
proto_tree *dvbci_tree, *hdr_tree;
tvbuff_t *payload_tvb;
guint16 cor_addr;
guint8 cor_value;
proto_item *pi;
guint8 hw_event;
if (tvb_length(tvb) < 4)
return 0;
offset_ver = offset;
version = tvb_get_guint8(tvb, offset++);
if (version != 0)
return 0;
offset_evt = offset;
event = tvb_get_guint8(tvb, offset++);
event_str = try_val_to_str(event, dvbci_event);
if (!event_str)
return 0;
packet_len = tvb_reported_length(tvb);
offset_len_field = offset;
len_field = tvb_get_ntohs(tvb, offset);
if (len_field != (packet_len-4))
return 0;
offset += 2;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "DVB-CI");
col_set_str(pinfo->cinfo, COL_INFO, event_str);
ti = proto_tree_add_protocol_format(tree, proto_dvbci,
tvb, 0, packet_len, "DVB Common Interface: %s", event_str);
dvbci_tree = proto_item_add_subtree(ti, ett_dvbci);
hdr_tree = proto_tree_add_subtree(dvbci_tree, tvb, 0, offset, ett_dvbci_hdr, NULL, "Pseudo header");
proto_tree_add_text(hdr_tree, tvb, offset_ver, 1, "Version: %d", version);
proto_tree_add_item(hdr_tree, hf_dvbci_event, tvb, offset_evt, 1, ENC_BIG_ENDIAN);
proto_tree_add_text(hdr_tree, tvb, offset_len_field, 2,
"Length field: %d", len_field);
if (IS_DATA_TRANSFER(event)) {
dvbci_set_addrs(event, pinfo);
payload_tvb = tvb_new_subset_remaining( tvb, offset);
if (len_field == 2) {
dissect_dvbci_buf_neg(payload_tvb, pinfo, dvbci_tree, event);
}
else {
dissect_dvbci_lpdu(payload_tvb, pinfo, dvbci_tree, event);
}
}
else if (event==DVBCI_EVT_COR_WRITE) {
/* PCAP format for DVB-CI defines COR address as big endian */
pi = proto_tree_add_item(dvbci_tree, hf_dvbci_cor_addr,
tvb, offset, 2, ENC_BIG_ENDIAN);
cor_addr = tvb_get_ntohs(tvb, offset);
if (cor_addr == 0xFFFF) {
proto_item_append_text(pi, " (COR address is unknown)");
col_append_sep_str(pinfo->cinfo, COL_INFO, ": ", "unknown address");
}
else if (cor_addr > 0xFFE) {
expert_add_info(pinfo, pi, &ei_dvbci_cor_addr);
}
else {
col_append_sep_fstr(pinfo->cinfo, COL_INFO, ": ",
"address 0x%x", cor_addr);
}
offset += 2;
cor_value = tvb_get_guint8(tvb, offset);
proto_tree_add_item(dvbci_tree, hf_dvbci_cor_val,
tvb, offset, 1, ENC_BIG_ENDIAN);
col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
"value 0x%x", cor_value);
}
else if (event==DVBCI_EVT_CIS_READ) {
dissect_dvbci_cis(tvb, offset, pinfo, dvbci_tree);
}
else if (event==DVBCI_EVT_HW_EVT) {
hw_event = tvb_get_guint8(tvb, offset);
col_set_str(pinfo->cinfo, COL_INFO,
val_to_str_const(hw_event, dvbci_hw_event, "Invalid hardware event"));
proto_tree_add_item(dvbci_tree, hf_dvbci_hw_event,
tvb, offset, 1, ENC_BIG_ENDIAN);
}
return packet_len;
}
void
proto_register_dvbci(void)
{
guint i;
module_t *dvbci_module;
expert_module_t* expert_dvbci;
static gint *ett[] = {
&ett_dvbci,
&ett_dvbci_hdr,
&ett_dvbci_cis,
&ett_dvbci_cis_tpl,
&ett_dvbci_cis_subtpl,
&ett_dvbci_link,
&ett_dvbci_link_frag,
&ett_dvbci_link_frags,
&ett_dvbci_transport,
&ett_dvbci_transport_frag,
&ett_dvbci_transport_frags,
&ett_dvbci_session,
&ett_dvbci_res,
&ett_dvbci_application,
&ett_dvbci_es,
&ett_dvbci_ca_desc,
&ett_dvbci_text,
&ett_dvbci_cc_item,
&ett_dvbci_sac_msg_body,
&ett_dvbci_ami_req_types,
&ett_dvbci_lsc_conn_desc,
&ett_dvbci_opp_cap_loop,
&ett_dvbci_dlv_sys_hint
};
static hf_register_info hf[] = {
{ &hf_dvbci_event,
{ "Event", "dvb-ci.event",
FT_UINT8, BASE_HEX, VALS(dvbci_event), 0, NULL, HFILL }
},
{ &hf_dvbci_hw_event,
{ "Hardware event", "dvb-ci.hw_event",
FT_UINT8, BASE_HEX, VALS(dvbci_hw_event), 0, NULL, HFILL }
},
{ &hf_dvbci_cor_addr,
{ "COR address", "dvb-ci.cor_address",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cor_val,
{ "COR value", "dvb-ci.cor_value",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpl_code,
{ "CIS tuple code", "dvb-ci.cis.tpl_code",
FT_UINT8, BASE_HEX, VALS(dvbci_cis_tpl_code), 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpl_len,
{ "Length field", "dvb-ci.cis.tpl_len",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpl_data,
{ "Tuple data", "dvb-ci.cis.tpl_data",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpll_v1_major,
{ "Major version number", "dvb-ci.cis.tpll_v1_major",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpll_v1_minor,
{ "Minor version number", "dvb-ci.cis.tpll_v1_minor",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpll_v1_info_manuf,
{ "Manufacturer", "dvb-ci.cis.tpll_v1_info.manufacturer",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpll_v1_info_name,
{ "Name", "dvb-ci.cis.tpll_v1_info.name",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpll_v1_info_additional,
{ "Additional info", "dvb-ci.cis.tpll_v1_info.additional",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpll_v1_end,
{ "End of chain", "dvb-ci.cis.tpll_v1_end",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpcc_rfsz,
{ "Size of reserved area", "dvb-ci.cis.tpcc_rfsz",
FT_UINT8, BASE_HEX, NULL, 0xC0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpcc_rmsz,
{ "Size of TPCC_RMSK field - 1", "dvb-ci.cis.tpcc_rmsz",
FT_UINT8, BASE_HEX, NULL, 0x3C, NULL, HFILL }
},
{ &hf_dvbci_cis_tpcc_rasz,
{ "Size of TPCC_RADR - 1", "dvb-ci.cis.tpcc_rasz",
FT_UINT8, BASE_HEX, NULL, 0x03, NULL, HFILL }
},
{ &hf_dvbci_cis_tpcc_last,
{ "Index of the last cftable entry", "dvb-ci.cis.tpcc_last",
FT_UINT8, BASE_HEX, NULL, 0x3F, NULL, HFILL }
},
{ &hf_dvbci_cis_tpcc_radr,
{ "COR base address", "dvb-ci.cis.tpcc_radr",
FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpcc_rmsk,
{ "Configuration register presence mask", "dvb-ci.cis.tpcc_rmsk",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_st_code,
{ "Subtuple tag", "dvb-ci.cis.st_code",
FT_UINT8, BASE_HEX, VALS(dvbci_cis_subtpl_code), 0, NULL, HFILL }
},
{ &hf_dvbci_cis_st_len,
{ "Subtuple length", "dvb-ci.cis.st_len",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_stci_ifn_size,
{ "Size of interface ID number - 1", "dvb-ci.cis.stci_ifn_size",
FT_UINT8, BASE_HEX, NULL, 0xC0, NULL, HFILL }
},
{ &hf_dvbci_cis_stci_ifn,
{ "Interface ID number", "dvb-ci.cis.stci_ifn",
FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_stci_str,
{ "Interface description strings", "dvb-ci.cis.stci_str",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tpce_indx_intface,
{ "Intface", "dvb-ci.cis.tpce_indx.intface",
FT_UINT8, BASE_HEX, NULL, 0x80, NULL, HFILL }
},
{ &hf_dvbci_cis_tpce_indx_default,
{ "Default", "dvb-ci.cis.tpce_indx.default",
FT_UINT8, BASE_HEX, NULL, 0x40, NULL, HFILL }
},
{ &hf_dvbci_cis_tpce_indx_cnf_entry,
{ "Configuration entry number", "dvb-ci.cis.tpce_indx.cnf_entry",
FT_UINT8, BASE_HEX, NULL, 0x3F, NULL, HFILL }
},
{ &hf_dvbci_cis_tpce_if_type,
{ "Interface type", "dvb-ci.cis.tpce_if.type", FT_UINT8, BASE_HEX,
VALS(dvbci_cis_tpce_if_type), 0x0F, NULL, HFILL }
},
{ &hf_dvbci_cis_tpce_fs_mem_space,
{ "Mem space", "dvb-ci.cis.tpce_fs.mem_space",
FT_UINT8, BASE_HEX, NULL, 0x60, NULL, HFILL }
},
{ &hf_dvbci_cis_tpce_fs_irq,
{ "IRQ", "dvb-ci.cis.tpce_fs.irq",
FT_UINT8, BASE_HEX, NULL, 0x10, NULL, HFILL }
},
{ &hf_dvbci_cis_tpce_fs_io,
{ "IO Space", "dvb-ci.cis.tpce_fs.io",
FT_UINT8, BASE_HEX, NULL, 0x08, NULL, HFILL }
},
{ &hf_dvbci_cis_tplmid_manf,
{ "PC Card manufacturer code", "dvb-ci.cis.tplmid_manf",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cis_tplmid_card,
{ "Manufacturer info", "dvb-ci.cis.tplmid_card",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_buf_size,
{ "Buffer Size", "dvb-ci.buf_size",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_tcid,
{ "Transport Connection ID", "dvb-ci.tcid",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_ml,
{ "More/Last indicator", "dvb-ci.more_last",
FT_UINT8, BASE_HEX, VALS(dvbci_ml), 0, NULL, HFILL }
},
/* on the link layer, tpdus are reassembled */
{ &hf_dvbci_l_frags,
{ "Tpdu fragments", "dvb-ci.tpdu_fragments",
FT_NONE, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_l_frag,
{ "Tpdu fragment", "dvb-ci.tpdu_fragment",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_l_frag_overlap,
{ "Tpdu fragment overlap", "dvb-ci.tpdu_fragment.overlap",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_l_frag_overlap_conflicts,
{ "Tpdu fragment overlapping with conflicting data",
"dvb-ci.tpdu_fragment.overlap.conflicts",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_l_frag_multiple_tails,
{ "Tpdu has multiple tail fragments",
"dvb-ci.tpdu_fragment.multiple_tails",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_l_frag_too_long_frag,
{ "Tpdu fragment too long", "dvb-ci.tpdu_fragment.too_long_fragment",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_l_frag_err,
{ "Tpdu defragmentation error", "dvb-ci.tpdu_fragment.error",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_l_frag_cnt,
{ "Tpdu fragment count", "dvb-ci.tpdu_fragment.count",
FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_l_reass_in,
{ "Tpdu reassembled in", "dvb-ci.tpdu_reassembled.in",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_l_reass_len,
{ "Reassembled tpdu length", "dvb-ci.tpdu_reassembled.length",
FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_c_tpdu_tag,
{ "Command TPDU Tag", "dvb-ci.c_tpdu_tag",
FT_UINT8, BASE_HEX, VALS(dvbci_c_tpdu), 0, NULL, HFILL }
},
{ &hf_dvbci_r_tpdu_tag,
{ "Response TPDU Tag", "dvb-ci.r_tpdu_tag",
FT_UINT8, BASE_HEX, VALS(dvbci_r_tpdu), 0, NULL, HFILL }
},
{ &hf_dvbci_t_c_id,
{ "Transport Connection ID", "dvb-ci.t_c_id",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sb_value,
{ "SB Value", "dvb-ci.sb_value", FT_UINT8, BASE_HEX,
VALS(dvbci_sb_value), 0, NULL, HFILL } },
/* on the transport layer, spdus are reassembled */
{ &hf_dvbci_t_frags,
{ "Spdu fragments", "dvb-ci.spdu_fragments",
FT_NONE, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_t_frag,
{ "Spdu fragment", "dvb-ci.spdu_fragment",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_t_frag_overlap,
{ "Spdu fragment overlap", "dvb-ci.spdu_fragment.overlap",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_t_frag_overlap_conflicts,
{ "Spdu fragment overlapping with conflicting data",
"dvb-ci.tpdu_fragment.overlap.conflicts",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_t_frag_multiple_tails,
{ "Spdu has multiple tail fragments",
"dvb-ci.spdu_fragment.multiple_tails",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_t_frag_too_long_frag,
{ "Spdu fragment too long", "dvb-ci.spdu_fragment.too_long_fragment",
FT_BOOLEAN, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_t_frag_err,
{ "Spdu defragmentation error", "dvb-ci.spdu_fragment.error",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_t_frag_cnt,
{ "Spdu fragment count", "dvb-ci.spdu_fragment.count",
FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_t_reass_in,
{ "Spdu reassembled in", "dvb-ci.spdu_reassembled.in",
FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_t_reass_len,
{ "Reassembled spdu length", "dvb-ci.spdu_reassembled.length",
FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }
},
{ &hf_dvbci_spdu_tag,
{ "SPDU Tag", "dvb-ci.spdu_tag",
FT_UINT8, BASE_HEX, VALS(dvbci_spdu_tag), 0, NULL, HFILL }
},
{ &hf_dvbci_sess_status,
{ "Session Status", "dvb-ci.session_status",
FT_UINT8, BASE_HEX, VALS(dvbci_sess_status), 0, NULL, HFILL }
},
{ &hf_dvbci_sess_nb,
{ "Session Number", "dvb-ci.session_nb",
FT_UINT16, BASE_DEC, NULL , 0, NULL, HFILL }
},
{ &hf_dvbci_close_sess_status,
{ "Session Status", "dvb-ci.close_session_status",
FT_UINT8, BASE_HEX, VALS(dvbci_close_sess_status), 0, NULL, HFILL }
},
{ &hf_dvbci_res_id_type,
{ "Resource ID Type", "dvb-ci.res.id_type",
FT_UINT32, BASE_HEX, NULL, RES_ID_TYPE_MASK, NULL, HFILL }
},
{ &hf_dvbci_res_class,
{ "Resource Class", "dvb-ci.res.class",
FT_UINT32, BASE_HEX, VALS(dvbci_res_class), RES_CLASS_MASK, NULL, HFILL }
},
{ &hf_dvbci_res_type,
{ "Resource Type", "dvb-ci.res.type",
FT_UINT32, BASE_HEX, NULL, RES_TYPE_MASK, NULL, HFILL }
},
{ &hf_dvbci_res_ver,
{ "Resource Version", "dvb-ci.res.version",
FT_UINT32, BASE_HEX, NULL, RES_VER_MASK, NULL, HFILL }
},
{ &hf_dvbci_apdu_tag,
{ "APDU Tag", "dvb-ci.apdu_tag",
FT_UINT24, BASE_HEX, VALS(dvbci_apdu_tag), 0, NULL, HFILL }
},
{ &hf_dvbci_app_type,
{ "Application type", "dvb-ci.ap.type",
FT_UINT8, BASE_HEX, VALS(dvbci_app_type), 0, NULL, HFILL }
},
{ &hf_dvbci_app_manf,
{ "Application manufacturer", "dvb-ci.ap.manufacturer",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_manf_code,
{ "Manufacturer code", "dvb-ci.ap.manufacturer_code",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_menu_str_len,
{ "Menu string length", "dvb-ci.ap.menu_string_length",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_ap_char_tbl,
{ "Character table", "dvb-ci.ap.menu_char_tbl",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL}
},
{ &hf_dvbci_menu_str,
{ "Menu string", "dvb-ci.ap.menu_string",
FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_data_rate,
{ "Transport stream data rate supported by the host",
"dvb-ci.ap.data_rate",
FT_UINT8, BASE_HEX, VALS(dvbci_data_rate), 0, NULL, HFILL }
},
{ &hf_dvbci_ca_sys_id,
{ "CA system ID", "dvb-ci.ca.ca_system_id",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_ca_pmt_list_mgmt,
{ "CA PMT list management", "dvb-ci.ca.ca_pmt_list_management",
FT_UINT8, BASE_HEX, VALS(dvbci_ca_pmt_list_mgmt), 0, NULL,
HFILL }
},
{ &hf_dvbci_prog_num,
{ "Program number", "dvb-ci.ca.program_number",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_prog_info_len,
{ "Program info length", "dvb-ci.ca.program_info_length",
FT_UINT16, BASE_HEX, NULL, 0x0FFF, NULL, HFILL }
},
{ &hf_dvbci_stream_type,
{ "Stream type", "dvb-ci.ca.stream_type", FT_UINT8,
BASE_HEX|BASE_EXT_STRING, &mpeg_pmt_stream_type_vals_ext,
0, NULL, HFILL }
},
{ &hf_dvbci_es_pid,
{ "Elementary stream PID", "dvb-ci.ca.elementary_pid",
FT_UINT16, BASE_HEX, NULL, 0x1FFF, NULL, HFILL }
},
{ &hf_dvbci_es_info_len,
{ "Elementary stream info length", "dvb-ci.ca.es_info_length",
FT_UINT16, BASE_HEX, NULL, 0x0FFF, NULL, HFILL }
},
{ &hf_dvbci_ca_pmt_cmd_id,
{ "CA PMT command ID", "dvb-ci.ca.ca_pmt_cmd_id",
FT_UINT8, BASE_HEX, VALS(dvbci_ca_pmt_cmd_id), 0, NULL, HFILL }
},
{ &hf_dvbci_descr_len,
{ "CA descriptor length", "dvb-ci.ca.ca_desc_len",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_ca_pid,
{ "CA PID", "dvb-ci.ca.ca_pid",
FT_UINT16, BASE_HEX, NULL, 0x1FFF, NULL, HFILL }
},
{ &hf_dvbci_ca_enable_flag,
{ "CA enable flag", "dvb-ci.ca.ca_enable_flag",
FT_UINT8, BASE_HEX, NULL, 0x80, NULL, HFILL }
},
{ &hf_dvbci_ca_enable,
{ "CA enable", "dvb-ci.ca.ca_enable",
FT_UINT8, BASE_HEX, VALS(dvbci_ca_enable), 0x7F, NULL, HFILL }
},
{ &hf_dvbci_auth_proto_id,
{ "Authentication protocol ID", "dvb-ci.aut.proto_id",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_auth_req_bytes,
{ "Authentication request data", "dvb-ci.aut.req",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_auth_resp_bytes,
{ "Authentication response data", "dvb-ci.aut.resp",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_network_id,
{ "Network ID", "dvb-ci.hc.nid",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_original_network_id,
{ "Original network ID", "dvb-ci.hc.onid",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_transport_stream_id,
{ "Transport stream ID", "dvb-ci.hc.tsid",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_service_id,
{ "Service ID", "dvb-ci.hc.svcid",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_replacement_ref,
{ "Replacement reference", "dvb-ci.hc.replacement_ref",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_replaced_pid,
{ "Replaced PID", "dvb-ci.hc.replaced_pid",
FT_UINT16, BASE_HEX, NULL, 0x1FFF, NULL, HFILL }
},
{ &hf_dvbci_replacement_pid,
{ "Replacement PID", "dvb-ci.hc.replacement_pid",
FT_UINT16, BASE_HEX, NULL, 0x1FFF, NULL, HFILL }
},
{ &hf_dvbci_pmt_flag,
{ "PMT flag", "dvb-ci.hc.pmt_flag",
FT_UINT8, BASE_HEX, NULL, 0x01, NULL, HFILL }
},
{ &hf_dvbci_hc_desc_loop_len,
{ "Descriptor loop length", "dvb-ci.hc.desc_loop_len",
FT_UINT16, BASE_DEC, NULL, 0x0FFF, NULL, HFILL }
},
{ &hf_dvbci_hc_status,
{ "Status field", "dvb-ci.hc.status_field",
FT_UINT8, BASE_HEX, VALS(dvbci_hc_status), 0, NULL, HFILL }
},
{ &hf_dvbci_hc_release_reply,
{ "Release reply", "dvb-ci.hc.release_reply",
FT_UINT8, BASE_HEX, VALS(dvbci_hc_release_reply), 0, NULL, HFILL }
},
{ &hf_dvbci_resp_intv,
{ "Response interval", "dvb-ci.dt.resp_interval",
FT_RELATIVE_TIME, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_utc_time,
{ "UTC time", "dvb-ci.dt.utc_time",
FT_ABSOLUTE_TIME, ABSOLUTE_TIME_UTC, NULL, 0, NULL, HFILL }
},
/* we have to use FT_INT16 instead of FT_RELATIVE_TIME,
local offset can be negative */
{ &hf_dvbci_local_offset,
{ "Local time offset", "dvb-ci.dt.local_offset",
FT_INT16, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_close_mmi_cmd_id,
{ "Command ID", "dvb-ci.mmi.close_mmi_cmd_id",
FT_UINT8, BASE_HEX, VALS(dvbci_close_mmi_cmd_id), 0, NULL, HFILL }
},
{ &hf_dvbci_close_mmi_delay,
{ "Delay (in sec)", "dvb-ci.mmi.delay",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_disp_ctl_cmd,
{ "Command", "dvb-ci.mmi.disp_ctl_cmd",
FT_UINT8, BASE_HEX, VALS(dvbci_disp_ctl_cmd), 0, NULL, HFILL }
},
{ &hf_dvbci_mmi_mode,
{ "MMI mode", "dvb-ci.mmi.mode",
FT_UINT8, BASE_HEX, VALS(dvbci_mmi_mode), 0, NULL, HFILL }
},
{ &hf_dvbci_disp_rep_id,
{ "Reply ID", "dvb-ci.mmi.disp_rep_id",
FT_UINT8, BASE_HEX, VALS(dvbci_disp_rep_id), 0, NULL, HFILL }
},
{ &hf_dvbci_mmi_char_tbl,
{ "Character table", "dvb-ci.mmi.char_tbl",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL}
},
{ &hf_dvbci_blind_ans,
{ "Blind answer flag", "dvb-ci.mmi.blind_ans",
FT_UINT8, BASE_HEX, VALS(dvbci_blind_ans), 0x01, NULL, HFILL }
},
{ &hf_dvbci_ans_txt_len,
{ "Answer text length", "dvb-ci.mmi.ans_txt_len",
FT_UINT8, BASE_DEC, NULL , 0, NULL, HFILL }
},
{ &hf_dvbci_enq,
{ "Enquiry string", "dvb-ci.mmi.enq",
FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_ans_id,
{ "Answer ID", "dvb-ci.mmi.ans_id",
FT_UINT8, BASE_HEX, VALS(dvbci_ans_id) , 0, NULL, HFILL }
},
{ &hf_dvbci_ans,
{ "Answer", "dvb-ci.mmi.ans",
FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_choice_nb,
{ "Number of menu items", "dvb-ci.mmi.choice_nb",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_choice_ref,
{ "Selected item", "dvb-ci.mmi.choice_ref",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_item_nb,
{ "Number of list items", "dvb-ci.mmi.item_nb",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_title,
{ "Title", "dvb-ci.mmi.title",
FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_subtitle,
{ "Sub-title", "dvb-ci.mmi.subtitle",
FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_bottom,
{ "Bottom line", "dvb-ci.mmi.bottom",
FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_item,
{ "Item", "dvb-ci.mmi.item",
FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_host_country,
{ "Host country", "dvb-ci.hlc.country",
FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_host_language,
{ "Host language", "dvb-ci.hlc.language",
FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cup_type,
{ "CAM upgrade type", "dvb-ci.cup.type",
FT_UINT8, BASE_HEX, VALS(dvbci_cup_type), 0, NULL, HFILL }
},
{ &hf_dvbci_cup_download_time,
{ "Download time", "dvb-ci.cup.download_time",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cup_answer,
{ "CAM upgrade answer", "dvb-ci.cup.answer",
FT_UINT8, BASE_HEX, VALS(dvbci_cup_answer), 0, NULL, HFILL }
},
{ &hf_dvbci_cup_progress,
{ "CAM upgrade progress", "dvb-ci.cup.progress",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cup_reset,
{ "requested CAM reset", "dvb-ci.cup.reset",
FT_UINT8, BASE_HEX, VALS(dvbci_cup_reset), 0, NULL, HFILL }
},
{ &hf_dvbci_cc_sys_id_bitmask,
{ "CC system id bitmask", "dvb-ci.cc.sys_id_bitmask",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cc_dat_id,
{ "CC datatype id", "dvb-ci.cc.datatype_id",
FT_UINT8, BASE_HEX, VALS(dvbci_cc_dat_id), 0, NULL, HFILL }
},
{ &hf_dvbci_brand_cert,
{ "Brand certificate", "dvb-ci.cc.brand_cert",
FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_dvbci_dev_cert,
{ "Device certificate", "dvb-ci.cc.dev_cert",
FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_dvbci_uri_ver,
{ "URI version", "dvb-ci.cc.uri.version",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_uri_aps,
{ "APS", "dvb-ci.cc.uri.aps",
FT_UINT8, BASE_HEX, NULL, 0xC0, NULL, HFILL }
},
{ &hf_dvbci_uri_emi,
{ "EMI", "dvb-ci.cc.uri.emi",
FT_UINT8, BASE_HEX, VALS(dvbci_cc_uri_emi), 0x30, NULL, HFILL }
},
{ &hf_dvbci_uri_ict,
{ "Image constraint token", "dvb-ci.cc.uri.ict",
FT_UINT8, BASE_HEX, NULL, 0x08, NULL, HFILL }
},
{ &hf_dvbci_uri_rct,
{ "Redistribution control trigger (RCT)", "dvb-ci.cc.uri.rct",
FT_UINT8, BASE_HEX, NULL, 0x04, NULL, HFILL }
},
{ &hf_dvbci_uri_dot,
{ "Digital only token (DOT)", "dvb-ci.cc.uri.dot",
FT_UINT8, BASE_HEX, NULL, 0x01, NULL, HFILL }
},
/* retention limit is 6bit in URIv1 and 8bit in URIv2 and later
the position depends on the version, we can't define a mask here */
{ &hf_dvbci_uri_rl,
{ "Retention limit", "dvb-ci.cc.uri.rl",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cc_key_register,
{ "Key register", "dvb-ci.cc.key_register",
FT_UINT8, BASE_HEX, VALS(dvbci_cc_key_register), 0, NULL, HFILL }
},
{ &hf_dvbci_cc_status_field,
{ "Status field", "dvb-ci.cc.status_field",
FT_UINT8, BASE_HEX, VALS(dvbci_cc_status), 0, NULL, HFILL }
},
{ &hf_dvbci_cc_op_mode,
{ "Operating mode", "dvb-ci.cc.op_mode",
FT_UINT8, BASE_HEX, VALS(dvbci_cc_op_mode), 0, NULL, HFILL }
},
{ &hf_dvbci_cc_data,
{ "Data", "dvb-ci.cc.data",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sac_msg_ctr,
{ "Message counter", "dvb-ci.cc.sac.msg_ctr",
FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sac_proto_ver,
{ "Protocol version", "dvb-ci.cc.sac.proto_ver",
FT_UINT8, BASE_HEX, NULL, 0xF0, NULL, HFILL }
},
{ &hf_dvbci_sac_auth_cip,
{ "Authentication cipher", "dvb-ci.cc.sac.auth_cip",
FT_UINT8, BASE_HEX, VALS(dvbci_cc_sac_auth), 0x0E, NULL, HFILL }
},
{ &hf_dvbci_sac_payload_enc,
{ "Payload encryption flag", "dvb-ci.cc.sac.payload_enc",
FT_UINT8, BASE_HEX, NULL, 0x01, NULL, HFILL }
},
{ &hf_dvbci_sac_enc_cip,
{ "Encryption cipher", "dvb-ci.cc.sac.enc_cip",
FT_UINT8, BASE_HEX, VALS(dvbci_cc_sac_enc), 0xE0, NULL, HFILL }
},
{ &hf_dvbci_sac_payload_len,
{ "Payload length", "dvb-ci.cc.sac.payload_len",
FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sac_enc_body,
{ "Encrypted SAC body", "dvb-ci.cc.sac.enc_body",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sac_padding,
{ "Padding", "dvb-ci.cc.sac.padding",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sac_signature,
{ "Signature", "dvb-ci.cc.sac.signature",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_rating,
{ "Rating", "dvb-ci.cc.rating",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_capability_field,
{ "Capability field", "dvb-ci.cc.capability_field",
FT_UINT8, BASE_HEX, VALS(dvbci_cc_cap), 0, NULL, HFILL }
},
{ &hf_dvbci_pin_chg_time,
{ "PIN change time (UTC)", "dvb-ci.cc.pin_change_time",
FT_ABSOLUTE_TIME, ABSOLUTE_TIME_UTC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_pincode_status,
{ "Pincode status field", "dvb-ci.cc.pincode_status_field",
FT_UINT8, BASE_HEX, VALS(dvbci_pincode_status), 0, NULL, HFILL }
},
{ &hf_dvbci_cc_prog_num,
{ "Program number", "dvb-ci.cc.program_number",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_pin_evt_time,
{ "PIN event time (UTC)", "dvb-ci.cc.pin_event_time",
FT_ABSOLUTE_TIME, ABSOLUTE_TIME_UTC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_pin_evt_cent,
{ "PIN event time centiseconds", "dvb-ci.cc.pin_event_time_centi",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cc_priv_data,
{ "Private data", "dvb-ci.cc.private_data",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_pincode,
{ "PIN code", "dvb-ci.cc.pincode",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_app_dom_id,
{ "Application Domain Identifier", "dvb-ci.ami.app_dom_id",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_init_obj,
{ "Initial Object", "dvb-ci.ami.init_obj",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_ack_code,
{ "Acknowledgement", "dvb-ci.ami.ack_code",
FT_UINT8, BASE_HEX, VALS(dvbci_ack_code), 0, NULL, HFILL }
},
{ &hf_dvbci_req_type,
{ "Request type", "dvb-ci.ami.req_type",
FT_UINT8, BASE_HEX, VALS(dvbci_req_type), 0, NULL, HFILL }
},
{ &hf_dvbci_file_hash,
{ "File hash", "dvb-ci.ami.file_hash",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_file_name,
{ "File name", "dvb-ci.ami.file_name",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_ami_priv_data,
{ "Private data", "dvb-ci.ami.private_data",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_req_ok,
{ "RequestOK", "dvb-ci.ami.request_ok",
FT_UINT8, BASE_HEX, NULL, 0x02, NULL, HFILL }
},
{ &hf_dvbci_file_ok,
{ "FileOK", "dvb-ci.ami.file_ok",
FT_UINT8, BASE_HEX, NULL, 0x01, NULL, HFILL }
},
{ &hf_dvbci_file_data,
{ "File data", "dvb-ci.ami.file_data",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_abort_req_code,
{ "Abort request code", "dvb-ci.ami.abort_req_code",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_abort_ack_code,
{ "Abort acknowledgement code", "dvb-ci.ami.abort_ack_code",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_phase_id,
{ "Phase ID", "dvb-ci.lsc.comms_phase_id",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_comms_rep_id,
{ "Comms reply ID", "dvb-ci.lsc.comms_reply_id",
FT_UINT8, BASE_HEX, VALS(dvbci_comms_rep_id), 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_buf_size,
{ "Buffer size", "dvb-ci.lsc.buf_size",
FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_ret_val,
{ "Return value", "dvb-ci.lsc.return_value",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_comms_cmd_id,
{ "Comms command ID", "dvb-ci.lsc.comms_cmd_id",
FT_UINT8, BASE_HEX, VALS(dvbci_comms_cmd_id), 0, NULL, HFILL }
},
{ &hf_dvbci_conn_desc_type,
{ "Type", "dvb-ci.lsc.conn_desc_type",
FT_UINT8, BASE_HEX, VALS(dvbci_conn_desc_type), 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_media_tag,
{ "Tag", "dvb-ci.lsc.media_tag",
FT_UINT8, BASE_HEX, VALS(dvbci_lsc_desc_tag), 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_media_len,
{ "Length", "dvb-ci.lsc.media_len",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_ip_ver,
{ "IP version", "dvb-ci.lsc.ip_version",
FT_UINT8, BASE_DEC, VALS(dvbci_lsc_ip_ver), 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_ipv4_addr,
{ "IP address", "dvb-ci.lsc.ipv4_addr",
FT_IPv4, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_ipv6_addr,
{ "IPv6 address", "dvb-ci.lsc.ipv6_addr",
FT_IPv6, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_dst_port,
{ "Destination port", "dvb-ci.lsc.dst_port",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_proto,
{ "Protocol", "dvb-ci.lsc.protocol",
FT_UINT8, BASE_HEX, VALS(dvbci_lsc_proto), 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_hostname,
{ "Hostname", "dvb-ci.lsc.hostname",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_retry_count,
{ "Retry count", "dvb-ci.lsc.retry_count",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_lsc_timeout,
{ "Timeout", "dvb-ci.lsc.timeout",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
/* filter string for hf_dvbci_info_ver_op_status and
* hf_dvbci_info_ver_op_info below is the same, it seems this is ok */
{ &hf_dvbci_info_ver_op_status,
{ "Info version", "dvb-ci.opp.info_ver",
FT_UINT8, BASE_HEX, NULL, 0xE0, NULL, HFILL }
},
{ &hf_dvbci_nit_ver,
{ "NIT version", "dvb-ci.opp.nit_ver",
FT_UINT8, BASE_HEX, NULL, 0x1F, NULL, HFILL }
},
{ &hf_dvbci_pro_typ,
{ "Profile type", "dvb-ci.opp.profile_type",
FT_UINT8, BASE_HEX, NULL, 0xC0, NULL, HFILL }
},
{ &hf_dvbci_init_flag,
{ "Initialized flag", "dvb-ci.opp.init_flag",
FT_UINT8, BASE_HEX, NULL, 0x20, NULL, HFILL }
},
{ &hf_dvbci_ent_chg_flag,
{ "Entitlement change flag", "dvb-ci.opp.ent_chg_flag",
FT_UINT8, BASE_HEX, NULL, 0x10, NULL, HFILL }
},
{ &hf_dvbci_ent_val_flag,
{ "Entitlement valid flag", "dvb-ci.opp.ent_val_flag",
FT_UINT8, BASE_HEX, NULL, 0x08, NULL, HFILL }
},
{ &hf_dvbci_ref_req_flag,
{ "Refresh request flag", "dvb-ci.opp.refresh_req_flag",
FT_UINT8, BASE_HEX, VALS(dvbci_opp_ref_req_flag), 0x03, NULL, HFILL }
},
{ &hf_dvbci_err_flag,
{ "Error flag", "dvb-ci.opp.err_flag",
FT_UINT8, BASE_HEX, VALS(dvbci_opp_err_flag), 0xF0, NULL, HFILL }
},
{ &hf_dvbci_dlv_sys_hint,
{ "Delivery system hint", "dvb-ci.opp.dlv_sys_hint",
FT_UINT8, BASE_HEX, NULL, 0x0F, NULL, HFILL }
},
{ &hf_dvbci_dlv_sys_hint_t,
{ "terrestrial network (DVB-T/T2)", "dvb-ci.opp.dlv_sys_hint.t",
FT_BOOLEAN, 4, TFS(&tfs_set_notset), 0x04, NULL, HFILL }
},
{ &hf_dvbci_dlv_sys_hint_s,
{ "satellite network (DVB-S/S2)", "dvb-ci.opp.dlv_sys_hint.s",
FT_BOOLEAN, 4, TFS(&tfs_set_notset), 0x02, NULL, HFILL }
},
{ &hf_dvbci_dlv_sys_hint_c,
{ "cable network (DVB-C/C2)", "dvb-ci.opp.dlv_sys_hint.c",
FT_BOOLEAN, 4, TFS(&tfs_set_notset), 0x01, NULL, HFILL }
},
{ &hf_dvbci_refr_req_date,
{ "Refresh request date", "dvb-ci.opp.refresh_req_date",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_refr_req_time,
{ "Refresh request time", "dvb-ci.opp.refresh_req_time",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_nit_loop_len,
{ "NIT loop length", "dvb-ci.opp.nit_loop_len",
FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_info_valid,
{ "Info valid", "dvb-ci.opp.info_valid",
FT_UINT8, BASE_HEX, NULL, 0x08, NULL, HFILL }
},
{ &hf_dvbci_info_ver_op_info,
{ "Info version", "dvb-ci.opp.info_ver",
FT_UINT8, BASE_HEX, NULL, 0x07, NULL, HFILL }
},
{ &hf_dvbci_cicam_onid,
{ "CICAM original network id", "dvb-ci.opp.cicam_onid",
FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_cicam_id,
{ "CICAM ID", "dvb-ci.opp.cicam_id",
FT_UINT32, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_opp_char_tbl,
{ "Character table", "dvb-ci.opp.char_tbl",
FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL}
},
{ &hf_dvbci_sdt_rst_trusted,
{ "SDT running status trusted", "dvb-ci.opp.sdt_rst_trusted",
FT_UINT8, BASE_HEX, NULL, 0x80, NULL, HFILL }
},
{ &hf_dvbci_eit_rst_trusted,
{ "EIT running status trusted", "dvb-ci.opp.eit_rst_trusted",
FT_UINT8, BASE_HEX, NULL, 0x40, NULL, HFILL }
},
{ &hf_dvbci_eit_pf_usage,
{ "EIT present/following usage", "dvb-ci.opp.eit_pf_usage",
FT_UINT8, BASE_HEX, VALS(dvbci_opp_eit_pf_usage), 0x30, NULL, HFILL }
},
{ &hf_dvbci_eit_sch_usage,
{ "EIT schedule usage", "dvb-ci.opp.eit_sch_usage",
FT_UINT8, BASE_HEX, VALS(dvbci_opp_eit_sch_usage), 0x0E, NULL, HFILL }
},
{ &hf_dvbci_ext_evt_usage,
{ "Extended event usage", "dvb-ci.opp.ext_evt_usage",
FT_UINT8, BASE_HEX, VALS(dvbci_opp_ext_evt), 0x01, NULL, HFILL }
},
{ &hf_dvbci_sdt_oth_trusted,
{ "SDT_other trusted", "dvb-ci.opp.sdt_oth_trusted",
FT_UINT8, BASE_HEX, NULL, 0x80, NULL, HFILL }
},
{ &hf_dvbci_eit_evt_trigger,
{ "EIT event trigger", "dvb-ci.opp.eit_evt_trigger",
FT_UINT8, BASE_HEX, NULL, 0x40, NULL, HFILL }
},
{ &hf_dvbci_opp_lang_code,
{ "Language code", "dvb-ci.opp.lang_code",
FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_prof_name,
{ "Profile name", "dvb-ci.opp.profile_name",
FT_UINT_STRING, BASE_NONE, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_unattended,
{ "Unattended flag", "dvb-ci.opp.unattended_flag",
FT_UINT8, BASE_HEX, NULL, 0x80, NULL, HFILL }
},
{ &hf_dvbci_opp_srv_type,
{ "Service type", "dvb-ci.opp.service_type", FT_UINT8,
BASE_HEX|BASE_EXT_STRING, &mpeg_descr_service_type_vals_ext,
0, NULL, HFILL }
},
{ &hf_dvbci_dlv_cap_byte,
{ "Delivery capability byte", "dvb-ci.opp.dlv_cap_byte",
FT_UINT8, BASE_HEX, VALS(dvbci_opp_dlv_cap), 0, NULL, HFILL }
},
/* the CI+ spec is not particularly clear about this but an
* application id in the capability loop must always be 2 bytes */
{ &hf_dvbci_app_cap_bytes,
{ "Application capability bytes", "dvb-ci.opp.app_cap_bytes",
FT_UINT16, BASE_HEX|BASE_EXT_STRING,
&mpeg_descr_data_bcast_id_vals_ext, 0, NULL, HFILL }
},
{ &hf_dvbci_desc_num,
{ "Next unprocessed descriptor number", "dvb-ci.opp.desc_num",
FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sig_strength,
{ "Signal strength", "dvb-ci.opp.sig_strength",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sig_qual,
{ "Signal quality", "dvb-ci.opp.sig_qual",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_opp_tune_status,
{ "Tuning status", "dvb-ci.opp.tune_status",
FT_UINT8, BASE_HEX, VALS(dvbci_opp_tune_stat), 0xF0, NULL, HFILL }
},
{ &hf_dvbci_opp_desc_loop_len,
{ "Descriptor loop length", "dvb-ci.opp.desc_loop_len",
FT_UINT16, BASE_DEC, NULL, 0x0FFF, NULL, HFILL }
},
{ &hf_dvbci_sas_app_id,
{ "Application ID", "dvb-ci.sas.app_id",
FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sas_sess_state,
{ "Connection state", "dvb-ci.sas.sess_state",
FT_UINT8, BASE_DEC, VALS(dvbci_sas_sess_state), 0, NULL, HFILL }
},
{ &hf_dvbci_sas_msg_nb,
{ "Message number", "dvb-ci.sas.msg_nb",
FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL }
},
{ &hf_dvbci_sas_msg_len,
{ "Message length", "dvb-ci.sas.msg_len",
FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL }
}
};
static ei_register_info ei[] = {
{ &ei_dvbci_invalid_char_tbl,
{ "dvb-ci.invalid_char_tbl", PI_MALFORMED, PI_ERROR,
"Invalid character table", EXPFILL }},
{ &ei_dvbci_ca_pmt_cmd_id, { "dvb-ci.ca.ca_pmt_cmd_id.ca_pmt", PI_MALFORMED, PI_ERROR, "The ca_pmt shall only contain ca descriptors (tag 0x9)", EXPFILL }},
{ &ei_dvbci_bad_length, { "dvb-ci.bad_length", PI_MALFORMED, PI_ERROR, "Invalid APDU length field, %s must be a multiple of 4 bytes", EXPFILL }},
{ &ei_dvbci_network_id, { "dvb-ci.hc.nid.ignored", PI_PROTOCOL, PI_NOTE, "Network ID is usually ignored by hosts", EXPFILL }},
{ &ei_dvbci_not_text_more_or_text_last, { "dvb-ci.not_text_more_or_text_last", PI_MALFORMED, PI_ERROR, "Items must be text_more() or text_last() objects", EXPFILL }},
{ &ei_dvbci_cup_progress, { "dvb-ci.cup.progress.invalid", PI_PROTOCOL, PI_WARN, "progress is in percent, value must be between 0 and 100", EXPFILL }},
{ &ei_dvbci_sac_payload_enc, { "dvb-ci.cc.sac.payload_enc.clear", PI_PROTOCOL, PI_NOTE, "The original PDU was encrypted, this exported PDU is in the clear", EXPFILL }},
{ &ei_dvbci_pin_evt_cent, { "dvb-ci.cc.pin_event_time_centi.invalid", PI_PROTOCOL, PI_WARN, "Invalid value for event time centiseconds, Value must be between 0 and 100", EXPFILL }},
{ &ei_dvbci_cicam_nit_table_id, { "dvb-ci.cicam_nit.table_id.invalid", PI_PROTOCOL, PI_WARN, "CICAM NIT must have table id 0x40 (NIT actual)", EXPFILL }},
{ &ei_dvbci_sig_qual, { "dvb-ci.opp.sig_qual.invalid", PI_PROTOCOL, PI_WARN, "Invalid value for signal strength / signal quality, values are in percent (0 to 100)", EXPFILL }},
{ &ei_dvbci_apdu_tag, { "dvb-ci.apdu_tag.invalid", PI_MALFORMED, PI_ERROR, "Invalid or unsupported APDU tag", EXPFILL }},
{ &ei_dvbci_apdu_not_supported, { "dvb-ci.apdu_not_supported", PI_PROTOCOL, PI_WARN, "Dissection of this APDU is not supported", EXPFILL }},
{ &ei_dvbci_apu_host_to_cam, { "dvb-ci.apu.host_to_cam", PI_PROTOCOL, PI_WARN, "Invalid APDU direction, this APDU must be sent from host to CAM", EXPFILL }},
{ &ei_dvbci_apu_cam_to_host, { "dvb-ci.apu.cam_to_host", PI_PROTOCOL, PI_WARN, "Invalid APDU direction, this APDU must be sent from CAM to host", EXPFILL }},
{ &ei_dvbci_res_class, { "dvb-ci.res.class.invalid", PI_PROTOCOL, PI_WARN, "Invalid resource class for this apdu", EXPFILL }},
{ &ei_dvbci_res_ver, { "dvb-ci.res.version.old", PI_PROTOCOL, PI_WARN, "Invalid resource version for this apdu", EXPFILL }},
{ &ei_dvbci_spdu_tag, { "dvb-ci.spdu_tag.invalid", PI_MALFORMED, PI_ERROR, "Invalid SPDU tag, See table 14 in the DVB-CI specification", EXPFILL }},
{ &ei_dvbci_spdu_host_to_cam, { "dvb-ci.spdu.host_to_cam", PI_PROTOCOL, PI_WARN, "Invalid SPDU direction, this SPDU must be sent from host to CAM", EXPFILL }},
{ &ei_dvbci_spdu_cam_to_host, { "dvb-ci.spdu.cam_to_host", PI_PROTOCOL, PI_WARN, "Invalid SPDU direction, this SPDU must be sent from CAM to host", EXPFILL }},
{ &ei_dvbci_tpdu_status_tag, { "dvb-ci.tpdu.status_tag.invalid", PI_MALFORMED, PI_ERROR, "Invalid status tag, this must always be T_SB (0x80)", EXPFILL }},
{ &ei_dvbci_t_c_id, { "dvb-ci.t_c_id.invalid", PI_PROTOCOL, PI_WARN, "Transport Connection ID mismatch, tcid is %d in the transport layer and %d in the link layer", EXPFILL }},
{ &ei_dvbci_sb_value, { "dvb-ci.sb_value.invalid", PI_PROTOCOL, PI_WARN, "Invalid SB_value, must be 0x00 or 0x80", EXPFILL }},
{ &ei_dvbci_c_tpdu_tag, { "dvb-ci.c_tpdu_tag.invalid", PI_MALFORMED, PI_ERROR, "Invalid Command-TPDU tag, see DVB-CI specification, table A.16 for valid values", EXPFILL }},
{ &ei_dvbci_r_tpdu_tag, { "dvb-ci.r_tpdu_tag.invalid", PI_MALFORMED, PI_ERROR, "Invalid Response-TPDU tag, see DVB-CI specification, table A.16 for valid values", EXPFILL }},
{ &ei_dvbci_r_tpdu_status_mandatory, { "dvb-ci.r_tpdu_status.mandatory", PI_MALFORMED, PI_ERROR, "Response TPDU's status part is missing, RTPDU status is mandatory", EXPFILL }},
{ &ei_dvbci_ml, { "dvb-ci.more_last.invalid", PI_PROTOCOL, PI_WARN, "Invalid More/Last indicator, second byte of an LPDU must be 0x80 or 0x00", EXPFILL }},
{ &ei_dvbci_buf_size, { "dvb-ci.buf_size.invalid", PI_PROTOCOL, PI_WARN, "Illegal buffer size command", EXPFILL }},
{ &ei_dvbci_cor_addr, { "dvb-ci.cor_address.invalid", PI_PROTOCOL, PI_WARN, "COR address must not be greater than 0xFFE (DVB-CI spec, A.5.6)", EXPFILL }},
};
spdu_table = g_hash_table_new(g_direct_hash, g_direct_equal);
for(i=0; i<array_length(spdu_info); i++) {
g_hash_table_insert(spdu_table,
GUINT_TO_POINTER((guint)spdu_info[i].tag),
(const gpointer)(&spdu_info[i]));
}
apdu_table = g_hash_table_new(g_direct_hash, g_direct_equal);
for(i=0; i<array_length(apdu_info); i++) {
g_hash_table_insert(apdu_table,
GUINT_TO_POINTER((guint)apdu_info[i].tag),
(const gpointer)(&apdu_info[i]));
}
proto_dvbci = proto_register_protocol("DVB Common Interface", "DVB-CI", "dvb-ci");
proto_register_field_array(proto_dvbci, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_dvbci = expert_register_protocol(proto_dvbci);
expert_register_field_array(expert_dvbci, ei, array_length(ei));
dvbci_module = prefs_register_protocol(
proto_dvbci, proto_reg_handoff_dvbci);
prefs_register_string_preference(dvbci_module,
"sek", "SAC Encryption Key", "SAC Encryption Key (16 hex bytes)",
&dvbci_sek);
prefs_register_string_preference(dvbci_module,
"siv", "SAC Init Vector", "SAC Init Vector (16 hex bytes)",
&dvbci_siv);
prefs_register_bool_preference(dvbci_module,
"dissect_lsc_msg",
"Dissect LSC messages",
"Dissect the content of messages transmitted "
"on the Low-Speed Communication resource. "
"This requires a dissector for the protocol and target port "
"contained in the connection descriptor.",
&dvbci_dissect_lsc_msg);
sas_msg_dissector_table = register_dissector_table("dvb-ci.sas.app_id_str",
"SAS application id", FT_STRING, STR_ASCII);
register_init_routine(dvbci_init);
/* the dissector for decrypted CI+ SAC messages which we can export */
new_register_dissector(EXPORTED_SAC_MSG_PROTO,
dissect_dvbci_exported_sac_msg, proto_dvbci);
exported_pdu_tap = register_export_pdu_tap("DVB-CI");
}
void
proto_reg_handoff_dvbci(void)
{
dissector_handle_t dvbci_handle;
dvbci_handle = new_create_dissector_handle(dissect_dvbci, proto_dvbci);
dissector_add_uint("wtap_encap", WTAP_ENCAP_DVBCI, dvbci_handle);
data_handle = find_dissector("data");
mpeg_pmt_handle = find_dissector("mpeg_pmt");
dvb_nit_handle = find_dissector("dvb_nit");
png_handle = find_dissector("png");
tcp_dissector_table = find_dissector_table("tcp.port");
udp_dissector_table = find_dissector_table("udp.port");
if (dvbci_sek_bin) {
g_free(dvbci_sek_bin);
dvbci_sek_bin = NULL;
}
if (dvbci_siv_bin) {
g_free(dvbci_siv_bin);
dvbci_siv_bin = NULL;
}
pref_key_string_to_bin(dvbci_sek, &dvbci_sek_bin);
pref_key_string_to_bin(dvbci_siv, &dvbci_siv_bin);
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
|
kevincox/wireshark
|
epan/dissectors/packet-dvbci.c
|
C
|
gpl-2.0
| 244,271 |
/**
* Marvell BT-over-SDIO driver: SDIO interface related functions.
*
* Copyright (C) 2009, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
**/
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/mmc/sdio_ids.h>
#include <linux/mmc/sdio_func.h>
#include <linux/module.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include "btmrvl_drv.h"
#include "btmrvl_sdio.h"
#define VERSION "1.0"
/* The btmrvl_sdio_remove() callback function is called
* when user removes this module from kernel space or ejects
* the card from the slot. The driver handles these 2 cases
* differently.
* If the user is removing the module, a MODULE_SHUTDOWN_REQ
* command is sent to firmware and interrupt will be disabled.
* If the card is removed, there is no need to send command
* or disable interrupt.
*
* The variable 'user_rmmod' is used to distinguish these two
* scenarios. This flag is initialized as FALSE in case the card
* is removed, and will be set to TRUE for module removal when
* module_exit function is called.
*/
static u8 user_rmmod;
static u8 sdio_ireg;
static const struct btmrvl_sdio_card_reg btmrvl_reg_8688 = {
.cfg = 0x03,
.host_int_mask = 0x04,
.host_intstatus = 0x05,
.card_status = 0x20,
.sq_read_base_addr_a0 = 0x10,
.sq_read_base_addr_a1 = 0x11,
.card_fw_status0 = 0x40,
.card_fw_status1 = 0x41,
.card_rx_len = 0x42,
.card_rx_unit = 0x43,
.io_port_0 = 0x00,
.io_port_1 = 0x01,
.io_port_2 = 0x02,
};
static const struct btmrvl_sdio_card_reg btmrvl_reg_87xx = {
.cfg = 0x00,
.host_int_mask = 0x02,
.host_intstatus = 0x03,
.card_status = 0x30,
.sq_read_base_addr_a0 = 0x40,
.sq_read_base_addr_a1 = 0x41,
.card_revision = 0x5c,
.card_fw_status0 = 0x60,
.card_fw_status1 = 0x61,
.card_rx_len = 0x62,
.card_rx_unit = 0x63,
.io_port_0 = 0x78,
.io_port_1 = 0x79,
.io_port_2 = 0x7a,
};
static const struct btmrvl_sdio_device btmrvl_sdio_sd8688 = {
.helper = "sd8688_helper.bin",
.firmware = "sd8688.bin",
.reg = &btmrvl_reg_8688,
.sd_blksz_fw_dl = 64,
};
static const struct btmrvl_sdio_device btmrvl_sdio_sd8787 = {
.helper = NULL,
.firmware = "mrvl/sd8787_uapsta.bin",
.reg = &btmrvl_reg_87xx,
.sd_blksz_fw_dl = 256,
};
static const struct btmrvl_sdio_device btmrvl_sdio_sd8797 = {
.helper = NULL,
.firmware = "mrvl/sd8797_uapsta.bin",
.reg = &btmrvl_reg_87xx,
.sd_blksz_fw_dl = 256,
};
static const struct sdio_device_id btmrvl_sdio_ids[] = {
/* Marvell SD8688 Bluetooth device */
{ SDIO_DEVICE(SDIO_VENDOR_ID_MARVELL, 0x9105),
.driver_data = (unsigned long) &btmrvl_sdio_sd8688 },
/* Marvell SD8787 Bluetooth device */
{ SDIO_DEVICE(SDIO_VENDOR_ID_MARVELL, 0x911A),
.driver_data = (unsigned long) &btmrvl_sdio_sd8787 },
/* Marvell SD8787 Bluetooth AMP device */
{ SDIO_DEVICE(SDIO_VENDOR_ID_MARVELL, 0x911B),
.driver_data = (unsigned long) &btmrvl_sdio_sd8787 },
/* Marvell SD8797 Bluetooth device */
{ SDIO_DEVICE(SDIO_VENDOR_ID_MARVELL, 0x912A),
.driver_data = (unsigned long) &btmrvl_sdio_sd8797 },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(sdio, btmrvl_sdio_ids);
static int btmrvl_sdio_get_rx_unit(struct btmrvl_sdio_card *card)
{
u8 reg;
int ret;
reg = sdio_readb(card->func, card->reg->card_rx_unit, &ret);
if (!ret)
card->rx_unit = reg;
return ret;
}
static int btmrvl_sdio_read_fw_status(struct btmrvl_sdio_card *card, u16 *dat)
{
u8 fws0, fws1;
int ret;
*dat = 0;
fws0 = sdio_readb(card->func, card->reg->card_fw_status0, &ret);
if (ret)
return -EIO;
fws1 = sdio_readb(card->func, card->reg->card_fw_status1, &ret);
if (ret)
return -EIO;
*dat = (((u16) fws1) << 8) | fws0;
return 0;
}
static int btmrvl_sdio_read_rx_len(struct btmrvl_sdio_card *card, u16 *dat)
{
u8 reg;
int ret;
reg = sdio_readb(card->func, card->reg->card_rx_len, &ret);
if (!ret)
*dat = (u16) reg << card->rx_unit;
return ret;
}
static int btmrvl_sdio_enable_host_int_mask(struct btmrvl_sdio_card *card,
u8 mask)
{
int ret;
sdio_writeb(card->func, mask, card->reg->host_int_mask, &ret);
if (ret) {
BT_ERR("Unable to enable the host interrupt!");
ret = -EIO;
}
return ret;
}
static int btmrvl_sdio_disable_host_int_mask(struct btmrvl_sdio_card *card,
u8 mask)
{
u8 host_int_mask;
int ret;
host_int_mask = sdio_readb(card->func, card->reg->host_int_mask, &ret);
if (ret)
return -EIO;
host_int_mask &= ~mask;
sdio_writeb(card->func, host_int_mask, card->reg->host_int_mask, &ret);
if (ret < 0) {
BT_ERR("Unable to disable the host interrupt!");
return -EIO;
}
return 0;
}
static int btmrvl_sdio_poll_card_status(struct btmrvl_sdio_card *card, u8 bits)
{
unsigned int tries;
u8 status;
int ret;
for (tries = 0; tries < MAX_POLL_TRIES * 1000; tries++) {
status = sdio_readb(card->func, card->reg->card_status, &ret);
if (ret)
goto failed;
if ((status & bits) == bits)
return ret;
udelay(1);
}
ret = -ETIMEDOUT;
failed:
BT_ERR("FAILED! ret=%d", ret);
return ret;
}
static int btmrvl_sdio_verify_fw_download(struct btmrvl_sdio_card *card,
int pollnum)
{
int ret = -ETIMEDOUT;
u16 firmwarestat;
unsigned int tries;
/* Wait for firmware to become ready */
for (tries = 0; tries < pollnum; tries++) {
if (btmrvl_sdio_read_fw_status(card, &firmwarestat) < 0)
continue;
if (firmwarestat == FIRMWARE_READY) {
ret = 0;
break;
} else {
msleep(10);
}
}
return ret;
}
static int btmrvl_sdio_download_helper(struct btmrvl_sdio_card *card)
{
const struct firmware *fw_helper = NULL;
const u8 *helper = NULL;
int ret;
void *tmphlprbuf = NULL;
int tmphlprbufsz, hlprblknow, helperlen;
u8 *helperbuf;
u32 tx_len;
ret = request_firmware(&fw_helper, card->helper,
&card->func->dev);
if ((ret < 0) || !fw_helper) {
BT_ERR("request_firmware(helper) failed, error code = %d",
ret);
ret = -ENOENT;
goto done;
}
helper = fw_helper->data;
helperlen = fw_helper->size;
BT_DBG("Downloading helper image (%d bytes), block size %d bytes",
helperlen, SDIO_BLOCK_SIZE);
tmphlprbufsz = ALIGN_SZ(BTM_UPLD_SIZE, BTSDIO_DMA_ALIGN);
tmphlprbuf = kzalloc(tmphlprbufsz, GFP_KERNEL);
if (!tmphlprbuf) {
BT_ERR("Unable to allocate buffer for helper."
" Terminating download");
ret = -ENOMEM;
goto done;
}
helperbuf = (u8 *) ALIGN_ADDR(tmphlprbuf, BTSDIO_DMA_ALIGN);
/* Perform helper data transfer */
tx_len = (FIRMWARE_TRANSFER_NBLOCK * SDIO_BLOCK_SIZE)
- SDIO_HEADER_LEN;
hlprblknow = 0;
do {
ret = btmrvl_sdio_poll_card_status(card,
CARD_IO_READY | DN_LD_CARD_RDY);
if (ret < 0) {
BT_ERR("Helper download poll status timeout @ %d",
hlprblknow);
goto done;
}
/* Check if there is more data? */
if (hlprblknow >= helperlen)
break;
if (helperlen - hlprblknow < tx_len)
tx_len = helperlen - hlprblknow;
/* Little-endian */
helperbuf[0] = ((tx_len & 0x000000ff) >> 0);
helperbuf[1] = ((tx_len & 0x0000ff00) >> 8);
helperbuf[2] = ((tx_len & 0x00ff0000) >> 16);
helperbuf[3] = ((tx_len & 0xff000000) >> 24);
memcpy(&helperbuf[SDIO_HEADER_LEN], &helper[hlprblknow],
tx_len);
/* Now send the data */
ret = sdio_writesb(card->func, card->ioport, helperbuf,
FIRMWARE_TRANSFER_NBLOCK * SDIO_BLOCK_SIZE);
if (ret < 0) {
BT_ERR("IO error during helper download @ %d",
hlprblknow);
goto done;
}
hlprblknow += tx_len;
} while (true);
BT_DBG("Transferring helper image EOF block");
memset(helperbuf, 0x0, SDIO_BLOCK_SIZE);
ret = sdio_writesb(card->func, card->ioport, helperbuf,
SDIO_BLOCK_SIZE);
if (ret < 0) {
BT_ERR("IO error in writing helper image EOF block");
goto done;
}
ret = 0;
done:
kfree(tmphlprbuf);
release_firmware(fw_helper);
return ret;
}
static int btmrvl_sdio_download_fw_w_helper(struct btmrvl_sdio_card *card)
{
const struct firmware *fw_firmware = NULL;
const u8 *firmware = NULL;
int firmwarelen, tmpfwbufsz, ret;
unsigned int tries, offset;
u8 base0, base1;
void *tmpfwbuf = NULL;
u8 *fwbuf;
u16 len, blksz_dl = card->sd_blksz_fw_dl;
int txlen = 0, tx_blocks = 0, count = 0;
ret = request_firmware(&fw_firmware, card->firmware,
&card->func->dev);
if ((ret < 0) || !fw_firmware) {
BT_ERR("request_firmware(firmware) failed, error code = %d",
ret);
ret = -ENOENT;
goto done;
}
firmware = fw_firmware->data;
firmwarelen = fw_firmware->size;
BT_DBG("Downloading FW image (%d bytes)", firmwarelen);
tmpfwbufsz = ALIGN_SZ(BTM_UPLD_SIZE, BTSDIO_DMA_ALIGN);
tmpfwbuf = kzalloc(tmpfwbufsz, GFP_KERNEL);
if (!tmpfwbuf) {
BT_ERR("Unable to allocate buffer for firmware."
" Terminating download");
ret = -ENOMEM;
goto done;
}
/* Ensure aligned firmware buffer */
fwbuf = (u8 *) ALIGN_ADDR(tmpfwbuf, BTSDIO_DMA_ALIGN);
/* Perform firmware data transfer */
offset = 0;
do {
ret = btmrvl_sdio_poll_card_status(card,
CARD_IO_READY | DN_LD_CARD_RDY);
if (ret < 0) {
BT_ERR("FW download with helper poll status"
" timeout @ %d", offset);
goto done;
}
/* Check if there is more data ? */
if (offset >= firmwarelen)
break;
for (tries = 0; tries < MAX_POLL_TRIES; tries++) {
base0 = sdio_readb(card->func,
card->reg->sq_read_base_addr_a0, &ret);
if (ret) {
BT_ERR("BASE0 register read failed:"
" base0 = 0x%04X(%d)."
" Terminating download",
base0, base0);
ret = -EIO;
goto done;
}
base1 = sdio_readb(card->func,
card->reg->sq_read_base_addr_a1, &ret);
if (ret) {
BT_ERR("BASE1 register read failed:"
" base1 = 0x%04X(%d)."
" Terminating download",
base1, base1);
ret = -EIO;
goto done;
}
len = (((u16) base1) << 8) | base0;
if (len)
break;
udelay(10);
}
if (!len)
break;
else if (len > BTM_UPLD_SIZE) {
BT_ERR("FW download failure @%d, invalid length %d",
offset, len);
ret = -EINVAL;
goto done;
}
txlen = len;
if (len & BIT(0)) {
count++;
if (count > MAX_WRITE_IOMEM_RETRY) {
BT_ERR("FW download failure @%d, "
"over max retry count", offset);
ret = -EIO;
goto done;
}
BT_ERR("FW CRC error indicated by the helper: "
"len = 0x%04X, txlen = %d", len, txlen);
len &= ~BIT(0);
/* Set txlen to 0 so as to resend from same offset */
txlen = 0;
} else {
count = 0;
/* Last block ? */
if (firmwarelen - offset < txlen)
txlen = firmwarelen - offset;
tx_blocks = (txlen + blksz_dl - 1) / blksz_dl;
memcpy(fwbuf, &firmware[offset], txlen);
}
ret = sdio_writesb(card->func, card->ioport, fwbuf,
tx_blocks * blksz_dl);
if (ret < 0) {
BT_ERR("FW download, writesb(%d) failed @%d",
count, offset);
sdio_writeb(card->func, HOST_CMD53_FIN,
card->reg->cfg, &ret);
if (ret)
BT_ERR("writeb failed (CFG)");
}
offset += txlen;
} while (true);
BT_DBG("FW download over, size %d bytes", offset);
ret = 0;
done:
kfree(tmpfwbuf);
release_firmware(fw_firmware);
return ret;
}
static int btmrvl_sdio_card_to_host(struct btmrvl_private *priv)
{
u16 buf_len = 0;
int ret, buf_block_len, blksz;
struct sk_buff *skb = NULL;
u32 type;
u8 *payload = NULL;
struct hci_dev *hdev = priv->btmrvl_dev.hcidev;
struct btmrvl_sdio_card *card = priv->btmrvl_dev.card;
if (!card || !card->func) {
BT_ERR("card or function is NULL!");
ret = -EINVAL;
goto exit;
}
/* Read the length of data to be transferred */
ret = btmrvl_sdio_read_rx_len(card, &buf_len);
if (ret < 0) {
BT_ERR("read rx_len failed");
ret = -EIO;
goto exit;
}
blksz = SDIO_BLOCK_SIZE;
buf_block_len = (buf_len + blksz - 1) / blksz;
if (buf_len <= SDIO_HEADER_LEN
|| (buf_block_len * blksz) > ALLOC_BUF_SIZE) {
BT_ERR("invalid packet length: %d", buf_len);
ret = -EINVAL;
goto exit;
}
/* Allocate buffer */
skb = bt_skb_alloc(buf_block_len * blksz + BTSDIO_DMA_ALIGN,
GFP_ATOMIC);
if (skb == NULL) {
BT_ERR("No free skb");
goto exit;
}
if ((unsigned long) skb->data & (BTSDIO_DMA_ALIGN - 1)) {
skb_put(skb, (unsigned long) skb->data &
(BTSDIO_DMA_ALIGN - 1));
skb_pull(skb, (unsigned long) skb->data &
(BTSDIO_DMA_ALIGN - 1));
}
payload = skb->data;
ret = sdio_readsb(card->func, payload, card->ioport,
buf_block_len * blksz);
if (ret < 0) {
BT_ERR("readsb failed: %d", ret);
ret = -EIO;
goto exit;
}
/* This is SDIO specific header length: byte[2][1][0], type: byte[3]
* (HCI_COMMAND = 1, ACL_DATA = 2, SCO_DATA = 3, 0xFE = Vendor)
*/
buf_len = payload[0];
buf_len |= (u16) payload[1] << 8;
type = payload[3];
switch (type) {
case HCI_ACLDATA_PKT:
case HCI_SCODATA_PKT:
case HCI_EVENT_PKT:
bt_cb(skb)->pkt_type = type;
skb->dev = (void *)hdev;
skb_put(skb, buf_len);
skb_pull(skb, SDIO_HEADER_LEN);
if (type == HCI_EVENT_PKT) {
if (btmrvl_check_evtpkt(priv, skb))
hci_recv_frame(skb);
} else {
hci_recv_frame(skb);
}
hdev->stat.byte_rx += buf_len;
break;
case MRVL_VENDOR_PKT:
bt_cb(skb)->pkt_type = HCI_VENDOR_PKT;
skb->dev = (void *)hdev;
skb_put(skb, buf_len);
skb_pull(skb, SDIO_HEADER_LEN);
if (btmrvl_process_event(priv, skb))
hci_recv_frame(skb);
hdev->stat.byte_rx += buf_len;
break;
default:
BT_ERR("Unknown packet type:%d", type);
print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, payload,
blksz * buf_block_len);
kfree_skb(skb);
skb = NULL;
break;
}
exit:
if (ret) {
hdev->stat.err_rx++;
if (skb)
kfree_skb(skb);
}
return ret;
}
static int btmrvl_sdio_process_int_status(struct btmrvl_private *priv)
{
ulong flags;
u8 ireg;
struct btmrvl_sdio_card *card = priv->btmrvl_dev.card;
spin_lock_irqsave(&priv->driver_lock, flags);
ireg = sdio_ireg;
sdio_ireg = 0;
spin_unlock_irqrestore(&priv->driver_lock, flags);
sdio_claim_host(card->func);
if (ireg & DN_LD_HOST_INT_STATUS) {
if (priv->btmrvl_dev.tx_dnld_rdy)
BT_DBG("tx_done already received: "
" int_status=0x%x", ireg);
else
priv->btmrvl_dev.tx_dnld_rdy = true;
}
if (ireg & UP_LD_HOST_INT_STATUS)
btmrvl_sdio_card_to_host(priv);
sdio_release_host(card->func);
return 0;
}
static void btmrvl_sdio_interrupt(struct sdio_func *func)
{
struct btmrvl_private *priv;
struct btmrvl_sdio_card *card;
ulong flags;
u8 ireg = 0;
int ret;
card = sdio_get_drvdata(func);
if (!card || !card->priv) {
BT_ERR("sbi_interrupt(%p) card or priv is "
"NULL, card=%p\n", func, card);
return;
}
priv = card->priv;
ireg = sdio_readb(card->func, card->reg->host_intstatus, &ret);
if (ret) {
BT_ERR("sdio_readb: read int status register failed");
return;
}
if (ireg != 0) {
/*
* DN_LD_HOST_INT_STATUS and/or UP_LD_HOST_INT_STATUS
* Clear the interrupt status register and re-enable the
* interrupt.
*/
BT_DBG("ireg = 0x%x", ireg);
sdio_writeb(card->func, ~(ireg) & (DN_LD_HOST_INT_STATUS |
UP_LD_HOST_INT_STATUS),
card->reg->host_intstatus, &ret);
if (ret) {
BT_ERR("sdio_writeb: clear int status register failed");
return;
}
}
spin_lock_irqsave(&priv->driver_lock, flags);
sdio_ireg |= ireg;
spin_unlock_irqrestore(&priv->driver_lock, flags);
btmrvl_interrupt(priv);
}
static int btmrvl_sdio_register_dev(struct btmrvl_sdio_card *card)
{
struct sdio_func *func;
u8 reg;
int ret = 0;
if (!card || !card->func) {
BT_ERR("Error: card or function is NULL!");
ret = -EINVAL;
goto failed;
}
func = card->func;
sdio_claim_host(func);
ret = sdio_enable_func(func);
if (ret) {
BT_ERR("sdio_enable_func() failed: ret=%d", ret);
ret = -EIO;
goto release_host;
}
ret = sdio_claim_irq(func, btmrvl_sdio_interrupt);
if (ret) {
BT_ERR("sdio_claim_irq failed: ret=%d", ret);
ret = -EIO;
goto disable_func;
}
ret = sdio_set_block_size(card->func, SDIO_BLOCK_SIZE);
if (ret) {
BT_ERR("cannot set SDIO block size");
ret = -EIO;
goto release_irq;
}
reg = sdio_readb(func, card->reg->io_port_0, &ret);
if (ret < 0) {
ret = -EIO;
goto release_irq;
}
card->ioport = reg;
reg = sdio_readb(func, card->reg->io_port_1, &ret);
if (ret < 0) {
ret = -EIO;
goto release_irq;
}
card->ioport |= (reg << 8);
reg = sdio_readb(func, card->reg->io_port_2, &ret);
if (ret < 0) {
ret = -EIO;
goto release_irq;
}
card->ioport |= (reg << 16);
BT_DBG("SDIO FUNC%d IO port: 0x%x", func->num, card->ioport);
sdio_set_drvdata(func, card);
sdio_release_host(func);
return 0;
release_irq:
sdio_release_irq(func);
disable_func:
sdio_disable_func(func);
release_host:
sdio_release_host(func);
failed:
return ret;
}
static int btmrvl_sdio_unregister_dev(struct btmrvl_sdio_card *card)
{
if (card && card->func) {
sdio_claim_host(card->func);
sdio_release_irq(card->func);
sdio_disable_func(card->func);
sdio_release_host(card->func);
sdio_set_drvdata(card->func, NULL);
}
return 0;
}
static int btmrvl_sdio_enable_host_int(struct btmrvl_sdio_card *card)
{
int ret;
if (!card || !card->func)
return -EINVAL;
sdio_claim_host(card->func);
ret = btmrvl_sdio_enable_host_int_mask(card, HIM_ENABLE);
btmrvl_sdio_get_rx_unit(card);
sdio_release_host(card->func);
return ret;
}
static int btmrvl_sdio_disable_host_int(struct btmrvl_sdio_card *card)
{
int ret;
if (!card || !card->func)
return -EINVAL;
sdio_claim_host(card->func);
ret = btmrvl_sdio_disable_host_int_mask(card, HIM_DISABLE);
sdio_release_host(card->func);
return ret;
}
static int btmrvl_sdio_host_to_card(struct btmrvl_private *priv,
u8 *payload, u16 nb)
{
struct btmrvl_sdio_card *card = priv->btmrvl_dev.card;
int ret = 0;
int buf_block_len;
int blksz;
int i = 0;
u8 *buf = NULL;
void *tmpbuf = NULL;
int tmpbufsz;
if (!card || !card->func) {
BT_ERR("card or function is NULL!");
return -EINVAL;
}
buf = payload;
if ((unsigned long) payload & (BTSDIO_DMA_ALIGN - 1)) {
tmpbufsz = ALIGN_SZ(nb, BTSDIO_DMA_ALIGN);
tmpbuf = kzalloc(tmpbufsz, GFP_KERNEL);
if (!tmpbuf)
return -ENOMEM;
buf = (u8 *) ALIGN_ADDR(tmpbuf, BTSDIO_DMA_ALIGN);
memcpy(buf, payload, nb);
}
blksz = SDIO_BLOCK_SIZE;
buf_block_len = (nb + blksz - 1) / blksz;
sdio_claim_host(card->func);
do {
/* Transfer data to card */
ret = sdio_writesb(card->func, card->ioport, buf,
buf_block_len * blksz);
if (ret < 0) {
i++;
BT_ERR("i=%d writesb failed: %d", i, ret);
print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
payload, nb);
ret = -EIO;
if (i > MAX_WRITE_IOMEM_RETRY)
goto exit;
}
} while (ret);
priv->btmrvl_dev.tx_dnld_rdy = false;
exit:
sdio_release_host(card->func);
kfree(tmpbuf);
return ret;
}
static int btmrvl_sdio_download_fw(struct btmrvl_sdio_card *card)
{
int ret = 0;
u8 fws0;
int pollnum = MAX_POLL_TRIES;
if (!card || !card->func) {
BT_ERR("card or function is NULL!");
return -EINVAL;
}
sdio_claim_host(card->func);
if (!btmrvl_sdio_verify_fw_download(card, 1)) {
BT_DBG("Firmware already downloaded!");
goto done;
}
/* Check if other function driver is downloading the firmware */
fws0 = sdio_readb(card->func, card->reg->card_fw_status0, &ret);
if (ret) {
BT_ERR("Failed to read FW downloading status!");
ret = -EIO;
goto done;
}
if (fws0) {
BT_DBG("BT not the winner (%#x). Skip FW downloading", fws0);
/* Give other function more time to download the firmware */
pollnum *= 10;
} else {
if (card->helper) {
ret = btmrvl_sdio_download_helper(card);
if (ret) {
BT_ERR("Failed to download helper!");
ret = -EIO;
goto done;
}
}
if (btmrvl_sdio_download_fw_w_helper(card)) {
BT_ERR("Failed to download firmware!");
ret = -EIO;
goto done;
}
}
if (btmrvl_sdio_verify_fw_download(card, pollnum)) {
BT_ERR("FW failed to be active in time!");
ret = -ETIMEDOUT;
goto done;
}
done:
sdio_release_host(card->func);
return ret;
}
static int btmrvl_sdio_wakeup_fw(struct btmrvl_private *priv)
{
struct btmrvl_sdio_card *card = priv->btmrvl_dev.card;
int ret = 0;
if (!card || !card->func) {
BT_ERR("card or function is NULL!");
return -EINVAL;
}
sdio_claim_host(card->func);
sdio_writeb(card->func, HOST_POWER_UP, card->reg->cfg, &ret);
sdio_release_host(card->func);
BT_DBG("wake up firmware");
return ret;
}
static int btmrvl_sdio_probe(struct sdio_func *func,
const struct sdio_device_id *id)
{
int ret = 0;
struct btmrvl_private *priv = NULL;
struct btmrvl_sdio_card *card = NULL;
BT_INFO("vendor=0x%x, device=0x%x, class=%d, fn=%d",
id->vendor, id->device, id->class, func->num);
card = kzalloc(sizeof(*card), GFP_KERNEL);
if (!card) {
ret = -ENOMEM;
goto done;
}
card->func = func;
if (id->driver_data) {
struct btmrvl_sdio_device *data = (void *) id->driver_data;
card->helper = data->helper;
card->firmware = data->firmware;
card->reg = data->reg;
card->sd_blksz_fw_dl = data->sd_blksz_fw_dl;
}
if (btmrvl_sdio_register_dev(card) < 0) {
BT_ERR("Failed to register BT device!");
ret = -ENODEV;
goto free_card;
}
/* Disable the interrupts on the card */
btmrvl_sdio_disable_host_int(card);
if (btmrvl_sdio_download_fw(card)) {
BT_ERR("Downloading firmware failed!");
ret = -ENODEV;
goto unreg_dev;
}
msleep(100);
btmrvl_sdio_enable_host_int(card);
priv = btmrvl_add_card(card);
if (!priv) {
BT_ERR("Initializing card failed!");
ret = -ENODEV;
goto disable_host_int;
}
card->priv = priv;
/* Initialize the interface specific function pointers */
priv->hw_host_to_card = btmrvl_sdio_host_to_card;
priv->hw_wakeup_firmware = btmrvl_sdio_wakeup_fw;
priv->hw_process_int_status = btmrvl_sdio_process_int_status;
if (btmrvl_register_hdev(priv)) {
BT_ERR("Register hdev failed!");
ret = -ENODEV;
goto disable_host_int;
}
priv->btmrvl_dev.psmode = 1;
btmrvl_enable_ps(priv);
priv->btmrvl_dev.gpio_gap = 0xffff;
btmrvl_send_hscfg_cmd(priv);
return 0;
disable_host_int:
btmrvl_sdio_disable_host_int(card);
unreg_dev:
btmrvl_sdio_unregister_dev(card);
free_card:
kfree(card);
done:
return ret;
}
static void btmrvl_sdio_remove(struct sdio_func *func)
{
struct btmrvl_sdio_card *card;
if (func) {
card = sdio_get_drvdata(func);
if (card) {
/* Send SHUTDOWN command & disable interrupt
* if user removes the module.
*/
if (user_rmmod) {
btmrvl_send_module_cfg_cmd(card->priv,
MODULE_SHUTDOWN_REQ);
btmrvl_sdio_disable_host_int(card);
}
BT_DBG("unregester dev");
btmrvl_sdio_unregister_dev(card);
btmrvl_remove_card(card->priv);
kfree(card);
}
}
}
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,34))
static int btmrvl_sdio_suspend(struct device *dev)
{
struct sdio_func *func = dev_to_sdio_func(dev);
struct btmrvl_sdio_card *card;
struct btmrvl_private *priv;
mmc_pm_flag_t pm_flags;
struct hci_dev *hcidev;
if (func) {
pm_flags = sdio_get_host_pm_caps(func);
BT_DBG("%s: suspend: PM flags = 0x%x", sdio_func_id(func),
pm_flags);
if (!(pm_flags & MMC_PM_KEEP_POWER)) {
BT_ERR("%s: cannot remain alive while suspended",
sdio_func_id(func));
return -ENOSYS;
}
card = sdio_get_drvdata(func);
if (!card || !card->priv) {
BT_ERR("card or priv structure is not valid");
return 0;
}
} else {
BT_ERR("sdio_func is not specified");
return 0;
}
priv = card->priv;
if (priv->adapter->hs_state != HS_ACTIVATED) {
if (btmrvl_enable_hs(priv)) {
BT_ERR("HS not actived, suspend failed!");
return -EBUSY;
}
}
hcidev = priv->btmrvl_dev.hcidev;
BT_DBG("%s: SDIO suspend", hcidev->name);
hci_suspend_dev(hcidev);
skb_queue_purge(&priv->adapter->tx_queue);
priv->adapter->is_suspended = true;
/* We will keep the power when hs enabled successfully */
if (priv->adapter->hs_state == HS_ACTIVATED) {
BT_DBG("suspend with MMC_PM_KEEP_POWER");
return sdio_set_host_pm_flags(func, MMC_PM_KEEP_POWER);
} else {
BT_DBG("suspend without MMC_PM_KEEP_POWER");
return 0;
}
}
static int btmrvl_sdio_resume(struct device *dev)
{
struct sdio_func *func = dev_to_sdio_func(dev);
struct btmrvl_sdio_card *card;
struct btmrvl_private *priv;
mmc_pm_flag_t pm_flags;
struct hci_dev *hcidev;
if (func) {
pm_flags = sdio_get_host_pm_caps(func);
BT_DBG("%s: resume: PM flags = 0x%x", sdio_func_id(func),
pm_flags);
card = sdio_get_drvdata(func);
if (!card || !card->priv) {
BT_ERR("card or priv structure is not valid");
return 0;
}
} else {
BT_ERR("sdio_func is not specified");
return 0;
}
priv = card->priv;
if (!priv->adapter->is_suspended) {
BT_DBG("device already resumed");
return 0;
}
priv->adapter->is_suspended = false;
hcidev = priv->btmrvl_dev.hcidev;
BT_DBG("%s: SDIO resume", hcidev->name);
hci_resume_dev(hcidev);
priv->hw_wakeup_firmware(priv);
priv->adapter->hs_state = HS_DEACTIVATED;
BT_DBG("%s: HS DEACTIVATED in resume!", hcidev->name);
return 0;
}
static const struct dev_pm_ops btmrvl_sdio_pm_ops = {
.suspend = btmrvl_sdio_suspend,
.resume = btmrvl_sdio_resume,
};
#endif
static struct sdio_driver bt_mrvl_sdio = {
.name = "btmrvl_sdio",
.id_table = btmrvl_sdio_ids,
.probe = btmrvl_sdio_probe,
.remove = btmrvl_sdio_remove,
.drv = {
.owner = THIS_MODULE,
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,34))
.pm = &btmrvl_sdio_pm_ops,
#endif
}
};
static int __init btmrvl_sdio_init_module(void)
{
if (sdio_register_driver(&bt_mrvl_sdio) != 0) {
BT_ERR("SDIO Driver Registration Failed");
return -ENODEV;
}
/* Clear the flag in case user removes the card. */
user_rmmod = 0;
return 0;
}
static void __exit btmrvl_sdio_exit_module(void)
{
/* Set the flag as user is removing this module. */
user_rmmod = 1;
sdio_unregister_driver(&bt_mrvl_sdio);
}
module_init(btmrvl_sdio_init_module);
module_exit(btmrvl_sdio_exit_module);
MODULE_AUTHOR("Marvell International Ltd.");
MODULE_DESCRIPTION("Marvell BT-over-SDIO driver ver " VERSION);
MODULE_VERSION(VERSION);
MODULE_LICENSE("GPL v2");
MODULE_FIRMWARE("sd8688_helper.bin");
MODULE_FIRMWARE("sd8688.bin");
MODULE_FIRMWARE("mrvl/sd8787_uapsta.bin");
MODULE_FIRMWARE("mrvl/sd8797_uapsta.bin");
|
BADBDY23/BKernel
|
compat-wireless-3.6.6-1/drivers/bluetooth/btmrvl_sdio.c
|
C
|
gpl-2.0
| 26,854 |
<?php
/**
Plugin Name: wpcu3er
Plugin URI: http://getcu3er.com/
Description: Plugin for embedding & managing CU3ER 3D slider in WordPress
Author: MADEBYPLAY
Version: 0.80
Author URI: http://www.madebyplay.com
*/
/*
Copyright 2010 MADEBYPLAY (email : [email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
require_once('php/config.php');
global $wp_version;
if (version_compare($wp_version, '2.8', '<')) {
exit($cu3er_messages['version']);
}
function cu3er__admin_actions() {
add_menu_page('CU3ER Admin Interface', 'CU3ER', 'edit_posts', 'CU3ER', 'cu3er__admin_overview', WP_PLUGIN_URL . '/wpcu3er/img/icon_cu3er.png');
add_submenu_page('CU3ER', 'CU3ER Overview', 'Overview', 'edit_posts', 'CU3ER', 'cu3er__admin_overview');
add_submenu_page('CU3ER', 'CU3ER Add SlideShow', 'Add New', 'edit_posts', 'CU3ERAddNew', 'cu3er__admin_add');
add_submenu_page('CU3ER', 'CU3ER Manage SlideShows', 'Edit', 'edit_posts', 'CU3ERManageAll', 'cu3er__admin_manage');
add_submenu_page('CU3ER', 'CU3ER Setup', 'Setup', 'edit_posts', 'CU3ERSetup', 'cu3er__admin_setup');
add_submenu_page('CU3ER', 'CU3ER Help', 'Help', 'edit_posts', 'CU3ERHelp', 'cu3er__admin_help');
}
function cu3er__admin_help() {
include_once($cu3er_path . 'tpl/help.php');
}
function cu3er__admin_overview() {
global $wpdb;
global $cu3er_messages;
$message .= cu3er__admin_checkCu3er();
$rows = $wpdb->query("SELECT `id` FROM `" . $wpdb->prefix . "cu3er__slideshows`", ARRAY_A);
foreach ($rows as $row) {
$slideshows[] = $row;
}
$news = cu3er__our_fopen('http://' . SERVER_IP . '/templates/plugins/wordpress/notification.html');
include_once($cu3er_path . 'tpl/overview.php');
}
function cu3er__admin_add() {
global $wpdb;
global $cu3er_messages;
if($_GET['update'] == 1) {
if($_GET['js'] == 1) {
$player = ($_GET['player'] == 1) ? true : false;
if(cu3er_downloadJS($player)) {
if($player) {
$message .= cu3er__admin_checkCu3er('JSPlayertrue');
} else {
$message .= cu3er__admin_checkCu3er('JStrue');
}
} else {
if($player) {
$message .= cu3er__admin_checkCu3er('JSPlayerfalse');
} else {
$message .= cu3er__admin_checkCu3er('JSfalse');
}
}
} else {
if(cu3er_download()) {
$message .= cu3er__admin_checkCu3er(true);
} else {
$message .= cu3er__admin_checkCu3er(false);
}
}
} else {
$message .= cu3er__admin_checkCu3er();
}
$uploadsDir = wp_upload_dir();
if(!is_dir($uploadsDir['basedir'] . '/wpcu3er')) {
@mkdir($uploadsDir['basedir'] . '/wpcu3er', 0777);
}
$writable = true;
if(is_writable($uploadsDir['basedir'] . '/wpcu3er')) {
touch($uploadsDir['basedir'] . '/wpcu3er/temp.txt');
if(!is_writable($uploadsDir['basedir'] . '/wpcu3er/temp.txt')) {
$writable = false;
}
} else {
$writable = false;
}
$basedir = ($writable === true) ? $uploadsDir['basedir'] .'/wpcu3er' : $uploadsDir['path'];
$baseurl = ($writable === true) ? $uploadsDir['baseurl'] .'/wpcu3er' : $uploadsDir['url'];
if($_POST['Submit'] == 'Add CU3ER') {
$rand = cu3er__getRand($basedir .'/');
$uplDir = $basedir .'/'. $rand . '/';
$save_path = $baseurl .'/'. $rand . '/';
$uploadErrors = array(
0 => "File can not be uploaded, probably due PHP safe mode restriction. More details <a href='http://support.getcu3er.com/entries/20162896-how-do-i-resolve-file-can-not-be-uploaded-error-on-project-upload-in-wpcu3er' target='blank'>here</a>.",
1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3 => "The uploaded file was only partially uploaded",
4 => "No file was uploaded",
6 => "Missing a temporary folder",
7 => "Failed to write file to disk.",
8 => "A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help."
);
if(($_FILES['import1']['name'] != '') && ($_FILES['import1']["tmp_name"] != '' || $_FILES['import1']['error'] > 0)) {
// if uploaded file //
$file_name = preg_replace('/[^.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-]|\.+$/i', "", basename($_FILES['import1']['name']));
@unlink($uplDir.$file_name);
if(!move_uploaded_file($_FILES['import1']["tmp_name"], $uplDir.$file_name)) {
echo("<div class='error'>File could not be saved. " . $uploadErrors[$_FILES['import1']['error']] . '</div>');
exit(0);
} else {
$testXmlFile = $uplDir.$file_name;
}
} else {
$testXmlFile = $_POST['import2'];
}
$zipFileType = false;
$type = explode(".", basename($testXmlFile));
if($type[1] == 'zip') {
// if zip //
if(!class_exists('PclZip')) {
include_once('php/pclzip.lib.php');
}
$testXmlFile = $basedir . '/' . $rand . '/' . basename($testXmlFile);
$zip = new PclZip($testXmlFile);
$dir = $basedir . '/' . $rand . '/' . basename($testXmlFile, ".zip");
$cu3er_pathDir = $baseurl . '/' . $rand . '/' . basename($testXmlFile, ".zip");
if($zip->extract(PCLZIP_OPT_PATH, $dir) != 0) {
// uploads dir //
$cu3er_pathDir = $baseurl . '/' . $rand . '/' . basename($testXmlFile, ".zip");
@mkdir($dir, 0777);
if(file_exists($dir . '/CU3ER-config.xml')) {
$xmlName[0] = 'CU3ER-config.xml';
} else {
$xmlName = glob($dir . '/*.xml');
}
if($xmlName[0] != '') {
$testXmlFile = $dir .'/'. basename($xmlName[0]);
}
} else {
die($zip->errorInfo(true));
}
cu3er__makeAll($basedir . '/' . $rand . '/', 755, true);
$zipFileType = true;
} else {
// xml file //
$cu3er_pathDir = $baseurl . '/' . $rand;
$dir = $basedir . '/' . $rand;
$xmlName[0] = $testXmlFile;
}
if($testXmlFile != '') {
$xmlStr = file_get_contents($testXmlFile);
if(!file_exists($dir . '/' .basename($xmlName[0]))) {
touch($dir . '/' . basename($xmlName[0]));
$handle = fopen($dir . '/' . basename($xmlName[0]), 'w+');
fwrite($handle, $xmlStr);
fclose($handle);
}
include_once("php/xml2array.php");
$xml_debugger = new XML2Array();
if($xmlStr != '') {
$xmlStr = preg_replace('/\<transition(.*?)\>/', '<transition empty="true"$1>', $xmlStr);
}
$arrXml = $xml_debugger->parse($xmlStr);
if(!is_array($arrXml)) {
$xmlStr = cu3er__our_fopen($testXmlFile);
if($xmlStr == false) {
cu3er__admin_manage($cu3er_messages['missingXML']);
} else {
$xmlStr = preg_replace('/\<transition(.*?)\>/', '<transition empty="true"$1>', $xmlStr);
$arrXml = $xml_debugger->parse($xmlStr);
}
}
if(!is_array($arrXml)) {
cu3er__admin_manage($cu3er_messages['notXML']);
} else {
$xml_parse = simplexml_load_string($xmlStr);
/*@chmod($testXmlFile, 0777);
@chmod($cu3er_pathDir . '/CU3ER.swf', 0777);*/
cu3er__chmodDir($dir, 0777, 0777);
$arrXml = cu3er__array_remove_empty($arrXml['data']);
// everything is ok //
if($arrXml['project_settings']['width'] == '') {
if($zipFileType) {
$newStr = file_get_contents($dir . '/' . 'embed_example.html');
preg_match_all('/swfobject\.embedSWF\((.*?)\)/', $newStr, $values);
$dimensions = explode(",", $values[1][0]);
} else {
$dimensions[2] = $arrXml['slides']['attr']['width'];
$dimensions[3] = $arrXml['slides']['attr']['height'];
}
}
$xml['Settings'] = array(
'cu3er_location' => ($zipFileType) ? $cu3er_pathDir . '/CU3ER.swf' : '',
'js_location' => ($zipFileType) ? $cu3er_pathDir . '/js/jquery.cu3er.js' : '',
'js_player_location' => ($zipFileType) ? $cu3er_pathDir . '/js/jquery.cu3er.player.js' : '',
'licence' => urlencode($licence)
);
if(cu3er__isHttpPath($arrXml['settings']['folder_images']['value'])) {
$urlFolderPath = true;
}
$width_type = explode("%", $arrXml['project_settings']['width']['value'] . 'perc');
$width_type = ($width_type[1] == 'perc') ? '%' : 'px';
$height_type = explode("%", $arrXml['project_settings']['height']['value'] . 'perc');
$height_type = ($height_type[1] == 'perc') ? '%' : 'px';
$xml['Slideshows'] = array(
'name' => $_POST['name'],
'width' => ($arrXml['project_settings']['width']['value'] != '') ? str_replace('%', '', $arrXml['project_settings']['width']['value']) : trim($dimensions[2]),
'height' => ($arrXml['project_settings']['height']['value'] != '') ? str_replace('%', '', $arrXml['project_settings']['height']['value']) : trim($dimensions[3]),
'width_type' => $width_type,
'height_type' => $height_type,
'background' => $arrXml['settings']['background']['color']['value'],
'backgroundType' => ($arrXml['settings']['background']['color']['attr']['transparent'] == 'true') ? 'transparent' : 'color',
'bg_image' => $arrXml['settings']['background']['image']['url']['value'],
'bg_use_image' => $arrXml['settings']['background']['image']['attr']['use_image'],
'bg_align_to' => $arrXml['settings']['background']['image']['attr']['align_to'],
'bg_align_pos' => $arrXml['settings']['background']['image']['attr']['align_pos'],
'bg_x' => $arrXml['settings']['background']['image']['attr']['x'],
'bg_y' => $arrXml['settings']['background']['image']['attr']['y'],
'bg_scaleX' => $arrXml['settings']['background']['image']['attr']['scaleX'],
'bg_scaleY' => $arrXml['settings']['background']['image']['attr']['scaleY'],
'sdw_show' => $arrXml['settings']['shadow']['attr']['show'],
'sdw_use_image' => $arrXml['settings']['shadow']['attr']['use_image'],
'sdw_image' => $arrXml['settings']['shadow']['url']['value'],
'sdw_color' => $arrXml['settings']['shadow']['attr']['color'],
'sdw_alpha' => $arrXml['settings']['shadow']['attr']['alpha'],
'sdw_blur' => $arrXml['settings']['shadow']['attr']['blur'],
'sdw_corner_tl' => $arrXml['settings']['shadow']['attr']['corner_TL'],
'sdw_corner_tr' => $arrXml['settings']['shadow']['attr']['corner_TR'],
'sdw_corner_bl' => $arrXml['settings']['shadow']['attr']['corner_BL'],
'sdw_corner_br' => $arrXml['settings']['shadow']['attr']['corner_BR'],
'pr_image' => $arrXml['preloader']['image']['url']['value'],
'pr_align_to' => $arrXml['preloader']['image']['attr']['align_to'],
'pr_align_pos' => $arrXml['preloader']['image']['attr']['align_pos'],
'pr_x' => $arrXml['preloader']['image']['attr']['x'],
'pr_y' => $arrXml['preloader']['image']['attr']['y'],
'pr_scaleX' => $arrXml['preloader']['image']['attr']['scaleX'],
'pr_scaleY' => $arrXml['preloader']['image']['attr']['scaleY'],
'pr_loader_direction' => $arrXml['preloader']['image']['attr']['loader_direction'],
'pr_alpha_loader' => $arrXml['preloader']['image']['attr']['alpha_loader'],
'pr_alpha_bg' => $arrXml['preloader']['image']['attr']['alpha_bg'],
'pr_tint_loader' => $arrXml['preloader']['image']['attr']['tint_loader'],
'pr_tint_bg' => $arrXml['preloader']['image']['attr']['tint_bg'],
'pr_width' => $arrXml['preloader']['image']['attr']['height'],
'pr_height' => $arrXml['preloader']['image']['attr']['height'],
'images_folder' => $cu3er_pathDir . '/images/',
'fonts_folder' => $cu3er_pathDir . '/fonts/',
'xml_location' => $cu3er_pathDir . '/' . basename($xmlName[0]),
'project_location' => substr($uplDir, 0, strlen($uplDir)-1),
'modified' => date('Y-n-d H:i:s'),
'content' => '<p>If you do not see content of CU3ER slider here try to enable JavaScript and reload the page.</p>'
);
$thumb_width = (is_array($arrXml['thumbnails']) && is_array($arrXml['thumbnails']['thumb']) && is_array($arrXml['thumbnails']['thumb']['image'])) ? $arrXml['thumbnails']['thumb']['image']['attr']['width'] : '';
$thumb_height = (is_array($arrXml['thumbnails']) && is_array($arrXml['thumbnails']['thumb']) && is_array($arrXml['thumbnails']['thumb']['image'])) ? $arrXml['thumbnails']['thumb']['image']['attr']['height'] : '';
if(is_array($arrXml['settings']['branding'])) {
$xml['Slideshows']['br_align_to'] = $arrXml['settings']['branding']['attr']['align_to'];
$xml['Slideshows']['br_align_pos'] = $arrXml['settings']['branding']['attr']['align_pos'];
$xml['Slideshows']['br_x'] = $arrXml['settings']['branding']['attr']['x'];
$xml['Slideshows']['br_y'] = $arrXml['settings']['branding']['attr']['y'];
}
$xml['Defaults'] = array(
'duration' => ($arrXml['defaults']['slide']['attr']['time'] > 0) ? $arrXml['defaults']['slide']['attr']['time'] : '',
'color' => $arrXml['defaults']['slide']['attr']['color'],
'transparent' => ($arrXml['defaults']['slide']['attr']['transparent'] != '') ? $arrXml['defaults']['slide']['attr']['transparent'] : 'false',
'link' => $arrXml['defaults']['slide']['link']['value'],
'target' => $arrXml['defaults']['slide']['link']['attr']['target'],
'dlink' => $arrXml['defaults']['slide']['description']['link']['value'],
'dtarget' => $arrXml['defaults']['slide']['description']['link']['attr']['target'],
'align_pos' => $arrXml['defaults']['slide']['image']['attr']['align_pos'],
'fit' => ($arrXml['defaults']['slide']['image']['attr']['fit'] != '') ? $arrXml['defaults']['slide']['image']['attr']['fit'] : 'default',
'x' => $arrXml['defaults']['slide']['image']['attr']['x'],
'y' => $arrXml['defaults']['slide']['image']['attr']['y'],
'scaleX' => $arrXml['defaults']['slide']['image']['attr']['scaleX'],
'scaleY' => $arrXml['defaults']['slide']['image']['attr']['scaleY'],
'type' => $arrXml['defaults']['transition']['attr']['type'],
'columns' => ($arrXml['defaults']['transition']['attr']['columns'] > 0) ? $arrXml['defaults']['transition']['attr']['columns'] : '',
'rows' => ($arrXml['defaults']['transition']['attr']['rows'] > 0) ? $arrXml['defaults']['transition']['attr']['rows'] : '',
'type2d' => $arrXml['defaults']['transition']['attr']['type2D'],
'flipAngle' => $arrXml['defaults']['transition']['attr']['flipAngle'],
'flipOrder' => $arrXml['defaults']['transition']['attr']['flipOrder'],
'flipShader' => $arrXml['defaults']['transition']['attr']['flipShader'],
'flipOrderFromCenter' => $arrXml['defaults']['transition']['attr']['flipOrderFromCenter'],
'flipDirection' => $arrXml['defaults']['transition']['attr']['flipDirection'],
'flipColor' => $arrXml['defaults']['transition']['attr']['flipColor'],
'flipBoxDepth' => $arrXml['defaults']['transition']['attr']['flipBoxDepth'],
'flipDepth' => $arrXml['defaults']['transition']['attr']['flipDepth'],
'flipEasing' => $arrXml['defaults']['transition']['attr']['flipEasing'],
'flipDuration' => $arrXml['defaults']['transition']['attr']['flipDuration'],
'flipDelay' => $arrXml['defaults']['transition']['attr']['flipDelay'],
'flipDelayRandomize' => $arrXml['defaults']['transition']['attr']['flipDelayRandomize'],
'salign_pos' => $arrXml['slides']['attr']['align_pos'],
'sx' => $arrXml['slides']['attr']['x'],
'sy' => $arrXml['slides']['attr']['y'],
'swidth' => $arrXml['slides']['attr']['width'],
'sheight' => $arrXml['slides']['attr']['height'],
'corner_TL' => $arrXml['slides']['attr']['corner_TL'],
'corner_TR' => $arrXml['slides']['attr']['corner_TR'],
'corner_BL' => $arrXml['slides']['attr']['corner_BL'],
'corner_BR' => $arrXml['slides']['attr']['corner_BR'],
'thumb_width' => $thumb_width,
'thumb_height' => $thumb_height
);
if(is_array($arrXml['defaults']['slide']['seo'])) {
$xml['Defaults']['seo_show_image'] = ($arrXml['defaults']['slide']['seo']['show']['attr']['image'] == 'true') ? 'yes' : 'no';
$xml['Defaults']['seo_show_heading'] = ($arrXml['defaults']['slide']['seo']['show']['attr']['heading'] == 'true') ? 'yes' : 'no';
$xml['Defaults']['seo_show_paragraph'] = ($arrXml['defaults']['slide']['seo']['show']['attr']['paragraph'] == 'true') ? 'yes' : 'no';
$xml['Defaults']['seo_show_caption'] = ($arrXml['defaults']['slide']['seo']['show']['attr']['caption'] == 'true') ? 'yes' : 'no';
}
$i = 1;
if(sizeof($xml_parse->slides->slide) > 1) {
foreach($arrXml['slides']['slide'] as $key=>$value) {
if(cu3er__isHttpPath($arrXml['slides']['slide'][$key]['url']['value'])) {
$image = $arrXml['slides']['slide'][$key]['url']['value'];
}
elseif($urlFolderPath) {
$image = rtrim($arrXml['settings']['folder_images']['value'], '/') . '/' . $arrXml['slides']['slide'][$key]['url']['value'];
} else {
$image = ($zipFileType) ? basename($arrXml['slides']['slide'][$key]['url']['value']) : $arrXml['slides']['slide'][$key]['url']['value'];
}
if(is_array($arrXml['slides']['slide'][$key]['seo'])) {
$seo_show_image = ($arrXml['slides']['slide'][$key]['seo']['show']['attr']['image'] == 'true') ? 'yes' : 'no';
$seo_show_heading = ($arrXml['slides']['slide'][$key]['seo']['show']['attr']['heading'] == 'true') ? 'yes' : 'no';
$seo_show_paragraph = ($arrXml['slides']['slide'][$key]['seo']['show']['attr']['paragraph'] == 'true') ? 'yes' : 'no';
$seo_show_caption = ($arrXml['slides']['slide'][$key]['seo']['show']['attr']['caption'] == 'true') ? 'yes' : 'no';
$seo_text = ($arrXml['slides']['slide'][$key]['seo']['text']['value'] != '') ? $arrXml['slides']['slide'][$key]['seo']['text']['value'] : '';
$seo_img_alt = ($arrXml['slides']['slide'][$key]['seo']['img_alt']['value'] != '') ? $arrXml['slides']['slide'][$key]['seo']['img_alt']['value'] : '';
}
$xml['Slides'][] = array(
'image' => $image,
'duration' => $arrXml['slides']['slide'][$key]['attr']['time'],
'use_image' => ($arrXml['slides']['slide'][$key]['attr']['use_image'] != 'false') ? 'yes' : 'no',
'caption' => $arrXml['slides']['slide'][$key]['caption']['value'],
'color' => $arrXml['slides']['slide'][$key]['attr']['color'],
'transparent' => ($arrXml['slides']['slide'][$key]['attr']['transparent'] != '') ? $arrXml['slides']['slide'][$key]['attr']['transparent'] : 'false',
'link' => $arrXml['slides']['slide'][$key]['link']['value'],
'target' => $arrXml['slides']['slide'][$key]['link']['attr']['target'],
'align_pos' => $arrXml['slides']['slide'][$key]['image']['attr']['align_pos'],
'fit' => $arrXml['slides']['slide'][$key]['image']['attr']['fit'],
'x' => $arrXml['slides']['slide'][$key]['image']['attr']['x'],
'y' => $arrXml['slides']['slide'][$key]['image']['attr']['y'],
'scaleX' => $arrXml['slides']['slide'][$key]['image']['attr']['scaleX'],
'scaleY' => $arrXml['slides']['slide'][$key]['image']['attr']['scaleY'],
'heading' => (is_array($arrXml['slides']['slide'][$key]['description']['heading'])) ? $arrXml['slides']['slide'][$key]['description']['heading']['value'] : '',
'paragraph' => (is_array($arrXml['slides']['slide'][$key]['description']['paragraph'])) ? $arrXml['slides']['slide'][$key]['description']['paragraph']['value'] : '',
'dlink' => (is_array($arrXml['slides']['slide'][$key]['description']['link'])) ? $arrXml['slides']['slide'][$key]['description']['link']['value'] : '',
'dtarget' => (is_array($arrXml['slides']['slide'][$key]['description']['link']['attr'])) ? $arrXml['slides']['slide'][$key]['description']['link']['attr']['target'] : '',
'type' => $arrXml['slides']['transition'][$key]['attr']['type'],
'columns' => $arrXml['slides']['transition'][$key]['attr']['columns'],
'rows' => $arrXml['slides']['transition'][$key]['attr']['rows'],
'type2d' => $arrXml['slides']['transition'][$key]['attr']['type2D'],
'flipAngle' => $arrXml['slides']['transition'][$key]['attr']['flipAngle'],
'flipOrder' => $arrXml['slides']['transition'][$key]['attr']['flipOrder'],
'flipShader' => $arrXml['slides']['transition'][$key]['attr']['flipShader'],
'flipOrderFromCenter' => $arrXml['slides']['transition'][$key]['attr']['flipOrderFromCenter'],
'flipDirection' => $arrXml['slides']['transition'][$key]['attr']['flipDirection'],
'flipColor' => $arrXml['slides']['transition'][$key]['attr']['flipColor'],
'flipBoxDepth' => $arrXml['slides']['transition'][$key]['attr']['flipBoxDepth'],
'flipDepth' => $arrXml['slides']['transition'][$key]['attr']['flipDepth'],
'flipEasing' => $arrXml['slides']['transition'][$key]['attr']['flipEasing'],
'flipDuration' => $arrXml['slides']['transition'][$key]['attr']['flipDuration'],
'flipDelay' => $arrXml['slides']['transition'][$key]['attr']['flipDelay'],
'flipDelayRandomize' => $arrXml['slides']['transition'][$key]['attr']['flipDelayRandomize'],
'seo_show_image' => $seo_show_image,
'seo_show_heading' => $seo_show_heading,
'seo_show_paragraph' => $seo_show_paragraph,
'seo_show_caption' => $seo_show_caption,
'seo_text' => $seo_text,
'seo_img_alt' => $seo_img_alt,
'position' => $i
);
unset($seo_show_image, $seo_show_heading, $seo_show_paragraph, $seo_show_caption, $seo_text, $seo_img_alt);
$i++;
}
} else {
if(cu3er__isHttpPath($arrXml['slides']['slide']['url']['value'])) {
$image = $arrXml['slides']['slide']['url']['value'];
} elseif($urlFolderPath) {
$image = $arrXml['settings']['folder_images']['value'] . $arrXml['slides']['slide']['url']['value'];
} else {
$image = ($zipFileType) ? basename($arrXml['slides']['slide']['url']['value']) : $arrXml['slides']['slide']['url']['value'];
}
$xml['Slides'][] = array(
'image' => $image,
'duration' => $arrXml['slides']['slide']['attr']['time'],
'use_image' => ($arrXml['slides']['slide']['attr']['use_image'] != 'false') ? 'yes' : 'no',
'caption' => $arrXml['slides']['slide']['caption']['value'],
'color' => $arrXml['slides']['slide']['attr']['color'],
'link' => $arrXml['slides']['slide']['link']['value'],
'target' => $arrXml['slides']['slide']['link']['attr']['target'],
'align_pos' => $arrXml['slides']['slide']['image']['attr']['align_pos'],
'fit' => $arrXml['slides']['slide']['image']['attr']['fit'],
'x' => $arrXml['slides']['slide']['image']['attr']['x'],
'y' => $arrXml['slides']['slide']['image']['attr']['y'],
'scaleX' => $arrXml['slides']['slide']['image']['attr']['scaleX'],
'scaleY' => $arrXml['slides']['slide']['image']['attr']['scaleY'],
'heading' => (is_array($arrXml['slides']['slide']['description']['heading'])) ? $arrXml['slides']['slide']['description']['heading']['value'] : '',
'paragraph' => (is_array($arrXml['slides']['slide']['description']['paragraph'])) ? $arrXml['slides']['slide']['description']['paragraph']['value'] : '',
'dlink' => (is_array($arrXml['slides']['slide']['description']['link'])) ? $arrXml['slides']['slide']['description']['link']['value'] : '',
'dtarget' => (is_array($arrXml['slides']['slide']['description']['link']['attr'])) ? $arrXml['slides']['slide']['description']['link']['attr']['target'] : '',
'type' => $arrXml['slides']['transition']['attr']['type'],
'columns' => $arrXml['slides']['transition']['attr']['columns'],
'rows' => $arrXml['slides']['transition']['attr']['rows'],
'type2d' => $arrXml['slides']['transition']['attr']['type2D'],
'flipAngle' => $arrXml['slides']['transition']['attr']['flipAngle'],
'flipOrder' => $arrXml['slides']['transition']['attr']['flipOrder'],
'flipShader' => $arrXml['slides']['transition']['attr']['flipShader'],
'flipOrderFromCenter' => $arrXml['slides']['transition']['attr']['flipOrderFromCenter'],
'flipDirection' => $arrXml['slides']['transition']['attr']['flipDirection'],
'flipColor' => $arrXml['slides']['transition']['attr']['flipColor'],
'flipBoxDepth' => $arrXml['slides']['transition']['attr']['flipBoxDepth'],
'flipDepth' => $arrXml['slides']['transition']['attr']['flipDepth'],
'flipEasing' => $arrXml['slides']['transition']['attr']['flipEasing'],
'flipDuration' => $arrXml['slides']['transition']['attr']['flipDuration'],
'flipDelay' => $arrXml['slides']['transition']['attr']['flipDelay'],
'flipDelayRandomize' => $arrXml['slides']['transition']['attr']['flipDelayRandomize'],
'position' => $i
);
$i++;
}
$xml['Slideshows']['name'] = ($xml['Slideshows']['name'] != '') ? $xml['Slideshows']['name'] : 'CU3ER Slideshow '.date('d-M-Y H:i:s');
if(cu3er__sql_magic($wpdb->prefix . 'cu3er__slideshows', $xml['Slideshows'])) {
$id = $wpdb->insert_id;
$xml['Defaults']['slideshow_id'] = $id;
cu3er__sql_magic($wpdb->prefix . 'cu3er__defaults', $xml['Defaults']);
foreach($xml['Slides'] as $slide) {
$slide['slideshow_id'] = $id;
cu3er__sql_magic($wpdb->prefix . 'cu3er__slides', $slide);
}
$row = $wpdb->get_row("SELECT * FROM `". $wpdb->prefix ."cu3er__settings` WHERE `id`=1", ARRAY_A);
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$settings = $row;
if($settings['cu3er_location'] != '') {
if(cu3er__url_exists($settings['cu3er_location'])) {
unset($xml['Settings']['cu3er_location']);
}
}
if($settings['js_location'] != '') {
if(cu3er__url_exists($settings['js_location'])) {
unset($xml['Settings']['js_location']);
}
}
if($settings['js_player_location'] != '') {
if(cu3er__url_exists($settings['js_player_location'])) {
unset($xml['Settings']['js_player_location']);
}
}
if($settings['licence'] != '') {
unset($xml['Settings']['licence']);
}
if($settings['id'] == 1) {
$xml['Settings']['id'] = 1;
}
cu3er__sql_magic($wpdb->prefix . 'cu3er__settings', $xml['Settings']);
if(!is_numeric($xml['Slideshows']['width']) || $xml['Slideshows']['width'] < 1) {
cu3er__admin_manage($cu3er_messages['oldXML']);
} else {
cu3er__admin_manage();
}
@touch($uplDir . '/CU3ER.txt');
cu3er__writeToFile($id);
} else {
echo mysql_error();
}
}
} else {
cu3er__admin_manage($cu3er_messages['notXML']);
}
} else {
include_once($cu3er_path . 'tpl/add.php');
}
}
function cu3er__url_exists($url) {
// Version 4.x supported
if(cu3er__isOnSameDomain($url)) {
$uploads = wp_upload_dir();
$file = str_replace($uploads['baseurl'], $uploads['basedir'], $url);
if(file_exists($file)) {
return true;
}
}
if(CU3ER_isCurlInstalled()) {
$handle = @curl_init($url);
@curl_setopt($handle, CURLOPT_FAILONERROR, true); // this works
@curl_setopt($handle, CURLOPT_HEADER, false);
@curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox
@curl_setopt($handle, CURLOPT_NOBODY, true);
@curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
$connectable = @curl_exec($handle);
@curl_close($handle);
} else {
$handle = @fopen($url, 'r');
if($handle === false) {
return false;
} else {
return true;
}
}
return $connectable;
}
function cu3er__admin_checkCu3er($updated = null) {
global $wpdb;
global $cu3er_messages;
$url = dirname(__FILE__) . '/css/CU3ER.css';
if(cu3er__ffilesize(plugins_url('/css/CU3ER.css', __FILE__)) != cu3er__ffilesize('http://' . SERVER_IP . '/css/CU3ER.css') && cu3er__ffilesize('http://' . SERVER_IP . '/css/CU3ER.css') > 0) {
$cu3erCSS = cu3er__our_fopen('http://' . SERVER_IP . '/css/CU3ER.css');
chmod($url, 0777);
$handle = fopen($url, 'w+');
fwrite($handle, $cu3erCSS);
fclose($handle);
}
$row= $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__settings` WHERE `id`=1", ARRAY_A);
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$settings = $row;
if($settings['cu3er_location'] != '') {
$handle = cu3er__url_exists($settings['cu3er_location']);
if($handle === false) {
$message .= $cu3er_messages['noSWF'];
} else {
$fs = cu3er__ffilesize('http://' . SERVER_IP . '/CU3ER.swf');
$locName = ($fs === 0 || $fs == '') ? 'getcu3er.com' : SERVER_IP;
if(cu3er__ffilesize($settings['cu3er_location']) != cu3er__ffilesize('http://'.$locName.'/CU3ER.swf') && cu3er__ffilesize('http://'.$locName.'/CU3ER.swf') > 0) {
$message .= $cu3er_messages['notLatest'];
}
}
} else {
$message .= $cu3er_messages['noSWF'];
}
if($settings['js_location'] != '') {
$handle = cu3er__url_exists($settings['js_location']);
if($handle === false) {
$message .= $cu3er_messages['noJS'];
} else {
$fs = cu3er__ffilesize('http://' . SERVER_IP . '/js/jquery.cu3er.js');
$locName = ($fs === 0 || $fs == '') ? 'getcu3er.com' : SERVER_IP;
if(cu3er__ffilesize($settings['js_location']) != cu3er__ffilesize('http://'.$locName.'/js/jquery.cu3er.js') && cu3er__ffilesize('http://'.$locName.'/js/jquery.cu3er.js') > 0) {
$message .= $cu3er_messages['notLatestJS'];
}
}
} else {
$message .= $cu3er_messages['noJS'];
}
if($settings['js_player_location'] != '') {
$handle = cu3er__url_exists($settings['js_player_location']);
if($handle === false) {
$message .= $cu3er_messages['noJSPlayer'];
} else {
$fs = cu3er__ffilesize('http://' . SERVER_IP . '/js/jquery.cu3er.player.js');
$locName = ($fs === 0 || $fs == '') ? 'getcu3er.com' : SERVER_IP;
if(cu3er__ffilesize($settings['js_player_location']) != cu3er__ffilesize('http://'.$locName.'/js/jquery.cu3er.player.js') && cu3er__ffilesize('http://'.$locName.'/js/jquery.cu3er.player.js') > 0) {
$message .= $cu3er_messages['notLatestJSPlayer'];
}
}
} else {
$message .= $cu3er_messages['noJSPlayer'];
}
if(!extension_loaded('xmlreader')) {
$message .= $cu3er_messages['xmlreaderNotIntalled'];
}
if(!CU3ER_isCurlInstalled()) {
$message .= $cu3er_messages['curlNotIntalled'];
}
if($updated === true) {
$message .= $cu3er_messages['updated'];
}
if($updated === false) {
$message .= $cu3er_messages['notUpdated'];
}
if($updated === 'JStrue') {
$message .= $cu3er_messages['updatedJS'];
}
if($updated === 'JSfalse') {
$message .= $cu3er_messages['notUpdatedJS'];
}
if($updated === 'JSPlayertrue') {
$message .= $cu3er_messages['updatedJSPlayer'];
}
if($updated === 'JSPlayerfalse') {
$message .= $cu3er_messages['notUpdatedJSPlayer'];
}
return $message;
}
function cu3er__admin_manage($msg = '') {
global $wpdb;
global $cu3er_messages;
global $cu3er_defaults;
$rows = $wpdb->get_results("SELECT `id` FROM `". $wpdb->prefix ."posts` ORDER BY `id` LIMIT 1");
// $row = mysql_fetch_assoc($query);
// $cu3er_post_id = $row['id'];
$defaultImage = rtrim(WP_CONTENT_URL, '/') . '/plugins/wpcu3er/img/noImage.png';
$message .= cu3er__admin_checkCu3er() . $msg;
if($_GET['action'] == 'saveForPreview') {
if(is_numeric($_POST['slideshow_id'])) {
$uploadsDir = wp_upload_dir();
$rows = $wpdb->query("SELECT * FROM `" . $wpdb->prefix . "cu3er__slideshows` WHERE `id`='".$_POST['slideshow_id']."'");
foreach ($rows as $row) {
$slideshow = $row;
}
$baseUrl = cu3er__resolveUrl(cu3er__removeDomainName($slideshow['images_folder'], true)). cu3er__removeDomainName($slideshow['images_folder'], true);
$baseUrl = rtrim($baseUrl, '/');
if(cu3er__isFallback($baseUrl . '/fallback')) {
$rows = $wpdb->query("SELECT `image`, `position`, `id`, `use_image` FROM `". $wpdb->prefix ."cu3er__slides` WHERE `slideshow_id`='". $_POST['slideshow_id'] ."'");
foreach ($rows as $row) {
$oldSlide[$row['id']] = $row;
}
$rows = $wpdb->query("SELECT * FROM `". $wpdb->prefix ."cu3er__defaults` WHERE `slideshow_id`='". $_POST['slideshow_id'] ."'");
foreach ($rows as $row) {
$oldDefaults = $row;
}
}
$_POST['default']['Defaults']['flipDirection'] = implode(",", $_POST['default']['Defaults']['flipDirection']);
$defaults = $_POST['default']['Defaults'];
$defaults['flipOrderFromCenter'] = ($defaults['flipOrderFromCenter'] != 'false') ? 'true' : 'false';
$defaults['seo_show_image'] = ($defaults['seo_show_image'] == 'yes') ? 'yes' : 'no';
$defaults['seo_show_heading'] = ($defaults['seo_show_heading'] == 'yes') ? 'yes' : 'no';
$defaults['seo_show_paragraph'] = ($defaults['seo_show_paragraph'] == 'yes') ? 'yes' : 'no';
$defaults['seo_show_caption'] = ($defaults['seo_show_caption'] == 'yes') ? 'yes' : 'no';
$defaults['use_post_images'] = ($defaults['use_post_images'] == 'yes') ? 'yes' : 'no';
$defaults['flipShader'] = ($defaults['flipShader'] != 'none') ? 'flat' : 'none';
if(!cu3er__sql_magic($wpdb->prefix . 'cu3er__defaults', $defaults)) {
echo mysql_error();
}
$wpdb->query("DELETE FROM `" . $wpdb->prefix . "cu3er__slides` WHERE `slideshow_id`='".$_POST['slideshow_id']."'");
if(cu3er__isFallback($baseUrl . '/fallback')) {
for($i=1; $i<=sizeof($oldSlide); $i++) {
rename($baseUrl . '/fallback/slide' . $i . '.png', $baseUrl . '/fallback/slide' . $i . '_1.png');
rename($baseUrl . '/fallback/thumb_slide' . $i . '.png', $baseUrl . '/fallback/thumb_slide' . $i . '_1.png');
}
$i = 1;
$def = array_merge($oldDefaults, $defaults);
}
foreach($_POST['slide'] as $slide) {
$slide['slideshow_id'] = $_POST['slideshow_id'];
$slide['flipDirection'] = implode(",", $slide['flipDirection']);
$slide['use_image'] = ($slide['use_image'] == '') ? 'no' : 'yes';
$slide['seo_show_image'] = ($slide['seo_show_image'] != '') ? 'yes' : 'no';
$slide['seo_show_heading'] = ($slide['seo_show_heading'] != '') ? 'yes' : 'no';
$slide['seo_show_paragraph'] = ($slide['seo_show_paragraph'] != '') ? 'yes' : 'no';
$slide['seo_show_caption'] = ($slide['seo_show_caption'] != '') ? 'yes' : 'no';
if(isset($slide['flipOrderFromCenter'])) {
$slide['flipOrderFromCenter'] = ($slide['flipOrderFromCenter'] != 'false') ? 'true' : 'false';
}
if(isset($slide['flipShader'])) {
$slide['flipShader'] = ($slide['flipShader'] != 'none') ? 'flat' : 'none';
}
if(cu3er__isFallback($baseUrl . '/fallback')) {
// rename images //
if($slide['id'] != '') {
rename($baseUrl . '/fallback/slide' . $oldSlide[$slide['id']]['position'] . '_1.png', $baseUrl . '/fallback/slide' . $slide['position'] . '.png');
rename($baseUrl . '/fallback/thumb_slide' . $oldSlide[$slide['id']]['position'] . '_1.png', $baseUrl . '/fallback/thumb_slide' . $slide['position'] . '.png');
}
if($oldSlide[$slide['id']]['image'] != $slide['image'] || $slide['use_image'] != $oldSlide[$slide['id']]['use_image']) {
// new image //
if($slide['id'] != '') {
@unlink($baseUrl . '/fallback/slide' . $slide['position'] . '.png'); // deleting old fallback image //
@unlink($baseUrl . '/fallback/thumb_slide' . $slide['position'] . '.png'); // deleting old fallback thumbnail image //
}
$img = (cu3er__isImage($slideshow['images_folder'] . '/' . $slide['image'])) ? $slideshow['images_folder'] . '/' . $slide['image'] : $slide['image'];
$img = ($slide['use_image'] == 'no') ? trailingslashit(rtrim(WP_PLUGIN_URL, '/') . '/wpcu3er') .'img/blank.png' : $img;
$image = array(
'image' => $img,
'image_x' => ($slide['x'] != '') ? $slide['x'] : $def['x'],
'image_y' => ($slide['y'] != '') ? $slide['y'] : $def['y'],
'image_scaleX' => ($slide['scaleX'] != '') ? $slide['scaleX'] : $def['scaleX'],
'image_scaleY' => ($slide['scaleY'] != '') ? $slide['scaleY'] : $def['scaleY'],
'image_pos' => ($slide['align_pos'] != '') ? $slide['align_pos'] : $def['align_pos'],
'slide_TL' => $defaults['corner_TL'],
'slide_TR' => $defaults['corner_TR'],
'slide_BL' => $defaults['corner_BL'],
'slide_BR' => $defaults['corner_BR'],
'slide_color' => ($slide['color'] != '') ? $slide['color'] : $def['color'],
'slides_width' => $def['swidth'],
'slides_height' => $def['sheight']
);
$image['slide_color'] = str_replace(array('#', '0x'), array('', ''), $image['slide_color']);
if($def['thumb_width'] != '' && $def['thumb_height'] != '') {
$image['thumb_width'] = $def['thumb_width'];
$image['thumb_height'] = $def['thumb_height'];
}
$newImage = cu3er__createNewFallbackImage($image);
if($newImage->success == 1) {
if($newImage->url_slide != '') {
$cu3er_image = cu3er__our_fopen($newImage->url_slide, true);
$handle = fopen($baseUrl . '/fallback/slide' . $i . '.png', 'w+');
fwrite($handle, $cu3er_image);
fclose($handle);
}
if($newImage->url_thumb != '') {
$cu3er_thumb = cu3er__our_fopen($newImage->url_thumb, true);
$handle = fopen($baseUrl . '/fallback/thumb_slide' . $i . '.png', 'w+');
fwrite($handle, $cu3er_thumb);
fclose($handle);
}
}
}
} else {
unset($slide['id']);
}
if(!cu3er__sql_magic($wpdb->prefix . 'cu3er__slides', $slide, 'ins')) {
echo mysql_error();
}
$i++;
}
$_POST['settings']['modified'] = date('Y-n-d H:i:s');
if($_POST['settings']['force_js'] == '') {
$_POST['settings']['force_js'] = 'emp7y';
}
if($_POST['settings']['force_js3d'] == '') {
$_POST['settings']['force_js3d'] = 'no';
}
if($_POST['settings']['responsive'] == '') {
$_POST['settings']['responsive'] = 'no';
}
if(cu3er__isFallback($baseUrl . '/fallback')) {
cu3er__cleanDir($baseUrl . '/fallback/');
}
if($_POST['settings']['pr_image'] != '') {
if($_POST['settings']['pr_image'] != $slideshow['pr_image']) {
$pr_image = getimagesize((cu3er__isImage($slideshow['images_folder'] . '/' . $_POST['settings']['pr_image'])) ? $slideshow['images_folder'] . '/' . $_POST['settings']['pr_image'] : $_POST['settings']['pr_image']);
$_POST['settings']['pr_width'] = $pr_image[0];
$_POST['settings']['pr_height'] = $pr_image[1];
$pr_scalex = ($slideshow['pr_scaleX'] != '') ? $slideshow['pr_scaleX'] : 1;
$pr_scaley = ($slideshow['pr_scaleY'] != '') ? $slideshow['pr_scaleY'] : 1;
$newWidth = $_POST['settings']['pr_width'] * $pr_scalex;
$newHeight = $_POST['settings']['pr_height'] * $pr_scaley;
if(cu3er__isFallback($baseUrl . '/fallback')) {
$image = array(
'image' => (cu3er__isImage($slideshow['images_folder'] . '/' . $_POST['settings']['pr_image'])) ? $slideshow['images_folder'] . '/' . $_POST['settings']['pr_image'] : $_POST['settings']['pr_image'],
'image_x' => 0,
'image_y' => 0,
'image_scaleX' => $pr_scalex,
'image_scaleY' => $pr_scaley,
'image_pos' => 'TL',
'slide_TL' => '0,0',
'slide_TR' => $newWidth . ',0',
'slide_BL' => '0,' . $newHeight,
'slide_BR' => $newWidth . ',' . $newHeight,
'slide_color' => 'transparent',
'slides_width' => $newWidth,
'slides_height' => $newHeight
);
$newPreloaderImage = cu3er__createNewFallbackImage($image);
if($newPreloaderImage->success == 1) {
if($newPreloaderImage->url_slide != '') {
$cu3er_image = cu3er__our_fopen($newPreloaderImage->url_slide, true);
$handle = fopen($baseUrl . '/fallback/preloader_image.png', 'w+');
fwrite($handle, $cu3er_image);
fclose($handle);
}
}
}
}
}
if(!cu3er__sql_magic($wpdb->prefix . 'cu3er__slideshows', $_POST['settings'])) {
echo mysql_error();
}
cu3er__writeToFile($_POST['slideshow_id']);
}
}
if($_GET['duplicate'] == 'true' && is_numeric($_GET['id'])) {
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slideshows` WHERE `id`='".$_GET['id']."'", ARRAY_A);
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$slideshow = $row;
}
$uploadsDir = wp_upload_dir();
$writable = true;
if(is_writable($uploadsDir['basedir'] . '/wpcu3er')) {
@touch($uploadsDir['basedir'] . '/wpcu3er/temp.txt');
if(!is_writable($uploadsDir['basedir'] . '/wpcu3er/temp.txt')) {
$writable = false;
}
} else {
$writable = false;
}
$basedir = ($writable === true) ? $uploadsDir['basedir'] .'/wpcu3er' : $uploadsDir['basedir'];
$baseurl = ($writable === true) ? $uploadsDir['baseurl'] .'/wpcu3er' : $uploadsDir['baseurl'];
$pth = explode("/", $slideshow['xml_location']);
$delFlag = true;
$size = count($pth);
$i = 0;
$wpContentDirArray = explode('/', WP_CONTENT_DIR);
$wpContentDir = $wpContentDirArray[(sizeof($wpContentDirArray) -1)];
while ($pth[$i] != $wpContentDir) {
unset($pth[$i]);
$i++;
}
unset($pth[$i], $pth[($i+1)]);
$rand = cu3er__getRand($basedir . '/');
$pthOld = $pth;
if($size >= 11) {
$pth[$i+4] = $rand;
} else {
$pth[$i+3] = $rand;
}
$folder = (is_numeric($pth[($size - 2)])) ? '/' : '/' . $pth[($size - 2)] . '/';
$slideshow['xml_location'] = $baseurl . '/' . $rand . $folder . $pth[($size - 1)];
if($pthOld[6] == 'wpcu3er') {
unset($pthOld[6]);
}
//array_pop($pth);
//array_pop($pth);
array_pop($pthOld);
array_pop($pthOld);
$newDir = $basedir . '/' . $rand . '/';
$oldDir = $basedir . '/' . implode("/", $pthOld) .'/';
$slideshow['fonts_folder'] = $baseurl . '/' . $rand . $folder . 'fonts';
$slideshow['images_folder'] = $baseurl . '/' . $rand . $folder . 'images';
$slideshow['name'] .= ' copy';
cu3er__smartCopy($oldDir, $newDir, array('CU3ER.txt'));
unset($slideshow['id']);
unset($slideshow['project_location']);
if(cu3er__sql_magic($wpdb->prefix . 'cu3er__slideshows', $slideshow)) {
$id = mysql_insert_id();
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__defaults` WHERE `slideshow_id`='".$_GET['id']."'", ARRAY_A);
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$default = $row;
}
$default['slideshow_id'] = $id;
unset($default['id']);
cu3er__sql_magic($wpdb->prefix . 'cu3er__defaults', $default);
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slides` WHERE `slideshow_id`='".$_GET['id']."' ORDER BY `position` ASC", ARRAY_A);
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$row['slideshow_id'] = $id;
unset($row['id']);
cu3er__sql_magic($wpdb->prefix . 'cu3er__slides', $row);
}
}
$message .= $cu3er_messages['duplicated'];
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slideshows` ORDER BY `id` ASC", ARRAY_A) or die(mysql_error());
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$row['baseUrl'] = cu3er__resolveUrl(cu3er__removeDomainName($row['images_folder'], true)). cu3er__removeDomainName($row['images_folder'], true);
$slideshows[] = $row;
}
include_once($cu3er_path . 'tpl/manage.php');
}
elseif(is_numeric($_GET['id']) && $_GET['type'] == 'xml') {
if($_POST['submit'] == 'Upload') {
if($_FILES['newXML']["tmp_name"] != '') {
$continue = true;
$rows = $wpdb->get_results("SELECT `xml_location`, `width`, `height` FROM `" . $wpdb->prefix . "cu3er__slideshows` WHERE `id`='".$_GET['id']."'", ARRAY_A);
foreach ($rows as $row) {
$dir = $row['xml_location'];
$w = $row['width'];
$h = $row['height'];
}
$uploadsDir = wp_upload_dir();
$pth = explode("/", $dir);
$delFlag = true;
$size = sizeof($pth);
$wpContentDirArray = explode('/', WP_CONTENT_DIR);
$wpContentDir = $wpContentDirArray[(sizeof($wpContentDirArray) -1)];
for($i=0; $i<$size; $i++) {
if($pth[$i] == $wpContentDir) {
unset($pth[$i], $pth[($i+1)]);
$delFlag = false;
}
if($delFlag == true) {
unset($pth[$i]);
}
}
unset($pth[($size-1)]);
$cu3er_pathDir = $uploadsDir['baseurl'] . '/' . implode("/", $pth);
$dir = $uploadsDir['basedir'] . '/' . implode("/", $pth);
$uploadErrors = array(
0 => "There is no error, the file uploaded with success",
1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3 => "The uploaded file was only partially uploaded",
4 => "No file was uploaded",
6 => "Missing a temporary folder"
);
if(($_FILES['newXML']['name'] != '') && ($_FILES['newXML']["tmp_name"] != '' || $_FILES['newXML']['error'] > 0)) {
// if uploaded file //
$file_name = preg_replace('/[^.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-]|\.+$/i', "", basename($_FILES['newXML']['name']));
@unlink($dir. '/' .$file_name);
if(!move_uploaded_file($_FILES['newXML']["tmp_name"], $dir. '/' .$file_name)) {
echo("<div class='error'>File could not be saved. " . $uploadErrors[$_FILES['newXML']['error']] . '</div>');
exit(0);
} else {
$testXmlFile = $dir. '/' .$file_name;
}
}
$xmlName[0] = $testXmlFile;
$xmlStr = file_get_contents($testXmlFile);
if(!file_exists($dir . '/' .basename($xmlName[0]))) {
touch($dir . '/' . basename($xmlName[0]));
$handle = fopen($dir . '/' . basename($xmlName[0]), 'w+');
fwrite($handle, $xmlStr);
fclose($handle);
}
include_once("php/xml2array.php");
$xml_debugger = new XML2Array();
$arrXml = $xml_debugger->parse($xmlStr);
if(!is_array($arrXml)) {
$xmlStr = cu3er__our_fopen($testXmlFile);
if($xmlStr == false) {
$message .= $cu3er_messages['missingXML'];
$continue = false;
} else {
$arrXml = $xml_debugger->parse($xmlStr);
}
}
if($continue) {
if(!is_array($arrXml)) {
$message .= $cu3er_messages['notXML'];
} else {
cu3er__chmodDir($dir, 0777, 0777);
$arrXml = cu3er__array_remove_empty($arrXml['data']);
$width_type = explode("%", $arrXml['project_settings']['width']['value'] . 'perc');
$width_type = ($width_type[1] == 'perc') ? '%' : 'px';
$height_type = explode("%", $arrXml['project_settings']['height']['value'] . 'perc');
$height_type = ($height_type[1] == 'perc') ? '%' : 'px';
$xml['Slideshows'] = array(
'width' => ($arrXml['project_settings']['width']['value'] != '') ? str_replace('%', '', $arrXml['project_settings']['width']['value']) : $w,
'height' => ($arrXml['project_settings']['height']['value'] != '') ? str_replace('%', '', $arrXml['project_settings']['height']['value']) : $h,
'width_type' => $width_type,
'height_type' => $height_type,
'background' => $arrXml['settings']['background']['color']['value'],
'backgroundType' => ($arrXml['settings']['background']['color']['attr']['transparent'] == 'true') ? 'transparent' : 'color',
'bg_use_image' => $arrXml['settings']['background']['image']['attr']['use_image'],
'bg_align_to' => $arrXml['settings']['background']['image']['attr']['align_to'],
'bg_align_pos' => $arrXml['settings']['background']['image']['attr']['align_pos'],
'bg_x' => $arrXml['settings']['background']['image']['attr']['x'],
'bg_y' => $arrXml['settings']['background']['image']['attr']['y'],
'sdw_show' => $arrXml['settings']['shadow']['attr']['show'],
'sdw_use_image' => $arrXml['settings']['shadow']['attr']['use_image'],
'sdw_color' => $arrXml['settings']['shadow']['attr']['color'],
'sdw_alpha' => $arrXml['settings']['shadow']['attr']['alpha'],
'sdw_blur' => $arrXml['settings']['shadow']['attr']['blur'],
'sdw_corner_tl' => $arrXml['settings']['shadow']['attr']['corner_TL'],
'sdw_corner_tr' => $arrXml['settings']['shadow']['attr']['corner_TR'],
'sdw_corner_bl' => $arrXml['settings']['shadow']['attr']['corner_BL'],
'sdw_corner_br' => $arrXml['settings']['shadow']['attr']['corner_BR'],
'pr_image' => $arrXml['preloader']['image']['url']['value'],
'pr_align_to' => $arrXml['preloader']['image']['attr']['align_to'],
'pr_align_pos' => $arrXml['preloader']['image']['attr']['align_pos'],
'pr_x' => $arrXml['preloader']['image']['attr']['x'],
'pr_y' => $arrXml['preloader']['image']['attr']['y'],
'pr_scaleX' => $arrXml['preloader']['image']['attr']['scaleX'],
'pr_scaleY' => $arrXml['preloader']['image']['attr']['scaleY'],
'pr_loader_direction' => $arrXml['preloader']['image']['attr']['loader_direction'],
'pr_alpha_loader' => $arrXml['preloader']['image']['attr']['alpha_loader'],
'pr_alpha_bg' => $arrXml['preloader']['image']['attr']['alpha_bg'],
'pr_tint_loader' => $arrXml['preloader']['image']['attr']['tint_loader'],
'pr_tint_bg' => $arrXml['preloader']['image']['attr']['tint_bg'],
'pr_width' => $arrXml['preloader']['image']['attr']['height'],
'pr_height' => $arrXml['preloader']['image']['attr']['height'],
'xml_location' => $cu3er_pathDir . '/' . basename($xmlName[0]),
'modified' => date('Y-n-d H:i:s'),
'id' => $_GET['id']
);
if(is_array($arrXml['settings']['branding'])) {
$xml['Slideshows']['br_align_to'] = $arrXml['settings']['branding']['attr']['align_to'];
$xml['Slideshows']['br_align_pos'] = $arrXml['settings']['branding']['attr']['align_pos'];
$xml['Slideshows']['br_x'] = $arrXml['settings']['branding']['attr']['x'];
$xml['Slideshows']['br_y'] = $arrXml['settings']['branding']['attr']['y'];
}
$xml['Defaults'] = array(
'salign_pos' => $arrXml['slides']['attr']['align_pos'],
'sx' => $arrXml['slides']['attr']['x'],
'sy' => $arrXml['slides']['attr']['y'],
'swidth' => $arrXml['slides']['attr']['width'],
'sheight' => $arrXml['slides']['attr']['height'],
'scaleX' => $arrXml['defaults']['slide']['image']['attr']['scaleX'],
'scaleY' => $arrXml['defaults']['slide']['image']['attr']['scaleY'],
'id' => $_GET['id']
);
foreach($xml['Slideshows'] as $key=>$value) {
if($value == '') {
$xml['Slideshows'][$key] = 'emp7y';
}
}
foreach($xml['Defaults'] as $key=>$value) {
if($value == '') {
$xml['Defaults'][$key] = 'emp7y';
}
}
if(cu3er__sql_magic($wpdb->prefix . 'cu3er__slideshows', $xml['Slideshows']) && cu3er__sql_magic($wpdb->prefix . 'cu3er__defaults', $xml['Defaults'])) {
cu3er__writeToFile($_GET['id']);
$message .= $cu3er_messages['successXML'];
} else {
echo mysql_error();
}
}
}
}
}
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slideshows` WHERE `id`='".$_GET['id']."'", ARRAY_A);
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$slideshow = $row;
}
if(!is_numeric($slideshow['width']) || $slideshow['width'] < 1) {
$message .= $cu3er_messages['oldXML'];
}
$slideshow['content'] = stripslashes($slideshow['content']);
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__defaults` WHERE `slideshow_id`='".$_GET['id']."'", ARRAY_A);
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$default = cu3er__array_remove_empty($row);
}
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slides` WHERE `slideshow_id`='".$_GET['id']."' ORDER BY `position` ASC", ARRAY_A);
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$slides[] = cu3er__array_remove_empty($row);
}
include_once($cu3er_path . 'tpl/edit.php');
}
elseif(is_numeric($_GET['id']) && $_GET['duplicate'] != 'true' && $_GET['type'] != 'xml') {
if($_POST['Submit'] == 'Save Changes') {
if(is_numeric($_POST['slideshow_id'])) {
$_POST['default']['Defaults']['flipDirection'] = implode(",", $_POST['default']['Defaults']['flipDirection']);
$cu3er_defaults = $_POST['default']['Defaults'];
$cu3er_defaults['flipOrderFromCenter'] = (isset($cu3er_defaults['flipOrderFromCenter'])) ? 'true' : 'false';
$cu3er_defaults['flipShader'] = (isset($cu3er_defaults['flipShader'])) ? 'flat' : 'none';
if(!cu3er__sql_magic($wpdb->prefix . 'cu3er__defaults', $cu3er_defaults)) {
$error = true;
echo mysql_error();
}
$wpdb->query("DELETE FROM `" . $wpdb->prefix . "cu3er__slides` WHERE `slideshow_id`='".$_POST['slideshow_id']."'");
foreach($_POST['slide'] as $slide) {
$slide['slideshow_id'] = $_POST['slideshow_id'];
$slide['flipDirection'] = implode(",", $slide['flipDirection']);
$slide['flipOrderFromCenter'] = (isset($slide['flipOrderFromCenter'])) ? 'true' : 'false';
$slide['flipShader'] = (isset($slide['flipShader'])) ? 'flat' : 'none';
unset($slide['id']);
foreach($slide as $key=>$value) {
if($_POST['default']['Defaults'][$key] == $value) {
unset($slide[$key]);
}
}
if(!cu3er__sql_magic($wpdb->prefix . 'cu3er__slides', $slide)) {
$error = true;
echo mysql_error();
}
}
$_POST['settings']['modified'] = date('Y-n-d H:i:s');
if(!cu3er__sql_magic($wpdb->prefix . 'cu3er__slideshows', $_POST['settings'])) {
$error = true;
echo mysql_error();
}
if($error) {
$message .= $cu3er_messages['error'];
} else {
$message .= $cu3er_messages['success'];
}
}
}
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slideshows` WHERE `id`='".$_GET['id']."'", ARRAY_A);
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$slideshow = $row;
}
if(!is_numeric($slideshow['width']) || $slideshow['width'] < 1) {
$message .= $cu3er_messages['oldXML'];
}
$slideshow['content'] = stripslashes($slideshow['content']);
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__defaults` WHERE `slideshow_id`='".$_GET['id']."'", ARRAY_A);
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$default = cu3er__array_remove_empty($row);
}
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slides` WHERE `slideshow_id`='".$_GET['id']."' ORDER BY `position` ASC", ARRAY_A);
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$slides[] = cu3er__array_remove_empty($row);
}
$baseUrl = cu3er__resolveUrl(cu3er__removeDomainName($slideshow['images_folder'], true)). cu3er__removeDomainName($slideshow['images_folder'], true);
include_once($cu3er_path . 'tpl/edit.php');
} else {
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slideshows` ORDER BY `id` ASC", ARRAY_A) or die(mysql_error());
foreach ($rows as $row) {
//$row = (array)$row;
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$row['baseUrl'] = cu3er__resolveUrl(cu3er__removeDomainName($row['images_folder'], true)). cu3er__removeDomainName($row['images_folder'], true);
$slideshows[] = $row;
}
include_once($cu3er_path . 'tpl/manage.php');
}
}
function cu3er__writeToFile($id, $ret = false) {
if(is_numeric($id)) {
global $wpdb;
$uploadsDir = wp_upload_dir();
// embeded code for showing cu3er //
$row = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__settings` LIMIT 1", ARRAY_A) or die(mysql_error());
$setting = array();
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
$settings[$key] = str_replace("'", "\'", $row[$key]);
}
$row = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__slideshows` WHERE `id`='".$id."'", ARRAY_A) or die(mysql_error());
$slideshowS = array();
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
$slideshowS[$key] = str_replace("'", "\'", $row[$key]);
}
//$slideshowS = str_replace("'", "\'", $row);
$row = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__defaults` WHERE `slideshow_id`='".$id."'", ARRAY_A) or die(mysql_error());
$default = array();
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
$default[$key] = str_replace("'", "\'", $row[$key]);
}
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slides` WHERE `slideshow_id`='".$id."' ORDER BY `position` ASC", ARRAY_A) or die(mysql_error());
foreach ($rows as $row) {
$arr = array();
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
$arr[$key] = str_replace("'", "\'", $row[$key]);
}
$slides[] = $arr;
}
if($default['posts_fit'] != '' && $default['posts_fit'] != 'default') {
$default['fit'] = $default['posts_fit'];
}
if($settings['licence'] != '') {
$arrXml[0]['licence'] = "<![CDATA[" .urldecode(trim($settings['licence'])). "]]>";
}
if($settings['licence1'] != '') {
$arrXml[1]['licence'] = "<![CDATA[" .urldecode(trim($settings['licence1'])). "]]>";
}
if($settings['licence2'] != '') {
$arrXml[2]['licence'] = "<![CDATA[" .urldecode(trim($settings['licence2'])). "]]>";
}
if($settings['licence3'] != '') {
$arrXml[3]['licence'] = "<![CDATA[" .urldecode(trim($settings['licence3'])). "]]>";
}
if($settings['licence4'] != '') {
$arrXml[4]['licence'] = "<![CDATA[" .urldecode(trim($settings['licence4'])). "]]>";
}
$slideshowS['width_type'] = ($slideshowS['width_type'] == '%') ? '%' : '';
$slideshowS['height_type'] = ($slideshowS['height_type'] == '%') ? '%' : '';
$arrXml['project_settings']['width'] = $slideshowS['width'] . $slideshowS['width_type'];
$arrXml['project_settings']['height'] = $slideshowS['height'] . $slideshowS['height_type'];
$arrXml['settings']['background']['color']['vle'] = str_replace('#', '0x', $slideshowS['background']);
$arrXml['settings']['background']['color']['@attributes']['transparent'] = ($slideshowS['backgroundType'] == 'transparent') ? 'true' : 'false';
$arrXml['settings']['background']['image']['url'] = "<![CDATA[" . $slideshowS['bg_image'] . "]]>";
if($arrXml['settings']['background']['image']['url'] == '<![CDATA[]]>') {
$arrXml['settings']['background']['image']['url'] = '';
}
$arrXml['settings']['background']['image']['@attributes']['use_image'] = $slideshowS['bg_use_image'];
$arrXml['settings']['background']['image']['@attributes']['align_to'] = $slideshowS['bg_align_to'];
$arrXml['settings']['background']['image']['@attributes']['align_pos'] = $slideshowS['bg_align_pos'];
$arrXml['settings']['background']['image']['@attributes']['x'] = $slideshowS['bg_x'];
$arrXml['settings']['background']['image']['@attributes']['y'] = $slideshowS['bg_y'];
$arrXml['settings']['background']['image']['@attributes']['scaleX'] = $slideshowS['bg_scaleX'];
$arrXml['settings']['background']['image']['@attributes']['scaleY'] = $slideshowS['bg_scaleY'];
if($slideshowS['sdw_use_image'] == 'true' && $slideshowS['sdw_image'] != '') {
$arrXml['settings']['shadow']['@attributes']['use_image'] = $slideshowS['sdw_use_image'];
$arrXml['settings']['shadow']['@attributes']['show'] = $slideshowS['sdw_show'];
$arrXml['settings']['shadow']['@attributes']['color'] = str_replace('#', '0x', $slideshowS['sdw_color']);
$arrXml['settings']['shadow']['@attributes']['alpha'] = $slideshowS['sdw_alpha'];
$arrXml['settings']['shadow']['@attributes']['blur'] = $slideshowS['sdw_blur'];
$arrXml['settings']['shadow']['@attributes']['corner_TL'] = $slideshowS['sdw_corner_tl'];
$arrXml['settings']['shadow']['@attributes']['corner_TR'] = $slideshowS['sdw_corner_tr'];
$arrXml['settings']['shadow']['@attributes']['corner_BL'] = $slideshowS['sdw_corner_bl'];
$arrXml['settings']['shadow']['@attributes']['corner_BR'] = $slideshowS['sdw_corner_br'];
$arrXml['settings']['shadow']['url'] = $slideshowS['sdw_image'];
}
if($settings['branding'] == 'yes') {
if($slideshowS['br_align_to'] != '') {
$arrXml['settings']['branding']['@attributes']['align_to'] = $slideshowS['br_align_to'];
}
if($slideshowS['br_align_pos'] != '') {
$arrXml['settings']['branding']['@attributes']['align_pos'] = $slideshowS['br_align_pos'];
}
if($slideshowS['br_x'] != '') {
$arrXml['settings']['branding']['@attributes']['x'] = $slideshowS['br_x'];
}
if($slideshowS['br_y'] != '') {
$arrXml['settings']['branding']['@attributes']['y'] = $slideshowS['br_y'];
}
$arrXml['settings']['branding']['remove_logo_loader'] = 'true';
$arrXml['settings']['branding']['remove_right_menu_info'] = 'true';
$arrXml['settings']['branding']['remove_right_menu_licence'] = 'true';
}
if($slideshowS['images_folder'] != '') {
$fImages = trailingslashit($slideshowS['images_folder']);
if(cu3er__isOnSameDomain($fImages)) {
$fImages = cu3er__removeDomainName($fImages);
}
} else {
$fImages = '';
}
$arrXml['settings']['folder_images'] = "<![CDATA[" .$fImages. "]]>";
if($arrXml['settings']['folder_images'] == '<![CDATA[]]>') {
$arrXml['settings']['folder_images'] = '';
}
if($slideshowS['fonts_folder'] != '') {
$fFonts = trailingslashit($slideshowS['fonts_folder']);
if(cu3er__isOnSameDomain($fFonts)) {
$fFonts = cu3er__removeDomainName($fFonts);
}
} else {
$fFonts = '';
}
$arrXml['settings']['folder_fonts'] = "<![CDATA[" .$fFonts. "]]>";
if($arrXml['settings']['folder_fonts'] == '<![CDATA[]]>') {
$arrXml['settings']['folder_fonts'] = '';
}
if($slideshowS['pr_image'] != '') {
$arrXml['preloader']['image']['@attributes']['align_to'] = $slideshowS['pr_align_to'];
$arrXml['preloader']['image']['@attributes']['align_pos'] = $slideshowS['pr_align_pos'];
$arrXml['preloader']['image']['@attributes']['x'] = $slideshowS['pr_x'];
$arrXml['preloader']['image']['@attributes']['y'] = $slideshowS['pr_y'];
$arrXml['preloader']['image']['@attributes']['scaleX'] = $slideshowS['pr_scaleX'];
$arrXml['preloader']['image']['@attributes']['scaleY'] = $slideshowS['pr_scaleY'];
$arrXml['preloader']['image']['@attributes']['loader_direction'] = $slideshowS['pr_loader_direction'];
$arrXml['preloader']['image']['@attributes']['alpha_loader'] = $slideshowS['pr_alpha_loader'];
$arrXml['preloader']['image']['@attributes']['alpha_bg'] = $slideshowS['pr_alpha_bg'];
$arrXml['preloader']['image']['@attributes']['tint_loader'] = $slideshowS['pr_tint_loader'];
$arrXml['preloader']['image']['@attributes']['tint_bg'] = $slideshowS['pr_tint_bg'];
$arrXml['preloader']['image']['@attributes']['width'] = $slideshowS['pr_width'];
$arrXml['preloader']['image']['@attributes']['height'] = $slideshowS['pr_height'];
$arrXml['preloader']['image']['url'] = $slideshowS['pr_image'];
}
$arrXml['defaults']['slide']['@attributes']['time'] = $default['duration'];
$arrXml['defaults']['slide']['@attributes']['color'] = str_replace('#', '0x', $default['color']);
$arrXml['defaults']['slide']['@attributes']['transparent'] = $default['transparent'];
$arrXml['defaults']['slide']['link']['vle'] = "<![CDATA[" .$default['link']. "]]>";
if($arrXml['defaults']['slide']['link']['vle'] == '<![CDATA[]]>') {
$arrXml['defaults']['slide']['link']['vle'] = '';
}
$arrXml['defaults']['slide']['link']['@attributes']['target'] = $default['target'];
$arrXml['defaults']['slide']['description']['link']['vle'] = "<![CDATA[" .$default['dlink']. "]]>";
if($arrXml['defaults']['slide']['description']['link']['vle'] == '<![CDATA[]]>') {
$arrXml['defaults']['slide']['description']['link']['vle'] = '';
}
$arrXml['defaults']['slide']['description']['link']['@attributes']['target'] = $default['dtarget'];
$arrXml['defaults']['slide']['image']['@attributes']['align_pos'] = $default['align_pos'];
$arrXml['defaults']['slide']['image']['@attributes']['x'] = $default['x'];
$arrXml['defaults']['slide']['image']['@attributes']['y'] = $default['y'];
$arrXml['defaults']['slide']['image']['@attributes']['scaleX'] = $default['scaleX'];
$arrXml['defaults']['slide']['image']['@attributes']['scaleY'] = $default['scaleY'];
$arrXml['defaults']['slide']['image']['@attributes']['fit'] = $default['fit'];
$arrXml['defaults']['transition']['@attributes']['type'] = $default['type'];
$arrXml['defaults']['transition']['@attributes']['columns'] = $default['columns'];
$arrXml['defaults']['transition']['@attributes']['rows'] = $default['rows'];
$arrXml['defaults']['transition']['@attributes']['type2D'] = $default['type2d'];
$arrXml['defaults']['transition']['@attributes']['flipAngle'] = $default['flipAngle'];
$arrXml['defaults']['transition']['@attributes']['flipOrder'] = $default['flipOrder'];
$arrXml['defaults']['transition']['@attributes']['flipShader'] = $default['flipShader'];
$arrXml['defaults']['transition']['@attributes']['flipOrderFromCenter'] = $default['flipOrderFromCenter'];
$arrXml['defaults']['transition']['@attributes']['flipDirection'] = $default['flipDirection'];
$arrXml['defaults']['transition']['@attributes']['flipColor'] = str_replace('#', '0x', $default['flipColor']);
$arrXml['defaults']['transition']['@attributes']['flipBoxDepth'] = $default['flipBoxDepth'];
$arrXml['defaults']['transition']['@attributes']['flipDepth'] = $default['flipDepth'];
$arrXml['defaults']['transition']['@attributes']['flipEasing'] = $default['flipEasing'];
$arrXml['defaults']['transition']['@attributes']['flipDuration'] = $default['flipDuration'];
$arrXml['defaults']['transition']['@attributes']['flipDelay'] = $default['flipDelay'];
$arrXml['defaults']['transition']['@attributes']['flipDelayRandomize'] = $default['flipDelayRandomize'];
$arrXml['slides']['@attributes']['align_pos'] = $default['salign_pos'];
$arrXml['slides']['@attributes']['x'] = $default['sx'];
$arrXml['slides']['@attributes']['y'] = $default['sy'];
$arrXml['slides']['@attributes']['width'] = $default['swidth'];
$arrXml['slides']['@attributes']['height'] = $default['sheight'];
foreach($slides as $key=>$value) {
if($default['posts_fit'] != '' && $default['posts_fit'] != 'default') {
$value['fit'] = $default['posts_fit'];
}
$arrXml['slides'][$key]['slide']['url'] = "<![CDATA[" .((cu3er__isHttpPath($value['image'])) ? $value['image'] : cu3er__removeDomainName($value['image'])). "]]>";
if($value['duration'] != $default['duration']) {
$arrXml['slides'][$key]['slide']['@attributes']['time'] = $value['duration'];
}
$arrXml['slides'][$key]['slide']['image']['@attributes']['align_pos'] = $value['align_pos'];
$arrXml['slides'][$key]['slide']['image']['@attributes']['fit'] = $value['fit'];
$arrXml['slides'][$key]['slide']['@attributes']['use_image'] = ($value['use_image'] == 'no') ? 'false' : 'true';
$arrXml['slides'][$key]['slide']['image']['@attributes']['x'] = $value['x'];
$arrXml['slides'][$key]['slide']['image']['@attributes']['y'] = $value['y'];
$arrXml['slides'][$key]['slide']['image']['@attributes']['scaleX'] = $value['scaleX'];
$arrXml['slides'][$key]['slide']['image']['@attributes']['scaleY'] = $value['scaleY'];
$arrXml['slides'][$key]['slide']['caption'] = "<![CDATA[" .$value['caption']. "]]>";
if($arrXml['slides'][$key]['slide']['caption'] == '<![CDATA[]]>') {
$arrXml['slides'][$key]['slide']['caption'] = '';
}
if($value['transparent'] != $default['transparent']) {
$arrXml['slides'][$key]['slide']['@attributes']['transparent'] = $value['transparent'];
}
if($value['color'] != $default['color']) {
$arrXml['slides'][$key]['slide']['@attributes']['color'] = str_replace('#', '0x', $value['color']);
}
if($value['link'] != $default['link']) {
$arrXml['slides'][$key]['slide']['link']['vle'] = "<![CDATA[" .$value['link']. "]]>";
}
if($value['target'] != $default['target']) {
$arrXml['slides'][$key]['slide']['link']['@attributes']['target'] = $value['target'];
}
if($arrXml['slides'][$key]['slide']['link']['vle'] == '<![CDATA[]]>') {
$arrXml['slides'][$key]['slide']['link']['vle'] = '';
}
$arrXml['slides'][$key]['slide']['description']['heading'] = "<![CDATA[" .$value['heading']. "]]>";
if($arrXml['slides'][$key]['slide']['description']['heading'] == '<![CDATA[]]>') {
$arrXml['slides'][$key]['slide']['description']['heading'] = '';
}
$arrXml['slides'][$key]['slide']['description']['paragraph'] = "<![CDATA[" .$value['paragraph']. "]]>";
if($arrXml['slides'][$key]['slide']['description']['paragraph'] == '<![CDATA[]]>') {
$arrXml['slides'][$key]['slide']['description']['paragraph'] = '';
}
if($value['dlink'] != $default['dlink']) {
$arrXml['slides'][$key]['slide']['description']['link']['vle'] = "<![CDATA[" .$value['dlink']. "]]>";
}
if($arrXml['slides'][$key]['slide']['description']['link']['vle'] == '<![CDATA[]]>') {
$arrXml['slides'][$key]['slide']['description']['link']['vle'] = '';
}
if($value['dtarget'] != $default['dtarget']) {
$arrXml['slides'][$key]['slide']['description']['link']['@attributes']['target'] = $value['dtarget'];
}
if($value['type'] != $default['type']) {
$arrXml['slides'][$key]['transition']['@attributes']['type'] = $value['type'];
}
if($value['columns'] != $default['columns']) {
$arrXml['slides'][$key]['transition']['@attributes']['columns'] = $value['columns'];
}
if($value['rows'] != $default['rows']) {
$arrXml['slides'][$key]['transition']['@attributes']['rows'] = $value['rows'];
}
if($value['type2d'] != $default['type2d']) {
$arrXml['slides'][$key]['transition']['@attributes']['type2D'] = $value['type2d'];
}
if($value['flipAngle'] != $default['flipAngle']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipAngle'] = $value['flipAngle'];
}
if($value['flipAngle'] != $default['flipAngle']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipOrder'] = $value['flipOrder'];
}
if($value['flipShader'] != $default['flipShader']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipShader'] = $value['flipShader'];
}
if($value['flipOrderFromCenter'] != $default['flipOrderFromCenter']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipOrderFromCenter'] = $value['flipOrderFromCenter'];
}
if($value['flipDirection'] != $default['flipDirection']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipDirection'] = $value['flipDirection'];
}
if($value['flipColor'] != $default['flipColor']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipColor'] = str_replace('#', '0x', $value['flipColor']);
}
if($value['flipBoxDepth'] != $default['flipBoxDepth']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipBoxDepth'] = $value['flipBoxDepth'];
}
if($value['flipDepth'] != $default['flipDepth']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipDepth'] = $value['flipDepth'];
}
if($value['flipEasing'] != $default['flipEasing']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipEasing'] = $value['flipEasing'];
}
if($value['flipDuration'] != $default['flipDuration']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipDuration'] = $value['flipDuration'];
}
if($value['flipDelay'] != $default['flipDelay']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipDelay'] = $value['flipDelay'];
}
if($value['flipDelayRandomize'] != $default['flipDelayRandomize']) {
$arrXml['slides'][$key]['transition']['@attributes']['flipDelayRandomize'] = $value['flipDelayRandomize'];
}
$image_url = $fImages . $value['image'];
$image_alt = $value['seo_img_alt'];
$heading = $value['heading'];
$paragraph = $value['paragraph'];
$caption = $value['caption'];
$seo_text = $value['seo_text'];
$slide_link = $value['link'];
$slide_link_target = $value['target'];
if ($slide_link_target == '') $slide_link_target = $value['target'];
$desc_link = $value['dlink'];
$desc_link_target = $value['dtarget'];
if ($desc_link_target == '') $desc_link_target = $default['dtarget'];
if ($slide_link == '') { $slide_link = $value['link']; }
if ($desc_link == '') { $desc_link = $value['dlink']; }
$seo_str .= "<li>";
if ($slide_link != "") {
$seo_str .= '<a href="'.$slide_link.'" target="'.$slide_link_target.'">' ."\n";
}
if (($default['seo_show_image'] == 'yes' && $value['seo_show_image'] != 'no') || $value['seo_show_image'] == 'yes') {
$seo_str .= "<img src='$image_url' alt='".addslashes($image_alt)."'/>\n";
}
if ($slide_link != "" && $desc_link != "") {
$seo_str .= '</a><a href="'.$desc_link.'" target="'.$desc_link_target.'">' ."\n";
} elseif($desc_link != '') {
$seo_str .= '<a href="'.$desc_link.'" target="'.$desc_link_target.'">' ."\n";
}
if ($default['seo_show_heading'] == 'yes' || $value['seo_show_heading'] == 'yes' && $heading != "") {
$seo_str .= "<h2>".$heading."</h2>" ."\n";
}
if ($default['seo_show_paragraph'] == 'yes' || $value['seo_show_paragraph'] == 'yes' && $paragraph != "") {
$seo_str .= "<p>".$paragraph."</p>" ."\n";
}
if ($desc_link != "") {
$seo_str .= "</a>" ."\n";
}
if ($slide_link != "" && $desc_link == "") {
$seo_str .= '</a>' ."\n";
}
if ($default['seo_show_caption'] == 'yes' || $value['seo_show_caption'] == 'yes' && $caption != "") {
$seo_str .= "<p>".$caption."</p>" ."\n";
}
if ($seo_text != "") {
$seo_str .= "<p>".$seo_text."</p>" ."\n";
}
$seo_str .= "</li>" ."\n";
}
$seo_str = '<ul style="position:absolute; left:-50000px;">'.$seo_str.'</ul>';
$array = cu3er__array_remove_empty($arrXml);
$data['data'] = $array;
if(trim($settings['licence']) != '') {
$data['data'][0]['licence'] = '<![CDATA['. urldecode(trim($settings['licence'])) .']]>';
}
if(trim($settings['licence1']) != '') {
$data['data'][1]['licence'] = '<![CDATA['. urldecode(trim($settings['licence1'])) .']]>';
}
if(trim($settings['licence2']) != '') {
$data['data'][2]['licence'] = '<![CDATA['. urldecode(trim($settings['licence2'])) .']]>';
}
if(trim($settings['licence3']) != '') {
$data['data'][3]['licence'] = '<![CDATA['. urldecode(trim($settings['licence3'])) .']]>';
}
if(trim($settings['licence4']) != '') {
$data['data'][4]['licence'] = '<![CDATA['. urldecode(trim($settings['licence4'])) .']]>';
}
$toWrite = urlencode(cu3er__array2xml($data)) . '|||||' . $seo_str;
if($slideshowS['project_location'] != '') {
$oldDir = $slideshowS['project_location'];
} else {
$pth = explode("/", $slideshowS['xml_location']);
$delFlag = true;
$size = sizeof($pth);
$wpContentDirArray = explode('/', WP_CONTENT_DIR);
$wpContentDir = $wpContentDirArray[(sizeof($wpContentDirArray) -1)];
for($i=0; $i<$size; $i++) {
if($pth[$i] == $wpContentDir) {
unset($pth[$i], $pth[($i+1)]);
$delFlag = false;
}
if($delFlag == true) {
unset($pth[$i]);
}
}
$pthOld = $pth;
unset($pthOld[9], $pthOld[10], $pthOld[11], $pthOld[12]);
$oldDir = $uploadsDir['basedir'] . '/' . implode("/", $pthOld);
}
if(!file_exists($oldDir . '/CU3ER.txt')) {
@touch($oldDir . '/CU3ER.txt');
}
@chmod($oldDir . '/CU3ER.txt', 0777);
$handle = fopen($oldDir . '/CU3ER.txt', 'w+');
fwrite($handle, $toWrite);
fclose($handle);
@chmod($oldDir . '/CU3ER.txt', 0755);
if($ret) {
return $toWrite;
}
}
}
function cu3er__readFromFile($id) {
if(is_numeric($id)) {
global $wpdb;
$uploadsDir = wp_upload_dir();
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__slideshows` WHERE `id`='".$id."'", ARRAY_A) or die(mysql_error());
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$slideshowS = str_replace("'", "\'", $row);
}
if($slideshowS['project_location'] != '') {
$oldDir = $slideshowS['project_location'];
} else {
$pth = explode("/", $slideshowS['xml_location']);
$delFlag = true;
$size = sizeof($pth);
$wpContentDirArray = explode('/', WP_CONTENT_DIR);
$wpContentDir = $wpContentDirArray[(sizeof($wpContentDirArray) -1)];
for($i=0; $i<$size; $i++) {
if($pth[$i] == $wpContentDir) {
unset($pth[$i], $pth[($i+1)]);
$delFlag = false;
}
if($delFlag == true) {
unset($pth[$i]);
}
}
$pthOld = $pth;
unset($pthOld[9], $pthOld[10], $pthOld[11], $pthOld[12]);
$oldDir = $uploadsDir['basedir'] . '/' . implode("/", $pthOld);
}
if(!file_exists($oldDir . '/CU3ER.txt') || file_get_contents($oldDir . '/CU3ER.txt') == '') {
$var = cu3er__writeToFile($id, true);
return $var;
} else {
return file_get_contents($oldDir . '/CU3ER.txt');
}
}
}
function cu3er__action_register_tinymce() {
if(get_user_option('rich_editing') == 'true') {
add_filter('mce_buttons', 'cu3er__filter_tinymce_button');
add_filter('mce_external_plugins', 'cu3er__filter_tinymce_plugin');
}
}
function cu3er__filter_tinymce_button($buttons) {
array_push($buttons, '|', 'wpCU3ER' );
return $buttons;
}
function cu3er__filter_tinymce_plugin($plugin_array) {
$cu3er_path = trailingslashit(rtrim(WP_PLUGIN_URL, '/') . '/wpcu3er');
$plugin_array['wpCU3ER'] = $cu3er_path . 'js/editor_plugin.js';
$plugin_array['contextmenu'] = $cu3er_path . 'mce/contextmenu/editor_plugin.js';
return $plugin_array;
}
function cu3er_download() {
global $wpdb;
global $cu3er_messages;
$ret = false;
$uploadsDir = wp_upload_dir();
$writable = true;
if(is_writable($uploadsDir['basedir'] . '/wpcu3er')) {
touch($uploadsDir['basedir'] . '/wpcu3er/temp.txt');
if(!is_writable($uploadsDir['basedir'] . '/wpcu3er/temp.txt')) {
$writable = false;
}
} else {
$writable = false;
}
$basedir = ($writable === true) ? $uploadsDir['basedir'] .'/wpcu3er' : $uploadsDir['path'];
$baseurl = ($writable === true) ? $uploadsDir['baseurl'] .'/wpcu3er' : $uploadsDir['url'];
$uplDir = $basedir .'/';
$save_path = $baseurl .'/';
$cu3er = cu3er__our_fopen('http://' . SERVER_IP . '/CU3ER.swf');
chmod($uplDir . 'CU3ER.swf', 0777);
$handle = fopen($uplDir . 'CU3ER.swf', 'w+');
if(fwrite($handle, $cu3er)) {
$ret = true;
}
fclose($handle);
$row = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__settings` WHERE `id`=1", ARRAY_A);
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$settings = $row;
$settings['cu3er_location'] = $save_path . 'CU3ER.swf';
cu3er__sql_magic($wpdb->prefix . 'cu3er__settings', $settings);
return $ret;
}
function cu3er_downloadJS($player = false) {
global $wpdb;
global $cu3er_messages;
$ret = false;
$uploadsDir = wp_upload_dir();
$writable = true;
if(is_writable($uploadsDir['basedir'] . '/wpcu3er')) {
touch($uploadsDir['basedir'] . '/wpcu3er/temp.txt');
if(!is_writable($uploadsDir['basedir'] . '/wpcu3er/temp.txt')) {
$writable = false;
}
} else {
$writable = false;
}
$basedir = ($writable === true) ? $uploadsDir['basedir'] .'/wpcu3er' : $uploadsDir['path'];
$baseurl = ($writable === true) ? $uploadsDir['baseurl'] .'/wpcu3er' : $uploadsDir['url'];
$uplDir = $basedir .'/';
$save_path = $baseurl .'/';
if($player) {
$cu3er = cu3er__our_fopen('http://' . SERVER_IP . '/js/jquery.cu3er.player.js');
chmod($uplDir . 'jquery.cu3er.player.js', 0777);
$handle = fopen($uplDir . 'jquery.cu3er.player.js', 'w+');
} else {
$cu3er = cu3er__our_fopen('http://' . SERVER_IP . '/js/jquery.cu3er.js');
chmod($uplDir . 'jquery.cu3er.js', 0777);
$handle = fopen($uplDir . 'jquery.cu3er.js', 'w+');
}
if(fwrite($handle, $cu3er)) {
$ret = true;
}
fclose($handle);
$row = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__settings` WHERE `id`=1", ARRAY_A);
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$settings = $row;
if($player) {
$settings['js_player_location'] = $save_path . 'jquery.cu3er.player.js';
} else {
$settings['js_location'] = $save_path . 'jquery.cu3er.js';
}
cu3er__sql_magic($wpdb->prefix . 'cu3er__settings', $settings);
return $ret;
}
function cu3er__isHttpPath($url) {
$cu3er_path = parse_url($url);
return ($cu3er_path['scheme'] == 'http') ? true : ($cu3er_path['scheme'] == 'https') ? true : false;
}
function cu3er__isOnSameDomain($url) {
$cu3er_path = parse_url($url);
$local_path = parse_url('http://' . $_SERVER['SERVER_NAME']);
$cu3er_path = str_replace('www.', '', $cu3er_path['host']);
$local_path = str_replace('www.', '', $local_path['host']);
return (trim($cu3er_path) == trim($local_path)) ? true : false;
}
function cu3er__admin_setup() {
global $wpdb;
global $cu3er_messages;
$uploadsDir = wp_upload_dir();
$writable = true;
if(is_writable($uploadsDir['basedir'] . '/wpcu3er')) {
touch($uploadsDir['basedir'] . '/wpcu3er/temp.txt');
if(!is_writable($uploadsDir['basedir'] . '/wpcu3er/temp.txt')) {
$writable = false;
}
} else {
$writable = false;
}
$basedir = ($writable === true) ? $uploadsDir['basedir'] .'/wpcu3er' : $uploadsDir['path'];
$baseurl = ($writable === true) ? $uploadsDir['baseurl'] .'/wpcu3er' : $uploadsDir['url'];
$uplDir = $baseurl .'/';
$save_path = $basedir .'/';
$message .= cu3er__admin_checkCu3er();
if($_POST['Submit'] == 'Save Changes' || $_POST['Submit'] == 'Save Licence') {
$upload_name = array(
0 => "cu3er_location",
1 => "js_location",
2 => "js_player_location"
);
$uploadErrors = array(
0 => "There is no error, the file uploaded with success",
1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3 => "The uploaded file was only partially uploaded",
4 => "No file was uploaded",
6 => "Missing a temporary folder"
);
$_POST['settings']['licence'] = ($_POST['settings']['licence'] != '') ? urlencode(stripslashes($_POST['settings']['licence'])) : ' ';
$_POST['settings']['licence1'] = ($_POST['settings']['licence1'] != '') ? urlencode(stripslashes($_POST['settings']['licence1'])) : ' ';
$_POST['settings']['licence2'] = ($_POST['settings']['licence2'] != '') ? urlencode(stripslashes($_POST['settings']['licence2'])) : ' ';
$_POST['settings']['licence3'] = ($_POST['settings']['licence3'] != '') ? urlencode(stripslashes($_POST['settings']['licence3'])) : ' ';
$_POST['settings']['licence4'] = ($_POST['settings']['licence4'] != '') ? urlencode(stripslashes($_POST['settings']['licence4'])) : ' ';
foreach($upload_name as $key=>$name) {
if($_FILES[$name]["tmp_name"] != '') {
$file_name = preg_replace('/[^.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-]|\.+$/i', "", basename($_FILES[$name]['name']));
@unlink($save_path.$file_name);
if(!move_uploaded_file($_FILES[$name]["tmp_name"], $save_path.$file_name)) {
echo("File could not be saved. " . $uploadErrors[$_FILES[$name]['error']]);
exit(0);
} else {
$_POST['settings'][$name] = $uplDir.$file_name;
}
}
}
$_POST['settings']['branding'] = (isset($_POST['settings']['branding'])) ? 'yes' : 'no';
cu3er__sql_magic($wpdb->prefix . "cu3er__settings", $_POST['settings']) or die(mysql_error());
/* empty all CU3ER.txt files */
global $wpdb;
$uploadsDir = wp_upload_dir();
// embeded code for showing cu3er //
$rows = $wpdb->get_results("SELECT `xml_location`,`project_location` FROM `" . $wpdb->prefix . "cu3er__slideshows`", ARRAY_A) or die(mysql_error());
foreach ($rows as $row) {
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$slideshowS = str_replace("'", "\'", $row);
if($slideshowS['project_location'] != '') {
$oldDir = $slideshowS['project_location'];
} else {
$pth = explode("/", $slideshowS['xml_location']);
$delFlag = true;
$size = sizeof($pth);
$wpContentDirArray = explode('/', WP_CONTENT_DIR);
$wpContentDir = $wpContentDirArray[(sizeof($wpContentDirArray) -1)];
for($i=0; $i<$size; $i++) {
if($pth[$i] == $wpContentDir) {
unset($pth[$i], $pth[($i+1)]);
$delFlag = false;
}
if($delFlag == true) {
unset($pth[$i]);
}
}
$pthOld = $pth;
unset($pthOld[9], $pthOld[10], $pthOld[11], $pthOld[12]);
$oldDir = $uploadsDir['basedir'] . '/' . implode("/", $pthOld);
}
if(file_exists($oldDir . '/CU3ER.txt') || file_get_contents($oldDir . '/CU3ER.txt') != '') {
@chmod($oldDir . '/CU3ER.txt', 0777);
$handle = fopen($oldDir . '/CU3ER.txt', 'w+');
fclose($handle);
@chmod($oldDir . '/CU3ER.txt', 0755);
}
}
$message .= $cu3er_messages['setupSuccess'];
}
$row = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__settings` WHERE `id`=1", ARRAY_A);
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$settings = $row;
include_once('tpl/setup.php');
}
function cu3er__action_load_scripts() {
$page = (isset($_GET['page'])) ? $_GET['page'] : '';
if(preg_match('/CU3ER/i', $page)) {
wp_enqueue_script('jquery');
wp_enqueue_script('jquery-ui-core');
wp_enqueue_script('jquery-ui-sortable');
wp_enqueue_script('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('farbtastic');
}
wp_enqueue_script('swfobject');
}
function cu3er__action_load_styles() {
global $wp_version;
if(strpos($_SERVER['PHP_SELF'], 'wp-admin') !== false) {
if (version_compare($wp_version, '3.3', '<')) {
wp_admin_css('dashboard');
}
wp_enqueue_style('thickbox');
wp_enqueue_style('farbtastic');
$page = (isset($_GET['page'])) ? $_GET['page'] : '';
if(preg_match('/CU3ER/i', $page)) {
wp_enqueue_style('cu3er', plugins_url('/css/style.css', __FILE__));
}
}
}
function cu3er__my_myme_types($mime_types){
$mime_types['xml'] = 'text/xml'; // Adding xml extension
$mime_types['js'] = 'text/javascript'; // Adding js extension
return $mime_types;
}
function cu3er__action_activate() {
global $wpdb;
if (function_exists('is_multisite') && is_multisite()) {
// check if it is a network activation - if so, run the activation function for each blog id
if (isset($_GET['networkwide']) && ($_GET['networkwide'] == 1)) {
$old_blog = $wpdb->blogid;
// Get all blog ids
$blogids = $wpdb->get_col($wpdb->prepare("SELECT blog_id FROM $wpdb->blogs"));
foreach ($blogids as $blog_id) {
switch_to_blog($blog_id);
cu3er__action_create_tables();
}
switch_to_blog($old_blog);
return;
}
$network = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : "";
$activate = isset($_GET['action']) ? $_GET['action'] : "";
$isNetwork = ($network == '/wp-admin/network/plugins.php') ? true : false;
$isActivation = ($activate == 'deactivate') ? false : true;
if($isNetwork && $isActivation){
$old_blog = $wpdb->blogid;
$blogids = $wpdb->get_col($wpdb->prepare("SELECT blog_id FROM $wpdb->blogs"));
foreach ($blogids as $blog_id) {
switch_to_blog($blog_id);
cu3er__action_create_tables();
}
switch_to_blog($old_blog);
return;
}
}
cu3er__action_create_tables();
}
function cu3er__action_create_tables() {
global $wpdb;
$rows = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "cu3er__settings`", ARRAY_A);
if(count($rows) == 0) {
$cu3er__collate = ' COLLATE utf8_general_ci';
$sql0 = "CREATE TABLE `" . $wpdb->prefix . "cu3er__slideshows` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`width` int(11) NOT NULL,
`width_type` enum('px', '%') NOT NULL DEFAULT 'px',
`height` int(11) NOT NULL,
`height_type` enum('px', '%') NOT NULL DEFAULT 'px',
`background` varchar(20) NOT NULL,
`images_folder` varchar(255) NOT NULL,
`fonts_folder` varchar(255) NOT NULL,
`content` text NOT NULL,
`xml_location` varchar(255) NOT NULL,
`bg_image` varchar(255) DEFAULT NULL,
`bg_align_to` varchar(10) DEFAULT NULL,
`bg_align_pos` varchar(10) DEFAULT NULL,
`bg_x` varchar(50) DEFAULT NULL,
`bg_y` varchar(50) DEFAULT NULL,
`bg_scaleX` varchar(50) DEFAULT NULL,
`bg_scaleY` varchar(50) DEFAULT NULL,
`bg_use_image` varchar(15) DEFAULT NULL,
`backgroundType` varchar(20) DEFAULT NULL,
`sdw_show` varchar(20) DEFAULT NULL,
`sdw_use_image` varchar(20) DEFAULT NULL,
`sdw_color` varchar(20) DEFAULT NULL,
`sdw_alpha` varchar(50) DEFAULT NULL,
`sdw_blur` varchar(50) DEFAULT NULL,
`sdw_corner_tl` varchar(30) DEFAULT NULL,
`sdw_corner_tr` varchar(30) DEFAULT NULL,
`sdw_corner_bl` varchar(30) DEFAULT NULL,
`sdw_corner_br` varchar(30) DEFAULT NULL,
`sdw_image` varchar(255) DEFAULT NULL,
`pr_image` varchar(255) DEFAULT NULL,
`pr_align_to` varchar(20) DEFAULT NULL,
`pr_align_pos` varchar(20) DEFAULT NULL,
`pr_x` varchar(50) DEFAULT NULL,
`pr_y` varchar(50) DEFAULT NULL,
`pr_scaleX` varchar(50) DEFAULT NULL,
`pr_scaleY` varchar(50) DEFAULT NULL,
`pr_loader_direction` varchar(20) DEFAULT NULL,
`pr_alpha_loader` varchar(15) DEFAULT NULL,
`pr_alpha_bg` varchar(15) DEFAULT NULL,
`pr_tint_loader` varchar(15) DEFAULT NULL,
`pr_tint_bg` varchar(15) DEFAULT NULL,
`pr_width` varchar(15) DEFAULT NULL,
`pr_height` varchar(15) DEFAULT NULL,
`modified` datetime,
`force_js` enum('no', 'yes') NOT NULL DEFAULT 'no',
`force_js3d` enum('no', 'yes') NOT NULL DEFAULT 'no',
`responsive` enum('yes', 'no') NOT NULL DEFAULT 'yes',
`br_align_to` varchar(20) DEFAULT NULL,
`br_align_pos` varchar(20) DEFAULT NULL,
`br_x` varchar(20) DEFAULT NULL,
`br_y` varchar(20) DEFAULT NULL,
`project_location` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
)";
$sql1 = "CREATE TABLE `" . $wpdb->prefix . "cu3er__slides` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`slideshow_id` int(11) NOT NULL,
`duration` varchar(50) DEFAULT NULL,
`color` varchar(20) DEFAULT NULL,
`caption` varchar(255) DEFAULT NULL,
`link` varchar(255) DEFAULT NULL,
`target` varchar(20) DEFAULT NULL,
`heading` text,
`paragraph` text,
`dlink` varchar(255) DEFAULT NULL,
`dtarget` varchar(20) DEFAULT NULL,
`type` varchar(5) DEFAULT NULL,
`columns` int(11) DEFAULT NULL,
`rows` int(11) DEFAULT NULL,
`type2d` varchar(50) DEFAULT NULL,
`flipAngle` int(11) DEFAULT NULL,
`flipOrder` int(11) DEFAULT NULL,
`flipShader` varchar(50) DEFAULT NULL,
`flipOrderFromCenter` varchar(20) DEFAULT NULL,
`flipDirection` varchar(50) DEFAULT NULL,
`flipColor` varchar(30) DEFAULT NULL,
`flipBoxDepth` varchar(50) DEFAULT NULL,
`flipDepth` varchar(50) DEFAULT NULL,
`flipEasing` varchar(50) DEFAULT NULL,
`flipDuration` varchar(50) DEFAULT NULL,
`flipDelay` varchar(50) DEFAULT NULL,
`flipDelayRandomize` varchar(50) DEFAULT NULL,
`position` int(11) NOT NULL,
`image` varchar(255) DEFAULT NULL,
`align_pos` varchar(255) DEFAULT NULL,
`fit` varchar(255) DEFAULT NULL,
`x` varchar(50) DEFAULT NULL,
`y` varchar(50) DEFAULT NULL,
`scaleX` varchar(50) DEFAULT NULL,
`scaleY` varchar(50) DEFAULT NULL,
`transparent` varchar(15) DEFAULT NULL,
`use_image` enum('yes', 'no') NOT NULL DEFAULT 'yes',
`seo_show_image` varchar(5) NOT NULL DEFAULT '',
`seo_show_heading` varchar(5) NOT NULL DEFAULT '',
`seo_show_paragraph` varchar(5) NOT NULL DEFAULT '',
`seo_show_caption` varchar(5) NOT NULL DEFAULT '',
`seo_text` text,
`seo_img_alt` text,
PRIMARY KEY (`id`)
)";
$sql2 = "CREATE TABLE `" . $wpdb->prefix . "cu3er__defaults` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`slideshow_id` int(11) NOT NULL,
`duration` varchar(50) DEFAULT NULL,
`color` varchar(20) DEFAULT NULL,
`caption` varchar(255) DEFAULT NULL,
`link` varchar(255) DEFAULT NULL,
`target` varchar(20) DEFAULT NULL,
`heading` text,
`paragraph` text,
`dlink` varchar(255) DEFAULT NULL,
`dtarget` varchar(20) DEFAULT NULL,
`type` varchar(5) DEFAULT NULL,
`columns` int(11) DEFAULT NULL,
`rows` int(11) DEFAULT NULL,
`type2d` varchar(50) DEFAULT NULL,
`flipAngle` int(11) DEFAULT NULL,
`flipOrder` int(11) DEFAULT NULL,
`flipShader` varchar(50) DEFAULT NULL,
`flipOrderFromCenter` varchar(20) DEFAULT NULL,
`flipDirection` varchar(50) DEFAULT NULL,
`flipColor` varchar(30) DEFAULT NULL,
`flipBoxDepth` varchar(50) DEFAULT NULL,
`flipDepth` varchar(50) DEFAULT NULL,
`flipEasing` varchar(50) DEFAULT NULL,
`flipDuration` varchar(50) DEFAULT NULL,
`flipDelay` varchar(50) DEFAULT NULL,
`flipDelayRandomize` varchar(50) DEFAULT NULL,
`align_pos` varchar(5) DEFAULT NULL,
`fit` varchar(255) DEFAULT NULL,
`x` varchar(50) DEFAULT NULL,
`y` varchar(50) DEFAULT NULL,
`scaleX` varchar(50) DEFAULT NULL,
`scaleY` varchar(50) DEFAULT NULL,
`salign_pos` varchar(5) DEFAULT NULL,
`sx` varchar(50) DEFAULT NULL,
`sy` varchar(50) DEFAULT NULL,
`swidth` varchar(50) DEFAULT NULL,
`sheight` varchar(50) DEFAULT NULL,
`corner_TL` varchar(50) DEFAULT NULL,
`corner_TR` varchar(50) DEFAULT NULL,
`corner_BL` varchar(50) DEFAULT NULL,
`corner_BR` varchar(50) DEFAULT NULL,
`thumb_width` varchar(50) DEFAULT NULL,
`thumb_height` varchar(50) DEFAULT NULL,
`transparent` varchar(15) DEFAULT NULL,
`seo_show_image` varchar(5) NOT NULL DEFAULT '',
`seo_show_heading` varchar(5) NOT NULL DEFAULT '',
`seo_show_paragraph` varchar(5) NOT NULL DEFAULT '',
`seo_show_caption` varchar(5) NOT NULL DEFAULT '',
`use_post_images` varchar(5) NOT NULL DEFAULT '',
`posts_count` int(11) NOT NULL DEFAULT 4,
`posts_fit` varchar(255) NOT NULL DEFAULT 'dafault',
PRIMARY KEY (`id`)
)";
$sql3 = "CREATE TABLE `" . $wpdb->prefix . "cu3er__settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cu3er_location` varchar(255) DEFAULT NULL,
`licence` varchar(255) DEFAULT NULL,
`licence1` varchar(255) DEFAULT NULL,
`licence2` varchar(255) DEFAULT NULL,
`licence3` varchar(255) DEFAULT NULL,
`licence4` varchar(255) DEFAULT NULL,
`js_location` varchar(255) DEFAULT NULL,
`js_player_location` varchar(255) DEFAULT NULL,
`version` varchar(10) NOT NULL DEFAULT '0.36',
`branding` enum('no', 'yes') NOT NULL DEFAULT 'no',
PRIMARY KEY (`id`)
)";
$sql4 = "INSERT INTO `" . $wpdb->prefix . "cu3er__settings` (`id`,`version`) VALUES (1,'0.36') ON DUPLICATE KEY UPDATE `version`='0.36'";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql0.$cu3er__collate);
dbDelta($sql1.$cu3er__collate);
dbDelta($sql2.$cu3er__collate);
dbDelta($sql3.$cu3er__collate);
dbDelta($sql4);
}
$uploads = wp_upload_dir();
if(!is_dir($uploads['basedir'] . '/wpcu3er')) {
@mkdir($uploads['basedir'] . '/wpcu3er', 0777);
}
}
function cu3er__checkDatabaseForUpdate() {
global $wpdb;
$sql1 = "SELECT `version` FROM `" . $wpdb->prefix . "cu3er__settings` WHERE `id`=1";
$row = $wpdb->get_row($sql1, ARRAY_A);
switch($r['version']) {
case '0.1b':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slideshows` ADD COLUMN `bg_scaleX` varchar(50) AFTER `bg_use_image`, ADD COLUMN `bg_scaleY` varchar(50) AFTER `bg_scaleX`;");
case '0.22':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__settings` CHARACTER SET utf8 COLLATE utf8_general_ci;");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__defaults` CHARACTER SET utf8 COLLATE utf8_general_ci;");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slideshows` CHARACTER SET utf8 COLLATE utf8_general_ci;");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slides` CHARACTER SET utf8 COLLATE utf8_general_ci;");
case '0.23':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slideshows` DROP COLUMN `type`");
case '0.24':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__settings` ADD COLUMN `branding` enum('no', 'yes') NOT NULL DEFAULT 'no' AFTER `version`");
case '0.25':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slideshows` ADD COLUMN `br_align_to` varchar(20) AFTER `modified`, ADD COLUMN `br_align_pos` varchar(20) AFTER `br_align_to`, ADD COLUMN `br_x` varchar(20) AFTER `br_align_pos`, ADD COLUMN `br_y` varchar(20) AFTER `br_x`");
case '0.26':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slideshows` ADD COLUMN `force_js` enum('no', 'yes') NOT NULL AFTER `modified`");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__defaults` ADD COLUMN `corner_TL` varchar(50) DEFAULT NULL AFTER `scaleY`, ADD COLUMN `corner_TR` varchar(50) DEFAULT NULL AFTER `corner_TL`, ADD COLUMN `corner_BL` varchar(50) DEFAULT NULL AFTER `corner_TR`, ADD COLUMN `corner_BR` varchar(50) DEFAULT NULL AFTER `corner_BL`");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__defaults` ADD COLUMN `thumb_width` varchar(50) DEFAULT NULL AFTER `sheight`, ADD COLUMN `thumb_height` varchar(50) DEFAULT NULL AFTER `thumb_width`");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__settings` ADD COLUMN `js_player_location` varchar(255) NOT NULL AFTER `branding`");
case '0.27':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slideshows` ADD COLUMN `pr_width` varchar(15) DEFAULT NULL AFTER `modified`");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slideshows` ADD COLUMN `pr_height` varchar(15) DEFAULT NULL AFTER `modified`");
case '0.28':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__defaults` ADD COLUMN `transparent` varchar(15) DEFAULT NULL AFTER `sheight`");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slides` ADD COLUMN `transparent` varchar(15) DEFAULT NULL AFTER `scaleY`");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slides` ADD COLUMN `use_image` enum('yes', 'no') NOT NULL DEFAULT 'yes' AFTER `scaleY`;");
case '0.29':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__defaults` ADD COLUMN `seo_show_image` varchar(5) NOT NULL DEFAULT '' AFTER `sheight`, ADD COLUMN `seo_show_heading` varchar(5) NOT NULL DEFAULT '' AFTER `seo_show_image`, ADD COLUMN `seo_show_paragraph` varchar(5) NOT NULL DEFAULT '' AFTER `seo_show_heading`, ADD COLUMN `seo_show_caption` varchar(5) NOT NULL DEFAULT '' AFTER `seo_show_paragraph`");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slides` ADD COLUMN `seo_show_image` varchar(5) NOT NULL DEFAULT '' AFTER `use_image`, ADD COLUMN `seo_show_heading` varchar(5) NOT NULL DEFAULT '' AFTER `seo_show_image`, ADD COLUMN `seo_show_paragraph` varchar(5) NOT NULL DEFAULT '' AFTER `seo_show_heading`, ADD COLUMN `seo_show_caption` varchar(5) NOT NULL DEFAULT '' AFTER `seo_show_paragraph`, ADD COLUMN `seo_text` text NOT NULL AFTER `seo_show_caption`, ADD COLUMN `seo_img_alt` text NOT NULL AFTER `seo_text`;");
case '0.30':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slideshows` ADD COLUMN `project_location` varchar(255) DEFAULT NULL AFTER `br_y`;");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__settings` ADD COLUMN `licence1` varchar(255) AFTER `licence`, ADD COLUMN `licence2` varchar(255) AFTER `licence1`, ADD COLUMN `licence3` varchar(255) AFTER `licence2`, ADD COLUMN `licence4` varchar(255) AFTER `licence3`;");
$wpdb->query("UPDATE `" . $wpdb->prefix . "cu3er__slideshows` SET `project_location`=''");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__defaults` ADD COLUMN `use_post_images` varchar(5) NOT NULL DEFAULT '' AFTER `sheight`, ADD COLUMN `seo_show_paragraph` varchar(5) NOT NULL DEFAULT '' AFTER `seo_show_heading`, ADD COLUMN `seo_show_caption` varchar(5) NOT NULL DEFAULT '' AFTER `seo_show_paragraph`");
case '0.31':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__settings` ADD COLUMN `licence1` varchar(255) AFTER `licence`, ADD COLUMN `licence2` varchar(255) AFTER `licence1`, ADD COLUMN `licence3` varchar(255) AFTER `licence2`, ADD COLUMN `licence4` varchar(255) AFTER `licence3`;");
case '0.32':
$wpdb->query("UPDATE `" . $wpdb->prefix . "cu3er__slideshows` SET `project_location`=''");
case '0.33':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__defaults` ADD COLUMN `use_post_images` varchar(5) NOT NULL DEFAULT '' AFTER `sheight`, ADD COLUMN `posts_count` int(11) NOT NULL DEFAULT 4 AFTER `seo_show_image`");
case '0.34':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__defaults` ADD COLUMN `posts_fit` varchar(255) NOT NULL DEFAULT 'default' AFTER `sheight`, ADD COLUMN `fit` varchar(255) NOT NULL DEFAULT '' AFTER `seo_show_image`");
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slides` ADD COLUMN `fit` varchar(255) NOT NULL DEFAULT '' AFTER `use_image`;");
break;
case '0.35':
$wpdb->query("ALTER TABLE `" . $wpdb->prefix . "cu3er__slideshows` ADD COLUMN `force_js3d` enum('no', 'yes') NOT NULL DEFAULT 'no' AFTER `project_location`,
ADD COLUMN `responsive` enum('yes', 'no') NOT NULL DEFAULT 'yes' AFTER `force_js3d`, ADD COLUMN `height_type` enum('px', '%') NOT NULL DEFAULT 'px' AFTER `height`, ADD COLUMN `width_type` enum('px', '%') NOT NULL DEFAULT 'px' AFTER `width`");
$wpdb->query("INSERT INTO `" . $wpdb->prefix . "cu3er__settings` (`id`,`version`) VALUES (1,'0.36') ON DUPLICATE KEY UPDATE `version`='0.36'");
break;
case '0.36':
// next version update will come here //
break;
}
}
function cu3er__checkCu3erJS() {
global $wpdb;
$row = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__settings` LIMIT 1", ARRAY_A) or die(mysql_error());
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$settings = str_replace("'", "\'", $row);
if(!preg_match('/jquery\.cu3er\.js/', $settings['js_location'])) {
cu3er_downloadJS();
}
if(!preg_match('/jquery\.cu3er\.player\.js/', $settings['js_player_location'])) {
cu3er_downloadJS(true);
}
}
function cu3er__action_uninstall() {
global $wpdb;
$wpdb->query("DROP TABLE `" . $wpdb->prefix . "cu3er__settings`");
$wpdb->query("DROP TABLE `" . $wpdb->prefix . "cu3er__defaults`");
$wpdb->query("DROP TABLE `" . $wpdb->prefix . "cu3er__slideshows`");
$wpdb->query("DROP TABLE `" . $wpdb->prefix . "cu3er__slides`");
}
function display_cu3er($slideshow, $ret = false) {
if(is_numeric($slideshow)) {
global $wpdb;
// embeded code for showing cu3er //
$row = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__settings` LIMIT 1", ARRAY_A) or die(mysql_error());
$settings = array();
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
$settings[$key] = str_replace("'", "\'", $row[$key]);
}
$row = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "cu3er__slideshows` WHERE `id`='".$slideshow."'", ARRAY_A) or die(mysql_error());
$slideshowS = array();
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
$slideshowS[$key] = str_replace("'", "\'", $row[$key]);
}
$row =$wpdb->get_row("SELECT `use_post_images`,`posts_count` FROM `".$wpdb->prefix."cu3er__defaults` WHERE `slideshow_id`='".$slideshow."'", ARRAY_A) or die(mysql_error());
$data = explode('|||||', cu3er__readFromFile($slideshow));
$seo_str = $data[1];
/*if($settings['licence'] != '') {
$data[0] = preg_replace('/\%3Clicence\%3E(.*?)\%2Flicence\%3E/', urlencode('<licence><![CDATA['. urldecode(trim($settings['licence'])) .']]></licence>'), $data[0]);
}*/
$cObject = "var CU3ER_object = new CU3ER('CU3ER".$slideshow."');";
$params = ($slideshowS['backgroundType'] == 'transparent') ? "wmode : 'transparent'" : "bgcolor : '".str_replace('0x', '#', $slideshowS['background'])."'";
$fjs = ($slideshowS['force_js'] == 'yes') ? 'true' : 'false';
$baseUrl = cu3er__resolveUrl(cu3er__removeDomainName($slideshowS['images_folder'], true)). cu3er__removeDomainName($slideshowS['images_folder'], true);
$fflash = (cu3er__isFallback($baseUrl . '/fallback')) ? 'false' : 'true';
$fjs3d = ($slideshowS['force_js3d'] == 'yes') ? ',display_js3d_first: true' : '';
$responsive = ($slideshowS['responsive'] == 'no') ? ',responsiveSlider: false' : '';
$content = ($seo_str != '') ? $seo_str : $slideshowS['content'];
$images_var = '';
if($defaults['use_post_images'] == 'yes' && $defaults['posts_count'] > 0) {
/*query_posts('showposts=' . $defaults['posts_count']);
while (have_posts()) : the_post();
$images[] = wp_get_attachment_url(get_post_thumbnail_id($post->ID));
endwhile;*/
$rPosts = new WP_Query();
$rPosts->query('showposts=' . $defaults['posts_count']);
while ($rPosts->have_posts()) : $rPosts->the_post();
$images[] = wp_get_attachment_url(get_post_thumbnail_id($post->ID));
endwhile;
wp_reset_query();
$images_var = ',images:"'.implode(",", $images).'"';
}
$slideshowS['width_type'] = ($slideshowS['width_type'] == '%') ? '%' : '';
$slideshowS['height_type'] = ($slideshowS['height_type'] == '%') ? '%' : '';
if($slideshowS['width'] > 0) {
$var = "<script type='text/javascript'>
jQuery(document).ready(function($) {
$('#CU3ER". $slideshow ."').cu3er({
vars: {
xml_location: \"".cu3er__removeDomainName($slideshowS['xml_location'])."\",
xml_encoded: '".$data[0]."',
swf_location: '". $settings['cu3er_location'] . "?" . time() . "',
css_location: '". WP_PLUGIN_URL."/wpcu3er/css/CU3ER.css',
js_location: '".$settings['js_player_location']."?".time()."',
width: '". $slideshowS['width'] . $slideshowS['width_type'] ."',
height: '". $slideshowS['height'] . $slideshowS['height_type'] ."',
force_javascript: ". $fjs .",
force_flash: ". $fflash ."".$images_var."".$fjs3d."".$responsive."
},
params: {
". $params .",
allowScriptAccess: 'always'
},
attributes: {
id:'CU3ER".$slideshow."',
name:'CU3ER".$slideshow."'
}
});
});
</script>" . $content;
} else {
$var = '';
}
if($ret) {
return $var;
} else {
echo '<div id="CU3ER'.$slideshow.'">' . $var . '</div>';
}
}
}
function CU3ER_func($atts) {
global $wpdb;
extract(shortcode_atts(array(
'slider' => false
), $atts));
if($slider) {
return display_cu3er($slider, true);
} else {
return false;
}
}
function cu3er__array_remove_empty($input){
return cu3er__cleanUpArray($input);
}
function cu3er__cleanUpArray($arr, $non_zero_start = 0) {
$main = array('transition', 'slide');
$new_arr = array();
foreach ($arr as $key => $value) {
if (isset($value)) {
if (is_array($value)) {
$value = cu3er__cleanUpArray($value, $non_zero_start);
// If after the cleaning there are not elements do not bother to add this item
if (count($value) == 0) {
if(!in_array($key, $main)) {
continue;
} else {
$new_arr[$key] = $value;
}
}
} else {
$value = trim($value);
if(((string)$value == '' || (string)$value == null) && !in_array($key, $main)) {
continue;
}
}
$new_arr[$key] = $value;
} else {
if($value === 0 || in_array($key, $main)) {
$new_arr[$key] = $value;
}
}
}
// Reordering elements
if (!empty($new_arr)) {
if (!empty($non_zero_start)) {
$new_arr = array_merge_recursive(array("") + $new_arr);
unset($new_arr[0]);
} else {
$new_arr = array_merge_recursive($new_arr);
}
}
return $new_arr;
}
function cu3er__getAttributes($array, $parent) {
if(is_array($array)) {
foreach($array as $key=>$value) {
if($key === '@attributes') {
foreach($value as $k=>$v) {
$attr[] = $k . '="' . $v . '"';
}
$attributes[$parent] = implode(" ", $attr);
unset($attr);
}
}
}
return $attributes;
}
function cu3er__getNodeValue($array) {
if(is_array($array)) {
foreach($array as $key=>$value) {
if($key === 'vle') {
return $value;
}
}
}
return '';
}
function cu3er__array2xml($array) {
foreach($array as $key=>$value) {
if(is_array($value)) {
if($key !== '@attributes' && $key !== 'vle') {
if(is_numeric($key)) {
$childs = '';
$children = cu3er__array2xml($value);
} else {
$childs .= cu3er__array2xml($value);
$childs = ($childs != '') ? $childs : 'empty';
}
}
} else {
$childs = ($value != '') ? $value : 'empty';
}
if($childs != '') {
$attributes = cu3er__getAttributes($array[$key], $key);
$vle = cu3er__getNodeValue($array[$key]);
$attributes[$key] = ($attributes[$key] != '') ? ' ' . $attributes[$key] : '';
if($key !== 'vle' && $key !== '@attributes') {
if($childs == 'empty') {
if($vle != '') {
$xml .= '<'. $key . $attributes[$key] .'>' . $vle . '</'. $key .'>';
} else {
$xml .= '<'. $key . $attributes[$key] .' />';
}
} else {
$xml .= '<'. $key . $attributes[$key] .'>' . $vle . $childs . '</'. $key .'>';
}
unset($attributes[$key], $childs);
}
}
if($children != '') {
$xml .= $children;
$children = '';
}
}
return $xml;
}
function cu3er__createNewFallbackImage($image) {
// expecting array of values //
foreach($image as $key=>$value) {
$options[] = $key . '=' . urlencode($value);
}
//echo pre('http://205.186.138.15/img/wpcu3er/generate_slide.php?' . implode("&", $options));
$slide = cu3er__our_fopen('http://' . SERVER_THUMB_IP . '/img/wpcu3er/generate_slide.php?' . implode("&", $options), true);
return json_decode($slide);
}
function cu3er__isImage($img) {
if($img != '') {
$handle = cu3er__our_fopen($img);
if($handle != '') {
return true;
}
}
return false;
}
function cu3er__sql_magic($table, $data, $type = null) {
global $wpdb;
$unexpected = array('Submit','MAX_FILE_SIZE','submit_x','submit_y','filePath', 'act');
if($type == 'del') {
foreach($data as $key=>$value) {
if(!in_array($key,$unexpected)) $qstr[] = "`".$key."` = '".mysql_real_escape_string($value)."'";
}
$qstr = @implode(" AND ",$qstr);
return ($wpdb->query("DELETE FROM `".$table."` WHERE ".$qstr)) ? true : false;
} else {
foreach($data as $key=>$value) {
if($value != '') {
if($value == 'emp7y') $value = '';
if($key == 'licence') {
$qstr[] = "`".$key."` = '".stripslashes($value)."'";
}
if($type == 'ins') {
if(!in_array($key, $unexpected)) $qstr[] = "`".$key."` = '".mysql_real_escape_string($value)."'";
} else {
if(!in_array($key, $unexpected)) (preg_match('{^\S{0,1}id$}', $key)) ? $str = "`".$key."`='".mysql_real_escape_string($value)."'" : $qstr[] = "`".$key."` = '".mysql_real_escape_string($value)."'";
}
}
}
$qstr = @implode(",",$qstr);
if(!empty($str)) {
//echo "UPDATE `".$table."` SET ".$qstr." WHERE ".$str;
//echo "<br/><br/>";
return $wpdb->query("UPDATE `".$table."` SET ".$qstr." WHERE ".$str);
} else {
//echo "INSERT INTO `".$table."` SET ".$qstr;
//echo "<br/><br/>";
return $wpdb->query("INSERT INTO `".$table."` SET ".$qstr);
}
}
}
function cu3er__removeDomainName($string, $explicit = false) {
$url = parse_url($string);
$url1 = parse_url('http://' . $_SERVER['HTTP_HOST'] . '/');
if($explicit) {
return preg_replace('/http\:\/\/(.*?)\//', '/', $string);
}
return ($url['host'] == $url1['host']) ? preg_replace('/http\:\/\/(.*?)\//', '/', $string) : $string;
}
function cu3er__ffilesize($file){
if(cu3er__isOnSameDomain($file)) {
$uploads = wp_upload_dir();
$url = str_replace($uploads['baseurl'], $uploads['basedir'], $file);
return @filesize($url);
}
if(CU3ER_isCurlInstalled()) {
$ch = @curl_init($file);
@curl_setopt($ch, CURLOPT_FAILONERROR, true);
@curl_setopt($ch, CURLOPT_NOBODY, true);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@curl_setopt($ch, CURLOPT_HEADER, true);
@curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4);
$data = @curl_exec($ch);
@curl_close($ch);
if($data === false) return false;
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) return (float)$matches[1];
} else {
return @filesize($file);
}
return false;
}
function cu3er__our_fopen($url, $force = false) {
if(CU3ER_isCurlInstalled()) {
$ch = curl_init();
if(!$force) {
if(strpos($url, $_SERVER['HTTP_HOST'])) {
$uploadsDir = wp_upload_dir();
$pth = explode("/", $url);
$delFlag = true;
$size = sizeof($pth);
$wpContentDirArray = explode('/', WP_CONTENT_DIR);
$wpContentDir = $wpContentDirArray[(sizeof($wpContentDirArray) -1)];
for($i=0; $i<$size; $i++) {
if($pth[$i] == $wpContentDir) {
unset($pth[$i], $pth[($i+1)]);
$delFlag = false;
}
if($delFlag == true) {
unset($pth[$i]);
}
}
$url = $uploadsDir['basedir'] . '/' . implode("/", $pth);
$contents = file_get_contents($url);
return ($contents != '') ? $contents : false;
}
}
@curl_setopt($ch, CURLOPT_FAILONERROR, true);
@curl_setopt($ch, CURLOPT_URL, $url);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
@curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4);
$contents = curl_exec($ch);
curl_close($ch);
} else {
$contents = file_get_contents($url);
}
return ($contents != '') ? $contents : false;
}
if(!function_exists('pre')) {
function pre() {
$out = '<pre>';
foreach (func_get_args() as $arg) $out .= sprintf("\n%s\n", print_r($arg, true));
$out .= '</pre>';
return $out;
}
}
function cu3er__getRand($loc) {
$rand = mt_rand(1,10000);
if(!is_dir($loc . $rand)) {
mkdir($loc . $rand);
chmod($loc . $rand, 0777);
return $rand;
} else {
cu3er__getRand($loc);
}
}
function CU3ER_isCurlInstalled() {
if(in_array('curl', get_loaded_extensions())) {
return true;
} else{
return false;
}
}
function cu3er__chmodDir($path = '.', $dirMod = '0755', $fileMod = '0644'){
$ignore = array("cgi-bin", ".", "..");
$extensionAllow = array('xml', 'jpg', 'jpeg', 'gif', 'png', 'swf');
$dh = @opendir($path);
while(false !== ($file = readdir($dh))) {
if(in_array(end(explode(".", $file)), $extensionAllow) || is_dir($path.'/'.$file)) {
if(!in_array($file, $ignore)) {
if(is_dir($path. "/" .$file)) {
chmod($path. "/" .$file, $dirMod);
cu3er__chmodDir($path. "/" .$file, $dirMod, $fileMod);
} else {
chmod($path. "/" .$file, $fileMod);
}
}
}
}
closedir($dh);
}
function cu3er__resolveUrl() {
/**
* The absolute pathname of the currently executing script.
* Notatka: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php,
* $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.
*/
if (isset($_SERVER['SCRIPT_FILENAME'])) {
$sRealPath = dirname($_SERVER['SCRIPT_FILENAME']);
}
else {
/**
* realpath — Returns canonicalized absolute pathname
*/
$sRealPath = realpath( './' ) ;
}
/**
* The filename of the currently executing script, relative to the document root.
* For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar
* would be /test.php/foo.bar.
*/
$sSelfPath = dirname($_SERVER['PHP_SELF']);
return substr($sRealPath, 0, strlen($sRealPath) - strlen($sSelfPath));
}
function cu3er__makeAll($dir, $mode = 0777, $recursive = true) {
if( is_null($dir) || $dir === "" ){
return FALSE;
}
if( is_dir($dir) || $dir === "/" ){
return TRUE;
}
if( cu3er__makeAll(dirname($dir), $mode, $recursive) ){
return mkdir($dir, $mode);
}
return FALSE;
}
function cu3er__smartCopy($source, $dest, $doNotCopy = array(), $options = array('folderPermission'=>0755,'filePermission'=>0755)) {
$result=false;
//For Cross Platform Compatibility
if (!isset($options['noTheFirstRun'])) {
$source=str_replace('\\','/',$source);
$dest=str_replace('\\','/',$dest);
$options['noTheFirstRun']=true;
}
if (is_file($source) && !in_array(basename($source), $doNotCopy)) {
if ($dest[strlen($dest)-1]=='/') {
if (!file_exists($dest)) {
cu3er__makeAll($dest,$options['folderPermission'],true);
}
$__dest=$dest."/".basename($source);
} else {
$__dest=$dest;
}
if (!file_exists($__dest)) {
$result=copy($source, $__dest);
chmod($__dest,$options['filePermission']);
}
} elseif(is_dir($source)) {
if ($dest[strlen($dest)-1]=='/') {
if ($source[strlen($source)-1]=='/') {
//Copy only contents
} else {
//Change parent itself and its contents
$dest=$dest.basename($source);
@mkdir($dest);
chmod($dest,$options['filePermission']);
}
} else {
if ($source[strlen($source)-1]=='/') {
//Copy parent directory with new name and all its content
@mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
} else {
//Copy parent directory with new name and all its content
@mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
}
}
$dirHandle=opendir($source);
while($file=readdir($dirHandle))
{
if($file!="." && $file!="..")
{
$__dest=$dest."/".$file;
$__source=$source."/".$file;
//echo "$__source ||| $__dest<br />";
if ($__source!=$dest) {
//echo $__source." ".$__dest." ".$options;
$result=cu3er__smartCopy($__source, $__dest, $doNotCopy, $options);
}
}
}
closedir($dirHandle);
} else {
$result=false;
}
return $result;
}
function cu3er__isFallback($url) {
return (file_exists($url)) ? true : false;
}
function cu3er__cleanDir($dir, $all = false) {
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if(!$all) {
if($file != "." && $file != ".." && !is_dir($dir.$file)) {
if(preg_match("/_1\.png/", $file)) {
@unlink($dir.$file);
}
}
} else {
if($file != "." && $file != "..") {
if(is_file($dir.$file)) {
@chmod($dir.$file, 0777);
@unlink($dir.$file);
} else {
cu3er__cleanDir($dir.$file.'/', true);
@rmdir($dir.$file.'/');
}
}
}
}
closedir($dh);
}
}
}
function cu3er__load_cu3er_js() {
global $wpdb;
$row = $wpdb->get_row("SELECT * FROM `". $wpdb->prefix ."cu3er__settings` WHERE `id`=1", ARRAY_A);
foreach($row as $key=>$value) {
$row[$key] = stripslashes($value);
}
$settings = $row;
if($settings['js_location'] != '') {
wp_enqueue_script( 'cu3er', $settings['js_location'], array('jquery'));
}
}
function cu3er__allow_img_insertion($vars) {
$vars['send'] = true; // 'send' as in "Send to Editor"
return($vars);
}
add_filter('get_media_item_args', 'cu3er__allow_img_insertion');
register_activation_hook(__FILE__, 'cu3er__action_activate'); // on install create everything needed for plugin to work correctly
register_uninstall_hook(__FILE__, 'cu3er__action_uninstall'); // on unistall delete all databases
add_action('admin_menu', 'cu3er__admin_actions'); // create menus for CU3ER
add_action('init', 'cu3er__action_load_scripts'); // loads required scripts
add_action('init', 'cu3er__action_load_styles'); // loads required styles
add_filter('upload_mimes', 'cu3er__my_myme_types', 1, 1); // allowing xml to be uploaded with media library
add_action('init', 'cu3er__action_register_tinymce'); // registers tinymce button and menu
add_action('init', 'cu3er__checkDatabaseForUpdate'); // registers tinymce button and menu
add_action('init', 'cu3er__checkCu3erJS');
add_action('wp_print_scripts', 'cu3er__load_cu3er_js');
add_shortcode('CU3ER', 'CU3ER_func'); // CU3ER shortcode
require_once('widgets/wpcu3er.php');
?>
|
shieldsdesignstudio/forefield
|
wp-content/plugins/wpcu3er/wpcu3er.php
|
PHP
|
gpl-2.0
| 122,647 |
/*
eXosip - This is the eXtended osip library.
Copyright (C) 2002,2003,2004,2005,2006,2007 Aymeric MOIZARD - [email protected]
eXosip 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.
eXosip 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 _JPIPE_H_
#define _JPIPE_H_
#ifdef OSIP_MT
#include <eXosip2/eXosip.h>
#ifdef _WIN32_WCE
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <osipparser2/osip_port.h>
#endif
#ifndef WIN32
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#endif
#if defined(__arc__)
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#endif
#ifdef WIN32
#include <windows.h>
#endif
/**
* @file jpipe.h
* @brief PPL Pipe Handling Routines
*/
/**
* @defgroup JPIPE Pipe Handling
* @ingroup PPL
* @{
*/
#ifdef __cplusplus
extern "C"
{
#endif
#ifndef WIN32
/**
* Structure for storing a pipe descriptor
* @defvar jpipe_t
*/
typedef struct jpipe_t jpipe_t;
struct jpipe_t
{
int pipes[2];
};
#else
/**
* Structure for storing a pipe descriptor
* @defvar ppl_pipe_t
*/
typedef struct jpipe_t jpipe_t;
struct jpipe_t
{
int pipes[2];
};
#endif
/**
* Get New pipe pair.
*/
jpipe_t *jpipe (void);
/**
* Close pipe
*/
int jpipe_close (jpipe_t * apipe);
/**
* Write in a pipe.
*/
int jpipe_write (jpipe_t * pipe, const void *buf, int count);
/**
* Read in a pipe.
*/
int jpipe_read (jpipe_t * pipe, void *buf, int count);
/**
* Get descriptor of reading pipe.
*/
int jpipe_get_read_descr (jpipe_t * pipe);
#ifdef __cplusplus
}
#endif
#endif
/** @} */
#endif
|
scs/uclinux
|
lib/libeXosip/libeXosip2-3.2.0/src/jpipe.h
|
C
|
gpl-2.0
| 2,181 |
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Represents the view for the administration dashboard.
*
* This includes the header, options, and other information that should provide
* The User Interface to the end user.
*
* @package ReadyGraph
* @author [email protected]
* @license GPL-2.0+
* @link http://www.readygraph.com
* @copyright 2014 Your Name or Company Name
*/
include("header.php");
if (!get_option('readygraph_access_token') || strlen(get_option('readygraph_access_token')) <= 0) {
}
else {
if (isset($_POST["readygraph_access_token"])) update_option('readygraph_access_token', $_POST["readygraph_access_token"]);
if (isset($_POST["readygraph_refresh_token"])) update_option('readygraph_refresh_token', $_POST["readygraph_refresh_token"]);
if (isset($_POST["readygraph_email"])) update_option('readygraph_email', $_POST["readygraph_email"]);
if (isset($_POST["readygraph_application_id"])) update_option('readygraph_application_id', $_POST["readygraph_application_id"]);
if (isset($_POST["readygraph_settings"])) update_option('readygraph_settings', $_POST["readygraph_settings"]);
if (isset($_POST["retentionemaileditor"])) update_option('readygraph_invite_email', $_POST["retentionemaileditor"]);
}
?>
<form method="post" id="myForm">
<input type="hidden" name="readygraph_access_token" value="<?php echo get_option('readygraph_access_token', '') ?>">
<input type="hidden" name="readygraph_refresh_token" value="<?php echo get_option('readygraph_refresh_token', '') ?>">
<input type="hidden" name="readygraph_email" value="<?php echo get_option('readygraph_email', '') ?>">
<input type="hidden" name="readygraph_application_id" value="<?php echo get_option('readygraph_application_id', '') ?>">
<input type="hidden" name="readygraph_settings" value="<?php echo htmlentities(str_replace("\\\"", "\"", get_option('readygraph_settings', '{}'))) ?>">
<input type="hidden" name="readygraph_delay" value="<?php echo get_option('readygraph_delay', '5000') ?>">
<input type="hidden" name="readygraph_enable_sidebar" value="<?php echo get_option('readygraph_enable_sidebar', 'false') ?>">
<input type="hidden" name="readygraph_enable_notification" value="<?php echo get_option('readygraph_enable_notification', 'true') ?>">
<input type="hidden" name="readygraph_auto_select_all" value="<?php echo get_option('readygraph_auto_select_all', 'true') ?>">
<input type="hidden" name="readygraph_enable_branding" value="<?php echo get_option('readygraph_enable_branding', 'false') ?>">
<input type="hidden" name="readygraph_send_blog_updates" value="<?php echo get_option('readygraph_send_blog_updates', 'true') ?>">
<input type="hidden" name="readygraph_send_real_time_post_updates" value="<?php echo get_option('readygraph_send_real_time_post_updates', 'false') ?>">
<input type="hidden" name="readygraph_popup_template" value="<?php echo get_option('readygraph_popup_template', 'default-template') ?>">
<div style="margin: 3% 5%">
<img src="<?php echo plugin_dir_url( __FILE__ );?>assets/15.png" style="float: right;margin-left: 10%;" width="310px" height="350px">
<h3><strong>Effortlessly Increase Your Site's Userbase</strong></h3>
<h4> Scale your audience faster with our Premium Growth Features:</h4>
<div style="width: 60%;">
<h4 class="rg-h4"><img src="<?php echo plugin_dir_url( __FILE__ );?>assets/round-check.png" class="rg-small-icon"/>Your site promoted to 10,000 New Users Every Month in our Community Email Update</h4>
<h4 class="rg-h4"><img src="<?php echo plugin_dir_url( __FILE__ );?>assets/round-check.png" class="rg-small-icon"/>Unlimited Viral Email/Facebook Invites</h4>
<h4 class="rg-h4"><img src="<?php echo plugin_dir_url( __FILE__ );?>assets/round-check.png" class="rg-small-icon"/>Unlimited Blog Post Notifications</h4>
<h4 class="rg-h4"><img src="<?php echo plugin_dir_url( __FILE__ );?>assets/round-check.png" class="rg-small-icon"/>Premium Phone/Email Support</h4>
<h4 class="rg-h4"><img src="<?php echo plugin_dir_url( __FILE__ );?>assets/round-check.png" class="rg-small-icon"/>More Premium Features Added All The Time!</h4>
<br>
<a href="https://readygraph.com/accounts/payment/?email=<?php echo get_option('readygraph_email', '') ?>" target="_blank"><img src="<?php echo plugin_dir_url( __FILE__ );?>assets/go-premium.png" height="40px" style="margin:5px"/></a>
</div>
<div style="margin: 65px 0; width: 100%; display: block;">
<div class="rg-three-column" style="float: left">
<img src="<?php echo plugin_dir_url( __FILE__ );?>assets/12.png" height="40px" style="margin:15px"/>Explosive Website Growth
</div>
<div class="rg-three-column" style="float: left">
<img src="<?php echo plugin_dir_url( __FILE__ );?>assets/13.png" height="40px" style="margin:15px"/>Develop a Community of Users
</div>
<div class="rg-three-column" style="float: left">
<img src="<?php echo plugin_dir_url( __FILE__ );?>assets/14.png" height="40px" style="margin:15px"/>Track Growth with Powerful Analytics
</div>
</div>
<p><h4 class="rg-h4">ReadyGraph Premium equips your Wordpress site with the industry's most powerful proven growth features. Websites have used our tools to increase their growth rate by upto 70X.</h4></p>
<p><h4 class="rg-h4">Don't keep keep your website a secret! Set your growth to "full-blast" with ReadyGraph.</h4> </p>
<p><h4 class="rg-h4"><a target="_blank" href="https://readygraph.com/accounts/payment/?email=<?php echo get_option('readygraph_email', '') ?>">Start A Free Trial Today!</a> </h4></p>
</div>
</form>
<?php include("footer.php"); ?>
|
jimrucinski/Vine
|
wp-content/plugins/subscribe2/extension/readygraph/go-premium.php
|
PHP
|
gpl-2.0
| 5,626 |
/* SPDX-License-Identifier: LGPL-2.1+ */
#ifndef foosdeventhfoo
#define foosdeventhfoo
/***
systemd 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.
systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <inttypes.h>
#include <signal.h>
#include <sys/epoll.h>
#include <sys/inotify.h>
#include <sys/signalfd.h>
#include <sys/types.h>
#include <time.h>
#include "_sd-common.h"
/*
Why is this better than pure epoll?
- Supports event source prioritization
- Scales better with a large number of time events because it does not require one timerfd each
- Automatically tries to coalesce timer events system-wide
- Handles signals and child PIDs
*/
_SD_BEGIN_DECLARATIONS;
#define SD_EVENT_DEFAULT ((sd_event *) 1)
typedef struct sd_event sd_event;
typedef struct sd_event_source sd_event_source;
enum {
SD_EVENT_OFF = 0,
SD_EVENT_ON = 1,
SD_EVENT_ONESHOT = -1
};
enum {
SD_EVENT_INITIAL,
SD_EVENT_ARMED,
SD_EVENT_PENDING,
SD_EVENT_RUNNING,
SD_EVENT_EXITING,
SD_EVENT_FINISHED,
SD_EVENT_PREPARING
};
enum {
/* And everything in-between and outside is good too */
SD_EVENT_PRIORITY_IMPORTANT = -100,
SD_EVENT_PRIORITY_NORMAL = 0,
SD_EVENT_PRIORITY_IDLE = 100
};
typedef int (*sd_event_handler_t)(sd_event_source *s, void *userdata);
typedef int (*sd_event_io_handler_t)(sd_event_source *s, int fd, uint32_t revents, void *userdata);
typedef int (*sd_event_time_handler_t)(sd_event_source *s, uint64_t usec, void *userdata);
typedef int (*sd_event_signal_handler_t)(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata);
#if defined _GNU_SOURCE || _POSIX_C_SOURCE >= 199309L
typedef int (*sd_event_child_handler_t)(sd_event_source *s, const siginfo_t *si, void *userdata);
#else
typedef void* sd_event_child_handler_t;
#endif
typedef int (*sd_event_inotify_handler_t)(sd_event_source *s, const struct inotify_event *event, void *userdata);
typedef void (*sd_event_destroy_t)(void *userdata);
int sd_event_default(sd_event **e);
int sd_event_new(sd_event **e);
sd_event* sd_event_ref(sd_event *e);
sd_event* sd_event_unref(sd_event *e);
int sd_event_add_io(sd_event *e, sd_event_source **s, int fd, uint32_t events, sd_event_io_handler_t callback, void *userdata);
int sd_event_add_time(sd_event *e, sd_event_source **s, clockid_t clock, uint64_t usec, uint64_t accuracy, sd_event_time_handler_t callback, void *userdata);
int sd_event_add_signal(sd_event *e, sd_event_source **s, int sig, sd_event_signal_handler_t callback, void *userdata);
int sd_event_add_child(sd_event *e, sd_event_source **s, pid_t pid, int options, sd_event_child_handler_t callback, void *userdata);
int sd_event_add_inotify(sd_event *e, sd_event_source **s, const char *path, uint32_t mask, sd_event_inotify_handler_t callback, void *userdata);
int sd_event_add_defer(sd_event *e, sd_event_source **s, sd_event_handler_t callback, void *userdata);
int sd_event_add_post(sd_event *e, sd_event_source **s, sd_event_handler_t callback, void *userdata);
int sd_event_add_exit(sd_event *e, sd_event_source **s, sd_event_handler_t callback, void *userdata);
int sd_event_prepare(sd_event *e);
int sd_event_wait(sd_event *e, uint64_t usec);
int sd_event_dispatch(sd_event *e);
int sd_event_run(sd_event *e, uint64_t usec);
int sd_event_loop(sd_event *e);
int sd_event_exit(sd_event *e, int code);
int sd_event_now(sd_event *e, clockid_t clock, uint64_t *usec);
int sd_event_get_fd(sd_event *e);
int sd_event_get_state(sd_event *e);
int sd_event_get_tid(sd_event *e, pid_t *tid);
int sd_event_get_exit_code(sd_event *e, int *code);
int sd_event_set_watchdog(sd_event *e, int b);
int sd_event_get_watchdog(sd_event *e);
int sd_event_get_iteration(sd_event *e, uint64_t *ret);
sd_event_source* sd_event_source_ref(sd_event_source *s);
sd_event_source* sd_event_source_unref(sd_event_source *s);
sd_event *sd_event_source_get_event(sd_event_source *s);
void* sd_event_source_get_userdata(sd_event_source *s);
void* sd_event_source_set_userdata(sd_event_source *s, void *userdata);
int sd_event_source_set_description(sd_event_source *s, const char *description);
int sd_event_source_get_description(sd_event_source *s, const char **description);
int sd_event_source_set_prepare(sd_event_source *s, sd_event_handler_t callback);
int sd_event_source_get_pending(sd_event_source *s);
int sd_event_source_get_priority(sd_event_source *s, int64_t *priority);
int sd_event_source_set_priority(sd_event_source *s, int64_t priority);
int sd_event_source_get_enabled(sd_event_source *s, int *enabled);
int sd_event_source_set_enabled(sd_event_source *s, int enabled);
int sd_event_source_get_io_fd(sd_event_source *s);
int sd_event_source_set_io_fd(sd_event_source *s, int fd);
int sd_event_source_get_io_fd_own(sd_event_source *s);
int sd_event_source_set_io_fd_own(sd_event_source *s, int own);
int sd_event_source_get_io_events(sd_event_source *s, uint32_t* events);
int sd_event_source_set_io_events(sd_event_source *s, uint32_t events);
int sd_event_source_get_io_revents(sd_event_source *s, uint32_t* revents);
int sd_event_source_get_time(sd_event_source *s, uint64_t *usec);
int sd_event_source_set_time(sd_event_source *s, uint64_t usec);
int sd_event_source_get_time_accuracy(sd_event_source *s, uint64_t *usec);
int sd_event_source_set_time_accuracy(sd_event_source *s, uint64_t usec);
int sd_event_source_get_time_clock(sd_event_source *s, clockid_t *clock);
int sd_event_source_get_signal(sd_event_source *s);
int sd_event_source_get_child_pid(sd_event_source *s, pid_t *pid);
int sd_event_source_get_inotify_mask(sd_event_source *s, uint32_t *ret);
int sd_event_source_set_destroy_callback(sd_event_source *s, sd_event_destroy_t callback);
int sd_event_source_get_destroy_callback(sd_event_source *s, sd_event_destroy_t *ret);
/* Define helpers so that __attribute__((cleanup(sd_event_unrefp))) and similar may be used. */
_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_event, sd_event_unref);
_SD_DEFINE_POINTER_CLEANUP_FUNC(sd_event_source, sd_event_source_unref);
_SD_END_DECLARATIONS;
#endif
|
whot/systemd
|
src/systemd/sd-event.h
|
C
|
gpl-2.0
| 6,651 |
/*
* Title : Music Player Module for Gmedia Gallery plugin
* Version : 2.0
* Copyright : 2013 CodEasily.com
* Website : http://www.codeasily.com
*/
(function($) {
$.fn.gmMusicPlayer = function(playlist, userOptions) {
var $self = this, opt_str, opt_int, opt_bool, opt_obj, options, cssSelector, appMgr, playlistMgr, interfaceMgr, ratingsMgr,
layout, ratings, myPlaylist, current,
$uid = $(this).data('uid');
cssSelector = {
jPlayer: ".gm-music-player",
jPlayerInterface: '.jqmp-'+$uid,
playerPrevious: ".jp-interface .jp-previous",
playerNext: ".jp-interface .jp-next",
trackList:'.gmmp-tracklist',
tracks:'.gmmp-tracks',
track:'.gmmp-track',
trackRating:'.gmmp-rating-bar',
rating:'.gmmp-rating',
ratingLevel:'.gmmp-rating-level',
ratingLevelOn:'.gmmp-on',
title: '.gmmp-track-title',
text: '.gmmp-track-description',
duration: '.gmmp-duration',
button:'.gmmp-button',
buttonNotActive:'.gmmp-not-active',
playing:'.gmmp-playing',
moreButton:'.gmmp-more',
player:'.gmmp-player',
//artist:'.gmmp-artist',
//artistOuter:'.gmmp-artist-outer',
albumCover:'.gmmp-img',
description:'.gmmp-description',
descriptionShowing:'.gmmp-showing'
};
opt_str = {
width:'auto',
buttonText:'Download',
moreText:'View More...'
};
opt_int = {
maxwidth:0,
tracksToShow:5
};
opt_bool = {
rating:true,
autoplay:false
};
opt_obj = {
jPlayer:{
swfPath: userOptions.pluginUrl + '/assets/jplayer'
}
};
options = $.extend(true, {}, opt_str, opt_int, opt_bool, opt_obj, userOptions);
$.each(options, function(key, val){
if(key in opt_bool){
options[key] = (!(!val || val == '0' || val == 'false'));
} else if(key in opt_int){
options[key] = parseInt(val);
}
});
myPlaylist = playlist;
current = 0;
appMgr = function() {
playlist = new playlistMgr();
layout = new interfaceMgr();
layout.buildInterface();
playlist.init(options.jPlayer);
//don't initialize the ratings until the playlist has been built, which wont happen until after the jPlayer ready event
$self.on('mbPlaylistLoaded', function() {
if(options.rating){
$self.on('mbInterfaceBuilt', function() {
ratings = new ratingsMgr();
});
}
layout.init();
});
};
playlistMgr = function() {
var playing = false, markup, $myJplayer = {},$tracks,$tracksWrapper, $more;
markup = {
listItem:'<li class="gmmp-track"><section>' +
'<span class="gmmp-maxwidth"><span class="gmmp-track-title-wrapper"> <span class="gmmp-track-title"></span></span></span>' +
'<span>' +
'<span class="gmmp-duration"> </span>' +
(options.rating ? '<span class="gmmp-rating"></span>' : '') +
'<a href="#" class="gmmp-button gmmp-not-active" target="_blank"></a>' +
'</span>' +
'</section></li>',
ratingBar:'<span class="gmmp-rating-level gmmp-rating-bar"></span>'
};
function init(playlistOptions) {
$myJplayer = $('.gm-music-player .jPlayer-container', $self);
var jPlayerDefaults, jPlayerOptions;
jPlayerDefaults = {
swfPath: "jplayer",
supplied: "mp3, oga",
cssSelectorAncestor: cssSelector.jPlayerInterface,
errorAlerts: false,
warningAlerts: false
};
//apply any user defined jPlayer options
jPlayerOptions = $.extend(true, {}, jPlayerDefaults, playlistOptions);
$myJplayer.on($.jPlayer.event.ready, function() {
//Bind jPlayer events. Do not want to pass in options object to prevent them from being overridden by the user
$myJplayer.on($.jPlayer.event.ended, function(event) {
playlistNext();
});
$myJplayer.on($.jPlayer.event.play, function(event) {
$myJplayer.jPlayer("pauseOthers");
$tracks.eq(current).addClass(attr(cssSelector.playing)).siblings().removeClass(attr(cssSelector.playing));
});
$myJplayer.on($.jPlayer.event.playing, function(event) {
playing = true;
});
$myJplayer.on($.jPlayer.event.pause, function(event) {
playing = false;
});
$myJplayer.on($.jPlayer.event.loadeddata, function(event) {
if(event.jPlayer.status.duration != 'NaN'){
$tracks.eq(current).find(cssSelector.duration).text($.jPlayer.convertTime( event.jPlayer.status.duration ));
}
});
//Bind next/prev click events
$(cssSelector.playerPrevious, $self).click(function() {
playlistPrev();
$(this).blur();
return false;
});
$(cssSelector.playerNext, $self).click(function() {
playlistNext();
$(this).blur();
return false;
});
$self.on('mbInitPlaylistAdvance', function(e) {
var changeTo = this.getData('mbInitPlaylistAdvance');
if (changeTo != current) {
current = changeTo;
playlistAdvance(current);
}
else {
if (!$myJplayer.data('jPlayer').status.srcSet) {
playlistAdvance(0);
}
else {
togglePlay();
}
}
});
buildPlaylist();
//If the user doesn't want to wait for widget loads, start playlist now
$self.trigger('mbPlaylistLoaded');
playlistInit(options.autoplay);
});
//Initialize jPlayer
$myJplayer.jPlayer(jPlayerOptions);
}
function playlistInit(autoplay) {
current = 0;
if (autoplay) {
playlistAdvance(current);
}
else {
playlistConfig(current);
$self.trigger('mbPlaylistInit');
}
}
function playlistConfig(index) {
current = index;
$myJplayer.jPlayer("setMedia", myPlaylist[current]);
}
function playlistAdvance(index) {
playlistConfig(index);
if (index >= options.tracksToShow)
showMore();
$self.trigger('mbPlaylistAdvance');
$myJplayer.jPlayer("play");
}
function playlistNext() {
var index = (current + 1 < myPlaylist.length) ? current + 1 : 0;
playlistAdvance(index);
}
function playlistPrev() {
var index = (current - 1 >= 0) ? current - 1 : myPlaylist.length - 1;
playlistAdvance(index);
}
function togglePlay() {
if (!playing)
$myJplayer.jPlayer("play");
else $myJplayer.jPlayer("pause");
}
function buildPlaylist() {
$tracksWrapper = $self.find(cssSelector.tracks);
if(options.rating){
var $ratings = $();
//set up the html for the track ratings
for (var i = 0; i < 10; i++)
$ratings = $ratings.add(markup.ratingBar);
}
for (var j = 0; j < myPlaylist.length; j++) {
var $track = $(markup.listItem, $self);
$track.find(cssSelector.title).html(trackName(j));
if(options.rating){
//since $ratings refers to a specific object, if we just use .html($ratings) we would be moving the $rating object from one list item to the next
$track.find(cssSelector.rating).html($ratings.clone());
setRating('track', $track, j);
}
setLink($track, j);
$track.data('index', j);
$tracksWrapper.append($track);
}
$tracks = $(cssSelector.track, $self);
$tracks.eq(options.tracksToShow - 1).nextAll().hide();
if (options.tracksToShow < myPlaylist.length) {
var $trackList = $(cssSelector.trackList, $self);
$trackList.addClass('gmmp-show-more-button');
$trackList.find(cssSelector.moreButton).click(function() {
$more = $(this);
showMore();
});
}
$tracks.find(cssSelector.title).click(function() {
playlistAdvance($(this).parents('li').data('index'));
});
}
function showMore() {
if (isUndefined($more))
$more = $self.find(cssSelector.moreButton);
$tracksWrapper.css('height', $tracksWrapper.height());
$tracks.show();
var tracks_height = $tracks.eq(0).outerHeight() * myPlaylist.length + 1;
$tracksWrapper.animate({height: tracks_height}, 400);
$more.removeClass('anim').animate({'height': 0}, 400, function() {
$more.parents(cssSelector.trackList).removeClass('gmmp-show-more-button');
$more.remove();
});
}
function setLink($track, index) {
if (myPlaylist[index].button !== '') {
$track.find(cssSelector.button).removeClass(attr(cssSelector.buttonNotActive)).attr('href', myPlaylist[index].button).html(options.buttonText);
var ext = myPlaylist[index].button.slice(-4);
if(('.mp3' == ext) || ('.ogg' == ext) ){
$track.find(cssSelector.button).attr('download', '');
}
}
}
return{
init:init,
playlistInit:playlistInit,
playlistAdvance:playlistAdvance,
playlistNext:playlistNext,
playlistPrev:playlistPrev,
togglePlay:togglePlay,
$myJplayer:$myJplayer
};
};
ratingsMgr = function() {
var $tracks = $self.find(cssSelector.track);
function bindEvents() {
//Handler for when user hovers over a rating
$(cssSelector.rating, $self).find(cssSelector.ratingLevel).hover(function() {
$(this).addClass('gmmp-hover').prevAll().addClass('gmmp-hover').end().nextAll().removeClass('gmmp-hover');
});
//Restores previous rating when user is finished hovering (assuming there is no new rating)
$(cssSelector.rating, $self).mouseleave(function() {
$(this).find(cssSelector.ratingLevel).removeClass('gmmp-hover');
});
//Set the new rating when the user clicks
$(cssSelector.ratingLevel, $self).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
if ($this.hasClass(attr(cssSelector.trackRating))) {
rating = rating / 2;
index = $this.parents('li').data('index');
if (index == current)
applyCurrentlyPlayingRating(rating);
}
else {
index = current;
applyTrackRating($tracks.eq(index), rating);
}
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
processRating(index, rating);
});
}
function processRating(index, rating) {
myPlaylist[index].rating = rating;
var gmid = myPlaylist[index].id,
uip = userOptions.ip;
$.post(userOptions.pluginUrl+'/rate.php', { rate: {uip:uip,gmid:gmid,rate:rating} }, function(r){
console.log(r);
});
//runCallback(options.ratingCallback, index, myPlaylist[index], rating);
}
bindEvents();
};
interfaceMgr = function() {
var $player, $title, $text, $artist, $albumCover;
function init() {
$player = $(cssSelector.player, $self),
$title = $player.find(cssSelector.title),
$text = $player.find(cssSelector.text),
//$artist = $player.find(cssSelector.artist),
$albumCover = $player.find(cssSelector.albumCover);
setDescription();
$self.on('mbPlaylistAdvance mbPlaylistInit', function() {
setTitle();
//setArtist();
setText();
if(options.rating){
setRating('current', null, current);
}
setCover();
});
}
function buildInterface() {
var markup, $interface;
//I would normally use the templating plugin for something like this, but I wanted to keep this plugin's footprint as small as possible
markup =
'<div class="gm-music-player">' +
' <div class="gmmp-player jp-interface jqmp-'+$uid+'">' +
' <div class="gmmp-album-cover">' +
' <span class="gmmp-img"></span>' +
' <span class="gmmp-highlight"></span>' +
(options.rating ?
' <div class="gmmp-rating">' +
' <span class="gmmp-rating-level gmmp-rating-star gmmp-on"></span>' +
' <span class="gmmp-rating-level gmmp-rating-star gmmp-on"></span>' +
' <span class="gmmp-rating-level gmmp-rating-star gmmp-on"></span>' +
' <span class="gmmp-rating-level gmmp-rating-star gmmp-on"></span>' +
' <span class="gmmp-rating-level gmmp-rating-star"></span>' +
' </div>' : '') +
' </div>' +
' <div class="gmmp-track-title"></div>' +
' <div class="gmmp-player-controls">' +
' <div class="gmmp-main">' +
' <div class="gmmp-previous jp-previous"></div>' +
' <div class="gmmp-play jp-play"></div>' +
' <div class="gmmp-pause jp-pause"></div>' +
' <div class="gmmp-next jp-next"></div>' +
'<!-- These controls aren\'t used by this plugin, but jPlayer seems to require that they exist -->' +
' <span class="gmmp-unused-controls">' +
' <span class="jp-video-play"></span>' +
' <span class="jp-stop"></span>' +
' <span class="jp-mute"></span>' +
' <span class="jp-unmute"></span>' +
' <span class="jp-volume-bar"></span>' +
' <span class="jp-volume-bar-value"></span>' +
' <span class="jp-volume-max"></span>' +
' <span class="jp-current-time"></span>' +
' <span class="jp-duration"></span>' +
' <span class="jp-full-screen"></span>' +
' <span class="jp-restore-screen"></span>' +
' <span class="jp-repeat"></span>' +
' <span class="jp-repeat-off"></span>' +
' <span class="jp-gui"></span>' +
' </span>' +
' </div>' +
' <div class="gmmp-progress-wrapper">' +
' <div class="gmmp-progress jp-seek-bar">' +
' <div class="gmmp-elapsed jp-play-bar"></div>' +
' </div>' +
' </div>' +
' </div>' +
' <div class="gmmp-track-description"></div>' +
' </div>' +
' <div class="gmmp-description"></div>' +
' <div class="gmmp-tracklist">' +
' <ol class="gmmp-tracks"></ol>' +
' <div class="gmmp-more gmmp-anim">' + options.moreText + '</div>' +
' </div>' +
' <div class="jPlayer-container"></div>' +
'</div>';
var mw = (0 === options.maxwidth)? 'none' : options.maxwidth;
$interface = $(markup).css({display:'none', opacity:0, width: options.width, 'max-width': mw}).appendTo($self).slideDown('slow', function() {
$interface.animate({opacity:1});
$self.trigger('mbInterfaceBuilt');
});
}
function setTitle() {
$title.html(trackName(current));
}
/*
function setArtist() {
if (isUndefined(myPlaylist[current].artist))
$artist.parent(cssSelector.artistOuter).animate({opacity:0}, 'fast');
else {
$artist.html(myPlaylist[current].artist).parent(cssSelector.artistOuter).animate({opacity:1}, 'fast');
}
}
*/
function setText() {
if (myPlaylist[current].text === '')
$text.animate({opacity:0}, 'fast', function(){ $(this).empty() });
else {
$text.html(myPlaylist[current].text).animate({opacity:1}, 'fast');
}
}
function setCover() {
$albumCover.animate({opacity:0}, 'fast', function() {
$(this).empty();
if (!isUndefined(myPlaylist[current].cover) || myPlaylist[current].cover !== '') {
var now = current;
$('<img src="' + myPlaylist[current].cover + '" alt="album cover" />').load(function(){
if(now == current)
$albumCover.html($(this)).animate({opacity:1})
});
}
});
}
function setDescription() {
if (!isUndefined(options.description))
$self.find(cssSelector.description).html(options.description).addClass(attr(cssSelector.descriptionShowing)).slideDown();
}
return{
buildInterface:buildInterface,
init:init
}
};
/** Common Functions **/
function trackName(index) {
if (myPlaylist[index].title !== '')
return myPlaylist[index].title;
if (myPlaylist[index].mp3 !== '')
return fileName(myPlaylist[index].mp3);
if (myPlaylist[index].oga !== '')
return fileName(myPlaylist[index].oga);
return 'NaN';
}
function fileName(path) {
path = path.split('/');
return path[path.length - 1];
}
function setRating(type, $track, index) {
if (type == 'track') {
if (!isUndefined(myPlaylist[index].rating)) {
applyTrackRating($track, myPlaylist[index].rating);
}
}
else {
//if the rating isn't set, use 0
var rating = isUndefined(myPlaylist[index].rating)? 0 : Math.ceil(myPlaylist[index].rating);
applyCurrentlyPlayingRating(rating);
}
}
function applyCurrentlyPlayingRating(rating) {
//reset the rating to 0, then set the rating defined above
$self.find(cssSelector.player).find(cssSelector.ratingLevel).removeClass(attr(cssSelector.ratingLevelOn)).slice(0, rating).addClass(attr(cssSelector.ratingLevelOn));
}
function applyTrackRating($track, rating) {
//multiply rating by 2 since the list ratings have 10 levels rather than 5
$track.find(cssSelector.ratingLevel).removeClass(attr(cssSelector.ratingLevelOn)).slice(0, rating * 2).addClass(attr(cssSelector.ratingLevelOn));
}
/** Utility Functions **/
function attr(selector) {
return selector.substr(1);
}
/*
function runCallback(callback) {
var functionArgs = Array.prototype.slice.call(arguments, 1);
if ($.isFunction(callback)) {
callback.apply(this, functionArgs);
}
}
*/
function isUndefined(value) {
return typeof value == 'undefined';
}
appMgr();
};
})(jQuery);
|
icommstudios/localsharingtree
|
wp-content/plugins/grand-media/module/jq-mplayer/js/gm-music-player.js
|
JavaScript
|
gpl-2.0
| 17,884 |
#region
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using UlteriusServer.Api.Network.Models;
using UlteriusServer.Api.Services.Network;
using UlteriusServer.Api.Win32;
using UlteriusServer.Api.Win32.ScreenShare.Models;
using UlteriusServer.Utilities.Drive;
using SystemInformation = UlteriusServer.Api.Network.Models.SystemInformation;
#endregion
namespace UlteriusServer.Api.Services.LocalSystem
{
internal class SystemService
{
private string _biosCaption;
private string _biosManufacturer;
private string _biosSerial;
private string _cdRom;
private string _motherBoard;
public void Start()
{
//static info
try
{
SetNetworkInformation();
SetCpuInformation();
SetOperatingSystemInformation();
SystemInformation.MotherBoard = GetMotherBoard();
SystemInformation.CdRom = GetCdRom();
SystemInformation.Bios = GetBiosInfo();
SystemInformation.RunningAsAdmin = IsRunningAsAdministrator();
var service = new Task(Updater);
service.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
// ReSharper disable once UnusedMethodReturnValue.Local
private void SetNetworkInformation()
{
try
{
if (string.IsNullOrEmpty(NetworkInformation.PublicIp))
{
NetworkInformation.PublicIp = NetworkService.GetPublicIp();
NetworkInformation.MacAddress = NetworkService.GetMacAddress();
NetworkInformation.InternalIp = NetworkService.GetDisplayAddress();
NetworkInformation.NetworkComputers = NetworkService.ConnectedDevices();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
public void SetOperatingSystemInformation()
{
try
{
if (string.IsNullOrEmpty(OperatingSystemInformation.Name))
{
var wmi =
new ManagementObjectSearcher("select * from Win32_OperatingSystem")
.Get()
.Cast<ManagementObject>()
.First();
OperatingSystemInformation.Name = ((string) wmi["Caption"]).Trim();
OperatingSystemInformation.Version = (string) wmi["Version"];
OperatingSystemInformation.MaxProcessCount = (uint) wmi["MaxNumberOfProcesses"];
OperatingSystemInformation.MaxProcessRam = (ulong) wmi["MaxProcessMemorySize"];
OperatingSystemInformation.Architecture = (string) wmi["OSArchitecture"];
OperatingSystemInformation.SerialNumber = (string) wmi["SerialNumber"];
OperatingSystemInformation.Build = (string) wmi["BuildNumber"];
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
public void SetCpuInformation()
{
try
{
if (string.IsNullOrEmpty(CpuInformation.Name))
{
var cpu =
new ManagementObjectSearcher("select * from Win32_Processor")
.Get()
.Cast<ManagementObject>()
.First();
CpuInformation.Id = (string) cpu["ProcessorId"];
CpuInformation.Socket = (string) cpu["SocketDesignation"];
CpuInformation.Name = (string) cpu["Name"];
CpuInformation.Description = (string) cpu["Caption"];
CpuInformation.AddressWidth = (ushort?) cpu["AddressWidth"] ?? 0;
CpuInformation.DataWidth = (ushort?) cpu["DataWidth"] ?? 0;
CpuInformation.Architecture = Environment.Is64BitOperatingSystem ? "x64" : "x86";
CpuInformation.SpeedMHz = (uint?) cpu["MaxClockSpeed"] ?? 0;
CpuInformation.BusSpeedMHz = (uint?) cpu["ExtClock"] ?? 0;
CpuInformation.L2Cache = (uint?) cpu["L2CacheSize"]*(ulong) 1024 ?? 0;
CpuInformation.L3Cache = (uint?) cpu["L3CacheSize"]*(ulong) 1024 ?? 0;
CpuInformation.Cores = (uint?) cpu["NumberOfCores"] ?? 0;
CpuInformation.Threads = (uint?) cpu["NumberOfLogicalProcessors"] ?? 0;
CpuInformation.CurrentVoltage = (uint?)cpu["VoltageCaps"] ?? 0;
CpuInformation.CurrentClockSpeed = (uint?)cpu["CurrentClockSpeed"] ?? 0;
CpuInformation.Name =
CpuInformation.Name
.Replace("(TM)", "™")
.Replace("(tm)", "™")
.Replace("(R)", "®")
.Replace("(r)", "®")
.Replace("(C)", "©")
.Replace("(c)", "©")
.Replace(" ", " ")
.Replace(" ", " ");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
private static long ConvertKilobytesToBytes(long kilobytes)
{
return kilobytes*1024;
}
private static long GetAvailablePhysicalMemory()
{
var winQuery = new ObjectQuery("SELECT * FROM CIM_OperatingSystem");
var searcher = new ManagementObjectSearcher(winQuery);
foreach (var o in searcher.Get())
{
var item = (ManagementObject) o;
return ConvertKilobytesToBytes(long.Parse(item["FreePhysicalMemory"].ToString()));
}
return -1;
}
private async void Updater()
{
while (true)
{
try
{
SystemInformation.AvailableMemory = GetAvailablePhysicalMemory();
SystemInformation.Drives = GetDriveInformation();
SystemInformation.UsedMemory = GetUsedMemory();
SystemInformation.TotalMemory = GetTotalPhysicalMemory();
SystemInformation.RunningProcesses = GetTotalProcesses();
SystemInformation.UpTime = GetUpTime().TotalMilliseconds;
SystemInformation.NetworkInfo = GetNetworkInfo();
SystemInformation.CpuUsage = GetPerformanceCounters();
SystemInformation.CpuTemps = GetCpuTemps();
SystemInformation.Displays = GetDisplayInformation();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
Console.WriteLine(ex.Message);
}
await Task.Delay(new TimeSpan(0, 0, 10));
}
}
private List<DisplayInformation> GetDisplayInformation()
{
var displays = new List<DisplayInformation>();
for (var i = 0; i < Screen.AllScreens.Length; i++)
{
var friendly = Display.GetDeviceFriendlyName(i);
var display = new DisplayInformation {FriendlyName = friendly};
var currentScreen = Screen.AllScreens[i];
display.CurrentResolution = new ResolutionInformation
{
BitsPerPixel = currentScreen.BitsPerPixel,
Frequency = 60,
Height = currentScreen.Bounds.Height,
Width = currentScreen.Bounds.Width,
Orientation = "Unknown",
X = currentScreen.Bounds.X,
Y = currentScreen.Bounds.Y
};
displays.Add(display);
}
return displays;
}
private List<float> GetCpuTemps()
{
return SystemData.GetCpuTemps();
}
public string GetMotherBoard()
{
if (!string.IsNullOrEmpty(_motherBoard)) return _motherBoard;
var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BaseBoard");
foreach (var wmi in searcher.Get())
{
try
{
_motherBoard = wmi.GetPropertyValue("Product").ToString();
return _motherBoard;
}
catch
{
_motherBoard = "Board Unknown";
}
}
return string.IsNullOrEmpty(_motherBoard) ? "Board Unknown" : _motherBoard;
}
private static object GetNetworkInfo()
{
long totalBytesReceived = 0;
long totalBytesSent = 0;
foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
totalBytesReceived += networkInterface?.GetIPv4Statistics()?.BytesReceived ?? 0;
totalBytesSent += networkInterface?.GetIPv4Statistics()?.BytesSent ?? 0;
}
var data = new
{
totalNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces()?.Length ?? 0,
networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(),
totalBytesReceived,
totalBytesSent
};
return data;
}
public string GetCdRom()
{
if (!string.IsNullOrEmpty(_cdRom)) return _cdRom;
var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_CDROMDrive");
foreach (var wmi in searcher.Get())
{
try
{
_cdRom = wmi.GetPropertyValue("Drive").ToString();
return _cdRom;
}
catch
{
_cdRom = "CD ROM Unknown";
}
}
return _cdRom;
}
private object GetBiosInfo()
{
var data = new
{
biosManufacturer = GetBiosManufacturer(),
biosSerial = GetBiosSerial(),
biosCaption = GetBiosCaption()
};
return data;
}
private string GetBiosSerial()
{
if (!string.IsNullOrEmpty(_biosSerial)) return _biosSerial;
var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS");
foreach (var wmi in searcher.Get().Cast<ManagementObject>())
{
try
{
_biosSerial = wmi.GetPropertyValue("SerialNumber").ToString();
return _biosSerial;
}
catch
{
_biosSerial = "Unknown BIOS Serial";
}
}
return _biosSerial;
}
private string GetBiosCaption()
{
if (!string.IsNullOrEmpty(_biosCaption)) return _biosCaption;
var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS");
foreach (var wmi in searcher.Get())
{
try
{
_biosCaption = wmi.GetPropertyValue("Caption").ToString();
return _biosCaption;
}
catch
{
_biosCaption = "Unknown BIOS Caption";
}
}
return _biosCaption;
}
private string GetBiosManufacturer()
{
if (!string.IsNullOrEmpty(_biosManufacturer)) return _biosManufacturer;
var searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS");
foreach (var wmi in searcher.Get())
{
try
{
_biosManufacturer = wmi.GetPropertyValue("Manufacturer").ToString();
return _biosManufacturer;
}
catch
{
_biosManufacturer = "BIOS Manufacturer Unknown";
}
}
return _biosManufacturer;
}
private static long GetUsedMemory()
{
return GetTotalPhysicalMemory() - GetAvailablePhysicalMemory();
}
private static long GetTotalPhysicalMemory()
{
var winQuery = new ObjectQuery("SELECT * FROM CIM_OperatingSystem");
var searcher = new ManagementObjectSearcher(winQuery);
foreach (var o in searcher.Get())
{
var item = (ManagementObject) o;
return ConvertKilobytesToBytes(long.Parse(item["TotalVisibleMemorySize"].ToString()));
}
return -1;
}
private static int GetTotalProcesses()
{
return Process.GetProcesses().Length;
}
private static TimeSpan GetUpTime()
{
return TimeSpan.FromMilliseconds(GetTickCount64());
}
private static bool IsRunningAsAdministrator()
{
return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
}
//Everyday We Stray Further From God's Light
//If you enjoy your computer eating GB's of ram
//If you enjoy timeouts
//When you give up trying to optimize this
//Call me maybe.
public static Dictionary<string, List<EventLogEntry>> GetEventLogs()
{
var dictionary = new Dictionary<string, List<EventLogEntry>>();
var d = EventLog.GetEventLogs();
foreach (var l in d)
{
var categoryName = l.LogDisplayName;
if (!dictionary.ContainsKey(categoryName))
dictionary.Add(categoryName, new List<EventLogEntry>());
foreach (EventLogEntry entry in l.Entries)
{
dictionary[categoryName].Add(entry);
}
}
return dictionary;
}
public List<DriveInformation> GetDriveInformation()
{
var q = new WqlObjectQuery("SELECT * FROM Win32_DiskDrive");
var res = new ManagementObjectSearcher(q);
var driveNames = (from ManagementBaseObject o in res.Get() select o["Model"]?.ToString()).ToList();
var driveList = new List<DriveInformation>();
var drives = DriveInfo.GetDrives();
for (var index = 0; index < drives.Length; index++)
{
try
{
var drive = drives[index];
var driveInfo = new DriveInformation();
if (!drive.IsReady) continue;
driveInfo.Model = driveNames.ElementAtOrDefault(index) != null ? driveNames[index] : "Unknown Model";
driveInfo.Name = drive.Name;
driveInfo.FreeSpace = drive.TotalFreeSpace;
driveInfo.TotalSize = drive.TotalSize;
driveInfo.DriveType = drive.DriveType.ToString();
driveInfo.DriveFormat = drive.DriveFormat;
driveInfo.VolumeLabel = drive.VolumeLabel;
driveInfo.RootDirectory = drive.RootDirectory.ToString();
driveInfo.IsReady = drive.IsReady;
//just set it for now
driveInfo.SmartData = new List<SmartModel>();
driveInfo.Partitions = new List<PartitionModel>();
driveList.Add(driveInfo);
try
{
var mosDisks =
new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" +
driveInfo.Model + "'").Get().GetEnumerator();
if (!mosDisks.MoveNext()) continue;
driveInfo.MediaType = mosDisks.Current.GetPropertyValue("MediaType")?.ToString() ?? "Unknown";
driveInfo.Serial = mosDisks.Current.GetPropertyValue("SerialNumber")?.ToString()?.Trim() ??
"Unknown";
driveInfo.Interface = mosDisks.Current.GetPropertyValue("InterfaceType")?.ToString() ??
"Unknown";
driveInfo.TotalPartitions = mosDisks.Current.GetPropertyValue("Partitions")?.ToString() ??
"Unknown";
driveInfo.Signature = mosDisks.Current.GetPropertyValue("Signature")?.ToString() ?? "Unknown";
driveInfo.Firmware = mosDisks.Current.GetPropertyValue("FirmwareRevision")?.ToString() ??
"Unknown";
driveInfo.Cylinders = mosDisks.Current.GetPropertyValue("TotalCylinders")?.ToString() ??
"Unknown";
driveInfo.Sectors = mosDisks.Current.GetPropertyValue("TotalSectors")?.ToString() ?? "Unknown";
driveInfo.Heads = mosDisks.Current.GetPropertyValue("TotalHeads")?.ToString() ?? "Unknown";
driveInfo.Tracks = mosDisks.Current.GetPropertyValue("TotalTracks")?.ToString() ?? "Unknown";
driveInfo.BytesPerSecond = mosDisks.Current.GetPropertyValue("BytesPerSector")?.ToString() ??
"Unknown";
driveInfo.SectorsPerTrack = mosDisks.Current.GetPropertyValue("SectorsPerTrack")?.ToString() ??
"Unknown";
driveInfo.TracksPerCylinder =
mosDisks.Current.GetPropertyValue("TracksPerCylinder")?.ToString() ?? "Unknown";
}
catch (Exception ex)
{
// Console.WriteLine(ex.Message);
//Console.WriteLine(ex.StackTrace);
}
try
{
var mosPartition =
new ManagementObjectSearcher("SELECT * FROM Win32_DiskPartition WHERE DiskIndex = '" +
index + "'").Get().GetEnumerator();
while (mosPartition.MoveNext())
{
var partion = new PartitionModel
{
Name = mosPartition.Current.GetPropertyValue("Name")?.ToString() ?? "Unknown",
Size = mosPartition.Current.GetPropertyValue("Size")?.ToString() ?? "Unknown",
BlockSize = mosPartition.Current.GetPropertyValue("BlockSize")?.ToString() ?? "Unknown",
StartingOffset =
mosPartition.Current.GetPropertyValue("StartingOffset")?.ToString() ?? "Unknown",
Index = mosPartition.Current.GetPropertyValue("Index")?.ToString() ?? "Unknown",
DiskIndex = mosPartition.Current.GetPropertyValue("DiskIndex")?.ToString() ?? "Unknown",
BootPartition =
mosPartition.Current.GetPropertyValue("BootPartition")?.ToString() ?? "Unknown",
PrimaryPartition =
mosPartition.Current.GetPropertyValue("PrimaryPartition")?.ToString() ?? "Unknown",
Bootable = mosPartition.Current.GetPropertyValue("Bootable")?.ToString() ?? "Unknown"
};
driveInfo.Partitions.Add(partion);
}
}
catch (Exception ex)
{
// Console.WriteLine(ex.Message);
//Console.WriteLine(ex.StackTrace);
}
}
catch (Exception ex)
{
// Console.WriteLine(ex.Message);
// Console.WriteLine(ex.StackTrace);
}
}
using (
var searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_ATAPISmartData")
)
using (
var thresSearcher = new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM MSStorageDriver_FailurePredictThresholds"))
using (
var failureSearch = new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM MSStorageDriver_FailurePredictStatus"))
{
try
{
var searcherEnumerator = searcher.Get().GetEnumerator();
var thresSearcherEnumerator = thresSearcher.Get().GetEnumerator();
var failureSearchEnumerator = failureSearch.Get().GetEnumerator();
var index = 0;
while (searcherEnumerator.MoveNext() && thresSearcherEnumerator.MoveNext())
{
var arrVendorSpecific = (byte[]) searcherEnumerator.Current.GetPropertyValue("VendorSpecific");
var arrThreshold = (byte[]) thresSearcherEnumerator.Current.GetPropertyValue("VendorSpecific");
/* Create SMART data from 'vendor specific' array */
var d = new SmartData(arrVendorSpecific, arrThreshold);
var smartRows = (from b in d.Attributes
where !Regex.IsMatch(b.AttributeType.ToString(), @"^\d+$")
let rawData =
BitConverter.ToString(b.VendorData.Reverse().ToArray()).Replace("-", string.Empty)
select
new SmartModel(b.AttributeType.ToString(),
b.Value.ToString(CultureInfo.InvariantCulture),
b.Threshold.ToString(CultureInfo.InvariantCulture), rawData,
long.Parse(rawData, NumberStyles.HexNumber).ToString(CultureInfo.InvariantCulture)))
.ToList();
driveList.ElementAt(index).SmartData = smartRows;
if (failureSearchEnumerator.MoveNext())
{
driveList.ElementAt(index).DriveHealth =
(bool) failureSearchEnumerator.Current.GetPropertyValue("PredictFailure")
? "WARNING"
: "OK";
}
index++;
}
}
catch (Exception ex)
{
// Console.WriteLine(ex.Message);
// Console.WriteLine(ex.StackTrace);
}
}
return driveList;
}
public List<float> GetPerformanceCounters()
{
var performanceCounters = new List<float>();
var procCount = Environment.ProcessorCount;
for (var i = 0; i < procCount; i++)
{
var pc = new PerformanceCounter("Processor", "% Processor Time", i.ToString());
pc.NextValue();
Thread.Sleep(1000);
// now matches task manager reading
dynamic secondValue = pc.NextValue();
performanceCounters.Add(secondValue);
}
return performanceCounters;
}
[DllImport("kernel32")]
private static extern ulong GetTickCount64();
}
}
|
StrikeOrg/ulterius-server
|
RemoteTaskServer/Api/Services/LocalSystem/SystemService.cs
|
C#
|
gpl-2.0
| 25,143 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.motorola.studio.android.generateviewbylayout.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import com.motorola.studio.android.codeutils.CodeUtilsActivator;
import com.motorola.studio.android.codeutils.i18n.CodeUtilsNLS;
import com.motorola.studio.android.generateviewbylayout.codegenerators.SaveStateCodeGenerator;
import com.motorola.studio.android.generateviewbylayout.model.LayoutNode;
/**
* GUI to enable selection of which Android items
* will be inserted into activity or fragment
*/
public class ChooseLayoutItemsDialog extends AbstractLayoutItemsDialog
{
private final String DIALOG_HELP = CodeUtilsActivator.PLUGIN_ID
+ ".generate-code-from-layout-dialog"; //$NON-NLS-1$
private Button generateListeners;
private boolean hasGuiItemsWithoutId = false;
private final Map<TableItem, TableEditor> itemToEditorMap;
private static final String WIZARD_IMAGE_PATH = "icons/wizban/fill_activity_ban.png"; //$NON-NLS-1$
public ChooseLayoutItemsDialog(Shell parentShell)
{
super(parentShell, CodeUtilsNLS.ChooseLayoutItemsDialog_DefaultMessage,
CodeUtilsNLS.UI_ChooseLayoutItemsDialog_Dialog_Title,
CodeUtilsNLS.ChooseLayoutItemsDialog_FillActivityBasedOnLayout, CodeUtilsActivator
.getImageDescriptor(WIZARD_IMAGE_PATH).createImage());
setHelpID(DIALOG_HELP);
itemToEditorMap = new HashMap<TableItem, TableEditor>();
}
@Override
protected void createCustomContentArea(Composite parent)
{
Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
separator.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 2, 1));
createCheckboxArea(parent);
}
@Override
protected void createColumns(TableViewer viewer)
{
super.createColumns(viewer);
TableViewerColumn column =
createTableViewerColumn(viewer, CodeUtilsNLS.ChooseLayoutItemsDialog_SaveState, 80,
3);
column.setLabelProvider(new ColumnLabelProvider()
{
@Override
public String getText(Object element)
{
return null;
}
});
column.getColumn().setToolTipText(CodeUtilsNLS.ChooseLayoutItemsDialog_SaveStateTooltip);
}
@Override
protected void populateViewer()
{
super.populateViewer();
populateSaveStateColumn();
}
private void populateSaveStateColumn()
{
if (getViewer() != null)
{
itemToEditorMap.clear();
for (final TableItem item : getViewer().getTable().getItems())
{
LayoutNode node = (LayoutNode) item.getData();
if (SaveStateCodeGenerator.canGenerateSaveStateCode(node))
{
final TableEditor editor = new TableEditor(getViewer().getTable());
editor.setColumn(3);
editor.horizontalAlignment = SWT.CENTER;
editor.grabHorizontal = false;
editor.minimumWidth =
getViewer().getTable().getColumn(3).getWidth() < 20 ? getViewer()
.getTable().getColumn(3).getWidth() : 20;
getViewer().getTable().getColumn(3).addControlListener(new ControlAdapter()
{
@Override
public void controlResized(ControlEvent e)
{
editor.minimumWidth =
getViewer().getTable().getColumn(3).getWidth() < 20
? getViewer().getTable().getColumn(3).getWidth() : 20;
}
});
final Button checkbox = new Button(getViewer().getTable(), SWT.CHECK);
checkbox.setEnabled(false);
checkbox.pack();
final SelectionListener listener = new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent e)
{
if ((e.detail & SWT.CHECK) != 0)
{
if ((e.item instanceof TableItem) && (editor.getItem() == e.item))
{
checkbox.setEnabled(((TableItem) e.item).getChecked());
}
}
}
};
checkbox.setSelection(node.getSaveState());
getViewer().getTable().addSelectionListener(listener);
checkbox.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent e)
{
LayoutNode node = (LayoutNode) editor.getItem().getData();
node.setSaveState(checkbox.getSelection());
}
});
editor.setEditor(checkbox, item, 3);
item.addDisposeListener(new DisposeListener()
{
public void widgetDisposed(DisposeEvent e)
{
getViewer().getTable().removeSelectionListener(listener);
editor.getEditor().dispose();
editor.dispose();
}
});
itemToEditorMap.put(item, editor);
}
}
}
}
@Override
protected void itemCheckStateChanged(TableItem item)
{
super.itemCheckStateChanged(item);
if (itemToEditorMap.get(item) != null)
{
((Button) itemToEditorMap.get(item).getEditor()).setEnabled(item.getChecked());
}
}
@Override
protected List<LayoutNode> getGuiItemsList()
{
List<LayoutNode> completeGuiItemsList = getCodeGeneratorData().getGUIItemsForUI();
List<LayoutNode> processedGuiItemsList = new ArrayList<LayoutNode>();
hasGuiItemsWithoutId = false;
for (LayoutNode guiItem : completeGuiItemsList)
{
if ((guiItem.getNodeId() != null) && (guiItem.getNodeId().length() > 0))
{
processedGuiItemsList.add(guiItem);
}
else
{
hasGuiItemsWithoutId = true;
}
}
return processedGuiItemsList;
}
/* (non-Javadoc)
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
@Override
protected void configureShell(Shell newShell)
{
newShell.setSize(640, 480);
super.configureShell(newShell);
}
/**
* Creates GUI items for choosing whether code for listeners should be auto-generated.
* @param optionsComposite
*/
private void createCheckboxArea(Composite parent)
{
generateListeners = new Button(parent, SWT.CHECK);
generateListeners.setText(CodeUtilsNLS.ChooseLayoutItemsDialog_GenerateDefaultListeners);
generateListeners.setSelection(true);
generateListeners.setLayoutData(new GridData(SWT.LEFT, SWT.BOTTOM, false, false, 2, 1));
}
/**
* Handles the enablement of the Ok button.
* It will only be enabled when at least one table item is checked.
*/
@Override
protected void validate()
{
super.validate();
if ((getViewer() != null) && (getErrorMessage() == null))
{
// set the appropriate message
String message = ""; //$NON-NLS-1$
int messageType = IMessageProvider.NONE;
//check if at least one table item was selected
for (TableItem item : getViewer().getTable().getItems())
{
LayoutNode node = (LayoutNode) item.getData();
if (item.getChecked()
&& (getCodeGeneratorData() != null)
&& getCodeGeneratorData().getJavaLayoutData().getVisitor()
.checkIfAttributeAlreadyDeclared(node, true))
{
message =
NLS.bind(CodeUtilsNLS.ChooseLayoutItemsDialog_VariableNameInUse_Error,
node.getNodeId());
messageType = IMessageProvider.ERROR;
break;
}
}
if (messageType == IMessageProvider.NONE)
{
if (getViewer().getTable().getItemCount() == 0)
{
message = CodeUtilsNLS.UI_ChooseLayoutItemsDialog_No_Gui_Items_Available;
messageType = IMessageProvider.INFORMATION;
}
else if (hasGuiItemsWithoutId)
{
message = CodeUtilsNLS.ChooseLayoutItemsDialog_Gui_Items_Available_No_Id;
messageType = IMessageProvider.INFORMATION;
}
else
{
message = CodeUtilsNLS.ChooseLayoutItemsDialog_DefaultMessage;
}
}
this.setMessage(message, messageType);
}
}
/**
* Each table item refers to a LayoutNode object.
* When user press Ok, the insertCode status of these objects are set accordingly to table selections.
*/
@Override
protected void okPressed()
{
//set the insertCode for each layoutNode accordingly
for (TableItem item : getViewer().getTable().getItems())
{
if (item.getData() instanceof LayoutNode)
{
LayoutNode node = (LayoutNode) item.getData();
node.setInsertCode(item.getChecked());
}
}
getModifier().setGenerateDefaultListeners(generateListeners.getSelection());
getModifier().setCodeGeneratorData(getCodeGeneratorData());
super.okPressed();
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus()
{
getViewer().getControl().setFocus();
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#isResizable()
*/
@Override
protected boolean isResizable()
{
return true;
}
}
|
DmitryADP/diff_qc750
|
tools/motodev/src/plugins/android.codeutils/src/com/motorola/studio/android/generateviewbylayout/ui/ChooseLayoutItemsDialog.java
|
Java
|
gpl-2.0
| 12,537 |
function passwordStrength(password1, username, password2) {
if (password1 != password2 && password2.length > 0)
return 5;
var result = zxcvbn( password1, [ username ] );
return result.score;
}
|
WebCampZg/2013
|
wp-admin/js/password-strength-meter.js
|
JavaScript
|
gpl-2.0
| 198 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>bazar: Class Members</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.6 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="classes.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="dirs.html"><span>Directories</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="files.html"><span>File List</span></a></li>
<li class="current"><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="globals.html"><span>All</span></a></li>
<li class="current"><a href="globals_func.html"><span>Functions</span></a></li>
<li><a href="globals_vars.html"><span>Variables</span></a></li>
<li><a href="globals_type.html"><span>Typedefs</span></a></li>
<li><a href="globals_eval.html"><span>Enumerator</span></a></li>
<li><a href="globals_defs.html"><span>Defines</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="globals_func.html#index_a"><span>a</span></a></li>
<li><a href="globals_func_0x63.html#index_c"><span>c</span></a></li>
<li><a href="globals_func_0x64.html#index_d"><span>d</span></a></li>
<li><a href="globals_func_0x65.html#index_e"><span>e</span></a></li>
<li><a href="globals_func_0x66.html#index_f"><span>f</span></a></li>
<li><a href="globals_func_0x67.html#index_g"><span>g</span></a></li>
<li class="current"><a href="globals_func_0x68.html#index_h"><span>h</span></a></li>
<li><a href="globals_func_0x69.html#index_i"><span>i</span></a></li>
<li><a href="globals_func_0x6b.html#index_k"><span>k</span></a></li>
<li><a href="globals_func_0x6c.html#index_l"><span>l</span></a></li>
<li><a href="globals_func_0x6d.html#index_m"><span>m</span></a></li>
<li><a href="globals_func_0x6e.html#index_n"><span>n</span></a></li>
<li><a href="globals_func_0x6f.html#index_o"><span>o</span></a></li>
<li><a href="globals_func_0x70.html#index_p"><span>p</span></a></li>
<li><a href="globals_func_0x72.html#index_r"><span>r</span></a></li>
<li><a href="globals_func_0x73.html#index_s"><span>s</span></a></li>
<li><a href="globals_func_0x74.html#index_t"><span>t</span></a></li>
<li><a href="globals_func_0x75.html#index_u"><span>u</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<p>
<h3><a class="anchor" name="index_h">- h -</a></h3><ul>
<li>homography_error()
: <a class="el" href="planar__object__recognizer_8cpp.html#6ab369d9ed14b3577638db7d772fb1f3">planar_object_recognizer.cpp</a>
</ul>
</div>
<hr size="1"><address style="text-align: right;"><small>Generated on Mon Aug 17 16:17:36 2009 for bazar by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.6 </small></address>
</body>
</html>
|
TheArtvertiser/TheArtvertiser
|
doc/doc/html/globals_func_0x68.html
|
HTML
|
gpl-2.0
| 3,439 |
/*
* Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.hotspot.nodes;
import org.graalvm.compiler.core.common.type.Stamp;
import org.graalvm.compiler.graph.NodeClass;
import org.graalvm.compiler.nodeinfo.NodeInfo;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.extended.GuardingNode;
import org.graalvm.compiler.nodes.java.LoadIndexedNode;
import jdk.vm.ci.meta.JavaKind;
@NodeInfo
public final class LoadIndexedPointerNode extends LoadIndexedNode {
public static final NodeClass<LoadIndexedPointerNode> TYPE = NodeClass.create(LoadIndexedPointerNode.class);
public LoadIndexedPointerNode(Stamp stamp, ValueNode array, ValueNode index, GuardingNode boundsCheck) {
super(TYPE, stamp, array, index, boundsCheck, JavaKind.Illegal);
}
@Override
public boolean inferStamp() {
return false;
}
}
|
md-5/jdk10
|
src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/nodes/LoadIndexedPointerNode.java
|
Java
|
gpl-2.0
| 1,900 |
/* $OpenBSD: exec_subr.c,v 1.25 2003/05/09 00:48:42 art Exp $ */
/* $NetBSD: exec_subr.c,v 1.9 1994/12/04 03:10:42 mycroft Exp $ */
/*
* Copyright (c) 1993, 1994 Christopher G. Demetriou
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Christopher G. Demetriou.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/malloc.h>
#include <sys/vnode.h>
#include <sys/filedesc.h>
#include <sys/exec.h>
#include <sys/mman.h>
#include <sys/resourcevar.h>
#include <uvm/uvm.h>
#ifdef DEBUG
/*
* new_vmcmd():
* create a new vmcmd structure and fill in its fields based
* on function call arguments. make sure objects ref'd by
* the vmcmd are 'held'.
*
* If not debugging, this is a macro, so it's expanded inline.
*/
void
new_vmcmd(evsp, proc, len, addr, vp, offset, prot, flags)
struct exec_vmcmd_set *evsp;
int (*proc)(struct proc * p, struct exec_vmcmd *);
u_long len;
u_long addr;
struct vnode *vp;
u_long offset;
u_int prot;
int flags;
{
struct exec_vmcmd *vcp;
if (evsp->evs_used >= evsp->evs_cnt)
vmcmdset_extend(evsp);
vcp = &evsp->evs_cmds[evsp->evs_used++];
vcp->ev_proc = proc;
vcp->ev_len = len;
vcp->ev_addr = addr;
if ((vcp->ev_vp = vp) != NULL)
vref(vp);
vcp->ev_offset = offset;
vcp->ev_prot = prot;
vcp->ev_flags = flags;
}
#endif /* DEBUG */
void
vmcmdset_extend(evsp)
struct exec_vmcmd_set *evsp;
{
struct exec_vmcmd *nvcp;
u_int ocnt;
#ifdef DIAGNOSTIC
if (evsp->evs_used < evsp->evs_cnt)
panic("vmcmdset_extend: not necessary");
#endif
ocnt = evsp->evs_cnt;
KASSERT(ocnt > 0);
/* figure out number of entries in new set */
evsp->evs_cnt += ocnt;
/* reallocate the command set */
nvcp = malloc(evsp->evs_cnt * sizeof(struct exec_vmcmd), M_EXEC,
M_WAITOK);
bcopy(evsp->evs_cmds, nvcp, (ocnt * sizeof(struct exec_vmcmd)));
if (evsp->evs_cmds != evsp->evs_start)
free(evsp->evs_cmds, M_EXEC);
evsp->evs_cmds = nvcp;
}
void
kill_vmcmds(struct exec_vmcmd_set *evsp)
{
struct exec_vmcmd *vcp;
int i;
for (i = 0; i < evsp->evs_used; i++) {
vcp = &evsp->evs_cmds[i];
if (vcp->ev_vp != NULLVP)
vrele(vcp->ev_vp);
}
/*
* Free old vmcmds and restet the array.
*/
evsp->evs_used = 0;
if (evsp->evs_cmds != evsp->evs_start)
free(evsp->evs_cmds, M_EXEC);
evsp->evs_cmds = evsp->evs_start;
evsp->evs_cnt = EXEC_DEFAULT_VMCMD_SETSIZE;
}
int
exec_process_vmcmds(struct proc *p, struct exec_package *epp)
{
struct exec_vmcmd *base_vc = NULL;
int error = 0;
int i;
for (i = 0; i < epp->ep_vmcmds.evs_used && !error; i++) {
struct exec_vmcmd *vcp;
vcp = &epp->ep_vmcmds.evs_cmds[i];
if (vcp->ev_flags & VMCMD_RELATIVE) {
#ifdef DIAGNOSTIC
if (base_vc == NULL)
panic("exec_process_vmcmds: RELATIVE no base");
#endif
vcp->ev_addr += base_vc->ev_addr;
}
error = (*vcp->ev_proc)(p, vcp);
if (vcp->ev_flags & VMCMD_BASE) {
base_vc = vcp;
}
}
kill_vmcmds(&epp->ep_vmcmds);
return (error);
}
/*
* vmcmd_map_pagedvn():
* handle vmcmd which specifies that a vnode should be mmap'd.
* appropriate for handling demand-paged text and data segments.
*/
int
vmcmd_map_pagedvn(p, cmd)
struct proc *p;
struct exec_vmcmd *cmd;
{
/*
* note that if you're going to map part of an process as being
* paged from a vnode, that vnode had damn well better be marked as
* VTEXT. that's handled in the routine which sets up the vmcmd to
* call this routine.
*/
struct uvm_object *uobj;
int error;
/*
* map the vnode in using uvm_map.
*/
if (cmd->ev_len == 0)
return(0);
if (cmd->ev_offset & PAGE_MASK)
return(EINVAL);
if (cmd->ev_addr & PAGE_MASK)
return(EINVAL);
if (cmd->ev_len & PAGE_MASK)
return(EINVAL);
/*
* first, attach to the object
*/
uobj = uvn_attach((void *) cmd->ev_vp, VM_PROT_READ|VM_PROT_EXECUTE);
if (uobj == NULL)
return(ENOMEM);
/*
* do the map
*/
error = uvm_map(&p->p_vmspace->vm_map, &cmd->ev_addr, cmd->ev_len,
uobj, cmd->ev_offset, 0,
UVM_MAPFLAG(cmd->ev_prot, VM_PROT_ALL, UVM_INH_COPY,
UVM_ADV_NORMAL, UVM_FLAG_COPYONW|UVM_FLAG_FIXED));
/*
* check for error
*/
if (error) {
/*
* error: detach from object
*/
uobj->pgops->pgo_detach(uobj);
}
return (error);
}
/*
* vmcmd_map_readvn():
* handle vmcmd which specifies that a vnode should be read from.
* appropriate for non-demand-paged text/data segments, i.e. impure
* objects (a la OMAGIC and NMAGIC).
*/
int
vmcmd_map_readvn(struct proc *p, struct exec_vmcmd *cmd)
{
int error;
vm_prot_t prot;
if (cmd->ev_len == 0)
return (0);
prot = cmd->ev_prot;
cmd->ev_addr = trunc_page(cmd->ev_addr); /* required by uvm_map */
error = uvm_map(&p->p_vmspace->vm_map, &cmd->ev_addr,
round_page(cmd->ev_len), NULL, UVM_UNKNOWN_OFFSET, 0,
UVM_MAPFLAG(prot | UVM_PROT_WRITE, UVM_PROT_ALL, UVM_INH_COPY,
UVM_ADV_NORMAL,
UVM_FLAG_FIXED|UVM_FLAG_OVERLAY|UVM_FLAG_COPYONW));
if (error)
return (error);
error = vn_rdwr(UIO_READ, cmd->ev_vp, (caddr_t)cmd->ev_addr,
cmd->ev_len, cmd->ev_offset, UIO_USERSPACE, IO_UNIT|IO_NODELOCKED,
p->p_ucred, NULL, p);
if (error)
return (error);
if (cmd->ev_prot != (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)) {
/*
* we had to map in the area at PROT_ALL so that vn_rdwr()
* could write to it. however, the caller seems to want
* it mapped read-only, so now we are going to have to call
* uvm_map_protect() to fix up the protection. ICK.
*/
return (uvm_map_protect(&p->p_vmspace->vm_map,
trunc_page(cmd->ev_addr),
round_page(cmd->ev_addr + cmd->ev_len),
prot, FALSE));
}
return (0);
}
/*
* vmcmd_map_zero():
* handle vmcmd which specifies a zero-filled address space region. The
* address range must be first allocated, then protected appropriately.
*/
int
vmcmd_map_zero(p, cmd)
struct proc *p;
struct exec_vmcmd *cmd;
{
int error;
if (cmd->ev_len == 0)
return (0);
cmd->ev_addr = trunc_page(cmd->ev_addr); /* required by uvm_map */
error = uvm_map(&p->p_vmspace->vm_map, &cmd->ev_addr,
round_page(cmd->ev_len), NULL, UVM_UNKNOWN_OFFSET, 0,
UVM_MAPFLAG(cmd->ev_prot, UVM_PROT_ALL, UVM_INH_COPY,
UVM_ADV_NORMAL, UVM_FLAG_FIXED|UVM_FLAG_COPYONW));
if (error)
return error;
return (0);
}
/*
* exec_setup_stack(): Set up the stack segment for an a.out
* executable.
*
* Note that the ep_ssize parameter must be set to be the current stack
* limit; this is adjusted in the body of execve() to yield the
* appropriate stack segment usage once the argument length is
* calculated.
*
* This function returns an int for uniformity with other (future) formats'
* stack setup functions. They might have errors to return.
*/
int
exec_setup_stack(p, epp)
struct proc *p;
struct exec_package *epp;
{
#ifdef MACHINE_STACK_GROWS_UP
epp->ep_maxsaddr = USRSTACK;
epp->ep_minsaddr = USRSTACK + MAXSSIZ;
#else
epp->ep_maxsaddr = USRSTACK - MAXSSIZ;
epp->ep_minsaddr = USRSTACK;
#endif
epp->ep_ssize = round_page(p->p_rlimit[RLIMIT_STACK].rlim_cur);
/*
* set up commands for stack. note that this takes *two*, one to
* map the part of the stack which we can access, and one to map
* the part which we can't.
*
* arguably, it could be made into one, but that would require the
* addition of another mapping proc, which is unnecessary
*
* note that in memory, things assumed to be: 0 ....... ep_maxsaddr
* <stack> ep_minsaddr
*/
#ifdef MACHINE_STACK_GROWS_UP
NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_zero,
((epp->ep_minsaddr - epp->ep_ssize) - epp->ep_maxsaddr),
epp->ep_maxsaddr + epp->ep_ssize, NULLVP, 0, VM_PROT_NONE);
NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_zero, epp->ep_ssize,
epp->ep_maxsaddr, NULLVP, 0,
VM_PROT_READ|VM_PROT_WRITE);
#else
NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_zero,
((epp->ep_minsaddr - epp->ep_ssize) - epp->ep_maxsaddr),
epp->ep_maxsaddr, NULLVP, 0, VM_PROT_NONE);
NEW_VMCMD(&epp->ep_vmcmds, vmcmd_map_zero, epp->ep_ssize,
(epp->ep_minsaddr - epp->ep_ssize), NULLVP, 0,
VM_PROT_READ|VM_PROT_WRITE);
#endif
return 0;
}
|
binhqnguyen/lena
|
nsc/openbsd3/kern/exec_subr.c
|
C
|
gpl-2.0
| 9,618 |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'showblocks', 'de', {
toolbar: 'Blöcke anzeigen'
} );
|
SeeyaSia/www
|
web/libraries/ckeditor/plugins/showblocks/lang/de.js
|
JavaScript
|
gpl-2.0
| 225 |
// 2001-05-21 Benjamin Kosnik <[email protected]>
// Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
// 27.8.1.4 Overridden virtual functions
#include <fstream>
#include <testsuite_hooks.h>
#include <testsuite_io.h>
// @require@ %-*.tst %-*.txt
// @diff@ %-*.tst %*.txt
const char name_01[] = "tmp_sputbackc_1io.tst"; // empty file, need to create
void test01()
{
using namespace std;
using namespace __gnu_test;
typedef filebuf::int_type int_type;
typedef filebuf::traits_type traits_type;
typedef size_t size_type;
bool test __attribute__((unused)) = true;
streamsize strmsz_1, strmsz_2;
int_type c1, c2, c3;
// int_type sputbackc(char_type c)
// if in_cur not avail || ! traits::eq(c, gptr() [-1]), return pbfail
// otherwise decrements in_cur and returns *gptr()
// in | out
{
constraint_filebuf fb_01;
fb_01.open(name_01, ios_base::out | ios_base::in | ios_base::trunc);
VERIFY( !fb_01.write_position() );
VERIFY( !fb_01.read_position() );
strmsz_1 = fb_01.sputn("racadabras", 10);//"abracadabras or what?"
strmsz_2 = fb_01.sputn(", i wanna reach out and", 10);
fb_01.pubseekoff(0, std::ios_base::cur);
c1 = fb_01.sgetc(); // -1
c2 = fb_01.sputbackc('z');
strmsz_2 = fb_01.in_avail();
c3 = fb_01.sgetc();
VERIFY( c3 == c2 );
VERIFY( c1 != c3 );
VERIFY( 1 == strmsz_2 );
//test for _in_cur == _in_beg
// fb_01._M_out_beg = "bd23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZracada" etc
fb_01.pubseekoff(10, std::ios_base::beg);
fb_01.sputc('m');
fb_01.pubseekoff(0, std::ios_base::cur);
strmsz_1 = fb_01.in_avail();
c1 = fb_01.sgetc();
fb_01.snextc();
c2 = fb_01.sputbackc('z');
strmsz_2 = fb_01.in_avail();
c3 = fb_01.sgetc();
VERIFY( c1 != c2 );
VERIFY( c3 == c2 );
VERIFY( c1 != c3 );
VERIFY( c2 == 'z' );
// test for replacing char with identical one
fb_01.snextc();
fb_01.pubseekoff(0, std::ios_base::cur);
fb_01.sputc('u');
fb_01.sputc('v');
fb_01.sputc('a');
fb_01.pubseekoff(0, std::ios_base::end);
strmsz_1 = fb_01.in_avail();
c2 = fb_01.sputbackc('a');
strmsz_2 = fb_01.in_avail();
c3 = fb_01.sgetc();
VERIFY( c3 == c2 );
VERIFY( strmsz_1 + 1 == strmsz_2 );
VERIFY( !fb_01.write_position() );
VERIFY( fb_01.read_position() );
}
}
int main()
{
test01();
return 0;
}
|
unofficial-opensource-apple/gcc_40
|
libstdc++-v3/testsuite/27_io/basic_filebuf/sputbackc/char/1-io.cc
|
C++
|
gpl-2.0
| 3,193 |
/*
* Gadget Driver for Android
*
* Copyright (C) 2008 Google, Inc.
* Author: Mike Lockwood <[email protected]>
* Benoit Goby <[email protected]>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/utsname.h>
#include <linux/platform_device.h>
#include <linux/pm_qos.h>
#include <linux/of.h>
#include <linux/usb/ch9.h>
#include <linux/usb/composite.h>
#include <linux/usb/gadget.h>
#include <linux/usb/android.h>
#include <mach/diag_dload.h>
#include "gadget_chips.h"
#ifdef CONFIG_USB_G_LGE_ANDROID
#include <linux/platform_data/lge_android_usb.h>
#endif
#ifdef CONFIG_LGE_PM
#include <mach/restart.h>
#include <linux/reboot.h>
#include <mach/board_lge.h>
#endif
#ifdef CONFIG_USB_LGE_LPM_STATE
#include <linux/usb/msm_hsusb.h>
#endif
/*
* Kbuild is not very cooperative with respect to linking separately
* compiled library objects into one module. So for now we won't use
* separate compilation ... ensuring init/exit sections work to shrink
* the runtime footprint, and giving us at least some parts of what
* a "gcc --combine ... part1.c part2.c part3.c ... " build would.
*/
#include "usbstring.c"
#include "config.c"
#include "epautoconf.c"
#include "composite.c"
#include "f_diag.c"
#include "f_qdss.c"
#include "f_rmnet_smd.c"
#include "f_rmnet_sdio.c"
#include "f_rmnet_smd_sdio.c"
#include "f_rmnet.c"
#include "f_gps.c"
#ifdef CONFIG_SND_PCM
#include "f_audio_source.c"
#endif
#include "f_mass_storage.c"
#include "u_serial.c"
#include "u_sdio.c"
#include "u_smd.c"
#include "u_bam.c"
#include "u_rmnet_ctrl_smd.c"
#include "u_rmnet_ctrl_qti.c"
#include "u_ctrl_hsic.c"
#include "u_data_hsic.c"
#include "u_ctrl_hsuart.c"
#include "u_data_hsuart.c"
#include "f_serial.c"
#include "f_acm.c"
#include "f_adb.c"
#include "f_ccid.c"
#include "f_mtp.c"
#include "f_accessory.c"
#define USB_ETH_RNDIS y
#include "f_rndis.c"
#include "rndis.c"
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
#include "f_charge_only.c"
#endif
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
#include "f_qc_ecm.c"
#include "f_mbim.c"
#include "u_bam_data.c"
#endif
#include "f_ecm.c"
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
#include "f_qc_rndis.c"
#endif
#include "u_ether.c"
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
#include "u_qc_ether.c"
#endif
#ifdef CONFIG_TARGET_CORE
#include "f_tcm.c"
#endif
#ifdef CONFIG_SND_PCM
#include "u_uac1.c"
#include "f_uac1.c"
#endif
#include "f_ncm.c"
#include "f_laf.c"
MODULE_AUTHOR("Mike Lockwood");
MODULE_DESCRIPTION("Android Composite USB Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION("1.0");
static const char longname[] = "Gadget Android";
/* Default vendor and product IDs, overridden by userspace */
#define VENDOR_ID 0x18D1
#define PRODUCT_ID 0x0001
#define ANDROID_DEVICE_NODE_NAME_LENGTH 11
#if !defined(CONFIG_MACH_MSM8974_G2_KR) && !defined(CONFIG_MACH_MSM8974_VU3_KR) || (defined(CONFIG_MACH_MSM8974_Z_KR) || defined(CONFIG_MACH_MSM8974_Z_US) || defined(CONFIG_MACH_MSM8974_Z_KDDI) || defined(CONFIG_MACH_MSM8974_Z_OPEN_COM))
static int firstboot_check = 1;
#endif
struct android_usb_function {
char *name;
void *config;
struct device *dev;
char *dev_name;
struct device_attribute **attributes;
struct android_dev *android_dev;
/* Optional: initialization during gadget bind */
int (*init)(struct android_usb_function *, struct usb_composite_dev *);
/* Optional: cleanup during gadget unbind */
void (*cleanup)(struct android_usb_function *);
/* Optional: called when the function is added the list of
* enabled functions */
void (*enable)(struct android_usb_function *);
/* Optional: called when it is removed */
void (*disable)(struct android_usb_function *);
int (*bind_config)(struct android_usb_function *,
struct usb_configuration *);
/* Optional: called when the configuration is removed */
void (*unbind_config)(struct android_usb_function *,
struct usb_configuration *);
/* Optional: handle ctrl requests before the device is configured */
int (*ctrlrequest)(struct android_usb_function *,
struct usb_composite_dev *,
const struct usb_ctrlrequest *);
};
struct android_usb_function_holder {
struct android_usb_function *f;
/* for android_conf.enabled_functions */
struct list_head enabled_list;
};
/**
* struct android_dev - represents android USB gadget device
* @name: device name.
* @functions: an array of all the supported USB function
* drivers that this gadget support but not necessarily
* added to one of the gadget configurations.
* @cdev: The internal composite device. Android gadget device
* is a composite device, such that it can support configurations
* with more than one function driver.
* @dev: The kernel device that represents this android device.
* @enabled: True if the android gadget is enabled, means all
* the configurations were set and all function drivers were
* bind and ready for USB enumeration.
* @disable_depth: Number of times the device was disabled, after
* symmetrical number of enables the device willl be enabled.
* Used for controlling ADB userspace disable/enable requests.
* @mutex: Internal mutex for protecting device member fields.
* @pdata: Platform data fetched from the kernel device platfrom data.
* @connected: True if got connect notification from the gadget UDC.
* False if got disconnect notification from the gadget UDC.
* @sw_connected: Equal to 'connected' only after the connect
* notification was handled by the android gadget work function.
* @suspended: True if got suspend notification from the gadget UDC.
* False if got resume notification from the gadget UDC.
* @sw_suspended: Equal to 'suspended' only after the susped
* notification was handled by the android gadget work function.
* @pm_qos: An attribute string that can be set by user space in order to
* determine pm_qos policy. Set to 'high' for always demand pm_qos
* when USB bus is connected and resumed. Set to 'low' for disable
* any setting of pm_qos by this driver. Default = 'high'.
* @work: workqueue used for handling notifications from the gadget UDC.
* @configs: List of configurations currently configured into the device.
* The android gadget supports more than one configuration. The host
* may choose one configuration from the suggested.
* @configs_num: Number of configurations currently configured and existing
* in the configs list.
* @list_item: This driver supports more than one android gadget device (for
* example in order to support multiple USB cores), therefore this is
* a item in a linked list of android devices.
*/
struct android_dev {
const char *name;
struct android_usb_function **functions;
struct usb_composite_dev *cdev;
struct device *dev;
bool enabled;
int disable_depth;
struct mutex mutex;
struct android_usb_platform_data *pdata;
bool connected;
bool sw_connected;
bool suspended;
bool sw_suspended;
char pm_qos[5];
struct pm_qos_request pm_qos_req_dma;
struct work_struct work;
#if defined CONFIG_USB_G_LGE_ANDROID && defined CONFIG_LGE_PM
bool check_pif;
#endif
/* A list of struct android_configuration */
struct list_head configs;
int configs_num;
/* A list node inside the android_dev_list */
struct list_head list_item;
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
bool check_charge_only;
#endif
};
struct android_configuration {
struct usb_configuration usb_config;
/* A list of the functions supported by this config */
struct list_head enabled_functions;
/* A list node inside the struct android_dev.configs list */
struct list_head list_item;
};
struct dload_struct __iomem *diag_dload;
static struct class *android_class;
static struct list_head android_dev_list;
static int android_dev_count;
static int android_bind_config(struct usb_configuration *c);
static void android_unbind_config(struct usb_configuration *c);
static struct android_dev *cdev_to_android_dev(struct usb_composite_dev *cdev);
static struct android_configuration *alloc_android_config
(struct android_dev *dev);
static void free_android_config(struct android_dev *dev,
struct android_configuration *conf);
static int usb_diag_update_pid_and_serial_num(uint32_t pid, const char *snum);
#ifdef CONFIG_USB_LGE_REPOSITION_FACTORY_BIND
static void android_lge_factory_bind(struct usb_composite_dev *cdev);
#endif
#ifdef CONFIG_USB_LGE_LPM_STATE
extern void set_tri_state_lpm(enum tri_state_lpm_type lpm_type);
extern enum tri_state_lpm_type get_tri_state_lpm(void);
#endif
/* string IDs are assigned dynamically */
#define STRING_MANUFACTURER_IDX 0
#define STRING_PRODUCT_IDX 1
#define STRING_SERIAL_IDX 2
#ifdef CONFIG_USB_G_LGE_ANDROID
#define LGE_PIF_VID 0x1004
#define LGE_PIF_PID 0x6000
#define LGE_PIF_SN 0
#endif
static char manufacturer_string[256];
static char product_string[256];
static char serial_string[256];
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
#define CHARGE_ONLY_STRING_IDX 3
static char charge_only_string[256];
#endif
#ifdef CONFIG_USB_G_LGE_SERIALNO_REDIRECTION
#define STRING_SERIAL_REDI_IDX 4
static char serial_string_redi[256];
#endif
/* String Table */
static struct usb_string strings_dev[] = {
[STRING_MANUFACTURER_IDX].s = manufacturer_string,
[STRING_PRODUCT_IDX].s = product_string,
[STRING_SERIAL_IDX].s = serial_string,
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
[CHARGE_ONLY_STRING_IDX].s = charge_only_string,
#endif
#ifdef CONFIG_USB_G_LGE_SERIALNO_REDIRECTION
[STRING_SERIAL_REDI_IDX].s = serial_string_redi,
#endif
{ } /* end of list */
};
static struct usb_gadget_strings stringtab_dev = {
.language = 0x0409, /* en-us */
.strings = strings_dev,
};
static struct usb_gadget_strings *dev_strings[] = {
&stringtab_dev,
NULL,
};
static struct usb_device_descriptor device_desc = {
.bLength = sizeof(device_desc),
.bDescriptorType = USB_DT_DEVICE,
.bcdUSB = __constant_cpu_to_le16(0x0200),
.bDeviceClass = USB_CLASS_PER_INTERFACE,
.idVendor = __constant_cpu_to_le16(VENDOR_ID),
.idProduct = __constant_cpu_to_le16(PRODUCT_ID),
.bcdDevice = __constant_cpu_to_le16(0xffff),
.bNumConfigurations = 1,
};
static struct usb_otg_descriptor otg_descriptor = {
.bLength = sizeof otg_descriptor,
.bDescriptorType = USB_DT_OTG,
.bmAttributes = USB_OTG_SRP | USB_OTG_HNP,
.bcdOTG = __constant_cpu_to_le16(0x0200),
};
static const struct usb_descriptor_header *otg_desc[] = {
(struct usb_descriptor_header *) &otg_descriptor,
NULL,
};
enum android_device_state {
USB_DISCONNECTED,
USB_CONNECTED,
USB_CONFIGURED,
USB_SUSPENDED,
USB_RESUMED
};
static void android_pm_qos_update_latency(struct android_dev *dev, int vote)
{
struct android_usb_platform_data *pdata = dev->pdata;
u32 swfi_latency = 0;
static int last_vote = -1;
if (!pdata || vote == last_vote
|| !pdata->swfi_latency)
return;
swfi_latency = pdata->swfi_latency + 1;
if (vote)
pm_qos_update_request(&dev->pm_qos_req_dma,
swfi_latency);
else
pm_qos_update_request(&dev->pm_qos_req_dma,
PM_QOS_DEFAULT_VALUE);
last_vote = vote;
}
extern int lge_get_sbl_cable_type(void);
static void android_work(struct work_struct *data)
{
struct android_dev *dev = container_of(data, struct android_dev, work);
struct usb_composite_dev *cdev = dev->cdev;
char *disconnected[2] = { "USB_STATE=DISCONNECTED", NULL };
char *connected[2] = { "USB_STATE=CONNECTED", NULL };
char *configured[2] = { "USB_STATE=CONFIGURED", NULL };
char *suspended[2] = { "USB_STATE=SUSPENDED", NULL };
char *resumed[2] = { "USB_STATE=RESUMED", NULL };
char **uevent_envp = NULL;
static enum android_device_state last_uevent, next_state;
unsigned long flags;
int pm_qos_vote = -1;
spin_lock_irqsave(&cdev->lock, flags);
if (dev->suspended != dev->sw_suspended && cdev->config) {
if (strncmp(dev->pm_qos, "low", 3))
pm_qos_vote = dev->suspended ? 0 : 1;
next_state = dev->suspended ? USB_SUSPENDED : USB_RESUMED;
uevent_envp = dev->suspended ? suspended : resumed;
} else if (cdev->config) {
uevent_envp = configured;
next_state = USB_CONFIGURED;
} else if (dev->connected != dev->sw_connected) {
uevent_envp = dev->connected ? connected : disconnected;
next_state = dev->connected ? USB_CONNECTED : USB_DISCONNECTED;
if (dev->connected && strncmp(dev->pm_qos, "low", 3))
pm_qos_vote = 1;
else if (!dev->connected || !strncmp(dev->pm_qos, "low", 3))
pm_qos_vote = 0;
}
dev->sw_connected = dev->connected;
dev->sw_suspended = dev->suspended;
spin_unlock_irqrestore(&cdev->lock, flags);
if (pm_qos_vote != -1)
android_pm_qos_update_latency(dev, pm_qos_vote);
if (uevent_envp) {
/*
* Some userspace modules, e.g. MTP, work correctly only if
* CONFIGURED uevent is preceded by DISCONNECT uevent.
* Check if we missed sending out a DISCONNECT uevent. This can
* happen if host PC resets and configures device really quick.
*/
if (((uevent_envp == connected) &&
(last_uevent != USB_DISCONNECTED)) ||
((uevent_envp == configured) &&
(last_uevent == USB_CONFIGURED))) {
pr_info("%s: sent missed DISCONNECT event\n", __func__);
kobject_uevent_env(&dev->dev->kobj, KOBJ_CHANGE,
disconnected);
msleep(20);
}
/*
* Before sending out CONFIGURED uevent give function drivers
* a chance to wakeup userspace threads and notify disconnect
*/
if (uevent_envp == configured)
msleep(50);
/* Do not notify on suspend / resume */
if (next_state != USB_SUSPENDED && next_state != USB_RESUMED) {
kobject_uevent_env(&dev->dev->kobj, KOBJ_CHANGE,
uevent_envp);
last_uevent = next_state;
}
pr_info("%s: sent uevent %s\n", __func__, uevent_envp[0]);
} else {
pr_info("%s: did not send uevent (%d %d %p)\n", __func__,
dev->connected, dev->sw_connected, cdev->config);
}
#if !defined(CONFIG_MACH_MSM8974_G2_KR) && !defined(CONFIG_MACH_MSM8974_VU3_KR) || (defined(CONFIG_MACH_MSM8974_Z_KR) || defined(CONFIG_MACH_MSM8974_Z_US) || defined(CONFIG_MACH_MSM8974_Z_KDDI) || defined(CONFIG_MACH_MSM8974_Z_OPEN_COM))
/*
* For G2 project, a battery type is different from like this:
* Korea (SKT/KT/LGU) : removable type
* Export models(AT&T/DCM/etc) : embedded type
*
* This reset scenario for 56K cable is from factory's request and
* apply to the only the export models
*/
#ifdef CONFIG_USB_LGE_LPM_STATE
if (next_state == USB_CONNECTED &&
(get_tri_state_lpm() == EXIT_LPM || get_tri_state_lpm() == NO_INIT_LPM)) {
#else
if (uevent_envp == connected) {
#endif
if (lge_pm_get_cable_type() == CABLE_56K &&
lge_get_boot_mode() == LGE_BOOT_MODE_NORMAL)
{
usb_gadget_disconnect(cdev->gadget);
usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
pr_info("[FACTORY] PIF_56K detected in NORMAL BOOT, reboot!!\n");
msleep(50); // wait for usb gadget disconnect
kernel_restart(NULL);
}
else if( lge_pm_get_cable_type() == CABLE_910K &&
( lge_get_sbl_cable_type() != 11 || !firstboot_check ))
{
usb_gadget_disconnect(cdev->gadget);
usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
pr_info("[FACTORY] reset due to 910K cable, pm:%d, sbl:%d, firstboot_check:%d\n",
lge_pm_get_cable_type(), lge_get_sbl_cable_type(), firstboot_check);
msleep(50); // wait for usb gadget disconnect
// write magic number for laf mode
msm_set_restart_mode(RESTART_DLOAD);
kernel_restart(NULL);
}
#ifdef CONFIG_USB_LGE_LPM_STATE
set_tri_state_lpm(KEEP_NO_LPM);
#endif
}
if(uevent_envp == configured)
{
pr_info("[cable info] boot_mode:%d, dlcomplete:%d\n",
lge_get_boot_mode(), lge_get_android_dlcomplete());
firstboot_check = 0;
}
#endif
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN_VZW
if (next_state == USB_CONFIGURED) {
send_drv_state_uevent(1);
}
#endif
}
static void android_enable(struct android_dev *dev)
{
struct usb_composite_dev *cdev = dev->cdev;
struct android_configuration *conf;
if (WARN_ON(!dev->disable_depth))
return;
if (--dev->disable_depth == 0) {
list_for_each_entry(conf, &dev->configs, list_item)
usb_add_config(cdev, &conf->usb_config,
android_bind_config);
usb_gadget_connect(cdev->gadget);
}
}
static void android_disable(struct android_dev *dev)
{
struct usb_composite_dev *cdev = dev->cdev;
struct android_configuration *conf;
if (dev->disable_depth++ == 0) {
usb_gadget_disconnect(cdev->gadget);
/* Cancel pending control requests */
usb_ep_dequeue(cdev->gadget->ep0, cdev->req);
list_for_each_entry(conf, &dev->configs, list_item)
usb_remove_config(cdev, &conf->usb_config);
}
}
/*-------------------------------------------------------------------------*/
/* Supported functions initialization */
struct adb_data {
bool opened;
bool enabled;
struct android_dev *dev;
};
static int
adb_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct adb_data), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return adb_setup();
}
static void adb_function_cleanup(struct android_usb_function *f)
{
adb_cleanup();
kfree(f->config);
}
static int
adb_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return adb_bind_config(c);
}
static void adb_android_function_enable(struct android_usb_function *f)
{
struct android_dev *dev = f->android_dev;
struct adb_data *data = f->config;
data->enabled = true;
/* Disable the gadget until adbd is ready */
if (!data->opened)
android_disable(dev);
}
static void adb_android_function_disable(struct android_usb_function *f)
{
struct android_dev *dev = f->android_dev;
struct adb_data *data = f->config;
data->enabled = false;
/* Balance the disable that was called in closed_callback */
if (!data->opened)
android_enable(dev);
}
static struct android_usb_function adb_function = {
.name = "adb",
.enable = adb_android_function_enable,
.disable = adb_android_function_disable,
.init = adb_function_init,
.cleanup = adb_function_cleanup,
.bind_config = adb_function_bind_config,
};
static void adb_ready_callback(void)
{
struct android_dev *dev = adb_function.android_dev;
struct adb_data *data = adb_function.config;
/* dev is null in case ADB is not in the composition */
if (dev)
mutex_lock(&dev->mutex);
/* Save dev in case the adb function will get disabled */
data->dev = dev;
data->opened = true;
if (data->enabled && dev)
android_enable(dev);
if (dev)
mutex_unlock(&dev->mutex);
}
static void adb_closed_callback(void)
{
struct adb_data *data = adb_function.config;
struct android_dev *dev = adb_function.android_dev;
/* In case new composition is without ADB, use saved one */
if (!dev)
dev = data->dev;
if (!dev)
pr_err("adb_closed_callback: data->dev is NULL");
if (dev)
mutex_lock(&dev->mutex);
data->opened = false;
if (data->enabled && dev)
android_disable(dev);
data->dev = NULL;
if (dev)
mutex_unlock(&dev->mutex);
}
/*-------------------------------------------------------------------------*/
/* Supported functions initialization */
/* laf */
struct laf_data {
bool opened;
bool enabled;
};
static int
laf_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct laf_data), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return laf_setup();
}
static void laf_function_cleanup(struct android_usb_function *f)
{
laf_cleanup();
kfree(f->config);
}
static int
laf_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return laf_bind_config(c);
}
static void laf_android_function_enable(struct android_usb_function *f)
{
struct laf_data *data = f->config;
data->enabled = true;
pr_err("laf_android_function_enable");
}
static void laf_android_function_disable(struct android_usb_function *f)
{
struct laf_data *data = f->config;
data->enabled = false;
}
static struct android_usb_function laf_function = {
.name = "laf",
.enable = laf_android_function_enable,
.disable = laf_android_function_disable,
.init = laf_function_init,
.cleanup = laf_function_cleanup,
.bind_config = laf_function_bind_config,
};
static void laf_ready_callback(void)
{
struct laf_data *data = laf_function.config;
data->opened = true;
}
static void laf_closed_callback(void)
{
struct laf_data *data = laf_function.config;
data->opened = false;
}
/*-------------------------------------------------------------------------*/
/* Supported functions initialization */
/* ACM */
static char acm_transports[32]; /*enabled ACM ports - "tty[,sdio]"*/
static ssize_t acm_transports_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(acm_transports, buff, sizeof(acm_transports));
return size;
}
static DEVICE_ATTR(acm_transports, S_IWUSR, NULL, acm_transports_store);
static struct device_attribute *acm_function_attributes[] = {
&dev_attr_acm_transports,
NULL
};
static void acm_function_cleanup(struct android_usb_function *f)
{
gserial_cleanup();
}
static int
acm_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *name;
char buf[32], *b;
int err = -1, i;
static int acm_initialized, ports;
#ifdef CONFIG_USB_G_LGE_ANDROID
if (acm_initialized && ports)
#else
if (acm_initialized)
#endif
goto bind_config;
acm_initialized = 1;
strlcpy(buf, acm_transports, sizeof(buf));
b = strim(buf);
while (b) {
name = strsep(&b, ",");
if (name) {
err = acm_init_port(ports, name);
if (err) {
pr_err("acm: Cannot open port '%s'", name);
goto out;
}
ports++;
}
}
err = acm_port_setup(c);
if (err) {
pr_err("acm: Cannot setup transports");
goto out;
}
bind_config:
for (i = 0; i < ports; i++) {
err = acm_bind_config(c, i);
if (err) {
pr_err("acm: bind_config failed for port %d", i);
goto out;
}
}
out:
return err;
}
static struct android_usb_function acm_function = {
.name = "acm",
.cleanup = acm_function_cleanup,
.bind_config = acm_function_bind_config,
.attributes = acm_function_attributes,
};
/* RMNET_SMD */
static int rmnet_smd_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return rmnet_smd_bind_config(c);
}
static struct android_usb_function rmnet_smd_function = {
.name = "rmnet_smd",
.bind_config = rmnet_smd_function_bind_config,
};
/* RMNET_SDIO */
static int rmnet_sdio_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return rmnet_sdio_function_add(c);
}
static struct android_usb_function rmnet_sdio_function = {
.name = "rmnet_sdio",
.bind_config = rmnet_sdio_function_bind_config,
};
/* RMNET_SMD_SDIO */
static int rmnet_smd_sdio_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return rmnet_smd_sdio_init();
}
static void rmnet_smd_sdio_function_cleanup(struct android_usb_function *f)
{
rmnet_smd_sdio_cleanup();
}
static int rmnet_smd_sdio_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return rmnet_smd_sdio_function_add(c);
}
static struct device_attribute *rmnet_smd_sdio_attributes[] = {
&dev_attr_transport, NULL };
static struct android_usb_function rmnet_smd_sdio_function = {
.name = "rmnet_smd_sdio",
.init = rmnet_smd_sdio_function_init,
.cleanup = rmnet_smd_sdio_function_cleanup,
.bind_config = rmnet_smd_sdio_bind_config,
.attributes = rmnet_smd_sdio_attributes,
};
/*rmnet transport string format(per port):"ctrl0,data0,ctrl1,data1..." */
#define MAX_XPORT_STR_LEN 50
static char rmnet_transports[MAX_XPORT_STR_LEN];
static void rmnet_function_cleanup(struct android_usb_function *f)
{
frmnet_cleanup();
}
static int rmnet_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int i;
int err = 0;
char *ctrl_name;
char *data_name;
char buf[MAX_XPORT_STR_LEN], *b;
static int rmnet_initialized, ports;
if (!rmnet_initialized) {
rmnet_initialized = 1;
strlcpy(buf, rmnet_transports, sizeof(buf));
b = strim(buf);
while (b) {
ctrl_name = strsep(&b, ",");
data_name = strsep(&b, ",");
if (ctrl_name && data_name) {
err = frmnet_init_port(ctrl_name, data_name);
if (err) {
pr_err("rmnet: Cannot open ctrl port:"
"'%s' data port:'%s'\n",
ctrl_name, data_name);
goto out;
}
ports++;
}
}
err = rmnet_gport_setup();
if (err) {
pr_err("rmnet: Cannot setup transports");
goto out;
}
}
for (i = 0; i < ports; i++) {
err = frmnet_bind_config(c, i);
if (err) {
pr_err("Could not bind rmnet%u config\n", i);
break;
}
}
out:
return err;
}
static ssize_t rmnet_transports_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", rmnet_transports);
}
static ssize_t rmnet_transports_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(rmnet_transports, buff, sizeof(rmnet_transports));
return size;
}
static struct device_attribute dev_attr_rmnet_transports =
__ATTR(transports, S_IRUGO | S_IWUSR,
rmnet_transports_show,
rmnet_transports_store);
static struct device_attribute *rmnet_function_attributes[] = {
&dev_attr_rmnet_transports,
NULL };
static struct android_usb_function rmnet_function = {
.name = "rmnet",
.cleanup = rmnet_function_cleanup,
.bind_config = rmnet_function_bind_config,
.attributes = rmnet_function_attributes,
};
static void gps_function_cleanup(struct android_usb_function *f)
{
gps_cleanup();
}
static int gps_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int err;
static int gps_initialized;
if (!gps_initialized) {
gps_initialized = 1;
err = gps_init_port();
if (err) {
pr_err("gps: Cannot init gps port");
return err;
}
}
err = gps_gport_setup();
if (err) {
pr_err("gps: Cannot setup transports");
return err;
}
err = gps_bind_config(c);
if (err) {
pr_err("Could not bind gps config\n");
return err;
}
return 0;
}
static struct android_usb_function gps_function = {
.name = "gps",
.cleanup = gps_function_cleanup,
.bind_config = gps_function_bind_config,
};
/* ncm */
#ifdef CONFIG_USB_G_LGE_ANDROID_NCM
struct ncm_function_config {
u8 ethaddr[ETH_ALEN];
};
static int ncm_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct ncm_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return ncm_init();
}
static void ncm_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
ncm_cleanup();
}
static int ncm_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int ret;
struct ncm_function_config *ncm = f->config;
if (!ncm) {
pr_err("%s: ncm_pdata\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
ncm->ethaddr[0], ncm->ethaddr[1], ncm->ethaddr[2],
ncm->ethaddr[3], ncm->ethaddr[4], ncm->ethaddr[5]);
ret = gether_setup_name(c->cdev->gadget, ncm->ethaddr, "usb");
if (ret) {
pr_err("%s: gether_setup failed\n", __func__);
return ret;
}
ret = ncm_bind_config(c, ncm->ethaddr);
if (ret) {
pr_err("%s: ncm_bind_config failed\n", __func__);
gether_cleanup();
}
return ret;
}
static void ncm_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
gether_cleanup();
}
static struct android_usb_function ncm_function = {
.name = "ncm",
.init = ncm_function_init,
.cleanup = ncm_function_cleanup,
.bind_config = ncm_function_bind_config,
.unbind_config = ncm_function_unbind_config,
};
#else
struct ncm_function_config {
u8 ethaddr[ETH_ALEN];
};
static int
ncm_function_init(struct android_usb_function *f, struct usb_composite_dev *c)
{
f->config = kzalloc(sizeof(struct ncm_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return 0;
}
static void ncm_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
static int
ncm_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct ncm_function_config *ncm = f->config;
int ret;
if (!ncm) {
pr_err("%s: ncm config is null\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
ncm->ethaddr[0], ncm->ethaddr[1], ncm->ethaddr[2],
ncm->ethaddr[3], ncm->ethaddr[4], ncm->ethaddr[5]);
ret = gether_setup_name(c->cdev->gadget, ncm->ethaddr, "ncm");
if (ret) {
pr_err("%s: gether setup failed err:%d\n", __func__, ret);
return ret;
}
ret = ncm_bind_config(c, ncm->ethaddr);
if (ret) {
pr_err("%s: ncm bind config failed err:%d", __func__, ret);
gether_cleanup();
return ret;
}
return ret;
}
static void ncm_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
gether_cleanup();
}
static ssize_t ncm_ethaddr_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct ncm_function_config *ncm = f->config;
return snprintf(buf, PAGE_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x\n",
ncm->ethaddr[0], ncm->ethaddr[1], ncm->ethaddr[2],
ncm->ethaddr[3], ncm->ethaddr[4], ncm->ethaddr[5]);
}
static ssize_t ncm_ethaddr_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct ncm_function_config *ncm = f->config;
if (sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x\n",
(int *)&ncm->ethaddr[0], (int *)&ncm->ethaddr[1],
(int *)&ncm->ethaddr[2], (int *)&ncm->ethaddr[3],
(int *)&ncm->ethaddr[4], (int *)&ncm->ethaddr[5]) == 6)
return size;
return -EINVAL;
}
static DEVICE_ATTR(ncm_ethaddr, S_IRUGO | S_IWUSR, ncm_ethaddr_show,
ncm_ethaddr_store);
static struct device_attribute *ncm_function_attributes[] = {
&dev_attr_ncm_ethaddr,
NULL
};
static struct android_usb_function ncm_function = {
.name = "ncm",
.init = ncm_function_init,
.cleanup = ncm_function_cleanup,
.bind_config = ncm_function_bind_config,
.unbind_config = ncm_function_unbind_config,
.attributes = ncm_function_attributes,
};
#endif
/* ecm transport string */
static char ecm_transports[MAX_XPORT_STR_LEN];
struct ecm_function_config {
u8 ethaddr[ETH_ALEN];
};
static int ecm_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct ecm_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return 0;
}
static void ecm_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
static int ecm_qc_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int ret;
char *trans;
struct ecm_function_config *ecm = f->config;
if (!ecm) {
pr_err("%s: ecm_pdata\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
ecm->ethaddr[0], ecm->ethaddr[1], ecm->ethaddr[2],
ecm->ethaddr[3], ecm->ethaddr[4], ecm->ethaddr[5]);
pr_debug("%s: ecm_transport is %s", __func__, ecm_transports);
trans = strim(ecm_transports);
if (strcmp("BAM2BAM_IPA", trans)) {
ret = gether_qc_setup_name(c->cdev->gadget,
ecm->ethaddr, "ecm");
if (ret) {
pr_err("%s: gether_setup failed\n", __func__);
return ret;
}
}
return ecm_qc_bind_config(c, ecm->ethaddr, trans);
}
static void ecm_qc_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *trans = strim(ecm_transports);
if (strcmp("BAM2BAM_IPA", trans))
gether_qc_cleanup_name("ecm0");
}
#endif
static ssize_t ecm_ethaddr_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct ecm_function_config *ecm = f->config;
return snprintf(buf, PAGE_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x\n",
ecm->ethaddr[0], ecm->ethaddr[1], ecm->ethaddr[2],
ecm->ethaddr[3], ecm->ethaddr[4], ecm->ethaddr[5]);
}
static ssize_t ecm_ethaddr_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct ecm_function_config *ecm = f->config;
if (sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x\n",
(int *)&ecm->ethaddr[0], (int *)&ecm->ethaddr[1],
(int *)&ecm->ethaddr[2], (int *)&ecm->ethaddr[3],
(int *)&ecm->ethaddr[4], (int *)&ecm->ethaddr[5]) == 6)
return size;
return -EINVAL;
}
static DEVICE_ATTR(ecm_ethaddr, S_IRUGO | S_IWUSR, ecm_ethaddr_show,
ecm_ethaddr_store);
static ssize_t ecm_transports_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", ecm_transports);
}
static ssize_t ecm_transports_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
strlcpy(ecm_transports, buf, sizeof(ecm_transports));
return size;
}
static DEVICE_ATTR(ecm_transports, S_IRUGO | S_IWUSR, ecm_transports_show,
ecm_transports_store);
static struct device_attribute *ecm_function_attributes[] = {
&dev_attr_ecm_transports,
&dev_attr_ecm_ethaddr,
NULL
};
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
static struct android_usb_function ecm_qc_function = {
.name = "ecm_qc",
.init = ecm_function_init,
.cleanup = ecm_function_cleanup,
.bind_config = ecm_qc_function_bind_config,
.unbind_config = ecm_qc_function_unbind_config,
.attributes = ecm_function_attributes,
};
#endif
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
/* MBIM - used with BAM */
#define MAX_MBIM_INSTANCES 1
static int mbim_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return mbim_init(MAX_MBIM_INSTANCES);
}
static void mbim_function_cleanup(struct android_usb_function *f)
{
fmbim_cleanup();
}
/* mbim transport string */
static char mbim_transports[MAX_XPORT_STR_LEN];
static int mbim_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *trans;
pr_debug("%s: mbim transport is %s", __func__, mbim_transports);
trans = strim(mbim_transports);
return mbim_bind_config(c, 0, trans);
}
static int mbim_function_ctrlrequest(struct android_usb_function *f,
struct usb_composite_dev *cdev,
const struct usb_ctrlrequest *c)
{
return mbim_ctrlrequest(cdev, c);
}
static ssize_t mbim_transports_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", mbim_transports);
}
static ssize_t mbim_transports_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
strlcpy(mbim_transports, buf, sizeof(mbim_transports));
return size;
}
static DEVICE_ATTR(mbim_transports, S_IRUGO | S_IWUSR, mbim_transports_show,
mbim_transports_store);
static struct device_attribute *mbim_function_attributes[] = {
&dev_attr_mbim_transports,
NULL
};
static struct android_usb_function mbim_function = {
.name = "usb_mbim",
.cleanup = mbim_function_cleanup,
.bind_config = mbim_function_bind_config,
.init = mbim_function_init,
.ctrlrequest = mbim_function_ctrlrequest,
.attributes = mbim_function_attributes,
};
#endif
#ifdef CONFIG_SND_PCM
/* PERIPHERAL AUDIO */
static int audio_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return audio_bind_config(c);
}
static struct android_usb_function audio_function = {
.name = "audio",
.bind_config = audio_function_bind_config,
};
#endif
/* DIAG */
static char diag_clients[32]; /*enabled DIAG clients- "diag[,diag_mdm]" */
static ssize_t clients_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
#if defined CONFIG_USB_G_LGE_ANDROID && defined CONFIG_LGE_PM
struct android_dev *dev = list_entry(android_dev_list.prev, struct android_dev, list_item);
if (dev->check_pif) {
dev_info(dev->dev, "pif cable is plugged, not permitted\n");
return -EPERM;
}
#endif
strlcpy(diag_clients, buff, sizeof(diag_clients));
return size;
}
static DEVICE_ATTR(clients, S_IWUSR, NULL, clients_store);
static struct device_attribute *diag_function_attributes[] =
{ &dev_attr_clients, NULL };
static int diag_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return diag_setup();
}
static void diag_function_cleanup(struct android_usb_function *f)
{
diag_cleanup();
}
static int diag_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *name;
char buf[32], *b;
int once = 0, err = -1;
int (*notify)(uint32_t, const char *);
struct android_dev *dev = cdev_to_android_dev(c->cdev);
strlcpy(buf, diag_clients, sizeof(buf));
b = strim(buf);
while (b) {
notify = NULL;
name = strsep(&b, ",");
/* Allow only first diag channel to update pid and serial no */
if (!once++) {
if (dev->pdata && dev->pdata->update_pid_and_serial_num)
notify = dev->pdata->update_pid_and_serial_num;
else
notify = usb_diag_update_pid_and_serial_num;
}
if (name) {
err = diag_function_add(c, name, notify);
if (err)
pr_err("diag: Cannot open channel '%s'", name);
}
}
return err;
}
static struct android_usb_function diag_function = {
.name = "diag",
.init = diag_function_init,
.cleanup = diag_function_cleanup,
.bind_config = diag_function_bind_config,
.attributes = diag_function_attributes,
};
/* DEBUG */
static int qdss_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return qdss_setup();
}
static void qdss_function_cleanup(struct android_usb_function *f)
{
qdss_cleanup();
}
static int qdss_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int err = -1;
err = qdss_bind_config(c, "qdss");
if (err)
pr_err("qdss: Cannot open channel qdss");
return err;
}
static struct android_usb_function qdss_function = {
.name = "qdss",
.init = qdss_function_init,
.cleanup = qdss_function_cleanup,
.bind_config = qdss_function_bind_config,
};
/* SERIAL */
static char serial_transports[32]; /*enabled FSERIAL ports - "tty[,sdio]"*/
static ssize_t serial_transports_store(
struct device *device, struct device_attribute *attr,
const char *buff, size_t size)
{
strlcpy(serial_transports, buff, sizeof(serial_transports));
return size;
}
static DEVICE_ATTR(transports, S_IWUSR, NULL, serial_transports_store);
static struct device_attribute *serial_function_attributes[] =
{ &dev_attr_transports, NULL };
static void serial_function_cleanup(struct android_usb_function *f)
{
gserial_cleanup();
}
static int serial_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
char *name;
char buf[32], *b;
int err = -1, i;
static int serial_initialized = 0, ports = 0;
if (serial_initialized)
goto bind_config;
serial_initialized = 1;
strlcpy(buf, serial_transports, sizeof(buf));
b = strim(buf);
while (b) {
name = strsep(&b, ",");
if (name) {
err = gserial_init_port(ports, name);
if (err) {
pr_err("serial: Cannot open port '%s'", name);
goto out;
}
ports++;
}
}
err = gport_setup(c);
if (err) {
pr_err("serial: Cannot setup transports");
goto out;
}
bind_config:
for (i = 0; i < ports; i++) {
err = gser_bind_config(c, i);
if (err) {
pr_err("serial: bind_config failed for port %d", i);
goto out;
}
}
out:
return err;
}
static struct android_usb_function serial_function = {
.name = "serial",
.cleanup = serial_function_cleanup,
.bind_config = serial_function_bind_config,
.attributes = serial_function_attributes,
};
/* CCID */
static int ccid_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return ccid_setup();
}
static void ccid_function_cleanup(struct android_usb_function *f)
{
ccid_cleanup();
}
static int ccid_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return ccid_bind_config(c);
}
static struct android_usb_function ccid_function = {
.name = "ccid",
.init = ccid_function_init,
.cleanup = ccid_function_cleanup,
.bind_config = ccid_function_bind_config,
};
static int
mtp_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return mtp_setup();
}
static void mtp_function_cleanup(struct android_usb_function *f)
{
mtp_cleanup();
}
static int
mtp_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return mtp_bind_config(c, false);
}
static int
ptp_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
/* nothing to do - initialization is handled by mtp_function_init */
return 0;
}
static void ptp_function_cleanup(struct android_usb_function *f)
{
/* nothing to do - cleanup is handled by mtp_function_cleanup */
}
static int
ptp_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return mtp_bind_config(c, true);
}
static int mtp_function_ctrlrequest(struct android_usb_function *f,
struct usb_composite_dev *cdev,
const struct usb_ctrlrequest *c)
{
return mtp_ctrlrequest(cdev, c);
}
static struct android_usb_function mtp_function = {
.name = "mtp",
.init = mtp_function_init,
.cleanup = mtp_function_cleanup,
.bind_config = mtp_function_bind_config,
.ctrlrequest = mtp_function_ctrlrequest,
};
/* PTP function is same as MTP with slightly different interface descriptor */
static struct android_usb_function ptp_function = {
.name = "ptp",
.init = ptp_function_init,
.cleanup = ptp_function_cleanup,
.bind_config = ptp_function_bind_config,
};
struct rndis_function_config {
u8 ethaddr[ETH_ALEN];
u32 vendorID;
u8 max_pkt_per_xfer;
char manufacturer[256];
/* "Wireless" RNDIS; auto-detected by Windows */
bool wceis;
};
static int
rndis_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct rndis_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return 0;
}
static void rndis_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
static int rndis_qc_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
f->config = kzalloc(sizeof(struct rndis_function_config), GFP_KERNEL);
if (!f->config)
return -ENOMEM;
return rndis_qc_init();
}
static void rndis_qc_function_cleanup(struct android_usb_function *f)
{
rndis_qc_cleanup();
kfree(f->config);
}
#endif
static int
rndis_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int ret;
struct rndis_function_config *rndis = f->config;
if (!rndis) {
pr_err("%s: rndis_pdata\n", __func__);
return -1;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
rndis->ethaddr[0], rndis->ethaddr[1], rndis->ethaddr[2],
rndis->ethaddr[3], rndis->ethaddr[4], rndis->ethaddr[5]);
if (rndis->ethaddr[0])
ret = gether_setup_name(c->cdev->gadget, NULL, "rndis");
else
ret = gether_setup_name(c->cdev->gadget, rndis->ethaddr,
"rndis");
if (ret) {
pr_err("%s: gether_setup failed\n", __func__);
return ret;
}
if (rndis->wceis) {
/* "Wireless" RNDIS; auto-detected by Windows */
rndis_iad_descriptor.bFunctionClass =
USB_CLASS_WIRELESS_CONTROLLER;
rndis_iad_descriptor.bFunctionSubClass = 0x01;
rndis_iad_descriptor.bFunctionProtocol = 0x03;
rndis_control_intf.bInterfaceClass =
USB_CLASS_WIRELESS_CONTROLLER;
rndis_control_intf.bInterfaceSubClass = 0x01;
rndis_control_intf.bInterfaceProtocol = 0x03;
}
return rndis_bind_config_vendor(c, rndis->ethaddr, rndis->vendorID,
rndis->manufacturer);
}
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
static int rndis_qc_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int ret;
struct rndis_function_config *rndis = f->config;
if (!rndis) {
pr_err("%s: rndis_pdata\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
rndis->ethaddr[0], rndis->ethaddr[1], rndis->ethaddr[2],
rndis->ethaddr[3], rndis->ethaddr[4], rndis->ethaddr[5]);
ret = gether_qc_setup_name(c->cdev->gadget, rndis->ethaddr, "rndis");
if (ret) {
pr_err("%s: gether_setup failed\n", __func__);
return ret;
}
if (rndis->wceis) {
/* "Wireless" RNDIS; auto-detected by Windows */
rndis_qc_iad_descriptor.bFunctionClass =
USB_CLASS_WIRELESS_CONTROLLER;
rndis_qc_iad_descriptor.bFunctionSubClass = 0x01;
rndis_qc_iad_descriptor.bFunctionProtocol = 0x03;
rndis_qc_control_intf.bInterfaceClass =
USB_CLASS_WIRELESS_CONTROLLER;
rndis_qc_control_intf.bInterfaceSubClass = 0x01;
rndis_qc_control_intf.bInterfaceProtocol = 0x03;
}
return rndis_qc_bind_config_vendor(c, rndis->ethaddr, rndis->vendorID,
rndis->manufacturer,
rndis->max_pkt_per_xfer);
}
#endif
static void rndis_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
gether_cleanup();
}
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
static void rndis_qc_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
gether_qc_cleanup_name("rndis0");
}
#endif
static ssize_t rndis_manufacturer_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%s\n", config->manufacturer);
}
static ssize_t rndis_manufacturer_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
if (size >= sizeof(config->manufacturer))
return -EINVAL;
if (sscanf(buf, "%255s", config->manufacturer) == 1)
return size;
return -1;
}
static DEVICE_ATTR(manufacturer, S_IRUGO | S_IWUSR, rndis_manufacturer_show,
rndis_manufacturer_store);
static ssize_t rndis_wceis_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%d\n", config->wceis);
}
static ssize_t rndis_wceis_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
int value;
if (sscanf(buf, "%d", &value) == 1) {
config->wceis = value;
return size;
}
return -EINVAL;
}
static DEVICE_ATTR(wceis, S_IRUGO | S_IWUSR, rndis_wceis_show,
rndis_wceis_store);
static ssize_t rndis_ethaddr_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *rndis = f->config;
return snprintf(buf, PAGE_SIZE, "%02x:%02x:%02x:%02x:%02x:%02x\n",
rndis->ethaddr[0], rndis->ethaddr[1], rndis->ethaddr[2],
rndis->ethaddr[3], rndis->ethaddr[4], rndis->ethaddr[5]);
}
static ssize_t rndis_ethaddr_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *rndis = f->config;
if (sscanf(buf, "%02x:%02x:%02x:%02x:%02x:%02x\n",
(int *)&rndis->ethaddr[0], (int *)&rndis->ethaddr[1],
(int *)&rndis->ethaddr[2], (int *)&rndis->ethaddr[3],
(int *)&rndis->ethaddr[4], (int *)&rndis->ethaddr[5]) == 6)
return size;
return -EINVAL;
}
static DEVICE_ATTR(ethaddr, S_IRUGO | S_IWUSR, rndis_ethaddr_show,
rndis_ethaddr_store);
static ssize_t rndis_vendorID_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%04x\n", config->vendorID);
}
static ssize_t rndis_vendorID_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
int value;
if (sscanf(buf, "%04x", &value) == 1) {
config->vendorID = value;
return size;
}
return -EINVAL;
}
static DEVICE_ATTR(vendorID, S_IRUGO | S_IWUSR, rndis_vendorID_show,
rndis_vendorID_store);
static ssize_t rndis_max_pkt_per_xfer_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%d\n", config->max_pkt_per_xfer);
}
static ssize_t rndis_max_pkt_per_xfer_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct rndis_function_config *config = f->config;
int value;
if (sscanf(buf, "%d", &value) == 1) {
config->max_pkt_per_xfer = value;
return size;
}
return -EINVAL;
}
static DEVICE_ATTR(max_pkt_per_xfer, S_IRUGO | S_IWUSR,
rndis_max_pkt_per_xfer_show,
rndis_max_pkt_per_xfer_store);
static struct device_attribute *rndis_function_attributes[] = {
&dev_attr_manufacturer,
&dev_attr_wceis,
&dev_attr_ethaddr,
&dev_attr_vendorID,
&dev_attr_max_pkt_per_xfer,
NULL
};
static struct android_usb_function rndis_function = {
.name = "rndis",
.init = rndis_function_init,
.cleanup = rndis_function_cleanup,
.bind_config = rndis_function_bind_config,
.unbind_config = rndis_function_unbind_config,
.attributes = rndis_function_attributes,
};
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
static struct android_usb_function rndis_qc_function = {
.name = "rndis_qc",
.init = rndis_qc_function_init,
.cleanup = rndis_qc_function_cleanup,
.bind_config = rndis_qc_function_bind_config,
.unbind_config = rndis_qc_function_unbind_config,
.attributes = rndis_function_attributes,
};
#endif
static int ecm_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
int ret;
struct ecm_function_config *ecm = f->config;
if (!ecm) {
pr_err("%s: ecm_pdata\n", __func__);
return -EINVAL;
}
pr_info("%s MAC: %02X:%02X:%02X:%02X:%02X:%02X\n", __func__,
ecm->ethaddr[0], ecm->ethaddr[1], ecm->ethaddr[2],
ecm->ethaddr[3], ecm->ethaddr[4], ecm->ethaddr[5]);
#ifdef CONFIG_USB_G_LGE_ANDROID
ret = gether_setup_name(c->cdev->gadget, ecm->ethaddr, "usb");
#else
ret = gether_setup_name(c->cdev->gadget, ecm->ethaddr, "ecm");
#endif
if (ret) {
pr_err("%s: gether_setup failed\n", __func__);
return ret;
}
ret = ecm_bind_config(c, ecm->ethaddr);
if (ret) {
pr_err("%s: ecm_bind_config failed\n", __func__);
gether_cleanup();
}
return ret;
}
static void ecm_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
gether_cleanup();
}
static struct android_usb_function ecm_function = {
.name = "ecm",
.init = ecm_function_init,
.cleanup = ecm_function_cleanup,
.bind_config = ecm_function_bind_config,
.unbind_config = ecm_function_unbind_config,
.attributes = ecm_function_attributes,
};
#ifdef CONFIG_USB_G_LGE_ANDROID
static const char lge_vendor_name[] = "LGE";
static const char lge_product_name[] = CONFIG_USB_G_LGE_ANDROID_STORAGE_NAME;
#endif
struct mass_storage_function_config {
struct fsg_config fsg;
struct fsg_common *common;
};
static int mass_storage_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
struct android_dev *dev = cdev_to_android_dev(cdev);
struct mass_storage_function_config *config;
struct fsg_common *common;
int err;
int i;
const char *name[2];
config = kzalloc(sizeof(struct mass_storage_function_config),
GFP_KERNEL);
if (!config)
return -ENOMEM;
#ifdef CONFIG_USB_G_LGE_ANDROID
config->fsg.vendor_name = lge_vendor_name;
config->fsg.product_name = lge_product_name;
#endif
config->fsg.nluns = 1;
name[0] = "lun";
if (dev->pdata && dev->pdata->cdrom) {
config->fsg.nluns = 2;
config->fsg.luns[1].cdrom = 1;
config->fsg.luns[1].ro = 1;
config->fsg.luns[1].removable = 0;
name[1] = "lun0";
}
config->fsg.luns[0].removable = 1;
common = fsg_common_init(NULL, cdev, &config->fsg);
if (IS_ERR(common)) {
kfree(config);
return PTR_ERR(common);
}
for (i = 0; i < config->fsg.nluns; i++) {
err = sysfs_create_link(&f->dev->kobj,
&common->luns[i].dev.kobj,
name[i]);
if (err)
goto error;
}
config->common = common;
f->config = config;
return 0;
error:
for (; i > 0 ; i--)
sysfs_remove_link(&f->dev->kobj, name[i-1]);
fsg_common_release(&common->ref);
kfree(config);
return err;
}
static void mass_storage_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
static int mass_storage_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct mass_storage_function_config *config = f->config;
return fsg_bind_config(c->cdev, c, config->common);
}
static ssize_t mass_storage_inquiry_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct mass_storage_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%s\n", config->common->inquiry_string);
}
static ssize_t mass_storage_inquiry_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct mass_storage_function_config *config = f->config;
if (size >= sizeof(config->common->inquiry_string))
return -EINVAL;
if (sscanf(buf, "%28s", config->common->inquiry_string) != 1)
return -EINVAL;
return size;
}
static DEVICE_ATTR(inquiry_string, S_IRUGO | S_IWUSR,
mass_storage_inquiry_show,
mass_storage_inquiry_store);
static struct device_attribute *mass_storage_function_attributes[] = {
&dev_attr_inquiry_string,
NULL
};
static struct android_usb_function mass_storage_function = {
.name = "mass_storage",
.init = mass_storage_function_init,
.cleanup = mass_storage_function_cleanup,
.bind_config = mass_storage_function_bind_config,
.attributes = mass_storage_function_attributes,
};
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
/* virtual cdrom usb gadget for autorun */
struct cdrom_storage_function_config {
struct fsg_config fsg;
struct fsg_common *common;
};
static const char cdrom_storage_kthread_name[] = "kcdrom-storaged";
static const char cdrom_lun_format[] = "clun%d";
static int cdrom_storage_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
struct cdrom_storage_function_config *config;
struct fsg_common *common;
int err;
config = kzalloc(sizeof(struct cdrom_storage_function_config),
GFP_KERNEL);
if (!config)
return -ENOMEM;
config->fsg.nluns = 1;
config->fsg.luns[0].removable = 1;
config->fsg.luns[0].cdrom = 1; /* cdrom(read only) flag */
config->fsg.thread_name = cdrom_storage_kthread_name;
config->fsg.lun_name_format = cdrom_lun_format;
config->fsg.vendor_name = lge_vendor_name;
config->fsg.product_name = lge_product_name;
common = fsg_common_init(NULL, cdev, &config->fsg);
if (IS_ERR(common)) {
kfree(config);
return PTR_ERR(common);
}
err = sysfs_create_link(&f->dev->kobj,
&common->luns[0].dev.kobj,
"lun");
if (err) {
fsg_common_release(&common->ref);
kfree(config);
return err;
}
config->common = common;
f->config = config;
return 0;
}
static int cdrom_storage_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct cdrom_storage_function_config *config = f->config;
return csg_bind_config(c->cdev, c, config->common);
}
static void cdrom_storage_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
f->config = NULL;
}
static ssize_t cdrom_storage_inquiry_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct cdrom_storage_function_config *config = f->config;
return snprintf(buf, PAGE_SIZE, "%s\n", config->common->inquiry_string);
}
static ssize_t cdrom_storage_inquiry_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct cdrom_storage_function_config *config = f->config;
if (size >= sizeof(config->common->inquiry_string))
return -EINVAL;
if (strlcpy(config->common->inquiry_string, buf,
sizeof(config->common->inquiry_string)) == 0)
return -EINVAL;
return size;
}
static DEVICE_ATTR(cdrom_inquiry_string, S_IRUGO | S_IWUSR,
cdrom_storage_inquiry_show,
cdrom_storage_inquiry_store);
/* we borrow another parts from mass storage function driver */
static struct device_attribute *cdrom_storage_function_attributes[] = {
&dev_attr_cdrom_inquiry_string,
NULL
};
static struct android_usb_function cdrom_storage_function = {
.name = "cdrom_storage",
.init = cdrom_storage_function_init,
.cleanup = cdrom_storage_function_cleanup,
.bind_config = cdrom_storage_function_bind_config,
.attributes = cdrom_storage_function_attributes,
};
/* charge only mode */
static int charge_only_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return charge_only_setup();
}
static void charge_only_function_cleanup(struct android_usb_function *f)
{
charge_only_cleanup();
}
static int charge_only_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return charge_only_bind_config(c);
}
static struct android_usb_function charge_only_function = {
.name = "charge_only",
.init = charge_only_function_init,
.cleanup = charge_only_function_cleanup,
.bind_config = charge_only_function_bind_config,
};
#endif /* CONFIG_USB_G_LGE_ANDROID_AUTORUN */
static int accessory_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return acc_setup();
}
static void accessory_function_cleanup(struct android_usb_function *f)
{
acc_cleanup();
}
static int accessory_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return acc_bind_config(c);
}
static int accessory_function_ctrlrequest(struct android_usb_function *f,
struct usb_composite_dev *cdev,
const struct usb_ctrlrequest *c)
{
return acc_ctrlrequest(cdev, c);
}
static struct android_usb_function accessory_function = {
.name = "accessory",
.init = accessory_function_init,
.cleanup = accessory_function_cleanup,
.bind_config = accessory_function_bind_config,
.ctrlrequest = accessory_function_ctrlrequest,
};
#ifdef CONFIG_SND_PCM
static int audio_source_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
struct audio_source_config *config;
config = kzalloc(sizeof(struct audio_source_config), GFP_KERNEL);
if (!config)
return -ENOMEM;
config->card = -1;
config->device = -1;
f->config = config;
return 0;
}
static void audio_source_function_cleanup(struct android_usb_function *f)
{
kfree(f->config);
}
static int audio_source_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct audio_source_config *config = f->config;
return audio_source_bind_config(c, config);
}
static void audio_source_function_unbind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
struct audio_source_config *config = f->config;
config->card = -1;
config->device = -1;
}
static ssize_t audio_source_pcm_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct android_usb_function *f = dev_get_drvdata(dev);
struct audio_source_config *config = f->config;
/* print PCM card and device numbers */
return sprintf(buf, "%d %d\n", config->card, config->device);
}
static DEVICE_ATTR(pcm, S_IRUGO | S_IWUSR, audio_source_pcm_show, NULL);
static struct device_attribute *audio_source_function_attributes[] = {
&dev_attr_pcm,
NULL
};
static struct android_usb_function audio_source_function = {
.name = "audio_source",
.init = audio_source_function_init,
.cleanup = audio_source_function_cleanup,
.bind_config = audio_source_function_bind_config,
.unbind_config = audio_source_function_unbind_config,
.attributes = audio_source_function_attributes,
};
#endif
static int android_uasp_connect_cb(bool connect)
{
/*
* TODO
* We may have to disable gadget till UASP configfs nodes
* are configured which includes mapping LUN with the
* backing file. It is a fundamental difference between
* f_mass_storage and f_tcp. That means UASP can not be
* in default composition.
*
* For now, assume that UASP configfs nodes are configured
* before enabling android gadget. Or cable should be
* reconnected after mapping the LUN.
*
* Also consider making UASP to respond to Host requests when
* Lun is not mapped.
*/
pr_debug("UASP %s\n", connect ? "connect" : "disconnect");
return 0;
}
static int uasp_function_init(struct android_usb_function *f,
struct usb_composite_dev *cdev)
{
return f_tcm_init(&android_uasp_connect_cb);
}
static void uasp_function_cleanup(struct android_usb_function *f)
{
f_tcm_exit();
}
static int uasp_function_bind_config(struct android_usb_function *f,
struct usb_configuration *c)
{
return tcm_bind_config(c);
}
static struct android_usb_function uasp_function = {
.name = "uasp",
.init = uasp_function_init,
.cleanup = uasp_function_cleanup,
.bind_config = uasp_function_bind_config,
};
static struct android_usb_function *supported_functions[] = {
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
&mbim_function,
&ecm_qc_function,
#endif
#ifdef CONFIG_SND_PCM
&audio_function,
#endif
&rmnet_smd_function,
&rmnet_sdio_function,
&rmnet_smd_sdio_function,
&rmnet_function,
&gps_function,
&diag_function,
&qdss_function,
&serial_function,
&adb_function,
&laf_function,
&ccid_function,
&acm_function,
&mtp_function,
&ptp_function,
&rndis_function,
#ifndef CONFIG_USB_G_LGE_ANDROID_NCM
&rndis_qc_function,
#endif
&ecm_function,
&ncm_function,
&mass_storage_function,
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
&cdrom_storage_function,
&charge_only_function,
#endif
&accessory_function,
#ifdef CONFIG_SND_PCM
&audio_source_function,
#endif
&uasp_function,
NULL
};
static void android_cleanup_functions(struct android_usb_function **functions)
{
struct android_usb_function *f;
struct device_attribute **attrs;
struct device_attribute *attr;
while (*functions) {
f = *functions++;
if (f->dev) {
device_destroy(android_class, f->dev->devt);
kfree(f->dev_name);
} else
continue;
if (f->cleanup)
f->cleanup(f);
attrs = f->attributes;
if (attrs) {
while ((attr = *attrs++))
device_remove_file(f->dev, attr);
}
}
}
static int android_init_functions(struct android_usb_function **functions,
struct usb_composite_dev *cdev)
{
struct android_dev *dev = cdev_to_android_dev(cdev);
struct android_usb_function *f;
struct device_attribute **attrs;
struct device_attribute *attr;
int err = 0;
int index = 1; /* index 0 is for android0 device */
for (; (f = *functions++); index++) {
f->dev_name = kasprintf(GFP_KERNEL, "f_%s", f->name);
f->android_dev = NULL;
if (!f->dev_name) {
err = -ENOMEM;
goto err_out;
}
f->dev = device_create(android_class, dev->dev,
MKDEV(0, index), f, f->dev_name);
if (IS_ERR(f->dev)) {
pr_err("%s: Failed to create dev %s", __func__,
f->dev_name);
err = PTR_ERR(f->dev);
f->dev = NULL;
goto err_create;
}
if (f->init) {
err = f->init(f, cdev);
if (err) {
pr_err("%s: Failed to init %s", __func__,
f->name);
goto err_init;
}
}
attrs = f->attributes;
if (attrs) {
while ((attr = *attrs++) && !err)
err = device_create_file(f->dev, attr);
}
if (err) {
pr_err("%s: Failed to create function %s attributes",
__func__, f->name);
goto err_attrs;
}
}
return 0;
err_attrs:
for (attr = *(attrs -= 2); attrs != f->attributes; attr = *(attrs--))
device_remove_file(f->dev, attr);
if (f->cleanup)
f->cleanup(f);
err_init:
device_destroy(android_class, f->dev->devt);
err_create:
f->dev = NULL;
kfree(f->dev_name);
err_out:
android_cleanup_functions(dev->functions);
return err;
}
static int
android_bind_enabled_functions(struct android_dev *dev,
struct usb_configuration *c)
{
struct android_usb_function_holder *f_holder;
struct android_configuration *conf =
container_of(c, struct android_configuration, usb_config);
int ret;
list_for_each_entry(f_holder, &conf->enabled_functions, enabled_list) {
ret = f_holder->f->bind_config(f_holder->f, c);
if (ret) {
pr_err("%s: %s failed", __func__, f_holder->f->name);
return ret;
}
}
return 0;
}
static void
android_unbind_enabled_functions(struct android_dev *dev,
struct usb_configuration *c)
{
struct android_usb_function_holder *f_holder;
struct android_configuration *conf =
container_of(c, struct android_configuration, usb_config);
list_for_each_entry(f_holder, &conf->enabled_functions, enabled_list) {
if (f_holder->f->unbind_config)
f_holder->f->unbind_config(f_holder->f, c);
}
}
static int android_enable_function(struct android_dev *dev,
struct android_configuration *conf,
char *name)
{
struct android_usb_function **functions = dev->functions;
struct android_usb_function *f;
struct android_usb_function_holder *f_holder;
while ((f = *functions++)) {
if (!strcmp(name, f->name)) {
if (f->android_dev && f->android_dev != dev)
pr_err("%s is enabled in other device\n",
f->name);
else {
f_holder = kzalloc(sizeof(*f_holder),
GFP_KERNEL);
if (!f_holder) {
pr_err("Failed to alloc f_holder\n");
return -ENOMEM;
}
f->android_dev = dev;
f_holder->f = f;
list_add_tail(&f_holder->enabled_list,
&conf->enabled_functions);
return 0;
}
}
}
return -EINVAL;
}
/*-------------------------------------------------------------------------*/
/* /sys/class/android_usb/android%d/ interface */
static ssize_t remote_wakeup_show(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct android_configuration *conf;
/*
* Show the wakeup attribute of the first configuration,
* since all configurations have the same wakeup attribute
*/
if (dev->configs_num == 0)
return 0;
conf = list_entry(dev->configs.next,
struct android_configuration,
list_item);
return snprintf(buf, PAGE_SIZE, "%d\n",
!!(conf->usb_config.bmAttributes &
USB_CONFIG_ATT_WAKEUP));
}
static ssize_t remote_wakeup_store(struct device *pdev,
struct device_attribute *attr, const char *buff, size_t size)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct android_configuration *conf;
int enable = 0;
sscanf(buff, "%d", &enable);
pr_debug("android_usb: %s remote wakeup\n",
enable ? "enabling" : "disabling");
list_for_each_entry(conf, &dev->configs, list_item)
if (enable)
conf->usb_config.bmAttributes |=
USB_CONFIG_ATT_WAKEUP;
else
conf->usb_config.bmAttributes &=
~USB_CONFIG_ATT_WAKEUP;
return size;
}
static ssize_t
functions_show(struct device *pdev, struct device_attribute *attr, char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct android_configuration *conf;
struct android_usb_function_holder *f_holder;
char *buff = buf;
mutex_lock(&dev->mutex);
list_for_each_entry(conf, &dev->configs, list_item) {
if (buff != buf)
*(buff-1) = ':';
list_for_each_entry(f_holder, &conf->enabled_functions,
enabled_list)
buff += snprintf(buff, PAGE_SIZE, "%s,",
f_holder->f->name);
}
mutex_unlock(&dev->mutex);
if (buff != buf)
*(buff-1) = '\n';
return buff - buf;
}
static ssize_t
functions_store(struct device *pdev, struct device_attribute *attr,
const char *buff, size_t size)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct list_head *curr_conf = &dev->configs;
struct android_configuration *conf;
char *conf_str;
struct android_usb_function_holder *f_holder;
char *name;
char buf[256], *b;
int err;
mutex_lock(&dev->mutex);
if (dev->enabled) {
mutex_unlock(&dev->mutex);
return -EBUSY;
}
#ifdef CONFIG_USB_G_LGE_ANDROID
dev_info(dev->dev, "request function list: %s\n", buff);
#endif
#if defined CONFIG_USB_G_LGE_ANDROID && defined CONFIG_LGE_PM
if (dev->check_pif) {
dev_info(dev->dev, "pif cable is plugged, not permitted\n");
mutex_unlock(&dev->mutex);
return -EPERM;
}
#endif
/* Clear previous enabled list */
list_for_each_entry(conf, &dev->configs, list_item) {
while (conf->enabled_functions.next !=
&conf->enabled_functions) {
f_holder = list_entry(conf->enabled_functions.next,
typeof(*f_holder),
enabled_list);
f_holder->f->android_dev = NULL;
list_del(&f_holder->enabled_list);
kfree(f_holder);
}
INIT_LIST_HEAD(&conf->enabled_functions);
}
strlcpy(buf, buff, sizeof(buf));
b = strim(buf);
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
dev->check_charge_only = false;
if (!strcmp(b, "charge_only"))
dev->check_charge_only = true;
#endif
while (b) {
conf_str = strsep(&b, ":");
if (conf_str) {
/* If the next not equal to the head, take it */
if (curr_conf->next != &dev->configs)
conf = list_entry(curr_conf->next,
struct android_configuration,
list_item);
else
conf = alloc_android_config(dev);
curr_conf = curr_conf->next;
}
while (conf_str) {
name = strsep(&conf_str, ",");
if (name) {
err = android_enable_function(dev, conf, name);
if (err)
pr_err("android_usb: Cannot enable %s",
name);
}
}
}
/* Free uneeded configurations if exists */
while (curr_conf->next != &dev->configs) {
conf = list_entry(curr_conf->next,
struct android_configuration, list_item);
free_android_config(dev, conf);
}
mutex_unlock(&dev->mutex);
return size;
}
static ssize_t enable_show(struct device *pdev, struct device_attribute *attr,
char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
return snprintf(buf, PAGE_SIZE, "%d\n", dev->enabled);
}
static ssize_t enable_store(struct device *pdev, struct device_attribute *attr,
const char *buff, size_t size)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct usb_composite_dev *cdev = dev->cdev;
struct android_usb_function_holder *f_holder;
struct android_configuration *conf;
int enabled = 0;
bool audio_enabled = false;
static DEFINE_RATELIMIT_STATE(rl, 10*HZ, 1);
if (!cdev)
return -ENODEV;
#ifdef CONFIG_USB_G_LGE_ANDROID
dev_info(dev->dev, "gadget enable(%s)\n", buff);
#endif
#if defined CONFIG_USB_G_LGE_ANDROID && defined CONFIG_LGE_PM
if (dev->check_pif) {
dev_info(dev->dev, "pif cable is plugged, not permitted\n");
return -EPERM;
}
#endif
mutex_lock(&dev->mutex);
sscanf(buff, "%d", &enabled);
if (enabled && !dev->enabled) {
#ifdef CONFIG_USB_LGE_REPOSITION_FACTORY_BIND
#else
/*
* Update values in composite driver's copy of
* device descriptor.
*/
cdev->desc.idVendor = device_desc.idVendor;
cdev->desc.idProduct = device_desc.idProduct;
cdev->desc.bcdDevice = device_desc.bcdDevice;
cdev->desc.bDeviceClass = device_desc.bDeviceClass;
cdev->desc.bDeviceSubClass = device_desc.bDeviceSubClass;
cdev->desc.bDeviceProtocol = device_desc.bDeviceProtocol;
#endif
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
if (dev->check_charge_only) {
cdev->desc.iSerialNumber = 0;
cdev->desc.iProduct = strings_dev[CHARGE_ONLY_STRING_IDX].id;
} else {
cdev->desc.iSerialNumber = strings_dev[STRING_SERIAL_IDX].id;
cdev->desc.iProduct = strings_dev[STRING_PRODUCT_IDX].id;
}
#endif
#ifdef CONFIG_USB_LGE_REPOSITION_FACTORY_BIND
if (!lge_get_laf_mode() && lgeusb_is_factory_mode()) {
dev_info(dev->dev, "pif cable is plugged, bind factory composition\n");
dev->check_pif = true;
android_lge_factory_bind(cdev);
} else {
/*
* Update values in composite driver's copy of
* device descriptor.
*/
cdev->desc.idVendor = device_desc.idVendor;
cdev->desc.idProduct = device_desc.idProduct;
cdev->desc.bcdDevice = device_desc.bcdDevice;
cdev->desc.bDeviceClass = device_desc.bDeviceClass;
cdev->desc.bDeviceSubClass = device_desc.bDeviceSubClass;
cdev->desc.bDeviceProtocol = device_desc.bDeviceProtocol;
}
#endif
#ifdef CONFIG_USB_G_LGE_ANDROID
if (cdev->desc.idVendor == LGE_PIF_VID &&
cdev->desc.idProduct == LGE_PIF_PID) {
cdev->desc.iSerialNumber = 0;
}
#endif
/* Audio dock accessory is unable to enumerate device if
* pull-up is enabled immediately. The enumeration is
* reliable with 100 msec delay.
*/
list_for_each_entry(conf, &dev->configs, list_item)
list_for_each_entry(f_holder, &conf->enabled_functions,
enabled_list) {
if (f_holder->f->enable)
f_holder->f->enable(f_holder->f);
if (!strncmp(f_holder->f->name,
"audio_source", 12))
audio_enabled = true;
}
if (audio_enabled)
msleep(100);
android_enable(dev);
dev->enabled = true;
} else if (!enabled && dev->enabled) {
android_disable(dev);
list_for_each_entry(conf, &dev->configs, list_item)
list_for_each_entry(f_holder, &conf->enabled_functions,
enabled_list) {
if (f_holder->f->disable)
f_holder->f->disable(f_holder->f);
}
dev->enabled = false;
} else if (__ratelimit(&rl)) {
pr_err("android_usb: already %s\n",
dev->enabled ? "enabled" : "disabled");
}
mutex_unlock(&dev->mutex);
return size;
}
static ssize_t pm_qos_show(struct device *pdev,
struct device_attribute *attr, char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
return snprintf(buf, PAGE_SIZE, "%s\n", dev->pm_qos);
}
static ssize_t pm_qos_store(struct device *pdev,
struct device_attribute *attr,
const char *buff, size_t size)
{
struct android_dev *dev = dev_get_drvdata(pdev);
strlcpy(dev->pm_qos, buff, sizeof(dev->pm_qos));
return size;
}
static ssize_t state_show(struct device *pdev, struct device_attribute *attr,
char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
struct usb_composite_dev *cdev = dev->cdev;
char *state = "DISCONNECTED";
unsigned long flags;
if (!cdev)
goto out;
spin_lock_irqsave(&cdev->lock, flags);
if (cdev->config)
state = "CONFIGURED";
else if (dev->connected)
state = "CONNECTED";
spin_unlock_irqrestore(&cdev->lock, flags);
out:
return snprintf(buf, PAGE_SIZE, "%s\n", state);
}
#ifdef CONFIG_USB_G_LGE_ANDROID
static ssize_t fmode_show(struct device *pdev, struct device_attribute *attr,
char *buf)
{
struct android_dev *dev = dev_get_drvdata(pdev);
return snprintf(buf, PAGE_SIZE, "%d\n", dev->check_pif);
}
static ssize_t fmode_store(struct device *pdev, struct device_attribute *attr,
const char *buff, size_t size)
{
struct android_dev *dev = dev_get_drvdata(pdev);
int enabled = 0;
mutex_lock(&dev->mutex);
sscanf(buff, "%d", &enabled);
if(enabled)
dev->check_pif = true;
else
dev->check_pif = false;
mutex_unlock(&dev->mutex);
return size;
}
#endif
#if defined CONFIG_USB_G_LGE_ANDROID && defined CONFIG_LGE_PM
/* if pif cable is plugged, not allow request from user space */
#define DESCRIPTOR_ATTR(field, format_string) \
static ssize_t \
field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
return snprintf(buf, PAGE_SIZE, \
format_string, device_desc.field); \
} \
static ssize_t \
field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
int value; \
struct android_dev *adev = dev_get_drvdata(dev); \
if (adev->check_pif) \
return -EPERM; \
if (sscanf(buf, format_string, &value) == 1) { \
device_desc.field = value; \
return size; \
} \
return -1; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
#define DESCRIPTOR_STRING_ATTR(field, buffer) \
static ssize_t \
field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
return snprintf(buf, PAGE_SIZE, "%s", buffer); \
} \
static ssize_t \
field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
struct android_dev *adev = dev_get_drvdata(dev); \
if (adev->check_pif) \
return -EPERM; \
if (size >= sizeof(buffer)) \
return -EINVAL; \
if (sscanf(buf, "%255s", buffer) == 1) { \
return size; \
} \
return -1; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
#else /* google original */
#define DESCRIPTOR_ATTR(field, format_string) \
static ssize_t \
field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
return snprintf(buf, PAGE_SIZE, \
format_string, device_desc.field); \
} \
static ssize_t \
field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
int value; \
if (sscanf(buf, format_string, &value) == 1) { \
device_desc.field = value; \
return size; \
} \
return -1; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
#define DESCRIPTOR_STRING_ATTR(field, buffer) \
static ssize_t \
field ## _show(struct device *dev, struct device_attribute *attr, \
char *buf) \
{ \
return snprintf(buf, PAGE_SIZE, "%s", buffer); \
} \
static ssize_t \
field ## _store(struct device *dev, struct device_attribute *attr, \
const char *buf, size_t size) \
{ \
if (size >= sizeof(buffer)) \
return -EINVAL; \
strlcpy(buffer, buf, sizeof(buffer)); \
strim(buffer); \
return size; \
} \
static DEVICE_ATTR(field, S_IRUGO | S_IWUSR, field ## _show, field ## _store);
#endif /* CONFIG_USB_G_LGE_ANDROID */
DESCRIPTOR_ATTR(idVendor, "%04x\n")
DESCRIPTOR_ATTR(idProduct, "%04x\n")
DESCRIPTOR_ATTR(bcdDevice, "%04x\n")
DESCRIPTOR_ATTR(bDeviceClass, "%d\n")
DESCRIPTOR_ATTR(bDeviceSubClass, "%d\n")
DESCRIPTOR_ATTR(bDeviceProtocol, "%d\n")
DESCRIPTOR_STRING_ATTR(iManufacturer, manufacturer_string)
DESCRIPTOR_STRING_ATTR(iProduct, product_string)
DESCRIPTOR_STRING_ATTR(iSerial, serial_string)
#ifdef CONFIG_USB_G_LGE_ANDROID
DESCRIPTOR_ATTR(iSerialNumber, "%d\n")
#endif
#ifdef CONFIG_USB_G_LGE_SERIALNO_REDIRECTION
DESCRIPTOR_STRING_ATTR(iSerial_redi, serial_string_redi)
#endif
static DEVICE_ATTR(functions, S_IRUGO | S_IWUSR, functions_show,
functions_store);
static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, enable_show, enable_store);
static DEVICE_ATTR(pm_qos, S_IRUGO | S_IWUSR,
pm_qos_show, pm_qos_store);
static DEVICE_ATTR(state, S_IRUGO, state_show, NULL);
static DEVICE_ATTR(remote_wakeup, S_IRUGO | S_IWUSR,
remote_wakeup_show, remote_wakeup_store);
#ifdef CONFIG_USB_G_LGE_ANDROID
static DEVICE_ATTR(fmode, S_IRUGO | S_IWUSR, fmode_show, fmode_store);
#endif
static struct device_attribute *android_usb_attributes[] = {
&dev_attr_idVendor,
&dev_attr_idProduct,
&dev_attr_bcdDevice,
&dev_attr_bDeviceClass,
&dev_attr_bDeviceSubClass,
&dev_attr_bDeviceProtocol,
&dev_attr_iManufacturer,
&dev_attr_iProduct,
&dev_attr_iSerial,
#ifdef CONFIG_USB_G_LGE_ANDROID
&dev_attr_iSerialNumber,
#endif
#ifdef CONFIG_USB_G_LGE_SERIALNO_REDIRECTION
&dev_attr_iSerial_redi,
#endif
&dev_attr_functions,
&dev_attr_enable,
&dev_attr_pm_qos,
&dev_attr_state,
&dev_attr_remote_wakeup,
#ifdef CONFIG_USB_G_LGE_ANDROID
&dev_attr_fmode,
#endif
NULL
};
/*-------------------------------------------------------------------------*/
/* Composite driver */
#if defined CONFIG_USB_G_LGE_ANDROID && defined CONFIG_LGE_PM
static void android_lge_factory_bind(struct usb_composite_dev *cdev)
{
struct android_dev *dev = cdev_to_android_dev(cdev);
struct list_head *curr_conf = &dev->configs;
struct android_configuration *conf;
struct android_usb_function_holder *f_holder;
char lge_factory_composition[256];
char *conf_str;
char *name, *b;
int ret, err, value;
/* update values in composite driver's copy of device descriptor */
value = lgeusb_get_vendor_id();
if (value < 0)
value = LGE_PIF_VID;
device_desc.idVendor = value;
value = lgeusb_get_factory_pid();
if (value < 0)
value = LGE_PIF_PID;
device_desc.idProduct = value;
value = lgeusb_get_serial_number();
if (value < 0)
value = LGE_PIF_SN;
device_desc.iSerialNumber = value;
/*XXX: should we create sysfs with below 3 field? */
device_desc.bDeviceClass = 2;
device_desc.bDeviceSubClass = 0;
device_desc.bDeviceProtocol = 0;
cdev->desc.idVendor = device_desc.idVendor;
cdev->desc.idProduct = device_desc.idProduct;
cdev->desc.bcdDevice = device_desc.bcdDevice;
cdev->desc.bDeviceClass = device_desc.bDeviceClass;
cdev->desc.bDeviceSubClass = device_desc.bDeviceSubClass;
cdev->desc.bDeviceProtocol = device_desc.bDeviceProtocol;
/*XXX: modem & diag specific configuration */
strncpy(acm_transports, "tty", sizeof(acm_transports));
strlcpy(diag_clients, "diag", sizeof(diag_clients));
/* Clear previous enabled list */
list_for_each_entry(conf, &dev->configs, list_item) {
while (conf->enabled_functions.next !=
&conf->enabled_functions) {
f_holder = list_entry(conf->enabled_functions.next,
typeof(*f_holder),
enabled_list);
f_holder->f->android_dev = NULL;
list_del(&f_holder->enabled_list);
kfree(f_holder);
}
INIT_LIST_HEAD(&conf->enabled_functions);
}
ret = lgeusb_get_factory_composition(lge_factory_composition);
if (ret)
strlcpy(lge_factory_composition, "acm,diag",
sizeof(lge_factory_composition) - 1);
b = strim(lge_factory_composition);
while (b) {
conf_str = strsep(&b, ":");
if (conf_str) {
/* If the next not equal to the head, take it */
if (curr_conf->next != &dev->configs)
conf = list_entry(curr_conf->next,
struct android_configuration,
list_item);
else
conf = alloc_android_config(dev);
curr_conf = curr_conf->next;
}
while (conf_str) {
name = strsep(&conf_str, ",");
if (name) {
err = android_enable_function(dev, conf, name);
if (err)
pr_err("android_usb: Cannot enable %s",
name);
}
}
}
#ifdef CONFIG_USB_LGE_REPOSITION_FACTORY_BIND
/* Free uneeded configurations if exists */
while (curr_conf->next != &dev->configs) {
conf = list_entry(curr_conf->next,
struct android_configuration, list_item);
free_android_config(dev, conf);
}
#else
if (usb_add_config(cdev, &conf->usb_config, android_bind_config))
return;
usb_gadget_connect(cdev->gadget);
dev->enabled = true;
#endif
}
#endif /* CONFIG_USB_G_LGE_ANDROID && CONFIG_LGE_PM */
static int android_bind_config(struct usb_configuration *c)
{
struct android_dev *dev = cdev_to_android_dev(c->cdev);
int ret = 0;
ret = android_bind_enabled_functions(dev, c);
if (ret)
return ret;
return 0;
}
static void android_unbind_config(struct usb_configuration *c)
{
struct android_dev *dev = cdev_to_android_dev(c->cdev);
android_unbind_enabled_functions(dev, c);
}
static int android_bind(struct usb_composite_dev *cdev)
{
struct android_dev *dev;
struct usb_gadget *gadget = cdev->gadget;
struct android_configuration *conf;
int gcnum, id, ret;
#ifdef CONFIG_USB_G_LGE_ANDROID
char lge_product[256];
char lge_manufacturer[256];
#endif
/* Bind to the last android_dev that was probed */
dev = list_entry(android_dev_list.prev, struct android_dev, list_item);
dev->cdev = cdev;
/*
* Start disconnected. Userspace will connect the gadget once
* it is done configuring the functions.
*/
usb_gadget_disconnect(gadget);
/* Init the supported functions only once, on the first android_dev */
if (android_dev_count == 1) {
ret = android_init_functions(dev->functions, cdev);
if (ret)
return ret;
}
/* Allocate string descriptor numbers ... note that string
* contents can be overridden by the composite_dev glue.
*/
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[STRING_MANUFACTURER_IDX].id = id;
device_desc.iManufacturer = id;
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[STRING_PRODUCT_IDX].id = id;
device_desc.iProduct = id;
#ifdef CONFIG_USB_G_LGE_ANDROID
/* Default string as LGE products */
ret = lgeusb_get_manufacturer_name(lge_manufacturer);
if (!ret)
strlcpy(manufacturer_string, lge_manufacturer,
sizeof(manufacturer_string) - 1);
else
strlcpy(manufacturer_string, "LG Electronics Inc.",
sizeof(manufacturer_string) - 1);
ret = lgeusb_get_product_name(lge_product);
if (!ret)
strlcpy(product_string, lge_product, sizeof(product_string) - 1);
else
strlcpy(product_string, "LGE Android Phone",
sizeof(product_string) - 1);
#else
/* Default strings - should be updated by userspace */
strlcpy(manufacturer_string, "Android",
sizeof(manufacturer_string) - 1);
strlcpy(product_string, "Android", sizeof(product_string) - 1);
#endif
strlcpy(serial_string, "0123456789ABCDEF", sizeof(serial_string) - 1);
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[STRING_SERIAL_IDX].id = id;
device_desc.iSerialNumber = id;
#ifdef CONFIG_USB_G_LGE_ANDROID_AUTORUN
id = usb_string_id(cdev);
if (id < 0)
return id;
strings_dev[CHARGE_ONLY_STRING_IDX].id = id;
sprintf(charge_only_string, "USB Charge Only Interface");
#endif
if (gadget_is_otg(cdev->gadget))
list_for_each_entry(conf, &dev->configs, list_item)
conf->usb_config.descriptors = otg_desc;
gcnum = usb_gadget_controller_number(gadget);
if (gcnum >= 0)
device_desc.bcdDevice = cpu_to_le16(0x0200 + gcnum);
else {
pr_warning("%s: controller '%s' not recognized\n",
longname, gadget->name);
device_desc.bcdDevice = __constant_cpu_to_le16(0x9999);
}
#if defined CONFIG_USB_G_LGE_ANDROID && defined CONFIG_LGE_PM
/* XXX:
* Android ICS prohibits to change persist property
* before initialization of persist properties. Therefore,
* we cannot change to factory usb composition at userspace
* when pif cable is plugged.
*/
#ifdef CONFIG_USB_LGE_REPOSITION_FACTORY_BIND
#else
if (!lge_get_laf_mode() && lgeusb_is_factory_mode()) {
dev_info(dev->dev, "pif cable is plugged, bind factory composition\n");
dev->check_pif = true;
android_lge_factory_bind(cdev);
}
#endif
#endif
return 0;
}
static int android_usb_unbind(struct usb_composite_dev *cdev)
{
struct android_dev *dev = cdev_to_android_dev(cdev);
manufacturer_string[0] = '\0';
product_string[0] = '\0';
serial_string[0] = '0';
cancel_work_sync(&dev->work);
android_cleanup_functions(dev->functions);
return 0;
}
static struct usb_composite_driver android_usb_driver = {
.name = "android_usb",
.dev = &device_desc,
.strings = dev_strings,
.unbind = android_usb_unbind,
.max_speed = USB_SPEED_SUPER
};
static int
android_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *c)
{
struct usb_composite_dev *cdev = get_gadget_data(gadget);
struct android_dev *dev = cdev_to_android_dev(cdev);
struct usb_request *req = cdev->req;
struct android_usb_function *f;
struct android_usb_function_holder *f_holder;
struct android_configuration *conf;
int value = -EOPNOTSUPP;
unsigned long flags;
req->zero = 0;
req->complete = composite_setup_complete;
req->length = 0;
gadget->ep0->driver_data = cdev;
list_for_each_entry(conf, &dev->configs, list_item)
list_for_each_entry(f_holder,
&conf->enabled_functions,
enabled_list) {
f = f_holder->f;
if (f->ctrlrequest) {
value = f->ctrlrequest(f, cdev, c);
if (value >= 0)
break;
}
}
#ifdef CONFIG_USB_G_LGE_ANDROID_NCM
if (value < 0)
value = ncm_ctrlrequest(cdev, c);
#endif
/* Special case the accessory function.
* It needs to handle control requests before it is enabled.
*/
if (value < 0)
value = acc_ctrlrequest(cdev, c);
if (value < 0)
value = composite_setup(gadget, c);
spin_lock_irqsave(&cdev->lock, flags);
if (!dev->connected) {
dev->connected = 1;
schedule_work(&dev->work);
} else if (c->bRequest == USB_REQ_SET_CONFIGURATION &&
cdev->config) {
schedule_work(&dev->work);
}
spin_unlock_irqrestore(&cdev->lock, flags);
return value;
}
static void android_disconnect(struct usb_gadget *gadget)
{
struct usb_composite_dev *cdev = get_gadget_data(gadget);
struct android_dev *dev = cdev_to_android_dev(cdev);
unsigned long flags;
composite_disconnect(gadget);
/* accessory HID support can be active while the
accessory function is not actually enabled,
so we need to inform it when we are disconnected.
*/
acc_disconnect();
spin_lock_irqsave(&cdev->lock, flags);
dev->connected = 0;
schedule_work(&dev->work);
spin_unlock_irqrestore(&cdev->lock, flags);
}
static void android_suspend(struct usb_gadget *gadget)
{
struct usb_composite_dev *cdev = get_gadget_data(gadget);
struct android_dev *dev = cdev_to_android_dev(cdev);
unsigned long flags;
spin_lock_irqsave(&cdev->lock, flags);
dev->suspended = 1;
schedule_work(&dev->work);
spin_unlock_irqrestore(&cdev->lock, flags);
composite_suspend(gadget);
}
static void android_resume(struct usb_gadget *gadget)
{
struct usb_composite_dev *cdev = get_gadget_data(gadget);
struct android_dev *dev = cdev_to_android_dev(cdev);
unsigned long flags;
spin_lock_irqsave(&cdev->lock, flags);
dev->suspended = 0;
schedule_work(&dev->work);
spin_unlock_irqrestore(&cdev->lock, flags);
composite_resume(gadget);
}
static int android_create_device(struct android_dev *dev, u8 usb_core_id)
{
struct device_attribute **attrs = android_usb_attributes;
struct device_attribute *attr;
char device_node_name[ANDROID_DEVICE_NODE_NAME_LENGTH];
int err;
/*
* The primary usb core should always have usb_core_id=0, since
* Android user space is currently interested in android0 events.
*/
snprintf(device_node_name, ANDROID_DEVICE_NODE_NAME_LENGTH,
"android%d", usb_core_id);
dev->dev = device_create(android_class, NULL,
MKDEV(0, 0), NULL, device_node_name);
if (IS_ERR(dev->dev))
return PTR_ERR(dev->dev);
dev_set_drvdata(dev->dev, dev);
while ((attr = *attrs++)) {
err = device_create_file(dev->dev, attr);
if (err) {
device_destroy(android_class, dev->dev->devt);
return err;
}
}
return 0;
}
static void android_destroy_device(struct android_dev *dev)
{
struct device_attribute **attrs = android_usb_attributes;
struct device_attribute *attr;
while ((attr = *attrs++))
device_remove_file(dev->dev, attr);
device_destroy(android_class, dev->dev->devt);
}
static struct android_dev *cdev_to_android_dev(struct usb_composite_dev *cdev)
{
struct android_dev *dev = NULL;
/* Find the android dev from the list */
list_for_each_entry(dev, &android_dev_list, list_item) {
if (dev->cdev == cdev)
break;
}
return dev;
}
static struct android_configuration *alloc_android_config
(struct android_dev *dev)
{
struct android_configuration *conf;
conf = kzalloc(sizeof(*conf), GFP_KERNEL);
if (!conf) {
pr_err("%s(): Failed to alloc memory for android conf\n",
__func__);
return ERR_PTR(-ENOMEM);
}
dev->configs_num++;
conf->usb_config.label = dev->name;
conf->usb_config.unbind = android_unbind_config;
conf->usb_config.bConfigurationValue = dev->configs_num;
INIT_LIST_HEAD(&conf->enabled_functions);
list_add_tail(&conf->list_item, &dev->configs);
return conf;
}
static void free_android_config(struct android_dev *dev,
struct android_configuration *conf)
{
list_del(&conf->list_item);
dev->configs_num--;
kfree(conf);
}
static int usb_diag_update_pid_and_serial_num(u32 pid, const char *snum)
{
struct dload_struct local_diag_dload = { 0 };
int *src, *dst, i;
if (!diag_dload) {
pr_debug("%s: unable to update PID and serial_no\n", __func__);
return -ENODEV;
}
pr_debug("%s: dload:%p pid:%x serial_num:%s\n",
__func__, diag_dload, pid, snum);
/* update pid */
local_diag_dload.magic_struct.pid = PID_MAGIC_ID;
local_diag_dload.pid = pid;
/* update serial number */
if (!snum) {
local_diag_dload.magic_struct.serial_num = 0;
memset(&local_diag_dload.serial_number, 0,
SERIAL_NUMBER_LENGTH);
} else {
local_diag_dload.magic_struct.serial_num = SERIAL_NUM_MAGIC_ID;
strlcpy((char *)&local_diag_dload.serial_number, snum,
SERIAL_NUMBER_LENGTH);
}
/* Copy to shared struct (accesses need to be 32 bit aligned) */
src = (int *)&local_diag_dload;
dst = (int *)diag_dload;
for (i = 0; i < sizeof(*diag_dload) / 4; i++)
*dst++ = *src++;
return 0;
}
static int __devinit android_probe(struct platform_device *pdev)
{
struct android_usb_platform_data *pdata;
struct android_dev *android_dev;
struct resource *res;
int ret = 0;
if (pdev->dev.of_node) {
dev_dbg(&pdev->dev, "device tree enabled\n");
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata) {
pr_err("unable to allocate platform data\n");
return -ENOMEM;
}
of_property_read_u32(pdev->dev.of_node,
"qcom,android-usb-swfi-latency",
&pdata->swfi_latency);
pdata->cdrom = of_property_read_bool(pdev->dev.of_node,
"qcom,android-usb-cdrom");
} else {
pdata = pdev->dev.platform_data;
}
if (!android_class) {
android_class = class_create(THIS_MODULE, "android_usb");
if (IS_ERR(android_class))
return PTR_ERR(android_class);
}
android_dev = kzalloc(sizeof(*android_dev), GFP_KERNEL);
if (!android_dev) {
pr_err("%s(): Failed to alloc memory for android_dev\n",
__func__);
ret = -ENOMEM;
goto err_alloc;
}
android_dev->name = pdev->name;
android_dev->disable_depth = 1;
android_dev->functions = supported_functions;
android_dev->configs_num = 0;
INIT_LIST_HEAD(&android_dev->configs);
INIT_WORK(&android_dev->work, android_work);
mutex_init(&android_dev->mutex);
#if defined CONFIG_USB_G_LGE_ANDROID && defined CONFIG_LGE_PM
android_dev->check_pif = false;
#endif
android_dev->pdata = pdata;
list_add_tail(&android_dev->list_item, &android_dev_list);
android_dev_count++;
if (pdata)
composite_driver.usb_core_id = pdata->usb_core_id;
else
composite_driver.usb_core_id = 0; /*To backward compatibility*/
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res) {
diag_dload = devm_ioremap(&pdev->dev, res->start,
resource_size(res));
if (!diag_dload) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err_dev;
}
} else {
dev_dbg(&pdev->dev, "failed to get mem resource\n");
}
ret = android_create_device(android_dev, composite_driver.usb_core_id);
if (ret) {
pr_err("%s(): android_create_device failed\n", __func__);
goto err_dev;
}
ret = usb_composite_probe(&android_usb_driver, android_bind);
if (ret) {
pr_err("%s(): Failed to register android "
"composite driver\n", __func__);
goto err_probe;
}
/* pm qos request to prevent apps idle power collapse */
if (pdata && pdata->swfi_latency)
pm_qos_add_request(&android_dev->pm_qos_req_dma,
PM_QOS_CPU_DMA_LATENCY, PM_QOS_DEFAULT_VALUE);
strlcpy(android_dev->pm_qos, "high", sizeof(android_dev->pm_qos));
return ret;
err_probe:
android_destroy_device(android_dev);
err_dev:
list_del(&android_dev->list_item);
android_dev_count--;
kfree(android_dev);
err_alloc:
if (list_empty(&android_dev_list)) {
class_destroy(android_class);
android_class = NULL;
}
return ret;
}
static int android_remove(struct platform_device *pdev)
{
struct android_dev *dev = NULL;
struct android_usb_platform_data *pdata = pdev->dev.platform_data;
int usb_core_id = 0;
if (pdata)
usb_core_id = pdata->usb_core_id;
/* Find the android dev from the list */
list_for_each_entry(dev, &android_dev_list, list_item) {
if (!dev->pdata)
break; /*To backward compatibility*/
if (dev->pdata->usb_core_id == usb_core_id)
break;
}
if (dev) {
android_destroy_device(dev);
if (pdata && pdata->swfi_latency)
pm_qos_remove_request(&dev->pm_qos_req_dma);
list_del(&dev->list_item);
android_dev_count--;
kfree(dev);
}
if (list_empty(&android_dev_list)) {
class_destroy(android_class);
android_class = NULL;
usb_composite_unregister(&android_usb_driver);
}
return 0;
}
static const struct platform_device_id android_id_table[] __devinitconst = {
{
.name = "android_usb",
},
{
.name = "android_usb_hsic",
},
};
static struct of_device_id usb_android_dt_match[] = {
{ .compatible = "qcom,android-usb",
},
{}
};
static struct platform_driver android_platform_driver = {
.driver = {
.name = "android_usb",
.of_match_table = usb_android_dt_match,
},
.probe = android_probe,
.remove = android_remove,
.id_table = android_id_table,
};
static int __init init(void)
{
int ret;
/* Override composite driver functions */
composite_driver.setup = android_setup;
composite_driver.disconnect = android_disconnect;
composite_driver.suspend = android_suspend;
composite_driver.resume = android_resume;
INIT_LIST_HEAD(&android_dev_list);
android_dev_count = 0;
ret = platform_driver_register(&android_platform_driver);
if (ret) {
pr_err("%s(): Failed to register android"
"platform driver\n", __func__);
}
return ret;
}
module_init(init);
static void __exit cleanup(void)
{
platform_driver_unregister(&android_platform_driver);
}
module_exit(cleanup);
|
slayher/android_kernel_lge_zee
|
drivers/usb/gadget/android.c
|
C
|
gpl-2.0
| 98,767 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_DLP_GooglePrivacyDlpV2RedactImageRequest extends Google_Collection
{
protected $collection_key = 'imageRedactionConfigs';
protected $byteItemType = 'Google_Service_DLP_GooglePrivacyDlpV2ByteContentItem';
protected $byteItemDataType = '';
protected $imageRedactionConfigsType = 'Google_Service_DLP_GooglePrivacyDlpV2ImageRedactionConfig';
protected $imageRedactionConfigsDataType = 'array';
public $includeFindings;
protected $inspectConfigType = 'Google_Service_DLP_GooglePrivacyDlpV2InspectConfig';
protected $inspectConfigDataType = '';
public $locationId;
/**
* @param Google_Service_DLP_GooglePrivacyDlpV2ByteContentItem
*/
public function setByteItem(Google_Service_DLP_GooglePrivacyDlpV2ByteContentItem $byteItem)
{
$this->byteItem = $byteItem;
}
/**
* @return Google_Service_DLP_GooglePrivacyDlpV2ByteContentItem
*/
public function getByteItem()
{
return $this->byteItem;
}
/**
* @param Google_Service_DLP_GooglePrivacyDlpV2ImageRedactionConfig[]
*/
public function setImageRedactionConfigs($imageRedactionConfigs)
{
$this->imageRedactionConfigs = $imageRedactionConfigs;
}
/**
* @return Google_Service_DLP_GooglePrivacyDlpV2ImageRedactionConfig[]
*/
public function getImageRedactionConfigs()
{
return $this->imageRedactionConfigs;
}
public function setIncludeFindings($includeFindings)
{
$this->includeFindings = $includeFindings;
}
public function getIncludeFindings()
{
return $this->includeFindings;
}
/**
* @param Google_Service_DLP_GooglePrivacyDlpV2InspectConfig
*/
public function setInspectConfig(Google_Service_DLP_GooglePrivacyDlpV2InspectConfig $inspectConfig)
{
$this->inspectConfig = $inspectConfig;
}
/**
* @return Google_Service_DLP_GooglePrivacyDlpV2InspectConfig
*/
public function getInspectConfig()
{
return $this->inspectConfig;
}
public function setLocationId($locationId)
{
$this->locationId = $locationId;
}
public function getLocationId()
{
return $this->locationId;
}
}
|
palasthotel/grid-wordpress-box-social
|
vendor/google/apiclient-services/src/Google/Service/DLP/GooglePrivacyDlpV2RedactImageRequest.php
|
PHP
|
gpl-2.0
| 2,690 |
/****************************************************************************
* *
* Project64 - A Nintendo 64 emulator. *
* http://www.pj64-emu.com/ *
* Copyright (C) 2012 Project64. All rights reserved. *
* *
* License: *
* GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html *
* *
****************************************************************************/
#include "stdafx.h"
#include "SettingsType-TempString.h"
CSettingTypeTempString::CSettingTypeTempString(const char * initialValue) :
m_value(initialValue)
{
}
CSettingTypeTempString::~CSettingTypeTempString ( void )
{
}
bool CSettingTypeTempString::Load ( int /*Index*/, bool & /*Value*/ ) const
{
g_Notify->BreakPoint(__FILE__, __LINE__);
return false;
}
bool CSettingTypeTempString::Load ( int /*Index*/, uint32_t & /*Value*/ ) const
{
g_Notify->BreakPoint(__FILE__, __LINE__);
return false;
}
bool CSettingTypeTempString::Load ( int /*Index*/, stdstr & Value ) const
{
Value = m_value;
return true;
}
//return the default values
void CSettingTypeTempString::LoadDefault ( int /*Index*/, bool & /*Value*/ ) const
{
g_Notify->BreakPoint(__FILE__, __LINE__);
}
void CSettingTypeTempString::LoadDefault ( int /*Index*/, uint32_t & /*Value*/ ) const
{
g_Notify->BreakPoint(__FILE__, __LINE__);
}
void CSettingTypeTempString::LoadDefault ( int /*Index*/, stdstr & /*Value*/ ) const
{
g_Notify->BreakPoint(__FILE__, __LINE__);
}
void CSettingTypeTempString::Save ( int /*Index*/, bool /*Value*/ )
{
g_Notify->BreakPoint(__FILE__, __LINE__);
}
void CSettingTypeTempString::Save ( int /*Index*/, uint32_t /*Value*/ )
{
g_Notify->BreakPoint(__FILE__, __LINE__);
}
void CSettingTypeTempString::Save ( int /*Index*/, const stdstr & Value )
{
m_value = Value;
}
void CSettingTypeTempString::Save ( int /*Index*/, const char * Value )
{
m_value = Value;
}
void CSettingTypeTempString::Delete( int /*Index*/ )
{
g_Notify->BreakPoint(__FILE__, __LINE__);
}
|
cxd4/project64
|
Source/Project64-core/Settings/SettingType/SettingsType-TempString.cpp
|
C++
|
gpl-2.0
| 2,397 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.