code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
<style type="text/css">
<!--
.msg {
text-align:left;
color: blue;
display: block;
padding: 5px 0;
}
.emsg {
text-align:left;
color: red;
display: block;
padding: 5px 0;
}
#loader{
visibility:hidden;
}
#f1_error{
font-family: Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight:bold;
color:#FF0000;
}
#f1_ok{
font-family: Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight:bold;
color:#00FF00;
}
#f1_upload_process {
z-index:100;
visibility:hidden;
position:absolute;
margin: 10px 0 0;
width:220px;
}
#f1_upload_process span { display: block; padding-left: 7px; }
-->
</style>
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, msg, src){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span>';
var ed = tinyMCE.get('jform_content'); // get editor instance
var newNode = ed.getDoc().createElement ( "img" ); // create img node
newNode.src = src; // add src attribute
ed.execCommand('mceInsertContent', false, newNode.outerHTML);
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span>';
}
result += '<input type="hidden" name="path_2_upload" value="<?php echo base64_encode(JPATH_ROOT . DS . 'tmp' . DS . session_id() . DS); ?>" />';
result += '<input type="hidden" name="link_2_upload" value="<?php echo base64_encode(JURI::root() . 'tmp/' . session_id() .'/'); ?>" />';
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + '<input name="myfile" type="file" size="30" style="float:left;" /><input type="button" name="submitBtn" id="submitBtn" class="sbtn" value="Upload" style="float: left;" />';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
window.addEvent('domready', function(){
// $$('#submitBtn').addEvent('click', function(e){
document.body.addEvent('click:relay(#submitBtn)', function(e){
var action = '<?php echo JURI::base(); ?>jelibs/ajaxupload/upload.php';
var formAction = $$('form[name="userForm"]').get('action');
$$('form[name="userForm"]').set('target', 'upload_target').set('action', action);
startUpload();
document.userForm.submit();
$$('form[name="userForm"]').set('target', '').set('action', formAction);
});
});
//-->
</script>
<?php
/**
* @version $Id: images2content.php 21097 2011-04-07 15:38:03Z dextercowley $
* @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('JPATH_BASE') or die;
jimport('joomla.html.html');
jimport('joomla.form.formfield');
jimport('joomla.form.helper');
JFormHelper::loadFieldClass('list');
/**
* Bannerclient Field class for the Joomla Framework.
*
* @package Joomla.Administrator
* @subpackage com_banners
* @since 1.6
*/
class JFormFieldFront_Images2Content extends JFormFieldList
{
/**
* The form field type.
*
* @var string
* @since 1.6
*/
protected $type = 'Front_Images2Content';
public function getInput()
{
$html = '<div>';
$html .= '<p id="f1_upload_process"><span>Loading...</span><img src="'.JURI::base().'jelibs/ajaxupload/loader.gif" /><br/></p>
<p id="f1_upload_form" align="center">
<br />
<span style="float: left;">Upload images to content</span>
<br/>
<input name="myfile" type="file" size="30" style="float: left;" />
<input type="hidden" name="path_2_upload" value="'.base64_encode(JPATH_ROOT . DS . 'tmp' . DS . session_id() . DS) .'" />
<input type="hidden" name="link_2_upload" value="'.base64_encode(JURI::root() . 'tmp/' . session_id() . '/') .'" />
<input type="button" name="submitBtn" id="submitBtn" class="sbtn" value="Upload" style="float: left;" />
</p>
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
';
$html .= '<div class="clr"></div></div>';
return $html;
}
}
| ngxuanmui/9trip.vn | administrator/components/com_ntrip/models/fields/front/images2content.php | PHP | gpl-2.0 | 4,610 |
/*****************************************************************************/
/* */
/* Ittiam WPS SOFTWARE */
/* */
/* ITTIAM SYSTEMS PVT LTD, BANGALORE */
/* COPYRIGHT(C) 2011 */
/* */
/* This program is proprietary to Ittiam Systems Private Limited and */
/* is protected under Indian Copyright Law as an unpublished work. Its use */
/* and disclosure is limited by the terms and conditions of a license */
/* agreement. It may not be copied or otherwise reproduced or disclosed to */
/* persons outside the licensee's organization except in accordance with the*/
/* terms and conditions of such an agreement. All copies and */
/* reproductions shall be the property of Ittiam Systems Private Limited and*/
/* must bear this notice in its entirety. */
/* */
/*****************************************************************************/
/*****************************************************************************/
/* */
/* File Name : wps_key.c */
/* */
/* Description : This file contains the functions to generate the */
/* Authentication and Key Wrap Key */
/* */
/* List of Functions : wps_kdf */
/* wps_gen_keys */
/* */
/* Issues / Problems : None */
/* */
/* Revision History : */
/* */
/* DD MM YYYY Author(s) Changes */
/* 25 02 2011 Ittiam Draft */
/* */
/*****************************************************************************/
#ifdef INT_WPS_REG_SUPP
/*****************************************************************************/
/* File Includes */
/*****************************************************************************/
#include "hmac_sha256.h"
#include "dh_key.h"
#include "wps_key.h"
/*****************************************************************************/
/* Static Function Declarations */
/*****************************************************************************/
static void wps_kdf(UWORD8* inp_key, UWORD8* pers_str, UWORD8 pers_str_len,
UWORD8* out_key, UWORD32 total_key_bytes);
/*****************************************************************************/
/* */
/* Function Name : wps_kdf */
/* */
/* Description : This function implements the Key Derivation function */
/* as described in WPS standard version v.1.2.2 */
/* */
/* Inputs : 1) Input Key used for key hashing */
/* 2) Pointer to personalization string */
/* 3) Length of personalization string */
/* 4) Pointer to location where output key needs to be */
/* stored. The output key buffer should be long */
/* enough to store ((Total Output key bytes + SHA256 */
/* hash length -1)/ SHA256 hash length) of bytes i.e */
/* this module output bytes in multiple of SHA256 */
/* hash length. Calling function should take care of */
/* selecting appropriate number of bytes */
/* 5) Required length in bytes of the output key */
/* */
/* Globals : None */
/* */
/* Processing : This function implements the following algorithm */
/* kdf(key, personalization_string, total_key_bits) : */
/* result := "" */
/* iterations = (total_key_bits+prf_digest_size-1)/ */
/* prf_digest_size */
/* for i = 1 to iterations do */
/* result = result || prf(key, i || */
/* personalization_string || total_key_bits)*/
/* return result */
/* The function prf is the keyed hash HMAC-SHA-256 */
/* */
/* Outputs : None */
/* */
/* Returns : Key bits generating using KDF function */
/* */
/* Issues : None */
/* */
/* Revision History: */
/* */
/* DD MM YYYY Author(s) Changes */
/* 24 02 2010 Ittiam Draft */
/* */
/*****************************************************************************/
void wps_kdf(UWORD8* inp_key, UWORD8* pers_str, UWORD8 pers_str_len,
UWORD8* out_key, UWORD32 total_key_bytes)
{
UWORD8 *msg[3];
UWORD8 iter_buff[4], total_key_bits_buff[4];
UWORD16 msg_len[3];
UWORD32 iter, max_iter;
/* use iter as temporary variable to store total number of bits */
iter = total_key_bytes * 8;
max_iter = (total_key_bytes + SHA_256_HASH_LEN - 1) / SHA_256_HASH_LEN;
total_key_bits_buff[3] = (UWORD8)(iter);
total_key_bits_buff[2] = (UWORD8)(iter >> 8);
total_key_bits_buff[1] = (UWORD8)(iter >> 16);
total_key_bits_buff[0] = (UWORD8)(iter >> 24);
msg[0] = iter_buff;
msg_len[0] = sizeof(iter_buff);
msg[1] = pers_str;
msg_len[1] = pers_str_len;
msg[2] = total_key_bits_buff;
msg_len[2] = sizeof(total_key_bits_buff);
/*************************************************************************/
/* This function will generates bytes in multiples of SHA_256_HASH_LEN */
/* calling function to ensure that the out_key has enough space */
/*************************************************************************/
for (iter = 1; iter <= max_iter; ++iter)
{
iter_buff[3] = (UWORD8)(iter);
iter_buff[2] = (UWORD8)(iter >> 8);
iter_buff[1] = (UWORD8)(iter >> 16);
iter_buff[0] = (UWORD8)(iter >> 24);
hmac_sha256(inp_key, SHA_256_HASH_LEN, msg, msg_len,3, out_key);
out_key += SHA_256_HASH_LEN;
}
}
/*****************************************************************************/
/* */
/* Function Name : wps_gen_keys */
/* */
/* Description : This function generates Diffie-Hellman shared secret */
/* key. This key needs to be hashed before it can be used*/
/* */
/* Inputs : 1) Pointer Rxed Public Key (PKe or PKr buffer) */
/* 2) Pointer to Enrollee`s Nonce, N1 */
/* 3) POinter to Registrar`s Nonce, N2 */
/* 4) Pointer to Enrollee`s MAC Address */
/* 5) Pointer to WPS Authentication Key */
/* 6) Pointer to WPS Key Wrap Key */
/* 7) Pointer to DH Private key (A or B) */
/* */
/* Globals : None */
/* */
/* Processing : Using the received public key and local private key */
/* this functions generate the shared secret key = */
/* = (pubic key ^private Key) mod p) where g =2, p is */
/* predefined prime. It then converts the secret key in */
/* byte format. Public key, Private key, secret key and */
/* Prime are all of length WPS_DH_PRIME_LEN_WORD32. */
/* */
/* Outputs : Authentication Key and Key Wrap key */
/* */
/* Returns : SUCCESS/FAILURE */
/* */
/* Issues : None */
/* */
/* Revision History: */
/* */
/* DD MM YYYY Author(s) Changes */
/* 25 02 2011 Ittiam Draft */
/* */
/*****************************************************************************/
STATUS_T wps_gen_keys(UWORD8 *rx_pub_key,
UWORD8 *enr_nonce,
UWORD8 *reg_nonce,
UWORD8 *enr_mac_addr,
UWORD8 *auth_key,
UWORD8 *key_wrap_key,
long_num_struct_t *priv_key_ptr)
{
UWORD8 *msg[3];
UWORD16 msg_len[3];
const UWORD8 pers_str[] = "Wi-Fi Easy and Secure Key Derivation";
/*************************************************************************/
/* Generate pre-hash DH Key = (Public Key ^ Private Key) mod Prime */
/* DH key will be stored in byte format in place of Received Public Key */
/*************************************************************************/
if(FAILURE == wps_gen_ph_dh_key((UWORD32 *)rx_pub_key, priv_key_ptr))
{
return FAILURE;
}
/*************************************************************************/
/* Generate DH Key = sha256(Pre-Hashed DH-Key) and store DH key in place */
/* of pre-hash DH key */
/*************************************************************************/
msg[0] = rx_pub_key;
msg_len[0] = WPS_DH_PRIME_LEN_BYTE;
sha256(msg, msg_len, 1, rx_pub_key);
/*************************************************************************/
/* Generate KDK = HMAC-SHA256(DHKey) (N1 || EnrolleeMAC || N2). Store KDK*/
/* in place of DH key */
/*************************************************************************/
msg[0] = enr_nonce;
msg[1] = enr_mac_addr;
msg[2] = reg_nonce;
msg_len[0] = WPS_NONCE_LEN;
msg_len[1] = MAC_ADDRESS_LEN;
msg_len[2] = WPS_NONCE_LEN;
hmac_sha256(rx_pub_key, SHA_256_HASH_LEN, msg, msg_len, 3, rx_pub_key);
/*************************************************************************/
/* Use key derivation function to generate AuthKey and Key Wrap key using*/
/* key derivation function key. */
/*************************************************************************/
wps_kdf(rx_pub_key, (UWORD8 *)pers_str, (UWORD8)(sizeof(pers_str) -1),
(rx_pub_key + SHA_256_HASH_LEN),
(WPS_AUTH_KEY_LEN + WPS_KEY_WRAP_KEY_LEN + WPS_EMSK_LEN));
/* Copy Auth Key to the WPS persistent memory */
memcpy(auth_key, rx_pub_key + SHA_256_HASH_LEN, WPS_AUTH_KEY_LEN);
/* Copy Key Wrap Key to the WPS persistent memory */
memcpy(key_wrap_key, (rx_pub_key + SHA_256_HASH_LEN + WPS_AUTH_KEY_LEN),
WPS_KEY_WRAP_KEY_LEN);
return SUCCESS;
}
#endif /* INT_WPS_REG_SUPP */
| voltagex/kernel-sprdb2g_gonk4.0_6821 | drivers/net/wireless/trout/mac/src/Library/WPS/Protocols/wps_key.c | C | gpl-2.0 | 14,127 |
/* SPDX-License-Identifier: GPL-2.0-only */
#include <delay.h>
#include <device/mmio.h>
#include <console/console.h>
#include <console/uart.h>
#include <soc/addressmap.h>
#include <soc/otp.h>
/*
* This is a driver for the eMemory EG004K32TQ028XW01 NeoFuse
* One-Time-Programmable (OTP) memory used within the SiFive FU540.
* It is documented in the FU540 manual here:
* https://www.sifive.com/documentation/chips/freedom-u540-c000-manual/
*/
struct sifive_otp_registers {
u32 pa; /* Address input */
u32 paio; /* Program address input */
u32 pas; /* Program redundancy cell selection input */
u32 pce; /* OTP Macro enable input */
u32 pclk; /* Clock input */
u32 pdin; /* Write data input */
u32 pdout; /* Read data output */
u32 pdstb; /* Deep standby mode enable input (active low) */
u32 pprog; /* Program mode enable input */
u32 ptc; /* Test column enable input */
u32 ptm; /* Test mode enable input */
u32 ptm_rep;/* Repair function test mode enable input */
u32 ptr; /* Test row enable input */
u32 ptrim; /* Repair function enable input */
u32 pwe; /* Write enable input (defines program cycle) */
} __packed;
/*
* Read a 32 bit value addressed by its index from the OTP.
* The FU540 stores 4096x32 bit (16KiB) values.
* Index 0x00-0xff are reserved for SiFive internal use. (first 1KiB)
*/
u32 otp_read_word(u16 idx)
{
u32 w;
if (idx >= 0x1000)
die("otp: idx out of bounds");
struct sifive_otp_registers *regs = (void *)(FU540_OTP);
// wake up from stand-by
write32(®s->pdstb, 0x01);
// enable repair function
write32(®s->ptrim, 0x01);
// enable input
write32(®s->pce, 0x01);
// address to read
write32(®s->pa, idx);
// cycle clock to read
write32(®s->pclk, 0x01);
mdelay(1);
write32(®s->pclk, 0x00);
mdelay(1);
w = read32(®s->pdout);
// shut down
write32(®s->pce, 0x00);
write32(®s->ptrim, 0x00);
write32(®s->pdstb, 0x00);
return w;
}
u32 otp_read_serial(void)
{
u32 serial = 0;
u32 serial_n = 0;
for (int i = 0xfe; i > 0; i -= 2) {
serial = otp_read_word(i);
serial_n = otp_read_word(i+1);
if (serial == ~serial_n)
break;
}
return serial;
}
| felixsinger/coreboot | src/soc/sifive/fu540/otp.c | C | gpl-2.0 | 2,193 |
ifeq ($(CONFIG_OF),y)
# Keep at91 dtb files sorted alphabetically for each SoC
# rm9200
dtb-$(CONFIG_ARCH_AT91) += at91rm9200ek.dtb
dtb-$(CONFIG_ARCH_AT91) += mpa1600.dtb
# sam9260
dtb-$(CONFIG_ARCH_AT91) += animeo_ip.dtb
dtb-$(CONFIG_ARCH_AT91) += aks-cdu.dtb
dtb-$(CONFIG_ARCH_AT91) += ethernut5.dtb
dtb-$(CONFIG_ARCH_AT91) += evk-pro3.dtb
dtb-$(CONFIG_ARCH_AT91) += tny_a9260.dtb
dtb-$(CONFIG_ARCH_AT91) += usb_a9260.dtb
# sam9263
dtb-$(CONFIG_ARCH_AT91) += at91sam9263ek.dtb
dtb-$(CONFIG_ARCH_AT91) += tny_a9263.dtb
dtb-$(CONFIG_ARCH_AT91) += usb_a9263.dtb
# sam9g20
dtb-$(CONFIG_ARCH_AT91) += at91sam9g20ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9g20ek_2mmc.dtb
dtb-$(CONFIG_ARCH_AT91) += kizbox.dtb
dtb-$(CONFIG_ARCH_AT91) += tny_a9g20.dtb
dtb-$(CONFIG_ARCH_AT91) += usb_a9g20.dtb
# sam9g45
dtb-$(CONFIG_ARCH_AT91) += at91sam9m10g45ek.dtb
dtb-$(CONFIG_ARCH_AT91) += pm9g45.dtb
# sam9n12
dtb-$(CONFIG_ARCH_AT91) += at91sam9n12ek.dtb
# sam9x5
dtb-$(CONFIG_ARCH_AT91) += at91-ariag25.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9g15ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9g25ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9g35ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9x25ek.dtb
dtb-$(CONFIG_ARCH_AT91) += at91sam9x35ek.dtb
# sama5d3
dtb-$(CONFIG_ARCH_AT91) += sama5d31ek.dtb
dtb-$(CONFIG_ARCH_AT91) += sama5d33ek.dtb
dtb-$(CONFIG_ARCH_AT91) += sama5d34ek.dtb
dtb-$(CONFIG_ARCH_AT91) += sama5d35ek.dtb
dtb-$(CONFIG_ARCH_BCM2835) += bcm2835-rpi-b.dtb
dtb-$(CONFIG_ARCH_BCM) += bcm11351-brt.dtb
dtb-$(CONFIG_ARCH_DAVINCI) += da850-enbw-cmc.dtb \
da850-evm.dtb
dtb-$(CONFIG_ARCH_DOVE) += dove-cm-a510.dtb \
dove-cubox.dtb \
dove-dove-db.dtb
dtb-$(CONFIG_ARCH_EXYNOS) += exynos4210-origen.dtb \
exynos4210-smdkv310.dtb \
exynos4210-trats.dtb \
exynos4210-universal_c210.dtb \
exynos4412-odroidx.dtb \
exynos4412-smdk4412.dtb \
exynos4412-origen.dtb \
exynos5250-arndale.dtb \
exynos5440-sd5v1.dtb \
exynos5250-smdk5250.dtb \
exynos5250-snow.dtb \
exynos5440-ssdk5440.dtb
dtb-$(CONFIG_ARCH_HIGHBANK) += highbank.dtb \
ecx-2000.dtb
dtb-$(CONFIG_ARCH_INTEGRATOR) += integratorap.dtb \
integratorcp.dtb
dtb-$(CONFIG_ARCH_LPC32XX) += ea3250.dtb phy3250.dtb
dtb-$(CONFIG_ARCH_KIRKWOOD) += kirkwood-cloudbox.dtb \
kirkwood-dns320.dtb \
kirkwood-dns325.dtb \
kirkwood-dockstar.dtb \
kirkwood-dreamplug.dtb \
kirkwood-goflexnet.dtb \
kirkwood-guruplug-server-plus.dtb \
kirkwood-ib62x0.dtb \
kirkwood-iconnect.dtb \
kirkwood-iomega_ix2_200.dtb \
kirkwood-is2.dtb \
kirkwood-km_kirkwood.dtb \
kirkwood-lschlv2.dtb \
kirkwood-lsxhl.dtb \
kirkwood-mplcec4.dtb \
kirkwood-netgear_readynas_duo_v2.dtb \
kirkwood-ns2.dtb \
kirkwood-ns2lite.dtb \
kirkwood-ns2max.dtb \
kirkwood-ns2mini.dtb \
kirkwood-nsa310.dtb \
kirkwood-topkick.dtb \
kirkwood-ts219-6281.dtb \
kirkwood-ts219-6282.dtb \
kirkwood-openblocks_a6.dtb
dtb-$(CONFIG_ARCH_MARCO) += marco-evb.dtb
dtb-$(CONFIG_ARCH_MSM) += msm8660-surf.dtb \
msm8960-cdp.dtb
dtb-$(CONFIG_ARCH_MVEBU) += armada-370-db.dtb \
armada-370-mirabox.dtb \
armada-370-rd.dtb \
armada-xp-db.dtb \
armada-xp-gp.dtb \
armada-xp-openblocks-ax3-4.dtb
dtb-$(CONFIG_ARCH_MXC) += \
imx25-karo-tx25.dtb \
imx25-pdk.dtb \
imx27-apf27.dtb \
imx27-apf27dev.dtb \
imx27-pdk.dtb \
imx27-phytec-phycore.dtb \
imx31-bug.dtb \
imx51-apf51.dtb \
imx51-apf51dev.dtb \
imx51-babbage.dtb \
imx53-ard.dtb \
imx53-evk.dtb \
imx53-mba53.dtb \
imx53-qsb.dtb \
imx53-smd.dtb \
imx6dl-sabreauto.dtb \
imx6dl-sabresd.dtb \
imx6dl-wandboard.dtb \
imx6q-arm2.dtb \
imx6q-sabreauto.dtb \
imx6q-sabrelite.dtb \
imx6q-sabresd.dtb \
imx6q-sbc6x.dtb
dtb-$(CONFIG_ARCH_MXS) += imx23-evk.dtb \
imx23-olinuxino.dtb \
imx23-stmp378x_devb.dtb \
imx28-apf28.dtb \
imx28-apf28dev.dtb \
imx28-apx4devkit.dtb \
imx28-cfa10036.dtb \
imx28-cfa10037.dtb \
imx28-cfa10049.dtb \
imx28-evk.dtb \
imx28-m28evk.dtb \
imx28-sps1.dtb \
imx28-tx28.dtb
dtb-$(CONFIG_ARCH_NOMADIK) += ste-nomadik-s8815.dtb
dtb-$(CONFIG_ARCH_OMAP2PLUS) += omap2420-h4.dtb \
omap3430-sdp.dtb \
omap3-beagle.dtb \
omap3-devkit8000.dtb \
omap3-beagle-xm.dtb \
omap3-evm.dtb \
omap3-tobi.dtb \
omap3-igep0020.dtb \
omap3-igep0030.dtb \
omap4-panda.dtb \
omap4-panda-a4.dtb \
omap4-panda-es.dtb \
omap4-var-som.dtb \
omap4-sdp.dtb \
omap5-evm.dtb \
am335x-evm.dtb \
am335x-evmsk.dtb \
am335x-bone.dtb
dtb-$(CONFIG_ARCH_ORION5X) += orion5x-lacie-ethernet-disk-mini-v2.dtb
dtb-$(CONFIG_ARCH_PRIMA2) += prima2-evb.dtb
dtb-$(CONFIG_ARCH_U8500) += snowball.dtb \
hrefprev60.dtb \
hrefv60plus.dtb \
ccu9540.dtb
dtb-$(CONFIG_ARCH_SHMOBILE) += emev2-kzm9d.dtb \
r8a7740-armadillo800eva.dtb \
r8a7778-bockw.dtb \
r8a7779-marzen-reference.dtb \
r8a7790-lager.dtb \
sh73a0-kzm9g.dtb \
sh73a0-kzm9g-reference.dtb \
r8a73a4-ape6evm.dtb \
sh7372-mackerel.dtb
dtb-$(CONFIG_ARCH_SOCFPGA) += socfpga_cyclone5.dtb \
socfpga_vt.dtb
dtb-$(CONFIG_ARCH_SPEAR13XX) += spear1310-evb.dtb \
spear1340-evb.dtb
dtb-$(CONFIG_ARCH_SPEAR3XX)+= spear300-evb.dtb \
spear310-evb.dtb \
spear320-evb.dtb \
spear320-hmi.dtb
dtb-$(CONFIG_ARCH_SPEAR6XX)+= spear600-evb.dtb
dtb-$(CONFIG_ARCH_SUNXI) += \
sun4i-a10-cubieboard.dtb \
sun4i-a10-mini-xplus.dtb \
sun4i-a10-hackberry.dtb \
sun5i-a13-olinuxino.dtb
dtb-$(CONFIG_ARCH_TEGRA) += tegra20-harmony.dtb \
tegra20-iris-512.dtb \
tegra20-medcom-wide.dtb \
tegra20-paz00.dtb \
tegra20-plutux.dtb \
tegra20-seaboard.dtb \
tegra20-tec.dtb \
tegra20-trimslice.dtb \
tegra20-ventana.dtb \
tegra20-whistler.dtb \
tegra30-beaver.dtb \
tegra30-cardhu-a02.dtb \
tegra30-cardhu-a04.dtb \
tegra114-dalmore.dtb \
tegra114-dalmore-e1611-1000-a00-00.dtb \
tegra114-dalmore-e1611-1001-a00-00.dtb \
tegra114-macallan.dtb \
tegra114-roth.dtb \
tegra114-pluto.dtb \
tegra114-pismo.dtb \
tegra124-bonaire_sim.dtb \
tegra124-bonaire.dtb \
tegra124-ardbeg.dtb \
tegra124-ardbeg-a03-00.dtb \
tegra124-laguna.dtb \
tegra124-pm375.dtb \
tegra124-norrin.dtb \
tegra124-loki.dtb \
tegra124-foster.dtb \
tegra124-thor195.dtb \
tegra124-tn8.dtb \
tegra124-tn8-p1761.dtb \
tegra124-tn8-p1761-2gb.dtb \
tegra124-tn8-p1761-battery.dtb \
tegra124-tn8-p1761-battery-2gb.dtb \
tegra124-tn8-aio.dtb \
tegra124-tn8-battery.dtb \
tegra124-tn8-a03-00.dtb \
tegra124-tn8-a03-00-battery.dtb \
tegra124-tn8-a03-01.dtb \
tegra124-tn8-a03-01-battery.dtb \
tegra124-e1782_sku1100.dtb \
tegra124-e1791.dtb \
tegra124-e1922.dtb \
tegra124-e1923.dtb \
tegra124-ardbeg_sata.dtb \
tegra124-vcm30_t124.dtb
dtb-$(CONFIG_ARCH_VERSATILE) += versatile-ab.dtb \
versatile-pb.dtb
dtb-$(CONFIG_ARCH_VEXPRESS) += vexpress-v2p-ca5s.dtb \
vexpress-v2p-ca9.dtb \
vexpress-v2p-ca15-tc1.dtb \
vexpress-v2p-ca15_a7.dtb
dtb-$(CONFIG_ARCH_VIRT) += xenvm-4.2.dtb
dtb-$(CONFIG_ARCH_VT8500) += vt8500-bv07.dtb \
wm8505-ref.dtb \
wm8650-mid.dtb \
wm8850-w70v2.dtb
dtb-$(CONFIG_ARCH_ZYNQ) += zynq-zc702.dtb
targets += dtbs
targets += $(dtb-y)
endif
# *.dtb used to be generated in the directory above. Clean out the
# old build results so people don't accidentally use them.
dtbs: $(addprefix $(obj)/, $(dtb-y))
$(Q)rm -f $(obj)/../*.dtb
clean-files := *.dtb
| btaidm/JetsonTK1-Kernel-Grinch | arch/arm/boot/dts/Makefile | Makefile | gpl-2.0 | 7,102 |
/* -*- C -*-
//C- -------------------------------------------------------------------
//C- DjView4
//C- Copyright (c) 2006 Leon Bottou
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, either version 2 of the license,
//C- or (at your option) any later version. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//C- GNU General Public License for more details.
//C- ------------------------------------------------------------------
*/
/* The following code is derived from program "tiff2pdf"
* whose copyright notice is reproduced below.
* Changes were made to make it independent from the private
* include file tiffiop.h.
*
* +--------------------------------------------------------------------
* | tiff2pdf - converts a TIFF image to a PDF document
* |
* | Copyright (c) 2003 Ross Finlayson
* |
* | Permission to use, copy, modify, distribute, and sell this software and
* | its documentation for any purpose is hereby granted without fee, provided
* | that (i) the above copyright notices and this permission notice appear in
* | all copies of the software and related documentation, and (ii) the name of
* | Ross Finlayson may not be used in any advertising or
* | publicity relating to the software without the specific, prior written
* | permission of Ross Finlayson.
* |
* | THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* | EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* | WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
* |
* | IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR
* | ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* | OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* | WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* | LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* | OF THIS SOFTWARE.
* +--------------------------------------------------------------------
*/
#include "tiff2pdf.h"
#if HAVE_TIFF2PDF
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifndef NULL
# define NULL ((void*)0)
#endif
#ifdef __GNUC__
# define unused __attribute__((unused))
#else
# define unused /**/
#endif
/* -------------------------------------------------- *
Tiff2Pdf declarations
* -------------------------------------------------- */
#define TIFF2PDF_MODULE "tiff2pdf"
#define T2P_VERSION "d"
/* This type is of PDF color spaces. */
typedef enum{
T2P_CS_BILEVEL=0x01, /* Bilevel, black and white */
T2P_CS_GRAY=0x02, /* Single channel */
T2P_CS_RGB=0x04, /* Three channel tristimulus RGB */
T2P_CS_CMYK=0x08, /* Four channel CMYK print inkset */
T2P_CS_LAB=0x10, /* Three channel L*a*b* color space */
T2P_CS_PALETTE=0x1000 /* One of the above with a color map */
, T2P_CS_CALGRAY=0x20 /* Calibrated single channel */
, T2P_CS_CALRGB=0x40 /* Calibrated three channel tristimulus RGB */
, T2P_CS_ICCBASED=0x80 /* ICC profile color specification */
} t2p_cs_t;
/* This type is of PDF compression types. */
typedef enum{
T2P_COMPRESS_NONE=0x00
#ifdef CCITT_SUPPORT
, T2P_COMPRESS_G4=0x01
#endif
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
, T2P_COMPRESS_JPEG=0x02
#endif
#ifdef ZIP_SUPPORT
, T2P_COMPRESS_ZIP=0x04
#endif
} t2p_compress_t;
/* This type is whether TIFF image data can be used in PDF without transcoding. */
typedef enum{
T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */
T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */
} t2p_transcode_t;
/* This type is of information about the data samples of the input image. */
typedef enum{
T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */
T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */
T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */
T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */
T2P_SAMPLE_YCBCR_TO_RGB=0x0008,
T2P_SAMPLE_YCBCR_TO_LAB=0x0010,
T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */
T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */
T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */
T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */
} t2p_sample_t;
/* This type is of error status of the T2P struct. */
typedef enum{
T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */
T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */
} t2p_err_t;
/* This struct defines a logical page of a TIFF. */
typedef struct {
tdir_t page_directory;
uint32 page_number;
ttile_t page_tilecount;
uint32 page_extra;
} T2P_PAGE;
/* This struct defines a PDF rectangle's coordinates. */
typedef struct {
float x1;
float y1;
float x2;
float y2;
float mat[9];
} T2P_BOX;
/* This struct defines a tile of a PDF. */
typedef struct {
T2P_BOX tile_box;
} T2P_TILE;
/* This struct defines information about the tiles on a PDF page. */
typedef struct {
ttile_t tiles_tilecount;
uint32 tiles_tilewidth;
uint32 tiles_tilelength;
uint32 tiles_tilecountx;
uint32 tiles_tilecounty;
uint32 tiles_edgetilewidth;
uint32 tiles_edgetilelength;
T2P_TILE* tiles_tiles;
} T2P_TILES;
/* This struct is the context of a function to generate PDF from a TIFF. */
typedef struct {
t2p_err_t t2p_error;
T2P_PAGE* tiff_pages;
T2P_TILES* tiff_tiles;
tdir_t tiff_pagecount;
uint16 tiff_compression;
uint16 tiff_photometric;
uint16 tiff_fillorder;
uint16 tiff_bitspersample;
uint16 tiff_samplesperpixel;
uint16 tiff_planar;
uint32 tiff_width;
uint32 tiff_length;
float tiff_xres;
float tiff_yres;
uint16 tiff_orientation;
toff_t tiff_dataoffset;
tsize_t tiff_datasize;
TIFFReadWriteProc tiff_readproc;
TIFFReadWriteProc tiff_writeproc;
TIFFSeekProc tiff_seekproc;
uint16 tiff_resunit;
uint16 pdf_centimeters;
uint16 pdf_overrideres;
uint16 pdf_overridepagesize;
float pdf_defaultxres;
float pdf_defaultyres;
float pdf_xres;
float pdf_yres;
float pdf_defaultpagewidth;
float pdf_defaultpagelength;
float pdf_pagewidth;
float pdf_pagelength;
float pdf_imagewidth;
float pdf_imagelength;
T2P_BOX pdf_mediabox;
T2P_BOX pdf_imagebox;
uint16 pdf_majorversion;
uint16 pdf_minorversion;
uint32 pdf_catalog;
uint32 pdf_pages;
uint32 pdf_info;
uint32 pdf_palettecs;
uint16 pdf_fitwindow;
uint32 pdf_startxref;
char* pdf_fileid;
char* pdf_datetime;
char* pdf_creator;
char* pdf_author;
char* pdf_title;
char* pdf_subject;
char* pdf_keywords;
t2p_cs_t pdf_colorspace;
uint16 pdf_colorspace_invert;
uint16 pdf_switchdecode;
uint16 pdf_palettesize;
unsigned char* pdf_palette;
int pdf_labrange[4];
t2p_compress_t pdf_defaultcompression;
uint16 pdf_defaultcompressionquality;
t2p_compress_t pdf_compression;
uint16 pdf_compressionquality;
uint16 pdf_nopassthrough;
t2p_transcode_t pdf_transcode;
t2p_sample_t pdf_sample;
uint32* pdf_xrefoffsets;
uint32 pdf_xrefcount;
tdir_t pdf_page;
#ifdef OJPEG_SUPPORT
tdata_t pdf_ojpegdata;
uint32 pdf_ojpegdatalength;
uint32 pdf_ojpegiflength;
#endif
float tiff_whitechromaticities[2];
float tiff_primarychromaticities[6];
float tiff_referenceblackwhite[2];
float* tiff_transferfunction[3];
int pdf_image_interpolate; /* 0 (default) : do not interpolate,
1 : interpolate */
uint16 tiff_transferfunctioncount;
uint32 pdf_icccs;
uint32 tiff_iccprofilelength;
tdata_t tiff_iccprofile;
/* LB additional fields */
FILE *outputfile;
int outputdisable;
tsize_t outputwritten;
} T2P;
/* These functions are called by main. */
static int tiff2pdf_match_paper_size(float*, float*, char*);
/* These functions are used to generate a PDF from a TIFF. */
static T2P* t2p_init(void);
static void t2p_validate(T2P*);
static tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*);
static void t2p_free(T2P*);
static void t2p_read_tiff_init(T2P*, TIFF*);
static int t2p_cmp_t2p_page(const void*, const void*);
static void t2p_read_tiff_data(T2P*, TIFF*);
static void t2p_read_tiff_size(T2P*, TIFF*);
static void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t);
static int t2p_tile_is_right_edge(T2P_TILES, ttile_t);
static int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t);
static tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*);
static tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t);
#ifdef OJPEG_SUPPORT
static int t2p_process_ojpeg_tables(T2P*, TIFF*);
#endif
#ifdef JPEG_SUPPORT
static int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32);
#endif
static void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32);
static void t2p_write_advance_directory(T2P*, TIFF*);
static tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t);
static tsize_t t2p_sample_realize_palette(T2P*, unsigned char*);
static tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32);
static tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32);
static tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32);
static tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32);
static tsize_t t2p_write_pdf_header(T2P*, TIFF*);
static tsize_t t2p_write_pdf_obj_start(uint32, TIFF*);
static tsize_t t2p_write_pdf_obj_end(TIFF*);
static tsize_t t2p_write_pdf_string(char*, TIFF*);
static tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*);
static tsize_t t2p_write_pdf_stream_start(TIFF*);
static tsize_t t2p_write_pdf_stream_end(TIFF*);
static tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*);
static tsize_t t2p_write_pdf_stream_dict_start(TIFF*);
static tsize_t t2p_write_pdf_stream_dict_end(TIFF*);
static tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*);
static tsize_t t2p_write_pdf_catalog(T2P*, TIFF*);
static tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*);
static void t2p_pdf_currenttime(T2P*);
static void t2p_pdf_tifftime(T2P*, TIFF*);
static tsize_t t2p_write_pdf_pages(T2P*, TIFF*);
static tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*);
static void t2p_compose_pdf_page(T2P*);
static void t2p_compose_pdf_page_orient(T2P_BOX*, uint16);
static void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16);
static tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*);
static tsize_t t2p_write_pdf_transfer(T2P*, TIFF*);
static tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16);
static tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16);
static tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*);
static tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*);
static tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*);
static tsize_t t2p_write_pdf_trailer(T2P*, TIFF*);
/* -------------------------------------------------- *
Replacement for tiffiop functions
* -------------------------------------------------- */
static unused tsize_t
t2pReadFile(TIFF *tif, tdata_t data, tsize_t size)
{
thandle_t client = TIFFClientdata(tif);
TIFFReadWriteProc proc = TIFFGetReadProc(tif);
if (proc)
return proc(client, data, size);
return -1;
}
static unused tsize_t
t2pWriteFile(TIFF *tif, tdata_t data, tsize_t size)
{
thandle_t client = TIFFClientdata(tif);
TIFFReadWriteProc proc = TIFFGetWriteProc(tif);
if (proc)
return proc(client, data, size);
return -1;
}
static unused toff_t
t2pSeekFile(TIFF *tif, toff_t offset, int whence)
{
thandle_t client = TIFFClientdata(tif);
TIFFSeekProc proc = TIFFGetSeekProc(tif);
if (proc)
return proc(client, offset, whence);
return -1;
}
#ifdef TIFFReadFile
# undef TIFFReadFile
#endif
#ifndef TIFFReadFile
# define TIFFReadFile t2pReadFile
#endif
#ifdef TIFFWriteFile
# undef TIFFWriteFile
#endif
#ifndef TIFFWriteFile
# define TIFFWriteFile t2pWriteFile
#endif
#ifdef TIFFSeekFile
# undef TIFFSeekFile
#endif
#ifndef TIFFSeekFile
# define TIFFSeekFile t2pSeekFile
#endif
static void
t2p_disable(TIFF *tif)
{
T2P *t2p = (T2P*) TIFFClientdata(tif);
t2p->outputdisable = 1;
}
static void
t2p_enable(TIFF *tif)
{
T2P *t2p = (T2P*) TIFFClientdata(tif);
t2p->outputdisable = 0;
}
/* -------------------------------------------------- *
Procs for TIFFClientOpen
* -------------------------------------------------- */
static tsize_t
t2p_readproc(thandle_t unused handle, tdata_t unused data , tsize_t unused size)
{
return -1;
}
static tsize_t
t2p_writeproc(thandle_t handle, tdata_t data, tsize_t size)
{
T2P *t2p = (T2P*) handle;
if (t2p->outputdisable <= 0 && t2p->outputfile)
{
tsize_t written = fwrite(data, 1, size, t2p->outputfile);
t2p->outputwritten += written;
return written;
}
return size;
}
static toff_t
t2p_seekproc(thandle_t handle, toff_t offset, int whence)
{
T2P *t2p = (T2P*) handle;
if (t2p->outputdisable <= 0 && t2p->outputfile)
return fseek(t2p->outputfile, offset, whence);
return offset;
}
static int
t2p_closeproc(thandle_t unused handle)
{
return 0;
}
static toff_t
t2p_sizeproc(thandle_t unused handle)
{
return -1;
}
static int
t2p_mapproc(thandle_t unused handle, tdata_t unused *data, toff_t unused *offset)
{
return -1;
}
static void
t2p_unmapproc(thandle_t unused handle, tdata_t unused data, toff_t unused offset)
{
}
/* -------------------------------------------------- *
Ports
* -------------------------------------------------- */
#ifdef WIN32
/*
* Copyright (c) 1987, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that 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.
*/
#if 0
static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95";
__RCSID("$NetBSD: getopt.c,v 1.26 2003/08/07 16:43:40 agc Exp $");
#endif
#include <stdio.h>
#include <string.h>
int opterr = 1, /* if error message should be printed */
optind = 1, /* index into parent argv vector */
optopt, /* character checked for validity */
optreset; /* reset getopt */
char *optarg; /* argument associated with option */
#define BADCH (int)'?'
#define BADARG (int)':'
#define EMSG ""
/*
* getopt --
* Parse argc/argv argument vector.
*/
int
getopt(int argc, char * const argv[], const char *optstring)
{
static char *place = EMSG; /* option letter processing */
char *oli; /* option letter list index */
if (optreset || *place == 0) { /* update scanning pointer */
optreset = 0;
place = argv[optind];
if (optind >= argc || *place++ != '-') {
/* Argument is absent or is not an option */
place = EMSG;
return (-1);
}
optopt = *place++;
if (optopt == '-' && *place == 0) {
/* "--" => end of options */
++optind;
place = EMSG;
return (-1);
}
if (optopt == 0) {
/* Solitary '-', treat as a '-' option
if the program (eg su) is looking for it. */
place = EMSG;
if (strchr(optstring, '-') == NULL)
return -1;
optopt = '-';
}
} else
optopt = *place++;
/* See if option letter is one the caller wanted... */
if (optopt == ':' || (oli = strchr(optstring, optopt)) == NULL) {
if (*place == 0)
++optind;
if (opterr && *optstring != ':')
(void)fprintf(stderr,
"unknown option -- %c\n", optopt);
return (BADCH);
}
/* Does this option need an argument? */
if (oli[1] != ':') {
/* don't need argument */
optarg = NULL;
if (*place == 0)
++optind;
} else {
/* Option-argument is either the rest of this argument or the
entire next argument. */
if (*place)
optarg = place;
else if (argc > ++optind)
optarg = argv[optind];
else {
/* option-argument absent */
place = EMSG;
if (*optstring == ':')
return (BADARG);
if (opterr)
(void)fprintf(stderr,
"option requires an argument -- %c\n",
optopt);
return (BADCH);
}
place = EMSG;
++optind;
}
return (optopt); /* return option letter */
}
#endif
/* -------------------------------------------------- *
Main function
* -------------------------------------------------- */
/*
This is the main function.
The program converts one TIFF file to one PDF file, including multiple page
TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF
files that contain data of TIFF photometric interpretations of bilevel,
grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by
libtiff and PDF.
If you have multiple TIFF files to convert into one PDF file then use tiffcp
or other program to concatenate the files into a multiple page TIFF file.
If the input TIFF file is of huge dimensions (greater than 10000 pixels height
or width) convert the input image to a tiled TIFF if it is not already.
The standard output is standard output. Set the output file name with the
"-o output.pdf" option.
All black and white files are compressed into a single strip CCITT G4 Fax
compressed PDF, unless tiled, where tiled black and white images are
compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support
is assumed.
Color and grayscale data can be compressed using either JPEG compression,
ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set
the compression type using the -j or -z options. JPEG compression support
requires that libtiff be configured with JPEG support, and Zip/Deflate
compression support requires that libtiff is configured with Zip support,
in tiffconf.h. Use only one or the other of -j and -z. The -q option
sets the image compression quality, that is 1-100 with libjpeg JPEG
compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression
predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9.
PNG Group differencing predictor methods are not currently implemented.
If the input TIFF contains single strip CCITT G4 Fax compressed information,
then that is written to the PDF file without transcoding, unless the options
of no compression and no passthrough are set, -d and -n.
If the input TIFF contains JPEG or single strip Zip/Deflate compressed
information, and they are configured, then that is written to the PDF file
without transcoding, unless the options of no compression and no passthrough
are set.
The default page size upon which the TIFF image is placed is determined by
the resolution and extent of the image data. Default values for the TIFF
image resolution can be set using the -x and -y options. The page size can
be set using the -p option for paper size, or -w and -l for paper width and
length, then each page of the TIFF image is centered on its page. The
distance unit for default resolution and page width and length can be set
by the -u option, the default unit is inch.
Various items of the output document information can be set with the -e, -c,
-a, -t, -s, and -k tags. Setting the argument of the option to "" for these
tags causes the relevant document information field to be not written. Some
of the document information values otherwise get their information from the
input TIFF image, the software, author, document name, and image description.
The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using
Zip/Deflate compression.
The Portable Document Format (PDF) specification is copyrighted by Adobe
Systems, Incorporated. Todos derechos reservados.
Here is a listing of the usage example and the options to the tiff2pdf
program that is part of the libtiff distribution. Options followed by
a colon have a required argument.
usage: tiff2pdf [options] input.tif
options:
-o: output to file name
-j compress with JPEG (requires libjpeg configured with libtiff)
-z compress with Zip/Deflate (requires zlib configured with libtiff)
-q: compression quality
-n no compressed data passthrough
-d do not compress (decompress)
-i invert colors
-u: set distance unit, 'i' for inch, 'm' for centimeter
-x: set x resolution default
-y: set y resolution default
-w: width in units
-l: length in units
-r: 'd' for resolution default, 'o' for resolution override
-p: paper size, eg "letter", "legal", "A4"
-f set PDF "Fit Window" user preference
-b set PDF "Interpolate" user preference
-e: date, overrides image or current date/time default, YYYYMMDDHHMMSS
-c: creator, overrides image software default
-a: author, overrides image artist default
-t: title, overrides image document name default
-s: subject, overrides image image description default
-k: keywords
-h usage
examples:
tiff2pdf -o output.pdf input.tiff
The above example would generate the file output.pdf from input.tiff.
tiff2pdf input.tiff
The above example would generate PDF output from input.tiff and write it
to standard output.
tiff2pdf -j -p letter -o output.pdf input.tiff
The above example would generate the file output.pdf from input.tiff,
putting the image pages on a letter sized page, compressing the output
with JPEG.
Please report bugs through:
http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff
See also libtiff.3t, tiffcp.
*/
int
tiff2pdf(TIFF *input, FILE *outputfile, int argc, const char **argv)
{
extern char *optarg;
const char *outfilename = "<null>";
T2P *t2p = NULL;
TIFF *output = NULL;
int c;
/* T2P */
t2p = t2p_init();
if (t2p == NULL){
TIFFError(TIFF2PDF_MODULE, "Can't initialize context");
goto fail;
}
/* Options */
while (argv &&
(c = getopt(argc, (char**)argv,
"o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbh")) != -1) {
switch (c) {
case 'o':
outfilename = optarg;
break;
#ifdef JPEG_SUPPORT
case 'j':
t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG;
break;
#endif
#ifdef ZIP_SUPPORT
case 'z':
t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP;
break;
#endif
case 'q':
t2p->pdf_defaultcompressionquality=atoi(optarg);
break;
case 'n':
t2p->pdf_nopassthrough=1;
break;
case 'd':
t2p->pdf_defaultcompression=T2P_COMPRESS_NONE;
break;
case 'u':
if(optarg[0]=='m'){
t2p->pdf_centimeters=1;
}
break;
case 'x':
t2p->pdf_defaultxres =
(float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'y':
t2p->pdf_defaultyres =
(float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'w':
t2p->pdf_overridepagesize=1;
t2p->pdf_defaultpagewidth =
((float)atof(optarg) * 72.0F) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'l':
t2p->pdf_overridepagesize=1;
t2p->pdf_defaultpagelength =
((float)atof(optarg) * 72.0F) / (t2p->pdf_centimeters?2.54F:1.0F);
break;
case 'r':
if(optarg[0]=='o'){
t2p->pdf_overrideres=1;
}
break;
case 'p':
if(tiff2pdf_match_paper_size(&(t2p->pdf_defaultpagewidth),
&(t2p->pdf_defaultpagelength),
optarg)){
t2p->pdf_overridepagesize=1;
} else {
TIFFWarning(TIFF2PDF_MODULE,
"Unknown paper size %s, ignoring option",
optarg);
}
break;
case 'i':
t2p->pdf_colorspace_invert=1;
break;
case 'f':
t2p->pdf_fitwindow=1;
break;
case 'e':
t2p->pdf_datetime = (char*)_TIFFmalloc(17);
if(t2p->pdf_datetime){
if(strlen(optarg)==0){
t2p->pdf_datetime[0]=0;
} else {
if(strlen(optarg)>14){optarg[14]=0;}
t2p->pdf_datetime[0]='D';
t2p->pdf_datetime[1]=':';
strcpy(&(t2p->pdf_datetime[2]), optarg);
}
}
break;
case 'c':
t2p->pdf_creator = (char *)_TIFFmalloc(strlen(optarg) + 1);
if(t2p->pdf_creator){
strcpy(t2p->pdf_creator, optarg);
t2p->pdf_creator[strlen(optarg)]=0;
}
break;
case 'a':
t2p->pdf_author = (char *)_TIFFmalloc(strlen(optarg) + 1);
if(t2p->pdf_author){
strcpy(t2p->pdf_author, optarg);
t2p->pdf_author[strlen(optarg)]=0;
}
break;
case 't':
t2p->pdf_title= (char*)_TIFFmalloc(strlen(optarg)+1);
if(t2p->pdf_title){
strcpy(t2p->pdf_title, optarg);
t2p->pdf_title[strlen(optarg)]=0;
}
break;
case 's':
t2p->pdf_subject= (char*)_TIFFmalloc(strlen(optarg)+1);
if(t2p->pdf_subject){
strcpy(t2p->pdf_subject, optarg);
t2p->pdf_subject[strlen(optarg)]=0;
}
break;
case 'k':
t2p->pdf_keywords= (char*)_TIFFmalloc(strlen(optarg)+1);
if(t2p->pdf_keywords){
strcpy(t2p->pdf_keywords, optarg);
t2p->pdf_keywords[strlen(optarg)]=0;
}
break;
case 'b':
t2p->pdf_image_interpolate = 1;
break;
}
}
/* Output */
t2p->outputdisable = 0;
t2p->outputfile = outputfile;
output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p,
t2p_readproc, t2p_writeproc, t2p_seekproc,
t2p_closeproc, t2p_sizeproc,
t2p_mapproc, t2p_unmapproc );
if (output == NULL){
TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor");
goto fail;
}
/* Validate */
t2p_validate(t2p);
TIFFSeekFile(output, (toff_t) 0, SEEK_SET);
/* Write */
t2p_write_pdf(t2p, input, output);
if(t2p->t2p_error != 0){
TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file");
goto fail;
}
if (output != NULL)
TIFFClose(output);
if (t2p != NULL)
t2p_free(t2p);
return(EXIT_SUCCESS);
fail:
if (output != NULL)
TIFFClose(output);
if (t2p != NULL)
t2p_free(t2p);
return(EXIT_FAILURE);
}
static int
tiff2pdf_match_paper_size(float* width, float* length, char* papersize)
{
int i=0;
int len=0;
const char* sizes[]={
"LETTER", "A4", "LEGAL",
"EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID",
"A", "B", "C", "D", "E", "F", "G", "H", "J", "K",
"A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0",
"2A0", "4A0", "2A", "4A",
"B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0",
"JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4",
"JISB3", "JISB2", "JISB1", "JISB0",
"C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0",
"RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0",
"A3EXTRA", "A4EXTRA",
"STATEMENT", "FOLIO", "QUARTO",
NULL
} ;
const int widths[]={
612, 595, 612,
522, 612,612,792,792,
612,792,1224,1584,2448,2016,792,2016,2448,2880,
74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768,
88,125,176,249,354,499,709,1001,1417,2004,2835,
91,128,181,258,363,516,729,1032,1460,2064,2920,
79,113,162,230,323,459,649,918,1298,1298,2599,
1219,1729,2438,638,907,1276,1814,2551,
914,667,
396, 612, 609,
0
};
const int lengths[]={
792,842,1008,
756,792,1008,1224,1224,
792,1224,1584,2448,3168,2880,6480,10296,12672,10296,
105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741,
125,176,249,354,499,709,1001,1417,2004,2835,4008,
128,181,258,363,516,729,1032,1460,2064,2920,4127,
113,162,230,323,459,649,918,1298,1837,1837,3677,
1729,2438,3458,907,1276,1814,2551,3628,
1262,914,
612, 936, 780,
0
};
len=strlen(papersize);
for(i=0;i<len;i++){
papersize[i]=toupper(papersize[i]);
}
for(i=0;sizes[i]!=NULL; i++){
if (strcmp( (const char*)papersize, sizes[i])==0){
*width=(float)widths[i];
*length=(float)lengths[i];
return(1);
}
}
return(0);
}
/* -------------------------------------------------- *
Tiff2Pdf proper with minor changes
* -------------------------------------------------- */
/*
This function allocates and initializes a T2P context struct pointer.
*/
static T2P* t2p_init()
{
T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P));
if(t2p==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_init",
(int)sizeof(T2P));
return( (T2P*) NULL );
}
_TIFFmemset(t2p, 0x00, sizeof(T2P));
t2p->pdf_majorversion=1;
t2p->pdf_minorversion=1;
t2p->pdf_defaultxres=300.0;
t2p->pdf_defaultyres=300.0;
t2p->pdf_defaultpagewidth=612.0;
t2p->pdf_defaultpagelength=792.0;
t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */
t2p->outputfile = NULL;
t2p->outputdisable = 0;
t2p->outputwritten = 0;
return(t2p);
}
/*
This function frees a T2P context struct pointer and any allocated data fields of it.
*/
static void t2p_free(T2P* t2p){
int i=0;
if(t2p != NULL){
if(t2p->pdf_xrefoffsets != NULL){
_TIFFfree( (tdata_t) t2p->pdf_xrefoffsets);
}
if(t2p->tiff_pages != NULL){
_TIFFfree( (tdata_t) t2p->tiff_pages);
}
for(i=0;i<t2p->tiff_pagecount;i++){
if(t2p->tiff_tiles[i].tiles_tiles != NULL){
_TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles);
}
}
if(t2p->tiff_tiles != NULL){
_TIFFfree( (tdata_t) t2p->tiff_tiles);
}
if(t2p->pdf_palette != NULL){
_TIFFfree( (tdata_t) t2p->pdf_palette);
}
if(t2p->pdf_fileid != NULL){
_TIFFfree( (tdata_t) t2p->pdf_fileid);
}
if(t2p->pdf_datetime != NULL){
_TIFFfree( (tdata_t) t2p->pdf_datetime);
}
if(t2p->pdf_creator != NULL){
_TIFFfree( (tdata_t) t2p->pdf_creator);
}
if(t2p->pdf_author != NULL){
_TIFFfree( (tdata_t) t2p->pdf_author);
}
if(t2p->pdf_title != NULL){
_TIFFfree( (tdata_t) t2p->pdf_title);
}
if(t2p->pdf_subject != NULL){
_TIFFfree( (tdata_t) t2p->pdf_subject);
}
if(t2p->pdf_keywords != NULL){
_TIFFfree( (tdata_t) t2p->pdf_keywords);
}
#ifdef OJPEG_SUPPORT
if(t2p->pdf_ojpegdata != NULL){
_TIFFfree( (tdata_t) t2p->pdf_ojpegdata);
}
#endif
_TIFFfree( (tdata_t) t2p );
}
return;
}
/*
This function validates the values of a T2P context struct pointer
before calling t2p_write_pdf with it.
*/
static void t2p_validate(T2P* t2p){
#ifdef JPEG_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
if(t2p->pdf_defaultcompressionquality<100 ||
t2p->pdf_defaultcompressionquality<1){
t2p->pdf_defaultcompressionquality=0;
}
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){
switch (t2p->pdf_defaultcompressionquality){
case 1: case 10: case 11: case 12: case 13: case 14: case 15:
case 101: case 110: case 111: case 112: case 113: case 114: case 115:
case 201: case 210: case 211: case 212: case 213: case 214: case 215:
case 301: case 310: case 311: case 312: case 313: case 314: case 315:
case 401: case 410: case 411: case 412: case 413: case 414: case 415:
case 501: case 510: case 511: case 512: case 513: case 514: case 515:
case 601: case 610: case 611: case 612: case 613: case 614: case 615:
case 701: case 710: case 711: case 712: case 713: case 714: case 715:
case 801: case 810: case 811: case 812: case 813: case 814: case 815:
case 901: case 910: case 911: case 912: case 913: case 914: case 915:
break;
default:
t2p->pdf_defaultcompressionquality=0;
}
if(t2p->pdf_defaultcompressionquality%100 !=0){
TIFFError(
TIFF2PDF_MODULE,
"PNG Group predictor differencing not implemented, assuming compression quality %u",
t2p->pdf_defaultcompressionquality);
}
t2p->pdf_defaultcompressionquality%=100;
if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;}
}
#endif
(void)0;
return;
}
/*
This function scans the input TIFF file for pages. It attempts
to determine which IFD's of the TIFF file contain image document
pages. For each, it gathers some information that has to do
with the output of the PDF document as a whole.
*/
static void t2p_read_tiff_init(T2P* t2p, TIFF* input){
tdir_t directorycount=0;
tdir_t i=0;
uint16 pagen=0;
uint16 paged=0;
uint16 xuint16=0;
directorycount=TIFFNumberOfDirectories(input);
t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(directorycount * sizeof(T2P_PAGE));
if(t2p->tiff_pages==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for tiff_pages array, %s",
directorycount * (int)sizeof(T2P_PAGE),
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
_TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE));
t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(directorycount * sizeof(T2P_TILES));
if(t2p->tiff_tiles==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for tiff_tiles array, %s",
directorycount * (int)sizeof(T2P_TILES),
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
_TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES));
for(i=0;i<directorycount;i++){
uint32 subfiletype = 0;
if(!TIFFSetDirectory(input, i)){
TIFFError(
TIFF2PDF_MODULE,
"Can't set directory %u of input file %s",
i,
TIFFFileName(input));
return;
}
if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){
if((pagen>paged) && (paged != 0)){
t2p->tiff_pages[t2p->tiff_pagecount].page_number =
paged;
} else {
t2p->tiff_pages[t2p->tiff_pagecount].page_number =
pagen;
}
goto ispage2;
}
if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){
if ( ((subfiletype & FILETYPE_PAGE) != 0)
|| (subfiletype == 0)){
goto ispage;
} else {
goto isnotpage;
}
}
if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){
if ((subfiletype == OFILETYPE_IMAGE)
|| (subfiletype == OFILETYPE_PAGE)
|| (subfiletype == 0) ){
goto ispage;
} else {
goto isnotpage;
}
}
ispage:
t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount;
ispage2:
t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i;
if(TIFFIsTiled(input)){
t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount =
TIFFNumberOfTiles(input);
}
t2p->tiff_pagecount++;
isnotpage:
(void)0;
}
qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount,
sizeof(T2P_PAGE), t2p_cmp_t2p_page);
for(i=0;i<t2p->tiff_pagecount;i++){
t2p->pdf_xrefcount += 5;
TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory );
if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16)
&& (xuint16==PHOTOMETRIC_PALETTE))
|| TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) {
t2p->tiff_pages[i].page_extra++;
t2p->pdf_xrefcount++;
}
#ifdef ZIP_SUPPORT
if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) {
if( (xuint16== COMPRESSION_DEFLATE ||
xuint16== COMPRESSION_ADOBE_DEFLATE) &&
((t2p->tiff_pages[i].page_tilecount != 0)
|| TIFFNumberOfStrips(input)==1) &&
(t2p->pdf_nopassthrough==0) ){
if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;}
}
}
#endif
if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION,
&(t2p->tiff_transferfunction[0]),
&(t2p->tiff_transferfunction[1]),
&(t2p->tiff_transferfunction[2]))) {
if(t2p->tiff_transferfunction[1] !=
t2p->tiff_transferfunction[0]) {
t2p->tiff_transferfunctioncount = 3;
t2p->tiff_pages[i].page_extra += 4;
t2p->pdf_xrefcount += 4;
} else {
t2p->tiff_transferfunctioncount = 1;
t2p->tiff_pages[i].page_extra += 2;
t2p->pdf_xrefcount += 2;
}
if(t2p->pdf_minorversion < 2)
t2p->pdf_minorversion = 2;
} else {
t2p->tiff_transferfunctioncount=0;
}
if( TIFFGetField(
input,
TIFFTAG_ICCPROFILE,
&(t2p->tiff_iccprofilelength),
&(t2p->tiff_iccprofile)) != 0){
t2p->tiff_pages[i].page_extra++;
t2p->pdf_xrefcount++;
if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;}
}
t2p->tiff_tiles[i].tiles_tilecount=
t2p->tiff_pages[i].page_tilecount;
if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0)
&& (xuint16 == PLANARCONFIG_SEPARATE ) ){
TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16);
t2p->tiff_tiles[i].tiles_tilecount/= xuint16;
}
if( t2p->tiff_tiles[i].tiles_tilecount > 0){
t2p->pdf_xrefcount +=
(t2p->tiff_tiles[i].tiles_tilecount -1)*2;
TIFFGetField(input,
TIFFTAG_TILEWIDTH,
&( t2p->tiff_tiles[i].tiles_tilewidth) );
TIFFGetField(input,
TIFFTAG_TILELENGTH,
&( t2p->tiff_tiles[i].tiles_tilelength) );
t2p->tiff_tiles[i].tiles_tiles =
(T2P_TILE*) _TIFFmalloc(
t2p->tiff_tiles[i].tiles_tilecount
* sizeof(T2P_TILE) );
if( t2p->tiff_tiles[i].tiles_tiles == NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_read_tiff_init, %s",
t2p->tiff_tiles[i].tiles_tilecount * (int)sizeof(T2P_TILE),
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
}
return;
}
/*
This function is used by qsort to sort a T2P_PAGE* array of page structures by page number.
*/
static int t2p_cmp_t2p_page(const void* e1, const void* e2){
return( ((T2P_PAGE*)e1)->page_number - ((T2P_PAGE*)e2)->page_number );
}
/*
This function sets the input directory to the directory of a given
page and determines information about the image. It checks
the image characteristics to determine if it is possible to convert
the image data into a page of PDF output, setting values of the T2P
struct for this page. It determines what color space is used in
the output PDF to represent the image.
It determines if the image can be converted as raw data without
requiring transcoding of the image data.
*/
static void t2p_read_tiff_data(T2P* t2p, TIFF* input){
int i=0;
uint16* r;
uint16* g;
uint16* b;
uint16* a;
uint16 xuint16;
uint16* xuint16p;
float* xfloatp;
t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
t2p->pdf_sample = T2P_SAMPLE_NOTHING;
t2p->pdf_switchdecode = t2p->pdf_colorspace_invert;
TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory);
TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width));
if(t2p->tiff_width == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with zero width",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length));
if(t2p->tiff_length == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with zero length",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with no compression tag",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with compression type %u: not configured",
TIFFFileName(input),
t2p->tiff_compression
);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample));
switch(t2p->tiff_bitspersample){
case 1:
case 2:
case 4:
case 8:
break;
case 0:
TIFFWarning(
TIFF2PDF_MODULE,
"Image %s has 0 bits per sample, assuming 1",
TIFFFileName(input));
t2p->tiff_bitspersample=1;
break;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with %u bits per sample",
TIFFFileName(input),
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel));
if(t2p->tiff_samplesperpixel>4){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(t2p->tiff_samplesperpixel==0){
TIFFWarning(
TIFF2PDF_MODULE,
"Image %s has 0 samples per pixel, assuming 1",
TIFFFileName(input));
t2p->tiff_samplesperpixel=1;
}
if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){
switch(xuint16){
case 0:
case 1:
case 4:
break;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with sample format %u",
TIFFFileName(input),
xuint16);
t2p->t2p_error = T2P_ERR_ERROR;
return;
break;
}
}
TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder));
if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with no photometric interpretation tag",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
switch(t2p->tiff_photometric){
case PHOTOMETRIC_MINISWHITE:
case PHOTOMETRIC_MINISBLACK:
if (t2p->tiff_bitspersample==1){
t2p->pdf_colorspace=T2P_CS_BILEVEL;
if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){
t2p->pdf_switchdecode ^= 1;
}
} else {
t2p->pdf_colorspace=T2P_CS_GRAY;
if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){
t2p->pdf_switchdecode ^= 1;
}
}
break;
case PHOTOMETRIC_RGB:
t2p->pdf_colorspace=T2P_CS_RGB;
if(t2p->tiff_samplesperpixel == 3){
break;
}
if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){
if(xuint16==1)
goto photometric_palette;
}
if(t2p->tiff_samplesperpixel > 3) {
if(t2p->tiff_samplesperpixel == 4) {
t2p->pdf_colorspace = T2P_CS_RGB;
if(TIFFGetField(input,
TIFFTAG_EXTRASAMPLES,
&xuint16, &xuint16p)
&& xuint16 == 1) {
if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){
t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB;
break;
}
if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){
t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB;
break;
}
TIFFWarning(
TIFF2PDF_MODULE,
"RGB image %s has 4 samples per pixel, assuming RGBA",
TIFFFileName(input));
break;
}
t2p->pdf_colorspace=T2P_CS_CMYK;
t2p->pdf_switchdecode ^= 1;
TIFFWarning(
TIFF2PDF_MODULE,
"RGB image %s has 4 samples per pixel, assuming inverse CMYK",
TIFFFileName(input));
break;
} else {
TIFFError(
TIFF2PDF_MODULE,
"No support for RGB image %s with %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
break;
}
} else {
TIFFError(
TIFF2PDF_MODULE,
"No support for RGB image %s with %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
break;
}
case PHOTOMETRIC_PALETTE:
photometric_palette:
if(t2p->tiff_samplesperpixel!=1){
TIFFError(
TIFF2PDF_MODULE,
"No support for palettized image %s with not one sample per pixel",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE;
t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample;
if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){
TIFFError(
TIFF2PDF_MODULE,
"Palettized image %s has no color map",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(t2p->pdf_palette != NULL){
_TIFFfree(t2p->pdf_palette);
t2p->pdf_palette=NULL;
}
t2p->pdf_palette = (unsigned char*)
_TIFFmalloc(t2p->pdf_palettesize*3);
if(t2p->pdf_palette==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_read_tiff_image, %s",
t2p->pdf_palettesize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
for(i=0;i<t2p->pdf_palettesize;i++){
t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8);
t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8);
t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8);
}
t2p->pdf_palettesize *= 3;
break;
case PHOTOMETRIC_SEPARATED:
if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){
if(xuint16==1){
goto photometric_palette_cmyk;
}
}
if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){
if(xuint16 != INKSET_CMYK){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s because its inkset is not CMYK",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
if(t2p->tiff_samplesperpixel==4){
t2p->pdf_colorspace=T2P_CS_CMYK;
} else {
TIFFError(
TIFF2PDF_MODULE,
"No support for %s because it has %u samples per pixel",
TIFFFileName(input),
t2p->tiff_samplesperpixel);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
break;
photometric_palette_cmyk:
if(t2p->tiff_samplesperpixel!=1){
TIFFError(
TIFF2PDF_MODULE,
"No support for palettized CMYK image %s with not one sample per pixel",
TIFFFileName(input) );
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE;
t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample;
if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){
TIFFError(
TIFF2PDF_MODULE,
"Palettized image %s has no color map",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(t2p->pdf_palette != NULL){
_TIFFfree(t2p->pdf_palette);
t2p->pdf_palette=NULL;
}
t2p->pdf_palette = (unsigned char*)
_TIFFmalloc(t2p->pdf_palettesize*4);
if(t2p->pdf_palette==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_read_tiff_image, %s",
t2p->pdf_palettesize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
for(i=0;i<t2p->pdf_palettesize;i++){
t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8);
t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8);
t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8);
t2p->pdf_palette[(i*4)+2]= (unsigned char) (a[i]>>8);
}
t2p->pdf_palettesize *= 4;
break;
case PHOTOMETRIC_YCBCR:
t2p->pdf_colorspace=T2P_CS_RGB;
if(t2p->tiff_samplesperpixel==1){
t2p->pdf_colorspace=T2P_CS_GRAY;
t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK;
break;
}
t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB;
#ifdef JPEG_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
t2p->pdf_sample=T2P_SAMPLE_NOTHING;
}
#endif
break;
case PHOTOMETRIC_CIELAB:
t2p->pdf_labrange[0]= -127;
t2p->pdf_labrange[1]= 127;
t2p->pdf_labrange[2]= -127;
t2p->pdf_labrange[3]= 127;
t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
t2p->pdf_colorspace=T2P_CS_LAB;
break;
case PHOTOMETRIC_ICCLAB:
t2p->pdf_labrange[0]= 0;
t2p->pdf_labrange[1]= 255;
t2p->pdf_labrange[2]= 0;
t2p->pdf_labrange[3]= 255;
t2p->pdf_colorspace=T2P_CS_LAB;
break;
case PHOTOMETRIC_ITULAB:
t2p->pdf_labrange[0]=-85;
t2p->pdf_labrange[1]=85;
t2p->pdf_labrange[2]=-75;
t2p->pdf_labrange[3]=124;
t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED;
t2p->pdf_colorspace=T2P_CS_LAB;
break;
case PHOTOMETRIC_LOGL:
case PHOTOMETRIC_LOGLUV:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with photometric interpretation LogL/LogLuv",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with photometric interpretation %u",
TIFFFileName(input),
t2p->tiff_photometric);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){
switch(t2p->tiff_planar){
case 0:
TIFFWarning(
TIFF2PDF_MODULE,
"Image %s has planar configuration 0, assuming 1",
TIFFFileName(input));
t2p->tiff_planar=PLANARCONFIG_CONTIG;
case PLANARCONFIG_CONTIG:
break;
case PLANARCONFIG_SEPARATE:
t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG;
if(t2p->tiff_bitspersample!=8){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with separated planar configuration and %u bits per sample",
TIFFFileName(input),
t2p->tiff_bitspersample);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
break;
default:
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with planar configuration %u",
TIFFFileName(input),
t2p->tiff_planar);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION,
&(t2p->tiff_orientation));
if(t2p->tiff_orientation>8){
TIFFWarning(TIFF2PDF_MODULE,
"Image %s has orientation %u, assuming 0",
TIFFFileName(input), t2p->tiff_orientation);
t2p->tiff_orientation=0;
}
if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){
t2p->tiff_xres=0.0;
}
if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){
t2p->tiff_yres=0.0;
}
TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit) );
if(t2p->tiff_resunit==RESUNIT_CENTIMETER){
t2p->tiff_xres*=2.54F;
t2p->tiff_yres*=2.54F;
} else if (t2p->tiff_resunit!=RESUNIT_INCH && t2p->pdf_centimeters!=0){
t2p->tiff_xres*=2.54F;
t2p->tiff_yres*=2.54F;
}
t2p_compose_pdf_page(t2p);
t2p->pdf_transcode = T2P_TRANSCODE_ENCODE;
if(t2p->pdf_nopassthrough==0){
#ifdef CCITT_SUPPORT
if(t2p->tiff_compression==COMPRESSION_CCITTFAX4
){
if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_G4;
}
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE
|| t2p->tiff_compression==COMPRESSION_DEFLATE){
if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_ZIP;
}
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_OJPEG){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_JPEG;
t2p_process_ojpeg_tables(t2p, input);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_JPEG){
t2p->pdf_transcode = T2P_TRANSCODE_RAW;
t2p->pdf_compression=T2P_COMPRESS_JPEG;
}
#endif
(void)0;
}
if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){
t2p->pdf_compression = t2p->pdf_defaultcompression;
}
#ifdef JPEG_SUPPORT
if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){
if(t2p->pdf_colorspace & T2P_CS_PALETTE){
t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE;
t2p->pdf_colorspace ^= T2P_CS_PALETTE;
t2p->tiff_pages[t2p->pdf_page].page_extra--;
}
}
if(t2p->tiff_compression==COMPRESSION_JPEG){
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with JPEG compression and separated planar configuration",
TIFFFileName(input));
t2p->t2p_error=T2P_ERR_ERROR;
return;
}
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_OJPEG){
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
TIFFError(
TIFF2PDF_MODULE,
"No support for %s with OJPEG compression and separated planar configuration",
TIFFFileName(input));
t2p->t2p_error=T2P_ERR_ERROR;
return;
}
}
#endif
if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){
if(t2p->pdf_colorspace & T2P_CS_CMYK){
t2p->tiff_samplesperpixel=4;
t2p->tiff_photometric=PHOTOMETRIC_SEPARATED;
} else {
t2p->tiff_samplesperpixel=3;
t2p->tiff_photometric=PHOTOMETRIC_RGB;
}
}
if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION,
&(t2p->tiff_transferfunction[0]),
&(t2p->tiff_transferfunction[1]),
&(t2p->tiff_transferfunction[2]))) {
if(t2p->tiff_transferfunction[1] !=
t2p->tiff_transferfunction[0]) {
t2p->tiff_transferfunctioncount=3;
} else {
t2p->tiff_transferfunctioncount=1;
}
} else {
t2p->tiff_transferfunctioncount=0;
}
if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){
t2p->tiff_whitechromaticities[0]=xfloatp[0];
t2p->tiff_whitechromaticities[1]=xfloatp[1];
if(t2p->pdf_colorspace & T2P_CS_GRAY){
t2p->pdf_colorspace |= T2P_CS_CALGRAY;
}
if(t2p->pdf_colorspace & T2P_CS_RGB){
t2p->pdf_colorspace |= T2P_CS_CALRGB;
}
}
if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){
t2p->tiff_primarychromaticities[0]=xfloatp[0];
t2p->tiff_primarychromaticities[1]=xfloatp[1];
t2p->tiff_primarychromaticities[2]=xfloatp[2];
t2p->tiff_primarychromaticities[3]=xfloatp[3];
t2p->tiff_primarychromaticities[4]=xfloatp[4];
t2p->tiff_primarychromaticities[5]=xfloatp[5];
if(t2p->pdf_colorspace & T2P_CS_RGB){
t2p->pdf_colorspace |= T2P_CS_CALRGB;
}
}
if(t2p->pdf_colorspace & T2P_CS_LAB){
if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){
t2p->tiff_whitechromaticities[0]=xfloatp[0];
t2p->tiff_whitechromaticities[1]=xfloatp[1];
} else {
t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */
t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */
}
}
if(TIFFGetField(input,
TIFFTAG_ICCPROFILE,
&(t2p->tiff_iccprofilelength),
&(t2p->tiff_iccprofile))!=0){
t2p->pdf_colorspace |= T2P_CS_ICCBASED;
} else {
t2p->tiff_iccprofilelength=0;
t2p->tiff_iccprofile=NULL;
}
#ifdef CCITT_SUPPORT
if( t2p->tiff_bitspersample==1 &&
t2p->tiff_samplesperpixel==1){
t2p->pdf_compression = T2P_COMPRESS_G4;
}
#endif
return;
}
/*
This function returns the necessary size of a data buffer to contain the raw or
uncompressed image data from the input TIFF for a page.
*/
static void t2p_read_tiff_size(T2P* t2p, TIFF* input){
uint32* sbc=NULL;
#if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT)
unsigned char* jpt=NULL;
uint32 xuint32=0;
tstrip_t i=0;
tstrip_t stripcount=0;
#endif
#ifdef OJPEG_SUPPORT
tsize_t k = 0;
#endif
if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4 ){
TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
t2p->tiff_datasize=sbc[0];
return;
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
t2p->tiff_datasize=sbc[0];
return;
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
TIFFError(TIFF2PDF_MODULE,
"Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
k += sbc[i];
}
if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){
if(t2p->tiff_dataoffset != 0){
if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){
if(t2p->tiff_datasize < k) {
t2p->pdf_ojpegiflength=t2p->tiff_datasize;
t2p->tiff_datasize+=k;
t2p->tiff_datasize+=6;
t2p->tiff_datasize+=2*stripcount;
TIFFWarning(TIFF2PDF_MODULE,
"Input file %s has short JPEG interchange file byte count",
TIFFFileName(input));
return;
}
return;
}else {
TIFFError(TIFF2PDF_MODULE,
"Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
}
}
t2p->tiff_datasize+=k;
t2p->tiff_datasize+=2*stripcount;
t2p->tiff_datasize+=2048;
return;
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
t2p->tiff_datasize = 2048; /* safety margin (actually used!) */
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt) != 0 ){
if(xuint32>4){
t2p->tiff_datasize+= xuint32;
t2p->tiff_datasize -=2; /* don't use EOI of header */
}
} else {
t2p->tiff_datasize=2; /* SOI for first strip */
}
stripcount=TIFFNumberOfStrips(input);
if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){
TIFFError(TIFF2PDF_MODULE,
"Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
for(i=0;i<stripcount;i++){
t2p->tiff_datasize += sbc[i];
t2p->tiff_datasize -=4; /* don't use SOI or EOI of strip */
}
t2p->tiff_datasize +=2; /* use EOI of last strip */
return;
}
#endif
(void) 0;
}
t2p->tiff_datasize=TIFFScanlineSize(input) * t2p->tiff_length;
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
t2p->tiff_datasize*= t2p->tiff_samplesperpixel;
}
return;
}
/*
This function returns the necessary size of a data buffer to contain the raw or
uncompressed image data from the input TIFF for a tile of a page.
*/
static void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){
uint32* tbc = NULL;
uint16 edge=0;
#ifdef JPEG_SUPPORT
uint32 xuint32=0;
unsigned char* jpt;
#endif
edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){
if(edge
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
&& !(t2p->pdf_compression==T2P_COMPRESS_JPEG)
#endif
){
t2p->tiff_datasize=TIFFTileSize(input);
return;
} else {
TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc);
t2p->tiff_datasize=tbc[tile];
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_OJPEG){
t2p->tiff_datasize+=2048;
return;
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression==COMPRESSION_JPEG){
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt)!=0){
if(xuint32>4){
t2p->tiff_datasize+=xuint32;
t2p->tiff_datasize-=4; /* don't use EOI of header or SOI of tile */
}
}
}
#endif
return;
}
}
t2p->tiff_datasize=TIFFTileSize(input);
if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){
t2p->tiff_datasize*= t2p->tiff_samplesperpixel;
}
return;
}
/*
This functions returns a non-zero value when the tile is on the right edge
and does not have full imaged tile width.
*/
static int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){
if( ((tile+1) % tiles.tiles_tilecountx == 0)
&& (tiles.tiles_edgetilewidth != 0) ){
return(1);
} else {
return(0);
}
return(0);
}
/*
This functions returns a non-zero value when the tile is on the bottom edge
and does not have full imaged tile length.
*/
static int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){
if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) )
&& (tiles.tiles_edgetilelength != 0) ){
return(1);
} else {
return(0);
}
return(0);
}
/*
This function reads the raster image data from the input TIFF for an image and writes
the data to the output PDF XObject image dictionary stream. It returns the amount written
or zero on error.
*/
static tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){
tsize_t written=0;
unsigned char* buffer=NULL;
unsigned char* samplebuffer=NULL;
tsize_t bufferoffset=0;
tsize_t samplebufferoffset=0;
tsize_t read=0;
tstrip_t i=0;
tstrip_t j=0;
tstrip_t stripcount=0;
tsize_t stripsize=0;
tsize_t sepstripcount=0;
tsize_t sepstripsize=0;
#ifdef OJPEG_SUPPORT
toff_t inputoffset=0;
uint16 h_samp=1;
uint16 v_samp=1;
uint16 ri=1;
uint32 rows=0;
#endif
#ifdef JPEG_SUPPORT
unsigned char* jpt;
uint32 xuint32=0;
uint16 xuint16_1=0;
uint16 xuint16_2=0;
float* xfloatp;
uint32* sbc;
unsigned char* stripbuffer;
tsize_t striplength=0;
uint32 max_striplength=0;
#endif
if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
/* make sure is lsb-to-msb bit-endianness fill order */
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(t2p->tiff_dataoffset != 0){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(t2p->pdf_ojpegiflength==0){
inputoffset=TIFFSeekFile(input, 0, SEEK_CUR);
TIFFSeekFile(input, t2p->tiff_dataoffset, SEEK_SET);
TIFFReadFile(input, (tdata_t) buffer, t2p->tiff_datasize);
TIFFSeekFile(input, inputoffset, SEEK_SET);
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
} else {
inputoffset=TIFFSeekFile(input, 0, SEEK_CUR);
TIFFSeekFile(input, t2p->tiff_dataoffset, SEEK_SET);
bufferoffset=TIFFReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength);
t2p->pdf_ojpegiflength=0;
TIFFSeekFile(input, inputoffset, SEEK_SET);
TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp);
buffer[bufferoffset++]= 0xff;
buffer[bufferoffset++]= 0xdd;
buffer[bufferoffset++]= 0x00;
buffer[bufferoffset++]= 0x04;
h_samp*=8;
v_samp*=8;
ri=(t2p->tiff_width+h_samp-1) / h_samp;
TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
ri*=(rows+v_samp-1)/v_samp;
buffer[bufferoffset++]= (ri>>8) & 0xff;
buffer[bufferoffset++]= ri & 0xff;
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
if(i != 0 ){
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=(0xd0 | ((i-1)%8));
}
bufferoffset+=TIFFReadRawStrip(input,
i,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
}
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
} else {
if(! t2p->pdf_ojpegdata){
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with bad tables",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
bufferoffset=t2p->pdf_ojpegdatalength;
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
if(i != 0){
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=(0xd0 | ((i-1)%8));
}
bufferoffset+=TIFFReadRawStrip(input,
i,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
}
if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=0xd9;
}
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with no JPEG File Interchange offset",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
return(t2p->tiff_datasize);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt) != 0){
if(xuint32>4){
_TIFFmemcpy(buffer, jpt, xuint32);
bufferoffset+=xuint32-2;
}
}
stripcount=TIFFNumberOfStrips(input);
TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc);
for(i=0;i<stripcount;i++){
if(sbc[i]>max_striplength) max_striplength=sbc[i];
}
stripbuffer=(unsigned char*) _TIFFmalloc(max_striplength);
if(stripbuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
max_striplength,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
for(i=0;i<stripcount;i++){
striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1);
if(!t2p_process_jpeg_strip(
stripbuffer,
&striplength,
buffer,
&bufferoffset,
i,
t2p->tiff_length)){
TIFFError(TIFF2PDF_MODULE,
"Can't process JPEG data in input file %s",
TIFFFileName(input));
_TIFFfree(stripbuffer);
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
}
buffer[bufferoffset++]=0xff;
buffer[bufferoffset++]=0xd9;
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(stripbuffer);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
(void)0;
}
if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
stripsize=TIFFStripSize(input);
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
read =
TIFFReadEncodedStrip(input,
i,
(tdata_t) &buffer[bufferoffset],
stripsize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding strip %u of %s",
i,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
bufferoffset+=read;
}
} else {
if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
sepstripsize=TIFFStripSize(input);
sepstripcount=TIFFNumberOfStrips(input);
stripsize=sepstripsize*t2p->tiff_samplesperpixel;
stripcount=sepstripcount/t2p->tiff_samplesperpixel;
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebuffer = (unsigned char*) _TIFFmalloc(stripsize);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
for(i=0;i<stripcount;i++){
samplebufferoffset=0;
for(j=0;j<t2p->tiff_samplesperpixel;j++){
read =
TIFFReadEncodedStrip(input,
i + j*stripcount,
(tdata_t) &(samplebuffer[samplebufferoffset]),
sepstripsize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding strip %u of %s",
i + j*stripcount,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
samplebufferoffset+=read;
}
t2p_sample_planar_separate_to_contig(
t2p,
&(buffer[bufferoffset]),
samplebuffer,
samplebufferoffset);
bufferoffset+=samplebufferoffset;
}
_TIFFfree(samplebuffer);
goto dataready;
}
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
memset(buffer, 0, t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
stripsize=TIFFStripSize(input);
stripcount=TIFFNumberOfStrips(input);
for(i=0;i<stripcount;i++){
read =
TIFFReadEncodedStrip(input,
i,
(tdata_t) &buffer[bufferoffset],
stripsize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding strip %u of %s",
i,
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
bufferoffset+=read;
}
if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){
samplebuffer=(unsigned char*)_TIFFrealloc(
(tdata_t) buffer,
t2p->tiff_datasize * t2p->tiff_samplesperpixel);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
_TIFFfree(buffer);
} else {
buffer=samplebuffer;
t2p->tiff_datasize *= t2p->tiff_samplesperpixel;
}
t2p_sample_realize_palette(t2p, buffer);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length);
}
if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
samplebuffer=(unsigned char*)_TIFFrealloc(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length*4);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
_TIFFfree(buffer);
return(0);
} else {
buffer=samplebuffer;
}
if(!TIFFReadRGBAImageOriented(
input,
t2p->tiff_width,
t2p->tiff_length,
(uint32*)buffer,
ORIENTATION_TOPLEFT,
0)){
TIFFError(TIFF2PDF_MODULE,
"Can't use TIFFReadRGBAImageOriented to extract RGB image from %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
t2p->tiff_datasize=t2p_sample_abgr_to_rgb(
(tdata_t) buffer,
t2p->tiff_width*t2p->tiff_length);
}
if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
(tdata_t)buffer,
t2p->tiff_width*t2p->tiff_length);
}
}
dataready:
t2p_disable(output);
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width);
TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length);
TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length);
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
switch(t2p->pdf_compression){
case T2P_COMPRESS_NONE:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR){
if(TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &xuint16_1, &xuint16_2)!=0){
if(xuint16_1 != 0 && xuint16_2 != 0){
TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, xuint16_1, xuint16_2);
}
}
if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
}
}
if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){
TIFFError(TIFF2PDF_MODULE,
"Unable to use JPEG compression for input %s and output %s",
TIFFFileName(input),
TIFFFileName(output));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0);
if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else {
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
}
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
(void)0;
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
(void)0;
}
if(t2p->pdf_defaultcompressionquality != 0){
TIFFSetField(output,
TIFFTAG_JPEGQUALITY,
t2p->pdf_defaultcompressionquality);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
if(t2p->pdf_defaultcompressionquality%100 != 0){
TIFFSetField(output,
TIFFTAG_PREDICTOR,
t2p->pdf_defaultcompressionquality % 100);
}
if(t2p->pdf_defaultcompressionquality/100 != 0){
TIFFSetField(output,
TIFFTAG_ZIPQUALITY,
(t2p->pdf_defaultcompressionquality / 100));
}
break;
#endif
default:
break;
}
t2p_enable(output);
t2p->outputwritten = 0;
#ifdef JPEG_SUPPORT
if(t2p->pdf_compression==T2P_COMPRESS_JPEG && t2p->tiff_photometric==PHOTOMETRIC_YCBCR){
bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer,stripsize*stripcount);
} else
#endif
bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize);
if(buffer != NULL){
_TIFFfree(buffer);
buffer=NULL;
}
if(bufferoffset==(tsize_t)-1){
TIFFError(TIFF2PDF_MODULE,
"Error writing encoded strip to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
written= t2p->outputwritten;
return(written);
}
/*
This function reads the raster image data from the input TIFF for an image tile and writes
the data to the output PDF XObject image dictionary stream for the tile. It returns the
amount written or zero on error.
*/
static tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){
uint16 edge=0;
tsize_t written=0;
unsigned char* buffer=NULL;
tsize_t bufferoffset=0;
unsigned char* samplebuffer=NULL;
tsize_t samplebufferoffset=0;
tsize_t read=0;
uint16 i=0;
ttile_t tilecount=0;
ttile_t septilecount=0;
tsize_t septilesize=0;
#ifdef JPEG_SUPPORT
unsigned char* jpt;
uint16 xuint16_1=0;
uint16 xuint16_2=0;
float* xfloatp;
uint32 xuint32=0;
#endif
edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile);
if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0)
#if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT)
|| (t2p->pdf_compression == T2P_COMPRESS_JPEG)
#endif
)
){
#ifdef CCITT_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_G4){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef ZIP_SUPPORT
if(t2p->pdf_compression == T2P_COMPRESS_ZIP){
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize);
if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){
TIFFReverseBits(buffer, t2p->tiff_datasize);
}
TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize);
_TIFFfree(buffer);
return(t2p->tiff_datasize);
}
#endif
#ifdef OJPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_OJPEG){
if(! t2p->pdf_ojpegdata){
TIFFError(TIFF2PDF_MODULE,
"No support for OJPEG image %s with "
"bad tables",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength);
if(edge!=0){
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[7]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff;
buffer[8]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff;
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){
buffer[9]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff;
buffer[10]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff;
}
}
bufferoffset=t2p->pdf_ojpegdatalength;
bufferoffset+=TIFFReadRawTile(input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
((unsigned char*)buffer)[bufferoffset++]=0xff;
((unsigned char*)buffer)[bufferoffset++]=0xd9;
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
#ifdef JPEG_SUPPORT
if(t2p->tiff_compression == COMPRESSION_JPEG){
unsigned char table_end[2];
buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint16_1, &jpt) != 0) {
if(xuint16_1 > 0){
_TIFFmemcpy(buffer, jpt, xuint16_1);
bufferoffset += xuint16_1 - 2;
table_end[0] = buffer[bufferoffset-2];
table_end[1] = buffer[bufferoffset-1];
}
if(xuint16_1 > 0) {
xuint32 = bufferoffset;
bufferoffset += TIFFReadRawTile(
input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]),
-1);
buffer[xuint32-2]=table_end[0];
buffer[xuint32-1]=table_end[1];
} else {
bufferoffset += TIFFReadRawTile(
input,
tile,
(tdata_t) &(((unsigned char*)buffer)[bufferoffset]),
-1);
}
}
TIFFWriteFile(output, (tdata_t) buffer, bufferoffset);
_TIFFfree(buffer);
return(bufferoffset);
}
#endif
(void)0;
}
if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for "
"t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
} else {
if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){
septilesize=TIFFTileSize(input);
septilecount=TIFFNumberOfTiles(input);
tilecount=septilecount/t2p->tiff_samplesperpixel;
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(samplebuffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
samplebufferoffset=0;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
read =
TIFFReadEncodedTile(input,
tile + i*tilecount,
(tdata_t) &(samplebuffer[samplebufferoffset]),
septilesize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile + i*tilecount,
TIFFFileName(input));
_TIFFfree(samplebuffer);
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
samplebufferoffset+=read;
}
t2p_sample_planar_separate_to_contig(
t2p,
&(buffer[bufferoffset]),
samplebuffer,
samplebufferoffset);
bufferoffset+=samplebufferoffset;
_TIFFfree(samplebuffer);
}
if(buffer==NULL){
buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize);
if(buffer==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory "
"for t2p_readwrite_pdf_image_tile, %s",
t2p->tiff_datasize,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
read = TIFFReadEncodedTile(
input,
tile,
(tdata_t) &buffer[bufferoffset],
t2p->tiff_datasize);
if(read==-1){
TIFFError(TIFF2PDF_MODULE,
"Error on decoding tile %u of %s",
tile,
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error=T2P_ERR_ERROR;
return(0);
}
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgba_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){
t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){
TIFFError(TIFF2PDF_MODULE,
"No support for YCbCr to RGB in tile for %s",
TIFFFileName(input));
_TIFFfree(buffer);
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){
t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned(
(tdata_t)buffer,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth
*t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
}
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){
t2p_tile_collapse_left(
buffer,
TIFFTileRowSize(input),
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
t2p_disable(output);
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric);
TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample);
TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel);
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGEWIDTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
}
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
} else {
TIFFSetField(
output,
TIFFTAG_IMAGELENGTH,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
TIFFSetField(
output,
TIFFTAG_ROWSPERSTRIP,
t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
}
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
switch(t2p->pdf_compression){
case T2P_COMPRESS_NONE:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
break;
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR){
if(TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &xuint16_1, &xuint16_2)!=0){
if(xuint16_1 != 0 && xuint16_2 != 0){
TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, xuint16_1, xuint16_2);
}
}
if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){
TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp);
}
}
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */
if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){
TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
} else {
TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW);
}
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
(void)0;
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
(void)0;
}
if(t2p->pdf_defaultcompressionquality != 0){
TIFFSetField(output,
TIFFTAG_JPEGQUALITY,
t2p->pdf_defaultcompressionquality);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE);
if(t2p->pdf_defaultcompressionquality%100 != 0){
TIFFSetField(output,
TIFFTAG_PREDICTOR,
t2p->pdf_defaultcompressionquality % 100);
}
if(t2p->pdf_defaultcompressionquality/100 != 0){
TIFFSetField(output,
TIFFTAG_ZIPQUALITY,
(t2p->pdf_defaultcompressionquality / 100));
}
break;
#endif
default:
break;
}
t2p_enable(output);
t2p->outputwritten = 0;
bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output));
if(buffer != NULL){
_TIFFfree(buffer);
buffer=NULL;
}
if(bufferoffset==-1){
TIFFError(TIFF2PDF_MODULE,
"Error writing encoded tile to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
written= t2p->outputwritten;
return(written);
}
#ifdef OJPEG_SUPPORT
static int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){
uint16 proc=0;
void* q;
uint32 q_length=0;
void* dc;
uint32 dc_length=0;
void* ac;
uint32 ac_length=0;
uint16* lp;
uint16* pt;
uint16 h_samp=1;
uint16 v_samp=1;
unsigned char* ojpegdata;
uint16 table_count;
uint32 offset_table;
uint32 offset_ms_l;
uint32 code_count;
uint32 i=0;
uint32 dest=0;
uint16 ri=0;
uint32 rows=0;
if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGProc field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){
TIFFError(TIFF2PDF_MODULE,
"Bad JPEGProc field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGQTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(q_length < (64U * t2p->tiff_samplesperpixel)){
TIFFError(TIFF2PDF_MODULE,
"Bad JPEGQTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGDCTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(proc==JPEGPROC_BASELINE){
if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGACTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
} else {
if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGLosslessPredictors field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGPointTransform field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
}
if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){
h_samp=1;
v_samp=1;
}
if(t2p->pdf_ojpegdata != NULL){
_TIFFfree(t2p->pdf_ojpegdata);
t2p->pdf_ojpegdata=NULL;
}
t2p->pdf_ojpegdata = _TIFFmalloc(2048);
if(t2p->pdf_ojpegdata == NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s",
2048,
TIFFFileName(input));
return(0);
}
_TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048);
t2p->pdf_ojpegdatalength = 0;
table_count=t2p->tiff_samplesperpixel;
if(proc==JPEGPROC_BASELINE){
if(table_count>2) table_count=2;
}
ojpegdata=(unsigned char*)t2p->pdf_ojpegdata;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
if(proc==JPEGPROC_BASELINE){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel);
ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff);
if(TIFFIsTiled(input)){
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_length >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_length ) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_width >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_width ) & 0xff;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff);
for(i=0;i<t2p->tiff_samplesperpixel;i++){
ojpegdata[t2p->pdf_ojpegdatalength++]=i;
if(i==0){
ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;;
ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=i;
}
for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x43;
ojpegdata[t2p->pdf_ojpegdatalength++]=dest;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]),
&(((unsigned char*)q)[64*dest]), 64);
t2p->pdf_ojpegdatalength+=64;
}
offset_table=0;
for(dest=0;dest<table_count;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
offset_ms_l=t2p->pdf_ojpegdatalength;
t2p->pdf_ojpegdatalength+=2;
ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)dc)[offset_table]), 16);
code_count=0;
offset_table+=16;
for(i=0;i<16;i++){
code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
}
ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)dc)[offset_table]), code_count);
offset_table+=code_count;
t2p->pdf_ojpegdatalength+=code_count;
}
if(proc==JPEGPROC_BASELINE){
offset_table=0;
for(dest=0;dest<table_count;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
offset_ms_l=t2p->pdf_ojpegdatalength;
t2p->pdf_ojpegdatalength+=2;
ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10;
ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)ac)[offset_table]), 16);
code_count=0;
offset_table+=16;
for(i=0;i<16;i++){
code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
}
ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)ac)[offset_table]), code_count);
offset_table+=code_count;
t2p->pdf_ojpegdatalength+=code_count;
}
}
if(TIFFNumberOfStrips(input)>1){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x04;
h_samp*=8;
v_samp*=8;
ri=(t2p->tiff_width+h_samp-1) / h_samp;
TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
ri*=(rows+v_samp-1)/v_samp;
ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xda;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel);
ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff;
if(proc==JPEGPROC_BASELINE){
ojpegdata[t2p->pdf_ojpegdatalength] |=
( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0;
ojpegdata[t2p->pdf_ojpegdatalength++] |=
( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0;
}
}
if(proc==JPEGPROC_BASELINE){
t2p->pdf_ojpegdatalength++;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f;
t2p->pdf_ojpegdatalength++;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff);
t2p->pdf_ojpegdatalength++;
ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f);
}
return(1);
}
#endif
#ifdef JPEG_SUPPORT
static int t2p_process_jpeg_strip(
unsigned char* strip,
tsize_t* striplength,
unsigned char* buffer,
tsize_t* bufferoffset,
tstrip_t no,
uint32 height){
tsize_t i=0;
uint16 ri =0;
uint16 v_samp=1;
uint16 h_samp=1;
int j=0;
i++;
while(i<(*striplength)){
switch( strip[i] ){
case 0xd8:
i+=2;
break;
case 0xc0:
case 0xc1:
case 0xc3:
case 0xc9:
case 0xca:
if(no==0){
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2);
for(j=0;j<buffer[*bufferoffset+9];j++){
if( (buffer[*bufferoffset+11+(2*j)]>>4) > h_samp)
h_samp = (buffer[*bufferoffset+11+(2*j)]>>4);
if( (buffer[*bufferoffset+11+(2*j)] & 0x0f) > v_samp)
v_samp = (buffer[*bufferoffset+11+(2*j)] & 0x0f);
}
v_samp*=8;
h_samp*=8;
ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) |
(uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/
v_samp);
ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) |
(uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/
h_samp);
buffer[*bufferoffset+5]=
(unsigned char) ((height>>8) & 0xff);
buffer[*bufferoffset+6]=
(unsigned char) (height & 0xff);
*bufferoffset+=strip[i+2]+2;
i+=strip[i+2]+2;
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=0xdd;
buffer[(*bufferoffset)++]=0x00;
buffer[(*bufferoffset)++]=0x04;
buffer[(*bufferoffset)++]=(ri >> 8) & 0xff;
buffer[(*bufferoffset)++]= ri & 0xff;
} else {
i+=strip[i+2]+2;
}
break;
case 0xc4:
case 0xdb:
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2);
*bufferoffset+=strip[i+2]+2;
i+=strip[i+2]+2;
break;
case 0xda:
if(no==0){
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2);
*bufferoffset+=strip[i+2]+2;
i+=strip[i+2]+2;
} else {
buffer[(*bufferoffset)++]=0xff;
buffer[(*bufferoffset)++]=
(unsigned char)(0xd0 | ((no-1)%8));
i+=strip[i+2]+2;
}
_TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), (*striplength)-i-1);
*bufferoffset+=(*striplength)-i-1;
return(1);
default:
i+=strip[i+2]+2;
}
}
return(0);
}
#endif
/*
This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x
tilelength buffer of samples.
*/
static void t2p_tile_collapse_left(
tdata_t buffer,
tsize_t scanwidth,
uint32 tilewidth,
uint32 edgetilewidth,
uint32 tilelength){
uint32 i=0;
tsize_t edgescanwidth=0;
edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth;
for(i=i;i<tilelength;i++){
_TIFFmemcpy(
&(((char*)buffer)[edgescanwidth*i]),
&(((char*)buffer)[scanwidth*i]),
edgescanwidth);
}
return;
}
/*
This function calls TIFFWriteDirectory on the output after blanking its output by replacing the
read, write, and seek procedures with empty implementations, then it replaces the original
implementations.
*/
static void t2p_write_advance_directory(T2P* t2p, TIFF* output){
t2p_disable(output);
if(!TIFFWriteDirectory(output)){
TIFFError(TIFF2PDF_MODULE,
"Error writing virtual directory to output PDF %s",
TIFFFileName(output));
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p_enable(output);
return;
}
static tsize_t t2p_sample_planar_separate_to_contig(T2P* t2p,
unsigned char* buffer,
unsigned char* samplebuffer,
tsize_t samplebuffersize){
tsize_t stride=0;
tsize_t i=0;
tsize_t j=0;
stride=samplebuffersize/t2p->tiff_samplesperpixel;
for(i=0;i<stride;i++){
for(j=0;j<t2p->tiff_samplesperpixel;j++){
buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride];
}
}
return(samplebuffersize);
}
static tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){
uint32 sample_count=0;
uint16 component_count=0;
uint32 palette_offset=0;
uint32 sample_offset=0;
uint32 i=0;
uint32 j=0;
sample_count=t2p->tiff_width*t2p->tiff_length;
component_count=t2p->tiff_samplesperpixel;
for(i=sample_count;i>0;i--){
palette_offset=buffer[i-1] * component_count;
sample_offset= (i-1) * component_count;
for(j=0;j<component_count;j++){
buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j];
}
}
return(0);
}
/*
This functions converts in place a buffer of ABGR interleaved data
into RGB interleaved data, discarding A.
*/
static tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount)
{
uint32 i=0;
uint32 sample=0;
for(i=0;i<samplecount;i++){
sample=((uint32*)data)[i];
((char*)data)[i*3]= (char) (sample & 0xff);
((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff);
((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff);
}
return(i*3);
}
/*
* This functions converts in place a buffer of RGBA interleaved data
* into RGB interleaved data, discarding A.
*/
static tsize_t
t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount)
{
uint32 i;
for(i = 0; i < samplecount; i++)
memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3);
return(i * 3);
}
/*
* This functions converts in place a buffer of RGBA interleaved data
* into RGB interleaved data, adding 255-A to each component sample.
*/
static tsize_t
t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount)
{
uint32 i = 0;
uint32 sample = 0;
uint8 alpha = 0;
for (i = 0; i < samplecount; i++) {
sample=((uint32*)data)[i];
alpha=(uint8)((255 - (sample & 0xff)));
((uint8 *)data)[i * 3] = (uint8) ((sample >> 24) & 0xff) + alpha;
((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 16) & 0xff) + alpha;
((uint8 *)data)[i * 3 + 2] = (uint8) ((sample >> 8) & 0xff) + alpha;
}
return (i * 3);
}
/*
This function converts the a and b samples of Lab data from signed
to unsigned.
*/
static tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){
uint32 i=0;
for(i=0;i<samplecount;i++){
if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){
((unsigned char*)buffer)[(i*3)+1] =
(unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]);
} else {
((unsigned char*)buffer)[(i*3)+1] |= 0x80;
}
if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){
((unsigned char*)buffer)[(i*3)+2] =
(unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]);
} else {
((unsigned char*)buffer)[(i*3)+2] |= 0x80;
}
}
return(samplecount*3);
}
/*
This function writes the PDF header to output.
*/
static tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
buflen=sprintf(buffer, "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t)"\r%\342\343\317\323\r\n", 8);
return(written);
}
/*
This function writes the beginning of a PDF object to output.
*/
static tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
buflen=sprintf(buffer, "%lu", (unsigned long)number);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen );
written += TIFFWriteFile(output, (tdata_t) " 0 obj\r", 7);
return(written);
}
/*
This function writes the end of a PDF object to output.
*/
static tsize_t t2p_write_pdf_obj_end(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) "endobj\r", 7);
return(written);
}
/*
This function writes a PDF string object to output.
*/
static tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output){
tsize_t written=0;
uint32 i=0;
char buffer[5];
uint32 len=0;
len=strlen(pdfstr);
written += TIFFWriteFile(output, (tdata_t) "(", 1);
for (i=0;i<len;i++){
if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){
sprintf(buffer, "\\%.3o", pdfstr[i]);
written += TIFFWriteFile(output, (tdata_t) buffer, 4);
} else {
switch (pdfstr[i]){
case 0x08:
written += TIFFWriteFile(output, (tdata_t) "\\b", 2);
break;
case 0x09:
written += TIFFWriteFile(output, (tdata_t) "\\t", 2);
break;
case 0x0A:
written += TIFFWriteFile(output, (tdata_t) "\\n", 2);
break;
case 0x0C:
written += TIFFWriteFile(output, (tdata_t) "\\f", 2);
break;
case 0x0D:
written += TIFFWriteFile(output, (tdata_t) "\\r", 2);
break;
case 0x28:
written += TIFFWriteFile(output, (tdata_t) "\\(", 2);
break;
case 0x29:
written += TIFFWriteFile(output, (tdata_t) "\\)", 2);
break;
case 0x5C:
written += TIFFWriteFile(output, (tdata_t) "\\\\", 2);
break;
default:
written += TIFFWriteFile(output, (tdata_t) &pdfstr[i], 1);
}
}
}
written += TIFFWriteFile(output, (tdata_t) ") ", 1);
return(written);
}
/*
This function writes a buffer of data to output.
*/
static tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) buffer, len);
return(written);
}
/*
This functions writes the beginning of a PDF stream to output.
*/
static tsize_t t2p_write_pdf_stream_start(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) "stream\r\n", 8);
return(written);
}
/*
This function writes the end of a PDF stream to output.
*/
static tsize_t t2p_write_pdf_stream_end(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) "\rendstream\r", 11);
return(written);
}
/*
This function writes a stream dictionary for a PDF stream to output.
*/
static tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "/Length ", 8);
if(len!=0){
written += t2p_write_pdf_stream_length(len, output);
} else {
buflen=sprintf(buffer, "%lu", (unsigned long)number);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
}
return(written);
}
/*
This functions writes the beginning of a PDF stream dictionary to output.
*/
static tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) "<< \r", 4);
return(written);
}
/*
This function writes the end of a PDF stream dictionary to output.
*/
static tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){
tsize_t written=0;
written += TIFFWriteFile(output, (tdata_t) " >>\r", 4);
return(written);
}
/*
This function writes a number to output.
*/
static tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
buflen=sprintf(buffer, "%lu", (unsigned long)len);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
return(written);
}
/*
This function writes the PDF Catalog structure to output.
*/
static tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output,
(tdata_t)"<< \r/Type /Catalog \r/Pages ",
27);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen );
written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
if(t2p->pdf_fitwindow){
written += TIFFWriteFile(output,
(tdata_t) "/ViewerPreferences <</FitWindow true>>\r",
39);
}
written += TIFFWriteFile(output, (tdata_t)">>\r", 3);
return(written);
}
/*
This function writes the PDF Info structure to output.
*/
static tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output){
tsize_t written=0;
char* info;
char buffer[512];
if(t2p->pdf_datetime==NULL){
t2p_pdf_tifftime(t2p, input);
}
if(strlen(t2p->pdf_datetime) > 0){
written += TIFFWriteFile(output, (tdata_t) "<< \r/CreationDate ", 18);
written += t2p_write_pdf_string(t2p->pdf_datetime, output);
written += TIFFWriteFile(output, (tdata_t) "\r/ModDate ", 10);
written += t2p_write_pdf_string(t2p->pdf_datetime, output);
}
written += TIFFWriteFile(output, (tdata_t) "\r/Producer ", 11);
_TIFFmemset((tdata_t)buffer, 0x00, 512);
sprintf(buffer, "libtiff / tiff2pdf - %d / %s",
TIFFLIB_VERSION, T2P_VERSION);
written += t2p_write_pdf_string(buffer, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
if(t2p->pdf_creator != NULL){
if(strlen(t2p->pdf_creator)>0){
if(strlen(t2p->pdf_creator)>511){t2p->pdf_creator[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Creator ", 9);
written += t2p_write_pdf_string(t2p->pdf_creator, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
} else{
if( TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Creator ", 9);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
if(t2p->pdf_author != NULL){
if(strlen(t2p->pdf_author)>0){
if(strlen(t2p->pdf_author)>511){t2p->pdf_author[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(t2p->pdf_author, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
} else{
if( TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
} else if ( TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Author ", 8);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
if(t2p->pdf_title != NULL){
if(strlen(t2p->pdf_title)>0){
if(strlen(t2p->pdf_title)>511){t2p->pdf_title[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Title ", 7);
written += t2p_write_pdf_string(t2p->pdf_title, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
} else{
if( TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Title ", 7);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
if(t2p->pdf_subject != NULL){
if(strlen(t2p->pdf_subject)>0){
if(strlen(t2p->pdf_subject)>511){t2p->pdf_subject[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Subject ", 9);
written += t2p_write_pdf_string(t2p->pdf_subject, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
} else{
if( TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0){
if(strlen(info)>511){info[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Subject ", 9);
written += t2p_write_pdf_string(info, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
if(t2p->pdf_keywords != NULL){
if(strlen(t2p->pdf_keywords)>0){
if(strlen(t2p->pdf_keywords)>511){t2p->pdf_keywords[512]=(char)0;}
written += TIFFWriteFile(output, (tdata_t) "/Keywords ", 10);
written += t2p_write_pdf_string(t2p->pdf_keywords, output);
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
written += TIFFWriteFile(output, (tdata_t) ">> \r", 4);
return(written);
}
/*
This function fills a string of a T2P struct with the current time as a PDF date string,
it is called by t2p_pdf_tifftime.
*/
static void t2p_pdf_currenttime(T2P* t2p){
struct tm* currenttime;
time_t timenow;
timenow=time(0);
currenttime=localtime(&timenow);
sprintf(t2p->pdf_datetime, "D:%.4d%.2d%.2d%.2d%.2d%.2d",
(currenttime->tm_year+1900) % 65536,
(currenttime->tm_mon+1) % 256,
(currenttime->tm_mday) % 256,
(currenttime->tm_hour) % 256,
(currenttime->tm_min) % 256,
(currenttime->tm_sec) % 256);
return;
}
/*
This function fills a string of a T2P struct with the date and time of a TIFF file if it
exists or the current time as a PDF date string.
*/
static void t2p_pdf_tifftime(T2P* t2p, TIFF* input){
char* datetime;
t2p->pdf_datetime= (char*) _TIFFmalloc(19);
if(t2p->pdf_datetime==NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_pdf_tiff_time",
17);
t2p->t2p_error = T2P_ERR_ERROR;
return;
}
t2p->pdf_datetime[16]=0;
if( TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0
&& (strlen(datetime) >= 19) ){
t2p->pdf_datetime[0]='D';
t2p->pdf_datetime[1]=':';
t2p->pdf_datetime[2]=datetime[0];
t2p->pdf_datetime[3]=datetime[1];
t2p->pdf_datetime[4]=datetime[2];
t2p->pdf_datetime[5]=datetime[3];
t2p->pdf_datetime[6]=datetime[5];
t2p->pdf_datetime[7]=datetime[6];
t2p->pdf_datetime[8]=datetime[8];
t2p->pdf_datetime[9]=datetime[9];
t2p->pdf_datetime[10]=datetime[11];
t2p->pdf_datetime[11]=datetime[12];
t2p->pdf_datetime[12]=datetime[14];
t2p->pdf_datetime[13]=datetime[15];
t2p->pdf_datetime[14]=datetime[17];
t2p->pdf_datetime[15]=datetime[18];
} else {
t2p_pdf_currenttime(t2p);
}
return;
}
/*
This function writes a PDF Pages Tree structure to output.
*/
static tsize_t t2p_write_pdf_pages(T2P* t2p,
TIFF* output){
tsize_t written=0;
tdir_t i=0;
char buffer[16];
int buflen=0;
int page=0;
written += TIFFWriteFile(output,
(tdata_t) "<< \r/Type /Pages \r/Kids [ ",
26);
page = t2p->pdf_pages+1;
for (i=0;i<t2p->tiff_pagecount;i++){
buflen=sprintf(buffer, "%d", page);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
if ( ((i+1)%8)==0 ) {
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
page +=3;
page += t2p->tiff_pages[i].page_extra;
if(t2p->tiff_pages[i].page_tilecount>0){
page += (2 * t2p->tiff_pages[i].page_tilecount);
} else {
page +=2;
}
}
written += TIFFWriteFile(output, (tdata_t) "] \r/Count ", 10);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%d", t2p->tiff_pagecount);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " \r>> \r", 6);
return(written);
}
/*
This function writes a PDF Page structure to output.
*/
static tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){
unsigned int i=0;
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "<<\r/Type /Page \r/Parent ", 24);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
written += TIFFWriteFile(output, (tdata_t) "/MediaBox [", 11);
buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x2);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y2);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "] \r", 3);
written += TIFFWriteFile(output, (tdata_t) "/Contents ", 10);
buflen=sprintf(buffer, "%lu", (unsigned long)(object + 1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6);
written += TIFFWriteFile(output, (tdata_t) "/Resources << \r", 15);
if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){
written += TIFFWriteFile(output, (tdata_t) "/XObject <<\r", 12);
for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){
written += TIFFWriteFile(output, (tdata_t) "/Im", 3);
buflen = sprintf(buffer, "%u", t2p->pdf_page+1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "_", 1);
buflen = sprintf(buffer, "%u", i+1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen = sprintf(
buffer,
"%lu",
(unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
if(i%4==3){
written += TIFFWriteFile(output, (tdata_t) "\r", 1);
}
}
written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
} else {
written += TIFFWriteFile(output, (tdata_t) "/XObject <<\r", 12);
written += TIFFWriteFile(output, (tdata_t) "/Im", 3);
buflen = sprintf(buffer, "%u", t2p->pdf_page+1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
buflen = sprintf(
buffer,
"%lu",
(unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
}
if(t2p->tiff_transferfunctioncount != 0) {
written += TIFFWriteFile(output, (tdata_t) "/ExtGState <<", 13);
TIFFWriteFile(output, (tdata_t) "/GS1 ", 5);
buflen = sprintf(
buffer,
"%lu",
(unsigned long)(object + 3));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
written += TIFFWriteFile(output, (tdata_t) ">> \r", 4);
}
written += TIFFWriteFile(output, (tdata_t) "/ProcSet [ ", 11);
if(t2p->pdf_colorspace == T2P_CS_BILEVEL
|| t2p->pdf_colorspace == T2P_CS_GRAY
){
written += TIFFWriteFile(output, (tdata_t) "/ImageB ", 8);
} else {
written += TIFFWriteFile(output, (tdata_t) "/ImageC ", 8);
if(t2p->pdf_colorspace & T2P_CS_PALETTE){
written += TIFFWriteFile(output, (tdata_t) "/ImageI ", 8);
}
}
written += TIFFWriteFile(output, (tdata_t) "]\r>>\r>>\r", 8);
return(written);
}
/*
This function composes the page size and image and tile locations on a page.
*/
static void t2p_compose_pdf_page(T2P* t2p){
uint32 i=0;
uint32 i2=0;
T2P_TILE* tiles=NULL;
T2P_BOX* boxp=NULL;
uint32 tilecountx=0;
uint32 tilecounty=0;
uint32 tilewidth=0;
uint32 tilelength=0;
int istiled=0;
float f=0;
t2p->pdf_xres = t2p->tiff_xres;
t2p->pdf_yres = t2p->tiff_yres;
if(t2p->pdf_overrideres){
t2p->pdf_xres = t2p->pdf_defaultxres;
t2p->pdf_yres = t2p->pdf_defaultyres;
}
if(t2p->pdf_xres==0.0){
t2p->pdf_xres = t2p->pdf_defaultxres;
}
if(t2p->pdf_yres==0.0){
t2p->pdf_yres = t2p->pdf_defaultyres;
}
t2p->pdf_imagewidth=((float)(t2p->tiff_width)) *72.0F / t2p->pdf_xres;
t2p->pdf_imagelength=((float)(t2p->tiff_length)) *72.0F / t2p->pdf_yres;
if(t2p->pdf_overridepagesize != 0){
t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth;
t2p->pdf_pagelength = t2p->pdf_defaultpagelength;
} else {
t2p->pdf_pagewidth = t2p->pdf_imagewidth;
t2p->pdf_pagelength = t2p->pdf_imagelength;
}
t2p->pdf_mediabox.x1=0.0;
t2p->pdf_mediabox.y1=0.0;
t2p->pdf_mediabox.x2=t2p->pdf_pagewidth;
t2p->pdf_mediabox.y2=t2p->pdf_pagelength;
t2p->pdf_imagebox.x1=0.0;
t2p->pdf_imagebox.y1=0.0;
t2p->pdf_imagebox.x2=t2p->pdf_imagewidth;
t2p->pdf_imagebox.y2=t2p->pdf_imagelength;
if(t2p->pdf_overridepagesize!=0){
t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F);
t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F);
t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F);
t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F);
}
if(t2p->tiff_orientation > 4){
f=t2p->pdf_mediabox.x2;
t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2;
t2p->pdf_mediabox.y2=f;
}
istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1;
if(istiled==0){
t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation);
return;
} else {
tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth;
tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength;
tilecountx=(t2p->tiff_width +
tilewidth -1)/
tilewidth;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx;
tilecounty=(t2p->tiff_length +
tilelength -1)/
tilelength;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth=
t2p->tiff_width % tilewidth;
(t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength=
t2p->tiff_length % tilelength;
tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles;
for(i2=0;i2<tilecounty-1;i2++){
for(i=0;i<tilecountx-1;i++){
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth)
/ (float)t2p->tiff_width);
boxp->y1 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * (i2+1) * tilelength)
/ (float)t2p->tiff_length);
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 = t2p->pdf_imagebox.x2;
boxp->y1 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * (i2+1) * tilelength)
/ (float)t2p->tiff_length);
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
for(i=0;i<tilecountx-1;i++){
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth)
/ (float)t2p->tiff_width);
boxp->y1 = t2p->pdf_imagebox.y1;
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
boxp=&(tiles[i2*tilecountx+i].tile_box);
boxp->x1 =
t2p->pdf_imagebox.x1
+ ((float)(t2p->pdf_imagewidth * i * tilewidth)
/ (float)t2p->tiff_width);
boxp->x2 = t2p->pdf_imagebox.x2;
boxp->y1 = t2p->pdf_imagebox.y1;
boxp->y2 =
t2p->pdf_imagebox.y2
- ((float)(t2p->pdf_imagelength * i2 * tilelength)
/ (float)t2p->tiff_length);
}
if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){
for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){
t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0);
}
return;
}
for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){
boxp=&(tiles[i].tile_box);
boxp->x1 -= t2p->pdf_imagebox.x1;
boxp->x2 -= t2p->pdf_imagebox.x1;
boxp->y1 -= t2p->pdf_imagebox.y1;
boxp->y2 -= t2p->pdf_imagebox.y1;
if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){
boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
}
if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){
boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
}
if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){
boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1;
boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2;
}
if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){
boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1;
boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2;
}
if(t2p->tiff_orientation > 4){
f=boxp->x1;
boxp->x1 = boxp->y1;
boxp->y1 = f;
f=boxp->x2;
boxp->x2 = boxp->y2;
boxp->y2 = f;
t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation);
} else {
t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation);
}
}
return;
}
static void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){
float m1[9];
float f=0.0;
if( boxp->x1 > boxp->x2){
f=boxp->x1;
boxp->x1=boxp->x2;
boxp->x2 = f;
}
if( boxp->y1 > boxp->y2){
f=boxp->y1;
boxp->y1=boxp->y2;
boxp->y2 = f;
}
boxp->mat[0]=m1[0]=boxp->x2-boxp->x1;
boxp->mat[1]=m1[1]=0.0;
boxp->mat[2]=m1[2]=0.0;
boxp->mat[3]=m1[3]=0.0;
boxp->mat[4]=m1[4]=boxp->y2-boxp->y1;
boxp->mat[5]=m1[5]=0.0;
boxp->mat[6]=m1[6]=boxp->x1;
boxp->mat[7]=m1[7]=boxp->y1;
boxp->mat[8]=m1[8]=1.0;
switch(orientation){
case 0:
case 1:
break;
case 2:
boxp->mat[0]=0.0F-m1[0];
boxp->mat[6]+=m1[0];
break;
case 3:
boxp->mat[0]=0.0F-m1[0];
boxp->mat[4]=0.0F-m1[4];
boxp->mat[6]+=m1[0];
boxp->mat[7]+=m1[4];
break;
case 4:
boxp->mat[4]=0.0F-m1[4];
boxp->mat[7]+=m1[4];
break;
case 5:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[0];
boxp->mat[3]=0.0F-m1[4];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[4];
boxp->mat[7]+=m1[0];
break;
case 6:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[0];
boxp->mat[3]=m1[4];
boxp->mat[4]=0.0F;
boxp->mat[7]+=m1[0];
break;
case 7:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[0];
boxp->mat[3]=m1[4];
boxp->mat[4]=0.0F;
break;
case 8:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[0];
boxp->mat[3]=0.0F-m1[4];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[4];
break;
}
return;
}
static void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){
float m1[9];
float f=0.0;
if( boxp->x1 > boxp->x2){
f=boxp->x1;
boxp->x1=boxp->x2;
boxp->x2 = f;
}
if( boxp->y1 > boxp->y2){
f=boxp->y1;
boxp->y1=boxp->y2;
boxp->y2 = f;
}
boxp->mat[0]=m1[0]=boxp->x2-boxp->x1;
boxp->mat[1]=m1[1]=0.0F;
boxp->mat[2]=m1[2]=0.0F;
boxp->mat[3]=m1[3]=0.0F;
boxp->mat[4]=m1[4]=boxp->y2-boxp->y1;
boxp->mat[5]=m1[5]=0.0F;
boxp->mat[6]=m1[6]=boxp->x1;
boxp->mat[7]=m1[7]=boxp->y1;
boxp->mat[8]=m1[8]=1.0F;
switch(orientation){
case 5:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[4];
boxp->mat[3]=0.0F-m1[0];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[0];
boxp->mat[7]+=m1[4];
break;
case 6:
boxp->mat[0]=0.0F;
boxp->mat[1]=0.0F-m1[4];
boxp->mat[3]=m1[0];
boxp->mat[4]=0.0F;
boxp->mat[7]+=m1[4];
break;
case 7:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[4];
boxp->mat[3]=m1[0];
boxp->mat[4]=0.0F;
break;
case 8:
boxp->mat[0]=0.0F;
boxp->mat[1]=m1[4];
boxp->mat[3]=0.0F-m1[0];
boxp->mat[4]=0.0F;
boxp->mat[6]+=m1[0];
break;
}
return;
}
/*
This function writes a PDF Contents stream to output.
*/
static tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){
tsize_t written=0;
ttile_t i=0;
char buffer[512];
int buflen=0;
T2P_BOX box;
if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){
for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){
box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box;
buflen=sprintf(buffer,
"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\r",
t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
box.mat[0],
box.mat[1],
box.mat[3],
box.mat[4],
box.mat[6],
box.mat[7],
t2p->pdf_page + 1,
(long)(i + 1));
written += t2p_write_pdf_stream(buffer, buflen, output);
}
} else {
box=t2p->pdf_imagebox;
buflen=sprintf(buffer,
"q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\r",
t2p->tiff_transferfunctioncount?"/GS1 gs ":"",
box.mat[0],
box.mat[1],
box.mat[3],
box.mat[4],
box.mat[6],
box.mat[7],
t2p->pdf_page+1);
written += t2p_write_pdf_stream(buffer, buflen, output);
}
return(written);
}
/*
This function writes a PDF Image XObject stream dictionary to output.
*/
static tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile,
T2P* t2p,
TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output);
written += TIFFWriteFile(output,
(tdata_t) "/Type /XObject \r/Subtype /Image \r/Name /Im",
42);
buflen=sprintf(buffer, "%u", t2p->pdf_page+1);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
if(tile != 0){
written += TIFFWriteFile(output, (tdata_t) "_", 1);
buflen=sprintf(buffer, "%lu", (unsigned long)tile);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
}
written += TIFFWriteFile(output, (tdata_t) "\r/Width ", 8);
_TIFFmemset((tdata_t)buffer, 0x00, 16);
if(tile==0){
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width);
} else {
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
} else {
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
}
}
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "\r/Height ", 9);
_TIFFmemset((tdata_t)buffer, 0x00, 16);
if(tile==0){
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_length);
} else {
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
} else {
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
}
}
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "\r/BitsPerComponent ", 19);
_TIFFmemset((tdata_t)buffer, 0x00, 16);
buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "\r/ColorSpace ", 13);
written += t2p_write_pdf_xobject_cs(t2p, output);
if (t2p->pdf_image_interpolate)
written += TIFFWriteFile(output,
(tdata_t) "\r/Interpolate true", 18);
if( (t2p->pdf_switchdecode != 0)
#ifdef CCITT_SUPPORT
&& ! (t2p->pdf_colorspace == T2P_CS_BILEVEL
&& t2p->pdf_compression == T2P_COMPRESS_G4)
#endif
){
written += t2p_write_pdf_xobject_decode(t2p, output);
}
written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output);
return(written);
}
/*
* This function writes a PDF Image XObject Colorspace name to output.
*/
static tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[128];
int buflen=0;
float X_W=1.0;
float Y_W=1.0;
float Z_W=1.0;
if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){
written += t2p_write_pdf_xobject_icccs(t2p, output);
return(written);
}
if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){
written += TIFFWriteFile(output, (tdata_t) "[ /Indexed ", 11);
t2p->pdf_colorspace ^= T2P_CS_PALETTE;
written += t2p_write_pdf_xobject_cs(t2p, output);
t2p->pdf_colorspace |= T2P_CS_PALETTE;
buflen=sprintf(buffer, "%u", (0x0001 << t2p->tiff_bitspersample)-1 );
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " ", 1);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_palettecs );
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ]\r", 7);
return(written);
}
if(t2p->pdf_colorspace & T2P_CS_BILEVEL){
written += TIFFWriteFile(output, (tdata_t) "/DeviceGray \r", 13);
}
if(t2p->pdf_colorspace & T2P_CS_GRAY){
if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
written += t2p_write_pdf_xobject_calcs(t2p, output);
} else {
written += TIFFWriteFile(output, (tdata_t) "/DeviceGray \r", 13);
}
}
if(t2p->pdf_colorspace & T2P_CS_RGB){
if(t2p->pdf_colorspace & T2P_CS_CALRGB){
written += t2p_write_pdf_xobject_calcs(t2p, output);
} else {
written += TIFFWriteFile(output, (tdata_t) "/DeviceRGB \r", 12);
}
}
if(t2p->pdf_colorspace & T2P_CS_CMYK){
written += TIFFWriteFile(output, (tdata_t) "/DeviceCMYK \r", 13);
}
if(t2p->pdf_colorspace & T2P_CS_LAB){
written += TIFFWriteFile(output, (tdata_t) "[/Lab << \r", 10);
written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12);
X_W = t2p->tiff_whitechromaticities[0];
Y_W = t2p->tiff_whitechromaticities[1];
Z_W = 1.0F - (X_W + Y_W);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0F;
buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
X_W = 0.3457F; /* 0.3127F; */ /* D50, commented D65 */
Y_W = 0.3585F; /* 0.3290F; */
Z_W = 1.0F - (X_W + Y_W);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0F;
buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Range ", 7);
buflen=sprintf(buffer, "[%d %d %d %d] \r",
t2p->pdf_labrange[0],
t2p->pdf_labrange[1],
t2p->pdf_labrange[2],
t2p->pdf_labrange[3]);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) ">>] \r", 5);
}
return(written);
}
static tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "<< /Type /ExtGState \r/TR ", 25);
if(t2p->tiff_transferfunctioncount == 1){
buflen=sprintf(buffer, "%lu",
(unsigned long)(t2p->pdf_xrefcount + 1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
} else {
written += TIFFWriteFile(output, (tdata_t) "[ ", 2);
buflen=sprintf(buffer, "%lu",
(unsigned long)(t2p->pdf_xrefcount + 1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
buflen=sprintf(buffer, "%lu",
(unsigned long)(t2p->pdf_xrefcount + 2));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
buflen=sprintf(buffer, "%lu",
(unsigned long)(t2p->pdf_xrefcount + 3));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5);
written += TIFFWriteFile(output, (tdata_t) "/Identity ] ", 12);
}
written += TIFFWriteFile(output, (tdata_t) " >> \r", 5);
return(written);
}
static tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){
tsize_t written=0;
char buffer[32];
int buflen=0;
(void)i; // XXX
written += TIFFWriteFile(output, (tdata_t) "/FunctionType 0 \r", 17);
written += TIFFWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \r", 19);
written += TIFFWriteFile(output, (tdata_t) "/Range [0.0 1.0] \r", 18);
buflen=sprintf(buffer, "/Size [%u] \r", (1<<t2p->tiff_bitspersample));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/BitsPerSample 16 \r", 19);
written += t2p_write_pdf_stream_dict(1<<(t2p->tiff_bitspersample+1), 0, output);
return(written);
}
static tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){
tsize_t written=0;
written += t2p_write_pdf_stream(
t2p->tiff_transferfunction[i],
(1<<(t2p->tiff_bitspersample+1)),
output);
return(written);
}
/*
This function writes a PDF Image XObject Colorspace array to output.
*/
static tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[128];
int buflen=0;
float X_W=0.0;
float Y_W=0.0;
float Z_W=0.0;
float X_R=0.0;
float Y_R=0.0;
float Z_R=0.0;
float X_G=0.0;
float Y_G=0.0;
float Z_G=0.0;
float X_B=0.0;
float Y_B=0.0;
float Z_B=0.0;
float x_w=0.0;
float y_w=0.0;
float z_w=0.0;
float x_r=0.0;
float y_r=0.0;
float x_g=0.0;
float y_g=0.0;
float x_b=0.0;
float y_b=0.0;
float R=1.0;
float G=1.0;
float B=1.0;
written += TIFFWriteFile(output, (tdata_t) "[", 1);
if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
written += TIFFWriteFile(output, (tdata_t) "/CalGray ", 9);
X_W = t2p->tiff_whitechromaticities[0];
Y_W = t2p->tiff_whitechromaticities[1];
Z_W = 1.0F - (X_W + Y_W);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0F;
}
if(t2p->pdf_colorspace & T2P_CS_CALRGB){
written += TIFFWriteFile(output, (tdata_t) "/CalRGB ", 8);
x_w = t2p->tiff_whitechromaticities[0];
y_w = t2p->tiff_whitechromaticities[1];
x_r = t2p->tiff_primarychromaticities[0];
y_r = t2p->tiff_primarychromaticities[1];
x_g = t2p->tiff_primarychromaticities[2];
y_g = t2p->tiff_primarychromaticities[3];
x_b = t2p->tiff_primarychromaticities[4];
y_b = t2p->tiff_primarychromaticities[5];
z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b);
Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w;
X_R = Y_R * x_r / y_r;
Z_R = Y_R * (((1-x_r)/y_r)-1);
Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w;
X_G = Y_G * x_g / y_g;
Z_G = Y_G * (((1-x_g)/y_g)-1);
Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w;
X_B = Y_B * x_b / y_b;
Z_B = Y_B * (((1-x_b)/y_b)-1);
X_W = (X_R * R) + (X_G * G) + (X_B * B);
Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B);
Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B);
X_W /= Y_W;
Z_W /= Y_W;
Y_W = 1.0;
}
written += TIFFWriteFile(output, (tdata_t) "<< \r", 4);
if(t2p->pdf_colorspace & T2P_CS_CALGRAY){
written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12);
buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Gamma 2.2 \r", 12);
}
if(t2p->pdf_colorspace & T2P_CS_CALRGB){
written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12);
buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Matrix ", 8);
buflen=sprintf(buffer, "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \r",
X_R, Y_R, Z_R,
X_G, Y_G, Z_G,
X_B, Y_B, Z_B);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \r", 22);
}
written += TIFFWriteFile(output, (tdata_t) ">>] \r", 5);
return(written);
}
/*
This function writes a PDF Image XObject Colorspace array to output.
*/
static tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "[/ICCBased ", 11);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_icccs);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " 0 R] \r", 7);
return(written);
}
static tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
written += TIFFWriteFile(output, (tdata_t) "/N ", 3);
buflen=sprintf(buffer, "%u \r", t2p->tiff_samplesperpixel);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) "/Alternate ", 11);
t2p->pdf_colorspace ^= T2P_CS_ICCBASED;
written += t2p_write_pdf_xobject_cs(t2p, output);
t2p->pdf_colorspace |= T2P_CS_ICCBASED;
written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output);
return(written);
}
static tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){
tsize_t written=0;
written += t2p_write_pdf_stream(
(tdata_t) t2p->tiff_iccprofile,
(tsize_t) t2p->tiff_iccprofilelength,
output);
return(written);
}
/*
This function writes a palette stream for an indexed color space to output.
*/
static tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){
tsize_t written=0;
written += t2p_write_pdf_stream(
(tdata_t) t2p->pdf_palette,
(tsize_t) t2p->pdf_palettesize,
output);
return(written);
}
/*
This function writes a PDF Image XObject Decode array to output.
*/
static tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){
tsize_t written=0;
int i=0;
written += TIFFWriteFile(output, (tdata_t) "/Decode [ ", 10);
for (i=0;i<t2p->tiff_samplesperpixel;i++){
written += TIFFWriteFile(output, (tdata_t) "1 0 ", 4);
}
written += TIFFWriteFile(output, (tdata_t) "]\r", 2);
return(written);
}
/*
This function writes a PDF Image XObject stream filter name and parameters to
output.
*/
static tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[16];
int buflen=0;
if(t2p->pdf_compression==T2P_COMPRESS_NONE){
return(written);
}
written += TIFFWriteFile(output, (tdata_t) "/Filter ", 8);
switch(t2p->pdf_compression){
#ifdef CCITT_SUPPORT
case T2P_COMPRESS_G4:
written += TIFFWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16);
written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13);
written += TIFFWriteFile(output, (tdata_t) "<< /K -1 ", 9);
if(tile==0){
written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9);
buflen=sprintf(buffer, "%lu",
(unsigned long)t2p->tiff_width);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7);
buflen=sprintf(buffer, "%lu",
(unsigned long)t2p->tiff_length);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
} else {
if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9);
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
} else {
written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9);
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
}
if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){
written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7);
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
} else {
written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7);
buflen=sprintf(
buffer,
"%lu",
(unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
}
}
if(t2p->pdf_switchdecode == 0){
written += TIFFWriteFile(output, (tdata_t) " /BlackIs1 true ", 16);
}
written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
break;
#endif
#ifdef JPEG_SUPPORT
case T2P_COMPRESS_JPEG:
written += TIFFWriteFile(output, (tdata_t) "/DCTDecode ", 11);
if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) {
written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13);
written += TIFFWriteFile(output, (tdata_t) "<< /ColorTransform 0 >>\r", 24);
}
break;
#endif
#ifdef ZIP_SUPPORT
case T2P_COMPRESS_ZIP:
written += TIFFWriteFile(output, (tdata_t) "/FlateDecode ", 13);
if(t2p->pdf_compressionquality%100){
written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13);
written += TIFFWriteFile(output, (tdata_t) "<< /Predictor ", 14);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%u", t2p->pdf_compressionquality%100);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " /Columns ", 10);
_TIFFmemset(buffer, 0x00, 16);
buflen = sprintf(buffer, "%lu",
(unsigned long)t2p->tiff_width);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " /Colors ", 9);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%u", t2p->tiff_samplesperpixel);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " /BitsPerComponent ", 19);
_TIFFmemset(buffer, 0x00, 16);
buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) ">>\r", 3);
}
break;
#endif
default:
break;
}
return(written);
}
/*
This function writes a PDF xref table to output.
*/
static tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){
tsize_t written=0;
char buffer[21];
int buflen=0;
uint32 i=0;
written += TIFFWriteFile(output, (tdata_t) "xref\r0 ", 7);
buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
written += TIFFWriteFile(output, (tdata_t) " \r0000000000 65535 f\r\n", 22);
for (i=0;i<t2p->pdf_xrefcount;i++){
sprintf(buffer, "%.10lu 00000 n\r\n",
(unsigned long)t2p->pdf_xrefoffsets[i]);
written += TIFFWriteFile(output, (tdata_t) buffer, 20);
}
return(written);
}
/*
* This function writes a PDF trailer to output.
*/
static tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output)
{
tsize_t written = 0;
char buffer[32];
int buflen = 0;
int ifileidbuf[4];
char *fileidbuf = (char*)ifileidbuf;
int i = 0;
ifileidbuf[0] = rand();
ifileidbuf[1] = rand();
ifileidbuf[2] = rand();
ifileidbuf[3] = rand();
t2p->pdf_fileid = (char*)_TIFFmalloc(33);
if(t2p->pdf_fileid == NULL) {
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_write_pdf_trailer",
33 );
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemset(t2p->pdf_fileid, 0x00, 33);
for (i=0; i<16; i++)
sprintf(&(t2p->pdf_fileid[2*i]), "%.2hhX", fileidbuf[i]);
written += TIFFWriteFile(output, (tdata_t) "trailer\r<<\r/Size ", 17);
buflen = sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount+1));
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
_TIFFmemset(buffer, 0x00, 32);
written += TIFFWriteFile(output, (tdata_t) "\r/Root ", 7);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_catalog);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
_TIFFmemset(buffer, 0x00, 32);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r/Info ", 12);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_info);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
_TIFFmemset(buffer, 0x00, 32);
written += TIFFWriteFile(output, (tdata_t) " 0 R \r/ID[<", 11);
written += TIFFWriteFile(output, (tdata_t) t2p->pdf_fileid, 32);
written += TIFFWriteFile(output, (tdata_t) "><", 2);
written += TIFFWriteFile(output, (tdata_t) t2p->pdf_fileid, 32);
written += TIFFWriteFile(output, (tdata_t) ">]\r>>\rstartxref\r", 16);
buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_startxref);
written += TIFFWriteFile(output, (tdata_t) buffer, buflen);
_TIFFmemset(buffer, 0x00, 32);
written += TIFFWriteFile(output, (tdata_t) "\r%%EOF\r", 7);
return(written);
}
/*
This function writes a PDF to a file given a pointer to a TIFF.
The idea with using a TIFF* as output for a PDF file is that the file
can be created with TIFFClientOpen for memory-mapped use within the TIFF
library, and TIFFWriteEncodedStrip can be used to write compressed data to
the output. The output is not actually a TIFF file, it is a PDF file.
This function uses only TIFFWriteFile and TIFFWriteEncodedStrip to write to
the output TIFF file. When libtiff would otherwise be writing data to the
output file, the write procedure of the TIFF structure is replaced with an
empty implementation.
The first argument to the function is an initialized and validated T2P
context struct pointer.
The second argument to the function is the TIFF* that is the input that has
been opened for reading and no other functions have been called upon it.
The third argument to the function is the TIFF* that is the output that has
been opened for writing. It has to be opened so that it hasn't written any
data to the output. If the output is seekable then it's OK to seek to the
beginning of the file. The function only writes to the output PDF and does
not seek. See the example usage in the main() function.
TIFF* output = TIFFOpen("output.pdf", "w");
assert(output != NULL);
if(output->tif_seekproc != NULL){
TIFFSeekFile(output, (toff_t) 0, SEEK_SET);
}
This function returns the file size of the output PDF file. On error it
returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR.
After this function completes, call t2p_free on t2p, TIFFClose on input,
and TIFFClose on output.
*/
static tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){
tsize_t written=0;
ttile_t i2=0;
tsize_t streamlen=0;
uint16 i=0;
t2p_read_tiff_init(t2p, input);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(t2p->pdf_xrefcount * sizeof(uint32) );
if(t2p->pdf_xrefoffsets==NULL){
TIFFError(
TIFF2PDF_MODULE,
"Can't allocate %lu bytes of memory for t2p_write_pdf",
t2p->pdf_xrefcount * sizeof(uint32) );
return(written);
}
t2p->pdf_xrefcount=0;
t2p->pdf_catalog=1;
t2p->pdf_info=2;
t2p->pdf_pages=3;
written += t2p_write_pdf_header(t2p, output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_catalog=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_catalog(t2p, output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_info=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_info(t2p, input, output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_pages=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_pages(t2p, output);
written += t2p_write_pdf_obj_end(output);
for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){
t2p_read_tiff_data(t2p, input);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
written += t2p_write_pdf_page_content_stream(t2p, output);
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_length(streamlen, output);
written += t2p_write_pdf_obj_end(output);
if(t2p->tiff_transferfunctioncount != 0){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_transfer(t2p, output);
written += t2p_write_pdf_obj_end(output);
for(i=0; i < t2p->tiff_transferfunctioncount; i++){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_transfer_dict(t2p, output, i);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
written += t2p_write_pdf_transfer_stream(t2p, output, i);
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
}
}
if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_palettecs=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
written += t2p_write_pdf_xobject_palettecs_stream(t2p, output);
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
}
if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
t2p->pdf_icccs=t2p->pdf_xrefcount;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_xobject_icccs_dict(t2p, output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
written += t2p_write_pdf_xobject_icccs_stream(t2p, output);
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
}
if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){
for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_xobject_stream_dict(
i2+1,
t2p,
output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
t2p_read_tiff_size_tile(t2p, input, i2);
written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2);
t2p_write_advance_directory(t2p, output);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_length(streamlen, output);
written += t2p_write_pdf_obj_end(output);
}
} else {
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_dict_start(output);
written += t2p_write_pdf_xobject_stream_dict(
0,
t2p,
output);
written += t2p_write_pdf_stream_dict_end(output);
written += t2p_write_pdf_stream_start(output);
streamlen=written;
t2p_read_tiff_size(t2p, input);
written += t2p_readwrite_pdf_image(t2p, input, output);
t2p_write_advance_directory(t2p, output);
if(t2p->t2p_error!=T2P_ERR_OK){return(0);}
streamlen=written-streamlen;
written += t2p_write_pdf_stream_end(output);
written += t2p_write_pdf_obj_end(output);
t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written;
written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output);
written += t2p_write_pdf_stream_length(streamlen, output);
written += t2p_write_pdf_obj_end(output);
}
}
t2p->pdf_startxref=written;
written += t2p_write_pdf_xreftable(t2p, output);
written += t2p_write_pdf_trailer(t2p, output);
t2p_disable(output);
return(written);
}
#endif
/* vim: set ts=8 sts=8 sw=8 noet: */
| Stannislav/djvulibre-3.5.25 | tools/tiff2pdf.c | C | gpl-2.0 | 159,904 |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit562156c4d0b385426dfb2e9042c495a5::getLoader();
| tumanob/Lib.KG | wp-content/plugins/wp-filebase/vendor/autoload.php | PHP | gpl-2.0 | 183 |
<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2014 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* 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.
*/
require_once CLASS_EX_REALDIR . 'page_extends/admin/LC_Page_Admin_Ex.php';
/**
* オーナーズストア:認証キー設定 のページクラス.
*
* @package Page
* @author LOCKON CO.,LTD.
* @version $Id: LC_Page_Admin_OwnersStore_Settings.php 23546 2014-06-12 14:47:59Z shutta $
*/
class LC_Page_Admin_OwnersStore_Settings extends LC_Page_Admin_Ex
{
/** SC_FormParamのインスタンス */
public $objForm;
/** リクエストパラメーターを格納する連想配列 */
public $arrForm;
/** バリデーションエラー情報を格納する連想配列 */
public $arrErr;
/**
* Page を初期化する.
*
* @return void
*/
public function init()
{
parent::init();
$this->tpl_mainpage = 'ownersstore/settings.tpl';
$this->tpl_mainno = 'ownersstore';
$this->tpl_subno = 'settings';
$this->tpl_maintitle = 'オーナーズストア';
$this->tpl_subtitle = '認証キー設定';
$this->httpCacheControl('nocache');
}
/**
* Page のプロセス.
*
* @return void
*/
public function process()
{
$this->action();
$this->sendResponse();
}
/**
* Page のアクション.
*
* @return void
*/
public function action()
{
switch ($this->getMode()) {
// 入力内容をDBへ登録する
case 'register':
$this->execRegisterMode();
break;
// 初回表示
default:
$this->execDefaultMode();
}
}
/**
* registerアクションの実行.
* 入力内容をDBへ登録する.
*
* @param void
* @return void
*/
public function execRegisterMode()
{
// パラメーターオブジェクトの初期化
$this->initRegisterMode();
// POSTされたパラメーターの検証
$arrErr = $this->validateRegistermode();
// エラー時の処理
if (!empty($arrErr)) {
$this->arrErr = $arrErr;
$this->arrForm = $this->objForm->getHashArray();
return;
}
// エラーがなければDBへ登録
$arrForm = $this->objForm->getHashArray();
$this->registerOwnersStoreSettings($arrForm);
$this->arrForm = $arrForm;
$this->tpl_onload = "alert('登録しました。')";
}
/**
* registerアクションの初期化.
* SC_FormParamを初期化しメンバ変数にセットする.
*
* @param void
* @return void
*/
public function initRegisterMode()
{
// 前後の空白を削除
if (isset($_POST['public_key'])) {
$_POST['public_key'] = trim($_POST['public_key']);
}
$objForm = new SC_FormParam_Ex();
$objForm->addParam('認証キー', 'public_key', LTEXT_LEN, '', array('EXIST_CHECK', 'ALNUM_CHECK', 'MAX_LENGTH_CHECK'));
$objForm->setParam($_POST);
$this->objForm = $objForm;
}
/**
* registerアクションのパラメーターを検証する.
*
* @param void
* @return array エラー情報を格納した連想配列
*/
public function validateRegistermode()
{
return $this->objForm->checkError();
}
/**
* defaultアクションの実行.
* DBから登録内容を取得し表示する.
*
* @param void
* @return void
*/
public function execDefaultMode()
{
$this->arrForm = $this->getOwnersStoreSettings();
}
/**
* DBへ入力内容を登録する.
*
* @param array $arrSettingsData オーナーズストア設定の連想配列
* @return void
*/
public function registerOwnersStoreSettings($arrSettingsData)
{
$table = 'dtb_ownersstore_settings';
$objQuery =& SC_Query_Ex::getSingletonInstance();
$exists = $objQuery->exists($table);
if ($exists) {
$objQuery->update($table, $arrSettingsData);
} else {
$objQuery->insert($table, $arrSettingsData);
}
}
/**
* DBから登録内容を取得する.
*
* @param void
* @return array
*/
public function getOwnersStoreSettings()
{
$table = 'dtb_ownersstore_settings';
$colmuns = '*';
$objQuery =& SC_Query_Ex::getSingletonInstance();
$arrRet = $objQuery->select($colmuns, $table);
if (isset($arrRet[0])) return $arrRet[0];
return array();
}
}
| shoheiworks/Labo-EcCube | data/class/pages/admin/ownersstore/LC_Page_Admin_OwnersStore_Settings.php | PHP | gpl-2.0 | 5,480 |
<?php
/**
* ClickBank® API Constants *(for site owners)*.
*
* Copyright: © 2009-2011
* {@link http://www.websharks-inc.com/ WebSharks, Inc.}
* (coded in the USA)
*
* This WordPress® plugin (s2Member Pro) is comprised of two parts:
*
* o (1) Its PHP code is licensed under the GPL license, as is WordPress®.
* You should have received a copy of the GNU General Public License,
* along with this software. In the main directory, see: /licensing/
* If not, see: {@link http://www.gnu.org/licenses/}.
*
* o (2) All other parts of (s2Member Pro); including, but not limited to:
* the CSS code, some JavaScript code, images, and design;
* are licensed according to the license purchased.
* See: {@link http://www.s2member.com/prices/}
*
* Unless you have our prior written consent, you must NOT directly or indirectly license,
* sub-license, sell, resell, or provide for free; part (2) of the s2Member Pro Module;
* or make an offer to do any of these things. All of these things are strictly
* prohibited with part (2) of the s2Member Pro Module.
*
* Your purchase of s2Member Pro includes free lifetime upgrades via s2Member.com
* (i.e. new features, bug fixes, updates, improvements); along with full access
* to our video tutorial library: {@link http://www.s2member.com/videos/}
*
* @package s2Member\API_Constants
* @since 1.5
*/
if (realpath (__FILE__) === realpath ($_SERVER["SCRIPT_FILENAME"]))
exit("Do not access this file directly.");
if (!class_exists ("c_ws_plugin__s2member_pro_clickbank_constants"))
{
/**
* ClickBank® API Constants *(for site owners)*.
*
* @package s2Member\API_Constants
* @since 1.5
*/
class c_ws_plugin__s2member_pro_clickbank_constants
{
/**
* ClickBank® API Constants *(for site owners)*.
*
* @package s2Member\API_Constants
* @since 1.5
*
* @attaches-to ``add_filter("ws_plugin__s2member_during_constants_c");``
*
* @param array $c Checksum array should be passed through by the Filter.
* @param array $vars Array of defined variables, passed through by the Filter.
* @return array Checksum array with new indexes for Constant values.
*/
public static function clickbank_constants ($c = FALSE, $vars = FALSE)
{
/**
* Flag indicating the ClickBank® Gateway is active.
*
* @package s2Member\API_Constants
* @since 1.5
*
* @var bool
*/
if (!defined ("S2MEMBER_PRO_CLICKBANK_GATEWAY"))
define ("S2MEMBER_PRO_CLICKBANK_GATEWAY", ($c[] = true));
return $c; // Return $c calculation values.
}
}
}
?> | foxydot/walker | wp-content/plugins/s2member-pro/includes/classes/gateways/clickbank/clickbank-constants.inc.php | PHP | gpl-2.0 | 2,593 |
<?php
/**
* File contains: eZ\Publish\Core\Persistence\Legacy\Tests\User\UserHandlerTest class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*
* @version //autogentag//
*/
namespace eZ\Publish\Core\Persistence\Legacy\Tests\User;
use eZ\Publish\API\Repository\Values\User\Role as APIRole;
use eZ\Publish\Core\Persistence\Legacy\Tests\TestCase;
use eZ\Publish\Core\Persistence\Legacy\User;
use eZ\Publish\Core\Persistence\Legacy\User\Role\LimitationConverter;
use eZ\Publish\Core\Persistence\Legacy\User\Role\LimitationHandler\ObjectStateHandler as ObjectStateLimitationHandler;
use eZ\Publish\SPI\Persistence;
/**
* Test case for UserHandlerTest.
*/
class UserHandlerTest extends TestCase
{
protected function getUserHandler()
{
$dbHandler = $this->getDatabaseHandler();
return new User\Handler(
new User\Gateway\DoctrineDatabase($dbHandler),
new User\Role\Gateway\DoctrineDatabase($dbHandler),
new User\Mapper(),
new LimitationConverter(array(new ObjectStateLimitationHandler($dbHandler)))
);
}
protected function getValidUser()
{
$user = new Persistence\User();
$user->id = 42;
$user->login = 'kore';
$user->email = 'kore@example.org';
$user->passwordHash = '1234567890';
$user->hashAlgorithm = 2;
$user->isEnabled = true;
$user->maxLogin = 23;
return $user;
}
public function testCreateUser()
{
$handler = $this->getUserHandler();
$handler->create($this->getValidUser());
$this->assertQueryResult(
array(array(1)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected one user to be created.'
);
$this->assertQueryResult(
array(array(1)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser_setting'),
'Expected one user setting to be created.'
);
}
/**
* @expectedException \Doctrine\DBAL\DBALException
*/
public function testCreateDuplicateUser()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$handler->create($user);
}
/**
* @expectedException \Doctrine\DBAL\DBALException
*/
public function testInsertIncompleteUser()
{
$handler = $this->getUserHandler();
$user = new Persistence\User();
$user->id = 42;
$handler->create($user);
}
public function testLoadUser()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$this->assertEquals(
$user,
$handler->load($user->id)
);
}
/**
* @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
*/
public function testLoadUnknownUser()
{
$handler = $this->getUserHandler();
$handler->load(1337);
}
public function testLoadUserByLogin()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$loadedUser = $handler->loadByLogin($user->login);
$this->assertEquals(
$user,
$loadedUser
);
}
/**
* @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
*/
public function testLoadUserByEmailNotFound()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$handler->loadByLogin($user->email);
}
public function testLoadUserByEmail()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$users = $handler->loadByEmail($user->email);
$this->assertEquals(
$user,
$users[0]
);
}
public function testCreateAndDeleteUser()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$this->assertQueryResult(
array(array(1)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected one user to be created.'
);
$this->assertQueryResult(
array(array(1)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser_setting'),
'Expected one user setting to be created.'
);
$handler->delete($user->id);
$this->assertQueryResult(
array(array(0)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected one user to be removed.'
);
$this->assertQueryResult(
array(array(0)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser_setting'),
'Expected one user setting to be removed.'
);
}
public function testDeleteNonExistingUser()
{
$handler = $this->getUserHandler();
$handler->delete(1337);
$this->assertQueryResult(
array(array(0)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected no existing user.'
);
}
public function testUpdateUser()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$user->login = 'New_lögin';
$handler->update($user);
$this->assertQueryResult(
array(array(42, 'kore@example.org', 'New_lögin', 'new_lögin', 1234567890, '2')),
$this->handler->createSelectQuery()->select('*')->from('ezuser'),
'Expected user data to be updated.'
);
}
public function testUpdateUserSettings()
{
$handler = $this->getUserHandler();
$handler->create($user = $this->getValidUser());
$user->maxLogin = 42;
$handler->update($user);
$this->assertQueryResult(
array(array(1, 42, 42)),
$this->handler->createSelectQuery()->select('*')->from('ezuser_setting'),
'Expected user data to be updated.'
);
}
public function testSilentlyUpdateNotExistingUser()
{
$handler = $this->getUserHandler();
$handler->update($this->getValidUser());
$this->assertQueryResult(
array(array(0)),
$this->handler->createSelectQuery()->select('COUNT( * )')->from('ezuser'),
'Expected no existing user.'
);
}
public function testCreateNewRoleWithoutPolicies()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$handler->createRole($createStruct);
$this->assertQueryResult(
array(array(1, 'Test', -1)),
$this->handler->createSelectQuery()->select('id', 'name', 'version')->from('ezrole'),
'Expected a new role draft.'
);
}
public function testCreateRoleDraftWithoutPolicies()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$handler->createRoleDraft($roleDraft->id);
$publishedRoleId = 1;
$this->assertQueryResult(
[
[$publishedRoleId, 'Test', APIRole::STATUS_DEFINED],
[2, 'Test', $publishedRoleId],
],
$this->handler->createSelectQuery()->select('id', 'name', 'version')->from('ezrole'),
'Expected a role and a role draft.'
);
}
public function testCreateNewRoleRoleId()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$this->assertSame('1', $roleDraft->id);
}
public function testLoadRole()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$this->assertEquals(
$roleDraft->id,
$role->id
);
}
public function testLoadRoleWithPolicies()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$handler->addPolicyByRoleDraft($roleDraft->id, $policy);
$handler->publishRoleDraft($roleDraft->id);
$loaded = $handler->loadRole($roleDraft->id);
$this->assertEquals(
array(
new Persistence\User\Policy(
array(
'id' => 1,
'roleId' => 1,
'module' => 'foo',
'function' => 'bar',
'limitations' => '*',
'originalId' => null,
)
),
),
$loaded->policies
);
}
public function testLoadRoleWithPoliciesAndGroups()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$handler->addPolicyByRoleDraft($roleDraft->id, $policy);
$handler->assignRole(23, $roleDraft->id);
$handler->assignRole(42, $roleDraft->id);
$handler->publishRoleDraft($roleDraft->id);
$loaded = $handler->loadRole($roleDraft->id);
$this->assertEquals(
array(
new Persistence\User\Policy(
array(
'id' => 1,
'roleId' => 1,
'module' => 'foo',
'function' => 'bar',
'limitations' => '*',
'originalId' => null,
)
),
),
$loaded->policies
);
}
public function testLoadRoleWithPolicyLimitations()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$policy->limitations = array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
);
$handler->addPolicyByRoleDraft($roleDraft->id, $policy);
$handler->publishRoleDraft($roleDraft->id);
$loaded = $handler->loadRole($roleDraft->id);
$this->assertEquals(
array(
new Persistence\User\Policy(
array(
'id' => 1,
'roleId' => 1,
'module' => 'foo',
'function' => 'bar',
'limitations' => array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
),
'originalId' => null,
)
),
),
$loaded->policies
);
}
public function testLoadRoles()
{
$handler = $this->getUserHandler();
$this->assertEquals(
array(),
$handler->loadRoles()
);
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$this->assertEquals(
array($role),
$handler->loadRoles()
);
}
public function testUpdateRole()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$update = new Persistence\User\RoleUpdateStruct();
$update->id = $role->id;
$update->identifier = 'Changed';
$handler->updateRole($update);
$this->assertQueryResult(
array(array(1, 'Changed')),
$this->handler->createSelectQuery()->select('id', 'name')->from('ezrole'),
'Expected a changed role.'
);
}
public function testDeleteRole()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
// 3 is the ID of Editor role
$handler->deleteRole(3);
$this->assertQueryResult(
array(),
$this->handler->createSelectQuery()->select('id')->from('ezrole')->where('id = 3'),
'Expected an empty set.'
);
$this->assertQueryResult(
array(),
$this->handler->createSelectQuery()->select('role_id')->from('ezpolicy')->where('role_id = 3'),
'Expected an empty set.'
);
$this->assertQueryResult(
array(),
$this->handler->createSelectQuery()->select('role_id')->from('ezuser_role')->where('role_id = 3'),
'Expected an empty set.'
);
}
public function testDeleteRoleDraft()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
// 3 is the ID of Editor role
$roleDraft = $handler->createRoleDraft(3);
$handler->deleteRole($roleDraft->id, APIRole::STATUS_DRAFT);
$this->assertQueryResult(
[['3', APIRole::STATUS_DEFINED]],
$this->handler->createSelectQuery()->select('id, version')->from('ezrole')->where('id = 3'),
'Expected a published role.'
);
$this->assertQueryResult(
[[implode("\n", array_fill(0, 27, '3, ' . APIRole::STATUS_DEFINED))]],
$this->handler->createSelectQuery()->select('role_id, original_id')->from('ezpolicy')->where('role_id = 3'),
'Expected 27 policies for the published role.'
);
$this->assertQueryResult(
[[3], [3]],
$this->handler->createSelectQuery()->select('role_id')->from('ezuser_role')->where('role_id = 3'),
'Expected that role assignments still exist.'
);
}
public function testAddPolicyToRoleLimitations()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$handler->addPolicy($role->id, $policy);
$this->assertQueryResult(
array(array(1, 'foo', 'bar', 1)),
$this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy'),
'Expected a new policy.'
);
}
public function testAddPolicyPolicyId()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$policy = $handler->addPolicy($role->id, $policy);
$this->assertEquals(1, $policy->id);
}
public function testAddPolicyLimitations()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$policy->limitations = array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
);
$handler->addPolicy($role->id, $policy);
$this->assertQueryResult(
array(
array(1, 'Subtree', 1),
array(2, 'Foo', 1),
),
$this->handler->createSelectQuery()->select('id', 'identifier', 'policy_id')->from('ezpolicy_limitation'),
'Expected a new policy.'
);
}
public function testAddPolicyLimitationValues()
{
$handler = $this->getUserHandler();
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$roleDraft = $handler->createRole($createStruct);
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$policy = new Persistence\User\Policy();
$policy->module = 'foo';
$policy->function = 'bar';
$policy->limitations = array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
);
$handler->addPolicy($role->id, $policy);
$this->assertQueryResult(
array(
array(1, '/1', 1),
array(2, '/1/2', 1),
array(3, 'Bar', 2),
),
$this->handler->createSelectQuery()->select('id', 'value', 'limitation_id')->from('ezpolicy_limitation_value'),
'Expected a new policy.'
);
}
protected function createRole()
{
$handler = $this->getUserHandler();
$policy1 = new Persistence\User\Policy();
$policy1->module = 'foo';
$policy1->function = 'bar';
$policy1->limitations = array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
);
$policy2 = new Persistence\User\Policy();
$policy2->module = 'foo';
$policy2->function = 'blubb';
$policy2->limitations = array(
'Foo' => array('Blubb'),
);
$createStruct = new Persistence\User\RoleCreateStruct();
$createStruct->identifier = 'Test';
$createStruct->policies = array($policy1, $policy2);
return $handler->createRole($createStruct);
}
public function testImplicitlyCreatePolicies()
{
$this->createRole();
$this->assertQueryResult(
array(
array(1, 'foo', 'bar', 1),
array(2, 'foo', 'blubb', 1),
),
$this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy'),
'Expected a new policy.'
);
}
public function testDeletePolicy()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$handler->deletePolicy($roleDraft->policies[0]->id);
$this->assertQueryResult(
array(
array(2, 'foo', 'blubb', 1),
),
$this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy')->where('original_id = 0'),
'Expected a new policy.'
);
}
public function testDeletePolicyLimitations()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->deletePolicy($roleDraft->policies[0]->id);
$this->assertQueryResult(
array(array(3, 'Foo', 2)),
$this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation')
);
}
public function testDeletePolicyLimitationValues()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->deletePolicy($roleDraft->policies[0]->id);
$this->assertQueryResult(
array(array(4, 3, 'Blubb')),
$this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation_value')
);
}
public function testUpdatePolicies()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$policy = $roleDraft->policies[0];
$policy->limitations = array(
'new' => array('something'),
);
$handler->updatePolicy($policy);
$this->assertQueryResult(
array(
array(3, 'Foo', 2),
array(4, 'new', 1),
),
$this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation')
);
$this->assertQueryResult(
array(
array(4, 3, 'Blubb'),
array(5, 4, 'something'),
),
$this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation_value')
);
}
public function testAddRoleToUser()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$handler->create($user = $this->getValidUser());
$handler->assignRole($user->id, $role->id, array());
$this->assertQueryResult(
array(
array(1, 42, 1, null, null),
),
$this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
'Expected a new user policy association.'
);
}
public function testAddRoleToUserWithLimitation()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$handler->create($user = $this->getValidUser());
$handler->assignRole(
$user->id,
$role->id,
array(
'Subtree' => array('/1'),
)
);
$this->assertQueryResult(
array(
array(1, 42, 1, 'Subtree', '/1'),
),
$this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
'Expected a new user policy association.'
);
}
public function testAddRoleToUserWithComplexLimitation()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$handler->create($user = $this->getValidUser());
$handler->assignRole(
$user->id,
$role->id,
array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
)
);
$this->assertQueryResult(
array(
array(1, 42, 1, 'Subtree', '/1'),
array(2, 42, 1, 'Subtree', '/1/2'),
array(3, 42, 1, 'Foo', 'Bar'),
),
$this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
'Expected a new user policy association.'
);
}
public function testRemoveUserRoleAssociation()
{
$handler = $this->getUserHandler();
$roleDraft = $this->createRole();
$handler->publishRoleDraft($roleDraft->id);
$role = $handler->loadRole($roleDraft->id);
$handler->create($user = $this->getValidUser());
$handler->assignRole(
$user->id,
$role->id,
array(
'Subtree' => array('/1', '/1/2'),
'Foo' => array('Bar'),
)
);
$handler->unassignRole($user->id, $role->id);
$this->assertQueryResult(
array(),
$this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
'Expected no user policy associations.'
);
}
public function testLoadPoliciesForUser()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$policies = $handler->loadPoliciesByUserId(10); // Anonymous user
// Verify, that we received an array of Policy objects
$this->assertTrue(
array_reduce(
array_map(
function ($policy) {
return $policy instanceof Persistence\User\Policy;
},
$policies
),
function ($a, $b) {
return $a && $b;
},
true
)
);
$this->assertEquals(8, count($policies));
}
public function testLoadRoleAssignmentsByGroupId()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 28,
'roleId' => 1,
'contentId' => 11,
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 34,
'roleId' => 5,
'contentId' => 11,
)
),
),
$handler->loadRoleAssignmentsByGroupId(11)// 11: Members
);
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 31,
'roleId' => 1,
'contentId' => 42,
)
),
),
$handler->loadRoleAssignmentsByGroupId(42)// 42: Anonymous Users
);
$this->assertEquals(
array(),
$handler->loadRoleAssignmentsByGroupId(10)// 10: Anonymous User
);
}
public function testLoadRoleAssignmentsByGroupIdInherited()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 31,
'roleId' => 1,
'contentId' => 42,
)
),
),
$handler->loadRoleAssignmentsByGroupId(10, true)// 10: Anonymous User
);
}
public function testLoadComplexRoleAssignments()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 32,
'roleId' => 3,
'contentId' => 13,
'limitationIdentifier' => 'Subtree',
'values' => array('/1/2/'),
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 33,
'roleId' => 3,
'contentId' => 13,
'limitationIdentifier' => 'Subtree',
'values' => array('/1/43/'),
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 38,
'roleId' => 5,
'contentId' => 13,
)
),
),
$handler->loadRoleAssignmentsByGroupId(13)
);
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 32,
'roleId' => 3,
'contentId' => 13,
'limitationIdentifier' => 'Subtree',
'values' => array('/1/2/'),
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 33,
'roleId' => 3,
'contentId' => 13,
'limitationIdentifier' => 'Subtree',
'values' => array('/1/43/'),
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 38,
'roleId' => 5,
'contentId' => 13,
)
),
),
$handler->loadRoleAssignmentsByGroupId(13, true)
);
}
public function testLoadRoleAssignmentsByRoleId()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$this->assertEquals(
array(
new Persistence\User\RoleAssignment(
array(
'id' => 28,
'roleId' => 1,
'contentId' => 11,
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 31,
'roleId' => 1,
'contentId' => 42,
)
),
new Persistence\User\RoleAssignment(
array(
'id' => 37,
'roleId' => 1,
'contentId' => 59,
)
),
),
$handler->loadRoleAssignmentsByRoleId(1)
);
}
public function testLoadRoleDraftByRoleId()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
// 3 is the ID of Editor role
$originalRoleId = 3;
$draft = $handler->createRoleDraft($originalRoleId);
$loadedDraft = $handler->loadRoleDraftByRoleId($originalRoleId);
self::assertSame($loadedDraft->originalId, $originalRoleId);
self::assertEquals($draft, $loadedDraft);
}
public function testRoleDraftOnlyHavePolicyDraft()
{
$this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/clean_ezdemo_47_dump.php');
$handler = $this->getUserHandler();
$originalRoleId = 3;
$originalRole = $handler->loadRole($originalRoleId);
$originalPolicies = [];
foreach ($originalRole->policies as $policy) {
$originalPolicies[$policy->id] = $policy;
}
$draft = $handler->createRoleDraft($originalRoleId);
$loadedDraft = $handler->loadRole($draft->id, Persistence\User\Role::STATUS_DRAFT);
self::assertSame($loadedDraft->originalId, $originalRoleId);
self::assertEquals($draft, $loadedDraft);
foreach ($loadedDraft->policies as $policy) {
self::assertTrue(isset($originalPolicies[$policy->originalId]));
}
// Now add a new policy. Original ID of the new one must be the same as its actual ID.
$newPolicyModule = 'foo';
$newPolicyFunction = 'bar';
$policy = new Persistence\User\Policy(['module' => $newPolicyModule, 'function' => $newPolicyFunction]);
$policyDraft = $handler->addPolicyByRoleDraft($loadedDraft->id, $policy);
// Test again by reloading the draft.
$loadedDraft = $handler->loadRole($draft->id, Persistence\User\Role::STATUS_DRAFT);
foreach ($loadedDraft->policies as $policy) {
if ($policy->id != $policyDraft->id) {
continue;
}
self::assertNotNull($policy->originalId);
self::assertSame($policy->id, $policy->originalId);
}
}
}
| lolautruche/ezpublish-kernel | eZ/Publish/Core/Persistence/Legacy/Tests/User/UserHandlerTest.php | PHP | gpl-2.0 | 34,490 |
# Exemplo: "Feliz Natal" em Esperanto: Gajan Kristnaskon
$ zznatal #→ --regex ^"Feliz Natal" em .+: .+$
| gmgall/funcoeszz | testador/zznatal.sh | Shell | gpl-2.0 | 108 |
/*
* Copyright (c) 1999-2005 Petko Manolov (petkan@users.sourceforge.net)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* ChangeLog:
* .... Most of the time spent on reading sources & docs.
* v0.2.x First official release for the Linux kernel.
* v0.3.0 Beutified and structured, some bugs fixed.
* v0.3.x URBifying bulk requests and bugfixing. First relatively
* stable release. Still can touch device's registers only
* from top-halves.
* v0.4.0 Control messages remained unurbified are now URBs.
* Now we can touch the HW at any time.
* v0.4.9 Control urbs again use process context to wait. Argh...
* Some long standing bugs (enable_net_traffic) fixed.
* Also nasty trick about resubmiting control urb from
* interrupt context used. Please let me know how it
* behaves. Pegasus II support added since this version.
* TODO: suppressing HCD warnings spewage on disconnect.
* v0.4.13 Ethernet address is now set at probe(), not at open()
* time as this seems to break dhcpd.
* v0.5.0 branch to 2.5.x kernels
* v0.5.1 ethtool support added
* v0.5.5 rx socket buffers are in a pool and the their allocation
* is out of the interrupt routine.
*/
#undef DEBUG
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/usb.h>
#include <linux/module.h>
#include <asm/byteorder.h>
#include <asm/uaccess.h>
#include "pegasus.h"
/*
* Version Information
*/
#define DRIVER_VERSION "v0.6.12 (2005/01/13)"
#define DRIVER_AUTHOR "Petko Manolov <petkan@users.sourceforge.net>"
#define DRIVER_DESC "Pegasus/Pegasus II USB Ethernet driver"
static const char driver_name[] = "pegasus";
#undef PEGASUS_WRITE_EEPROM
#define BMSR_MEDIA (BMSR_10HALF | BMSR_10FULL | BMSR_100HALF | \
BMSR_100FULL | BMSR_ANEGCAPABLE)
static int loopback = 0;
static int mii_mode = 0;
static struct usb_eth_dev usb_dev_id[] = {
#define PEGASUS_DEV(pn, vid, pid, flags) \
{.name = pn, .vendor = vid, .device = pid, .private = flags},
#include "pegasus.h"
#undef PEGASUS_DEV
{NULL, 0, 0, 0}
};
static struct usb_device_id pegasus_ids[] = {
#define PEGASUS_DEV(pn, vid, pid, flags) \
{.match_flags = USB_DEVICE_ID_MATCH_DEVICE, .idVendor = vid, .idProduct = pid},
#include "pegasus.h"
#undef PEGASUS_DEV
{}
};
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
module_param(loopback, bool, 0);
module_param(mii_mode, bool, 0);
MODULE_PARM_DESC(loopback, "Enable MAC loopback mode (bit 0)");
MODULE_PARM_DESC(mii_mode, "Enable HomePNA mode (bit 0),default=MII mode = 0");
/* use ethtool to change the level for any given device */
static int msg_level = -1;
module_param (msg_level, int, 0);
MODULE_PARM_DESC (msg_level, "Override default message level");
MODULE_DEVICE_TABLE(usb, pegasus_ids);
static int update_eth_regs_async(pegasus_t *);
/* Aargh!!! I _really_ hate such tweaks */
static void ctrl_callback(struct urb *urb, struct pt_regs *regs)
{
pegasus_t *pegasus = urb->context;
if (!pegasus)
return;
switch (urb->status) {
case 0:
if (pegasus->flags & ETH_REGS_CHANGE) {
pegasus->flags &= ~ETH_REGS_CHANGE;
pegasus->flags |= ETH_REGS_CHANGED;
update_eth_regs_async(pegasus);
return;
}
break;
case -EINPROGRESS:
return;
case -ENOENT:
break;
default:
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, urb->status);
}
pegasus->flags &= ~ETH_REGS_CHANGED;
wake_up(&pegasus->ctrl_wait);
}
static int get_registers(pegasus_t * pegasus, __u16 indx, __u16 size,
void *data)
{
int ret;
char *buffer;
DECLARE_WAITQUEUE(wait, current);
buffer = kmalloc(size, GFP_KERNEL);
if (!buffer) {
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "out of memory in %s\n",
__FUNCTION__);
return -ENOMEM;
}
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
while (pegasus->flags & ETH_REGS_CHANGED)
schedule();
remove_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_RUNNING);
pegasus->dr.bRequestType = PEGASUS_REQT_READ;
pegasus->dr.bRequest = PEGASUS_REQ_GET_REGS;
pegasus->dr.wValue = cpu_to_le16(0);
pegasus->dr.wIndex = cpu_to_le16p(&indx);
pegasus->dr.wLength = cpu_to_le16p(&size);
pegasus->ctrl_urb->transfer_buffer_length = size;
usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb,
usb_rcvctrlpipe(pegasus->usb, 0),
(char *) &pegasus->dr,
buffer, size, ctrl_callback, pegasus);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
/* using ATOMIC, we'd never wake up if we slept */
if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) {
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, ret);
goto out;
}
schedule();
out:
remove_wait_queue(&pegasus->ctrl_wait, &wait);
memcpy(data, buffer, size);
kfree(buffer);
return ret;
}
static int set_registers(pegasus_t * pegasus, __u16 indx, __u16 size,
void *data)
{
int ret;
char *buffer;
DECLARE_WAITQUEUE(wait, current);
buffer = kmalloc(size, GFP_KERNEL);
if (!buffer) {
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "out of memory in %s\n",
__FUNCTION__);
return -ENOMEM;
}
memcpy(buffer, data, size);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
while (pegasus->flags & ETH_REGS_CHANGED)
schedule();
remove_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_RUNNING);
pegasus->dr.bRequestType = PEGASUS_REQT_WRITE;
pegasus->dr.bRequest = PEGASUS_REQ_SET_REGS;
pegasus->dr.wValue = cpu_to_le16(0);
pegasus->dr.wIndex = cpu_to_le16p(&indx);
pegasus->dr.wLength = cpu_to_le16p(&size);
pegasus->ctrl_urb->transfer_buffer_length = size;
usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb,
usb_sndctrlpipe(pegasus->usb, 0),
(char *) &pegasus->dr,
buffer, size, ctrl_callback, pegasus);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) {
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, ret);
goto out;
}
schedule();
out:
remove_wait_queue(&pegasus->ctrl_wait, &wait);
kfree(buffer);
return ret;
}
static int set_register(pegasus_t * pegasus, __u16 indx, __u8 data)
{
int ret;
char *tmp;
DECLARE_WAITQUEUE(wait, current);
tmp = kmalloc(1, GFP_KERNEL);
if (!tmp) {
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "out of memory in %s\n",
__FUNCTION__);
return -ENOMEM;
}
memcpy(tmp, &data, 1);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
while (pegasus->flags & ETH_REGS_CHANGED)
schedule();
remove_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_RUNNING);
pegasus->dr.bRequestType = PEGASUS_REQT_WRITE;
pegasus->dr.bRequest = PEGASUS_REQ_SET_REG;
pegasus->dr.wValue = cpu_to_le16(data);
pegasus->dr.wIndex = cpu_to_le16p(&indx);
pegasus->dr.wLength = cpu_to_le16(1);
pegasus->ctrl_urb->transfer_buffer_length = 1;
usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb,
usb_sndctrlpipe(pegasus->usb, 0),
(char *) &pegasus->dr,
&tmp, 1, ctrl_callback, pegasus);
add_wait_queue(&pegasus->ctrl_wait, &wait);
set_current_state(TASK_UNINTERRUPTIBLE);
if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) {
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, ret);
goto out;
}
schedule();
out:
remove_wait_queue(&pegasus->ctrl_wait, &wait);
kfree(tmp);
return ret;
}
static int update_eth_regs_async(pegasus_t * pegasus)
{
int ret;
pegasus->dr.bRequestType = PEGASUS_REQT_WRITE;
pegasus->dr.bRequest = PEGASUS_REQ_SET_REGS;
pegasus->dr.wValue = 0;
pegasus->dr.wIndex = cpu_to_le16(EthCtrl0);
pegasus->dr.wLength = cpu_to_le16(3);
pegasus->ctrl_urb->transfer_buffer_length = 3;
usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb,
usb_sndctrlpipe(pegasus->usb, 0),
(char *) &pegasus->dr,
pegasus->eth_regs, 3, ctrl_callback, pegasus);
if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC)))
if (netif_msg_drv(pegasus))
dev_err(&pegasus->intf->dev, "%s, status %d\n",
__FUNCTION__, ret);
return ret;
}
static int read_mii_word(pegasus_t * pegasus, __u8 phy, __u8 indx, __u16 * regd)
{
int i;
__u8 data[4] = { phy, 0, 0, indx };
__le16 regdi;
int ret;
ret = set_register(pegasus, PhyCtrl, 0);
ret = set_registers(pegasus, PhyAddr, sizeof (data), data);
ret = set_register(pegasus, PhyCtrl, (indx | PHY_READ));
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, PhyCtrl, 1, data);
if (data[0] & PHY_DONE)
break;
}
if (i < REG_TIMEOUT) {
ret = get_registers(pegasus, PhyData, 2, ®di);
*regd = le16_to_cpu(regdi);
return 1;
}
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__);
return 0;
}
static int mdio_read(struct net_device *dev, int phy_id, int loc)
{
pegasus_t *pegasus = (pegasus_t *) netdev_priv(dev);
u16 res;
read_mii_word(pegasus, phy_id, loc, &res);
return (int)res;
}
static int write_mii_word(pegasus_t * pegasus, __u8 phy, __u8 indx, __u16 regd)
{
int i;
__u8 data[4] = { phy, 0, 0, indx };
int ret;
data[1] = (u8) regd;
data[2] = (u8) (regd >> 8);
ret = set_register(pegasus, PhyCtrl, 0);
ret = set_registers(pegasus, PhyAddr, sizeof(data), data);
ret = set_register(pegasus, PhyCtrl, (indx | PHY_WRITE));
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, PhyCtrl, 1, data);
if (data[0] & PHY_DONE)
break;
}
if (i < REG_TIMEOUT)
return 0;
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__);
return 1;
}
static void mdio_write(struct net_device *dev, int phy_id, int loc, int val)
{
pegasus_t *pegasus = (pegasus_t *) netdev_priv(dev);
write_mii_word(pegasus, phy_id, loc, val);
}
static int read_eprom_word(pegasus_t * pegasus, __u8 index, __u16 * retdata)
{
int i;
__u8 tmp;
__le16 retdatai;
int ret;
ret = set_register(pegasus, EpromCtrl, 0);
ret = set_register(pegasus, EpromOffset, index);
ret = set_register(pegasus, EpromCtrl, EPROM_READ);
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, EpromCtrl, 1, &tmp);
if (tmp & EPROM_DONE)
break;
}
if (i < REG_TIMEOUT) {
ret = get_registers(pegasus, EpromData, 2, &retdatai);
*retdata = le16_to_cpu(retdatai);
return 0;
}
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__);
return -1;
}
#ifdef PEGASUS_WRITE_EEPROM
static inline void enable_eprom_write(pegasus_t * pegasus)
{
__u8 tmp;
int ret;
ret = get_registers(pegasus, EthCtrl2, 1, &tmp);
ret = set_register(pegasus, EthCtrl2, tmp | EPROM_WR_ENABLE);
}
static inline void disable_eprom_write(pegasus_t * pegasus)
{
__u8 tmp;
int ret;
ret = get_registers(pegasus, EthCtrl2, 1, &tmp);
ret = set_register(pegasus, EpromCtrl, 0);
ret = set_register(pegasus, EthCtrl2, tmp & ~EPROM_WR_ENABLE);
}
static int write_eprom_word(pegasus_t * pegasus, __u8 index, __u16 data)
{
int i;
__u8 tmp, d[4] = { 0x3f, 0, 0, EPROM_WRITE };
int ret;
ret = set_registers(pegasus, EpromOffset, 4, d);
enable_eprom_write(pegasus);
ret = set_register(pegasus, EpromOffset, index);
ret = set_registers(pegasus, EpromData, 2, &data);
ret = set_register(pegasus, EpromCtrl, EPROM_WRITE);
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, EpromCtrl, 1, &tmp);
if (tmp & EPROM_DONE)
break;
}
disable_eprom_write(pegasus);
if (i < REG_TIMEOUT)
return 0;
if (netif_msg_drv(pegasus))
dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__);
return -1;
}
#endif /* PEGASUS_WRITE_EEPROM */
static inline void get_node_id(pegasus_t * pegasus, __u8 * id)
{
int i;
__u16 w16;
for (i = 0; i < 3; i++) {
read_eprom_word(pegasus, i, &w16);
((__le16 *) id)[i] = cpu_to_le16p(&w16);
}
}
static void set_ethernet_addr(pegasus_t * pegasus)
{
__u8 node_id[6];
int ret;
get_node_id(pegasus, node_id);
ret = set_registers(pegasus, EthID, sizeof (node_id), node_id);
memcpy(pegasus->net->dev_addr, node_id, sizeof (node_id));
}
static inline int reset_mac(pegasus_t * pegasus)
{
__u8 data = 0x8;
int i;
int ret;
ret = set_register(pegasus, EthCtrl1, data);
for (i = 0; i < REG_TIMEOUT; i++) {
ret = get_registers(pegasus, EthCtrl1, 1, &data);
if (~data & 0x08) {
if (loopback & 1)
break;
if (mii_mode && (pegasus->features & HAS_HOME_PNA))
ret = set_register(pegasus, Gpio1, 0x34);
else
ret = set_register(pegasus, Gpio1, 0x26);
ret = set_register(pegasus, Gpio0, pegasus->features);
ret = set_register(pegasus, Gpio0, DEFAULT_GPIO_SET);
break;
}
}
if (i == REG_TIMEOUT)
return 1;
if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS ||
usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) {
ret = set_register(pegasus, Gpio0, 0x24);
ret = set_register(pegasus, Gpio0, 0x26);
}
if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_ELCON) {
__u16 auxmode;
read_mii_word(pegasus, 3, 0x1b, &auxmode);
write_mii_word(pegasus, 3, 0x1b, auxmode | 4);
}
return 0;
}
static int enable_net_traffic(struct net_device *dev, struct usb_device *usb)
{
__u16 linkpart;
__u8 data[4];
pegasus_t *pegasus = netdev_priv(dev);
int ret;
read_mii_word(pegasus, pegasus->phy, MII_LPA, &linkpart);
data[0] = 0xc9;
data[1] = 0;
if (linkpart & (ADVERTISE_100FULL | ADVERTISE_10FULL))
data[1] |= 0x20; /* set full duplex */
if (linkpart & (ADVERTISE_100FULL | ADVERTISE_100HALF))
data[1] |= 0x10; /* set 100 Mbps */
if (mii_mode)
data[1] = 0;
data[2] = (loopback & 1) ? 0x09 : 0x01;
memcpy(pegasus->eth_regs, data, sizeof (data));
ret = set_registers(pegasus, EthCtrl0, 3, data);
if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS ||
usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) {
u16 auxmode;
read_mii_word(pegasus, 0, 0x1b, &auxmode);
write_mii_word(pegasus, 0, 0x1b, auxmode | 4);
}
return 0;
}
static void fill_skb_pool(pegasus_t * pegasus)
{
int i;
for (i = 0; i < RX_SKBS; i++) {
if (pegasus->rx_pool[i])
continue;
pegasus->rx_pool[i] = dev_alloc_skb(PEGASUS_MTU + 2);
/*
** we give up if the allocation fail. the tasklet will be
** rescheduled again anyway...
*/
if (pegasus->rx_pool[i] == NULL)
return;
pegasus->rx_pool[i]->dev = pegasus->net;
skb_reserve(pegasus->rx_pool[i], 2);
}
}
static void free_skb_pool(pegasus_t * pegasus)
{
int i;
for (i = 0; i < RX_SKBS; i++) {
if (pegasus->rx_pool[i]) {
dev_kfree_skb(pegasus->rx_pool[i]);
pegasus->rx_pool[i] = NULL;
}
}
}
static inline struct sk_buff *pull_skb(pegasus_t * pegasus)
{
int i;
struct sk_buff *skb;
for (i = 0; i < RX_SKBS; i++) {
if (likely(pegasus->rx_pool[i] != NULL)) {
skb = pegasus->rx_pool[i];
pegasus->rx_pool[i] = NULL;
return skb;
}
}
return NULL;
}
static void read_bulk_callback(struct urb *urb, struct pt_regs *regs)
{
pegasus_t *pegasus = urb->context;
struct net_device *net;
int rx_status, count = urb->actual_length;
u8 *buf = urb->transfer_buffer;
__u16 pkt_len;
if (!pegasus)
return;
net = pegasus->net;
if (!netif_device_present(net) || !netif_running(net))
return;
switch (urb->status) {
case 0:
break;
case -ETIMEDOUT:
if (netif_msg_rx_err(pegasus))
pr_debug("%s: reset MAC\n", net->name);
pegasus->flags &= ~PEGASUS_RX_BUSY;
break;
case -EPIPE: /* stall, or disconnect from TT */
/* FIXME schedule work to clear the halt */
if (netif_msg_rx_err(pegasus))
printk(KERN_WARNING "%s: no rx stall recovery\n",
net->name);
return;
case -ENOENT:
case -ECONNRESET:
case -ESHUTDOWN:
if (netif_msg_ifdown(pegasus))
pr_debug("%s: rx unlink, %d\n", net->name, urb->status);
return;
default:
if (netif_msg_rx_err(pegasus))
pr_debug("%s: RX status %d\n", net->name, urb->status);
goto goon;
}
if (!count || count < 4)
goto goon;
rx_status = buf[count - 2];
if (rx_status & 0x1e) {
if (netif_msg_rx_err(pegasus))
pr_debug("%s: RX packet error %x\n",
net->name, rx_status);
pegasus->stats.rx_errors++;
if (rx_status & 0x06) // long or runt
pegasus->stats.rx_length_errors++;
if (rx_status & 0x08)
pegasus->stats.rx_crc_errors++;
if (rx_status & 0x10) // extra bits
pegasus->stats.rx_frame_errors++;
goto goon;
}
if (pegasus->chip == 0x8513) {
pkt_len = le32_to_cpu(*(__le32 *)urb->transfer_buffer);
pkt_len &= 0x0fff;
pegasus->rx_skb->data += 2;
} else {
pkt_len = buf[count - 3] << 8;
pkt_len += buf[count - 4];
pkt_len &= 0xfff;
pkt_len -= 8;
}
/*
* If the packet is unreasonably long, quietly drop it rather than
* kernel panicing by calling skb_put.
*/
if (pkt_len > PEGASUS_MTU)
goto goon;
/*
* at this point we are sure pegasus->rx_skb != NULL
* so we go ahead and pass up the packet.
*/
skb_put(pegasus->rx_skb, pkt_len);
pegasus->rx_skb->protocol = eth_type_trans(pegasus->rx_skb, net);
netif_rx(pegasus->rx_skb);
pegasus->stats.rx_packets++;
pegasus->stats.rx_bytes += pkt_len;
if (pegasus->flags & PEGASUS_UNPLUG)
return;
spin_lock(&pegasus->rx_pool_lock);
pegasus->rx_skb = pull_skb(pegasus);
spin_unlock(&pegasus->rx_pool_lock);
if (pegasus->rx_skb == NULL)
goto tl_sched;
goon:
usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb,
usb_rcvbulkpipe(pegasus->usb, 1),
pegasus->rx_skb->data, PEGASUS_MTU + 8,
read_bulk_callback, pegasus);
if (usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC)) {
pegasus->flags |= PEGASUS_RX_URB_FAIL;
goto tl_sched;
} else {
pegasus->flags &= ~PEGASUS_RX_URB_FAIL;
}
return;
tl_sched:
tasklet_schedule(&pegasus->rx_tl);
}
static void rx_fixup(unsigned long data)
{
pegasus_t *pegasus;
unsigned long flags;
pegasus = (pegasus_t *) data;
if (pegasus->flags & PEGASUS_UNPLUG)
return;
spin_lock_irqsave(&pegasus->rx_pool_lock, flags);
fill_skb_pool(pegasus);
if (pegasus->flags & PEGASUS_RX_URB_FAIL)
if (pegasus->rx_skb)
goto try_again;
if (pegasus->rx_skb == NULL) {
pegasus->rx_skb = pull_skb(pegasus);
}
if (pegasus->rx_skb == NULL) {
if (netif_msg_rx_err(pegasus))
printk(KERN_WARNING "%s: low on memory\n",
pegasus->net->name);
tasklet_schedule(&pegasus->rx_tl);
goto done;
}
usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb,
usb_rcvbulkpipe(pegasus->usb, 1),
pegasus->rx_skb->data, PEGASUS_MTU + 8,
read_bulk_callback, pegasus);
try_again:
if (usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC)) {
pegasus->flags |= PEGASUS_RX_URB_FAIL;
tasklet_schedule(&pegasus->rx_tl);
} else {
pegasus->flags &= ~PEGASUS_RX_URB_FAIL;
}
done:
spin_unlock_irqrestore(&pegasus->rx_pool_lock, flags);
}
static void write_bulk_callback(struct urb *urb, struct pt_regs *regs)
{
pegasus_t *pegasus = urb->context;
struct net_device *net = pegasus->net;
if (!pegasus)
return;
if (!netif_device_present(net) || !netif_running(net))
return;
switch (urb->status) {
case -EPIPE:
/* FIXME schedule_work() to clear the tx halt */
netif_stop_queue(net);
if (netif_msg_tx_err(pegasus))
printk(KERN_WARNING "%s: no tx stall recovery\n",
net->name);
return;
case -ENOENT:
case -ECONNRESET:
case -ESHUTDOWN:
if (netif_msg_ifdown(pegasus))
pr_debug("%s: tx unlink, %d\n", net->name, urb->status);
return;
default:
if (netif_msg_tx_err(pegasus))
pr_info("%s: TX status %d\n", net->name, urb->status);
/* FALL THROUGH */
case 0:
break;
}
net->trans_start = jiffies;
netif_wake_queue(net);
}
static void intr_callback(struct urb *urb, struct pt_regs *regs)
{
pegasus_t *pegasus = urb->context;
struct net_device *net;
int status;
if (!pegasus)
return;
net = pegasus->net;
switch (urb->status) {
case 0:
break;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN:
return;
default:
/* some Pegasus-I products report LOTS of data
* toggle errors... avoid log spamming
*/
if (netif_msg_timer(pegasus))
pr_debug("%s: intr status %d\n", net->name,
urb->status);
}
if (urb->actual_length >= 6) {
u8 * d = urb->transfer_buffer;
/* byte 0 == tx_status1, reg 2B */
if (d[0] & (TX_UNDERRUN|EXCESSIVE_COL
|LATE_COL|JABBER_TIMEOUT)) {
pegasus->stats.tx_errors++;
if (d[0] & TX_UNDERRUN)
pegasus->stats.tx_fifo_errors++;
if (d[0] & (EXCESSIVE_COL | JABBER_TIMEOUT))
pegasus->stats.tx_aborted_errors++;
if (d[0] & LATE_COL)
pegasus->stats.tx_window_errors++;
}
/* d[5].LINK_STATUS lies on some adapters.
* d[0].NO_CARRIER kicks in only with failed TX.
* ... so monitoring with MII may be safest.
*/
if (d[0] & NO_CARRIER)
netif_carrier_off(net);
else
netif_carrier_on(net);
/* bytes 3-4 == rx_lostpkt, reg 2E/2F */
pegasus->stats.rx_missed_errors += ((d[3] & 0x7f) << 8) | d[4];
}
status = usb_submit_urb(urb, SLAB_ATOMIC);
if (status && netif_msg_timer(pegasus))
printk(KERN_ERR "%s: can't resubmit interrupt urb, %d\n",
net->name, status);
}
static void pegasus_tx_timeout(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
if (netif_msg_timer(pegasus))
printk(KERN_WARNING "%s: tx timeout\n", net->name);
usb_unlink_urb(pegasus->tx_urb);
pegasus->stats.tx_errors++;
}
static int pegasus_start_xmit(struct sk_buff *skb, struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
int count = ((skb->len + 2) & 0x3f) ? skb->len + 2 : skb->len + 3;
int res;
__u16 l16 = skb->len;
netif_stop_queue(net);
((__le16 *) pegasus->tx_buff)[0] = cpu_to_le16(l16);
memcpy(pegasus->tx_buff + 2, skb->data, skb->len);
usb_fill_bulk_urb(pegasus->tx_urb, pegasus->usb,
usb_sndbulkpipe(pegasus->usb, 2),
pegasus->tx_buff, count,
write_bulk_callback, pegasus);
if ((res = usb_submit_urb(pegasus->tx_urb, GFP_ATOMIC))) {
if (netif_msg_tx_err(pegasus))
printk(KERN_WARNING "%s: fail tx, %d\n",
net->name, res);
switch (res) {
case -EPIPE: /* stall, or disconnect from TT */
/* cleanup should already have been scheduled */
break;
case -ENODEV: /* disconnect() upcoming */
break;
default:
pegasus->stats.tx_errors++;
netif_start_queue(net);
}
} else {
pegasus->stats.tx_packets++;
pegasus->stats.tx_bytes += skb->len;
net->trans_start = jiffies;
}
dev_kfree_skb(skb);
return 0;
}
static struct net_device_stats *pegasus_netdev_stats(struct net_device *dev)
{
return &((pegasus_t *) netdev_priv(dev))->stats;
}
static inline void disable_net_traffic(pegasus_t * pegasus)
{
int tmp = 0;
int ret;
ret = set_registers(pegasus, EthCtrl0, 2, &tmp);
}
static inline void get_interrupt_interval(pegasus_t * pegasus)
{
__u8 data[2];
read_eprom_word(pegasus, 4, (__u16 *) data);
if (pegasus->usb->speed != USB_SPEED_HIGH) {
if (data[1] < 0x80) {
if (netif_msg_timer(pegasus))
dev_info(&pegasus->intf->dev, "intr interval "
"changed from %ums to %ums\n",
data[1], 0x80);
data[1] = 0x80;
#ifdef PEGASUS_WRITE_EEPROM
write_eprom_word(pegasus, 4, *(__u16 *) data);
#endif
}
}
pegasus->intr_interval = data[1];
}
static void set_carrier(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
u16 tmp;
if (!read_mii_word(pegasus, pegasus->phy, MII_BMSR, &tmp))
return;
if (tmp & BMSR_LSTATUS)
netif_carrier_on(net);
else
netif_carrier_off(net);
}
static void free_all_urbs(pegasus_t * pegasus)
{
usb_free_urb(pegasus->intr_urb);
usb_free_urb(pegasus->tx_urb);
usb_free_urb(pegasus->rx_urb);
usb_free_urb(pegasus->ctrl_urb);
}
static void unlink_all_urbs(pegasus_t * pegasus)
{
usb_kill_urb(pegasus->intr_urb);
usb_kill_urb(pegasus->tx_urb);
usb_kill_urb(pegasus->rx_urb);
usb_kill_urb(pegasus->ctrl_urb);
}
static int alloc_urbs(pegasus_t * pegasus)
{
pegasus->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!pegasus->ctrl_urb) {
return 0;
}
pegasus->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!pegasus->rx_urb) {
usb_free_urb(pegasus->ctrl_urb);
return 0;
}
pegasus->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!pegasus->tx_urb) {
usb_free_urb(pegasus->rx_urb);
usb_free_urb(pegasus->ctrl_urb);
return 0;
}
pegasus->intr_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!pegasus->intr_urb) {
usb_free_urb(pegasus->tx_urb);
usb_free_urb(pegasus->rx_urb);
usb_free_urb(pegasus->ctrl_urb);
return 0;
}
return 1;
}
static int pegasus_open(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
int res;
if (pegasus->rx_skb == NULL)
pegasus->rx_skb = pull_skb(pegasus);
/*
** Note: no point to free the pool. it is empty :-)
*/
if (!pegasus->rx_skb)
return -ENOMEM;
res = set_registers(pegasus, EthID, 6, net->dev_addr);
usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb,
usb_rcvbulkpipe(pegasus->usb, 1),
pegasus->rx_skb->data, PEGASUS_MTU + 8,
read_bulk_callback, pegasus);
if ((res = usb_submit_urb(pegasus->rx_urb, GFP_KERNEL))) {
if (netif_msg_ifup(pegasus))
pr_debug("%s: failed rx_urb, %d", net->name, res);
goto exit;
}
usb_fill_int_urb(pegasus->intr_urb, pegasus->usb,
usb_rcvintpipe(pegasus->usb, 3),
pegasus->intr_buff, sizeof (pegasus->intr_buff),
intr_callback, pegasus, pegasus->intr_interval);
if ((res = usb_submit_urb(pegasus->intr_urb, GFP_KERNEL))) {
if (netif_msg_ifup(pegasus))
pr_debug("%s: failed intr_urb, %d\n", net->name, res);
usb_kill_urb(pegasus->rx_urb);
goto exit;
}
if ((res = enable_net_traffic(net, pegasus->usb))) {
if (netif_msg_ifup(pegasus))
pr_debug("%s: can't enable_net_traffic() - %d\n",
net->name, res);
res = -EIO;
usb_kill_urb(pegasus->rx_urb);
usb_kill_urb(pegasus->intr_urb);
free_skb_pool(pegasus);
goto exit;
}
set_carrier(net);
netif_start_queue(net);
if (netif_msg_ifup(pegasus))
pr_debug("%s: open\n", net->name);
res = 0;
exit:
return res;
}
static int pegasus_close(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
netif_stop_queue(net);
if (!(pegasus->flags & PEGASUS_UNPLUG))
disable_net_traffic(pegasus);
tasklet_kill(&pegasus->rx_tl);
unlink_all_urbs(pegasus);
return 0;
}
static void pegasus_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
pegasus_t *pegasus = netdev_priv(dev);
strncpy(info->driver, driver_name, sizeof (info->driver) - 1);
strncpy(info->version, DRIVER_VERSION, sizeof (info->version) - 1);
usb_make_path(pegasus->usb, info->bus_info, sizeof (info->bus_info));
}
/* also handles three patterns of some kind in hardware */
#define WOL_SUPPORTED (WAKE_MAGIC|WAKE_PHY)
static void
pegasus_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
pegasus_t *pegasus = netdev_priv(dev);
wol->supported = WAKE_MAGIC | WAKE_PHY;
wol->wolopts = pegasus->wolopts;
}
static int
pegasus_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
pegasus_t *pegasus = netdev_priv(dev);
u8 reg78 = 0x04;
if (wol->wolopts & ~WOL_SUPPORTED)
return -EINVAL;
if (wol->wolopts & WAKE_MAGIC)
reg78 |= 0x80;
if (wol->wolopts & WAKE_PHY)
reg78 |= 0x40;
/* FIXME this 0x10 bit still needs to get set in the chip... */
if (wol->wolopts)
pegasus->eth_regs[0] |= 0x10;
else
pegasus->eth_regs[0] &= ~0x10;
pegasus->wolopts = wol->wolopts;
return set_register(pegasus, WakeupControl, reg78);
}
static inline void pegasus_reset_wol(struct net_device *dev)
{
struct ethtool_wolinfo wol;
memset(&wol, 0, sizeof wol);
(void) pegasus_set_wol(dev, &wol);
}
static int
pegasus_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
pegasus_t *pegasus;
if (in_atomic())
return 0;
pegasus = netdev_priv(dev);
mii_ethtool_gset(&pegasus->mii, ecmd);
return 0;
}
static int
pegasus_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
pegasus_t *pegasus = netdev_priv(dev);
return mii_ethtool_sset(&pegasus->mii, ecmd);
}
static int pegasus_nway_reset(struct net_device *dev)
{
pegasus_t *pegasus = netdev_priv(dev);
return mii_nway_restart(&pegasus->mii);
}
static u32 pegasus_get_link(struct net_device *dev)
{
pegasus_t *pegasus = netdev_priv(dev);
return mii_link_ok(&pegasus->mii);
}
static u32 pegasus_get_msglevel(struct net_device *dev)
{
pegasus_t *pegasus = netdev_priv(dev);
return pegasus->msg_enable;
}
static void pegasus_set_msglevel(struct net_device *dev, u32 v)
{
pegasus_t *pegasus = netdev_priv(dev);
pegasus->msg_enable = v;
}
static struct ethtool_ops ops = {
.get_drvinfo = pegasus_get_drvinfo,
.get_settings = pegasus_get_settings,
.set_settings = pegasus_set_settings,
.nway_reset = pegasus_nway_reset,
.get_link = pegasus_get_link,
.get_msglevel = pegasus_get_msglevel,
.set_msglevel = pegasus_set_msglevel,
.get_wol = pegasus_get_wol,
.set_wol = pegasus_set_wol,
};
static int pegasus_ioctl(struct net_device *net, struct ifreq *rq, int cmd)
{
__u16 *data = (__u16 *) & rq->ifr_ifru;
pegasus_t *pegasus = netdev_priv(net);
int res;
switch (cmd) {
case SIOCDEVPRIVATE:
data[0] = pegasus->phy;
case SIOCDEVPRIVATE + 1:
read_mii_word(pegasus, data[0], data[1] & 0x1f, &data[3]);
res = 0;
break;
case SIOCDEVPRIVATE + 2:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
write_mii_word(pegasus, pegasus->phy, data[1] & 0x1f, data[2]);
res = 0;
break;
default:
res = -EOPNOTSUPP;
}
return res;
}
static void pegasus_set_multicast(struct net_device *net)
{
pegasus_t *pegasus = netdev_priv(net);
if (net->flags & IFF_PROMISC) {
pegasus->eth_regs[EthCtrl2] |= RX_PROMISCUOUS;
if (netif_msg_link(pegasus))
pr_info("%s: Promiscuous mode enabled.\n", net->name);
} else if (net->mc_count ||
(net->flags & IFF_ALLMULTI)) {
pegasus->eth_regs[EthCtrl0] |= RX_MULTICAST;
pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS;
if (netif_msg_link(pegasus))
pr_info("%s: set allmulti\n", net->name);
} else {
pegasus->eth_regs[EthCtrl0] &= ~RX_MULTICAST;
pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS;
}
pegasus->flags |= ETH_REGS_CHANGE;
ctrl_callback(pegasus->ctrl_urb, NULL);
}
static __u8 mii_phy_probe(pegasus_t * pegasus)
{
int i;
__u16 tmp;
for (i = 0; i < 32; i++) {
read_mii_word(pegasus, i, MII_BMSR, &tmp);
if (tmp == 0 || tmp == 0xffff || (tmp & BMSR_MEDIA) == 0)
continue;
else
return i;
}
return 0xff;
}
static inline void setup_pegasus_II(pegasus_t * pegasus)
{
__u8 data = 0xa5;
int ret;
ret = set_register(pegasus, Reg1d, 0);
ret = set_register(pegasus, Reg7b, 1);
mdelay(100);
if ((pegasus->features & HAS_HOME_PNA) && mii_mode)
ret = set_register(pegasus, Reg7b, 0);
else
ret = set_register(pegasus, Reg7b, 2);
ret = set_register(pegasus, 0x83, data);
ret = get_registers(pegasus, 0x83, 1, &data);
if (data == 0xa5) {
pegasus->chip = 0x8513;
} else {
pegasus->chip = 0;
}
ret = set_register(pegasus, 0x80, 0xc0);
ret = set_register(pegasus, 0x83, 0xff);
ret = set_register(pegasus, 0x84, 0x01);
if (pegasus->features & HAS_HOME_PNA && mii_mode)
ret = set_register(pegasus, Reg81, 6);
else
ret = set_register(pegasus, Reg81, 2);
}
static struct workqueue_struct *pegasus_workqueue = NULL;
#define CARRIER_CHECK_DELAY (2 * HZ)
static void check_carrier(void *data)
{
pegasus_t *pegasus = data;
set_carrier(pegasus->net);
if (!(pegasus->flags & PEGASUS_UNPLUG)) {
queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check,
CARRIER_CHECK_DELAY);
}
}
static int pegasus_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct net_device *net;
pegasus_t *pegasus;
int dev_index = id - pegasus_ids;
int res = -ENOMEM;
usb_get_dev(dev);
net = alloc_etherdev(sizeof(struct pegasus));
if (!net) {
dev_err(&intf->dev, "can't allocate %s\n", "device");
goto out;
}
pegasus = netdev_priv(net);
memset(pegasus, 0, sizeof (struct pegasus));
pegasus->dev_index = dev_index;
init_waitqueue_head(&pegasus->ctrl_wait);
if (!alloc_urbs(pegasus)) {
dev_err(&intf->dev, "can't allocate %s\n", "urbs");
goto out1;
}
tasklet_init(&pegasus->rx_tl, rx_fixup, (unsigned long) pegasus);
INIT_WORK(&pegasus->carrier_check, check_carrier, pegasus);
pegasus->intf = intf;
pegasus->usb = dev;
pegasus->net = net;
SET_MODULE_OWNER(net);
net->open = pegasus_open;
net->stop = pegasus_close;
net->watchdog_timeo = PEGASUS_TX_TIMEOUT;
net->tx_timeout = pegasus_tx_timeout;
net->do_ioctl = pegasus_ioctl;
net->hard_start_xmit = pegasus_start_xmit;
net->set_multicast_list = pegasus_set_multicast;
net->get_stats = pegasus_netdev_stats;
SET_ETHTOOL_OPS(net, &ops);
pegasus->mii.dev = net;
pegasus->mii.mdio_read = mdio_read;
pegasus->mii.mdio_write = mdio_write;
pegasus->mii.phy_id_mask = 0x1f;
pegasus->mii.reg_num_mask = 0x1f;
spin_lock_init(&pegasus->rx_pool_lock);
pegasus->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV
| NETIF_MSG_PROBE | NETIF_MSG_LINK);
pegasus->features = usb_dev_id[dev_index].private;
get_interrupt_interval(pegasus);
if (reset_mac(pegasus)) {
dev_err(&intf->dev, "can't reset MAC\n");
res = -EIO;
goto out2;
}
set_ethernet_addr(pegasus);
fill_skb_pool(pegasus);
if (pegasus->features & PEGASUS_II) {
dev_info(&intf->dev, "setup Pegasus II specific registers\n");
setup_pegasus_II(pegasus);
}
pegasus->phy = mii_phy_probe(pegasus);
if (pegasus->phy == 0xff) {
dev_warn(&intf->dev, "can't locate MII phy, using default\n");
pegasus->phy = 1;
}
pegasus->mii.phy_id = pegasus->phy;
usb_set_intfdata(intf, pegasus);
SET_NETDEV_DEV(net, &intf->dev);
pegasus_reset_wol(net);
res = register_netdev(net);
if (res)
goto out3;
queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check,
CARRIER_CHECK_DELAY);
dev_info(&intf->dev, "%s, %s, %02x:%02x:%02x:%02x:%02x:%02x\n",
net->name,
usb_dev_id[dev_index].name,
net->dev_addr [0], net->dev_addr [1],
net->dev_addr [2], net->dev_addr [3],
net->dev_addr [4], net->dev_addr [5]);
return 0;
out3:
usb_set_intfdata(intf, NULL);
free_skb_pool(pegasus);
out2:
free_all_urbs(pegasus);
out1:
free_netdev(net);
out:
usb_put_dev(dev);
return res;
}
static void pegasus_disconnect(struct usb_interface *intf)
{
struct pegasus *pegasus = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
if (!pegasus) {
dev_dbg(&intf->dev, "unregistering non-bound device?\n");
return;
}
pegasus->flags |= PEGASUS_UNPLUG;
cancel_delayed_work(&pegasus->carrier_check);
unregister_netdev(pegasus->net);
usb_put_dev(interface_to_usbdev(intf));
unlink_all_urbs(pegasus);
free_all_urbs(pegasus);
free_skb_pool(pegasus);
if (pegasus->rx_skb)
dev_kfree_skb(pegasus->rx_skb);
free_netdev(pegasus->net);
}
static int pegasus_suspend (struct usb_interface *intf, pm_message_t message)
{
struct pegasus *pegasus = usb_get_intfdata(intf);
netif_device_detach (pegasus->net);
if (netif_running(pegasus->net)) {
cancel_delayed_work(&pegasus->carrier_check);
usb_kill_urb(pegasus->rx_urb);
usb_kill_urb(pegasus->intr_urb);
}
intf->dev.power.power_state = PMSG_SUSPEND;
return 0;
}
static int pegasus_resume (struct usb_interface *intf)
{
struct pegasus *pegasus = usb_get_intfdata(intf);
intf->dev.power.power_state = PMSG_ON;
netif_device_attach (pegasus->net);
if (netif_running(pegasus->net)) {
pegasus->rx_urb->status = 0;
pegasus->rx_urb->actual_length = 0;
read_bulk_callback(pegasus->rx_urb, NULL);
pegasus->intr_urb->status = 0;
pegasus->intr_urb->actual_length = 0;
intr_callback(pegasus->intr_urb, NULL);
queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check,
CARRIER_CHECK_DELAY);
}
return 0;
}
static struct usb_driver pegasus_driver = {
.name = driver_name,
.probe = pegasus_probe,
.disconnect = pegasus_disconnect,
.id_table = pegasus_ids,
.suspend = pegasus_suspend,
.resume = pegasus_resume,
};
static int __init pegasus_init(void)
{
pr_info("%s: %s, " DRIVER_DESC "\n", driver_name, DRIVER_VERSION);
pegasus_workqueue = create_singlethread_workqueue("pegasus");
if (!pegasus_workqueue)
return -ENOMEM;
return usb_register(&pegasus_driver);
}
static void __exit pegasus_exit(void)
{
destroy_workqueue(pegasus_workqueue);
usb_deregister(&pegasus_driver);
}
module_init(pegasus_init);
module_exit(pegasus_exit);
| ipwndev/DSLinux-Mirror | linux-2.6.x/drivers/usb/net/pegasus.c | C | gpl-2.0 | 36,647 |
########################################################################
#
# filepp is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not, write to
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
#
########################################################################
########################################################################
#
# Project : File Pre Processor - cpp module
# Filename : $RCSfile: Makefile.in,v $
# Originator : $Author: darren $
# Maintainer : Darren Miller: darren@cabaret.demon.co.uk
# File version : $Revision: 1.3 $
# Last changed : $Date: 2007/02/13 00:08:09 $
# Description : Makefile for cpp module
# Licence : GNU copyleft
#
########################################################################
##############################################################################
# Paths
##############################################################################
srcdir = .
datarootdir = ${prefix}/share
moduledir = /usr/local/share/filepp/modules
# top level of test build directory
TESTBUILD = ../../testbuild
TESTFILEPP = $(TESTBUILD)/bin/filepp
ECHO=echo
DIFF=diff
RM=rm -fr
INSTALL=/usr/bin/install -c
test:
@$(ECHO) ----------- Testing cpp.pm ----------------
$(TESTFILEPP) -m cpp.pm $(srcdir)/test.in -o test.out
$(DIFF) $(srcdir)/test.good test.out
@$(ECHO) ----------- Done --------------------------
install:
$(INSTALL) -m 644 $(srcdir)/cpp.pm $(moduledir)
clean:
$(RM) test.out
distclean:
$(RM) Makefile
##############################################################################
# End of file
##############################################################################
| timbertson/filepp | modules/cpp/Makefile | Makefile | gpl-2.0 | 2,251 |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
# Copyright (C) 2010 Benny Malengier
#
# 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.
#
#-------------------------------------------------------------------------
#
# Python classes
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext
#-------------------------------------------------------------------------
#
# GTK classes
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import Pango
_TAB = Gdk.keyval_from_name("Tab")
_ENTER = Gdk.keyval_from_name("Enter")
#-------------------------------------------------------------------------
#
# Gramps classes
#
#-------------------------------------------------------------------------
from .surnamemodel import SurnameModel
from .embeddedlist import EmbeddedList, TEXT_EDIT_COL
from ...ddtargets import DdTargets
from gramps.gen.lib import Surname, NameOriginType
from ...utils import match_primary_mask, no_match_primary_mask
# table for skipping illegal control chars
INVISIBLE = dict.fromkeys(list(range(32)))
#-------------------------------------------------------------------------
#
# SurnameTab
#
#-------------------------------------------------------------------------
class SurnameTab(EmbeddedList):
_HANDLE_COL = 5
_DND_TYPE = DdTargets.SURNAME
_MSG = {
'add' : _('Create and add a new surname'),
'del' : _('Remove the selected surname'),
'edit' : _('Edit the selected surname'),
'up' : _('Move the selected surname upwards'),
'down' : _('Move the selected surname downwards'),
}
#index = column in model. Value =
# (name, sortcol in model, width, markup/text
_column_names = [
(_('Prefix'), 0, 150, TEXT_EDIT_COL, -1, None),
(_('Surname'), 1, -1, TEXT_EDIT_COL, -1, None),
(_('Connector'), 2, 100, TEXT_EDIT_COL, -1, None),
]
_column_combo = (_('Origin'), -1, 150, 3) # name, sort, width, modelcol
_column_toggle = (_('Primary', 'Name'), -1, 80, 4)
def __init__(self, dbstate, uistate, track, name, on_change=None,
top_label='<b>%s</b>' % _("Multiple Surnames") ):
self.obj = name
self.on_change = on_change
self.curr_col = -1
self.curr_cellr = None
self.curr_celle = None
EmbeddedList.__init__(self, dbstate, uistate, track, _('Family Surnames'),
SurnameModel, move_buttons=True,
top_label=top_label)
def build_columns(self):
#first the standard text columns with normal method
EmbeddedList.build_columns(self)
# now we add the two special columns
# combobox for type
colno = len(self.columns)
name = self._column_combo[0]
renderer = Gtk.CellRendererCombo()
renderer.set_property('ellipsize', Pango.EllipsizeMode.END)
# set up the comboentry editable
no = NameOriginType()
self.cmborig = Gtk.ListStore(GObject.TYPE_INT, GObject.TYPE_STRING)
self.cmborigmap = no.get_map().copy()
#sort the keys based on the value
keys = sorted(self.cmborigmap, key=lambda x: glocale.sort_key(self.cmborigmap[x]))
for key in keys:
if key != no.get_custom():
self.cmborig.append(row=[key, self.cmborigmap[key]])
additional = self.dbstate.db.get_origin_types()
if additional:
for type in additional:
if type:
self.cmborig.append(row=[no.get_custom(), type])
renderer.set_property("model", self.cmborig)
renderer.set_property("text-column", 1)
renderer.set_property('editable', not self.dbstate.db.readonly)
renderer.connect('editing_started', self.on_edit_start_cmb, colno)
renderer.connect('edited', self.on_orig_edited, self._column_combo[3])
# add to treeview
column = Gtk.TreeViewColumn(name, renderer, text=self._column_combo[3])
column.set_resizable(True)
column.set_sort_column_id(self._column_combo[1])
column.set_min_width(self._column_combo[2])
column.set_expand(False)
self.columns.append(column)
self.tree.append_column(column)
# toggle box for primary
colno += 1
name = self._column_toggle[0]
renderer = Gtk.CellRendererToggle()
renderer.set_property('activatable', True)
renderer.set_property('radio', True)
renderer.connect( 'toggled', self.on_prim_toggled, self._column_toggle[3])
# add to treeview
column = Gtk.TreeViewColumn(name, renderer, active=self._column_toggle[3])
column.set_resizable(False)
column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
column.set_alignment(0.5)
column.set_sort_column_id(self._column_toggle[1])
column.set_max_width(self._column_toggle[2])
self.columns.append(column)
self.tree.append_column(column)
## def by_value(self, first, second):
## """
## Method for sorting keys based on the values.
## """
## fvalue = self.cmborigmap[first]
## svalue = self.cmborigmap[second]
## return glocale.strcoll(fvalue, svalue)
def setup_editable_col(self):
"""
inherit this and set the variables needed for editable columns
Variable edit_col_funcs needs to be a dictionary from model col_nr to
function to call for
Example:
self.edit_col_funcs ={1: {'edit_start': self.on_edit_start,
'edited': self.on_edited
}}
"""
self.edit_col_funcs = {
0: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline},
1: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline},
2: {'edit_start': self.on_edit_start,
'edited': self.on_edit_inline}}
def get_data(self):
return self.obj.get_surname_list()
def is_empty(self):
return len(self.model)==0
def _get_surn_from_model(self):
"""
Return new surname_list for storing in the name based on content of
the model
"""
new_list = []
for idx in range(len(self.model)):
node = self.model.get_iter(idx)
surn = self.model.get_value(node, 5)
surn.set_prefix(self.model.get_value(node, 0))
surn.set_surname(self.model.get_value(node, 1))
surn.set_connector(self.model.get_value(node, 2))
surn.get_origintype().set(self.model.get_value(node, 3))
surn.set_primary(self.model.get_value(node, 4))
new_list += [surn]
return new_list
def update(self):
"""
Store the present data in the model to the name object
"""
new_map = self._get_surn_from_model()
self.obj.set_surname_list(new_map)
# update name in previews
if self.on_change:
self.on_change()
def post_rebuild(self, prebuildpath):
"""
Called when data model has changed, in particular necessary when row
order is updated.
@param prebuildpath: path selected before rebuild, None if none
@type prebuildpath: tree path
"""
if self.on_change:
self.on_change()
def column_order(self):
# order of columns for EmbeddedList. Only the text columns here
return ((1, 0), (1, 1), (1, 2))
def add_button_clicked(self, obj):
"""Add button is clicked, add a surname to the person"""
prim = False
if len(self.obj.get_surname_list()) == 0:
prim = True
node = self.model.append(row=['', '', '', str(NameOriginType()), prim,
Surname()])
self.selection.select_iter(node)
path = self.model.get_path(node)
self.tree.set_cursor_on_cell(path,
focus_column=self.columns[0],
focus_cell=None,
start_editing=True)
self.update()
def del_button_clicked(self, obj):
"""
Delete button is clicked. Remove from the model
"""
(model, node) = self.selection.get_selected()
if node:
self.model.remove(node)
self.update()
def on_edit_start(self, cellr, celle, path, colnr):
""" start of editing. Store stuff so we know when editing ends where we
are
"""
self.curr_col = colnr
self.curr_cellr = cellr
self.curr_celle = celle
def on_edit_start_cmb(self, cellr, celle, path, colnr):
"""
An edit starts in the origin type column
This means a cmb has been created as celle, and we can set up the stuff
we want this cmb to contain: autocompletion, stop edit when selection
in the cmb happens.
"""
self.on_edit_start(cellr, celle, path, colnr)
#set up autocomplete
entry = celle.get_child()
entry.set_width_chars(10)
completion = Gtk.EntryCompletion()
completion.set_model(self.cmborig)
completion.set_minimum_key_length(1)
completion.set_text_column(1)
entry.set_completion(completion)
#
celle.connect('changed', self.on_origcmb_change, path, colnr)
def on_edit_start_toggle(self, cellr, celle, path, colnr):
"""
Edit
"""
self.on_edit_start(cellr, celle, path, colnr)
def on_edit_inline(self, cell, path, new_text, colnr):
"""
Edit is happening. The model is updated and the surname objects updated.
colnr must be the column in the model.
"""
node = self.model.get_iter(path)
text = new_text.translate(INVISIBLE).strip()
self.model.set_value(node, colnr, text)
self.update()
def on_orig_edited(self, cellr, path, new_text, colnr):
"""
An edit is finished in the origin type column. For a cmb in an editor,
the model may only be updated when typing is finished, as editing stops
automatically on update of the model.
colnr must be the column in the model.
"""
self.on_edit_inline(cellr, path, new_text, colnr)
def on_origcmb_change(self, cmb, path, colnr):
"""
A selection occured in the cmb of the origin type column. colnr must
be the column in the model.
"""
act = cmb.get_active()
if act == -1:
return
self.on_orig_edited(None, path,
self.cmborig.get_value(
self.cmborig.get_iter((act,)),1),
colnr)
def on_prim_toggled(self, cell, path, colnr):
"""
Primary surname on path is toggled. colnr must be the col
in the model
"""
#obtain current value
node = self.model.get_iter(path)
old_val = self.model.get_value(node, colnr)
for nr in range(len(self.obj.get_surname_list())):
if nr == int(path[0]):
if old_val:
#True remains True
break
else:
#This value becomes True
self.model.set_value(self.model.get_iter((nr,)), colnr, True)
else:
self.model.set_value(self.model.get_iter((nr,)), colnr, False)
self.update()
return
def edit_button_clicked(self, obj):
""" Edit button clicked
"""
(model, node) = self.selection.get_selected()
if node:
path = self.model.get_path(node)
self.tree.set_cursor_on_cell(path,
focus_column=self.columns[0],
focus_cell=None,
start_editing=True)
def key_pressed(self, obj, event):
"""
Handles the key being pressed.
Here we make sure tab moves to next or previous value in row on TAB
"""
if not EmbeddedList.key_pressed(self, obj, event):
if event.type == Gdk.EventType.KEY_PRESS and event.keyval in (_TAB,):
if no_match_primary_mask(event.get_state(),
Gdk.ModifierType.SHIFT_MASK):
return self.next_cell()
elif match_primary_mask(event.get_state(), Gdk.ModifierType.SHIFT_MASK):
return self.prev_cell()
else:
return
else:
return
return True
def next_cell(self):
"""
Move to the next cell to edit it
"""
(model, node) = self.selection.get_selected()
if node:
path = self.model.get_path(node).get_indices()[0]
nccol = self.curr_col+1
if nccol < 4:
if self.curr_celle:
self.curr_celle.editing_done()
self.tree.set_cursor_on_cell(Gtk.TreePath((path,)),
focus_column=self.columns[nccol],
focus_cell=None,
start_editing=True)
elif nccol == 4:
#go to next line if there is one
if path < len(self.obj.get_surname_list()):
newpath = Gtk.TreePath((path+1,))
self.curr_celle.editing_done()
self.selection.select_path(newpath)
self.tree.set_cursor_on_cell(newpath,
focus_column=self.columns[0],
focus_cell=None,
start_editing=True)
else:
#stop editing
self.curr_celle.editing_done()
return
return True
def prev_cell(self):
"""
Move to the next cell to edit it
"""
(model, node) = self.selection.get_selected()
if node:
path = self.model.get_path(node).get_indices()[0]
if self.curr_col > 0:
self.tree.set_cursor_on_cell(Gtk.TreePath((path,)),
focus_column=self.columns[self.curr_col-1],
focus_cell=None,
start_editing=True)
elif self.curr_col == 0:
#go to prev line if there is one
if path > 0:
newpath = Gtk.TreePath((path-1,))
self.selection.select_path(newpath)
self.tree.set_cursor_on_cell(newpath,
focus_column=self.columns[-2],
focus_cell=None,
start_editing=True)
else:
#stop editing
self.curr_celle.editing_done()
return
return True
| Fedik/gramps | gramps/gui/editors/displaytabs/surnametab.py | Python | gpl-2.0 | 16,204 |
--強欲な壺の精霊
function c4896788.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_CHAIN_SOLVING)
e1:SetCondition(c4896788.drcon)
e1:SetOperation(c4896788.drop)
c:RegisterEffect(e1)
end
function c4896788.drcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsAttackPos()
and re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:GetHandler():IsCode(55144522)
end
function c4896788.drop(e,tp,eg,ep,ev,re,r,rp)
Duel.ChangeTargetParam(ev,3)
end
| Lsty/ygopro-scripts | c4896788.lua | Lua | gpl-2.0 | 558 |
package Qtopia::Vars;
use strict;
use warnings;
use File::Basename;
use Qtopia::Paths;
use Qtopia::File;
use Carp;
#perl2exe_include Carp::Heavy
$Carp::CarpLevel = 1;
use Digest::MD5 qw(md5_base64);
require Exporter;
our @ISA = qw(Exporter);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
# This allows declaration use Qtopia::opt ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = ( 'all' => [ qw(
) ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw(
$isWindows
$isMac
$qtopiaVersionStr
$qtVersionStr
$shadow
check_script
configopt
script_name
$depotpath
$SDKROOT
);
our $VERSION = '0.01';
# imported variables
our $depotpath;
our $SDKROOT;
use constant TRACE => 0;
# Platform detection
our $isWindows = ( $^O eq "MSWin32" );
our $isMac = ( $^O eq "darwin" );
our $qtopiaVersionStr;
our $qtVersionStr;
our @configureoptions;
our $shadow;
our $perl2exe_hash;
# Check for a bug in perl on RedHat 9.1
if ( !$isWindows ) {
TRACE and print "Qtopia::Vars::perl_bug_test()\n";
my $testfile = "/etc/passwd";
open IN, "$testfile" or die "Can't read $testfile";
my $common_perl_bug_test = <IN>;
close IN;
if ( !defined($common_perl_bug_test) ) {
die "ERROR: Your /etc/passwd file has no contents!";
}
unless ( $common_perl_bug_test =~ /[^\s]+/ ) {
warn "WARNING: Your perl has a bug with regular expressions and UTF-8\n";
# remove the UTF8 bit from the LANG environment variable and relaunch
my $lang = $ENV{LANG};
if ( !$lang ) {
die "ERROR: ".basename($0)." cannot work around the bug.\n";
}
unless ( $lang =~ s/\.UTF-?8//i ) {
die "ERROR: ".basename($0)." cannot work around the bug.\n";
}
warn "WARNING: ".basename($0)." will attempt to work around the bug by changing your\n".
" LANG variable from ".$ENV{LANG}." to $lang.\n";
$ENV{LANG} = $lang;
exec($0, @ARGV);
die "ERROR Could not relaunch ".basename($0);
}
# RedHat upgraded their perl so that it does not trigger the test above but now
# it overruns output data, potentially leading to an unexplained segfault.
# Try to detect RedHat 9 and just force the fix.
my $redhat_verfile = "/etc/redhat-release";
if ( -f $redhat_verfile ) {
open IN, $redhat_verfile or die "Can't read $redhat_verfile";
$_ = <IN>;
close IN;
if ( !defined($_) ) {
die "ERROR: Your /etc/redhat-release file has no contents!";
}
if ( /release 9/ ) {
my $lang = $ENV{LANG};
if ( $lang =~ /\.UTF-?8/i ) {
warn "WARNING: Your perl has a bug with output and UTF-8\n";
# remove the UTF8 bit from the LANG environment variable and relaunch
unless ( $lang =~ s/\.UTF-?8//i ) {
die "ERROR: ".basename($0)." cannot work around the bug.\n";
}
warn "WARNING: ".basename($0)." will attempt to work around the bug by changing your\n".
" LANG variable from ".$ENV{LANG}." to $lang.\n";
$ENV{LANG} = $lang;
exec($0, @ARGV);
die "ERROR Could not relaunch ".basename($0)."\n";
}
}
}
}
sub check_script
{
TRACE and print "Qtopia::Vars::check_script()\n";
my ( $script, $path, $arg ) = @_;
#print "check_script $script $path ".(defined($arg)?$arg:"")."\n";
my $compiled_code = 0;
if ( $script =~ /\.exe$/i ) {
$compiled_code = 1;
}
my $orig = "$path/".script_name($script);
# perl2exe test run bail out hook
if ( $compiled_code && defined($arg) && $arg eq "-nop" ) {
if ( !check_perl2exe_hash($orig) ) {
die "ERROR: Stored hash does not match script hash:\n".
" $0\n".
" ".fixpath($orig)."\n";
}
exit 0;
}
# If we're in the depot, run the perl scripts directly
if ( $compiled_code ) {
$script = script_name($script);
#print "running the perl script ".fixpath("$path/$script")."\n";
my @cmd = ( "perl", "$path/$script", @ARGV );
my $ret = system(@cmd);
$ret = $ret >> 8;
exit $ret;
}
# Windows doesn't set HOME but the build system expects it to be set!
$ENV{HOME} = $ENV{HOMEDRIVE}.$ENV{HOMEPATH};
}
# Check the md5sum embedded in the .exe file with the script it was built from
sub check_perl2exe_hash
{
my ( $orig ) = @_;
if ( !defined($perl2exe_hash) ) {
die "ERROR: Stored hash is missing!";
}
open IN, "$orig" or die "Can't read $orig";
my $data = join("", <IN>);
close IN;
my $md5 = md5_base64($data);
#print "stored hash $perl2exe_hash\n";
#print "script hash $md5\n";
if ( $perl2exe_hash eq $md5 ) {
return 1;
}
return 0;
}
# Is a particular value in the .configureoptions file
sub configopt
{
TRACE and print "Qtopia::Vars::configopt()\n";
my $dir = $depotpath;
if ( ! $dir ) {
$dir = $SDKROOT;
}
if ( ! $dir ) {
#Qtopia::Paths::get_vars();
croak "You must use Qtopia::Paths and call get_paths() before using Qtopia::Vars";
}
if ( ! @configureoptions ) {
if ( -f "$dir/LICENSE.GPL" ) {
push(@configureoptions, "free");
}
if ( -d "$dir/src/qtopiadesktop" ) {
push(@configureoptions, "desktop");
}
}
my ( $opt ) = @_;
if ( grep { $_ eq $opt } @configureoptions ) {
return 1;
}
return 0;
}
sub script_name
{
TRACE and print "Qtopia::Vars::script_name()\n";
my ( $script ) = @_;
$script = basename($script);
my $len = length $script;
my $compiled_code = 0;
if ( basename($script) =~ /\.exe$/i ) {
$compiled_code = 1;
}
if ( $compiled_code ) {
$len -= 4;
}
return substr($script, 0, $len);
}
# Make this file require()able.
1;
| Trim/qtmoko | src/qtopiadesktop/build/bin/Qtopia/Vars.pm | Perl | gpl-2.0 | 6,263 |
/*
Take the Plunge Wedding Template
Table of Contents:
Reset
Common
Typography
Layout
Supersized Slideshow
Youtube Player
Parallax
Portfolio
About Us
Services
Features
Accordion
Tooltips
Contacts
Form Elements
Flickr
Alert Boxes
Footer
Our Clients
Misc
Media Queries
*/
/* #Reset & Basics (Inspired by E. Meyers)
--------------------------------------------------------*/
html, body {
height: 100%;
}
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* Commons
--------------------------------------------------------*/
::-moz-selection {background: #af1b5a;color: white; }
::selection {background: #af1b5a;color: white; }
body {
background-color: #fff;
font: 15px 'Oswald', sans-serif;
font-weight: 300;
color: #222;
-webkit-font-smoothing: antialiased;
-webkit-text-size-adjust: 100%;
text-align: left;
width: 100%;
height: 100%;
}
.embed-container {
position: relative;
padding-bottom: 56.25%; /* 16/9 ratio */
padding-top: 30px; /* IE6 workaround*/
height: 0;
overflow: hidden;
}
.embed-container iframe,
.embed-container object,
.embed-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.hidden {
display: none;
}
.parallaxText {
display: table-cell;
vertical-align: middle;
}
img.scale-with-grid {
max-width: 100%;
height: auto; }
/* Typography
--------------------------------------------------------*/
h1, h2, h3, h4 {
font-weight: 300;
font-family: 'Oswald',sans-serif;
color: #222;
margin: 0 0 6px;
}
h1 {
font-size: 250px;
text-transform: uppercase;
position: relative;
letter-spacing: -2px;
text-align: left;
line-height: 0.8;
margin-bottom: 35px;
padding-top: 15px;
}
h1 span{
color: #7b133c;
font-size: 150px;
}
h2 {
font-size: 44px;
text-transform: uppercase;
position: relative;
}
h2.white { color: #222;}
h3 {font-size: 22px; line-height: 1; color: #555;}
h3.sectionTitle {
border-bottom: 1px solid #cacaca;
font-size: 28px;
line-height: 30px;
margin-bottom: 10px;
padding: 26px 0 6px;
}
.small {font-size: 36px; font-weight:300;}
.smallBold {font-size: 36px; font-weight:700;}
.medium {font-size: 44px; text-transform: uppercase;}
.mediumBold {font-size: 44px; font-weight:700; text-transform: uppercase;}
.large {font-size: 56px; text-transform: uppercase;}
.largeBold {font-size: 56px; font-weight:700; text-transform: uppercase;}
.author {font-size: 18px; font-weight:300;}
h4 {font-size: 22px;}
p {margin-bottom: 10px;}
p a {color: #222; text-decoration: none;}
p a:hover {color: #a90e4b;transition: color 0.5s;}
a {color:#222;text-decoration:none;}
a:hover{color:#a90e4b;}
.introtext {font-size: 20px;}
.marginTop {
margin-top: 30px;
}
.highlight {
background: #7b133c;
color: #FFFFFF;
padding: 0 6px;
}
.dropcap {
background: #7b133c;
color: #FFFFFF;
display: inline-block;
float: left;
font-size: 30px;
font-weight: bold;
height: 44px;
line-height: 44px;
margin: 7px 7px 0 0;
text-align: center;
width: 44px;
}
blockquote {
color: #999999;
display: block;
font-size: 20px;
font-style: italic;
letter-spacing: 0;
padding: 20px 50px 20px 40px;
position: relative;
}
blockquote:before, blockquote:after {
color: #7B133C;
content: "“";
font-size: 80px;
font-style: italic;
left: -25px;
line-height: 1em;
position: absolute;
top: 0;
}
blockquote:after {
content: "”";
float: right;
margin-right: -30px;
margin-top: 0;
position: relative;
}
/* Layout
--------------------------------------------------------*/
.homepage{
position:relative;
overflow:hidden;
z-index:1;
margin-bottom: -70px;
}
.page{
position:relative;
overflow:hidden;
z-index:2;
}
.page.desktop{
position:relative !important;
z-index:6;
}
.page {
padding-top: 100px;
}
.page{
background:#fff;
background-attachment:scroll;
}
nav {
background: #000;
background: rgba(0,0,0,0.8);
width: 100%;
position: relative;
z-index: 1000;
height: 50px;
text-align: center;
margin-bottom: 10px;
}
nav ul {
height: 40px;
display: inline-block;
padding-top: 10px;
padding-bottom: 15px;
}
nav ul li {
position: relative;
float: left;
margin: 0;
}
nav ul li a {
font-family: 'Oswald',sans-serif;
font-size: 18px;
font-weight: 400;
color: white;
text-decoration: none;
text-transform: uppercase;
padding: 10px;
}
nav ul li a:hover {
color: #a90e4b;
transition: color 0.5s;
}
.dropmenu {
display: none;
}
#homepage .container {
height: 100%;
}
.logo {
float: right;
margin-top: 50px;
}
/* supersized slideshow
--------------------------------------------------------*/
.slider-text {
width: 100%;
}
.slider-text {
bottom: 0px;
min-height: 220px;
overflow: hidden;
position: absolute;
}
#prevslide, #nextslide{
position:absolute;
height:40px;
width:40px;
top:64px;
margin-top:-21px;
opacity:0.8;
font-size: 32px;
color: #fff;
background: #000;
display: block;
text-align: center;
}
#prevslide{
right:60px;
}
#nextslide{
right:10px;
}
#prevslide:active, #nextslide:active{
margin-top:-19px;
}
#prevslide:hover, #nextslide:hover{
cursor:pointer;
}
#slidecaption h2, #slidecaption p{
text-shadow: 0 0 5px #000;
font-weight: 700;
font-size: 48px;
color: #fff
}
#slidecaption h2 span{
font-family: 'Shadows Into Light', cursive;
text-transform: capitalize;
font-size: 72px;
font-weight: 400;
}
#supersized-loader { position:absolute; top:50%; left:50%; z-index:0; width:60px; height:60px; margin:-30px 0 0 -30px; text-indent:-999em; background:url(../images/progress.gif) no-repeat center center;}
#supersized { display:block; position:absolute; left:0; top:0; overflow:hidden; z-index:-999; height:100%; width:100%; }
#supersized img { width:auto; height:auto; position:relative; display:none; outline:none; border:none; }
#supersized.speed img { -ms-interpolation-mode:nearest-neighbor; image-rendering: -moz-crisp-edges; } /*Speed*/
#supersized.quality img { -ms-interpolation-mode:bicubic; image-rendering: optimizeQuality; } /*Quality*/
#supersized li { display:block; list-style:none; z-index:-30; position:absolute; overflow:hidden; top:0; left:0; width:100%; height:100%; background:#111; }
#supersized a { width:100%; height:100%; display:block; }
#supersized li.prevslide { z-index:-20; }
#supersized li.activeslide { z-index:-10; }
#supersized li.image-loading { background:#111 url(../images/progress.gif) no-repeat center center; width:100%; height:100%; }
#supersized li.image-loading img{ visibility:hidden; }
#supersized li.prevslide img, #supersized li.activeslide img{ display:inline; }
/*parallax
--------------------------------------------------------*/
.parallax{
width:100%;
height:480px;
padding:0;
margin:0;
background-attachment:fixed;
background-repeat:no-repeat;
border-top:10px solid rgba(255,255,255,0.3);
border-bottom:10px solid rgba(255,255,255,0.3);
color:#fff;
position:relative;
}
.parallax .quoteWrap{
display:table;
width:100%;
height:100%;
padding:0 !important;
margin:0 !important;
}
.parallax.fixed{
background-attachment:fixed;
}
.parallax.fixed-desktop{
background-attachment:fixed !important;
}
.parallax .quoteWrap .quote{
display: table-cell;
vertical-align:middle;
}
.parallax {
text-align:center;
}
.parallax h3 span{
text-shadow: 0px 0px 5px #222;
color: #fff;
}
/* portfolio
--------------------------------------------------------*/
#folio {
background:url(../images/gallery-quote-white.png) center 80px no-repeat #fff;
padding-top:100px;
clear: left;
}
.portfolio_container {
position:relative;
display:block;
overflow:hidden;
width:100%;
}
.portfolio_container .portfolio {
position:relative;
display:block;
float:left;
overflow:hidden;
width:25%;
height:auto;
}
.portfolio_container .portfolio .media_box figure a img {
display:block;
margin-left: auto;
margin-right: auto;
}
.portfolio_container .portfolio .media_box .hover_effect {
top:0;
left:0;
}
.gallerySelector {
background: #E5E5E5;
height: 44px;
width: 100%;
margin-top: 20px;
}
.gallerySelectorList {
margin:0;
width: 100%;
}
.gallerySelectorList li {
float: left;
margin:0;
list-style:none;
width: 20%;
text-align: center;
padding: 0;
}
.gallerySelectorList li:hover {
background: #83103e;
}
.gallerySelectorList li:hover a {
color: #fff;
}
.gallerySelectorList li a {
display:block;
padding:11px 0;
color: #222;
text-decoration: none;
margin: 0;
transition:background-color 0.3s ease, color 0.2s ease;
}
.gallerySelectorList li.current {
background: #7b133c;
}
.gallerySelectorList li.current a {
color: #fff;
}
.portfolio_container .portfolio {
width: 20%;
}
.fullwidth {
display: block;
max-width: 100%;
min-width: 100%;
}
#gallery h3 {
margin-bottom: 20px;
}
.project-title {
font-family: 'Oswald', sans-serif;
font-size: 12px;
text-transform: uppercase;
margin-top: 7px;
}
.project-description {
color: #868991;
font-size: 10px;
text-transform: uppercase;
font-weight: 600;
margin: 0 0 20px 0;
}
.thumbLink {
display: block;
width: 100%;
}
.thumbImage {
float: left;
position: relative;
overflow: hidden;
display: block;
margin-bottom: 0px;
box-sizing: border-box;
text-align: center;
width: 100%;
height: 100%;
}
.thumbImage img{
transition: all 0.7s ease-in-out;
}
.thumbImage .thumbText h3 {
margin-bottom: 10px;
padding-top: 10px;
color: #fff;
border-bottom: 1px solid #fff;
transition: all 1s ease-in-out;
}
.thumbImage .thumbText p {
margin-bottom: 10px;
color: #fff;
transition: all 1s ease-in-out;
}
.thumbImage .thumbTextWrap {
position: absolute;
top: 0;
height: 100%;
opacity: 0;
max-width: 100%;
min-width: 100%;
background: #7b133c;
text-align: center;
transition: all 1s ease-in-out;
-webkit-user-select: none;
}
.ie8 .thumbImage .thumbTextWrap {
display:none;
}
.thumbImage .thumbTextWrap:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.5em; /* Adjusts for spacing */
}
.thumbText {
text-align: center;
transform: scale(0);
transition: all 0.7s ease-in-out;
display: inline-block;
vertical-align: middle;
width: 90%;
}
.thumbImage:hover img {
opacity: 0;
transform: scale(10);
}
.touch-device .thumbImage:hover img {
transform: none;
}
.thumbImage:hover .thumbTextWrap {
opacity: 1;
}
.ie8 .thumbImage:hover .thumbTextWrap {
display: block;
}
.thumbImage:hover .thumbText {
transform: scale(1);
}
.touch-device .thumbImage:hover .thumbTextWrap {
display: block;
}
.touch-device .thumbText,
.touch-device .thumbImage img,
.touch-device .thumbImage .thumbText h3,
.touch-device .thumbImage .thumbText p,
.touch-device .thumbImage .thumbTextWrap {
transition: none;
}
.ie8 .thumbImage:hover .thumbTextWrap {
display: block;
}
.thumbLink {
background:#fff;
color: #7A133C;
font-size: 20px;
width: 30px;
height: 30px;
border-radius: 15px;
opacity: 0.5;
margin: 0 auto;
}
.thumbLink:hover {
opacity: 1;
}
.portfolioBottom {
background: #E5E5E5;
height: 44px;
width: 100%;
clear: left;
}
/**** Isotope Filtering ****/
.isotope-item {
z-index: 2;
}
.isotope-hidden.isotope-item {
pointer-events: none;
z-index: 1;
}
/**** Isotope CSS3 transitions ****/
.isotope,
.isotope .isotope-item {
transition-duration: 0.8s;
}
.isotope {
transition-property: height, width;
}
.isotope .isotope-item {
-o-transition-property: top, left, opacity;
transition-property: transform, opacity;
}
/**** disabling Isotope CSS3 transitions ****/
.isotope.no-transition,
.isotope.no-transition .isotope-item,
.isotope .isotope-item.no-transition {
transition-duration: 0s;
}
/* End: Recommended Isotope styles */
/* disable CSS transitions for containers with infinite scrolling*/
.isotope.infinite-scrolling {
transition: none;
}
/* About Us
--------------------------------------------------------*/
#about {
padding-top: 0px;
}
.aboutContainer {
padding-bottom: 100px;
}
.teamImage {
margin-top: 40px;
margin-bottom: 20px;
cursor: default;
overflow: hidden;
position: relative;
text-align: center;
}
.teamImage img {
transform: scale(1);
transition: all 0.7s ease-in-out 0s;
}
.teamImage .teamName {
background-color: #7b133c;
opacity: 0;
transition: all 0.5s linear 0s;
height: 100%;
left: 0;
overflow: hidden;
position: absolute;
top: 0;
width: 100%;
text-align: center;
-webkit-user-select: none;
}
.touch-device .teamImage .teamName {
display: none;
transition: none;
}
.ie8 .teamImage .teamName {
display: none;
}
.teamImage h2 {
margin-top: 145px;
opacity: 0;
transform: scale(0);
color: #fff;
transition: all 0.5s linear 0s;
}
.teamImage h3 {
opacity: 0;
transform: scale(0);
color: #fff;
transition: all 0.7s linear 0s;
}
.teamImage:hover img {
opacity: 0;
transform: scale(10);
}
.teamImage:hover .teamName {
opacity: 1;
}
.touch-device .teamImage:hover .teamName {
display: block;
}
.touch-device .teamImage:hover img {
opacity: 0;
transform: none;
}
.ie8 .teamImage:hover .teamName {
display: block;
}
.teamImage:hover h2, .teamImage:hover h3 {
opacity: 1;
transform: scale(1);
}
.teamImage:hover .socialLinksTeam {
opacity: 1;
transform: scale(1);
}
.socialLinksTeam {
text-align: center;
width: 100%;
opacity: 0;
transform: scale(0);
transition: all 0.8s linear 0s;
}
.socialLinksTeam li {
display: inline-block;
height: 30px;
margin: 35px 1px 0;
transition: all 0.3s ease-in-out 0s;
width: 30px;
}
.socialLinksTeam li a {
color: #FFFFFF;
display: block;
font-size: 16px;
height: 16px;
margin: 0;
transition: all 0.3s ease-in-out 0s;
width: 16px;
opacity: 0.5;
}
.socialLinksTeam li:hover a {
opacity: 1;
}
.teamSkill {
margin-bottom: 40px;
-webkit-user-select: none;
}
p.skill {
clear: left;
font-size: 11px;
letter-spacing: 0.04em;
margin: 0;
text-transform: uppercase;
}
.bar {
background-color: #7B133C;
border-radius: 11px;
color: #FFFFFF;
display: inline-block;
float: left;
height: 22px;
line-height: 22px;
margin: 0 0 2px;
transition: all 0.6s ease-in-out 0s;
width: 22px;
}
.teamSkill:hover .percent100 {width: 100%;}
.teamSkill:hover .percent95 {width: 95%;}
.teamSkill:hover .percent90 {width: 90%;}
.teamSkill:hover .percent85 {width: 85%;}
.teamSkill:hover .percent80 {width: 80%;}
.teamSkill:hover .percent75 {width: 75%;}
.teamSkill:hover .percent70 {width: 70%;}
.teamSkill:hover .percent65 {width: 65%;}
.teamSkill:hover .percent60 {width: 60%;}
.teamSkill:hover .percent55 {width: 55%;}
.teamSkill:hover .percent50 {width: 50%;}
.teamSkill:hover .percent45 {width: 45%;}
.teamSkill:hover .percent40 {width: 40%;}
.teamSkill:hover .percent35 {width: 35%;}
.teamSkill:hover .percent30 {width: 30%;}
.teamSkill:hover .percent25 {width: 25%;}
.teamSkill:hover .percent20 {width: 20%;}
p.percent {
float: right;
margin-right: 6px;
text-align: right;
opacity: 0;
transition: all 0.6s ease-in-out 0s;
}
.ie8 p.percent {
display:none;
}
.teamSkill:hover p.percent {
opacity: 1;
}
.ie8 .teamSkill:hover p.percent {
display:block;
}
.statsWrap {
width: 130px;
margin: 10px;
float: left;
}
.stats {
display: inline-block;
position: relative;
width: 100%;
transition: all 0.3s ease-in-out 0s;
-webkit-user-select: none;
}
.statDummy {
margin-top: 100%;
}
.statInfo {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: #7B133C;
border-radius: 50%;
text-align: center;
}
.statNumber {
font-size: 60px;
transition: all 0.5s ease-in-out 0s;
padding-top: 24px;
margin-bottom: 0;
color: #fff;
}
.statNumberMedium {
font-size: 50px;
transition: all 0.5s ease-in-out 0s;
padding-top: 30px;
margin-bottom: 0;
}
.statNumberSmall {
font-size: 36px;
transition: all 0.5s ease-in-out 0s;
padding-top: 38px;
margin-bottom: 0;
}
.statText {
transition: all 0.5s ease-in-out 0s;
opacity: 0;
transform: scale(0);
padding: 0;
margin-top: -25px;
color: #fff;
}
.stats:hover {
transform: scale(2);
z-index: 10;
}
.stats:hover .statNumber {
transform: scale(.6);
}
.stats:hover .statText {
transform: scale(.6);
opacity: 1;
}
/* Services
--------------------------------------------------------*/
#services {
padding-top: 0;
}
.servicesContainer {
padding-bottom: 100px;
}
.serviceItem {
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
cursor: default;
height: 236px;
position: relative;
width: 236px;
margin: 20px auto;
}
.serviceInfoWrap, .serviceInfo {
height: 196px;
position: absolute;
width: 196px;
}
.serviceInfoWrap {
background: #F9F9F9;
box-shadow: 0 0 0 20px rgba(255,255,255, 0.4), 0 0 3px rgba(115, 114, 23, 0.8) inset;
left: 20px;
top: 20px;
}
.serviceInfo > div {
background-position: center center;
display: block;
height: 100%;
position: absolute;
width: 100%;
text-align: center;
}
.serviceInfo .serviceInfoFront {
transition: all 0.6s ease-in-out 0s;
}
.serviceInfo .serviceInfoBack {
background:#7B133C;
opacity: 0;
pointer-events: none;
transform: scale(1.5);
transition: all 0.4s ease-in-out 0.2s;
-webkit-user-select: none;
}
.ie8 .serviceInfo .serviceInfoBack {
display: none;
}
.copywriting, .copywriting .serviceInfoFront {background-image: url(../images/services/copywriting.jpg);}
.creativity, .creativity .serviceInfoFront {background-image: url(../images/services/creativity.jpg);}
.production, .production .serviceInfoFront {background-image: url(../images/services/production.jpg);}
.development, .development .serviceInfoFront {background-image: url(../images/services/development.jpg);}
.photography, .photography .serviceInfoFront {background-image: url(../images/services/photography.jpg);}
.strategy, .strategy .serviceInfoFront {background-image: url(../images/services/strategy.jpg);}
.serviceInfo h3 {
color: #FFFFFF;
font-size: 18px;
margin: 0 15px;
padding: 0 0 10px;
text-align: center;
text-transform: uppercase;
}
.serviceInfo p {
border-top: 1px solid rgba(255, 255, 255, 0.5);
color: #FFFFFF;
margin: 0 20px;
padding: 5px 10px 0;
}
.serviceIcon {
width: 35px;
height: 35px;
margin: 20px auto 10px auto;
}
.serviceIcon i{
color: #fff;
font-size: 32px;
}
.serviceItem:hover .serviceInfoFront {
opacity: 0;
transform: scale(0);
}
.serviceItem:hover .serviceInfoBack {
opacity: 1;
pointer-events: auto;
transform: scale(1);
}
.ie8 .serviceItem:hover .serviceInfoBack {
display: block;
}
/* Features
--------------------------------------------------------*/
#features {
padding-top: 0px;
}
.featuresContainer {
padding-bottom: 100px;
}
/* Accordion
--------------------------------------------------------*/
.accTrigger {
cursor: pointer;
display: block;
margin: 10px 0;
background: #e5e5e5;
border-radius: 6px;
border-left: 3px solid #7B133C;
}
.accTrigger a {
display: block;
color: #222;
outline: none;
padding: 10px;
text-decoration: none;
font-size: 24px;
}
.accTrigger.active a {
cursor: default;
color: #9c2252;
}
.accTrigger.active a:hover {
}
.accTrigger a:hover {
color: #9c2252;
}
.accContainer .content{
padding: 2px 15px 5px 15px;
line-height: 19px;
}
.accContent p {
margin-bottom: 10px;
}
.accContent {
padding: 5px 13px 20px 13px;
}
/* Tooltip
--------------------------------------------------------*/
.tooltip {
position: absolute;
z-index: 1020;
display: block;
padding: 5px;
font-size: 12px;
opacity: 0;
filter: alpha(opacity=0);
visibility: visible;
}
.tooltip.in {
opacity: 0.8;
filter: alpha(opacity=80);
}
.tooltip.top {
margin-top: -2px;
}
.tooltip.right {
margin-left: 2px;
}
.tooltip.bottom {
margin-top: 2px;
}
.tooltip.left {
margin-left: -2px;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-top: 5px solid #555;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 5px solid #555;
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-right: 5px solid transparent;
border-bottom: 5px solid #555;
border-left: 5px solid transparent;
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-top: 5px solid transparent;
border-right: 5px solid #555;
border-bottom: 5px solid transparent;
}
.tooltip-inner {
max-width: 200px;
padding: 4px 10px;
color: #222;
text-align: center;
text-decoration: none;
background-color: #555;
border-radius: 6px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
}
/*contact
--------------------------------------------------------*/
.contactContainer {
padding-bottom: 100px;
}
.contactDetails li span {
padding-right: 5px;
color: #555;
font-size: 12px;
}
.icon-spacer {
padding-left: 12px;
}
.socialLinks {
text-align: center;
}
.socialLinks li {
background-color: #7B133C;
border-radius: 50% 50% 50% 50%;
float: left;
height: 60px;
margin: 10px 5px;
transition: all 0.6s ease-in-out 0s;
width: 60px;
}
.socialLinks li a {
display: block;
}
.socialLinks li a i {
color: #FFFFFF;
display: block;
font-size: 32px;
height: 30px;
margin: 15px 0 0 15px;
width: 30px;
}
.socialLinks li:hover {
background-color: #8A97A6;
}
/*form elements
--------------------------------------------------------*/
textarea {
height:156px;
padding:20px;
margin-bottom:20px;
overflow:auto;
}
.formSecWrap {
float: left;
margin-right: 20px;
}
.formSecWrap2 {
margin-right: 0px;
}
input[type="text"], input[type="password"], input[type="email"], textarea, select {
background: #e5e5e5;
border: none;
border-radius: 3px;
color: #222;
display: block;
margin: 0 0 10px 0;
outline: medium none;
padding: 4px 4px;
width: 370px;
font-family:'Oswald', sans-serif;
font-size: 16px;
font-weight: 400;
}
input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus, textarea:focus {
box-shadow: 0 0 7px #222;
}
.formWrap label{
margin: 0 0 2px 0;
}
.formWrap input[type="submit"]{
margin: 10px 0 20px 0;
float: right;
}
a.button,
button,
input[type="submit"],
input[type="reset"],
input[type="button"] {
background: #7b133c;
border: none;
padding: 4px 12px;
border-radius: 0;
font-family: 'Oswald', sans-serif;
color: #fff;
display: inline-block;
font-size: 13px;
text-decoration: none;
cursor: pointer;
margin: 0 5px 10px 0;
line-height: 21px;
-webkit-appearance: none;
}
a.button:hover,
button:hover,
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="button"]:hover {
color: #222;
background: #ddd;
}
/* Flickr
--------------------------------------------------------*/
.flickrListing {
margin-right: -12px;
margin-top: 15px;
margin-bottom: 25px;
}
.flickrListing img {
display: block;
width: 100%;
}
.flickrListing a {
float: left;
margin-right: 12px;
margin-bottom: 12px;
border: 1px solid #333;
padding: 3px;
transition: all 0.2s ease-in-out;
}
.flickrListing a:hover {
border: 1px solid #222;
}
/* Alert Boxes
--------------------------------------------------------*/
.alert {
padding: 8px 35px 8px 14px;
margin-bottom: 10px;
margin-top: 10px;
clear: left;
color: #c09853;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
background-color: #fcf8e3;
border: 1px solid #fbeed5;
border-radius: 3px;
}
.alert h4 {
margin: 0;
}
.alert p {
margin: 0;
}
.alert .close {
position: relative;
top: -2px;
right: -35px;
line-height: 20px;
}
.alert-success {
color: #468847;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.alert-danger,
.alert-error {
color: #b94a48;
background-color: #f2dede;
border-color: #eed3d7;
}
.alert-info {
color: #3a87ad;
background-color: #d9edf7;
border-color: #bce8f1;
}
button.close {
background: none;
border: 0 none;
cursor: pointer;
padding: 0;
}
.close {
color: #000000;
float: right;
font-size: 20px;
font-weight: bold;
line-height: 20px;
opacity: 0.2;
text-shadow: 0 1px 0 #FFFFFF;
}
/*footer
--------------------------------------------------------*/
#footer{
position:relative;
overflow:hidden;
padding:30px 0 50px 0;
z-index:1;
background:#fff;
}
#footer p.copyright{
margin-bottom:0;
margin-top: 20px;
text-align: center;
color: #888888;
}
/* Our Clients
--------------------------------------------------------*/
.flex-container a:active, .flexslider a:active, .flex-container a:focus, .flexslider a:focus {
outline: medium none;
}
.slides, .flex-control-nav, .flex-direction-nav {
list-style: none outside none;
margin: 0;
padding: 0;
}
.slides li {
margin: 0;
}
.flexslider {
margin: 0;
padding: 0;
}
.flexslider .slides > li {
backface-visibility: hidden;
display: none;
}
.flex-pauseplay span {
text-transform: capitalize;
}
.slides:after {
clear: both;
content: ".";
display: block;
height: 0;
line-height: 0;
visibility: hidden;
}
html[xmlns] .slides {
display: block;
}
* html .slides {
height: 1%;
}
.no-js .slides > li:first-child {
display: block;
}
.flexslider {
position: relative;
z-index: 1;
}
.flexslider .slides > li {
position: relative;
}
.flex-container {
position: relative;
}
.flexslider .slides img {
display: block;
margin: auto;
max-width: 100%;
}
.flex-direction-nav a {
cursor: pointer;
display: block;
height: 60px;
margin: -30px 0 0;
opacity: 0;
position: absolute;
top: 50%;
width: 30px;
background: #555;
font-family: 'surreal';
font-size: 32px;
color: #fff;
line-height: 60px;
}
.flex-direction-nav a:hover {
color: #999;
}
.flex-direction-nav a.flex-next:before {
content: "\e016";
}
.flex-direction-nav a.flex-prev:before {
content: "\e013";
}
.flex-direction-nav a.flex-next {
right: 0;
border-radius:30px 0 0 30px;
}
.flex-direction-nav a.flex-prev {
left: 0;
border-radius:0 30px 30px 0;
}
.flexslider:hover .flex-next {
opacity: 1;
right: 0;
}
.flexslider:hover .flex-prev {
left: 0;
opacity: 1;
}
.flex-direction-nav .disabled {
cursor: default;
opacity: 0.3 !important;
}
.flex-direction-nav .flex-next {
right: -30px;
}
.flex-direction-nav .flex-prev {
left: -30px;
}
#carouselSlider, #carouselSlider .slides, #carouselSlider .slides li {
height: 120px;
}
#carouselSlider li {
border-right: 1px solid #333;
}
.flex-control-nav {
margin-top: 20px;
position: absolute;
text-align: center;
width: 100%;
z-index: 99;
}
.flex-control-nav li {
display: inline-block;
margin: 0 0 0 3px;
}
.flex-control-nav li:first-child {
margin: 0;
}
.flex-control-nav li a {
cursor: pointer;
display: block;
height: 14px;
text-indent: -9000px;
width: 14px;
}
.flex-control-nav li a:hover {
background-position: 0 0;
}
.flex-control-nav li a.active {
background-position: 0 -14px;
cursor: default;
}
/* Blog
--------------------------------------------------------*/
.blogTitle {
margin-top: -80px;
}
.blogTitlePost h2{
font-size: 125px;
text-transform: uppercase;
position: relative;
letter-spacing: -2px;
text-align: left;
line-height: 0.8;
margin-bottom: 35px;
padding-top: 0px;
}
.blogTitlePost h2 span{
color: #7B133C;
font-size: 75px;
}
.post {
margin-bottom: 50px;
border-top: 1px solid #333333;
padding-top: 20px;
}
.post-title h3{
font-size: 30px;
}
.dateWrap {
background: #7B133C;
padding: 10px;
position: absolute;
margin-top: 10px;
z-index: 2000;
color: #fff;
}
.date-day {
font-size: 48px;
}
.post-media {
margin: 10px 0 20px 0;
}
.post-media img{
border-bottom: 10px solid #7B133C;
}
.post-body div a {
background: #7B133C;
padding: 2px 10px;
color: #fff;
}
.post-body div a:hover {
background: #333333;
}
.tags {
margin: 30px 0;
overflow: auto;
}
.tags a {
color: #FFFFFF;
float: left;
font-weight: 300;
height: 26px;
line-height: 26px;
margin-bottom: 5px;
margin-right: 5px;
padding: 3px 8px;
text-transform: uppercase;
transition: background-color 0.3s ease 0s;
background: #c3c3c3;
border-left: 1px solid #7B133C;
}
.tags a:hover {
background-color: #7B133C;
}
/* Comments */
#comments {
border-top: 1px solid #333333;
margin-top: 40px;
padding-top: 20px;
clear: both;
}
#comments [class*="span"] {
-moz-box-sizing: border-box;
display: block;
float: left;
margin-left: 2.5641%;
min-height: 30px;
width: 100%;
}
#comments .span11 {
width: 91.453%;
}
.comment-body > .span11 > p:last-child {
margin-bottom: 0;
}
.comment-body > .span11 > p a {
color: #AAAAAA;
}
.comment-body > .span11 > p a:hover {
color: #555555;
}
#commentform [class*="span"] {
margin-left: 0;
}
#comments .span12 {
margin-left: 0;
}
#comments .span1 {
margin-left: 0;
width: 5.98291%;
}
#comments li {
background: none repeat scroll 0 0 transparent;
padding-left: 0;
}
#comments p {
margin-bottom: 20px;
}
#comments .comment-body {
margin-bottom: 10px;
}
#comments-title {
font-size: 28px;
margin-bottom: 30px;
}
#comments-title span {
color: #7B133C;
font-size: 14px;
font-weight: 400;
line-height: 10px;
padding: 0 5px;
vertical-align: middle;
}
.commentlist, #comments .children {
list-style-type: none;
margin: 0;
padding: 0;
}
.pe-offset1 {
margin-left: 8.54701% !important;
}
.commentlist {
margin-bottom: 40px;
}
.row-fluid {
width: 100%;
}
.row-fluid:before, .row-fluid:after {
content: "";
display: table;
line-height: 0;
}
.row-fluid:after {
clear: both;
}
.comment-author img {
border: 2px solid #F5F5F5;
display: block;
max-width: 100%;
}
.bypostauthor > .comment-body > .comment-author img {
border: 2px solid #7B133C;
}
.bypostauthor > .comment-body .fn a {
color: #7B133C;
}
.bypostauthor > .comment-body p {
color: #666666;
}
#comments .fn {
font-weight: 700;
margin-top: 2px;
}
.fn a {
color: #AAAAAA;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
}
.comment-body .fn, .comment-body .says {
float: left;
font-size: 14px;
}
.says {
margin-left: 5px;
margin-top: 2px;
}
#comments [id*="div-comment"] .span11 {
background: #C3C3C3;
padding: 10px;
position: relative;
}
#comments .comment-arrow {
border-bottom: 14px solid transparent;
border-right: 14px solid #333333;
border-top: 14px solid transparent;
height: 0;
left: -14px;
position: absolute;
top: 13px;
width: 0;
}
#comments .fn a:hover {
color: #555555;
text-decoration: none;
}
#comments .comment-meta {
clear: both;
margin-bottom: 10px;
}
#comments .comment-meta a {
color: #AAAAAA;
font-size: 13px;
}
#comments .comment-meta a:hover {
color: #666666;
text-decoration: none;
}
#comments .reply {
float: right;
}
#comments .reply .label {
background-color: #7B133C;
color: #FFFFFF;
font-size: 10px;
padding: 4px 8px;
text-shadow: none;
text-transform: uppercase;
}
#comments .reply .label:hover {
background-color: #555555;
}
#comments .post-pagination {
margin-bottom: 60px;
}
#comments .pagination .active a {
background-color: #666666;
border-color: #666666;
color: #FFFFFF;
}
#respond {
margin-bottom: 50px;
}
#respond #reply-title {
color: #BBBBBB;
font-size: 22px;
font-weight: 400;
margin-bottom: 40px;
}
#commentform .comment-notes {
color: #AAAAAA;
font-size: 12px;
}
#commentform .comment-notes a {
color: #7B133C;
}
#commentform .comment-notes a:hover {
color: #555555;
}
#commentform label {
color: #fff;
padding-top: 0;
text-align: left;
width: auto;
position: absolute;
left: 0px;
top: 0px;
}
#commentform .controls {
margin-left: 0;
}
#commentform .controls input {
border-radius: 0 0 0 0;
float: left;
margin-right: 30px;
}
#commentform .control-group .required {
color: #7B133C;
margin-left: 3px;
margin-top: 3px;
}
#commentform .control-group {
position: relative;
float: left;
width: 33.3%
}
#commentform .control-label {
float: left;
text-align: left;
}
#comment input[type="text"], #commentform textarea {
width: 400px;
}
#commentform input[type="text"] {
margin-right: 20px;
}
#commentform .comment-form-comment .controls {
clear: both;
float: none;
}
#commentform textarea {
width: 100%;
}
#commentform .form-submit .controls {
margin-left: 0;
}
#commentform .form-submit button[type="submit"] {
background: none repeat scroll 0 0 #7B133C;
border: 0 none;
border-radius: 0;
box-shadow: none;
clear: both;
color: #FFFFFF;
float: left;
font-family: 'Oswald', sans-serif;
font-size: 13px;
height: 40px;
padding: 5px 10px;
text-shadow: none;
text-transform: uppercase;
transition: all 0.3s ease-out 0s;
}
#commentform .form-submit button[type="submit"]:hover {
background-color: #555555;
color: #FFFFFF;
}
#commentform input[type="text"], #commentform textarea {
background-color: #333333;
border-radius: 0px;
box-shadow: none;
color: #D0D0D0;
font-size: 14px;
min-height: 30px;
padding: 5px 10px;
font-weight: 400;
}
#commentform input[type="text"]:focus, #commentform textarea:focus {
border-color: #7B133C;
}
#commentform input[type="text"] {
height: 30px;
width: 96%;
}
#commentform .comment-form-url input[type="text"] {
width: 100%;
}
#commentform .control-group .controls {
float: left;
margin-left: 0 !important;
overflow: hidden;
padding-top: 22px;
width: 100%;
}
.comment-form-comment .controls {
float: none;
width: 98%;
}
#commentform .comment-form-comment {
width: 100%
}
#commentform .comment-form-comment .controls{
padding-top: 0px;
}
.form-horizontal .control-group:before, .form-horizontal .control-group:after {
content: "";
line-height: 0;
}
.form-horizontal .control-group:after {
clear: both;
}
.form-horizontal .control-label {
float: left;
padding-top: 5px;
text-align: right;
width: 160px;
}
.form-horizontal .controls {
margin-left: 180px;
}
.form-horizontal .controls:first-child {
}
.form-horizontal .help-block {
margin-bottom: 0;
}
.form-horizontal input + .help-block, .form-horizontal select + .help-block, .form-horizontal textarea + .help-block {
margin-top: 10px;
}
.form-horizontal .form-actions {
padding-left: 180px;
}
/* Widgets */
.sidebar {
margin-bottom: 60px;
padding-top: 20px;
border-top: 1px solid #333333;
}
.sidebar .widget {
font-size: 16px;
line-height: 20px;
margin-bottom: 20px;
}
.sidebar h3 {
border-bottom: 1px solid #333333;
font-size: 28px;
line-height: 30px;
margin-bottom: 10px;
padding: 26px 0 6px;
}
.widget_search {
position: relative;
}
.widget_search button[type="submit"] {
background-color: transparent;
background-position: -44px 7px;
border: 0 none;
cursor: pointer;
height: 27px;
opacity: 0.4;
padding: 5px 10px 8px 5px;
position: absolute;
right: 4px;
top: 4px;
width: 26px;
}
.widget_search button[type="submit"]:hover {
opacity: 0.7;
}
.widget_search input[type="text"] {
background-color: #C3C3C3;
border-radius: 0;
box-shadow: none;
color: #222222;
display: block;
font-size: 12px;
height: 30px;
padding: 2px 10px;
transition: border-color 0.3s ease 0s;
width: 85%;
margin: 0;
box-sizing: border-box;
float: left;
}
.widget_search input[type="text"]:focus {
border-color: #7B133C;
}
.widget_search input[type="submit"] {
width: 15%;
margin: 0;
box-sizing: border-box;
}
.widget_text {
margin-bottom: 65px;
}
.widget_categories ul li {
color: #CCCCCC;
font-size: 11px;
}
.widget_categories a {
color: #666666;
font-size: 16px;
margin-right: 10px;
}
.widget_categories a:hover {
color: #D95137;
}
.widget_archive li {
color: #999999;
font-size: 11px;
}
.widget_archive a {
font-size: 16px;
margin-right: 9px;
}
.widget_menu li:before {
content: "";
}
.widget_menu a {
border: 1px solid #EEEEEE;
height: 26px;
line-height: 26px;
text-shadow: none !important;
text-transform: uppercase;
}
.widget_menu a:hover {
background-color: #DDDDDD;
color: #666666;
}
.widget_menu li.active a {
background: url("../../styles/../img/skin/sidebar_menu_active.png") no-repeat scroll 95% 50% #D95137;
color: #FFFFFF;
}
.widget_menu li.active a:hover {
background-color: #D95137;
color: #FFFFFF;
cursor: default;
}
.widget_tag_cloud li:before {
content: "";
}
.widget_tag_cloud a {
color: #FFFFFF;
float: left;
font-weight: 300;
height: 26px;
line-height: 26px;
margin-bottom: 5px;
margin-right: 5px;
padding: 3px 8px;
text-transform: uppercase;
transition: background-color 0.3s ease 0s;
background: #c3c3c3;
border-left: 1px solid #7B133C;
}
.widget_tag_cloud a:hover {
background-color: #7B133C;
color: #FFFFFF;
}
.widget_tag_cloud .tagcloud {
overflow: hidden;
}
.widget_calendar li:before {
content: "";
}
.widget_calendar #wp-calendar {
color: #999999;
text-align: center;
width: 100%;
}
.widget_calendar caption, .widget_calendar th, .widget_calendar td {
text-align: center;
padding-top: 2px;
padding-bottom: 2px;
}
.widget_calendar caption {
color: #fff;
font-size: 16px;
padding: 25px 0 12px;
text-align: left;
text-transform: uppercase;
}
.widget_calendar th {
background: #C3C3C3;
border-bottom: 0 none;
border-top: 0 none;
font-weight: 600;
padding-bottom: 5px;
padding-top: 5px;
color: #fff;
}
.widget_calendar tbody td a {
background: #E4E4E4;
padding: 0px 5px;
width: 100%;
}
.widget_calendar tfoot td a:hover {
background: #F6F6F6;
}
.widget_calendar tfoot td {
background: none repeat scroll 0 0 transparent;
border-bottom: 0 none;
border-top: 0 none;
}
.widget_calendar tfoot td a {
color: #666666;
text-transform: uppercase;
}
.widget_calendar tfoot td a:hover {
background: none repeat scroll 0 0 transparent;
color: #fff;
}
.widget_calendar tfoot #prev {
text-align: left;
}
.widget_calendar tfoot #next {
text-align: right;
}
.widget_links ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.sidebar li:before {
color: #7B133C;
content: "\e016";
display: inline-block;
font-family: 'surreal';
font-size: 13px;
font-style: normal;
font-weight: normal;
line-height: 1em;
margin-right: 0.2em;
margin-top: 9px;
text-align: center;
text-decoration: inherit;
width: 1em;
transition: all 0.3s ease-in-out;
}
.sidebar li span {
color: #CCCCCC;
font-size: 10px;
font-style: italic;
margin-left: 15px;
}
.widget_links li a,
.widget_pages li a,
.widget_meta li a,
.widget_archive li a,
.widget_calendar tbody td a,
.widget_categories li a,
.widget_recent_entries li a,
.widget_recent_comments li a {
color: #999999;
transition: all 0.3s ease-in-out;
}
.widget_links li a:hover,
.widget_pages li a:hover,
.widget_meta li a:hover,
.widget_archive li a:hover,
.widget_categories li a:hover,
.widget_calendar tbody td a:hover,
.widget_recent_entries li a:hover,
.widget_recent_comments li a:hover {
color: #222;
text-decoration: none;
}
.widget_recent_entries {
font-size: 16px;
margin-right: 0;
}
.widget_recent_entries p {
margin-top: 25px;
}
.comments-num {
display: block;
float: right;
width: 28px;
}
.widget_recent_entries span {
text-transform: lowercase;
}
/* Custom Font
--------------------------------------------------------*/
@font-face {
font-family: 'surreal';
src:url('../fonts/surreal.eot');
src:url('../fonts/surreal.eot?#iefix') format('embedded-opentype'),
url('../fonts/surreal.woff') format('woff'),
url('../fonts/surreal.ttf') format('truetype'),
url('../fonts/surreal.svg#surreal') format('svg');
font-weight: normal;
font-style: normal;
}
/* Use the following CSS code if you want to use data attributes for inserting your icons */
[data-icon]:before {
font-family: 'surreal';
content: attr(data-icon);
speak: none;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
}
/* Use the following CSS code if you want to have a class per icon */
/*
Instead of a list of all class selectors,
you can use the generic selector below, but it's slower:
[class*="icon-"] {
*/
.icon-location, .icon-envelop, .icon-phone, .icon-print, .icon-clock, .icon-arrow-right, .icon-arrow-left, .icon-twitter, .icon-google-plus, .icon-facebook, .icon-flickr, .icon-skype, .icon-linkedin, .icon-pinterest, .icon-youtube, .icon-vimeo, .icon-dribbble, .icon-feed, .icon-plus, .icon-arrow-left-2, .icon-arrow-down, .icon-arrow-up, .icon-arrow-right-2, .icon-quote, .icon-search, .icon-brush, .icon-share, .icon-mobile, .icon-camera, .icon-camera-2, .icon-quill {
font-family: 'surreal';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
}
.icon-location:before {
content: "\e001";
}
.icon-envelop:before {
content: "\e002";
}
.icon-phone:before {
content: "\e003";
}
.icon-print:before {
content: "\e004";
}
.icon-clock:before {
content: "\e005";
}
.icon-arrow-right:before {
content: "\e006";
}
.icon-arrow-left:before {
content: "\e007";
}
.icon-twitter:before {
content: "\e008";
}
.icon-google-plus:before {
content: "\e009";
}
.icon-facebook:before {
content: "\e00a";
}
.icon-flickr:before {
content: "\e00b";
}
.icon-skype:before {
content: "\e00c";
}
.icon-linkedin:before {
content: "\e00d";
}
.icon-pinterest:before {
content: "\e00e";
}
.icon-youtube:before {
content: "\e00f";
}
.icon-vimeo:before {
content: "\e010";
}
.icon-dribbble:before {
content: "\e011";
}
.icon-feed:before {
content: "\e012";
}
.icon-plus:before {
content: "\e000";
}
.icon-arrow-left-2:before {
content: "\e013";
}
.icon-arrow-down:before {
content: "\e014";
}
.icon-arrow-up:before {
content: "\e015";
}
.icon-arrow-right-2:before {
content: "\e016";
}
.icon-quote:before {
content: "\e017";
}
.icon-search:before {
content: "\e018";
}
.icon-brush:before {
content: "\e019";
}
.icon-share:before {
content: "\e01a";
}
.icon-mobile:before {
content: "\e01b";
}
.icon-camera:before {
content: "\e01c";
}
.icon-camera-2:before {
content: "\e01d";
}
.icon-quill:before {
content: "\e01e";
}
/* MISC
--------------------------------------------------------*/
.clear{float:none;}
/* Media Queries
--------------------------------------------------------*/
/* Smaller than standard 1199 (devices and browsers) */
@media only screen and (max-width: 1199px) {
.parallax.fixed{background-attachment:scroll; background-position: center center;}
}
/* Higher than 960 (desktop devices) */
@media only screen and (min-width: 960px) and (max-width: 1199px) {
.teamImage h2 {margin-top: 105px; font-size:40px;}
input[type="text"], input[type="password"], input[type="email"], textarea, select {width: 290px;}
}
/* Smaller than standard 960 (devices and browsers) */
@media only screen and (max-width: 959px) {
.small {font-size: 30px; font-weight:300;}
.smallBold {font-size: 30px; font-weight:700;}
.medium {font-size: 38px; text-transform: uppercase;}
.mediumBold {font-size: 38px; font-weight:700; text-transform: uppercase;}
.large {font-size: 50px; text-transform: uppercase;}
.largeBold {font-size: 50px; font-weight:700; text-transform: uppercase;}
.author {font-size: 16px; font-weight:300;}
}
/* Tablet Portrait size to standard 960 (devices and browsers) */
@media only screen and (min-width: 768px) and (max-width: 959px) {
h1 {font-size: 200px;}
.teamImage h2 {margin-top: 75px; font-size:32px;}
input[type="text"], input[type="password"], input[type="email"], textarea, select {width: 226px;}
.parallax.fixed{background-attachment:scroll; background-position: center center;}
.blogTitle {margin-top: -40px;}
}
/* All Mobile Sizes (devices and browser) */
@media only screen and (max-width: 767px) {
.dropmenu { display: block; margin-top: 5px; }
#nav {display: none;}
#slidecaption { display:none;}
#prevslide, #nextslide{top:120px;}
.parallax.fixed{background-attachment:scroll; background-position: center center;}
.logo {margin-top: 10px; transform: scale(.5);}
#prevslide {right: 45px; transform: scale(.5);}
#nextslide {right: 22px; transform: scale(.5);}
.homepage {margin-bottom: -50px;}
.thumbImage .thumbTextWrap {padding: 0 10px;}
.thumbImage .thumbText p {font-size: 12px;}
.thumbImage .thumbText h3 {font-size: 21px;}
.blogTitle {margin-top: 0px;}
}
/* Mobile Landscape Size to Tablet Portrait (devices and browsers) */
@media only screen and (min-width: 480px) and (max-width: 767px) {
h1 {font-size: 110px;}
h1 span{font-size: 80px;}
input[type="text"], input[type="password"], input[type="email"], textarea, select {width: 418px;}
}
/* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */
@media only screen and (max-width: 479px) {
h1 {font-size: 80px;}
h1 span{font-size: 60px;}
.teamImage h2 {margin-top: 105px; font-size:40px;}
input[type="text"], input[type="password"], input[type="email"], textarea, select {width: 298px;}
} | apple777/wp | wp-content/themes/surreal/styles/layout-white.css | CSS | gpl-2.0 | 46,963 |
<?php defined('WPSS_PATH') or die();?>
<?php $util = new WPSS_Util();?>
<?php $question = new WPSS_Question((int) $_GET['id']);?>
<?php $quiz = new WPSS_Quiz($question->quiz_id);?>
<!-- Admin questions#new -->
<div class="wrap wpss">
<img class="left" src="<?php echo WPSS_URL.'assets/images/wpss_admin.png'?>" />
<h2 class="left"><?php echo $quiz->title;?>, Editing Question</h2>
<div class="clear"></div>
<hr />
<p class="wpss-breadcrumb">
<a href="<?php echo $util->admin_url('','','');?>">Quizzes</a> » <a href="<?php echo $util->admin_url('quiz', 'edit', $quiz->id);?>"><?php echo $quiz->title;?></a> » <a href="<?php echo $util->admin_url('quiz', 'questions_index', $quiz->id);?>">Questions</a> » <a class="current">Edit</a>
</p>
<?php include( WPSS_PATH . "admin/questions/_form.php");?>
</div>
| JohnBueno/cafequill | wp-content/plugins/wordpress-simple-survey/admin/questions/edit.php | PHP | gpl-2.0 | 843 |
<?php
namespace Drutiny\Audit;
use Drutiny\Sandbox\Sandbox;
use Drutiny\Audit\AuditInterface;
/**
*
*/
interface RemediableInterface extends AuditInterface
{
/**
* Attempt to remediate the check after it has failed.
*
* @param Sandbox $sandbox
* @return bool
*/
public function remediate(Sandbox $sandbox);
}
| drutiny/drutiny | src/Audit/RemediableInterface.php | PHP | gpl-2.0 | 336 |
<?php
pb_backupbuddy::$ui->start_metabox( 'BackupBuddy Settings', true, 'width: 100%; max-width: 1200px;' );
$settings_form->display_settings( 'Save Settings' );
echo '<br><br>';
pb_backupbuddy::$ui->end_metabox();
/*
REMOVED v3.1.
pb_backupbuddy::$ui->start_metabox( __('Remote Offsite Storage / Destinations', 'it-l10n-backupbuddy' ) . ' ' . pb_backupbuddy::video( 'PmXLw_tS42Q#177', __( 'Remote Offsite Management / Remote Clients Tutorial', 'it-l10n-backupbuddy' ), false ), true, 'width: 100%; max-width: 1200px;' );
//echo '<h3>' . __('Remote Offsite Storage / Destinations', 'it-l10n-backupbuddy' ) . ' ' . pb_backupbuddy::video( 'PmXLw_tS42Q#177', __( 'Remote Offsite Management / Remote Clients Tutorial', 'it-l10n-backupbuddy' ), false ) . '</h3>';
//echo '<br>';
echo '<a href="' . pb_backupbuddy::ajax_url( 'destination_picker' ) . '&action_verb=to%20manage%20files&TB_iframe=1&width=640&height=600" class="thickbox button secondary-button" style="margin-top: 3px;" title="' . __( 'Manage Destinations & Archives', 'it-l10n-backupbuddy' ) . '">' . __('Manage Destinations & Archives', 'it-l10n-backupbuddy' ) . '</a>';
echo ' ';
_e( 'Add & configure destinations or select a destination to browse & manage its files.', 'it-l10n-backupbuddy' );
echo '<br><br>';
pb_backupbuddy::$ui->end_metabox();
*/
?>
<script type="text/javascript">
function pb_backupbuddy_selectdestination( destination_id, destination_title, callback_data ) {
window.location.href = '<?php
if ( is_network_admin() ) {
echo network_admin_url( 'admin.php' );
} else {
echo admin_url( 'admin.php' );
}
?>?page=pb_backupbuddy_backup&custom=remoteclient&destination_id=' + destination_id;
}
</script>
<?php
// Handles thickbox auto-resizing. Keep at bottom of page to avoid issues.
if ( !wp_script_is( 'media-upload' ) ) {
wp_enqueue_script( 'media-upload' );
wp_print_scripts( 'media-upload' );
}
?> | Ransom-Brent/HVAC | wp-content/plugins/backupbuddy/views/settings.php | PHP | gpl-2.0 | 1,947 |
// Copyright 2008 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "Core/Boot/Boot.h"
#include <algorithm>
#include <array>
#include <cstring>
#include <memory>
#include <numeric>
#include <optional>
#include <string>
#include <unordered_set>
#include <vector>
#include <zlib.h>
#include "Common/Align.h"
#include "Common/CDUtils.h"
#include "Common/CommonPaths.h"
#include "Common/CommonTypes.h"
#include "Common/Config/Config.h"
#include "Common/File.h"
#include "Common/FileUtil.h"
#include "Common/Logging/Log.h"
#include "Common/MsgHandler.h"
#include "Common/StringUtil.h"
#include "Core/Boot/DolReader.h"
#include "Core/Boot/ElfReader.h"
#include "Core/CommonTitles.h"
#include "Core/Config/SYSCONFSettings.h"
#include "Core/ConfigManager.h"
#include "Core/FifoPlayer/FifoPlayer.h"
#include "Core/HLE/HLE.h"
#include "Core/HW/DVD/DVDInterface.h"
#include "Core/HW/EXI/EXI_DeviceIPL.h"
#include "Core/HW/Memmap.h"
#include "Core/HW/VideoInterface.h"
#include "Core/Host.h"
#include "Core/IOS/IOS.h"
#include "Core/PatchEngine.h"
#include "Core/PowerPC/PPCAnalyst.h"
#include "Core/PowerPC/PPCSymbolDB.h"
#include "Core/PowerPC/PowerPC.h"
#include "DiscIO/Enums.h"
#include "DiscIO/Volume.h"
BootParameters::BootParameters(Parameters&& parameters_,
const std::optional<std::string>& savestate_path_)
: parameters(std::move(parameters_)), savestate_path(savestate_path_)
{
}
std::unique_ptr<BootParameters>
BootParameters::GenerateFromFile(const std::string& path,
const std::optional<std::string>& savestate_path)
{
const bool is_drive = cdio_is_cdrom(path);
// Check if the file exist, we may have gotten it from a --elf command line
// that gave an incorrect file name
if (!is_drive && !File::Exists(path))
{
PanicAlertT("The specified file \"%s\" does not exist", path.c_str());
return {};
}
std::string extension;
SplitPath(path, nullptr, nullptr, &extension);
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
static const std::unordered_set<std::string> disc_image_extensions = {
{".gcm", ".iso", ".tgc", ".wbfs", ".ciso", ".gcz", ".dol", ".elf"}};
if (disc_image_extensions.find(extension) != disc_image_extensions.end() || is_drive)
{
std::unique_ptr<DiscIO::Volume> volume = DiscIO::CreateVolumeFromFilename(path);
if (volume)
return std::make_unique<BootParameters>(Disc{path, std::move(volume)}, savestate_path);
if (extension == ".elf")
{
return std::make_unique<BootParameters>(Executable{path, std::make_unique<ElfReader>(path)},
savestate_path);
}
if (extension == ".dol")
{
return std::make_unique<BootParameters>(Executable{path, std::make_unique<DolReader>(path)},
savestate_path);
}
if (is_drive)
{
PanicAlertT("Could not read \"%s\". "
"There is no disc in the drive or it is not a GameCube/Wii backup. "
"Please note that Dolphin cannot play games directly from the original "
"GameCube and Wii discs.",
path.c_str());
}
else
{
PanicAlertT("\"%s\" is an invalid GCM/ISO file, or is not a GC/Wii ISO.", path.c_str());
}
return {};
}
if (extension == ".dff")
return std::make_unique<BootParameters>(DFF{path}, savestate_path);
if (extension == ".wad")
return std::make_unique<BootParameters>(DiscIO::WiiWAD{path}, savestate_path);
PanicAlertT("Could not recognize file %s", path.c_str());
return {};
}
BootParameters::IPL::IPL(DiscIO::Region region_) : region(region_)
{
const std::string directory = SConfig::GetInstance().GetDirectoryForRegion(region);
path = SConfig::GetInstance().GetBootROMPath(directory);
}
BootParameters::IPL::IPL(DiscIO::Region region_, Disc&& disc_) : IPL(region_)
{
disc = std::move(disc_);
}
// Inserts a disc into the emulated disc drive and returns a pointer to it.
// The returned pointer must only be used while we are still booting,
// because DVDThread can do whatever it wants to the disc after that.
static const DiscIO::Volume* SetDisc(std::unique_ptr<DiscIO::Volume> volume)
{
const DiscIO::Volume* pointer = volume.get();
DVDInterface::SetDisc(std::move(volume));
return pointer;
}
bool CBoot::DVDRead(const DiscIO::Volume& volume, u64 dvd_offset, u32 output_address, u32 length,
const DiscIO::Partition& partition)
{
std::vector<u8> buffer(length);
if (!volume.Read(dvd_offset, length, buffer.data(), partition))
return false;
Memory::CopyToEmu(output_address, buffer.data(), length);
return true;
}
void CBoot::UpdateDebugger_MapLoaded()
{
Host_NotifyMapLoaded();
}
// Get map file paths for the active title.
bool CBoot::FindMapFile(std::string* existing_map_file, std::string* writable_map_file)
{
const std::string& game_id = SConfig::GetInstance().m_debugger_game_id;
if (writable_map_file)
*writable_map_file = File::GetUserPath(D_MAPS_IDX) + game_id + ".map";
bool found = false;
static const std::string maps_directories[] = {File::GetUserPath(D_MAPS_IDX),
File::GetSysDirectory() + MAPS_DIR DIR_SEP};
for (size_t i = 0; !found && i < ArraySize(maps_directories); ++i)
{
std::string path = maps_directories[i] + game_id + ".map";
if (File::Exists(path))
{
found = true;
if (existing_map_file)
*existing_map_file = path;
}
}
return found;
}
bool CBoot::LoadMapFromFilename()
{
std::string strMapFilename;
bool found = FindMapFile(&strMapFilename, nullptr);
if (found && g_symbolDB.LoadMap(strMapFilename))
{
UpdateDebugger_MapLoaded();
return true;
}
return false;
}
// If ipl.bin is not found, this function does *some* of what BS1 does:
// loading IPL(BS2) and jumping to it.
// It does not initialize the hardware or anything else like BS1 does.
bool CBoot::Load_BS2(const std::string& boot_rom_filename)
{
// CRC32 hashes of the IPL file; including source where known
// https://forums.dolphin-emu.org/Thread-unknown-hash-on-ipl-bin?pid=385344#pid385344
constexpr u32 USA_v1_0 = 0x6D740AE7;
// https://forums.dolphin-emu.org/Thread-unknown-hash-on-ipl-bin?pid=385334#pid385334
constexpr u32 USA_v1_1 = 0xD5E6FEEA;
// https://forums.dolphin-emu.org/Thread-unknown-hash-on-ipl-bin?pid=385399#pid385399
constexpr u32 USA_v1_2 = 0x86573808;
// GameCubes sold in Brazil have this IPL. Same as USA v1.2 but localized
constexpr u32 BRA_v1_0 = 0x667D0B64;
// Redump
constexpr u32 JAP_v1_0 = 0x6DAC1F2A;
// https://bugs.dolphin-emu.org/issues/8936
constexpr u32 JAP_v1_1 = 0xD235E3F9;
constexpr u32 JAP_v1_2 = 0x8BDABBD4;
// Redump
constexpr u32 PAL_v1_0 = 0x4F319F43;
// https://forums.dolphin-emu.org/Thread-ipl-with-unknown-hash-dd8cab7c-problem-caused-by-my-pal-gamecube-bios?pid=435463#pid435463
constexpr u32 PAL_v1_1 = 0xDD8CAB7C;
// Redump
constexpr u32 PAL_v1_2 = 0xAD1B7F16;
// Load the whole ROM dump
std::string data;
if (!File::ReadFileToString(boot_rom_filename, data))
return false;
// Use zlibs crc32 implementation to compute the hash
u32 ipl_hash = crc32(0L, Z_NULL, 0);
ipl_hash = crc32(ipl_hash, (const Bytef*)data.data(), (u32)data.size());
DiscIO::Region ipl_region;
switch (ipl_hash)
{
case USA_v1_0:
case USA_v1_1:
case USA_v1_2:
case BRA_v1_0:
ipl_region = DiscIO::Region::NTSC_U;
break;
case JAP_v1_0:
case JAP_v1_1:
case JAP_v1_2:
ipl_region = DiscIO::Region::NTSC_J;
break;
case PAL_v1_0:
case PAL_v1_1:
case PAL_v1_2:
ipl_region = DiscIO::Region::PAL;
break;
default:
PanicAlertT("IPL with unknown hash %x", ipl_hash);
ipl_region = DiscIO::Region::Unknown;
break;
}
const DiscIO::Region boot_region = SConfig::GetInstance().m_region;
if (ipl_region != DiscIO::Region::Unknown && boot_region != ipl_region)
PanicAlertT("%s IPL found in %s directory. The disc might not be recognized",
SConfig::GetDirectoryForRegion(ipl_region),
SConfig::GetDirectoryForRegion(boot_region));
// Run the descrambler over the encrypted section containing BS1/BS2
ExpansionInterface::CEXIIPL::Descrambler((u8*)data.data() + 0x100, 0x1AFE00);
// TODO: Execution is supposed to start at 0xFFF00000, not 0x81200000;
// copying the initial boot code to 0x81200000 is a hack.
// For now, HLE the first few instructions and start at 0x81200150
// to work around this.
Memory::CopyToEmu(0x01200000, data.data() + 0x100, 0x700);
Memory::CopyToEmu(0x01300000, data.data() + 0x820, 0x1AFE00);
PowerPC::ppcState.gpr[3] = 0xfff0001f;
PowerPC::ppcState.gpr[4] = 0x00002030;
PowerPC::ppcState.gpr[5] = 0x0000009c;
UReg_MSR& m_MSR = ((UReg_MSR&)PowerPC::ppcState.msr);
m_MSR.FP = 1;
m_MSR.DR = 1;
m_MSR.IR = 1;
PowerPC::ppcState.spr[SPR_HID0] = 0x0011c464;
PowerPC::ppcState.spr[SPR_IBAT3U] = 0xfff0001f;
PowerPC::ppcState.spr[SPR_IBAT3L] = 0xfff00001;
PowerPC::ppcState.spr[SPR_DBAT3U] = 0xfff0001f;
PowerPC::ppcState.spr[SPR_DBAT3L] = 0xfff00001;
SetupBAT(/*is_wii*/ false);
PC = 0x81200150;
return true;
}
static void SetDefaultDisc()
{
const SConfig& config = SConfig::GetInstance();
if (!config.m_strDefaultISO.empty())
SetDisc(DiscIO::CreateVolumeFromFilename(config.m_strDefaultISO));
}
static void CopyDefaultExceptionHandlers()
{
constexpr u32 EXCEPTION_HANDLER_ADDRESSES[] = {0x00000100, 0x00000200, 0x00000300, 0x00000400,
0x00000500, 0x00000600, 0x00000700, 0x00000800,
0x00000900, 0x00000C00, 0x00000D00, 0x00000F00,
0x00001300, 0x00001400, 0x00001700};
constexpr u32 RFI_INSTRUCTION = 0x4C000064;
for (const u32 address : EXCEPTION_HANDLER_ADDRESSES)
Memory::Write_U32(RFI_INSTRUCTION, address);
}
// Third boot step after BootManager and Core. See Call schedule in BootManager.cpp
bool CBoot::BootUp(std::unique_ptr<BootParameters> boot)
{
SConfig& config = SConfig::GetInstance();
g_symbolDB.Clear();
// PAL Wii uses NTSC framerate and linecount in 60Hz modes
VideoInterface::Preset(DiscIO::IsNTSC(config.m_region) ||
(config.bWii && Config::Get(Config::SYSCONF_PAL60)));
struct BootTitle
{
BootTitle() : config(SConfig::GetInstance()) {}
bool operator()(BootParameters::Disc& disc) const
{
NOTICE_LOG(BOOT, "Booting from disc: %s", disc.path.c_str());
const DiscIO::Volume* volume = SetDisc(std::move(disc.volume));
if (!volume)
return false;
if (!EmulatedBS2(config.bWii, *volume))
return false;
// Try to load the symbol map if there is one, and then scan it for
// and eventually replace code
if (LoadMapFromFilename())
HLE::PatchFunctions();
return true;
}
bool operator()(const BootParameters::Executable& executable) const
{
NOTICE_LOG(BOOT, "Booting from executable: %s", executable.path.c_str());
if (!executable.reader->IsValid())
return false;
if (!executable.reader->LoadIntoMemory())
{
PanicAlertT("Failed to load the executable to memory.");
return false;
}
SetDefaultDisc();
SetupMSR();
SetupBAT(config.bWii);
CopyDefaultExceptionHandlers();
if (config.bWii)
{
PowerPC::ppcState.spr[SPR_HID0] = 0x0011c464;
PowerPC::ppcState.spr[SPR_HID4] = 0x82000000;
// Set a value for the SP. It doesn't matter where this points to,
// as long as it is a valid location. This value is taken from a homebrew binary.
PowerPC::ppcState.gpr[1] = 0x8004d4bc;
// Because there is no TMD to get the requested system (IOS) version from,
// we default to IOS58, which is the version used by the Homebrew Channel.
SetupWiiMemory();
IOS::HLE::GetIOS()->BootIOS(Titles::IOS(58));
}
else
{
SetupGCMemory();
}
PC = executable.reader->GetEntryPoint();
if (executable.reader->LoadSymbols() || LoadMapFromFilename())
{
UpdateDebugger_MapLoaded();
HLE::PatchFunctions();
}
return true;
}
bool operator()(const DiscIO::WiiWAD& wad) const
{
SetDefaultDisc();
return Boot_WiiWAD(wad);
}
bool operator()(const BootParameters::NANDTitle& nand_title) const
{
SetDefaultDisc();
return BootNANDTitle(nand_title.id);
}
bool operator()(const BootParameters::IPL& ipl) const
{
NOTICE_LOG(BOOT, "Booting GC IPL: %s", ipl.path.c_str());
if (!File::Exists(ipl.path))
{
if (ipl.disc)
PanicAlertT("Cannot start the game, because the GC IPL could not be found.");
else
PanicAlertT("Cannot find the GC IPL.");
return false;
}
if (!Load_BS2(ipl.path))
return false;
if (ipl.disc)
{
NOTICE_LOG(BOOT, "Inserting disc: %s", ipl.disc->path.c_str());
SetDisc(DiscIO::CreateVolumeFromFilename(ipl.disc->path));
}
if (LoadMapFromFilename())
HLE::PatchFunctions();
return true;
}
bool operator()(const BootParameters::DFF& dff) const
{
NOTICE_LOG(BOOT, "Booting DFF: %s", dff.dff_path.c_str());
return FifoPlayer::GetInstance().Open(dff.dff_path);
}
private:
const SConfig& config;
};
if (!std::visit(BootTitle(), boot->parameters))
return false;
PatchEngine::LoadPatches();
HLE::PatchFixedFunctions();
return true;
}
BootExecutableReader::BootExecutableReader(const std::string& file_name)
: BootExecutableReader(File::IOFile{file_name, "rb"})
{
}
BootExecutableReader::BootExecutableReader(File::IOFile file)
{
file.Seek(0, SEEK_SET);
m_bytes.resize(file.GetSize());
file.ReadBytes(m_bytes.data(), m_bytes.size());
}
BootExecutableReader::BootExecutableReader(const std::vector<u8>& bytes) : m_bytes(bytes)
{
}
BootExecutableReader::~BootExecutableReader() = default;
void StateFlags::UpdateChecksum()
{
constexpr size_t length_in_bytes = sizeof(StateFlags) - 4;
constexpr size_t num_elements = length_in_bytes / sizeof(u32);
std::array<u32, num_elements> flag_data;
std::memcpy(flag_data.data(), &flags, length_in_bytes);
checksum = std::accumulate(flag_data.cbegin(), flag_data.cend(), 0U);
}
void UpdateStateFlags(std::function<void(StateFlags*)> update_function)
{
const std::string file_path =
Common::GetTitleDataPath(Titles::SYSTEM_MENU, Common::FROM_SESSION_ROOT) + WII_STATE;
File::IOFile file;
StateFlags state;
if (File::Exists(file_path))
{
file.Open(file_path, "r+b");
file.ReadBytes(&state, sizeof(state));
}
else
{
File::CreateFullPath(file_path);
file.Open(file_path, "a+b");
memset(&state, 0, sizeof(state));
}
update_function(&state);
state.UpdateChecksum();
file.Seek(0, SEEK_SET);
file.WriteBytes(&state, sizeof(state));
}
| SeannyM/dolphin | Source/Core/Core/Boot/Boot.cpp | C++ | gpl-2.0 | 15,252 |
package My::Suite::WSREP;
use File::Basename;
use My::Find;
@ISA = qw(My::Suite);
return "Not run for embedded server" if $::opt_embedded_server;
return "WSREP is not compiled in" unless defined $::mysqld_variables{'wsrep-on'};
my ($provider) = grep { -f $_ } $ENV{WSREP_PROVIDER},
"/usr/lib64/galera-3/libgalera_smm.so",
"/usr/lib64/galera/libgalera_smm.so",
"/usr/lib/galera-3/libgalera_smm.so",
"/usr/lib/galera/libgalera_smm.so";
return "No wsrep provider library" unless -f $provider;
$ENV{WSREP_PROVIDER} = $provider;
my ($spath) = grep { -f "$_/wsrep_sst_rsync"; } "$::bindir/scripts", $::path_client_bindir;
return "No SST scripts" unless $spath;
my ($epath) = grep { -f "$_/my_print_defaults"; } "$::bindir/extra", $::path_client_bindir;
return "No my_print_defaults" unless $epath;
push @::global_suppressions,
(
qr(WSREP: Could not open saved state file for reading: .*),
qr(WSREP: Could not open state file for reading: .*),
qr|WSREP: access file\(.*gvwstate.dat\) failed\(No such file or directory\)|,
);
$ENV{PATH}="$epath:$ENV{PATH}";
$ENV{PATH}="$spath:$ENV{PATH}" unless $epath eq $spath;
bless { };
| tempesta-tech/mariadb_10.2 | mysql-test/suite/wsrep/suite.pm | Perl | gpl-2.0 | 1,277 |
<?php
namespace TYPO3\CMS\Extbase\Persistence\Generic;
/**
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
/**
* The Query class used to run queries against the database
*
* @api
*/
class Query implements QueryInterface {
/**
* An inner join.
*/
const JCR_JOIN_TYPE_INNER = '{http://www.jcp.org/jcr/1.0}joinTypeInner';
/**
* A left-outer join.
*/
const JCR_JOIN_TYPE_LEFT_OUTER = '{http://www.jcp.org/jcr/1.0}joinTypeLeftOuter';
/**
* A right-outer join.
*/
const JCR_JOIN_TYPE_RIGHT_OUTER = '{http://www.jcp.org/jcr/1.0}joinTypeRightOuter';
/**
* Charset of strings in QOM
*/
const CHARSET = 'utf-8';
/**
* @var string
*/
protected $type;
/**
* @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
* @inject
*/
protected $objectManager;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
* @inject
*/
protected $dataMapper;
/**
* @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
* @inject
*/
protected $persistenceManager;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\QueryObjectModelFactory
* @inject
*/
protected $qomFactory;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface
*/
protected $source;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface
*/
protected $constraint;
/**
* @var \TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement
*/
protected $statement;
/**
* @var int
*/
protected $orderings = array();
/**
* @var int
*/
protected $limit;
/**
* @var int
*/
protected $offset;
/**
* The query settings.
*
* @var QuerySettingsInterface
*/
protected $querySettings;
/**
* Constructs a query object working on the given class name
*
* @param string $type
*/
public function __construct($type) {
$this->type = $type;
}
/**
* Sets the Query Settings. These Query settings must match the settings expected by
* the specific Storage Backend.
*
* @param QuerySettingsInterface $querySettings The Query Settings
* @return void
* @api This method is not part of FLOW3 API
*/
public function setQuerySettings(QuerySettingsInterface $querySettings) {
$this->querySettings = $querySettings;
}
/**
* Returns the Query Settings.
*
* @throws Exception
* @return QuerySettingsInterface $querySettings The Query Settings
* @api This method is not part of FLOW3 API
*/
public function getQuerySettings() {
if (!$this->querySettings instanceof QuerySettingsInterface) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception('Tried to get the query settings without seting them before.', 1248689115);
}
return $this->querySettings;
}
/**
* Returns the type this query cares for.
*
* @return string
* @api
*/
public function getType() {
return $this->type;
}
/**
* Sets the source to fetch the result from
*
* @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source
*/
public function setSource(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface $source) {
$this->source = $source;
}
/**
* Returns the selectorn name or an empty string, if the source is not a selector
* TODO This has to be checked at another place
*
* @return string The selector name
*/
protected function getSelectorName() {
$source = $this->getSource();
if ($source instanceof \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface) {
return $source->getSelectorName();
} else {
return '';
}
}
/**
* Gets the node-tuple source for this query.
*
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface the node-tuple source; non-null
*/
public function getSource() {
if ($this->source === NULL) {
$this->source = $this->qomFactory->selector($this->getType(), $this->dataMapper->convertClassNameToTableName($this->getType()));
}
return $this->source;
}
/**
* Executes the query against the database and returns the result
*
* @param $returnRawQueryResult boolean avoids the object mapping by the persistence
* @return \TYPO3\CMS\Extbase\Persistence\QueryResultInterface|array The query result object or an array if $returnRawQueryResult is TRUE
* @api
*/
public function execute($returnRawQueryResult = FALSE) {
if ($returnRawQueryResult === TRUE || $this->getQuerySettings()->getReturnRawQueryResult() === TRUE) {
return $this->persistenceManager->getObjectDataByQuery($this);
} else {
return $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\QueryResultInterface', $this);
}
}
/**
* Sets the property names to order the result by. Expected like this:
* array(
* 'foo' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
* 'bar' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
* )
* where 'foo' and 'bar' are property names.
*
* @param array $orderings The property names to order by
* @return QueryInterface
* @api
*/
public function setOrderings(array $orderings) {
$this->orderings = $orderings;
return $this;
}
/**
* Returns the property names to order the result by. Like this:
* array(
* 'foo' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING,
* 'bar' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING
* )
*
* @return array
* @api
*/
public function getOrderings() {
return $this->orderings;
}
/**
* Sets the maximum size of the result set to limit. Returns $this to allow
* for chaining (fluid interface)
*
* @param integer $limit
* @throws \InvalidArgumentException
* @return QueryInterface
* @api
*/
public function setLimit($limit) {
if (!is_int($limit) || $limit < 1) {
throw new \InvalidArgumentException('The limit must be an integer >= 1', 1245071870);
}
$this->limit = $limit;
return $this;
}
/**
* Resets a previously set maximum size of the result set. Returns $this to allow
* for chaining (fluid interface)
*
* @return QueryInterface
* @api
*/
public function unsetLimit() {
unset($this->limit);
return $this;
}
/**
* Returns the maximum size of the result set to limit.
*
* @return integer
* @api
*/
public function getLimit() {
return $this->limit;
}
/**
* Sets the start offset of the result set to offset. Returns $this to
* allow for chaining (fluid interface)
*
* @param integer $offset
* @throws \InvalidArgumentException
* @return QueryInterface
* @api
*/
public function setOffset($offset) {
if (!is_int($offset) || $offset < 0) {
throw new \InvalidArgumentException('The offset must be a positive integer', 1245071872);
}
$this->offset = $offset;
return $this;
}
/**
* Returns the start offset of the result set.
*
* @return integer
* @api
*/
public function getOffset() {
return $this->offset;
}
/**
* The constraint used to limit the result set. Returns $this to allow
* for chaining (fluid interface)
*
* @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint
* @return QueryInterface
* @api
*/
public function matching($constraint) {
$this->constraint = $constraint;
return $this;
}
/**
* Sets the statement of this query. If you use this, you will lose the abstraction from a concrete storage
* backend (database).
*
* @param string|\TYPO3\CMS\Core\Database\PreparedStatement $statement The statement
* @param array $parameters An array of parameters. These will be bound to placeholders '?' in the $statement.
* @return QueryInterface
*/
public function statement($statement, array $parameters = array()) {
$this->statement = $this->qomFactory->statement($statement, $parameters);
return $this;
}
/**
* Returns the statement of this query.
*
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\Statement
*/
public function getStatement() {
return $this->statement;
}
/**
* Gets the constraint for this query.
*
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface|NULL the constraint, or null if none
* @api
*/
public function getConstraint() {
return $this->constraint;
}
/**
* Performs a logical conjunction of the given constraints. The method takes one or more contraints and concatenates them with a boolean AND.
* It also scepts a single array of constraints to be concatenated.
*
* @param mixed $constraint1 The first of multiple constraints or an array of constraints.
* @throws Exception\InvalidNumberOfConstraintsException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface
* @api
*/
public function logicalAnd($constraint1) {
if (is_array($constraint1)) {
$resultingConstraint = array_shift($constraint1);
$constraints = $constraint1;
} else {
$constraints = func_get_args();
$resultingConstraint = array_shift($constraints);
}
if ($resultingConstraint === NULL) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidNumberOfConstraintsException('There must be at least one constraint or a non-empty array of constraints given.', 1268056288);
}
foreach ($constraints as $constraint) {
$resultingConstraint = $this->qomFactory->_and($resultingConstraint, $constraint);
}
return $resultingConstraint;
}
/**
* Performs a logical disjunction of the two given constraints
*
* @param mixed $constraint1 The first of multiple constraints or an array of constraints.
* @throws Exception\InvalidNumberOfConstraintsException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface
* @api
*/
public function logicalOr($constraint1) {
if (is_array($constraint1)) {
$resultingConstraint = array_shift($constraint1);
$constraints = $constraint1;
} else {
$constraints = func_get_args();
$resultingConstraint = array_shift($constraints);
}
if ($resultingConstraint === NULL) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidNumberOfConstraintsException('There must be at least one constraint or a non-empty array of constraints given.', 1268056289);
}
foreach ($constraints as $constraint) {
$resultingConstraint = $this->qomFactory->_or($resultingConstraint, $constraint);
}
return $resultingConstraint;
}
/**
* Performs a logical negation of the given constraint
*
* @param \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint Constraint to negate
* @throws \RuntimeException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface
* @api
*/
public function logicalNot(\TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface $constraint) {
return $this->qomFactory->not($constraint);
}
/**
* Returns an equals criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @param boolean $caseSensitive Whether the equality test should be done case-sensitive
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function equals($propertyName, $operand, $caseSensitive = TRUE) {
if (is_object($operand) || $caseSensitive) {
$comparison = $this->qomFactory->comparison(
$this->qomFactory->propertyValue($propertyName, $this->getSelectorName()),
QueryInterface::OPERATOR_EQUAL_TO,
$operand
);
} else {
$comparison = $this->qomFactory->comparison(
$this->qomFactory->lowerCase($this->qomFactory->propertyValue($propertyName, $this->getSelectorName())),
QueryInterface::OPERATOR_EQUAL_TO,
\TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Charset\\CharsetConverter')->conv_case(\TYPO3\CMS\Extbase\Persistence\Generic\Query::CHARSET, $operand, 'toLower')
);
}
return $comparison;
}
/**
* Returns a like criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @param boolean $caseSensitive Whether the matching should be done case-sensitive
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function like($propertyName, $operand, $caseSensitive = TRUE) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_LIKE, $operand);
}
/**
* Returns a "contains" criterion used for matching objects against a query.
* It matches if the multivalued property contains the given operand.
*
* @param string $propertyName The name of the (multivalued) property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function contains($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_CONTAINS, $operand);
}
/**
* Returns an "in" criterion used for matching objects against a query. It
* matches if the property's value is contained in the multivalued operand.
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with, multivalued
* @throws Exception\UnexpectedTypeException
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function in($propertyName, $operand) {
if (!is_array($operand) && !$operand instanceof \ArrayAccess && !$operand instanceof \Traversable) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnexpectedTypeException('The "in" operator must be given a multivalued operand (array, ArrayAccess, Traversable).', 1264678095);
}
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_IN, $operand);
}
/**
* Returns a less than criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function lessThan($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_LESS_THAN, $operand);
}
/**
* Returns a less or equal than criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function lessThanOrEqual($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO, $operand);
}
/**
* Returns a greater than criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function greaterThan($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_GREATER_THAN, $operand);
}
/**
* Returns a greater than or equal criterion used for matching objects against a query
*
* @param string $propertyName The name of the property to compare against
* @param mixed $operand The value to compare with
* @return \TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface
* @api
*/
public function greaterThanOrEqual($propertyName, $operand) {
return $this->qomFactory->comparison($this->qomFactory->propertyValue($propertyName, $this->getSelectorName()), QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO, $operand);
}
/**
* @return void
*/
public function __wakeup() {
$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$this->persistenceManager = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\PersistenceManagerInterface');
$this->dataMapper = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Mapper\\DataMapper');
$this->qomFactory = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Qom\\QueryObjectModelFactory');
}
/**
* @return array
*/
public function __sleep() {
return array('type', 'source', 'constraint', 'statement', 'orderings', 'limit', 'offset', 'querySettings');
}
/**
* Returns the query result count.
*
* @return integer The query result count
* @api
*/
public function count() {
return $this->execute()->count();
}
/**
* Returns an "isEmpty" criterion used for matching objects against a query.
* It matches if the multivalued property contains no values or is NULL.
*
* @param string $propertyName The name of the multivalued property to compare against
* @throws \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException
* @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException if used on a single-valued property
* @return bool
* @api
*/
public function isEmpty($propertyName) {
throw new \TYPO3\CMS\Extbase\Persistence\Generic\Exception\NotImplementedException(__METHOD__);
}
}
| federicobernardin/labs | typo3/sysext/extbase/Classes/Persistence/Generic/Query.php | PHP | gpl-2.0 | 18,075 |
#!/bin/sh
set -e
$GREP_DCTRL -I -sPackage '' 0001.out
| ip1981/dctrl-tools | tests/bug144174.sh | Shell | gpl-2.0 | 56 |
file(REMOVE_RECURSE
"CMakeFiles/ortp.dir/avprofile.c.o"
"CMakeFiles/ortp.dir/b64.c.o"
"CMakeFiles/ortp.dir/event.c.o"
"CMakeFiles/ortp.dir/extremum.c.o"
"CMakeFiles/ortp.dir/jitterctl.c.o"
"CMakeFiles/ortp.dir/logging.c.o"
"CMakeFiles/ortp.dir/netsim.c.o"
"CMakeFiles/ortp.dir/ortp.c.o"
"CMakeFiles/ortp.dir/payloadtype.c.o"
"CMakeFiles/ortp.dir/port.c.o"
"CMakeFiles/ortp.dir/posixtimer.c.o"
"CMakeFiles/ortp.dir/rtcp.c.o"
"CMakeFiles/ortp.dir/rtcp_fb.c.o"
"CMakeFiles/ortp.dir/rtcp_xr.c.o"
"CMakeFiles/ortp.dir/rtcpparse.c.o"
"CMakeFiles/ortp.dir/rtpparse.c.o"
"CMakeFiles/ortp.dir/rtpprofile.c.o"
"CMakeFiles/ortp.dir/rtpsession.c.o"
"CMakeFiles/ortp.dir/rtpsession_inet.c.o"
"CMakeFiles/ortp.dir/rtpsignaltable.c.o"
"CMakeFiles/ortp.dir/rtptimer.c.o"
"CMakeFiles/ortp.dir/scheduler.c.o"
"CMakeFiles/ortp.dir/sessionset.c.o"
"CMakeFiles/ortp.dir/str_utils.c.o"
"CMakeFiles/ortp.dir/telephonyevents.c.o"
"CMakeFiles/ortp.dir/utils.c.o"
"libortp.pdb"
"libortp.a"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/ortp.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
| husseinalzand/linphone | WORK/ios-x86_64/Build/ortp/src/CMakeFiles/ortp.dir/cmake_clean.cmake | CMake | gpl-2.0 | 1,171 |
<?php
/**
* @version 1.0.0
* @package com_oauth
* @copyright Copyright (C) 2011 - 2013 Slashes & Dots Sdn Bhd. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Offiria Team
*/
// No direct access
defined('_JEXEC') or die;
/**
* HTML View class for the Oauth component
*/
class OauthViewOauth extends OauthView
{
/**
* The purpose of this view is to retrieve the token generated for the app
* Process flow:
* 1) Navigate to index.php/component/oauth/?view=oauth&task=authenticate&appId=[appId]
* 2) Get the device approved
* 3) Run in the background to retrieve the token generated in this view
*/
public function display() {
$model = OauthFactory::getModel('application');
$token = $model->getAppToken(JRequest::getVar('appId'));
// make sure only the token belongs to the user will be generate
if ($model->isAppBelongToUser(JRequest::getVar('appId'))) {
$vals['token'] = $token;
echo json_encode($vals);
}
exit;
}
} | epireve/bib | components/com_oauth/views/oauth/view.json.php | PHP | gpl-2.0 | 1,035 |
<?php
/**
* @version $Id: controller.php 14401 2010-01-26 14:10:00Z louis $
* @package Joomla
* @subpackage Content
* @copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant to the
* GNU General Public License, and as distributed it includes or is derivative
* of works licensed under the GNU General Public License or other free or open
* source software licenses. See COPYRIGHT.php for copyright notices and
* details.
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );
jimport('joomla.application.component.controller');
/**
* Content Component Controller
*
* @package Joomla
* @subpackage Content
* @since 1.5
*/
class ContentController extends JController
{
/**
* Method to show an article as the main page display
*
* @access public
* @since 1.5
*/
function display()
{
JHTML::_('behavior.caption');
// Set a default view if none exists
if ( ! JRequest::getCmd( 'view' ) ) {
$default = JRequest::getInt('id') ? 'article' : 'frontpage';
JRequest::setVar('view', $default );
}
// View caching logic -- simple... are we logged in?
$user = &JFactory::getUser();
$view = JRequest::getVar('view');
$viewcache = JRequest::getVar('viewcache',1,'POST','INT');
if ($user->get('id') ||
($view == 'category' && JRequest::getVar('layout') != 'blog' && $viewcache == 0) ||
$view == 'archive' && $viewcache == 0) {
parent::display(false);
} else {
parent::display(true);
}
}
/**
* Edits an article
*
* @access public
* @since 1.5
*/
function edit()
{
$user =& JFactory::getUser();
// Create a user access object for the user
$access = new stdClass();
$access->canEdit = $user->authorize('com_content', 'edit', 'content', 'all');
$access->canEditOwn = $user->authorize('com_content', 'edit', 'content', 'own');
$access->canPublish = $user->authorize('com_content', 'publish', 'content', 'all');
// Create the view
$view = & $this->getView('article', 'html');
// Get/Create the model
$model = & $this->getModel('Article');
// new record
if (!($access->canEdit || $access->canEditOwn)) {
JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
}
if( $model->get('id') > 1 && $user->get('gid') <= 19 && $model->get('created_by') != $user->id ) {
JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
}
if ( $model->isCheckedOut($user->get('id')))
{
$msg = JText::sprintf('DESCBEINGEDITTED', JText::_('The item'), $model->get('title'));
$this->setRedirect(JRoute::_('index.php?view=article&id='.$model->get('id'), false), $msg);
return;
}
//Checkout the article
$model->checkout();
// Push the model into the view (as default)
$view->setModel($model, true);
// Set the layout
$view->setLayout('form');
// Display the view
$view->display();
}
/**
* Saves the content item an edit form submit
*
* @todo
*/
function save()
{
// Check for request forgeries
JRequest::checkToken() or jexit( 'Invalid Token' );
// Initialize variables
$db = & JFactory::getDBO();
$user = & JFactory::getUser();
$task = JRequest::getVar('task', null, 'default', 'cmd');
// Make sure you are logged in and have the necessary access rights
if ($user->get('gid') < 19) {
JError::raiseError( 403, JText::_('ALERTNOTAUTH') );
return;
}
// Create a user access object for the user
$access = new stdClass();
$access->canEdit = $user->authorize('com_content', 'edit', 'content', 'all');
$access->canEditOwn = $user->authorize('com_content', 'edit', 'content', 'own');
$access->canPublish = $user->authorize('com_content', 'publish', 'content', 'all');
if (!($access->canEdit || $access->canEditOwn)) {
JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
}
//get data from the request
$model = $this->getModel('article');
//get data from request
$post = JRequest::get('post');
$post['text'] = JRequest::getVar('text', '', 'post', 'string', JREQUEST_ALLOWRAW);
//preform access checks
$isNew = ((int) $post['id'] < 1);
if ($model->store($post)) {
$msg = JText::_( 'Article Saved' );
if($isNew) {
$post['id'] = (int) $model->get('id');
}
} else {
$msg = JText::_( 'Error Saving Article' );
JError::raiseError( 500, $model->getError() );
}
// manage frontpage items
//TODO : Move this into a frontpage model
require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_frontpage'.DS.'tables'.DS.'frontpage.php');
$fp = new TableFrontPage($db);
if (JRequest::getVar('frontpage', false, '', 'boolean'))
{
// toggles go to first place
if (!$fp->load($post['id']))
{
// new entry
$query = 'INSERT INTO #__content_frontpage' .
' VALUES ( '.(int) $post['id'].', 1 )';
$db->setQuery($query);
if (!$db->query()) {
JError::raiseError( 500, $db->stderr());
}
$fp->ordering = 1;
}
}
else
{
// no frontpage mask
if (!$fp->delete($post['id'])) {
$msg .= $fp->stderr();
}
$fp->ordering = 0;
}
$fp->reorder();
$model->checkin();
// gets section name of item
$query = 'SELECT s.title' .
' FROM #__sections AS s' .
' WHERE s.scope = "content"' .
' AND s.id = ' . (int) $post['sectionid'];
$db->setQuery($query);
// gets category name of item
$section = $db->loadResult();
$query = 'SELECT c.title' .
' FROM #__categories AS c' .
' WHERE c.id = ' . (int) $post['catid'];
$db->setQuery($query);
$category = $db->loadResult();
if ($isNew)
{
// messaging for new items
require_once (JPATH_ADMINISTRATOR.DS.'components'.DS.'com_messages'.DS.'tables'.DS.'message.php');
// load language for messaging
$lang =& JFactory::getLanguage();
$lang->load('com_messages');
$query = 'SELECT id' .
' FROM #__users' .
' WHERE sendEmail = 1';
$db->setQuery($query);
$users = $db->loadResultArray();
foreach ($users as $user_id)
{
$msg = new TableMessage($db);
$msg->send($user->get('id'), $user_id, JText::_('New Item'), JText::sprintf('ON_NEW_CONTENT', $user->get('username'), $post['title'], $section, $category));
}
} else {
// If the article isn't new, then we need to clean the cache so that our changes appear realtime :)
$cache = &JFactory::getCache('com_content');
$cache->clean();
}
if ($access->canPublish)
{
// Publishers, admins, etc just get the stock msg
$msg = JText::_('Item successfully saved.');
}
else
{
$msg = $isNew ? JText::_('THANK_SUB') : JText::_('Item successfully saved.');
}
$referer = JRequest::getString('ret', base64_encode(JURI::base()), 'get');
$referer = base64_decode($referer);
if (!JURI::isInternal($referer)) {
$referer = '';
}
$this->setRedirect($referer, $msg);
}
/**
* Cancels an edit article operation
*
* @access public
* @since 1.5
*/
function cancel()
{
// Initialize some variables
$db = & JFactory::getDBO();
$user = & JFactory::getUser();
// Get an article table object and bind post variabes to it [We don't need a full model here]
$article = & JTable::getInstance('content');
$article->bind(JRequest::get('post'));
if ($user->authorize('com_content', 'edit', 'content', 'all') || ($user->authorize('com_content', 'edit', 'content', 'own') && $article->created_by == $user->get('id'))) {
$article->checkin();
}
// If the task was edit or cancel, we go back to the content item
$referer = JRequest::getString('ret', base64_encode(JURI::base()), 'get');
$referer = base64_decode($referer);
if (!JURI::isInternal($referer)) {
$referer = '';
}
$this->setRedirect($referer);
}
/**
* Rates an article
*
* @access public
* @since 1.5
*/
function vote()
{
$url = JRequest::getVar('url', '', 'default', 'string');
$rating = JRequest::getVar('user_rating', 0, '', 'int');
$id = JRequest::getVar('cid', 0, '', 'int');
// Get/Create the model
$model = & $this->getModel('Article' );
$model->setId($id);
if(!JURI::isInternal($url)) {
$url = JRoute::_('index.php?option=com_content&view=article&id='.$id);
}
if ($model->storeVote($rating)) {
$this->setRedirect($url, JText::_('Thanks for rating!'));
} else {
$this->setRedirect($url, JText::_('You already rated this article today!'));
}
}
/**
* Searches for an item by a key parameter
*
* @access public
* @since 1.5
*/
function findkey()
{
// Initialize variables
$db = & JFactory::getDBO();
$keyref = JRequest::getVar('keyref', null, 'default', 'cmd');
JRequest::setVar('keyref', $keyref);
// If no keyref left, throw 404
if( empty($keyref) === true ) {
JError::raiseError( 404, JText::_("Key Not Found") );
}
$keyref = $db->Quote( '%keyref='.$db->getEscaped( $keyref, true ).'%', false );
$query = 'SELECT id' .
' FROM #__content' .
' WHERE attribs LIKE '.$keyref;
$db->setQuery($query);
$id = (int) $db->loadResult();
if ($id > 0)
{
// Create the view
$view =& $this->getView('article', 'html');
// Get/Create the model
$model =& $this->getModel('Article' );
// Set the id of the article to display
$model->setId($id);
// Push the model into the view (as default)
$view->setModel($model, true);
// Display the view
$view->display();
}
else {
JError::raiseError( 404, JText::_( 'Key Not Found' ) );
}
}
/**
* Output the pagebreak dialog
*
* @access public
* @since 1.5
*/
function ins_pagebreak()
{
// Create the view
$view = & $this->getView('article', 'html');
// Set the layout
$view->setLayout('pagebreak');
// Display the view
$view->display();
}
}
| rbartolomeirb/joomlaatirb | components/com_content/controller.php | PHP | gpl-2.0 | 9,797 |
/*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* 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.
*
*/
#include "precompiled.hpp"
#include "ci/bcEscapeAnalyzer.hpp"
#include "compiler/oopMap.hpp"
#include "opto/callGenerator.hpp"
#include "opto/callnode.hpp"
#include "opto/escape.hpp"
#include "opto/locknode.hpp"
#include "opto/machnode.hpp"
#include "opto/matcher.hpp"
#include "opto/parse.hpp"
#include "opto/regalloc.hpp"
#include "opto/regmask.hpp"
#include "opto/rootnode.hpp"
#include "opto/runtime.hpp"
// Portions of code courtesy of Clifford Click
// Optimization - Graph Style
//=============================================================================
uint StartNode::size_of() const { return sizeof(*this); }
uint StartNode::cmp( const Node &n ) const
{ return _domain == ((StartNode&)n)._domain; }
const Type *StartNode::bottom_type() const { return _domain; }
const Type *StartNode::Value(PhaseTransform *phase) const { return _domain; }
#ifndef PRODUCT
void StartNode::dump_spec(outputStream *st) const { st->print(" #"); _domain->dump_on(st);}
#endif
//------------------------------Ideal------------------------------------------
Node *StartNode::Ideal(PhaseGVN *phase, bool can_reshape){
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
//------------------------------calling_convention-----------------------------
void StartNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
Matcher::calling_convention( sig_bt, parm_regs, argcnt, false );
}
//------------------------------Registers--------------------------------------
const RegMask &StartNode::in_RegMask(uint) const {
return RegMask::Empty;
}
//------------------------------match------------------------------------------
// Construct projections for incoming parameters, and their RegMask info
Node *StartNode::match( const ProjNode *proj, const Matcher *match ) {
switch (proj->_con) {
case TypeFunc::Control:
case TypeFunc::I_O:
case TypeFunc::Memory:
return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
case TypeFunc::FramePtr:
return new (match->C) MachProjNode(this,proj->_con,Matcher::c_frame_ptr_mask, Op_RegP);
case TypeFunc::ReturnAdr:
return new (match->C) MachProjNode(this,proj->_con,match->_return_addr_mask,Op_RegP);
case TypeFunc::Parms:
default: {
uint parm_num = proj->_con - TypeFunc::Parms;
const Type *t = _domain->field_at(proj->_con);
if (t->base() == Type::Half) // 2nd half of Longs and Doubles
return new (match->C) ConNode(Type::TOP);
uint ideal_reg = t->ideal_reg();
RegMask &rm = match->_calling_convention_mask[parm_num];
return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);
}
}
return NULL;
}
//------------------------------StartOSRNode----------------------------------
// The method start node for an on stack replacement adapter
//------------------------------osr_domain-----------------------------
const TypeTuple *StartOSRNode::osr_domain() {
const Type **fields = TypeTuple::fields(2);
fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM; // address of osr buffer
return TypeTuple::make(TypeFunc::Parms+1, fields);
}
//=============================================================================
const char * const ParmNode::names[TypeFunc::Parms+1] = {
"Control", "I_O", "Memory", "FramePtr", "ReturnAdr", "Parms"
};
#ifndef PRODUCT
void ParmNode::dump_spec(outputStream *st) const {
if( _con < TypeFunc::Parms ) {
st->print("%s", names[_con]);
} else {
st->print("Parm%d: ",_con-TypeFunc::Parms);
// Verbose and WizardMode dump bottom_type for all nodes
if( !Verbose && !WizardMode ) bottom_type()->dump_on(st);
}
}
#endif
uint ParmNode::ideal_reg() const {
switch( _con ) {
case TypeFunc::Control : // fall through
case TypeFunc::I_O : // fall through
case TypeFunc::Memory : return 0;
case TypeFunc::FramePtr : // fall through
case TypeFunc::ReturnAdr: return Op_RegP;
default : assert( _con > TypeFunc::Parms, "" );
// fall through
case TypeFunc::Parms : {
// Type of argument being passed
const Type *t = in(0)->as_Start()->_domain->field_at(_con);
return t->ideal_reg();
}
}
ShouldNotReachHere();
return 0;
}
//=============================================================================
ReturnNode::ReturnNode(uint edges, Node *cntrl, Node *i_o, Node *memory, Node *frameptr, Node *retadr ) : Node(edges) {
init_req(TypeFunc::Control,cntrl);
init_req(TypeFunc::I_O,i_o);
init_req(TypeFunc::Memory,memory);
init_req(TypeFunc::FramePtr,frameptr);
init_req(TypeFunc::ReturnAdr,retadr);
}
Node *ReturnNode::Ideal(PhaseGVN *phase, bool can_reshape){
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
const Type *ReturnNode::Value( PhaseTransform *phase ) const {
return ( phase->type(in(TypeFunc::Control)) == Type::TOP)
? Type::TOP
: Type::BOTTOM;
}
// Do we Match on this edge index or not? No edges on return nodes
uint ReturnNode::match_edge(uint idx) const {
return 0;
}
#ifndef PRODUCT
void ReturnNode::dump_req(outputStream *st) const {
// Dump the required inputs, enclosed in '(' and ')'
uint i; // Exit value of loop
for (i = 0; i < req(); i++) { // For all required inputs
if (i == TypeFunc::Parms) st->print("returns");
if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
else st->print("_ ");
}
}
#endif
//=============================================================================
RethrowNode::RethrowNode(
Node* cntrl,
Node* i_o,
Node* memory,
Node* frameptr,
Node* ret_adr,
Node* exception
) : Node(TypeFunc::Parms + 1) {
init_req(TypeFunc::Control , cntrl );
init_req(TypeFunc::I_O , i_o );
init_req(TypeFunc::Memory , memory );
init_req(TypeFunc::FramePtr , frameptr );
init_req(TypeFunc::ReturnAdr, ret_adr);
init_req(TypeFunc::Parms , exception);
}
Node *RethrowNode::Ideal(PhaseGVN *phase, bool can_reshape){
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
const Type *RethrowNode::Value( PhaseTransform *phase ) const {
return (phase->type(in(TypeFunc::Control)) == Type::TOP)
? Type::TOP
: Type::BOTTOM;
}
uint RethrowNode::match_edge(uint idx) const {
return 0;
}
#ifndef PRODUCT
void RethrowNode::dump_req(outputStream *st) const {
// Dump the required inputs, enclosed in '(' and ')'
uint i; // Exit value of loop
for (i = 0; i < req(); i++) { // For all required inputs
if (i == TypeFunc::Parms) st->print("exception");
if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
else st->print("_ ");
}
}
#endif
//=============================================================================
// Do we Match on this edge index or not? Match only target address & method
uint TailCallNode::match_edge(uint idx) const {
return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;
}
//=============================================================================
// Do we Match on this edge index or not? Match only target address & oop
uint TailJumpNode::match_edge(uint idx) const {
return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;
}
//=============================================================================
JVMState::JVMState(ciMethod* method, JVMState* caller) :
_method(method) {
assert(method != NULL, "must be valid call site");
_reexecute = Reexecute_Undefined;
debug_only(_bci = -99); // random garbage value
debug_only(_map = (SafePointNode*)-1);
_caller = caller;
_depth = 1 + (caller == NULL ? 0 : caller->depth());
_locoff = TypeFunc::Parms;
_stkoff = _locoff + _method->max_locals();
_monoff = _stkoff + _method->max_stack();
_scloff = _monoff;
_endoff = _monoff;
_sp = 0;
}
JVMState::JVMState(int stack_size) :
_method(NULL) {
_bci = InvocationEntryBci;
_reexecute = Reexecute_Undefined;
debug_only(_map = (SafePointNode*)-1);
_caller = NULL;
_depth = 1;
_locoff = TypeFunc::Parms;
_stkoff = _locoff;
_monoff = _stkoff + stack_size;
_scloff = _monoff;
_endoff = _monoff;
_sp = 0;
}
//--------------------------------of_depth-------------------------------------
JVMState* JVMState::of_depth(int d) const {
const JVMState* jvmp = this;
assert(0 < d && (uint)d <= depth(), "oob");
for (int skip = depth() - d; skip > 0; skip--) {
jvmp = jvmp->caller();
}
assert(jvmp->depth() == (uint)d, "found the right one");
return (JVMState*)jvmp;
}
//-----------------------------same_calls_as-----------------------------------
bool JVMState::same_calls_as(const JVMState* that) const {
if (this == that) return true;
if (this->depth() != that->depth()) return false;
const JVMState* p = this;
const JVMState* q = that;
for (;;) {
if (p->_method != q->_method) return false;
if (p->_method == NULL) return true; // bci is irrelevant
if (p->_bci != q->_bci) return false;
if (p->_reexecute != q->_reexecute) return false;
p = p->caller();
q = q->caller();
if (p == q) return true;
assert(p != NULL && q != NULL, "depth check ensures we don't run off end");
}
}
//------------------------------debug_start------------------------------------
uint JVMState::debug_start() const {
debug_only(JVMState* jvmroot = of_depth(1));
assert(jvmroot->locoff() <= this->locoff(), "youngest JVMState must be last");
return of_depth(1)->locoff();
}
//-------------------------------debug_end-------------------------------------
uint JVMState::debug_end() const {
debug_only(JVMState* jvmroot = of_depth(1));
assert(jvmroot->endoff() <= this->endoff(), "youngest JVMState must be last");
return endoff();
}
//------------------------------debug_depth------------------------------------
uint JVMState::debug_depth() const {
uint total = 0;
for (const JVMState* jvmp = this; jvmp != NULL; jvmp = jvmp->caller()) {
total += jvmp->debug_size();
}
return total;
}
#ifndef PRODUCT
//------------------------------format_helper----------------------------------
// Given an allocation (a Chaitin object) and a Node decide if the Node carries
// any defined value or not. If it does, print out the register or constant.
static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i, GrowableArray<SafePointScalarObjectNode*> *scobjs ) {
if (n == NULL) { st->print(" NULL"); return; }
if (n->is_SafePointScalarObject()) {
// Scalar replacement.
SafePointScalarObjectNode* spobj = n->as_SafePointScalarObject();
scobjs->append_if_missing(spobj);
int sco_n = scobjs->find(spobj);
assert(sco_n >= 0, "");
st->print(" %s%d]=#ScObj" INT32_FORMAT, msg, i, sco_n);
return;
}
if (regalloc->node_regs_max_index() > 0 &&
OptoReg::is_valid(regalloc->get_reg_first(n))) { // Check for undefined
char buf[50];
regalloc->dump_register(n,buf);
st->print(" %s%d]=%s",msg,i,buf);
} else { // No register, but might be constant
const Type *t = n->bottom_type();
switch (t->base()) {
case Type::Int:
st->print(" %s%d]=#"INT32_FORMAT,msg,i,t->is_int()->get_con());
break;
case Type::AnyPtr:
assert( t == TypePtr::NULL_PTR || n->in_dump(), "" );
st->print(" %s%d]=#NULL",msg,i);
break;
case Type::AryPtr:
case Type::InstPtr:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->isa_oopptr()->const_oop()));
break;
case Type::KlassPtr:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_klassptr()->klass()));
break;
case Type::MetadataPtr:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_metadataptr()->metadata()));
break;
case Type::NarrowOop:
st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_oopptr()->const_oop()));
break;
case Type::RawPtr:
st->print(" %s%d]=#Raw" INTPTR_FORMAT,msg,i,p2i(t->is_rawptr()));
break;
case Type::DoubleCon:
st->print(" %s%d]=#%fD",msg,i,t->is_double_constant()->_d);
break;
case Type::FloatCon:
st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f);
break;
case Type::Long:
st->print(" %s%d]=#"INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));
break;
case Type::Half:
case Type::Top:
st->print(" %s%d]=_",msg,i);
break;
default: ShouldNotReachHere();
}
}
}
//------------------------------format-----------------------------------------
void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) const {
st->print(" #");
if (_method) {
_method->print_short_name(st);
st->print(" @ bci:%d ",_bci);
} else {
st->print_cr(" runtime stub ");
return;
}
if (n->is_MachSafePoint()) {
GrowableArray<SafePointScalarObjectNode*> scobjs;
MachSafePointNode *mcall = n->as_MachSafePoint();
uint i;
// Print locals
for (i = 0; i < (uint)loc_size(); i++)
format_helper(regalloc, st, mcall->local(this, i), "L[", i, &scobjs);
// Print stack
for (i = 0; i < (uint)stk_size(); i++) {
if ((uint)(_stkoff + i) >= mcall->len())
st->print(" oob ");
else
format_helper(regalloc, st, mcall->stack(this, i), "STK[", i, &scobjs);
}
for (i = 0; (int)i < nof_monitors(); i++) {
Node *box = mcall->monitor_box(this, i);
Node *obj = mcall->monitor_obj(this, i);
if (regalloc->node_regs_max_index() > 0 &&
OptoReg::is_valid(regalloc->get_reg_first(box))) {
box = BoxLockNode::box_node(box);
format_helper(regalloc, st, box, "MON-BOX[", i, &scobjs);
} else {
OptoReg::Name box_reg = BoxLockNode::reg(box);
st->print(" MON-BOX%d=%s+%d",
i,
OptoReg::regname(OptoReg::c_frame_pointer),
regalloc->reg2offset(box_reg));
}
const char* obj_msg = "MON-OBJ[";
if (EliminateLocks) {
if (BoxLockNode::box_node(box)->is_eliminated())
obj_msg = "MON-OBJ(LOCK ELIMINATED)[";
}
format_helper(regalloc, st, obj, obj_msg, i, &scobjs);
}
for (i = 0; i < (uint)scobjs.length(); i++) {
// Scalar replaced objects.
st->cr();
st->print(" # ScObj" INT32_FORMAT " ", i);
SafePointScalarObjectNode* spobj = scobjs.at(i);
ciKlass* cik = spobj->bottom_type()->is_oopptr()->klass();
assert(cik->is_instance_klass() ||
cik->is_array_klass(), "Not supported allocation.");
ciInstanceKlass *iklass = NULL;
if (cik->is_instance_klass()) {
cik->print_name_on(st);
iklass = cik->as_instance_klass();
} else if (cik->is_type_array_klass()) {
cik->as_array_klass()->base_element_type()->print_name_on(st);
st->print("[%d]", spobj->n_fields());
} else if (cik->is_obj_array_klass()) {
ciKlass* cie = cik->as_obj_array_klass()->base_element_klass();
if (cie->is_instance_klass()) {
cie->print_name_on(st);
} else if (cie->is_type_array_klass()) {
cie->as_array_klass()->base_element_type()->print_name_on(st);
} else {
ShouldNotReachHere();
}
st->print("[%d]", spobj->n_fields());
int ndim = cik->as_array_klass()->dimension() - 1;
while (ndim-- > 0) {
st->print("[]");
}
}
st->print("={");
uint nf = spobj->n_fields();
if (nf > 0) {
uint first_ind = spobj->first_index(mcall->jvms());
Node* fld_node = mcall->in(first_ind);
ciField* cifield;
if (iklass != NULL) {
st->print(" [");
cifield = iklass->nonstatic_field_at(0);
cifield->print_name_on(st);
format_helper(regalloc, st, fld_node, ":", 0, &scobjs);
} else {
format_helper(regalloc, st, fld_node, "[", 0, &scobjs);
}
for (uint j = 1; j < nf; j++) {
fld_node = mcall->in(first_ind+j);
if (iklass != NULL) {
st->print(", [");
cifield = iklass->nonstatic_field_at(j);
cifield->print_name_on(st);
format_helper(regalloc, st, fld_node, ":", j, &scobjs);
} else {
format_helper(regalloc, st, fld_node, ", [", j, &scobjs);
}
}
}
st->print(" }");
}
}
st->cr();
if (caller() != NULL) caller()->format(regalloc, n, st);
}
void JVMState::dump_spec(outputStream *st) const {
if (_method != NULL) {
bool printed = false;
if (!Verbose) {
// The JVMS dumps make really, really long lines.
// Take out the most boring parts, which are the package prefixes.
char buf[500];
stringStream namest(buf, sizeof(buf));
_method->print_short_name(&namest);
if (namest.count() < sizeof(buf)) {
const char* name = namest.base();
if (name[0] == ' ') ++name;
const char* endcn = strchr(name, ':'); // end of class name
if (endcn == NULL) endcn = strchr(name, '(');
if (endcn == NULL) endcn = name + strlen(name);
while (endcn > name && endcn[-1] != '.' && endcn[-1] != '/')
--endcn;
st->print(" %s", endcn);
printed = true;
}
}
if (!printed)
_method->print_short_name(st);
st->print(" @ bci:%d",_bci);
if(_reexecute == Reexecute_True)
st->print(" reexecute");
} else {
st->print(" runtime stub");
}
if (caller() != NULL) caller()->dump_spec(st);
}
void JVMState::dump_on(outputStream* st) const {
bool print_map = _map && !((uintptr_t)_map & 1) &&
((caller() == NULL) || (caller()->map() != _map));
if (print_map) {
if (_map->len() > _map->req()) { // _map->has_exceptions()
Node* ex = _map->in(_map->req()); // _map->next_exception()
// skip the first one; it's already being printed
while (ex != NULL && ex->len() > ex->req()) {
ex = ex->in(ex->req()); // ex->next_exception()
ex->dump(1);
}
}
_map->dump(Verbose ? 2 : 1);
}
if (caller() != NULL) {
caller()->dump_on(st);
}
st->print("JVMS depth=%d loc=%d stk=%d arg=%d mon=%d scalar=%d end=%d mondepth=%d sp=%d bci=%d reexecute=%s method=",
depth(), locoff(), stkoff(), argoff(), monoff(), scloff(), endoff(), monitor_depth(), sp(), bci(), should_reexecute()?"true":"false");
if (_method == NULL) {
st->print_cr("(none)");
} else {
_method->print_name(st);
st->cr();
if (bci() >= 0 && bci() < _method->code_size()) {
st->print(" bc: ");
_method->print_codes_on(bci(), bci()+1, st);
}
}
}
// Extra way to dump a jvms from the debugger,
// to avoid a bug with C++ member function calls.
void dump_jvms(JVMState* jvms) {
jvms->dump();
}
#endif
//--------------------------clone_shallow--------------------------------------
JVMState* JVMState::clone_shallow(Compile* C) const {
JVMState* n = has_method() ? new (C) JVMState(_method, _caller) : new (C) JVMState(0);
n->set_bci(_bci);
n->_reexecute = _reexecute;
n->set_locoff(_locoff);
n->set_stkoff(_stkoff);
n->set_monoff(_monoff);
n->set_scloff(_scloff);
n->set_endoff(_endoff);
n->set_sp(_sp);
n->set_map(_map);
return n;
}
//---------------------------clone_deep----------------------------------------
JVMState* JVMState::clone_deep(Compile* C) const {
JVMState* n = clone_shallow(C);
for (JVMState* p = n; p->_caller != NULL; p = p->_caller) {
p->_caller = p->_caller->clone_shallow(C);
}
assert(n->depth() == depth(), "sanity");
assert(n->debug_depth() == debug_depth(), "sanity");
return n;
}
/**
* Reset map for all callers
*/
void JVMState::set_map_deep(SafePointNode* map) {
for (JVMState* p = this; p->_caller != NULL; p = p->_caller) {
p->set_map(map);
}
}
// Adapt offsets in in-array after adding or removing an edge.
// Prerequisite is that the JVMState is used by only one node.
void JVMState::adapt_position(int delta) {
for (JVMState* jvms = this; jvms != NULL; jvms = jvms->caller()) {
jvms->set_locoff(jvms->locoff() + delta);
jvms->set_stkoff(jvms->stkoff() + delta);
jvms->set_monoff(jvms->monoff() + delta);
jvms->set_scloff(jvms->scloff() + delta);
jvms->set_endoff(jvms->endoff() + delta);
}
}
// Mirror the stack size calculation in the deopt code
// How much stack space would we need at this point in the program in
// case of deoptimization?
int JVMState::interpreter_frame_size() const {
const JVMState* jvms = this;
int size = 0;
int callee_parameters = 0;
int callee_locals = 0;
int extra_args = method()->max_stack() - stk_size();
while (jvms != NULL) {
int locks = jvms->nof_monitors();
int temps = jvms->stk_size();
bool is_top_frame = (jvms == this);
ciMethod* method = jvms->method();
int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
temps + callee_parameters,
extra_args,
locks,
callee_parameters,
callee_locals,
is_top_frame);
size += frame_size;
callee_parameters = method->size_of_parameters();
callee_locals = method->max_locals();
extra_args = 0;
jvms = jvms->caller();
}
return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
}
//=============================================================================
uint CallNode::cmp( const Node &n ) const
{ return _tf == ((CallNode&)n)._tf && _jvms == ((CallNode&)n)._jvms; }
#ifndef PRODUCT
void CallNode::dump_req(outputStream *st) const {
// Dump the required inputs, enclosed in '(' and ')'
uint i; // Exit value of loop
for (i = 0; i < req(); i++) { // For all required inputs
if (i == TypeFunc::Parms) st->print("(");
if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
else st->print("_ ");
}
st->print(")");
}
void CallNode::dump_spec(outputStream *st) const {
st->print(" ");
tf()->dump_on(st);
if (_cnt != COUNT_UNKNOWN) st->print(" C=%f",_cnt);
if (jvms() != NULL) jvms()->dump_spec(st);
}
#endif
const Type *CallNode::bottom_type() const { return tf()->range(); }
const Type *CallNode::Value(PhaseTransform *phase) const {
if (phase->type(in(0)) == Type::TOP) return Type::TOP;
return tf()->range();
}
//------------------------------calling_convention-----------------------------
void CallNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
// Use the standard compiler calling convention
Matcher::calling_convention( sig_bt, parm_regs, argcnt, true );
}
//------------------------------match------------------------------------------
// Construct projections for control, I/O, memory-fields, ..., and
// return result(s) along with their RegMask info
Node *CallNode::match( const ProjNode *proj, const Matcher *match ) {
switch (proj->_con) {
case TypeFunc::Control:
case TypeFunc::I_O:
case TypeFunc::Memory:
return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
case TypeFunc::Parms+1: // For LONG & DOUBLE returns
assert(tf()->_range->field_at(TypeFunc::Parms+1) == Type::HALF, "");
// 2nd half of doubles and longs
return new (match->C) MachProjNode(this,proj->_con, RegMask::Empty, (uint)OptoReg::Bad);
case TypeFunc::Parms: { // Normal returns
uint ideal_reg = tf()->range()->field_at(TypeFunc::Parms)->ideal_reg();
OptoRegPair regs = is_CallRuntime()
? match->c_return_value(ideal_reg,true) // Calls into C runtime
: match-> return_value(ideal_reg,true); // Calls into compiled Java code
RegMask rm = RegMask(regs.first());
if( OptoReg::is_valid(regs.second()) )
rm.Insert( regs.second() );
return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);
}
case TypeFunc::ReturnAdr:
case TypeFunc::FramePtr:
default:
ShouldNotReachHere();
}
return NULL;
}
// Do we Match on this edge index or not? Match no edges
uint CallNode::match_edge(uint idx) const {
return 0;
}
//
// Determine whether the call could modify the field of the specified
// instance at the specified offset.
//
bool CallNode::may_modify(const TypeOopPtr *t_oop, PhaseTransform *phase) {
assert((t_oop != NULL), "sanity");
if (t_oop->is_known_instance()) {
// The instance_id is set only for scalar-replaceable allocations which
// are not passed as arguments according to Escape Analysis.
return false;
}
if (t_oop->is_ptr_to_boxed_value()) {
ciKlass* boxing_klass = t_oop->klass();
if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {
// Skip unrelated boxing methods.
Node* proj = proj_out(TypeFunc::Parms);
if ((proj == NULL) || (phase->type(proj)->is_instptr()->klass() != boxing_klass)) {
return false;
}
}
if (is_CallJava() && as_CallJava()->method() != NULL) {
ciMethod* meth = as_CallJava()->method();
if (meth->is_accessor()) {
return false;
}
// May modify (by reflection) if an boxing object is passed
// as argument or returned.
if (returns_pointer() && (proj_out(TypeFunc::Parms) != NULL)) {
Node* proj = proj_out(TypeFunc::Parms);
const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();
if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
(inst_t->klass() == boxing_klass))) {
return true;
}
}
const TypeTuple* d = tf()->domain();
for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
const TypeInstPtr* inst_t = d->field_at(i)->isa_instptr();
if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
(inst_t->klass() == boxing_klass))) {
return true;
}
}
return false;
}
}
return true;
}
// Does this call have a direct reference to n other than debug information?
bool CallNode::has_non_debug_use(Node *n) {
const TypeTuple * d = tf()->domain();
for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
Node *arg = in(i);
if (arg == n) {
return true;
}
}
return false;
}
// Returns the unique CheckCastPP of a call
// or 'this' if there are several CheckCastPP
// or returns NULL if there is no one.
Node *CallNode::result_cast() {
Node *cast = NULL;
Node *p = proj_out(TypeFunc::Parms);
if (p == NULL)
return NULL;
for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {
Node *use = p->fast_out(i);
if (use->is_CheckCastPP()) {
if (cast != NULL) {
return this; // more than 1 CheckCastPP
}
cast = use;
}
}
return cast;
}
void CallNode::extract_projections(CallProjections* projs, bool separate_io_proj) {
projs->fallthrough_proj = NULL;
projs->fallthrough_catchproj = NULL;
projs->fallthrough_ioproj = NULL;
projs->catchall_ioproj = NULL;
projs->catchall_catchproj = NULL;
projs->fallthrough_memproj = NULL;
projs->catchall_memproj = NULL;
projs->resproj = NULL;
projs->exobj = NULL;
for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
ProjNode *pn = fast_out(i)->as_Proj();
if (pn->outcnt() == 0) continue;
switch (pn->_con) {
case TypeFunc::Control:
{
// For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
projs->fallthrough_proj = pn;
DUIterator_Fast jmax, j = pn->fast_outs(jmax);
const Node *cn = pn->fast_out(j);
if (cn->is_Catch()) {
ProjNode *cpn = NULL;
for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
cpn = cn->fast_out(k)->as_Proj();
assert(cpn->is_CatchProj(), "must be a CatchProjNode");
if (cpn->_con == CatchProjNode::fall_through_index)
projs->fallthrough_catchproj = cpn;
else {
assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
projs->catchall_catchproj = cpn;
}
}
}
break;
}
case TypeFunc::I_O:
if (pn->_is_io_use)
projs->catchall_ioproj = pn;
else
projs->fallthrough_ioproj = pn;
for (DUIterator j = pn->outs(); pn->has_out(j); j++) {
Node* e = pn->out(j);
if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {
assert(projs->exobj == NULL, "only one");
projs->exobj = e;
}
}
break;
case TypeFunc::Memory:
if (pn->_is_io_use)
projs->catchall_memproj = pn;
else
projs->fallthrough_memproj = pn;
break;
case TypeFunc::Parms:
projs->resproj = pn;
break;
default:
assert(false, "unexpected projection from allocation node.");
}
}
// The resproj may not exist because the result couuld be ignored
// and the exception object may not exist if an exception handler
// swallows the exception but all the other must exist and be found.
assert(projs->fallthrough_proj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->fallthrough_catchproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->fallthrough_memproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->fallthrough_ioproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->catchall_catchproj != NULL, "must be found");
if (separate_io_proj) {
assert(Compile::current()->inlining_incrementally() || projs->catchall_memproj != NULL, "must be found");
assert(Compile::current()->inlining_incrementally() || projs->catchall_ioproj != NULL, "must be found");
}
}
Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {
CallGenerator* cg = generator();
if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {
// Check whether this MH handle call becomes a candidate for inlining
ciMethod* callee = cg->method();
vmIntrinsics::ID iid = callee->intrinsic_id();
if (iid == vmIntrinsics::_invokeBasic) {
if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {
phase->C->prepend_late_inline(cg);
set_generator(NULL);
}
} else {
assert(callee->has_member_arg(), "wrong type of call?");
if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {
phase->C->prepend_late_inline(cg);
set_generator(NULL);
}
}
}
return SafePointNode::Ideal(phase, can_reshape);
}
//=============================================================================
uint CallJavaNode::size_of() const { return sizeof(*this); }
uint CallJavaNode::cmp( const Node &n ) const {
CallJavaNode &call = (CallJavaNode&)n;
return CallNode::cmp(call) && _method == call._method;
}
#ifndef PRODUCT
void CallJavaNode::dump_spec(outputStream *st) const {
if( _method ) _method->print_short_name(st);
CallNode::dump_spec(st);
}
#endif
//=============================================================================
uint CallStaticJavaNode::size_of() const { return sizeof(*this); }
uint CallStaticJavaNode::cmp( const Node &n ) const {
CallStaticJavaNode &call = (CallStaticJavaNode&)n;
return CallJavaNode::cmp(call);
}
//----------------------------uncommon_trap_request----------------------------
// If this is an uncommon trap, return the request code, else zero.
int CallStaticJavaNode::uncommon_trap_request() const {
if (_name != NULL && !strcmp(_name, "uncommon_trap")) {
return extract_uncommon_trap_request(this);
}
return 0;
}
int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {
#ifndef PRODUCT
if (!(call->req() > TypeFunc::Parms &&
call->in(TypeFunc::Parms) != NULL &&
call->in(TypeFunc::Parms)->is_Con())) {
assert(in_dump() != 0, "OK if dumping");
tty->print("[bad uncommon trap]");
return 0;
}
#endif
return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();
}
#ifndef PRODUCT
void CallStaticJavaNode::dump_spec(outputStream *st) const {
st->print("# Static ");
if (_name != NULL) {
st->print("%s", _name);
int trap_req = uncommon_trap_request();
if (trap_req != 0) {
char buf[100];
st->print("(%s)",
Deoptimization::format_trap_request(buf, sizeof(buf),
trap_req));
}
st->print(" ");
}
CallJavaNode::dump_spec(st);
}
#endif
//=============================================================================
uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }
uint CallDynamicJavaNode::cmp( const Node &n ) const {
CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;
return CallJavaNode::cmp(call);
}
#ifndef PRODUCT
void CallDynamicJavaNode::dump_spec(outputStream *st) const {
st->print("# Dynamic ");
CallJavaNode::dump_spec(st);
}
#endif
//=============================================================================
uint CallRuntimeNode::size_of() const { return sizeof(*this); }
uint CallRuntimeNode::cmp( const Node &n ) const {
CallRuntimeNode &call = (CallRuntimeNode&)n;
return CallNode::cmp(call) && !strcmp(_name,call._name);
}
#ifndef PRODUCT
void CallRuntimeNode::dump_spec(outputStream *st) const {
st->print("# ");
st->print("%s", _name);
CallNode::dump_spec(st);
}
#endif
//------------------------------calling_convention-----------------------------
void CallRuntimeNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );
}
//=============================================================================
//------------------------------calling_convention-----------------------------
//=============================================================================
#ifndef PRODUCT
void CallLeafNode::dump_spec(outputStream *st) const {
st->print("# ");
st->print("%s", _name);
CallNode::dump_spec(st);
}
#endif
//=============================================================================
void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {
assert(verify_jvms(jvms), "jvms must match");
int loc = jvms->locoff() + idx;
if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {
// If current local idx is top then local idx - 1 could
// be a long/double that needs to be killed since top could
// represent the 2nd half ofthe long/double.
uint ideal = in(loc -1)->ideal_reg();
if (ideal == Op_RegD || ideal == Op_RegL) {
// set other (low index) half to top
set_req(loc - 1, in(loc));
}
}
set_req(loc, c);
}
uint SafePointNode::size_of() const { return sizeof(*this); }
uint SafePointNode::cmp( const Node &n ) const {
return (&n == this); // Always fail except on self
}
//-------------------------set_next_exception----------------------------------
void SafePointNode::set_next_exception(SafePointNode* n) {
assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");
if (len() == req()) {
if (n != NULL) add_prec(n);
} else {
set_prec(req(), n);
}
}
//----------------------------next_exception-----------------------------------
SafePointNode* SafePointNode::next_exception() const {
if (len() == req()) {
return NULL;
} else {
Node* n = in(req());
assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");
return (SafePointNode*) n;
}
}
//------------------------------Ideal------------------------------------------
// Skip over any collapsed Regions
Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {
return remove_dead_region(phase, can_reshape) ? this : NULL;
}
//------------------------------Identity---------------------------------------
// Remove obviously duplicate safepoints
Node *SafePointNode::Identity( PhaseTransform *phase ) {
// If you have back to back safepoints, remove one
if( in(TypeFunc::Control)->is_SafePoint() )
return in(TypeFunc::Control);
if( in(0)->is_Proj() ) {
Node *n0 = in(0)->in(0);
// Check if he is a call projection (except Leaf Call)
if( n0->is_Catch() ) {
n0 = n0->in(0)->in(0);
assert( n0->is_Call(), "expect a call here" );
}
if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {
// Useless Safepoint, so remove it
return in(TypeFunc::Control);
}
}
return this;
}
//------------------------------Value------------------------------------------
const Type *SafePointNode::Value( PhaseTransform *phase ) const {
if( phase->type(in(0)) == Type::TOP ) return Type::TOP;
if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop
return Type::CONTROL;
}
#ifndef PRODUCT
void SafePointNode::dump_spec(outputStream *st) const {
st->print(" SafePoint ");
}
#endif
const RegMask &SafePointNode::in_RegMask(uint idx) const {
if( idx < TypeFunc::Parms ) return RegMask::Empty;
// Values outside the domain represent debug info
return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
}
const RegMask &SafePointNode::out_RegMask() const {
return RegMask::Empty;
}
void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {
assert((int)grow_by > 0, "sanity");
int monoff = jvms->monoff();
int scloff = jvms->scloff();
int endoff = jvms->endoff();
assert(endoff == (int)req(), "no other states or debug info after me");
Node* top = Compile::current()->top();
for (uint i = 0; i < grow_by; i++) {
ins_req(monoff, top);
}
jvms->set_monoff(monoff + grow_by);
jvms->set_scloff(scloff + grow_by);
jvms->set_endoff(endoff + grow_by);
}
void SafePointNode::push_monitor(const FastLockNode *lock) {
// Add a LockNode, which points to both the original BoxLockNode (the
// stack space for the monitor) and the Object being locked.
const int MonitorEdges = 2;
assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
assert(req() == jvms()->endoff(), "correct sizing");
int nextmon = jvms()->scloff();
if (GenerateSynchronizationCode) {
ins_req(nextmon, lock->box_node());
ins_req(nextmon+1, lock->obj_node());
} else {
Node* top = Compile::current()->top();
ins_req(nextmon, top);
ins_req(nextmon, top);
}
jvms()->set_scloff(nextmon + MonitorEdges);
jvms()->set_endoff(req());
}
void SafePointNode::pop_monitor() {
// Delete last monitor from debug info
debug_only(int num_before_pop = jvms()->nof_monitors());
const int MonitorEdges = 2;
assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
int scloff = jvms()->scloff();
int endoff = jvms()->endoff();
int new_scloff = scloff - MonitorEdges;
int new_endoff = endoff - MonitorEdges;
jvms()->set_scloff(new_scloff);
jvms()->set_endoff(new_endoff);
while (scloff > new_scloff) del_req_ordered(--scloff);
assert(jvms()->nof_monitors() == num_before_pop-1, "");
}
Node *SafePointNode::peek_monitor_box() const {
int mon = jvms()->nof_monitors() - 1;
assert(mon >= 0, "most have a monitor");
return monitor_box(jvms(), mon);
}
Node *SafePointNode::peek_monitor_obj() const {
int mon = jvms()->nof_monitors() - 1;
assert(mon >= 0, "most have a monitor");
return monitor_obj(jvms(), mon);
}
// Do we Match on this edge index or not? Match no edges
uint SafePointNode::match_edge(uint idx) const {
if( !needs_polling_address_input() )
return 0;
return (TypeFunc::Parms == idx);
}
//============== SafePointScalarObjectNode ==============
SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,
#ifdef ASSERT
AllocateNode* alloc,
#endif
uint first_index,
uint n_fields) :
TypeNode(tp, 1), // 1 control input -- seems required. Get from root.
#ifdef ASSERT
_alloc(alloc),
#endif
_first_index(first_index),
_n_fields(n_fields)
{
init_class_id(Class_SafePointScalarObject);
}
// Do not allow value-numbering for SafePointScalarObject node.
uint SafePointScalarObjectNode::hash() const { return NO_HASH; }
uint SafePointScalarObjectNode::cmp( const Node &n ) const {
return (&n == this); // Always fail except on self
}
uint SafePointScalarObjectNode::ideal_reg() const {
return 0; // No matching to machine instruction
}
const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {
return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
}
const RegMask &SafePointScalarObjectNode::out_RegMask() const {
return RegMask::Empty;
}
uint SafePointScalarObjectNode::match_edge(uint idx) const {
return 0;
}
SafePointScalarObjectNode*
SafePointScalarObjectNode::clone(Dict* sosn_map) const {
void* cached = (*sosn_map)[(void*)this];
if (cached != NULL) {
return (SafePointScalarObjectNode*)cached;
}
SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();
sosn_map->Insert((void*)this, (void*)res);
return res;
}
#ifndef PRODUCT
void SafePointScalarObjectNode::dump_spec(outputStream *st) const {
st->print(" # fields@[%d..%d]", first_index(),
first_index() + n_fields() - 1);
}
#endif
//=============================================================================
uint AllocateNode::size_of() const { return sizeof(*this); }
AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,
Node *ctrl, Node *mem, Node *abio,
Node *size, Node *klass_node, Node *initial_test)
: CallNode(atype, NULL, TypeRawPtr::BOTTOM)
{
init_class_id(Class_Allocate);
init_flags(Flag_is_macro);
_is_scalar_replaceable = false;
_is_non_escaping = false;
Node *topnode = C->top();
init_req( TypeFunc::Control , ctrl );
init_req( TypeFunc::I_O , abio );
init_req( TypeFunc::Memory , mem );
init_req( TypeFunc::ReturnAdr, topnode );
init_req( TypeFunc::FramePtr , topnode );
init_req( AllocSize , size);
init_req( KlassNode , klass_node);
init_req( InitialTest , initial_test);
init_req( ALength , topnode);
C->add_macro_node(this);
}
//=============================================================================
Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
if (remove_dead_region(phase, can_reshape)) return this;
// Don't bother trying to transform a dead node
if (in(0) && in(0)->is_top()) return NULL;
const Type* type = phase->type(Ideal_length());
if (type->isa_int() && type->is_int()->_hi < 0) {
if (can_reshape) {
PhaseIterGVN *igvn = phase->is_IterGVN();
// Unreachable fall through path (negative array length),
// the allocation can only throw so disconnect it.
Node* proj = proj_out(TypeFunc::Control);
Node* catchproj = NULL;
if (proj != NULL) {
for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {
Node *cn = proj->fast_out(i);
if (cn->is_Catch()) {
catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);
break;
}
}
}
if (catchproj != NULL && catchproj->outcnt() > 0 &&
(catchproj->outcnt() > 1 ||
catchproj->unique_out()->Opcode() != Op_Halt)) {
assert(catchproj->is_CatchProj(), "must be a CatchProjNode");
Node* nproj = catchproj->clone();
igvn->register_new_node_with_optimizer(nproj);
Node *frame = new (phase->C) ParmNode( phase->C->start(), TypeFunc::FramePtr );
frame = phase->transform(frame);
// Halt & Catch Fire
Node *halt = new (phase->C) HaltNode( nproj, frame );
phase->C->root()->add_req(halt);
phase->transform(halt);
igvn->replace_node(catchproj, phase->C->top());
return this;
}
} else {
// Can't correct it during regular GVN so register for IGVN
phase->C->record_for_igvn(this);
}
}
return NULL;
}
// Retrieve the length from the AllocateArrayNode. Narrow the type with a
// CastII, if appropriate. If we are not allowed to create new nodes, and
// a CastII is appropriate, return NULL.
Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {
Node *length = in(AllocateNode::ALength);
assert(length != NULL, "length is not null");
const TypeInt* length_type = phase->find_int_type(length);
const TypeAryPtr* ary_type = oop_type->isa_aryptr();
if (ary_type != NULL && length_type != NULL) {
const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);
if (narrow_length_type != length_type) {
// Assert one of:
// - the narrow_length is 0
// - the narrow_length is not wider than length
assert(narrow_length_type == TypeInt::ZERO ||
length_type->is_con() && narrow_length_type->is_con() &&
(narrow_length_type->_hi <= length_type->_lo) ||
(narrow_length_type->_hi <= length_type->_hi &&
narrow_length_type->_lo >= length_type->_lo),
"narrow type must be narrower than length type");
// Return NULL if new nodes are not allowed
if (!allow_new_nodes) return NULL;
// Create a cast which is control dependent on the initialization to
// propagate the fact that the array length must be positive.
length = new (phase->C) CastIINode(length, narrow_length_type);
length->set_req(0, initialization()->proj_out(0));
}
}
return length;
}
//=============================================================================
uint LockNode::size_of() const { return sizeof(*this); }
// Redundant lock elimination
//
// There are various patterns of locking where we release and
// immediately reacquire a lock in a piece of code where no operations
// occur in between that would be observable. In those cases we can
// skip releasing and reacquiring the lock without violating any
// fairness requirements. Doing this around a loop could cause a lock
// to be held for a very long time so we concentrate on non-looping
// control flow. We also require that the operations are fully
// redundant meaning that we don't introduce new lock operations on
// some paths so to be able to eliminate it on others ala PRE. This
// would probably require some more extensive graph manipulation to
// guarantee that the memory edges were all handled correctly.
//
// Assuming p is a simple predicate which can't trap in any way and s
// is a synchronized method consider this code:
//
// s();
// if (p)
// s();
// else
// s();
// s();
//
// 1. The unlocks of the first call to s can be eliminated if the
// locks inside the then and else branches are eliminated.
//
// 2. The unlocks of the then and else branches can be eliminated if
// the lock of the final call to s is eliminated.
//
// Either of these cases subsumes the simple case of sequential control flow
//
// Addtionally we can eliminate versions without the else case:
//
// s();
// if (p)
// s();
// s();
//
// 3. In this case we eliminate the unlock of the first s, the lock
// and unlock in the then case and the lock in the final s.
//
// Note also that in all these cases the then/else pieces don't have
// to be trivial as long as they begin and end with synchronization
// operations.
//
// s();
// if (p)
// s();
// f();
// s();
// s();
//
// The code will work properly for this case, leaving in the unlock
// before the call to f and the relock after it.
//
// A potentially interesting case which isn't handled here is when the
// locking is partially redundant.
//
// s();
// if (p)
// s();
//
// This could be eliminated putting unlocking on the else case and
// eliminating the first unlock and the lock in the then side.
// Alternatively the unlock could be moved out of the then side so it
// was after the merge and the first unlock and second lock
// eliminated. This might require less manipulation of the memory
// state to get correct.
//
// Additionally we might allow work between a unlock and lock before
// giving up eliminating the locks. The current code disallows any
// conditional control flow between these operations. A formulation
// similar to partial redundancy elimination computing the
// availability of unlocking and the anticipatability of locking at a
// program point would allow detection of fully redundant locking with
// some amount of work in between. I'm not sure how often I really
// think that would occur though. Most of the cases I've seen
// indicate it's likely non-trivial work would occur in between.
// There may be other more complicated constructs where we could
// eliminate locking but I haven't seen any others appear as hot or
// interesting.
//
// Locking and unlocking have a canonical form in ideal that looks
// roughly like this:
//
// <obj>
// | \\------+
// | \ \
// | BoxLock \
// | | | \
// | | \ \
// | | FastLock
// | | /
// | | /
// | | |
//
// Lock
// |
// Proj #0
// |
// MembarAcquire
// |
// Proj #0
//
// MembarRelease
// |
// Proj #0
// |
// Unlock
// |
// Proj #0
//
//
// This code proceeds by processing Lock nodes during PhaseIterGVN
// and searching back through its control for the proper code
// patterns. Once it finds a set of lock and unlock operations to
// eliminate they are marked as eliminatable which causes the
// expansion of the Lock and Unlock macro nodes to make the operation a NOP
//
//=============================================================================
//
// Utility function to skip over uninteresting control nodes. Nodes skipped are:
// - copy regions. (These may not have been optimized away yet.)
// - eliminated locking nodes
//
static Node *next_control(Node *ctrl) {
if (ctrl == NULL)
return NULL;
while (1) {
if (ctrl->is_Region()) {
RegionNode *r = ctrl->as_Region();
Node *n = r->is_copy();
if (n == NULL)
break; // hit a region, return it
else
ctrl = n;
} else if (ctrl->is_Proj()) {
Node *in0 = ctrl->in(0);
if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {
ctrl = in0->in(0);
} else {
break;
}
} else {
break; // found an interesting control
}
}
return ctrl;
}
//
// Given a control, see if it's the control projection of an Unlock which
// operating on the same object as lock.
//
bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,
GrowableArray<AbstractLockNode*> &lock_ops) {
ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;
if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {
Node *n = ctrl_proj->in(0);
if (n != NULL && n->is_Unlock()) {
UnlockNode *unlock = n->as_Unlock();
if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&
!unlock->is_eliminated()) {
lock_ops.append(unlock);
return true;
}
}
}
return false;
}
//
// Find the lock matching an unlock. Returns null if a safepoint
// or complicated control is encountered first.
LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {
LockNode *lock_result = NULL;
// find the matching lock, or an intervening safepoint
Node *ctrl = next_control(unlock->in(0));
while (1) {
assert(ctrl != NULL, "invalid control graph");
assert(!ctrl->is_Start(), "missing lock for unlock");
if (ctrl->is_top()) break; // dead control path
if (ctrl->is_Proj()) ctrl = ctrl->in(0);
if (ctrl->is_SafePoint()) {
break; // found a safepoint (may be the lock we are searching for)
} else if (ctrl->is_Region()) {
// Check for a simple diamond pattern. Punt on anything more complicated
if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {
Node *in1 = next_control(ctrl->in(1));
Node *in2 = next_control(ctrl->in(2));
if (((in1->is_IfTrue() && in2->is_IfFalse()) ||
(in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {
ctrl = next_control(in1->in(0)->in(0));
} else {
break;
}
} else {
break;
}
} else {
ctrl = next_control(ctrl->in(0)); // keep searching
}
}
if (ctrl->is_Lock()) {
LockNode *lock = ctrl->as_Lock();
if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {
lock_result = lock;
}
}
return lock_result;
}
// This code corresponds to case 3 above.
bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,
GrowableArray<AbstractLockNode*> &lock_ops) {
Node* if_node = node->in(0);
bool if_true = node->is_IfTrue();
if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {
Node *lock_ctrl = next_control(if_node->in(0));
if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {
Node* lock1_node = NULL;
ProjNode* proj = if_node->as_If()->proj_out(!if_true);
if (if_true) {
if (proj->is_IfFalse() && proj->outcnt() == 1) {
lock1_node = proj->unique_out();
}
} else {
if (proj->is_IfTrue() && proj->outcnt() == 1) {
lock1_node = proj->unique_out();
}
}
if (lock1_node != NULL && lock1_node->is_Lock()) {
LockNode *lock1 = lock1_node->as_Lock();
if (lock->obj_node()->eqv_uncast(lock1->obj_node()) &&
BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&
!lock1->is_eliminated()) {
lock_ops.append(lock1);
return true;
}
}
}
}
lock_ops.trunc_to(0);
return false;
}
bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,
GrowableArray<AbstractLockNode*> &lock_ops) {
// check each control merging at this point for a matching unlock.
// in(0) should be self edge so skip it.
for (int i = 1; i < (int)region->req(); i++) {
Node *in_node = next_control(region->in(i));
if (in_node != NULL) {
if (find_matching_unlock(in_node, lock, lock_ops)) {
// found a match so keep on checking.
continue;
} else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {
continue;
}
// If we fall through to here then it was some kind of node we
// don't understand or there wasn't a matching unlock, so give
// up trying to merge locks.
lock_ops.trunc_to(0);
return false;
}
}
return true;
}
#ifndef PRODUCT
//
// Create a counter which counts the number of times this lock is acquired
//
void AbstractLockNode::create_lock_counter(JVMState* state) {
_counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);
}
void AbstractLockNode::set_eliminated_lock_counter() {
if (_counter) {
// Update the counter to indicate that this lock was eliminated.
// The counter update code will stay around even though the
// optimizer will eliminate the lock operation itself.
_counter->set_tag(NamedCounter::EliminatedLockCounter);
}
}
#endif
//=============================================================================
Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
// perform any generic optimizations first (returns 'this' or NULL)
Node *result = SafePointNode::Ideal(phase, can_reshape);
if (result != NULL) return result;
// Don't bother trying to transform a dead node
if (in(0) && in(0)->is_top()) return NULL;
// Now see if we can optimize away this lock. We don't actually
// remove the locking here, we simply set the _eliminate flag which
// prevents macro expansion from expanding the lock. Since we don't
// modify the graph, the value returned from this function is the
// one computed above.
if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
//
// If we are locking an unescaped object, the lock/unlock is unnecessary
//
ConnectionGraph *cgr = phase->C->congraph();
if (cgr != NULL && cgr->not_global_escape(obj_node())) {
assert(!is_eliminated() || is_coarsened(), "sanity");
// The lock could be marked eliminated by lock coarsening
// code during first IGVN before EA. Replace coarsened flag
// to eliminate all associated locks/unlocks.
this->set_non_esc_obj();
return result;
}
//
// Try lock coarsening
//
PhaseIterGVN* iter = phase->is_IterGVN();
if (iter != NULL && !is_eliminated()) {
GrowableArray<AbstractLockNode*> lock_ops;
Node *ctrl = next_control(in(0));
// now search back for a matching Unlock
if (find_matching_unlock(ctrl, this, lock_ops)) {
// found an unlock directly preceding this lock. This is the
// case of single unlock directly control dependent on a
// single lock which is the trivial version of case 1 or 2.
} else if (ctrl->is_Region() ) {
if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {
// found lock preceded by multiple unlocks along all paths
// joining at this point which is case 3 in description above.
}
} else {
// see if this lock comes from either half of an if and the
// predecessors merges unlocks and the other half of the if
// performs a lock.
if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {
// found unlock splitting to an if with locks on both branches.
}
}
if (lock_ops.length() > 0) {
// add ourselves to the list of locks to be eliminated.
lock_ops.append(this);
#ifndef PRODUCT
if (PrintEliminateLocks) {
int locks = 0;
int unlocks = 0;
for (int i = 0; i < lock_ops.length(); i++) {
AbstractLockNode* lock = lock_ops.at(i);
if (lock->Opcode() == Op_Lock)
locks++;
else
unlocks++;
if (Verbose) {
lock->dump(1);
}
}
tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);
}
#endif
// for each of the identified locks, mark them
// as eliminatable
for (int i = 0; i < lock_ops.length(); i++) {
AbstractLockNode* lock = lock_ops.at(i);
// Mark it eliminated by coarsening and update any counters
lock->set_coarsened();
}
} else if (ctrl->is_Region() &&
iter->_worklist.member(ctrl)) {
// We weren't able to find any opportunities but the region this
// lock is control dependent on hasn't been processed yet so put
// this lock back on the worklist so we can check again once any
// region simplification has occurred.
iter->_worklist.push(this);
}
}
}
return result;
}
//=============================================================================
bool LockNode::is_nested_lock_region() {
BoxLockNode* box = box_node()->as_BoxLock();
int stk_slot = box->stack_slot();
if (stk_slot <= 0)
return false; // External lock or it is not Box (Phi node).
// Ignore complex cases: merged locks or multiple locks.
Node* obj = obj_node();
LockNode* unique_lock = NULL;
if (!box->is_simple_lock_region(&unique_lock, obj) ||
(unique_lock != this)) {
return false;
}
// Look for external lock for the same object.
SafePointNode* sfn = this->as_SafePoint();
JVMState* youngest_jvms = sfn->jvms();
int max_depth = youngest_jvms->depth();
for (int depth = 1; depth <= max_depth; depth++) {
JVMState* jvms = youngest_jvms->of_depth(depth);
int num_mon = jvms->nof_monitors();
// Loop over monitors
for (int idx = 0; idx < num_mon; idx++) {
Node* obj_node = sfn->monitor_obj(jvms, idx);
BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();
if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {
return true;
}
}
}
return false;
}
//=============================================================================
uint UnlockNode::size_of() const { return sizeof(*this); }
//=============================================================================
Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
// perform any generic optimizations first (returns 'this' or NULL)
Node *result = SafePointNode::Ideal(phase, can_reshape);
if (result != NULL) return result;
// Don't bother trying to transform a dead node
if (in(0) && in(0)->is_top()) return NULL;
// Now see if we can optimize away this unlock. We don't actually
// remove the unlocking here, we simply set the _eliminate flag which
// prevents macro expansion from expanding the unlock. Since we don't
// modify the graph, the value returned from this function is the
// one computed above.
// Escape state is defined after Parse phase.
if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
//
// If we are unlocking an unescaped object, the lock/unlock is unnecessary.
//
ConnectionGraph *cgr = phase->C->congraph();
if (cgr != NULL && cgr->not_global_escape(obj_node())) {
assert(!is_eliminated() || is_coarsened(), "sanity");
// The lock could be marked eliminated by lock coarsening
// code during first IGVN before EA. Replace coarsened flag
// to eliminate all associated locks/unlocks.
this->set_non_esc_obj();
}
}
return result;
}
| smarr/graal | src/share/vm/opto/callnode.cpp | C++ | gpl-2.0 | 64,301 |
<?php namespace Indikator\Backend\ReportWidgets;
use Backend\Classes\ReportWidgetBase;
use Exception;
use DB;
class Logs extends ReportWidgetBase
{
public function render()
{
try {
$this->loadData();
}
catch (Exception $ex) {
$this->vars['error'] = $ex->getMessage();
}
return $this->makePartial('widget');
}
public function defineProperties()
{
return [
'title' => [
'title' => 'backend::lang.dashboard.widget_title_label',
'default' => 'indikator.backend::lang.widgets.logs.label',
'type' => 'string',
'validationPattern' => '^.+$',
'validationMessage' => 'backend::lang.dashboard.widget_title_error'
],
'access' => [
'title' => 'indikator.backend::lang.properties.access',
'default' => true,
'type' => 'checkbox'
],
'event' => [
'title' => 'indikator.backend::lang.properties.event',
'default' => true,
'type' => 'checkbox'
],
'request' => [
'title' => 'indikator.backend::lang.properties.request',
'default' => true,
'type' => 'checkbox'
],
'total' => [
'title' => 'indikator.backend::lang.properties.total',
'default' => true,
'type' => 'checkbox'
]
];
}
protected function loadData()
{
$this->vars['access'] = DB::table('backend_access_log')->count();
$this->vars['event'] = DB::table('system_event_logs')->count();
$this->vars['request'] = DB::table('system_request_logs')->count();
}
}
| janusnic/Portfolio | hostweb/kernel/plugins/indikator/backend/reportwidgets/Logs.php | PHP | gpl-2.0 | 2,006 |
--[[
BY-@Sadik_alknani10
BY_CH : @KINGTELE1
]]
local function get_variables_hash(msg)
if msg.to.type == 'chat' or msg.to.type == 'channel' then
return 'chat:bot:variables'
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
local function list_chats(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = '👇الردود هي : ️\n\n'
for i=1, #names do
text = text..'® '..names[i]..'\n'
end
return text
else
return
end
end
local function save_value(msg, name, value)
if (not name or not value) then
return "Usage: !set var_name value"
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hset(hash, name, value)
return '('..name..')\n تـ﷽ـم اضُافَُه ُهذَا الُرَدِ🌝 '
end
end
local function del_value(msg, name)
if not name then
return
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hdel(hash, name)
return '('..name..')\n تْـ﷽ـم حُذَفَ ُهذَا الُرَدِ🌝 '
end
end
local function delallchats(msg)
local hash = 'chat:bot:variables'
if hash then
local names = redis:hkeys(hash)
for i=1, #names do
redis:hdel(hash,names[i])
end
return "saved!"
else
return
end
end
local function run(msg, matches)
if is_sudo(msg) then
local name = matches[3]
local value = matches[4]
if matches[2] == 'حذف الجميع' then
local output = delallchats(msg)
return output
end
if matches[2] == 'اضف' then
local name1 = user_print_name(msg.from)
savelog(msg.to.id, name1.." ["..msg.from.id.."] saved ["..name.."] as > "..value )
local text = save_value(msg, name, value)
return text
elseif matches[2] == 'حذف' then
local text = del_value(msg,name)
return text
end
end
if matches[1] == 'الردود' then
local output = list_chats(msg)
return output
else
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /get ".. matches[1])-- save to logs
local text = get_value(msg, matches[1])
return reply_msg(msg.id,text,ok_cb,false)
end
end
return {
patterns = {
"^(الردود)$",
"^(رد) (اضف) ([^%s]+) (.+)$",
"^(رد) (حذف الجميع)$",
"^(رد) (حذف) (.*)$",
"^(.+)$",
},
run = run
}
-- @KINGTELE1
| gowadbd/DevDroid | plugins/addreplay.lua | Lua | gpl-2.0 | 2,727 |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.rm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class rep_movsb_a32 extends Executable
{
final int segIndex;
public rep_movsb_a32(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
segIndex = Prefices.getSegment(prefices, Processor.DS_INDEX);
}
public Branch execute(Processor cpu)
{
Segment seg = cpu.segs[segIndex];
StaticOpcodes.rep_movsb_a32(cpu, seg);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | ysangkok/JPC | src/org/jpc/emulator/execution/opcodes/rm/rep_movsb_a32.java | Java | gpl-2.0 | 1,819 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim:expandtab:shiftwidth=2:tabstop=2: */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Gtk2XtBin Widget Implementation.
*
* The Initial Developer of the Original Code is
* Sun Microsystems, Inc.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/*
* The GtkXtBin widget allows for Xt toolkit code to be used
* inside a GTK application.
*/
#include "xembed.h"
#include "gtk2xtbin.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <glib.h>
#include <assert.h>
#include <sys/time.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* Xlib/Xt stuff */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Shell.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
/* uncomment this if you want debugging information about widget
creation and destruction */
#undef DEBUG_XTBIN
#define XTBIN_MAX_EVENTS 30
static void gtk_xtbin_class_init (GtkXtBinClass *klass);
static void gtk_xtbin_init (GtkXtBin *xtbin);
static void gtk_xtbin_realize (GtkWidget *widget);
static void gtk_xtbin_unrealize (GtkWidget *widget);
static void gtk_xtbin_destroy (GtkObject *object);
static void gtk_xtbin_shutdown (GtkObject *object);
/* Xt aware XEmbed */
static void xt_client_init (XtClient * xtclient,
Visual *xtvisual,
Colormap xtcolormap,
int xtdepth);
static void xt_client_create (XtClient * xtclient,
Window embeder,
int height,
int width );
static void xt_client_unrealize (XtClient* xtclient);
static void xt_client_destroy (XtClient* xtclient);
static void xt_client_set_info (Widget xtplug,
unsigned long flags);
static void xt_client_event_handler (Widget w,
XtPointer client_data,
XEvent *event);
static void xt_client_handle_xembed_message (Widget w,
XtPointer client_data,
XEvent *event);
static void xt_client_focus_listener (Widget w,
XtPointer user_data,
XEvent *event);
static void xt_add_focus_listener( Widget w, XtPointer user_data );
static void xt_add_focus_listener_tree ( Widget treeroot, XtPointer user_data);
static void xt_remove_focus_listener(Widget w, XtPointer user_data);
static void send_xembed_message (XtClient *xtclient,
long message,
long detail,
long data1,
long data2,
long time);
static int error_handler (Display *display,
XErrorEvent *error);
/* For error trap of XEmbed */
static void trap_errors(void);
static int untrap_error(void);
static int (*old_error_handler) (Display *, XErrorEvent *);
static int trapped_error_code = 0;
static GtkWidgetClass *parent_class = NULL;
static Display *xtdisplay = NULL;
static String *fallback = NULL;
static gboolean xt_is_initialized = FALSE;
static gint num_widgets = 0;
static GPollFD xt_event_poll_fd;
static gint xt_polling_timer_id = 0;
static guint tag = 0;
static gboolean
xt_event_prepare (GSource* source_data,
gint *timeout)
{
int mask;
GDK_THREADS_ENTER();
mask = XPending(xtdisplay);
GDK_THREADS_LEAVE();
return (gboolean)mask;
}
static gboolean
xt_event_check (GSource* source_data)
{
GDK_THREADS_ENTER ();
if (xt_event_poll_fd.revents & G_IO_IN) {
int mask;
mask = XPending(xtdisplay);
GDK_THREADS_LEAVE ();
return (gboolean)mask;
}
GDK_THREADS_LEAVE ();
return FALSE;
}
static gboolean
xt_event_dispatch (GSource* source_data,
GSourceFunc call_back,
gpointer user_data)
{
XEvent event;
XtAppContext ac;
int i = 0;
ac = XtDisplayToApplicationContext(xtdisplay);
GDK_THREADS_ENTER ();
/* Process only real X traffic here. We only look for data on the
* pipe, limit it to XTBIN_MAX_EVENTS and only call
* XtAppProcessEvent so that it will look for X events. There's no
* timer processing here since we already have a timer callback that
* does it. */
for (i=0; i < XTBIN_MAX_EVENTS && XPending(xtdisplay); i++) {
XtAppProcessEvent(ac, XtIMXEvent);
}
GDK_THREADS_LEAVE ();
return TRUE;
}
static GSourceFuncs xt_event_funcs = {
xt_event_prepare,
xt_event_check,
xt_event_dispatch,
g_free,
(GSourceFunc)NULL,
(GSourceDummyMarshal)NULL
};
static gboolean
xt_event_polling_timer_callback(gpointer user_data)
{
Display * display;
XtAppContext ac;
int eventsToProcess = 20;
display = (Display *)user_data;
ac = XtDisplayToApplicationContext(display);
/* We need to process many Xt events here. If we just process
one event we might starve one or more Xt consumers. On the other hand
this could hang the whole app if Xt events come pouring in. So process
up to 20 Xt events right now and save the rest for later. This is a hack,
but it oughta work. We *really* should have out of process plugins.
*/
while (eventsToProcess-- && XtAppPending(ac))
XtAppProcessEvent(ac, XtIMAll);
return TRUE;
}
GType
gtk_xtbin_get_type (void)
{
static GType xtbin_type = 0;
if (!xtbin_type) {
static const GTypeInfo xtbin_info =
{
sizeof (GtkXtBinClass),
NULL,
NULL,
(GClassInitFunc)gtk_xtbin_class_init,
NULL,
NULL,
sizeof (GtkXtBin),
0,
(GInstanceInitFunc)gtk_xtbin_init,
};
xtbin_type = g_type_register_static (GTK_TYPE_SOCKET,
"GtkXtBin",
&xtbin_info,
0);
}
return xtbin_type;
}
static void
gtk_xtbin_class_init (GtkXtBinClass *klass)
{
GtkWidgetClass *widget_class;
GtkObjectClass *object_class;
parent_class = g_type_class_peek_parent (klass);
widget_class = GTK_WIDGET_CLASS (klass);
widget_class->realize = gtk_xtbin_realize;
widget_class->unrealize = gtk_xtbin_unrealize;
object_class = GTK_OBJECT_CLASS (klass);
object_class->destroy = gtk_xtbin_destroy;
}
static void
gtk_xtbin_init (GtkXtBin *xtbin)
{
xtbin->xtdisplay = NULL;
xtbin->parent_window = NULL;
xtbin->xtwindow = 0;
xtbin->x = 0;
xtbin->y = 0;
}
static void
gtk_xtbin_realize (GtkWidget *widget)
{
GtkXtBin *xtbin;
GtkAllocation allocation = { 0, 0, 200, 200 };
gint x, y, w, h, d; /* geometry of window */
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_realize()\n");
#endif
g_return_if_fail (GTK_IS_XTBIN (widget));
xtbin = GTK_XTBIN (widget);
/* caculate the allocation before realize */
gdk_window_get_geometry(xtbin->parent_window, &x, &y, &w, &h, &d);
allocation.width = w;
allocation.height = h;
gtk_widget_size_allocate (widget, &allocation);
#ifdef DEBUG_XTBIN
printf("initial allocation %d %d %d %d\n", x, y, w, h);
#endif
xtbin->width = widget->allocation.width;
xtbin->height = widget->allocation.height;
/* use GtkSocket's realize */
(*GTK_WIDGET_CLASS(parent_class)->realize)(widget);
/* create the Xt client widget */
xt_client_create(&(xtbin->xtclient),
gtk_socket_get_id(GTK_SOCKET(xtbin)),
xtbin->height,
xtbin->width);
xtbin->xtwindow = XtWindow(xtbin->xtclient.child_widget);
gdk_flush();
/* now that we have created the xt client, add it to the socket. */
gtk_socket_add_id(GTK_SOCKET(widget), xtbin->xtwindow);
}
GtkWidget*
gtk_xtbin_new (GdkWindow *parent_window, String * f)
{
GtkXtBin *xtbin;
gpointer user_data;
assert(parent_window != NULL);
xtbin = g_object_new (GTK_TYPE_XTBIN, NULL);
if (!xtbin)
return (GtkWidget*)NULL;
if (f)
fallback = f;
/* Initialize the Xt toolkit */
xtbin->parent_window = parent_window;
xt_client_init(&(xtbin->xtclient),
GDK_VISUAL_XVISUAL(gdk_rgb_get_visual()),
GDK_COLORMAP_XCOLORMAP(gdk_rgb_get_colormap()),
gdk_rgb_get_visual()->depth);
if (!xtbin->xtclient.xtdisplay) {
/* If XtOpenDisplay failed, we can't go any further.
* Bail out.
*/
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_init: XtOpenDisplay() returned NULL.\n");
#endif
g_free (xtbin);
return (GtkWidget *)NULL;
}
/* If this is the first running widget, hook this display into the
mainloop */
if (0 == num_widgets) {
int cnumber;
/*
* hook Xt event loop into the glib event loop.
*/
/* the assumption is that gtk_init has already been called */
GSource* gs = g_source_new(&xt_event_funcs, sizeof(GSource));
if (!gs) {
return NULL;
}
g_source_set_priority(gs, GDK_PRIORITY_EVENTS);
g_source_set_can_recurse(gs, TRUE);
tag = g_source_attach(gs, (GMainContext*)NULL);
#ifdef VMS
cnumber = XConnectionNumber(xtdisplay);
#else
cnumber = ConnectionNumber(xtdisplay);
#endif
xt_event_poll_fd.fd = cnumber;
xt_event_poll_fd.events = G_IO_IN;
xt_event_poll_fd.revents = 0; /* hmm... is this correct? */
g_main_context_add_poll ((GMainContext*)NULL,
&xt_event_poll_fd,
G_PRIORITY_LOW);
/* add a timer so that we can poll and process Xt timers */
xt_polling_timer_id =
g_timeout_add(25,
(GSourceFunc)xt_event_polling_timer_callback,
xtdisplay);
}
/* Bump up our usage count */
num_widgets++;
/* Build the hierachy */
xtbin->xtdisplay = xtbin->xtclient.xtdisplay;
gtk_widget_set_parent_window(GTK_WIDGET(xtbin), parent_window);
gdk_window_get_user_data(xtbin->parent_window, &user_data);
if (user_data)
gtk_container_add(GTK_CONTAINER(user_data), GTK_WIDGET(xtbin));
return GTK_WIDGET (xtbin);
}
void
gtk_xtbin_set_position (GtkXtBin *xtbin,
gint x,
gint y)
{
xtbin->x = x;
xtbin->y = y;
if (GTK_WIDGET_REALIZED (xtbin))
gdk_window_move (GTK_WIDGET (xtbin)->window, x, y);
}
void
gtk_xtbin_resize (GtkWidget *widget,
gint width,
gint height)
{
Arg args[2];
GtkXtBin *xtbin = GTK_XTBIN (widget);
GtkAllocation allocation;
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_resize %p %d %d\n", (void *)widget, width, height);
#endif
xtbin->height = height;
xtbin->width = width;
// Avoid BadValue errors in XtSetValues
if (height <= 0 || width <=0) {
height = 1;
width = 1;
}
XtSetArg(args[0], XtNheight, height);
XtSetArg(args[1], XtNwidth, width);
XtSetValues(xtbin->xtclient.top_widget, args, 2);
/* we need to send a size allocate so the socket knows about the
size changes */
allocation.x = xtbin->x;
allocation.y = xtbin->y;
allocation.width = xtbin->width;
allocation.height = xtbin->height;
gtk_widget_size_allocate(widget, &allocation);
}
static void
gtk_xtbin_unrealize (GtkWidget *object)
{
GtkXtBin *xtbin;
GtkWidget *widget;
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_unrealize()\n");
#endif
/* gtk_object_destroy() will already hold a refcount on object
*/
xtbin = GTK_XTBIN(object);
widget = GTK_WIDGET(object);
GTK_WIDGET_UNSET_FLAGS (widget, GTK_VISIBLE);
if (GTK_WIDGET_REALIZED (widget)) {
xt_client_unrealize(&(xtbin->xtclient));
}
(*GTK_WIDGET_CLASS (parent_class)->unrealize)(widget);
}
static void
gtk_xtbin_destroy (GtkObject *object)
{
GtkXtBin *xtbin;
#ifdef DEBUG_XTBIN
printf("gtk_xtbin_destroy()\n");
#endif
g_return_if_fail (object != NULL);
g_return_if_fail (GTK_IS_XTBIN (object));
xtbin = GTK_XTBIN (object);
if(xtbin->xtwindow) {
/* remove the event handler */
xt_client_destroy(&(xtbin->xtclient));
xtbin->xtwindow = 0;
num_widgets--; /* reduce our usage count */
/* If this is the last running widget, remove the Xt display
connection from the mainloop */
if (0 == num_widgets) {
#ifdef DEBUG_XTBIN
printf("removing the Xt connection from the main loop\n");
#endif
g_main_context_remove_poll((GMainContext*)NULL, &xt_event_poll_fd);
g_source_remove(tag);
g_source_remove(xt_polling_timer_id);
xt_polling_timer_id = 0;
}
}
GTK_OBJECT_CLASS(parent_class)->destroy(object);
}
/*
* Following is the implementation of Xt XEmbedded for client side
*/
/* Initial Xt plugin */
static void
xt_client_init( XtClient * xtclient,
Visual *xtvisual,
Colormap xtcolormap,
int xtdepth)
{
XtAppContext app_context;
char *mArgv[1];
int mArgc = 0;
/*
* Initialize Xt stuff
*/
xtclient->top_widget = NULL;
xtclient->child_widget = NULL;
xtclient->xtdisplay = NULL;
xtclient->xtvisual = NULL;
xtclient->xtcolormap = 0;
xtclient->xtdepth = 0;
if (!xt_is_initialized) {
#ifdef DEBUG_XTBIN
printf("starting up Xt stuff\n");
#endif
XtToolkitInitialize();
app_context = XtCreateApplicationContext();
if (fallback)
XtAppSetFallbackResources(app_context, fallback);
xtdisplay = XtOpenDisplay(app_context, gdk_get_display(), NULL,
"Wrapper", NULL, 0, &mArgc, mArgv);
if (xtdisplay)
xt_is_initialized = TRUE;
}
xtclient->xtdisplay = xtdisplay;
xtclient->xtvisual = xtvisual;
xtclient->xtcolormap = xtcolormap;
xtclient->xtdepth = xtdepth;
}
/* Create the Xt client widgets
* */
static void
xt_client_create ( XtClient* xtclient ,
Window embedderid,
int height,
int width )
{
int n;
Arg args[6];
Widget child_widget;
Widget top_widget;
#ifdef DEBUG_XTBIN
printf("xt_client_create() \n");
#endif
top_widget = XtAppCreateShell("drawingArea", "Wrapper",
applicationShellWidgetClass,
xtclient->xtdisplay,
NULL, 0);
xtclient->top_widget = top_widget;
/* set size of Xt window */
n = 0;
XtSetArg(args[n], XtNheight, height);n++;
XtSetArg(args[n], XtNwidth, width);n++;
XtSetValues(top_widget, args, n);
child_widget = XtVaCreateWidget("form",
compositeWidgetClass,
top_widget, NULL);
n = 0;
XtSetArg(args[n], XtNheight, height);n++;
XtSetArg(args[n], XtNwidth, width);n++;
XtSetArg(args[n], XtNvisual, xtclient->xtvisual ); n++;
XtSetArg(args[n], XtNdepth, xtclient->xtdepth ); n++;
XtSetArg(args[n], XtNcolormap, xtclient->xtcolormap ); n++;
XtSetArg(args[n], XtNborderWidth, 0); n++;
XtSetValues(child_widget, args, n);
XSync(xtclient->xtdisplay, FALSE);
xtclient->oldwindow = top_widget->core.window;
top_widget->core.window = embedderid;
/* this little trick seems to finish initializing the widget */
#if XlibSpecificationRelease >= 6
XtRegisterDrawable(xtclient->xtdisplay,
embedderid,
top_widget);
#else
_XtRegisterWindow( embedderid,
top_widget);
#endif
XtRealizeWidget(child_widget);
/* listen to all Xt events */
XSelectInput(xtclient->xtdisplay,
XtWindow(top_widget),
0x0FFFFF);
xt_client_set_info (child_widget, 0);
XtManageChild(child_widget);
xtclient->child_widget = child_widget;
/* set the event handler */
XtAddEventHandler(child_widget,
0x0FFFFF & ~ResizeRedirectMask,
TRUE,
(XtEventHandler)xt_client_event_handler, xtclient);
XtAddEventHandler(child_widget,
SubstructureNotifyMask | ButtonReleaseMask,
TRUE,
(XtEventHandler)xt_client_focus_listener,
xtclient);
XSync(xtclient->xtdisplay, FALSE);
}
static void
xt_client_unrealize ( XtClient* xtclient )
{
#if XlibSpecificationRelease >= 6
XtUnregisterDrawable(xtclient->xtdisplay,
xtclient->top_widget->core.window);
#else
_XtUnregisterWindow(xtclient->top_widget->core.window,
xtclient->top_widget);
#endif
/* flush the queue before we returning origin top_widget->core.window
or we can get X error since the window is gone */
XSync(xtclient->xtdisplay, False);
xtclient->top_widget->core.window = xtclient->oldwindow;
XtUnrealizeWidget(xtclient->top_widget);
}
static void
xt_client_destroy (XtClient* xtclient)
{
if(xtclient->top_widget) {
XtRemoveEventHandler(xtclient->child_widget, 0x0FFFFF, TRUE,
(XtEventHandler)xt_client_event_handler, xtclient);
XtDestroyWidget(xtclient->top_widget);
xtclient->top_widget = NULL;
}
}
static void
xt_client_set_info (Widget xtplug, unsigned long flags)
{
unsigned long buffer[2];
Atom infoAtom = XInternAtom(XtDisplay(xtplug), "_XEMBED_INFO", False);
buffer[1] = 0; /* Protocol version */
buffer[1] = flags;
XChangeProperty (XtDisplay(xtplug), XtWindow(xtplug),
infoAtom, infoAtom, 32,
PropModeReplace,
(unsigned char *)buffer, 2);
}
static void
xt_client_handle_xembed_message(Widget w, XtPointer client_data, XEvent *event)
{
XtClient *xtplug = (XtClient*)client_data;
switch (event->xclient.data.l[1])
{
case XEMBED_EMBEDDED_NOTIFY:
break;
case XEMBED_WINDOW_ACTIVATE:
#ifdef DEBUG_XTBIN
printf("Xt client get XEMBED_WINDOW_ACTIVATE\n");
#endif
break;
case XEMBED_WINDOW_DEACTIVATE:
#ifdef DEBUG_XTBIN
printf("Xt client get XEMBED_WINDOW_DEACTIVATE\n");
#endif
break;
case XEMBED_MODALITY_ON:
#ifdef DEBUG_XTBIN
printf("Xt client get XEMBED_MODALITY_ON\n");
#endif
break;
case XEMBED_MODALITY_OFF:
#ifdef DEBUG_XTBIN
printf("Xt client get XEMBED_MODALITY_OFF\n");
#endif
break;
case XEMBED_FOCUS_IN:
case XEMBED_FOCUS_OUT:
{
XEvent xevent;
memset(&xevent, 0, sizeof(xevent));
if(event->xclient.data.l[1] == XEMBED_FOCUS_IN) {
#ifdef DEBUG_XTBIN
printf("XTEMBED got focus in\n");
#endif
xevent.xfocus.type = FocusIn;
}
else {
#ifdef DEBUG_XTBIN
printf("XTEMBED got focus out\n");
#endif
xevent.xfocus.type = FocusOut;
}
xevent.xfocus.window = XtWindow(xtplug->child_widget);
xevent.xfocus.display = XtDisplay(xtplug->child_widget);
XSendEvent(XtDisplay(xtplug->child_widget),
xevent.xfocus.window,
False, NoEventMask,
&xevent );
XSync( XtDisplay(xtplug->child_widget), False);
}
break;
default:
break;
} /* End of XEmbed Message */
}
static void
xt_client_event_handler( Widget w, XtPointer client_data, XEvent *event)
{
XtClient *xtplug = (XtClient*)client_data;
switch(event->type)
{
case ClientMessage:
/* Handle xembed message */
if (event->xclient.message_type==
XInternAtom (XtDisplay(xtplug->child_widget),
"_XEMBED", False)) {
xt_client_handle_xembed_message(w, client_data, event);
}
break;
case ReparentNotify:
break;
case MappingNotify:
xt_client_set_info (w, XEMBED_MAPPED);
break;
case UnmapNotify:
xt_client_set_info (w, 0);
break;
case FocusIn:
send_xembed_message ( xtplug,
XEMBED_REQUEST_FOCUS, 0, 0, 0, 0);
break;
case FocusOut:
break;
case KeyPress:
#ifdef DEBUG_XTBIN
printf("Key Press Got!\n");
#endif
break;
default:
break;
} /* End of switch(event->type) */
}
static void
send_xembed_message (XtClient *xtclient,
long message,
long detail,
long data1,
long data2,
long time)
{
XEvent xevent;
Window w=XtWindow(xtclient->top_widget);
Display* dpy=xtclient->xtdisplay;
int errorcode;
memset(&xevent,0,sizeof(xevent));
xevent.xclient.window = w;
xevent.xclient.type = ClientMessage;
xevent.xclient.message_type = XInternAtom(dpy,"_XEMBED",False);
xevent.xclient.format = 32;
xevent.xclient.data.l[0] = time;
xevent.xclient.data.l[1] = message;
xevent.xclient.data.l[2] = detail;
xevent.xclient.data.l[3] = data1;
xevent.xclient.data.l[4] = data2;
trap_errors ();
XSendEvent (dpy, w, False, NoEventMask, &xevent);
XSync (dpy,False);
if((errorcode = untrap_error())) {
#ifdef DEBUG_XTBIN
printf("send_xembed_message error(%d)!!!\n",errorcode);
#endif
}
}
static int
error_handler(Display *display, XErrorEvent *error)
{
trapped_error_code = error->error_code;
return 0;
}
static void
trap_errors(void)
{
trapped_error_code =0;
old_error_handler = XSetErrorHandler(error_handler);
}
static int
untrap_error(void)
{
XSetErrorHandler(old_error_handler);
if(trapped_error_code) {
#ifdef DEBUG_XTBIN
printf("Get X Window Error = %d\n", trapped_error_code);
#endif
}
return trapped_error_code;
}
static void
xt_client_focus_listener( Widget w, XtPointer user_data, XEvent *event)
{
Display *dpy = XtDisplay(w);
XtClient *xtclient = user_data;
Window win = XtWindow(w);
switch(event->type)
{
case CreateNotify:
if(event->xcreatewindow.parent == win) {
Widget child=XtWindowToWidget( dpy, event->xcreatewindow.window);
if (child)
xt_add_focus_listener_tree(child, user_data);
}
break;
case DestroyNotify:
xt_remove_focus_listener( w, user_data);
break;
case ReparentNotify:
if(event->xreparent.parent == win) {
/* I am the new parent */
Widget child=XtWindowToWidget(dpy, event->xreparent.window);
if (child)
xt_add_focus_listener_tree( child, user_data);
}
else if(event->xreparent.window == win) {
/* I am the new child */
}
else {
/* I am the old parent */
}
break;
case ButtonRelease:
#if 0
XSetInputFocus(dpy, XtWindow(xtclient->child_widget), RevertToParent, event->xbutton.time);
#endif
send_xembed_message ( xtclient,
XEMBED_REQUEST_FOCUS, 0, 0, 0, 0);
break;
default:
break;
} /* End of switch(event->type) */
}
static void
xt_add_focus_listener( Widget w, XtPointer user_data)
{
XWindowAttributes attr;
long eventmask;
XtClient *xtclient = user_data;
int errorcode;
trap_errors ();
XGetWindowAttributes(XtDisplay(w), XtWindow(w), &attr);
eventmask = attr.your_event_mask | SubstructureNotifyMask | ButtonReleaseMask;
XSelectInput(XtDisplay(w),
XtWindow(w),
eventmask);
XtAddEventHandler(w,
SubstructureNotifyMask | ButtonReleaseMask,
TRUE,
(XtEventHandler)xt_client_focus_listener,
xtclient);
untrap_error();
}
static void
xt_remove_focus_listener(Widget w, XtPointer user_data)
{
int errorcode;
trap_errors ();
XtRemoveEventHandler(w, SubstructureNotifyMask | ButtonReleaseMask, TRUE,
(XtEventHandler)xt_client_focus_listener, user_data);
untrap_error();
}
static void
xt_add_focus_listener_tree ( Widget treeroot, XtPointer user_data)
{
Window win = XtWindow(treeroot);
Window *children;
Window root, parent;
Display *dpy = XtDisplay(treeroot);
unsigned int i, nchildren;
/* ensure we don't add more than once */
xt_remove_focus_listener( treeroot, user_data);
xt_add_focus_listener( treeroot, user_data);
trap_errors();
if(!XQueryTree(dpy, win, &root, &parent, &children, &nchildren)) {
untrap_error();
return;
}
if(untrap_error())
return;
for(i=0; i<nchildren; ++i) {
Widget child = XtWindowToWidget(dpy, children[i]);
if (child)
xt_add_focus_listener_tree( child, user_data);
}
XFree((void*)children);
return;
}
| EpicCM/SPH-D700-Kernel | external/webkit/WebCore/plugins/gtk/gtk2xtbin.c | C | gpl-2.0 | 26,348 |
obj-$(CONFIG_LCD_NULL) += lcd_null.o
obj-$(CONFIG_LCD_RK2928) += lcd_rk2928.o
obj-$(CONFIG_LCD_RK3168_FAC) += lcd_rk3168_fac.o
obj-$(CONFIG_LCD_TD043MGEA1) += lcd_td043mgea1.o
obj-$(CONFIG_LCD_HSD070IDW1) += lcd_hsd800x480.o
obj-$(CONFIG_LCD_HL070VM4AU) += lcd_hl070vm4.o
obj-$(CONFIG_LCD_BYD8688FTGF) += lcd_byd1024x600.o
obj-$(CONFIG_LCD_LG_LP097X02)+= lcd_LG_LP097X02.o
obj-$(CONFIG_LCD_TJ048NC01CA) += lcd_tj048nc01ca.o
obj-$(CONFIG_LCD_A060SE02) += lcd_a060se02.o
obj-$(CONFIG_LCD_S1D13521) += lcd_s1d13521.o
obj-$(CONFIG_LCD_NT35582) += lcd_nt35582.o
obj-$(CONFIG_LCD_NT35580) += lcd_nt35580.o
obj-$(CONFIG_LCD_IPS1P5680_V1_E) += lcd_ips1p5680_v1_e.o
obj-$(CONFIG_LCD_RGB_TFT480800_25_E) += lcd_rgb_tft480800_25_e.o
obj-$(CONFIG_LCD_MCU_TFT480800_25_E) += lcd_mcu_tft480800_25_e.o
obj-$(CONFIG_LCD_LS035Y8DX02A) += lcd_ls035y8dx02a.o
obj-$(CONFIG_LCD_LS035Y8DX04A) += lcd_ls035y8dx04a.o
obj-$(CONFIG_LCD_CPTCLAA038LA31XE) += lcd_CPTclaa038la31xe.o
obj-$(CONFIG_LCD_HX8357) += lcd_hx8357.o
obj-$(CONFIG_LCD_HSD100PXN) += lcd_hsd100pxn.o
obj-$(CONFIG_LCD_HDMI_1366x768) += lcd_hdmi_1366x768.o
obj-$(CONFIG_LCD_HDMI_1280x800) += lcd_hdmi_1280x800.o
obj-$(CONFIG_LCD_HDMI_1024x768) += lcd_hdmi_1024x768.o
obj-$(CONFIG_LCD_HDMI_800x480) += lcd_hdmi_800x480.o
obj-$(CONFIG_LCD_B101AW06) += lcd_B101AW06.o
obj-$(CONFIG_LCD_NT35510) += lcd_nt35510.o
obj-$(CONFIG_LCD_ILI9803_CPT4_3) += lcd_ili9803_cpt4_3.o
obj-$(CONFIG_LCD_RGB_TFT480800_25_E) += lcd_rgb_tft480800_25_e.o
obj-$(CONFIG_LCD_LS035Y8DX02A) += lcd_ls035y8dx02a.o
obj-$(CONFIG_LCD_IPS1P5680_V1_E) += lcd_ips1p5680_v1_e.o
obj-$(CONFIG_LCD_MCU_TFT480800_25_E) += lcd_mcu_tft480800_25_e.o
obj-$(CONFIG_LCD_AT070TNA2) += lcd_AT070TNA2.o
obj-$(CONFIG_LCD_TX23D88VM) += lcd_tx23d88vm.o
obj-$(CONFIG_LCD_AT070TN93) += lcd_at070tn93.o
obj-$(CONFIG_LCD_A050VL01) += lcd_A050VL01.o
obj-$(CONFIG_LCD_B101EW05) += lcd_b101ew05.o
obj-$(CONFIG_LCD_RK3168M_B101EW05) += lcd_hdmi_rk3168m_b101ew05.o
obj-$(CONFIG_LCD_HJ050NA_06A) += lcd_hj050na_06a.o
obj-$(CONFIG_LCD_HSD100PXN_FOR_TDW851) += lcd_hsd100pxn_for_tdw851.o
obj-$(CONFIG_LCD_HV070WSA100) += lcd_hv070wsa.o
obj-$(CONFIG_LCD_COMMON) += lcd_common.o
obj-$(CONFIG_LCD_RK2928_A720) += lcd_YQ70CPT9160.o
obj-$(CONFIG_LCD_RK3168_AUO_A080SN03) += lcd_AUO_A080SN03.o
obj-$(CONFIG_LCD_RK2926_V86) += lcd_YQ70CPT9160_v86.o
obj-$(CONFIG_LCD_RK3168_86V) += lcd_YQ70CPT9160_rk3168_86v.o
obj-$(CONFIG_LCD_HSD07PFW1) += lcd_hdmi_1024x600.o
obj-$(CONFIG_LCD_HJ080NA) += lcd_hj080na.o
obj-$(CONFIG_LCD_HJ101NA) += lcd_hj101na.o
obj-$(CONFIG_LCD_AUTO) += lcd_auto.o
obj-$(CONFIG_LCD_I30_800X480) += lcd_I30_800x480.o
obj-$(CONFIG_LCD_TL5001_MIPI) += lcd_tl5001_mipi.o
obj-$(CONFIG_LCD_LP097QX1) += lcd_LP097QX1.o
obj-$(CONFIG_LCD_DS1006H) += lcd_ds1006h.o
obj-$(CONFIG_LCD_B101UANO_1920x1200) += lcd_b101uano_1920x1200.o
obj-$(CONFIG_LCD_E242868_1024X600) += lcd_E242868_rk3168_86v.o
obj-$(CONFIG_LCD_E242868_RK616_1024X600) += lcd_E242868_rk3168_rk616_86v.o
obj-$(CONFIG_LCD_WY_800X480) += lcd_wy_800x480.o
obj-$(CONFIG_LCD_HH070D_LVDS) += lcd_hh070d_lvds.o
obj-$(CONFIG_LCD_RK3028_86V) += lcd_E242868_rk3028_86v.o
obj-$(CONFIG_LCD_MQ0801D) += lcd_mq0801d.o
obj-$(CONFIG_LCD_LD089WU1_MIPI_M8HD) += lcd_LD089WU1_mipi_m8hd.o
obj-$(CONFIG_LCD_LD089WU1_MIPI_M7PRO) += lcd_LD089WU1_mipi_m7pro.o
obj-$(CONFIG_LCD_PIPO_MIPI_M7PRO) += lcd_PIPO_m7pro_mipi.o
obj-$(CONFIG_LCD_CLAA101FP01_MIPI_M9PRO) += lcd_claa101fp01_mipi_m9pro.o
obj-$(CONFIG_LCD_PIPO_MIPI_M9PRO) += lcd_PIPO_m9pro_mipi.o
obj-$(CONFIG_LCD_PIPO_MIPI_U8) += lcd_PIPO_U8_mipi.o
obj-$(CONFIG_LCD_D33_MIPI_U8) += lcd_D33_U8.o
obj-$(CONFIG_LCD_B080XAN02_MIPI) += lcd_B080XAN02_mipi.o
quiet_cmd_gen = GEN $@
cmd_gen = cmp -s $< $@ || cp $< $@
lcd-obj := $(filter lcd_%.o,$(obj-y))
lcd-cfile := $(patsubst %.o,%.c,$(lcd-obj))
lcd-cpath := $(src)/$(lcd-cfile)
obj-y := $(filter-out $(lcd-obj),$(obj-y))
$(obj)/lcd.h: $(lcd-cpath) FORCE
$(call if_changed,gen)
$(obj)/rk_screen.o: $(obj)/lcd.h
obj-y += rk_screen.o
clean-files := lcd.h
| beaka/RK3188_tablet_kernel_sources | drivers/video/rockchip/screen/Makefile | Makefile | gpl-2.0 | 4,058 |
#! /usr/local/bin/ruby -Kn
# usage: exyacc.rb [yaccfiles]
# this is coverted from exyacc.pl in the camel book
ARGF.each(nil) do |source|
sbeg = source.index("\n%%") + 1
send = source.rindex("\n%%") + 1
grammar = source[sbeg, send-sbeg]
grammar.sub!(/.*\n/, "")
grammar.gsub!(/'\{'/, "'\001'")
grammar.gsub!(/'\}'/, "'\002'")
grammar.gsub!(%r{\*/}, "\003\003")
grammar.gsub!(%r{/\*[^\003]*\003\003}, '')
while grammar.gsub!(/\{[^{}]*\}/, ''); end
grammar.gsub!(/'\001'/, "'{'")
grammar.gsub!(/'\002'/, "'}'")
while grammar.gsub!(/^[ \t]*\n(\s)/, '\1'); end
grammar.gsub!(/([:|])[ \t\n]+(\w)/, '\1 \2')
print grammar
end
| atmark-techno/atmark-dist | user/ruby/ruby-2.1.2/sample/exyacc.rb | Ruby | gpl-2.0 | 648 |
#header .top-header .header-navigation ul li.menu-item-has-children .sub-menu .sub-menu{width:250px;padding-top:0;border-left:1px solid #eee;top:0;left:250px} | renatosoares/vozprofetica | wp-content/themes/illdy/layout/css/custom.min.css | CSS | gpl-2.0 | 158 |
/**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*/
package quest.beluslan;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.Npc;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.questEngine.handlers.HandlerResult;
import com.aionemu.gameserver.questEngine.handlers.QuestHandler;
import com.aionemu.gameserver.model.DialogAction;
import com.aionemu.gameserver.questEngine.model.QuestEnv;
import com.aionemu.gameserver.questEngine.model.QuestState;
import com.aionemu.gameserver.questEngine.model.QuestStatus;
import com.aionemu.gameserver.services.QuestService;
import com.aionemu.gameserver.world.zone.ZoneName;
/**
* @author Ritsu
*
*/
public class _2533BeritrasCurse extends QuestHandler {
private final static int questId = 2533;
public _2533BeritrasCurse() {
super(questId);
}
@Override
public void register() {
qe.registerQuestNpc(204801).addOnQuestStart(questId); //Gigrite
qe.registerQuestNpc(204801).addOnTalkEvent(questId);
qe.registerQuestItem(182204425, questId);//Empty Durable Potion Bottle
qe.registerOnQuestTimerEnd(questId);
}
@Override
public HandlerResult onItemUseEvent(final QuestEnv env, Item item) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs != null && qs.getStatus() == QuestStatus.START) {
if (player.isInsideZone(ZoneName.get("BERITRAS_WEAPON_220040000"))) {
QuestService.questTimerStart(env, 300);
return HandlerResult.fromBoolean(useQuestItem(env, item, 0, 1, false, 182204426, 1, 0));
}
}
return HandlerResult.SUCCESS; // ??
}
@Override
public boolean onDialogEvent(QuestEnv env) {
final Player player = env.getPlayer();
int targetId = 0;
if (env.getVisibleObject() instanceof Npc) {
targetId = ((Npc) env.getVisibleObject()).getNpcId();
}
final QuestState qs = player.getQuestStateList().getQuestState(questId);
DialogAction dialog = env.getDialog();
if (qs == null || qs.getStatus() == QuestStatus.NONE) {
if (targetId == 204801) {
if (dialog == DialogAction.QUEST_SELECT) {
return sendQuestDialog(env, 4762);
} else if (dialog == DialogAction.QUEST_ACCEPT_1) {
if (!giveQuestItem(env, 182204425, 1)) {
return true;
}
return sendQuestStartDialog(env);
} else {
return sendQuestStartDialog(env);
}
}
} else if (qs.getStatus() == QuestStatus.START) {
int var = qs.getQuestVarById(0);
if (targetId == 204801) {
switch (dialog) {
case QUEST_SELECT:
if (var == 1) {
qs.setStatus(QuestStatus.REWARD);
updateQuestStatus(env);
return sendQuestDialog(env, 1352);
}
case SELECT_QUEST_REWARD: {
QuestService.questTimerEnd(env);
return sendQuestDialog(env, 5);
}
}
}
} else if (qs.getStatus() == QuestStatus.REWARD) {
if (targetId == 204801) {
return sendQuestEndDialog(env);
}
}
return false;
}
@Override
public boolean onQuestTimerEndEvent(QuestEnv env) {
Player player = env.getPlayer();
QuestState qs = player.getQuestStateList().getQuestState(questId);
if (qs != null && qs.getStatus() == QuestStatus.START) {
removeQuestItem(env, 182204426, 1);
QuestService.abandonQuest(player, questId);
player.getController().updateNearbyQuests();
return true;
}
return false;
}
}
| GiGatR00n/Aion-Core-v4.7.5 | AC-Game/data/scripts/system/handlers/quest/beluslan/_2533BeritrasCurse.java | Java | gpl-2.0 | 5,403 |
/* Separate lexical analyzer for GNU C++.
Copyright (C) 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
1999, 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2010
Free Software Foundation, Inc.
Hacked by Michael Tiemann (tiemann@cygnus.com)
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/>. */
/* This file is the lexical analyzer for GNU C++. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "input.h"
#include "tree.h"
#include "cp-tree.h"
#include "cpplib.h"
#include "flags.h"
#include "c-family/c-pragma.h"
#include "c-family/c-objc.h"
#include "tm_p.h"
#include "timevar.h"
static int interface_strcmp (const char *);
static void init_cp_pragma (void);
static tree parse_strconst_pragma (const char *, int);
static void handle_pragma_vtable (cpp_reader *);
static void handle_pragma_unit (cpp_reader *);
static void handle_pragma_interface (cpp_reader *);
static void handle_pragma_implementation (cpp_reader *);
static void handle_pragma_java_exceptions (cpp_reader *);
static void init_operators (void);
static void copy_lang_type (tree);
/* A constraint that can be tested at compile time. */
#define CONSTRAINT(name, expr) extern int constraint_##name [(expr) ? 1 : -1]
/* Functions and data structures for #pragma interface.
`#pragma implementation' means that the main file being compiled
is considered to implement (provide) the classes that appear in
its main body. I.e., if this is file "foo.cc", and class `bar'
is defined in "foo.cc", then we say that "foo.cc implements bar".
All main input files "implement" themselves automagically.
`#pragma interface' means that unless this file (of the form "foo.h"
is not presently being included by file "foo.cc", the
CLASSTYPE_INTERFACE_ONLY bit gets set. The effect is that none
of the vtables nor any of the inline functions defined in foo.h
will ever be output.
There are cases when we want to link files such as "defs.h" and
"main.cc". In this case, we give "defs.h" a `#pragma interface',
and "main.cc" has `#pragma implementation "defs.h"'. */
struct impl_files
{
const char *filename;
struct impl_files *next;
};
static struct impl_files *impl_file_chain;
/* True if we saw "#pragma GCC java_exceptions". */
bool pragma_java_exceptions;
void
cxx_finish (void)
{
c_common_finish ();
}
/* A mapping from tree codes to operator name information. */
operator_name_info_t operator_name_info[(int) MAX_TREE_CODES];
/* Similar, but for assignment operators. */
operator_name_info_t assignment_operator_name_info[(int) MAX_TREE_CODES];
/* Initialize data structures that keep track of operator names. */
#define DEF_OPERATOR(NAME, C, M, AR, AP) \
CONSTRAINT (C, sizeof "operator " + sizeof NAME <= 256);
#include "operators.def"
#undef DEF_OPERATOR
static void
init_operators (void)
{
tree identifier;
char buffer[256];
struct operator_name_info_t *oni;
#define DEF_OPERATOR(NAME, CODE, MANGLING, ARITY, ASSN_P) \
sprintf (buffer, ISALPHA (NAME[0]) ? "operator %s" : "operator%s", NAME); \
identifier = get_identifier (buffer); \
IDENTIFIER_OPNAME_P (identifier) = 1; \
\
oni = (ASSN_P \
? &assignment_operator_name_info[(int) CODE] \
: &operator_name_info[(int) CODE]); \
oni->identifier = identifier; \
oni->name = NAME; \
oni->mangled_name = MANGLING; \
oni->arity = ARITY;
#include "operators.def"
#undef DEF_OPERATOR
operator_name_info[(int) ERROR_MARK].identifier
= get_identifier ("<invalid operator>");
/* Handle some special cases. These operators are not defined in
the language, but can be produced internally. We may need them
for error-reporting. (Eventually, we should ensure that this
does not happen. Error messages involving these operators will
be confusing to users.) */
operator_name_info [(int) INIT_EXPR].name
= operator_name_info [(int) MODIFY_EXPR].name;
operator_name_info [(int) EXACT_DIV_EXPR].name = "(ceiling /)";
operator_name_info [(int) CEIL_DIV_EXPR].name = "(ceiling /)";
operator_name_info [(int) FLOOR_DIV_EXPR].name = "(floor /)";
operator_name_info [(int) ROUND_DIV_EXPR].name = "(round /)";
operator_name_info [(int) CEIL_MOD_EXPR].name = "(ceiling %)";
operator_name_info [(int) FLOOR_MOD_EXPR].name = "(floor %)";
operator_name_info [(int) ROUND_MOD_EXPR].name = "(round %)";
operator_name_info [(int) ABS_EXPR].name = "abs";
operator_name_info [(int) TRUTH_AND_EXPR].name = "strict &&";
operator_name_info [(int) TRUTH_OR_EXPR].name = "strict ||";
operator_name_info [(int) RANGE_EXPR].name = "...";
operator_name_info [(int) UNARY_PLUS_EXPR].name = "+";
assignment_operator_name_info [(int) EXACT_DIV_EXPR].name
= "(exact /=)";
assignment_operator_name_info [(int) CEIL_DIV_EXPR].name
= "(ceiling /=)";
assignment_operator_name_info [(int) FLOOR_DIV_EXPR].name
= "(floor /=)";
assignment_operator_name_info [(int) ROUND_DIV_EXPR].name
= "(round /=)";
assignment_operator_name_info [(int) CEIL_MOD_EXPR].name
= "(ceiling %=)";
assignment_operator_name_info [(int) FLOOR_MOD_EXPR].name
= "(floor %=)";
assignment_operator_name_info [(int) ROUND_MOD_EXPR].name
= "(round %=)";
}
/* Initialize the reserved words. */
void
init_reswords (void)
{
unsigned int i;
tree id;
int mask = 0;
if (cxx_dialect < cxx0x)
mask |= D_CXX0X;
if (flag_no_asm)
mask |= D_ASM | D_EXT;
if (flag_no_gnu_keywords)
mask |= D_EXT;
/* The Objective-C keywords are all context-dependent. */
mask |= D_OBJC;
ridpointers = ggc_alloc_cleared_vec_tree ((int) RID_MAX);
for (i = 0; i < num_c_common_reswords; i++)
{
if (c_common_reswords[i].disable & D_CONLY)
continue;
id = get_identifier (c_common_reswords[i].word);
C_SET_RID_CODE (id, c_common_reswords[i].rid);
ridpointers [(int) c_common_reswords[i].rid] = id;
if (! (c_common_reswords[i].disable & mask))
C_IS_RESERVED_WORD (id) = 1;
}
}
static void
init_cp_pragma (void)
{
c_register_pragma (0, "vtable", handle_pragma_vtable);
c_register_pragma (0, "unit", handle_pragma_unit);
c_register_pragma (0, "interface", handle_pragma_interface);
c_register_pragma (0, "implementation", handle_pragma_implementation);
c_register_pragma ("GCC", "interface", handle_pragma_interface);
c_register_pragma ("GCC", "implementation", handle_pragma_implementation);
c_register_pragma ("GCC", "java_exceptions", handle_pragma_java_exceptions);
}
/* TRUE if a code represents a statement. */
bool statement_code_p[MAX_TREE_CODES];
/* Initialize the C++ front end. This function is very sensitive to
the exact order that things are done here. It would be nice if the
initialization done by this routine were moved to its subroutines,
and the ordering dependencies clarified and reduced. */
bool
cxx_init (void)
{
location_t saved_loc;
unsigned int i;
static const enum tree_code stmt_codes[] = {
CTOR_INITIALIZER, TRY_BLOCK, HANDLER,
EH_SPEC_BLOCK, USING_STMT, TAG_DEFN,
IF_STMT, CLEANUP_STMT, FOR_STMT,
RANGE_FOR_STMT, WHILE_STMT, DO_STMT,
BREAK_STMT, CONTINUE_STMT, SWITCH_STMT,
EXPR_STMT
};
memset (&statement_code_p, 0, sizeof (statement_code_p));
for (i = 0; i < ARRAY_SIZE (stmt_codes); i++)
statement_code_p[stmt_codes[i]] = true;
saved_loc = input_location;
input_location = BUILTINS_LOCATION;
init_reswords ();
init_tree ();
init_cp_semantics ();
init_operators ();
init_method ();
init_error ();
current_function_decl = NULL;
class_type_node = ridpointers[(int) RID_CLASS];
cxx_init_decl_processing ();
if (c_common_init () == false)
{
input_location = saved_loc;
return false;
}
init_cp_pragma ();
init_repo ();
input_location = saved_loc;
return true;
}
/* Return nonzero if S is not considered part of an
INTERFACE/IMPLEMENTATION pair. Otherwise, return 0. */
static int
interface_strcmp (const char* s)
{
/* Set the interface/implementation bits for this scope. */
struct impl_files *ifiles;
const char *s1;
for (ifiles = impl_file_chain; ifiles; ifiles = ifiles->next)
{
const char *t1 = ifiles->filename;
s1 = s;
if (*s1 == 0 || filename_ncmp (s1, t1, 1) != 0)
continue;
while (*s1 != 0 && filename_ncmp (s1, t1, 1) == 0)
s1++, t1++;
/* A match. */
if (*s1 == *t1)
return 0;
/* Don't get faked out by xxx.yyy.cc vs xxx.zzz.cc. */
if (strchr (s1, '.') || strchr (t1, '.'))
continue;
if (*s1 == '\0' || s1[-1] != '.' || t1[-1] != '.')
continue;
/* A match. */
return 0;
}
/* No matches. */
return 1;
}
/* Parse a #pragma whose sole argument is a string constant.
If OPT is true, the argument is optional. */
static tree
parse_strconst_pragma (const char* name, int opt)
{
tree result, x;
enum cpp_ttype t;
t = pragma_lex (&result);
if (t == CPP_STRING)
{
if (pragma_lex (&x) != CPP_EOF)
warning (0, "junk at end of #pragma %s", name);
return result;
}
if (t == CPP_EOF && opt)
return NULL_TREE;
error ("invalid #pragma %s", name);
return error_mark_node;
}
static void
handle_pragma_vtable (cpp_reader* /*dfile*/)
{
parse_strconst_pragma ("vtable", 0);
sorry ("#pragma vtable no longer supported");
}
static void
handle_pragma_unit (cpp_reader* /*dfile*/)
{
/* Validate syntax, but don't do anything. */
parse_strconst_pragma ("unit", 0);
}
static void
handle_pragma_interface (cpp_reader* /*dfile*/)
{
tree fname = parse_strconst_pragma ("interface", 1);
struct c_fileinfo *finfo;
const char *filename;
if (fname == error_mark_node)
return;
else if (fname == 0)
filename = lbasename (input_filename);
else
filename = TREE_STRING_POINTER (fname);
finfo = get_fileinfo (input_filename);
if (impl_file_chain == 0)
{
/* If this is zero at this point, then we are
auto-implementing. */
if (main_input_filename == 0)
main_input_filename = input_filename;
}
finfo->interface_only = interface_strcmp (filename);
/* If MULTIPLE_SYMBOL_SPACES is set, we cannot assume that we can see
a definition in another file. */
if (!MULTIPLE_SYMBOL_SPACES || !finfo->interface_only)
finfo->interface_unknown = 0;
}
/* Note that we have seen a #pragma implementation for the key MAIN_FILENAME.
We used to only allow this at toplevel, but that restriction was buggy
in older compilers and it seems reasonable to allow it in the headers
themselves, too. It only needs to precede the matching #p interface.
We don't touch finfo->interface_only or finfo->interface_unknown;
the user must specify a matching #p interface for this to have
any effect. */
static void
handle_pragma_implementation (cpp_reader* /*dfile*/)
{
tree fname = parse_strconst_pragma ("implementation", 1);
const char *filename;
struct impl_files *ifiles = impl_file_chain;
if (fname == error_mark_node)
return;
if (fname == 0)
{
if (main_input_filename)
filename = main_input_filename;
else
filename = input_filename;
filename = lbasename (filename);
}
else
{
filename = TREE_STRING_POINTER (fname);
if (cpp_included_before (parse_in, filename, input_location))
warning (0, "#pragma implementation for %qs appears after "
"file is included", filename);
}
for (; ifiles; ifiles = ifiles->next)
{
if (! filename_cmp (ifiles->filename, filename))
break;
}
if (ifiles == 0)
{
ifiles = XNEW (struct impl_files);
ifiles->filename = xstrdup (filename);
ifiles->next = impl_file_chain;
impl_file_chain = ifiles;
}
}
/* Indicate that this file uses Java-personality exception handling. */
static void
handle_pragma_java_exceptions (cpp_reader* /*dfile*/)
{
tree x;
if (pragma_lex (&x) != CPP_EOF)
warning (0, "junk at end of #pragma GCC java_exceptions");
choose_personality_routine (lang_java);
pragma_java_exceptions = true;
}
/* Issue an error message indicating that the lookup of NAME (an
IDENTIFIER_NODE) failed. Returns the ERROR_MARK_NODE. */
tree
unqualified_name_lookup_error (tree name)
{
if (IDENTIFIER_OPNAME_P (name))
{
if (name != ansi_opname (ERROR_MARK))
error ("%qD not defined", name);
}
else
{
if (!objc_diagnose_private_ivar (name))
{
error ("%qD was not declared in this scope", name);
suggest_alternatives_for (location_of (name), name);
}
/* Prevent repeated error messages by creating a VAR_DECL with
this NAME in the innermost block scope. */
if (local_bindings_p ())
{
tree decl;
decl = build_decl (input_location,
VAR_DECL, name, error_mark_node);
DECL_CONTEXT (decl) = current_function_decl;
push_local_binding (name, decl, 0);
/* Mark the variable as used so that we do not get warnings
about it being unused later. */
TREE_USED (decl) = 1;
}
}
return error_mark_node;
}
/* Like unqualified_name_lookup_error, but NAME is an unqualified-id
used as a function. Returns an appropriate expression for
NAME. */
tree
unqualified_fn_lookup_error (tree name)
{
if (processing_template_decl)
{
/* In a template, it is invalid to write "f()" or "f(3)" if no
declaration of "f" is available. Historically, G++ and most
other compilers accepted that usage since they deferred all name
lookup until instantiation time rather than doing unqualified
name lookup at template definition time; explain to the user what
is going wrong.
Note that we have the exact wording of the following message in
the manual (trouble.texi, node "Name lookup"), so they need to
be kept in synch. */
permerror (input_location, "there are no arguments to %qD that depend on a template "
"parameter, so a declaration of %qD must be available",
name, name);
if (!flag_permissive)
{
static bool hint;
if (!hint)
{
inform (input_location, "(if you use %<-fpermissive%>, G++ will accept your "
"code, but allowing the use of an undeclared name is "
"deprecated)");
hint = true;
}
}
return name;
}
return unqualified_name_lookup_error (name);
}
/* Wrapper around build_lang_decl_loc(). Should gradually move to
build_lang_decl_loc() and then rename build_lang_decl_loc() back to
build_lang_decl(). */
tree
build_lang_decl (enum tree_code code, tree name, tree type)
{
return build_lang_decl_loc (input_location, code, name, type);
}
/* Build a decl from CODE, NAME, TYPE declared at LOC, and then add
DECL_LANG_SPECIFIC info to the result. */
tree
build_lang_decl_loc (location_t loc, enum tree_code code, tree name, tree type)
{
tree t;
t = build_decl (loc, code, name, type);
retrofit_lang_decl (t);
return t;
}
/* Add DECL_LANG_SPECIFIC info to T. Called from build_lang_decl
and pushdecl (for functions generated by the back end). */
void
retrofit_lang_decl (tree t)
{
struct lang_decl *ld;
size_t size;
int sel;
if (TREE_CODE (t) == FUNCTION_DECL)
sel = 1, size = sizeof (struct lang_decl_fn);
else if (TREE_CODE (t) == NAMESPACE_DECL)
sel = 2, size = sizeof (struct lang_decl_ns);
else if (TREE_CODE (t) == PARM_DECL)
sel = 3, size = sizeof (struct lang_decl_parm);
else if (LANG_DECL_HAS_MIN (t))
sel = 0, size = sizeof (struct lang_decl_min);
else
gcc_unreachable ();
ld = ggc_alloc_cleared_lang_decl (size);
ld->u.base.selector = sel;
DECL_LANG_SPECIFIC (t) = ld;
if (current_lang_name == lang_name_cplusplus
|| decl_linkage (t) == lk_none)
SET_DECL_LANGUAGE (t, lang_cplusplus);
else if (current_lang_name == lang_name_c)
SET_DECL_LANGUAGE (t, lang_c);
else if (current_lang_name == lang_name_java)
SET_DECL_LANGUAGE (t, lang_java);
else
gcc_unreachable ();
if (GATHER_STATISTICS)
{
tree_node_counts[(int)lang_decl] += 1;
tree_node_sizes[(int)lang_decl] += size;
}
}
void
cxx_dup_lang_specific_decl (tree node)
{
int size;
struct lang_decl *ld;
if (! DECL_LANG_SPECIFIC (node))
return;
if (TREE_CODE (node) == FUNCTION_DECL)
size = sizeof (struct lang_decl_fn);
else if (TREE_CODE (node) == NAMESPACE_DECL)
size = sizeof (struct lang_decl_ns);
else if (TREE_CODE (node) == PARM_DECL)
size = sizeof (struct lang_decl_parm);
else if (LANG_DECL_HAS_MIN (node))
size = sizeof (struct lang_decl_min);
else
gcc_unreachable ();
ld = ggc_alloc_lang_decl (size);
memcpy (ld, DECL_LANG_SPECIFIC (node), size);
DECL_LANG_SPECIFIC (node) = ld;
if (GATHER_STATISTICS)
{
tree_node_counts[(int)lang_decl] += 1;
tree_node_sizes[(int)lang_decl] += size;
}
}
/* Copy DECL, including any language-specific parts. */
tree
copy_decl (tree decl)
{
tree copy;
copy = copy_node (decl);
cxx_dup_lang_specific_decl (copy);
return copy;
}
/* Replace the shared language-specific parts of NODE with a new copy. */
static void
copy_lang_type (tree node)
{
int size;
struct lang_type *lt;
if (! TYPE_LANG_SPECIFIC (node))
return;
if (TYPE_LANG_SPECIFIC (node)->u.h.is_lang_type_class)
size = sizeof (struct lang_type);
else
size = sizeof (struct lang_type_ptrmem);
lt = ggc_alloc_lang_type (size);
memcpy (lt, TYPE_LANG_SPECIFIC (node), size);
TYPE_LANG_SPECIFIC (node) = lt;
if (GATHER_STATISTICS)
{
tree_node_counts[(int)lang_type] += 1;
tree_node_sizes[(int)lang_type] += size;
}
}
/* Copy TYPE, including any language-specific parts. */
tree
copy_type (tree type)
{
tree copy;
copy = copy_node (type);
copy_lang_type (copy);
return copy;
}
tree
cxx_make_type (enum tree_code code)
{
tree t = make_node (code);
/* Create lang_type structure. */
if (RECORD_OR_UNION_CODE_P (code)
|| code == BOUND_TEMPLATE_TEMPLATE_PARM)
{
struct lang_type *pi
= ggc_alloc_cleared_lang_type (sizeof (struct lang_type));
TYPE_LANG_SPECIFIC (t) = pi;
pi->u.c.h.is_lang_type_class = 1;
if (GATHER_STATISTICS)
{
tree_node_counts[(int)lang_type] += 1;
tree_node_sizes[(int)lang_type] += sizeof (struct lang_type);
}
}
/* Set up some flags that give proper default behavior. */
if (RECORD_OR_UNION_CODE_P (code))
{
struct c_fileinfo *finfo = get_fileinfo (input_filename);
SET_CLASSTYPE_INTERFACE_UNKNOWN_X (t, finfo->interface_unknown);
CLASSTYPE_INTERFACE_ONLY (t) = finfo->interface_only;
}
return t;
}
tree
make_class_type (enum tree_code code)
{
tree t = cxx_make_type (code);
SET_CLASS_TYPE_P (t, 1);
return t;
}
/* Returns true if we are currently in the main source file, or in a
template instantiation started from the main source file. */
bool
in_main_input_context (void)
{
struct tinst_level *tl = outermost_tinst_level();
if (tl)
return filename_cmp (main_input_filename,
LOCATION_FILE (tl->locus)) == 0;
else
return filename_cmp (main_input_filename, input_filename) == 0;
}
| h4ck3rm1k3/gcc | gcc/cp/lex.c | C | gpl-2.0 | 19,780 |
<?php
/**
* Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
* File: form.php<br /><br />
*
* This is a very simple form sending a username and password.<br />
* It demonstrates how you can integrate the image script into your code.<br />
* By creating a new instance of the class and passing the user entered code as the only parameter, you can then immediately call $obj->checkCode() which will return true if the code is correct, or false otherwise.<br />
*
* 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 any later version.<br /><br />
*
* 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.<br /><br />
*
* 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<br /><br />
*
* Any modifications to the library should be indicated clearly in the source code
* to inform users that the changes are not a part of the original software.<br /><br />
*
* If you found this script useful, please take a quick moment to rate it.<br />
* http://www.hotscripts.com/rate/49400.html Thanks.
*
* @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
* @link http://www.phpcaptcha.org/latest.zip Download Latest Version
* @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
* @copyright 2007 Drew Phillips
* @author drew010 <drew@drew-phillips.com>
* @version 1.0.3.1 (March 23, 2008)
* @package Securimage
*
*/ ?>
<html>
<head>
<title>Securimage Test Form</title>
</head>
<body>
<?php
if (empty($_POST)) { ?>
<form method="POST">
Username:<br />
<input type="text" name="username" /><br />
Password:<br />
<input type="text" name="password" /><br />
<!-- pass a session id to the query string of the script to prevent ie caching -->
<img src="securimage_show.php?sid=<?php echo md5(uniqid(time())); ?>"><br />
<input type="text" name="code" /><br />
<input type="submit" value="Submit Form" />
</form>
<?php
} else { //form is posted
include("securimage.php");
$img = new Securimage();
$valid = $img->check($_POST['code']);
if($valid == true) {
echo "<center>Thanks, you entered the correct code.</center>";
} else {
echo "<center>Sorry, the code you entered was invalid. <a href=\"javascript:history.go(-1)\">Go back</a> to try again.</center>";
}
}
?>
</body>
</html>
| HadoDokis/OpenUpload | plugins/securimage/example_form.php | PHP | gpl-2.0 | 2,824 |
/*
** Copyright (C) 1998-2007 George Tzanetakis <gtzan@cs.uvic.ca>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef MARSYAS_STEREOSPECTRUMSOURCES_H
#define MARSYAS_STEREOSPECTRUMSOURCES_H
#include "MarSystem.h"
namespace Marsyas
{
/**
\class StereoSpectrumSources
\ingroup Analysis
\brief StereoSpectrumSources estimates the number of sources placed into different stereo positions.
After computing the Stereo Spectrum we can try to estimate the number of sources playing in different
stereo positions.
*/
class Peaker;
class StereoSpectrumSources: public MarSystem
{
private:
realvec orderedPans_;
realvec panChanges_;
realvec panPeaks_;
Peaker* panPeaker_;
void myUpdate(MarControlPtr sender);
public:
StereoSpectrumSources(std::string name);
StereoSpectrumSources(const StereoSpectrumSources& a);
~StereoSpectrumSources();
MarSystem* clone() const;
void myProcess(realvec& in, realvec& out);
};
}//namespace Marsyas
#endif
| murraymeehan/marsyas | src/marsyas/StereoSpectrumSources.h | C | gpl-2.0 | 1,667 |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
*
* 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.
*
* Copyright 2011 Red Hat, Inc.
*/
#ifndef __NETWORKMANAGER_DEVICE_INFINIBAND_H__
#define __NETWORKMANAGER_DEVICE_INFINIBAND_H__
#include "nm-device.h"
#define NM_TYPE_DEVICE_INFINIBAND (nm_device_infiniband_get_type ())
#define NM_DEVICE_INFINIBAND(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), NM_TYPE_DEVICE_INFINIBAND, NMDeviceInfiniband))
#define NM_DEVICE_INFINIBAND_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), NM_TYPE_DEVICE_INFINIBAND, NMDeviceInfinibandClass))
#define NM_IS_DEVICE_INFINIBAND(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), NM_TYPE_DEVICE_INFINIBAND))
#define NM_IS_DEVICE_INFINIBAND_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), NM_TYPE_DEVICE_INFINIBAND))
#define NM_DEVICE_INFINIBAND_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), NM_TYPE_DEVICE_INFINIBAND, NMDeviceInfinibandClass))
typedef struct _NMDeviceInfiniband NMDeviceInfiniband;
typedef struct _NMDeviceInfinibandClass NMDeviceInfinibandClass;
GType nm_device_infiniband_get_type (void);
#endif /* __NETWORKMANAGER_DEVICE_INFINIBAND_H__ */
| mar-kolya/NetworkManager | src/devices/nm-device-infiniband.h | C | gpl-2.0 | 1,929 |
/********************************************************************
KWin - the KDE window manager
This file is part of the KDE project.
Copyright (C) 2010 Thomas Lübking <thomas.luebking@web.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*********************************************************************/
#ifndef WINDOWGEOMETRY_CONFIG_H
#define WINDOWGEOMETRY_CONFIG_H
#include <kcmodule.h>
#include "ui_windowgeometry_config.h"
namespace KWin
{
class WindowGeometryConfigForm : public QWidget, public Ui::WindowGeometryConfigForm
{
Q_OBJECT
public:
explicit WindowGeometryConfigForm(QWidget* parent);
};
class WindowGeometryConfig : public KCModule
{
Q_OBJECT
public:
explicit WindowGeometryConfig(QWidget* parent = 0, const QVariantList& args = QVariantList());
~WindowGeometryConfig();
public Q_SLOTS:
void save();
void defaults();
private:
WindowGeometryConfigForm* myUi;
KActionCollection* myActionCollection;
};
} // namespace
#endif
| falbrechtskirchinger/kde-workspace | kwin/effects/windowgeometry/windowgeometry_config.h | C | gpl-2.0 | 1,567 |
<p>No API Key or List Id Exist!</p> | xTesseracTx/WP-AromatikaWebsite | wp-content/plugins/yikes-inc-easy-mailchimp-extender/templates/shortcode_error_data.php | PHP | gpl-2.0 | 35 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.dao.api;
import org.opennms.netmgt.model.OnmsMemo;
/**
* @author <a href="mailto:Markus@OpenNMS.com">Markus Neumann</a>
*/
public interface MemoDao extends OnmsDao<OnmsMemo, Integer> {
}
| rfdrake/opennms | opennms-dao-api/src/main/java/org/opennms/netmgt/dao/api/MemoDao.java | Java | gpl-2.0 | 1,404 |
<div>
{% for new in news %}
<div widget-toggle="news" id_widget_note="{{new.id_article}}">
<h2 change_key="title" replace="input">{{new.title}}</h2>
<div change_key="content" replace="ck">{{new.content}}</div>
</div>
{% endfor %}
<br clear="both">
</div> | akudryav/cms | v/themes/ura/widgets/v_news.php | PHP | gpl-2.0 | 286 |
/* -*- c-set-style: "K&R"; c-basic-offset: 8 -*-
*
* This file is part of PRoot.
*
* Copyright (C) 2014 STMicroelectronics
*
* 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.
*/
#ifndef AOXP_H
#define AOXP_H
#include <stdbool.h>
#include "tracee/reg.h"
#include "arch.h"
typedef struct array_of_xpointers ArrayOfXPointers;
typedef int (*read_xpointee_t)(ArrayOfXPointers *array, size_t index, void **object);
typedef int (*write_xpointee_t)(ArrayOfXPointers *array, size_t index, const void *object);
typedef int (*compare_xpointee_t)(ArrayOfXPointers *array, size_t index, const void *reference);
typedef int (*sizeof_xpointee_t)(ArrayOfXPointers *array, size_t index);
typedef struct mixed_pointer XPointer;
struct array_of_xpointers {
XPointer *_xpointers;
size_t length;
read_xpointee_t read_xpointee;
write_xpointee_t write_xpointee;
compare_xpointee_t compare_xpointee;
sizeof_xpointee_t sizeof_xpointee;
};
static inline int read_xpointee(ArrayOfXPointers *array, size_t index, void **object)
{
return array->read_xpointee(array, index, object);
}
static inline int write_xpointee(ArrayOfXPointers *array, size_t index, const void *object)
{
return array->write_xpointee(array, index, object);
}
static inline int compare_xpointee(ArrayOfXPointers *array, size_t index, const void *reference)
{
return array->compare_xpointee(array, index, reference);
}
static inline int sizeof_xpointee(ArrayOfXPointers *array, size_t index)
{
return array->sizeof_xpointee(array, index);
}
extern int find_xpointee(ArrayOfXPointers *array, const void *reference);
extern int resize_array_of_xpointers(ArrayOfXPointers *array, size_t index, ssize_t nb_delta_entries);
extern int fetch_array_of_xpointers(Tracee *tracee, ArrayOfXPointers **array, Reg reg, size_t nb_entries);
extern int push_array_of_xpointers(ArrayOfXPointers *array, Reg reg);
extern int read_xpointee_as_object(ArrayOfXPointers *array, size_t index, void **object);
extern int read_xpointee_as_string(ArrayOfXPointers *array, size_t index, char **string);
extern int write_xpointee_as_string(ArrayOfXPointers *array, size_t index, const char *string);
extern int write_xpointees(ArrayOfXPointers *array, size_t index, size_t nb_xpointees, ...);
extern int compare_xpointee_generic(ArrayOfXPointers *array, size_t index, const void *reference);
extern int sizeof_xpointee_as_string(ArrayOfXPointers *array, size_t index);
#endif /* AOXP_H */
| solderzzc/PRoot | src/execve/aoxp.h | C | gpl-2.0 | 3,107 |
/* packet-forces.c
* RFC 5810
* Routines for dissecting IETF ForCES protocol layer messages.Now support the following TML types:TCP+UDP,SCTP.
* Copyright 2009, NDSC & Zhejiang Gongshang University,Fenggen Jia <fgjia@mail.zjgsu.edu.cn or fenggen.jia@gmail.com>
*
* $Id$
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* 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.
*/
#include "config.h"
#include <glib.h>
#include <epan/packet.h>
#include <epan/prefs.h>
#include <epan/expert.h>
static dissector_handle_t ip_handle;
/* Initialize the ForCES protocol and registered fields */
static int proto_forces = -1;
/*Main header*/
static int hf_forces_version = -1;
static int hf_forces_rsvd = -1;
static int hf_forces_messagetype = -1;
static int hf_forces_sid = -1;
static int hf_forces_did = -1;
static int hf_forces_correlator = -1;
static int hf_forces_length = -1;
/*Flags*/
static int hf_forces_flags= -1;
static int hf_forces_flags_ack= -1;
static int hf_forces_flags_pri= -1;
static int hf_forces_flags_rsrvd= -1;
static int hf_forces_flags_em= -1;
static int hf_forces_flags_at= -1;
static int hf_forces_flags_tp= -1;
static int hf_forces_flags_reserved = -1;
static int hf_forces_tlv_type = -1;
static int hf_forces_tlv_length = -1;
/*Initiation of LFBSelect TLV*/
static int hf_forces_lfbselect_tlv_type_lfb_classid = -1;
static int hf_forces_lfbselect_tlv_type_lfb_instanceid = -1;
/*Initiation of Operation TLV*/
static int hf_forces_lfbselect_tlv_type_operation_type = -1;
static int hf_forces_lfbselect_tlv_type_operation_length = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_type = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_length = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_flags = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_flags_selector = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_flags_reserved = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_IDcount = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_IDs = -1;
static int hf_forces_lfbselect_tlv_type_operation_path_data = -1;
/*Initiation of Redirect TLV*/
static int hf_forces_redirect_tlv_meta_data_tlv_type = -1;
static int hf_forces_redirect_tlv_meta_data_tlv_length = -1;
static int hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv = -1;
static int hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_id = -1;
static int hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_length = -1;
static int hf_forces_redirect_tlv_redirect_data_tlv_type = -1;
static int hf_forces_redirect_tlv_redirect_data_tlv_length = -1;
/*Initiation of ASResult TLV*/
static int hf_forces_asresult_association_setup_result = -1;
/*Initiation of ASTreason TLV*/
static int hf_forces_astreason_tlv_teardown_reason = -1;
/*Main TLV may be unknown*/
static int hf_forces_unknown_tlv = -1;
/*Message Types */
#define AssociationSetup 0x01
#define AssociationTeardown 0x02
#define Config 0x03
#define Query 0x04
#define EventNotification 0x05
#define PacketRedirect 0x06
#define Heartbeat 0x0F
#define AssociationSetupRepsonse 0x11
#define ConfigResponse 0x13
#define QueryResponse 0x14
/*TLV Types*/
#define Reserved 0x0000
#define REDIRECT_TLV 0x0001
#define ASResult_TLV 0x0010
#define ASTreason_TLV 0x0011
#define LFBselect_TLV 0x1000
#define PATH_DATA_TLV 0x0110
#define KEYINFO_TLV 0x0111
#define FULLDATA_TLV 0x0112
#define SPARSEDATA_TLV 0x0113
#define RESULT_TLV 0x0114
#define METADATA_TLV 0x0115
#define REDIRECTDATA_TLV 0x0116
/*Operation Type*/
#define Reserved 0x0000
#define SET 0x0001
#define SET_PROP 0x0002
#define SET_RESPONSE 0x0003
#define SET_PROP_RESPONSE 0x0004
#define DEL 0x0005
#define DEL_RESPONSE 0x0006
#define GET 0x0007
#define GET_PROP 0x0008
#define GET_RESPONSE 0x0009
#define GET_PROP_RESPONSE 0x000A
#define REPORT 0x000B
#define COMMIT 0x000C
#define COMMIT_RESPONSE 0x000D
#define TRCOMP 0x000E
#define FLAG_SELECTOR 0x8000
#define ForCES_HEADER_LENGTH 24
#define TLV_TL_LENGTH 4 /*Type+length*/
#define MIN_IP_HEADER_LENGTH 20
/*For TCP+UDP TML. There are two bytes added to the ForCES PL message, not strictly combine to the ForCES protocol.
For other type TMLs,no need to add these 2 bytes.*/
#define TCP_UDP_TML_FOCES_MESSAGE_OFFSET_TCP 2
/*TCP+UDP TML*/
static guint forces_alternate_tcp_port = 0;
static guint forces_alternate_udp_port = 0;
/*SCTP TML*/
static guint forces_alternate_sctp_high_prio_channel_port = 0;
static guint forces_alternate_sctp_med_prio_channel_port = 0;
static guint forces_alternate_sctp_low_prio_channel_port = 0;
/*Initialize the subtree pointers*/
static gint ett_forces = -1;
static gint ett_forces_main_header = -1;
static gint ett_forces_flags = -1;
static gint ett_forces_tlv = -1;
static gint ett_forces_lfbselect_tlv_type = -1;
/*Operation TLV subtree*/
static gint ett_forces_lfbselect_tlv_type_operation = -1;
static gint ett_forces_lfbselect_tlv_type_operation_path = -1;
static gint ett_forces_lfbselect_tlv_type_operation_path_data = -1;
static gint ett_forces_lfbselect_tlv_type_operation_path_data_path = -1;
static gint ett_forces_path_data_tlv = -1;
static gint ett_forces_path_data_tlv_flags = -1;
/*Selector subtree*/
static gint ett_forces_lfbselect_tlv_type_operation_path_selector = -1;
/*Redirect TLV subtree*/
static gint ett_forces_redirect_tlv_type = -1;
static gint ett_forces_redirect_tlv_meta_data_tlv = -1;
static gint ett_forces_redirect_tlv_meta_data_tlv_meta_data_ilv = -1;
static gint ett_forces_redirect_tlv_redirect_data_tlv = -1;
/*ASResult TLV subtree*/
static gint ett_forces_asresult_tlv = -1;
/*ASReason subtree*/
static gint ett_forces_astreason_tlv = -1;
/*Main_TLV unknown subtree*/
static gint ett_forces_unknown_tlv = -1;
static expert_field ei_forces_length = EI_INIT;
static expert_field ei_forces_tlv_type = EI_INIT;
static expert_field ei_forces_tlv_length = EI_INIT;
static expert_field ei_forces_lfbselect_tlv_type_operation_path_length = EI_INIT;
static expert_field ei_forces_lfbselect_tlv_type_operation_type = EI_INIT;
static expert_field ei_forces_redirect_tlv_redirect_data_tlv_length = EI_INIT;
/*ACK values and the strings to be displayed*/
static const value_string main_header_flags_ack_vals[] = {
{ 0x0, "NoACK" },
{ 0x1, "SuccessACK" },
{ 0x2, "FailureACK" },
{ 0x3, "AlwaysACK" },
{ 0, NULL}
};
/*Execution mode(EM) values and the strings to be displayed*/
static const value_string main_header_flags_em_vals[] = {
{ 0x0, "Reserved" },
{ 0x1, "Execute-all-or-none" },
{ 0x2, "Execute-until-failure" },
{ 0x3, "Continue-execute-on-failure" },
{ 0, NULL}
};
/*Transaction Phase values and the strings to be displayed*/
static const value_string main_header_flags_tp_vals[] = {
{ 0x0, "SOT (Start of Transaction)" },
{ 0x1, "MOT (Middle of Transaction)" },
{ 0x2, "EOT (End of Transaction)" },
{ 0x3, "ABT (Abort)" },
{ 0, NULL}
};
/*Atomic Transaction(AT) values and the strings to be displayed*/
static const value_string main_header_flags_at_vals[] = {
{ 0x0, "Stand-alone Message"},
{ 0x1, "2PC Transaction Message"},
{ 0, NULL}
};
/*Association Setup Result*/
static const value_string association_setup_result_at_vals[] = {
{ 0x0, "success"},
{ 0x1, "FE ID invalid"},
{ 0x2, "permission denied"},
{ 0, NULL},
};
/*Teardown Reason*/
static const value_string teardown_reason_at_vals[] = {
{ 0x0, "normal-teardown by administrator"},
{ 0x1, "error - loss of heartbeats"},
{ 0x2, "error - out of bandwidth"},
{ 0x3, "error - out of memory"},
{ 0x4, "error - application crash"},
{ 0x255, "error - other or unspecified"},
{ 0, NULL},
};
static const value_string message_type_vals[] = {
{ AssociationSetup, "AssociationSetup" },
{ AssociationTeardown, "AssociationTeardown" },
{ Config, "Config" },
{ Query, "Query" },
{ EventNotification, "EventNotification" },
{ PacketRedirect, "PacketRedirect" },
{ Heartbeat, "Heartbeat" },
{ AssociationSetupRepsonse, "AssociationSetupRepsonse" },
{ ConfigResponse, "ConfigResponse" },
{ QueryResponse, "QueryResponse" },
{ 0, NULL},
};
static const value_string tlv_type_vals[] = {
{ REDIRECT_TLV, "REDIRECT-TLV" },
{ ASResult_TLV, "ASResult-TLV" },
{ ASTreason_TLV, "ASTreason-TLV" },
{ LFBselect_TLV, "LFBselect-TLV" },
{ PATH_DATA_TLV, "PATH DATA-TLV" },
{ KEYINFO_TLV, "KEYINFO-TLV" },
{ FULLDATA_TLV, "FULLDATA-TLV" },
{ SPARSEDATA_TLV, "SPARSEDATA-TLV" },
{ RESULT_TLV, "RESULT-TLV" },
{ METADATA_TLV, "METADATA-TLV" },
{ REDIRECTDATA_TLV, "REDIRECTDATA-TLV" },
{ 0, NULL},
};
static const value_string operation_type_vals[] = {
{ Reserved, "Reserved" },
{ SET, "SET" },
{ SET_PROP, "SET-PROP" },
{ SET_RESPONSE, "SET-RESPONSE" },
{ SET_PROP_RESPONSE, "SET-PROP-RESPONSE" },
{ DEL, "DEL" },
{ DEL_RESPONSE, "DEL-RESPONSE" },
{ GET, "GET" },
{ GET_PROP, "GET-PROP" },
{ GET_RESPONSE, "GET-RESPONSE" },
{ GET_PROP_RESPONSE, "GET-PROP-RESPONSE" },
{ REPORT, "REPORT" },
{ COMMIT, "COMMIT" },
{ COMMIT_RESPONSE, "COMMIT-RESPONSE" },
{ TRCOMP, "TRCOMP" },
{ 0, NULL},
};
static void
dissect_path_data_tlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset)
{
proto_item *ti, *flag_item;
guint length_TLV, IDcount, i;
guint16 type, flag;
proto_tree *tlv_tree, *path_data_tree, *flag_tree;
while (tvb_reported_length_remaining(tvb, offset) >= TLV_TL_LENGTH)
{
ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_path_data_tlv);
type = tvb_get_ntohs(tvb, offset);
proto_tree_add_item(tlv_tree, hf_forces_lfbselect_tlv_type_operation_path_type,
tvb, offset, 2, ENC_BIG_ENDIAN);
length_TLV = tvb_get_ntohs(tvb, offset+2);
proto_tree_add_item(tlv_tree, hf_forces_lfbselect_tlv_type_operation_path_length,
tvb, offset+2, 2, ENC_BIG_ENDIAN);
if (length_TLV < TLV_TL_LENGTH)
{
expert_add_info_format(pinfo, ti, &ei_forces_lfbselect_tlv_type_operation_path_length, "Bogus TLV length: %u", length_TLV);
break;
}
proto_item_set_len(ti, length_TLV);
if (type == PATH_DATA_TLV)
{
ti = proto_tree_add_text(tree, tvb, offset+TLV_TL_LENGTH, length_TLV-TLV_TL_LENGTH, "Path Data TLV");
path_data_tree = proto_item_add_subtree(ti, ett_forces_path_data_tlv);
flag = tvb_get_ntohs(tvb, offset+TLV_TL_LENGTH);
flag_item = proto_tree_add_item(path_data_tree, hf_forces_lfbselect_tlv_type_operation_path_flags,
tvb, offset+TLV_TL_LENGTH, 2, ENC_BIG_ENDIAN);
flag_tree = proto_item_add_subtree(flag_item, ett_forces_path_data_tlv_flags);
proto_tree_add_item(flag_tree, hf_forces_lfbselect_tlv_type_operation_path_flags_selector,
tvb, offset+TLV_TL_LENGTH, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(flag_tree, hf_forces_lfbselect_tlv_type_operation_path_flags_reserved,
tvb, offset+TLV_TL_LENGTH, 2, ENC_BIG_ENDIAN);
IDcount = tvb_get_ntohs(tvb, offset + TLV_TL_LENGTH + 2);
proto_tree_add_item(path_data_tree, hf_forces_lfbselect_tlv_type_operation_path_IDcount,
tvb, offset+TLV_TL_LENGTH+2, 2, ENC_BIG_ENDIAN);
for (i = 0; i < IDcount; i++)
proto_tree_add_item(path_data_tree, hf_forces_lfbselect_tlv_type_operation_path_IDs,
tvb, offset+TLV_TL_LENGTH+2+(i*4), 4, ENC_BIG_ENDIAN);
}
else
{
flag = 0;
proto_tree_add_item(tree, hf_forces_lfbselect_tlv_type_operation_path_data,
tvb, offset+TLV_TL_LENGTH, length_TLV-TLV_TL_LENGTH, ENC_NA);
}
if ((flag & FLAG_SELECTOR) == 0)
break;
offset += length_TLV;
}
}
static void
dissect_operation_tlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset, gint length_count)
{
proto_item *ti;
proto_tree *oper_tree;
guint type, length;
while (tvb_reported_length_remaining(tvb, offset) >= TLV_TL_LENGTH)
{
ti = proto_tree_add_text(tree, tvb, offset, length_count, "Operation TLV");
oper_tree = proto_item_add_subtree(ti, ett_forces_lfbselect_tlv_type_operation);
type = tvb_get_ntohs(tvb,offset);
ti = proto_tree_add_item(oper_tree, hf_forces_lfbselect_tlv_type_operation_type,
tvb, offset, 2, ENC_BIG_ENDIAN);
if (try_val_to_str(type, operation_type_vals) == NULL)
expert_add_info_format(pinfo, ti, &ei_forces_lfbselect_tlv_type_operation_type,
"Bogus: ForCES Operation TLV (Type:0x%04x) is not supported", type);
length = tvb_get_ntohs(tvb, offset+2);
proto_tree_add_uint_format_value(oper_tree, hf_forces_lfbselect_tlv_type_operation_length,
tvb, offset+2, 2, length, "%u Bytes", length);
dissect_path_data_tlv(tvb, pinfo, oper_tree, offset+TLV_TL_LENGTH);
if (length == 0)
break;
offset += length;
}
}
static void
dissect_lfbselecttlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset, gint length_count)
{
guint tlv_length;
proto_tree_add_item(tree, hf_forces_lfbselect_tlv_type_lfb_classid, tvb, offset, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(tree, hf_forces_lfbselect_tlv_type_lfb_instanceid, tvb, offset+4, 4, ENC_BIG_ENDIAN);
offset += 8;
while ((tvb_reported_length_remaining(tvb, offset) > TLV_TL_LENGTH) && (length_count > 12))
{
tlv_length = tvb_get_ntohs(tvb, offset+2);
dissect_operation_tlv(tvb, pinfo, tree, offset, tlv_length);
if (tlv_length == 0)
break;
offset += tlv_length;
}
}
static void
dissect_redirecttlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset)
{
proto_tree *meta_data_tree, *meta_data_ilv_tree, *redirect_data_tree;
gint start_offset;
gint length_meta, length_ilv, length_redirect;
proto_item *ti;
address src_addr = pinfo->src,
src_net_addr = pinfo->net_src,
dst_addr = pinfo->dst,
dst_net_addr = pinfo->net_dst;
ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "Meta Data TLV");
meta_data_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_meta_data_tlv);
proto_tree_add_item(meta_data_tree, hf_forces_redirect_tlv_meta_data_tlv_type, tvb, offset, 2, ENC_BIG_ENDIAN);
length_meta = tvb_get_ntohs(tvb, offset+2);
proto_tree_add_uint_format_value(meta_data_tree, hf_forces_redirect_tlv_meta_data_tlv_length, tvb, offset+2, 2,
length_meta, "%u Bytes", length_meta);
proto_item_set_len(ti, length_meta);
start_offset = offset;
while ((tvb_reported_length_remaining(tvb, offset) >= 8) && (start_offset+length_meta > offset))
{
ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "Meta Data ILV");
meta_data_ilv_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_meta_data_tlv_meta_data_ilv);
proto_tree_add_item(meta_data_ilv_tree, hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_id,
tvb, offset+8, 4, ENC_BIG_ENDIAN);
length_ilv = tvb_get_ntohl(tvb, offset+12);
proto_tree_add_uint_format_value(meta_data_ilv_tree, hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_length,
tvb, offset+12, 4, length_ilv, "%u Bytes", length_ilv);
if (length_ilv > 0)
proto_tree_add_item(meta_data_ilv_tree, hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv,
tvb, offset+8, length_ilv, ENC_NA);
proto_item_set_len(ti, length_ilv + 8);
offset += length_ilv + 8;
}
if (tvb_reported_length_remaining(tvb, offset) > 0)
{
ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "Redirect Data TLV");
redirect_data_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_redirect_data_tlv);
proto_tree_add_item(redirect_data_tree, hf_forces_redirect_tlv_redirect_data_tlv_type,
tvb, offset, 2, ENC_BIG_ENDIAN);
length_redirect = tvb_get_ntohs(tvb, offset+2);
proto_tree_add_uint_format_value(redirect_data_tree, hf_forces_redirect_tlv_redirect_data_tlv_length,
tvb, offset+2, 2, length_redirect, "%u Bytes", length_redirect);
if (tvb_reported_length_remaining(tvb, offset) < length_redirect)
{
expert_add_info_format(pinfo, ti, &ei_forces_redirect_tlv_redirect_data_tlv_length, "Bogus: Redirect Data TLV length (%u bytes) is wrong", length_redirect);
}
else if (length_redirect < TLV_TL_LENGTH + MIN_IP_HEADER_LENGTH)
{
expert_add_info_format(pinfo, ti, &ei_forces_redirect_tlv_redirect_data_tlv_length, "Bogus: Redirect Data TLV length (%u bytes) not big enough for IP layer", length_redirect);
}
else
{
tvbuff_t *next_tvb;
next_tvb = tvb_new_subset(tvb, offset+4, length_redirect-TLV_TL_LENGTH, length_redirect-TLV_TL_LENGTH);
call_dissector(ip_handle, next_tvb, pinfo, redirect_data_tree);
/* Restore IP info */
memcpy(&(pinfo->src), &src_addr, sizeof(address));
memcpy(&(pinfo->net_src), &src_net_addr, sizeof(address));
memcpy(&(pinfo->dst), &dst_addr, sizeof(address));
memcpy(&(pinfo->net_dst), &dst_net_addr, sizeof(address));
}
}
}
static void
dissect_forces(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset)
{
/* Set up structures needed to add the protocol subtree and manage it */
proto_item *ti, *tlv_item;
proto_tree *forces_tree, *forces_flags_tree;
proto_tree *forces_main_header_tree, *forces_tlv_tree, *tlv_tree;
gint length_count;
guint8 message_type;
guint16 tlv_type;
/* Make entries in Protocol column and Info column on summary display */
col_set_str(pinfo->cinfo, COL_PROTOCOL, "ForCES");
col_clear(pinfo->cinfo, COL_INFO);
ti = proto_tree_add_item(tree, proto_forces, tvb, 0, -1, ENC_NA);
forces_tree = proto_item_add_subtree(ti, ett_forces);
ti = proto_tree_add_text(forces_tree, tvb, 0, ForCES_HEADER_LENGTH, "Common Header");
forces_main_header_tree = proto_item_add_subtree(ti, ett_forces_main_header);
proto_tree_add_item(forces_main_header_tree, hf_forces_version, tvb, 0, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_main_header_tree, hf_forces_rsvd, tvb, 0, 1, ENC_BIG_ENDIAN);
message_type = tvb_get_guint8(tvb, offset+1);
proto_tree_add_item( forces_main_header_tree, hf_forces_messagetype, tvb, offset+1, 1, ENC_BIG_ENDIAN);
length_count = tvb_get_ntohs(tvb, offset+2) * 4; /*multiply 4 DWORD*/
ti = proto_tree_add_uint_format( forces_main_header_tree, hf_forces_length,
tvb, offset+2, 2, length_count, "Length: %u Bytes", length_count);
if (length_count != tvb_reported_length_remaining(tvb, offset))
expert_add_info_format(pinfo, ti, &ei_forces_length, "Bogus: ForCES Header length (%u bytes) is wrong),should be (%u bytes)",
length_count, tvb_reported_length_remaining(tvb, offset));
if (length_count < 24)
expert_add_info_format(pinfo, ti, &ei_forces_length, "Bogus: ForCES Header length (%u bytes) is less than 24bytes)", length_count);
col_add_fstr(pinfo->cinfo, COL_INFO, "Message Type: %s, Total Length: %u Bytes",
val_to_str(message_type, message_type_vals, "Unknown messagetype 0x%x"), length_count);
proto_tree_add_item( forces_main_header_tree, hf_forces_sid, tvb, offset+4, 4, ENC_BIG_ENDIAN);
proto_tree_add_item( forces_main_header_tree, hf_forces_did, tvb, offset+8, 4, ENC_BIG_ENDIAN);
proto_tree_add_item( forces_main_header_tree, hf_forces_correlator, tvb, offset+12, 8, ENC_BIG_ENDIAN);
/*Add flags tree*/
ti = proto_tree_add_item(forces_main_header_tree, hf_forces_flags, tvb, offset+20, 4, ENC_BIG_ENDIAN);
forces_flags_tree = proto_item_add_subtree(ti, ett_forces_flags);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_ack, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_at, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_em, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_pri, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_reserved, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_rsrvd, tvb, offset+20, 4, ENC_BIG_ENDIAN);
proto_tree_add_item(forces_flags_tree, hf_forces_flags_tp, tvb, offset+20, 4, ENC_BIG_ENDIAN);
offset += 24;
while (tvb_reported_length_remaining(tvb, offset) >= TLV_TL_LENGTH)
{
ti = proto_tree_add_text(forces_tree, tvb, offset, TLV_TL_LENGTH, "TLV");
forces_tlv_tree = proto_item_add_subtree(ti, ett_forces_tlv);
tlv_type = tvb_get_ntohs(tvb, offset);
tlv_item = proto_tree_add_item(forces_tlv_tree, hf_forces_tlv_type, tvb, offset, 2, ENC_BIG_ENDIAN);
length_count = tvb_get_ntohs(tvb, offset+2) * 4;
proto_item_set_len(ti, length_count);
ti = proto_tree_add_uint_format_value(forces_tlv_tree, hf_forces_tlv_length,
tvb, offset+2, 2, length_count, "%u Bytes", length_count);
if (tvb_reported_length_remaining(tvb, offset) < length_count)
expert_add_info_format(pinfo, ti, &ei_forces_tlv_length, "Bogus: Main TLV length (%u bytes) is wrong", length_count);
if (length_count < TLV_TL_LENGTH)
{
expert_add_info_format(pinfo, ti, &ei_forces_tlv_length, "Bogus TLV length: %u", length_count);
break;
}
offset += TLV_TL_LENGTH;
length_count -= TLV_TL_LENGTH;
switch(tlv_type)
{
case LFBselect_TLV:
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "LFB select TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_lfbselect_tlv_type);
dissect_lfbselecttlv(tvb, pinfo, tlv_tree, offset, length_count);
break;
case REDIRECT_TLV:
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "Redirect TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_type);
dissect_redirecttlv(tvb, pinfo, tlv_tree, offset);
break;
case ASResult_TLV:
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "ASResult TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_asresult_tlv);
proto_tree_add_item(tlv_tree, hf_forces_asresult_association_setup_result, tvb, offset, 4, ENC_BIG_ENDIAN);
break;
case ASTreason_TLV:
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "ASTreason TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_astreason_tlv);
proto_tree_add_item(tlv_tree, hf_forces_astreason_tlv_teardown_reason, tvb, offset, 4, ENC_BIG_ENDIAN);
break;
default:
expert_add_info(pinfo, tlv_item, &ei_forces_tlv_type);
ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "Unknown TLV");
tlv_tree = proto_item_add_subtree(ti, ett_forces_unknown_tlv);
proto_tree_add_item(tlv_tree, hf_forces_unknown_tlv, tvb, offset, length_count, ENC_NA);
break;
}
offset += length_count;
}
}
/* Code to actually dissect the TCP packets */
static void
dissect_forces_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
dissect_forces(tvb, pinfo, tree, TCP_UDP_TML_FOCES_MESSAGE_OFFSET_TCP);
}
/* Code to actually dissect the ForCES protocol layer packets,like UDP,SCTP and others */
static void
dissect_forces_not_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
dissect_forces(tvb, pinfo, tree, 0);
}
void proto_reg_handoff_forces(void);
void
proto_register_forces(void)
{
module_t *forces_module;
expert_module_t* expert_forces;
/* Setup list of header fields See Section 1.6.1 for details*/
static hf_register_info hf[] = {
{ &hf_forces_version,
{ "Version", "forces.flags.version",
FT_UINT8, BASE_DEC, NULL, 0xF0, NULL, HFILL }
},
{ &hf_forces_rsvd,
{ "Rsvd", "forces.flags.rsvd",
FT_UINT8, BASE_DEC, NULL, 0x0F, NULL, HFILL }
},
{ &hf_forces_messagetype,
{ "Message Type", "forces.messagetype",
FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_length,
{ "Header Length", "forces.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_sid,
{ "Source ID", "forces.sid",
FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_did,
{ "Destination ID", "forces.did",
FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_correlator,
{ "Correlator", "forces.correlator",
FT_UINT64, BASE_HEX, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_tlv_type,
{ "Type", "forces.tlv.type",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_tlv_length,
{ "Length", "forces.tlv.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
/*flags*/
{ &hf_forces_flags,
{ "Flags", "forces.Flags",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_flags_ack,
{ "ACK indicator", "forces.flags.ack",
FT_UINT32, BASE_DEC, VALS(main_header_flags_ack_vals), 0xC0000000, NULL, HFILL }
},
{ &hf_forces_flags_pri,
{ "Priority", "forces.flags.pri",
FT_UINT32, BASE_DEC, NULL, 0x38000000, NULL, HFILL }
},
{ &hf_forces_flags_rsrvd,
{ "Rsrvd", "forces.Flags",
FT_UINT32, BASE_DEC,NULL, 0x07000000, NULL, HFILL }
},
{ &hf_forces_flags_em,
{ "Execution mode", "forces.flags.em",
FT_UINT32, BASE_DEC, VALS(main_header_flags_em_vals), 0x00C00000, NULL, HFILL }
},
{ &hf_forces_flags_at,
{ "Atomic Transaction", "forces.flags.at",
FT_UINT32, BASE_DEC, VALS(main_header_flags_at_vals), 0x00200000, NULL, HFILL }
},
{ &hf_forces_flags_tp,
{ "Transaction phase", "forces.flags.tp",
FT_UINT32, BASE_DEC, VALS(main_header_flags_tp_vals), 0x00180000, NULL, HFILL }
},
{ &hf_forces_flags_reserved,
{ "Reserved", "forces.flags.reserved",
FT_UINT32, BASE_DEC,NULL, 0x0007ffff, NULL, HFILL }
},
/*LFBSelectTLV*/
{ &hf_forces_lfbselect_tlv_type_lfb_classid,
{ "Class ID", "forces.lfbselect.tlv.type.lfb.classid",
FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_lfb_instanceid,
{ "Instance ID", "forces.fbselect.tlv.type.lfb.instanceid",
FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
/*Operation TLV*/
{ &hf_forces_lfbselect_tlv_type_operation_type,
{ "Type", "forces.lfbselect.tlv.type.operation.type",
FT_UINT16, BASE_DEC, VALS(operation_type_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_length,
{ "Length", "forces.lfbselect.tlv.type.operation.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_type,
{ "Type", "forces.lfbselect.tlv.type.operation.path.type",
FT_UINT16, BASE_DEC, VALS(tlv_type_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_length,
{ "Length", "forces.lfbselect.tlv.type.operation.path.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_data,
{ "Data", "forces.lfbselect.tlv.type.operation.path.data",
FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_flags,
{"Path Data Flags", "forces.lfbselect.tlv.type.operation.path.data.flags",
FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_flags_selector,
{"Selector", "forces.lfbselect.tlv.type.operation.path.data.flags.selector",
FT_UINT16, BASE_HEX, NULL, 0x80, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_flags_reserved,
{"Reserved", "forces.lfbselect.tlv.type.operation.path.data.flags.reserved",
FT_UINT16, BASE_HEX, NULL, 0x7F, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_IDcount,
{ "Path Data IDcount", "forces.lfbselect.tlv.type.operation.path.data.IDcount",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_lfbselect_tlv_type_operation_path_IDs,
{ "Path Data IDs", "forces.lfbselect.tlv.type.operation.path.data.IDs",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
/*Meta data TLV*/
{&hf_forces_redirect_tlv_meta_data_tlv_type,
{ "Type", "forces.redirect.tlv.meta.data.tlv.type",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_meta_data_tlv_length,
{ "Length", "forces.redirect.tlv.meta.data.tlv.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv,
{ "Meta Data ILV", "forces.redirect.tlv.meta.data.tlv.meta.data.ilv",
FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_id,
{ "ID", "forces.redirect.tlv.meta.data.tlv.meta.data.ilv.id",
FT_UINT32, BASE_HEX_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_length,
{ "Length", "forces.redirect.tlv.meta.data.tlv.meta.data.ilv.length",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_redirect_data_tlv_type,
{ "Type", "forces.redirect.tlv.redirect.data.tlv.type",
FT_UINT16, BASE_DEC, VALS(tlv_type_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_redirect_tlv_redirect_data_tlv_length,
{ "Length", "forces.redirect.tlv.redirect.data.tlv.length",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }
},
{ &hf_forces_asresult_association_setup_result,
{ "Association Setup Result", "forces.teardown.reason",
FT_UINT32, BASE_DEC, VALS(association_setup_result_at_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_astreason_tlv_teardown_reason,
{ "AStreason TLV TearDonw Reason", "forces.astreason.tlv.teardonw.reason",
FT_UINT32, BASE_DEC, VALS(teardown_reason_at_vals), 0x0, NULL, HFILL }
},
{ &hf_forces_unknown_tlv,
{ "Data", "forces.unknown.tlv",
FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }
}
};
/* Setup protocol subtree array */
static gint *ett[] = {
&ett_forces,
&ett_forces_main_header,
&ett_forces_flags,
&ett_forces_tlv,
&ett_forces_lfbselect_tlv_type,
&ett_forces_lfbselect_tlv_type_operation,
&ett_forces_lfbselect_tlv_type_operation_path,
&ett_forces_lfbselect_tlv_type_operation_path_data,
&ett_forces_lfbselect_tlv_type_operation_path_data_path,
&ett_forces_lfbselect_tlv_type_operation_path_selector,
&ett_forces_path_data_tlv,
&ett_forces_path_data_tlv_flags,
&ett_forces_redirect_tlv_type,
&ett_forces_redirect_tlv_meta_data_tlv,
&ett_forces_redirect_tlv_redirect_data_tlv,
&ett_forces_redirect_tlv_meta_data_tlv_meta_data_ilv,
&ett_forces_asresult_tlv,
&ett_forces_astreason_tlv,
&ett_forces_unknown_tlv
};
static ei_register_info ei[] = {
{ &ei_forces_length, { "forces.length.bad", PI_PROTOCOL, PI_WARN, "ForCES Header length is wrong", EXPFILL }},
{ &ei_forces_tlv_type, { "forces.tlv.type.unknown", PI_PROTOCOL, PI_WARN, "Bogus: The Main_TLV type is unknown", EXPFILL }},
{ &ei_forces_tlv_length, { "forces.tlv.length.bad", PI_PROTOCOL, PI_WARN, "Bogus TLV length", EXPFILL }},
{ &ei_forces_lfbselect_tlv_type_operation_path_length, { "forces.lfbselect.tlv.type.operation.path.length.bad", PI_PROTOCOL, PI_WARN, "Bogus TLV length", EXPFILL }},
{ &ei_forces_lfbselect_tlv_type_operation_type, { "forces.lfbselect.tlv.type.operation.type.unsupported", PI_PROTOCOL, PI_WARN, "ForCES Operation TLV is not supported", EXPFILL }},
{ &ei_forces_redirect_tlv_redirect_data_tlv_length, { "forces.redirect.tlv.redirect.data.tlv.length.bad", PI_PROTOCOL, PI_WARN, "Redirect Data TLV length is wrong", EXPFILL }},
};
/* Register the protocol name and description */
proto_forces = proto_register_protocol("Forwarding and Control Element Separation Protocol", "ForCES", "forces");
/* Required function calls to register the header fields and subtrees used */
proto_register_field_array(proto_forces, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_forces = expert_register_protocol(proto_forces);
expert_register_field_array(expert_forces, ei, array_length(ei));
forces_module = prefs_register_protocol(proto_forces,proto_reg_handoff_forces);
prefs_register_uint_preference(forces_module, "tcp_alternate_port",
"TCP port",
"Decode packets on this TCP port as ForCES",
10, &forces_alternate_tcp_port);
prefs_register_uint_preference(forces_module, "udp_alternate_port",
"UDP port",
"Decode packets on this UDP port as ForCES",
10, &forces_alternate_udp_port);
prefs_register_uint_preference(forces_module, "sctp_high_prio_port",
"SCTP High Priority channel port",
"Decode packets on this sctp port as ForCES",
10, &forces_alternate_sctp_high_prio_channel_port);
prefs_register_uint_preference(forces_module, "sctp_med_prio_port",
"SCTP Meidium Priority channel port",
"Decode packets on this sctp port as ForCES",
10, &forces_alternate_sctp_med_prio_channel_port);
prefs_register_uint_preference(forces_module, "sctp_low_prio_port",
"SCTP Low Priority channel port",
"Decode packets on this sctp port as ForCES",
10, &forces_alternate_sctp_low_prio_channel_port);
}
void
proto_reg_handoff_forces(void)
{
static gboolean inited = FALSE;
static guint alternate_tcp_port = 0; /* 3000 */
static guint alternate_udp_port = 0;
static guint alternate_sctp_high_prio_channel_port = 0; /* 6700 */
static guint alternate_sctp_med_prio_channel_port = 0;
static guint alternate_sctp_low_prio_channel_port = 0;
static dissector_handle_t forces_handle_tcp, forces_handle;
if (!inited) {
forces_handle_tcp = create_dissector_handle(dissect_forces_tcp, proto_forces);
forces_handle = create_dissector_handle(dissect_forces_not_tcp, proto_forces);
ip_handle = find_dissector("ip");
inited = TRUE;
}
/* Register TCP port for dissection */
if ((alternate_tcp_port != 0) && (alternate_tcp_port != forces_alternate_tcp_port))
dissector_delete_uint("tcp.port", alternate_tcp_port, forces_handle_tcp);
if ((forces_alternate_tcp_port != 0) && (alternate_tcp_port != forces_alternate_tcp_port))
dissector_add_uint("tcp.port", forces_alternate_tcp_port, forces_handle_tcp);
alternate_tcp_port = forces_alternate_tcp_port;
/* Register UDP port for dissection */
if ((alternate_udp_port != 0) && (alternate_udp_port != forces_alternate_udp_port))
dissector_delete_uint("udp.port", alternate_udp_port, forces_handle);
if ((forces_alternate_udp_port != 0) && (alternate_udp_port != forces_alternate_udp_port))
dissector_add_uint("udp.port", forces_alternate_udp_port, forces_handle);
alternate_udp_port = forces_alternate_udp_port;
/* Register SCTP port for high priority dissection */
if ((alternate_sctp_high_prio_channel_port != 0) &&
(alternate_sctp_high_prio_channel_port != forces_alternate_sctp_high_prio_channel_port))
dissector_delete_uint("sctp.port", alternate_sctp_high_prio_channel_port, forces_handle);
if ((forces_alternate_sctp_high_prio_channel_port != 0) &&
(alternate_sctp_high_prio_channel_port != forces_alternate_sctp_high_prio_channel_port))
dissector_add_uint("sctp.port", forces_alternate_sctp_high_prio_channel_port, forces_handle);
alternate_sctp_high_prio_channel_port = forces_alternate_sctp_high_prio_channel_port;
/* Register SCTP port for medium priority dissection */
if ((alternate_sctp_med_prio_channel_port != 0) &&
(alternate_sctp_med_prio_channel_port != forces_alternate_sctp_med_prio_channel_port))
dissector_delete_uint("udp.port", alternate_sctp_med_prio_channel_port, forces_handle);
if ((forces_alternate_sctp_med_prio_channel_port != 0) &&
(alternate_sctp_med_prio_channel_port != forces_alternate_sctp_med_prio_channel_port))
dissector_add_uint("udp.port", forces_alternate_sctp_med_prio_channel_port, forces_handle);
alternate_sctp_med_prio_channel_port = forces_alternate_sctp_med_prio_channel_port;
/* Register SCTP port for low priority dissection */
if ((alternate_sctp_low_prio_channel_port != 0) &&
(alternate_sctp_low_prio_channel_port != forces_alternate_sctp_low_prio_channel_port))
dissector_delete_uint("udp.port", alternate_sctp_low_prio_channel_port, forces_handle);
if ((forces_alternate_sctp_low_prio_channel_port != 0) &&
(alternate_sctp_low_prio_channel_port != forces_alternate_sctp_low_prio_channel_port))
dissector_add_uint("udp.port", forces_alternate_sctp_low_prio_channel_port, forces_handle);
alternate_sctp_low_prio_channel_port = forces_alternate_sctp_low_prio_channel_port;
}
/*
* 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:
*/
| slowfranklin/wireshark | epan/dissectors/packet-forces.c | C | gpl-2.0 | 41,483 |
package lejos.robotics.mapping;
import java.io.*;
import java.util.ArrayList;
import lejos.geom.Line;
import lejos.geom.Rectangle;
/*
* WARNING: THIS CLASS IS SHARED BETWEEN THE classes AND pccomms PROJECTS.
* DO NOT EDIT THE VERSION IN pccomms AS IT WILL BE OVERWRITTEN WHEN THE PROJECT IS BUILT.
*/
/**
* <p>This class loads map data from a Shapefile and produces a LineMap object, which can
* be used by the leJOS navigation package.</p>
*
* <p>There are many map editors which can use the Shapefile format (OpenEV, Global Mapper). Once you
* have created a map, export it as Shapefile. This will produce three files ending in .shp .shx and
* .dbf. The only file used by this class is .shp.</p>
*
* <p>NOTE: Shapefiles can only contain one type of shape data (polygon or polyline, not both). A single file can't
* mix polylines with polygons.</p>
*
* <p>This class' code can parse points and multipoints. However, a LineMap object can't deal with
* points (only lines) so points and multipoints are discarded.</p>
*
* @author BB
*
*/
public class ShapefileLoader {
/* OTHER POTENTIAL MAP FILE FORMATS TO ADD:
* (none have really been researched yet for viability)
* KML
* GML
* WMS? (more of a service than a file)
* MIF/MID (MapInfo)
* SVG (Scalable Vector Graphics)
* EPS (Encapsulated Post Script)
* DXF (Autodesk)
* AI (Adobe Illustrator)
*
*/
// 2D shape types types:
private static final byte NULL_SHAPE = 0;
private static final byte POINT = 1;
private static final byte POLYLINE = 3;
private static final byte POLYGON = 5;
private static final byte MULTIPOINT = 8;
private final int SHAPEFILE_ID = 0x0000270a;
DataInputStream data_is = null;
/**
* Creates a ShapefileLoader object using an input stream. Likely you will use a FileInputStream
* which points to the *.shp file containing the map data.
* @param in
*/
public ShapefileLoader(InputStream in) {
this.data_is = new DataInputStream(in);
}
/**
* Retrieves a LineMap object from the Shapefile input stream.
* @return the line map
* @throws IOException
*/
public LineMap readLineMap() throws IOException {
ArrayList <Line> lines = new ArrayList <Line> ();
int fileCode = data_is.readInt(); // Big Endian
if(fileCode != SHAPEFILE_ID) throw new IOException("File is not a Shapefile");
data_is.skipBytes(20); // Five int32 unused by Shapefile
/*int fileLength =*/ data_is.readInt();
//System.out.println("Length: " + fileLength); // TODO: Docs say length is in 16-bit words. Unsure if this is strictly correct. Seems higher than what hex editor shows.
/*int version =*/ readLEInt();
//System.out.println("Version: " + version);
/*int shapeType =*/ readLEInt();
//System.out.println("Shape type: " + shapeType);
// These x and y min/max values define bounding rectangle:
double xMin = readLEDouble();
double yMin = readLEDouble();
double xMax = readLEDouble();
double yMax = readLEDouble();
// Create bounding rectangle:
Rectangle rect = new Rectangle((float)xMin, (float)yMin, (float)(xMax - xMin), (float)(yMax - yMin));
/*double zMin =*/ readLEDouble();
/*double zMax =*/ readLEDouble();
/*double mMin =*/ readLEDouble();
/*double mMax =*/ readLEDouble();
// TODO These values seem to be rounded down to nearest 0.5. Must round them up?
//System.out.println("Xmin " + xMin + " Ymin " + yMin);
//System.out.println("Xmax " + xMax + " Ymax " + yMax);
try { // TODO: This is a cheesy way to detect EOF condition. Not very good coding.
while(2 > 1) { // TODO: Temp code to keep it looping. Should really detect EOF condition.
// NOW ONTO READING INDIVIDUAL SHAPES:
// Record Header (2 values):
/*int recordNum =*/ data_is.readInt();
int recordLen = data_is.readInt(); // TODO: in 16-bit words. Might cause bug if number of shapes gets bigger than 16-bit short?
// Record (variable length depending on shape type):
int recShapeType = readLEInt();
// Now to read the actual shape data
switch (recShapeType) {
case NULL_SHAPE:
break;
case POINT:
// DO WE REALLY NEED TO DEAL WITH POINT? Feature might use them possibly.
/*double pointX =*/ readLEDouble(); // TODO: skip bytes instead
/*double pointY =*/ readLEDouble();
break;
case POLYLINE:
// NOTE: Data structure for polygon/polyline is identical. Code should work for both.
case POLYGON:
// Polygons can contain multiple polygons, such as a donut with outer ring and inner ring for hole.
// Max bounding rect: 4 doubles in a row. TODO: Discard bounding rect. values and skip instead.
/*double polyxMin =*/ readLEDouble();
/*double polyyMin =*/ readLEDouble();
/*double polyxMax =*/ readLEDouble();
/*double polyyMax =*/ readLEDouble();
int numParts = readLEInt();
int numPoints = readLEInt();
// Retrieve array of indexes for each part in the polygon
int [] partIndex = new int[numParts];
for(int i=0;i<numParts;i++) {
partIndex[i] = readLEInt();
}
// Now go through numParts times pulling out points
double firstX=0;
double firstY=0;
for(int i=0;i<numPoints-1;i++) {
// Could check here if onto new polygon (i = next index). If so, do something with line formation.
for(int j=0;j<numParts;j++) {
if(i == partIndex[j]) {
firstX = readLEDouble();
firstY = readLEDouble();
continue;
}
}
double secondX = readLEDouble();
double secondY = readLEDouble();
Line myLine = new Line((float)firstX, (float)firstY, (float)secondX, (float)secondY);
lines.add(myLine);
firstX = secondX;
firstY = secondY;
}
break;
case MULTIPOINT:
// TODO: DO WE REALLY NEED TO DEAL WITH MULTIPOINT? Comment out and skip bytes?
/*double multixMin = */readLEDouble();
/*double multiyMin = */readLEDouble();
/*double multixMax = */readLEDouble();
/*double multiyMax = */readLEDouble();
int multiPoints = readLEInt();
double [] xVals = new double[multiPoints];
double [] yVals = new double[multiPoints];
for(int i=0;i<multiPoints;i++) {
xVals[i] = readLEDouble();
yVals[i] = readLEDouble();
}
break;
default:
// IGNORE REST OF SHAPE TYPES and skip over data using recordLen value
//System.out.println("Some other unknown shape");
data_is.skipBytes(recordLen); // TODO: Check if this works on polyline or point
}
} // END OF WHILE
} catch(EOFException e) {
// End of File, just needs to continue
}
Line [] arrList = new Line [lines.size()];
return new LineMap(lines.toArray(arrList), rect);
}
/**
* Translates a little endian int into a big endian int
*
* @return int A big endian int
*/
private int readLEInt() throws IOException {
int byte1, byte2, byte3, byte4;
synchronized (this) {
byte1 = data_is.read();
byte2 = data_is.read();
byte3 = data_is.read();
byte4 = data_is.read();
}
if (byte4 == -1) {
throw new EOFException();
}
return (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1;
}
/**
* Reads a little endian double into a big endian double
*
* @return double A big endian double
*/
private final double readLEDouble() throws IOException {
return Double.longBitsToDouble(this.readLELong());
}
/**
* Translates a little endian long into a big endian long
*
* @return long A big endian long
*/
private long readLELong() throws IOException {
long byte1 = data_is.read();
long byte2 = data_is.read();
long byte3 = data_is.read();
long byte4 = data_is.read();
long byte5 = data_is.read();
long byte6 = data_is.read();
long byte7 = data_is.read();
long byte8 = data_is.read();
if (byte8 == -1) {
throw new EOFException();
}
return (byte8 << 56) + (byte7 << 48) + (byte6 << 40) + (byte5 << 32)
+ (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1;
}
}
| atsoc0ocsav/IEEE-Firefighter | ieeefirefighter-beta/pc/pccomm-src/lejos/robotics/mapping/ShapefileLoader.java | Java | gpl-2.0 | 9,323 |
/*
* This file is part of the coreboot project.
*
* Copyright 2014 Google Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <arch/io.h>
#include <gpio.h>
#include <reset.h>
#include "board.h"
void hard_reset(void)
{
gpio_output(GPIO_RESET, 1);
while (1)
;
}
| acorn-marvell/coreboot | src/mainboard/google/veyron_rialto/reset.c | C | gpl-2.0 | 902 |
<?php
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2013 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk 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 in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# ails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
$queue = str_replace("_", " ", substr($servicedesc, 6));
$opt[1] = "--vertical-label 'Queue length' -l0 --title \"$hostname / Exchange Queue: $queue\" ";
$def[1] = "DEF:length=$RRDFILE[1]:$DS[1]:MAX ";
$def[1] .= "AREA:length#6090ff:\"length\" ";
$def[1] .= "LINE:length#304f80 ";
$def[1] .= "GPRINT:length:LAST:\"last\: %.0lf %s\" ";
$def[1] .= "GPRINT:length:AVERAGE:\"average\: %.0lf %s\" ";
$def[1] .= "GPRINT:length:MAX:\"max\:%.0lf %s\\n\" ";
?>
| opinkerfi/check_mk | pnp-templates/check_mk-winperf_msx_queues.php | PHP | gpl-2.0 | 1,870 |
<?php
/**
* @file
* Contains \Drupal\google_analytics_reports\Routing\RouteSubscriber.
*/
namespace Drupal\google_analytics_reports\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Subscriber for google analytics reports routes.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('google_analytics_reports_api.settings')) {
$route->setDefault('_form', 'Drupal\google_analytics_reports\Form\GoogleAnalyticsReportsAdminSettingsForm');
}
}
}
| yonashaile/google_analytics_reports | src/Routing/RouteSubscriber.php | PHP | gpl-2.0 | 651 |
/* Duplicate handle for selection of locales.
Copyright (C) 1997, 2000, 2001 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <locale.h>
#include <bits/libc-lock.h>
#include <stdlib.h>
#include <localeinfo.h>
/* Lock for protecting global data. */
__libc_lock_define (extern , __libc_setlocale_lock)
__locale_t
__duplocale (__locale_t dataset)
{
__locale_t result;
/* We modify global data. */
__libc_lock_lock (__libc_setlocale_lock);
/* Get memory. */
result = (__locale_t) malloc (sizeof (struct __locale_struct));
if (result != NULL)
{
int cnt;
for (cnt = 0; cnt < __LC_LAST; ++cnt)
if (cnt != LC_ALL)
{
result->__locales[cnt] = dataset->__locales[cnt];
if (result->__locales[cnt]->usage_count < MAX_USAGE_COUNT)
++result->__locales[cnt]->usage_count;
}
}
/* Update the special members. */
result->__ctype_b = dataset->__ctype_b;
result->__ctype_tolower = dataset->__ctype_tolower;
result->__ctype_toupper = dataset->__ctype_toupper;
/* It's done. */
__libc_lock_unlock (__libc_setlocale_lock);
return result;
}
| nslu2/glibc | locale/duplocale.c | C | gpl-2.0 | 1,954 |
/* packet-bpkmreq.c
* Routines for Baseline Privacy Key Management Request dissection
* Copyright 2002, Anand V. Narwani <anand[AT]narwani.org>
*
* $Id: packet-bpkmreq.c 45015 2012-09-20 01:29:52Z morriss $
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* 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.
*/
#include "config.h"
#include <epan/packet.h>
/* Initialize the protocol and registered fields */
static int proto_docsis_bpkmreq = -1;
static int hf_docsis_bpkmreq_code = -1;
static int hf_docsis_bpkmreq_length = -1;
static int hf_docsis_bpkmreq_ident = -1;
static const value_string code_field_vals[] = {
{0, "Reserved"},
{1, "Reserved"},
{2, "Reserved"},
{3, "Reserved"},
{4, "Auth Request"},
{5, "Auth Reply"},
{6, "Auth Reject"},
{7, "Key Request"},
{8, "Key Reply"},
{9, "Key Reject"},
{10, "Auth Invalid"},
{11, "TEK Invalid"},
{12, "Authent Info"},
{13, "Map Request"},
{14, "Map Reply"},
{15, "Map Reject"},
{0, NULL},
};
/* Initialize the subtree pointers */
static gint ett_docsis_bpkmreq = -1;
static dissector_handle_t attrs_handle;
/* Code to actually dissect the packets */
static void
dissect_bpkmreq (tvbuff_t * tvb, packet_info * pinfo, proto_tree * tree)
{
proto_item *it;
proto_tree *bpkmreq_tree;
guint8 code;
tvbuff_t *attrs_tvb;
code = tvb_get_guint8 (tvb, 0);
col_add_fstr (pinfo->cinfo, COL_INFO, "BPKM Request (%s)",
val_to_str (code, code_field_vals, "%d"));
if (tree)
{
it =
proto_tree_add_protocol_format (tree, proto_docsis_bpkmreq, tvb, 0, -1,
"BPKM Request Message");
bpkmreq_tree = proto_item_add_subtree (it, ett_docsis_bpkmreq);
proto_tree_add_item (bpkmreq_tree, hf_docsis_bpkmreq_code, tvb, 0, 1,
ENC_BIG_ENDIAN);
proto_tree_add_item (bpkmreq_tree, hf_docsis_bpkmreq_ident, tvb, 1, 1,
ENC_BIG_ENDIAN);
proto_tree_add_item (bpkmreq_tree, hf_docsis_bpkmreq_length, tvb, 2, 2,
ENC_BIG_ENDIAN);
}
/* Code to Call subdissector */
attrs_tvb = tvb_new_subset_remaining (tvb, 4);
call_dissector (attrs_handle, attrs_tvb, pinfo, tree);
}
/* Register the protocol with Wireshark */
/* this format is require because a script is used to build the C function
that calls all the protocol registration.
*/
void
proto_register_docsis_bpkmreq (void)
{
/* Setup list of header fields See Section 1.6.1 for details*/
static hf_register_info hf[] = {
{&hf_docsis_bpkmreq_code,
{"BPKM Code", "docsis_bpkmreq.code",
FT_UINT8, BASE_DEC, VALS (code_field_vals), 0x0,
"BPKM Request Message", HFILL}
},
{&hf_docsis_bpkmreq_ident,
{"BPKM Identifier", "docsis_bpkmreq.ident",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL}
},
{&hf_docsis_bpkmreq_length,
{"BPKM Length", "docsis_bpkmreq.length",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL}
},
};
/* Setup protocol subtree array */
static gint *ett[] = {
&ett_docsis_bpkmreq,
};
/* Register the protocol name and description */
proto_docsis_bpkmreq =
proto_register_protocol ("DOCSIS Baseline Privacy Key Management Request",
"DOCSIS BPKM-REQ", "docsis_bpkmreq");
/* Required function calls to register the header fields and subtrees used */
proto_register_field_array (proto_docsis_bpkmreq, hf, array_length (hf));
proto_register_subtree_array (ett, array_length (ett));
register_dissector ("docsis_bpkmreq", dissect_bpkmreq,
proto_docsis_bpkmreq);
}
/* If this dissector uses sub-dissector registration add a registration routine.
This format is required because a script is used to find these routines and
create the code that calls these routines.
*/
void
proto_reg_handoff_docsis_bpkmreq (void)
{
dissector_handle_t docsis_bpkmreq_handle;
docsis_bpkmreq_handle = find_dissector ("docsis_bpkmreq");
attrs_handle = find_dissector ("docsis_bpkmattr");
dissector_add_uint ("docsis_mgmt", 0x0C, docsis_bpkmreq_handle);
}
| P1sec/LTE_monitor_c2xx | wireshark/plugins/docsis/packet-bpkmreq.c | C | gpl-2.0 | 4,716 |
<?php
declare(strict_types=1);
namespace PhpMyAdmin\Tests\Controllers\Database\Structure;
use PhpMyAdmin\Controllers\Database\Structure\RealRowCountController;
use PhpMyAdmin\Template;
use PhpMyAdmin\Tests\AbstractTestCase;
use PhpMyAdmin\Tests\Stubs\ResponseRenderer as ResponseStub;
use function json_encode;
/**
* @covers \PhpMyAdmin\Controllers\Database\Structure\RealRowCountController
*/
class RealRowCountControllerTest extends AbstractTestCase
{
public function testRealRowCount(): void
{
$GLOBALS['server'] = 1;
$GLOBALS['text_dir'] = 'ltr';
$GLOBALS['PMA_PHP_SELF'] = 'index.php';
$GLOBALS['cfg']['Server']['DisableIS'] = true;
$GLOBALS['is_db'] = true;
$GLOBALS['db'] = 'world';
$response = new ResponseStub();
$response->setAjax(true);
$_REQUEST['table'] = 'City';
(new RealRowCountController($response, new Template(), $this->dbi))();
$json = $response->getJSONResult();
$this->assertEquals('4,079', $json['real_row_count']);
$_REQUEST['real_row_count_all'] = 'on';
(new RealRowCountController($response, new Template(), $this->dbi))();
$json = $response->getJSONResult();
$expected = [
['table' => 'City', 'row_count' => 4079],
['table' => 'Country', 'row_count' => 239],
['table' => 'CountryLanguage', 'row_count' => 984],
];
$this->assertEquals(json_encode($expected), $json['real_row_count_all']);
}
}
| phpmyadmin/phpmyadmin | test/classes/Controllers/Database/Structure/RealRowCountControllerTest.php | PHP | gpl-2.0 | 1,525 |
//
// This file was automatically generated by wxrc, do not edit by hand.
//
#include <wx/wxprec.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include <wx/filesys.h>
#include <wx/fs_mem.h>
#include <wx/xrc/xmlres.h>
#include <wx/xrc/xh_all.h>
#if wxCHECK_VERSION(2,8,5) && wxABI_VERSION >= 20805
#define XRC_ADD_FILE(name, data, size, mime) \
wxMemoryFSHandler::AddFileWithMimeType(name, data, size, mime)
#else
#define XRC_ADD_FILE(name, data, size, mime) \
wxMemoryFSHandler::AddFile(name, data, size)
#endif
static size_t xml_res_size_0 = 137;
static unsigned char xml_res_file_0[] = {
60,63,120,109,108,32,118,101,114,115,105,111,110,61,34,49,46,48,34,32,101,
110,99,111,100,105,110,103,61,34,85,84,70,45,56,34,63,62,10,60,114,101,
115,111,117,114,99,101,32,120,109,108,110,115,61,34,104,116,116,112,58,
47,47,119,119,119,46,119,120,119,105,100,103,101,116,115,46,111,114,103,
47,119,120,120,114,99,34,62,10,32,32,60,33,45,45,32,72,97,110,100,108,101,
114,32,71,101,110,101,114,97,116,105,111,110,32,105,115,32,79,78,32,45,
45,62,10,60,47,114,101,115,111,117,114,99,101,62,10};
void wxC47E7InitBitmapResources()
{
// Check for memory FS. If not present, load the handler:
{
wxMemoryFSHandler::AddFile(wxT("XRC_resource/dummy_file"), wxT("dummy one"));
wxFileSystem fsys;
wxFSFile *f = fsys.OpenFile(wxT("memory:XRC_resource/dummy_file"));
wxMemoryFSHandler::RemoveFile(wxT("XRC_resource/dummy_file"));
if (f) delete f;
else wxFileSystem::AddHandler(new wxMemoryFSHandlerBase);
}
XRC_ADD_FILE(wxT("XRC_resource/continousbuildbasepane_continuousbuild_bitmaps.cpp$C__src_codelite_ContinuousBuild_continousbuildbasepane_continuousbuild_bitmaps.xrc"), xml_res_file_0, xml_res_size_0, wxT("text/xml"));
wxXmlResource::Get()->Load(wxT("memory:XRC_resource/continousbuildbasepane_continuousbuild_bitmaps.cpp$C__src_codelite_ContinuousBuild_continousbuildbasepane_continuousbuild_bitmaps.xrc"));
}
| eranif/codelite | ContinuousBuild/continousbuildbasepane_continuousbuild_bitmaps.cpp | C++ | gpl-2.0 | 2,047 |
<?php
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
*/
namespace Google\AdsApi\Examples\AdWords\v201609\Reporting;
require '../../../../vendor/autoload.php';
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Reporting\v201609\ReportDownloader;
use Google\AdsApi\AdWords\Reporting\v201609\DownloadFormat;
use Google\AdsApi\AdWords\ReportSettingsBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
/**
* Downloads CRITERIA_PERFORMANCE_REPORT for the specified client customer ID.
*/
class DownloadCriteriaReportWithAwql {
public static function runExample(AdWordsSession $session, $reportFormat) {
// Create report query to get the data for last 7 days.
$reportQuery = 'SELECT CampaignId, AdGroupId, Id, Criteria, CriteriaType, '
. 'Impressions, Clicks, Cost FROM CRITERIA_PERFORMANCE_REPORT '
. 'WHERE Status IN [ENABLED, PAUSED] DURING LAST_7_DAYS';
// Download report as a string.
$reportDownloader = new ReportDownloader($session);
$reportDownloadResult = $reportDownloader->downloadReportWithAwql(
$reportQuery, $reportFormat);
print "Report was downloaded and printed below:\n";
print $reportDownloadResult->getAsString();
}
public static function main() {
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile()
->build();
// See: ReportSettingsBuilder for more options (e.g., suppress headers)
// or set them in your adsapi_php.ini file.
$reportSettings = (new ReportSettingsBuilder())
->fromFile()
->includeZeroImpressions(false)
->build();
// See: AdWordsSessionBuilder for setting a client customer ID that is
// different from that specified in your adsapi_php.ini file.
// Construct an API session configured from a properties file and the OAuth2
// credentials above.
$session = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->withReportSettings($reportSettings)
->build();
self::runExample($session, DownloadFormat::CSV);
}
}
DownloadCriteriaReportWithAwql::main();
| renshuki/dfp-manager | vendor/googleads/googleads-php-lib/examples/AdWords/v201609/Reporting/DownloadCriteriaReportWithAwql.php | PHP | gpl-2.0 | 2,811 |
-- license:BSD-3-Clause
-- copyright-holders:MAMEdev Team
---------------------------------------------------------------------------
--
-- tools.lua
--
-- Rules for the building of tools
--
---------------------------------------------------------------------------
--------------------------------------------------
-- romcmp
--------------------------------------------------
project("romcmp")
uuid ("1b40275b-194c-497b-8abd-9338775a21b8")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/romcmp.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- chdman
--------------------------------------------------
project("chdman")
uuid ("7d948868-42db-432a-9bb5-70ce5c5f4620")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
}
includedirs {
ext_includedir("flac"),
}
files {
MAME_DIR .. "src/tools/chdman.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
MAME_DIR .. "src/version.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- jedutil
--------------------------------------------------
project("jedutil")
uuid ("bda60edb-f7f5-489f-b232-23d33c43dda1")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/jedutil.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- unidasm
--------------------------------------------------
project("unidasm")
uuid ("65f81d3b-299a-4b08-a3fa-d5241afa9fd1")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"dasm",
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/emu",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
}
files {
MAME_DIR .. "src/tools/unidasm.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- ldresample
--------------------------------------------------
project("ldresample")
uuid ("3401561a-4407-4e13-9c6d-c0801330f7cc")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
}
includedirs {
ext_includedir("flac"),
}
files {
MAME_DIR .. "src/tools/ldresample.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- ldverify
--------------------------------------------------
project("ldverify")
uuid ("3e66560d-b928-4227-928b-eadd0a10f00a")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
}
includedirs {
ext_includedir("flac"),
}
files {
MAME_DIR .. "src/tools/ldverify.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- regrep
--------------------------------------------------
project("regrep")
uuid ("7f6de580-d800-4e8d-bed6-9fc86829584d")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/regrep.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- srcclean
---------------------------------------------------
project("srcclean")
uuid ("4dd58139-313a-42c5-965d-f378bdeed220")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/srcclean.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- src2html
--------------------------------------------------
project("src2html")
uuid ("b31e963a-09ef-4696-acbd-e663e35ce6f7")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/src2html.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- split
--------------------------------------------------
project("split")
uuid ("8ef6ff18-3199-4cc2-afd0-d64033070faa")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/split.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- pngcmp
--------------------------------------------------
project("pngcmp")
uuid ("61f647d9-b129-409b-9c62-8acf98ed39be")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/pngcmp.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- nltool
--------------------------------------------------
project("nltool")
uuid ("853a03b7-fa37-41a8-8250-0dc23dd935d6")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
"netlist",
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "src/lib/netlist",
}
files {
MAME_DIR .. "src/lib/netlist/prg/nltool.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- nlwav
--------------------------------------------------
project("nlwav")
uuid ("7c5396d1-2a1a-4c93-bed6-6b8fa182054a")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"utils",
"ocore_" .. _OPTIONS["osd"],
"netlist",
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "src/lib/netlist",
}
files {
MAME_DIR .. "src/lib/netlist/prg/nlwav.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- castool
--------------------------------------------------
project("castool")
uuid ("7d9ed428-e2ba-4448-832d-d882a64d5c22")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"formats",
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/castool.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- floptool
--------------------------------------------------
project("floptool")
uuid ("85d8e3a6-1661-4ac9-8c21-281d20cbaf5b")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"formats",
"emu",
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/tools/floptool.cpp",
MAME_DIR .. "src/emu/emucore.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- imgtool
--------------------------------------------------
project("imgtool")
uuid ("f3707807-e587-4297-a5d8-bc98f3d0b1ca")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
links {
"formats",
"emu",
"utils",
ext_lib("expat"),
"7z",
"ocore_" .. _OPTIONS["osd"],
ext_lib("zlib"),
ext_lib("flac"),
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/lib",
MAME_DIR .. "src/lib/util",
ext_includedir("zlib"),
MAME_DIR .. "src/tools/imgtool",
}
files {
MAME_DIR .. "src/tools/imgtool/main.cpp",
MAME_DIR .. "src/tools/imgtool/main.h",
MAME_DIR .. "src/tools/imgtool/stream.cpp",
MAME_DIR .. "src/tools/imgtool/stream.h",
MAME_DIR .. "src/tools/imgtool/library.cpp",
MAME_DIR .. "src/tools/imgtool/library.h",
MAME_DIR .. "src/tools/imgtool/modules.cpp",
MAME_DIR .. "src/tools/imgtool/modules.h",
MAME_DIR .. "src/tools/imgtool/iflopimg.cpp",
MAME_DIR .. "src/tools/imgtool/iflopimg.h",
MAME_DIR .. "src/tools/imgtool/filter.cpp",
MAME_DIR .. "src/tools/imgtool/filter.h",
MAME_DIR .. "src/tools/imgtool/filteoln.cpp",
MAME_DIR .. "src/tools/imgtool/filtbas.cpp",
MAME_DIR .. "src/tools/imgtool/imgtool.cpp",
MAME_DIR .. "src/tools/imgtool/imgtool.h",
MAME_DIR .. "src/tools/imgtool/imgterrs.cpp",
MAME_DIR .. "src/tools/imgtool/imgterrs.h",
MAME_DIR .. "src/tools/imgtool/imghd.cpp",
MAME_DIR .. "src/tools/imgtool/imghd.h",
MAME_DIR .. "src/tools/imgtool/charconv.cpp",
MAME_DIR .. "src/tools/imgtool/charconv.h",
MAME_DIR .. "src/tools/imgtool/formats/vt_dsk.cpp",
MAME_DIR .. "src/tools/imgtool/formats/vt_dsk.h",
MAME_DIR .. "src/tools/imgtool/formats/coco_dsk.cpp",
MAME_DIR .. "src/tools/imgtool/formats/coco_dsk.h",
MAME_DIR .. "src/tools/imgtool/modules/amiga.cpp",
MAME_DIR .. "src/tools/imgtool/modules/macbin.cpp",
MAME_DIR .. "src/tools/imgtool/modules/rsdos.cpp",
MAME_DIR .. "src/tools/imgtool/modules/os9.cpp",
MAME_DIR .. "src/tools/imgtool/modules/mac.cpp",
MAME_DIR .. "src/tools/imgtool/modules/ti99.cpp",
MAME_DIR .. "src/tools/imgtool/modules/ti990hd.cpp",
MAME_DIR .. "src/tools/imgtool/modules/concept.cpp",
MAME_DIR .. "src/tools/imgtool/modules/fat.cpp",
MAME_DIR .. "src/tools/imgtool/modules/fat.h",
MAME_DIR .. "src/tools/imgtool/modules/pc_flop.cpp",
MAME_DIR .. "src/tools/imgtool/modules/pc_hard.cpp",
MAME_DIR .. "src/tools/imgtool/modules/prodos.cpp",
MAME_DIR .. "src/tools/imgtool/modules/vzdos.cpp",
MAME_DIR .. "src/tools/imgtool/modules/thomson.cpp",
MAME_DIR .. "src/tools/imgtool/modules/macutil.cpp",
MAME_DIR .. "src/tools/imgtool/modules/macutil.h",
MAME_DIR .. "src/tools/imgtool/modules/cybiko.cpp",
MAME_DIR .. "src/tools/imgtool/modules/cybikoxt.cpp",
MAME_DIR .. "src/tools/imgtool/modules/psion.cpp",
MAME_DIR .. "src/tools/imgtool/modules/bml3.cpp",
MAME_DIR .. "src/tools/imgtool/modules/hp48.cpp",
}
configuration { "mingw*" or "vs*" }
targetextension ".exe"
configuration { }
strip()
--------------------------------------------------
-- aueffectutil
--------------------------------------------------
if _OPTIONS["targetos"] == "macosx" then
project("aueffectutil")
uuid ("3db8316d-fad7-4f5b-b46a-99373c91550e")
kind "ConsoleApp"
flags {
"Symbols", -- always include minimum symbols for executables
}
if _OPTIONS["SEPARATE_BIN"]~="1" then
targetdir(MAME_DIR)
end
linkoptions {
"-sectcreate __TEXT __info_plist " .. MAME_DIR .. "src/tools/aueffectutil-Info.plist",
}
dependency {
{ "aueffectutil", MAME_DIR .. "src/tools/aueffectutil-Info.plist", true },
}
links {
"AudioUnit.framework",
"AudioToolbox.framework",
"CoreAudio.framework",
"CoreAudioKit.framework",
"CoreServices.framework",
}
files {
MAME_DIR .. "src/tools/aueffectutil.mm",
}
configuration { }
strip()
end
| RJRetro/mame | scripts/src/tools.lua | Lua | gpl-2.0 | 14,854 |
/* hostlist_sctp.c 2008 Stig Bjorlykke
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* 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.
*/
#include "config.h"
#include <string.h>
#include <gtk/gtk.h>
#include "epan/packet.h"
#include <epan/stat_cmd_args.h>
#include <epan/tap.h>
#include <epan/dissectors/packet-sctp.h>
#include "../stat_menu.h"
#include "ui/gtk/gui_stat_menu.h"
#include "ui/gtk/hostlist_table.h"
void register_tap_listener_sctp_hostlist(void);
static int
sctp_hostlist_packet(void *pit, packet_info *pinfo, epan_dissect_t *edt _U_, const void *vip)
{
hostlist_table *hosts=(hostlist_table *)pit;
const struct _sctp_info *sctphdr=(const struct _sctp_info *)vip;
/* Take two "add" passes per packet, adding for each direction, ensures that all
packets are counted properly (even if address is sending to itself)
XXX - this could probably be done more efficiently inside hostlist_table */
add_hostlist_table_data(hosts, &sctphdr->ip_src, sctphdr->sport, TRUE, 1,
pinfo->fd->pkt_len, SAT_NONE, PT_SCTP);
add_hostlist_table_data(hosts, &sctphdr->ip_dst, sctphdr->dport, FALSE, 1,
pinfo->fd->pkt_len, SAT_NONE, PT_SCTP);
return 1;
}
static void
gtk_sctp_hostlist_init(const char *opt_arg, void* userdata _U_)
{
const char *filter=NULL;
if(!strncmp(opt_arg,"hosts,sctp,",11)){
filter=opt_arg+11;
} else {
filter=NULL;
}
init_hostlist_table(FALSE, "SCTP", "sctp", filter, sctp_hostlist_packet);
}
void
gtk_sctp_hostlist_cb(GtkAction *action _U_, gpointer user_data _U_)
{
gtk_sctp_hostlist_init("hosts,sctp",NULL);
}
void
register_tap_listener_sctp_hostlist(void)
{
register_stat_cmd_arg("hosts,sctp", gtk_sctp_hostlist_init,NULL);
register_hostlist_table(FALSE, "SCTP", "sctp", NULL /*filter*/, sctp_hostlist_packet);
}
| morynicz/pyroshark | ui/gtk/hostlist_sctp.c | C | gpl-2.0 | 2,658 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright held by original author
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
\*---------------------------------------------------------------------------*/
#include "kinematicCloud.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace Foam
{
defineTypeNameAndDebug(kinematicCloud, 0);
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::kinematicCloud::kinematicCloud()
{}
// * * * * * * * * * * * * * * * * Destructors * * * * * * * * * * * * * * //
Foam::kinematicCloud::~kinematicCloud()
{}
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-Core-OpenFOAM-1.5-dev | src/lagrangian/intermediate/clouds/baseClasses/kinematicCloud/kinematicCloud.C | C++ | gpl-2.0 | 1,724 |
<!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 Mon Dec 02 20:33:00 CET 2013 -->
<title>NVTextureRectangle (LWJGL API)</title>
<meta name="date" content="2013-12-02">
<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="NVTextureRectangle (LWJGL 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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/NVTextureRectangle.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/lwjgl/opengl/NVTextureMultisample.html" title="class in org.lwjgl.opengl"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/lwjgl/opengl/NVTextureShader.html" title="class in org.lwjgl.opengl"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/lwjgl/opengl/NVTextureRectangle.html" target="_top">Frames</a></li>
<li><a href="NVTextureRectangle.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.lwjgl.opengl</div>
<h2 title="Class NVTextureRectangle" class="title">Class NVTextureRectangle</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.lwjgl.opengl.NVTextureRectangle</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public final class <span class="strong">NVTextureRectangle</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../org/lwjgl/opengl/NVTextureRectangle.html#GL_MAX_RECTANGLE_TEXTURE_SIZE_NV">GL_MAX_RECTANGLE_TEXTURE_SIZE_NV</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../org/lwjgl/opengl/NVTextureRectangle.html#GL_PROXY_TEXTURE_RECTANGLE_NV">GL_PROXY_TEXTURE_RECTANGLE_NV</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../org/lwjgl/opengl/NVTextureRectangle.html#GL_TEXTURE_BINDING_RECTANGLE_NV">GL_TEXTURE_BINDING_RECTANGLE_NV</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../org/lwjgl/opengl/NVTextureRectangle.html#GL_TEXTURE_RECTANGLE_NV">GL_TEXTURE_RECTANGLE_NV</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="GL_TEXTURE_RECTANGLE_NV">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>GL_TEXTURE_RECTANGLE_NV</h4>
<pre>public static final int GL_TEXTURE_RECTANGLE_NV</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#org.lwjgl.opengl.NVTextureRectangle.GL_TEXTURE_RECTANGLE_NV">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="GL_TEXTURE_BINDING_RECTANGLE_NV">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>GL_TEXTURE_BINDING_RECTANGLE_NV</h4>
<pre>public static final int GL_TEXTURE_BINDING_RECTANGLE_NV</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#org.lwjgl.opengl.NVTextureRectangle.GL_TEXTURE_BINDING_RECTANGLE_NV">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="GL_PROXY_TEXTURE_RECTANGLE_NV">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>GL_PROXY_TEXTURE_RECTANGLE_NV</h4>
<pre>public static final int GL_PROXY_TEXTURE_RECTANGLE_NV</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#org.lwjgl.opengl.NVTextureRectangle.GL_PROXY_TEXTURE_RECTANGLE_NV">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="GL_MAX_RECTANGLE_TEXTURE_SIZE_NV">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>GL_MAX_RECTANGLE_TEXTURE_SIZE_NV</h4>
<pre>public static final int GL_MAX_RECTANGLE_TEXTURE_SIZE_NV</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../constant-values.html#org.lwjgl.opengl.NVTextureRectangle.GL_MAX_RECTANGLE_TEXTURE_SIZE_NV">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/NVTextureRectangle.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/lwjgl/opengl/NVTextureMultisample.html" title="class in org.lwjgl.opengl"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/lwjgl/opengl/NVTextureShader.html" title="class in org.lwjgl.opengl"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/lwjgl/opengl/NVTextureRectangle.html" target="_top">Frames</a></li>
<li><a href="NVTextureRectangle.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li>Constr | </li>
<li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><i>Copyright © 2002-2009 lwjgl.org. All Rights Reserved.</i></small></p>
</body>
</html>
| filthy-mattress/JPong | lwjgl-2.9.1/javadoc/org/lwjgl/opengl/NVTextureRectangle.html | HTML | gpl-2.0 | 10,018 |
<?php
if(!function_exists ('ew_code')){
function ew_code($atts,$content = false){
extract(shortcode_atts(array(
),$atts));
//add_filter('the_content','ew_do_shortcode',1001);
return "<div class='border-code'><div class='background-code'><pre class='code'>".htmlspecialchars($content)."</pre></div></div>";
}
}
add_shortcode('code','ew_code');
?> | DiegoUX/recubre | wp-content/themes/recubre/framework/shortcodes/code.php | PHP | gpl-2.0 | 356 |
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <impl/Kokkos_Utilities.hpp> // type_list
#include <traits/Kokkos_Traits_fwd.hpp>
#ifndef KOKKOS_KOKKOS_POLICYTRAITADAPTOR_HPP
#define KOKKOS_KOKKOS_POLICYTRAITADAPTOR_HPP
namespace Kokkos {
namespace Impl {
//==============================================================================
// <editor-fold desc="Adapter for replacing/adding a trait"> {{{1
//------------------------------------------------------------------------------
// General strategy: given a TraitSpecification, go through the entries in the
// parameter pack of the policy template and find the first one that returns
// `true` for the nested `trait_matches_specification` variable template. If
// that nested variable template is not found these overloads should be safely
// ignored, and the trait can specialize PolicyTraitAdapterImpl to get the
// desired behavior.
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// <editor-fold desc="PolicyTraitMatcher"> {{{2
// To handle the WorkTag case, we need more than just a predicate; we need
// something that we can default to in the unspecialized case, just like we
// do for AnalyzeExecPolicy
template <class TraitSpec, class Trait, class Enable = void>
struct PolicyTraitMatcher;
template <class TraitSpec, class Trait>
struct PolicyTraitMatcher<
TraitSpec, Trait,
std::enable_if_t<
TraitSpec::template trait_matches_specification<Trait>::value>>
: std::true_type {};
// </editor-fold> end PolicyTraitMatcher }}}2
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// <editor-fold desc="PolicyTraitAdaptorImpl specializations"> {{{2
// Matching version, replace the trait
template <class TraitSpec, template <class...> class PolicyTemplate,
class... ProcessedTraits, class MatchingTrait,
class... ToProcessTraits, class NewTrait>
struct PolicyTraitAdaptorImpl<
TraitSpec, PolicyTemplate, type_list<ProcessedTraits...>,
type_list<MatchingTrait, ToProcessTraits...>, NewTrait,
std::enable_if_t<PolicyTraitMatcher<TraitSpec, MatchingTrait>::value>> {
static_assert(PolicyTraitMatcher<TraitSpec, NewTrait>::value, "");
using type = PolicyTemplate<ProcessedTraits..., NewTrait, ToProcessTraits...>;
};
// Non-matching version, check the next option
template <class TraitSpec, template <class...> class PolicyTemplate,
class... ProcessedTraits, class NonMatchingTrait,
class... ToProcessTraits, class NewTrait>
struct PolicyTraitAdaptorImpl<
TraitSpec, PolicyTemplate, type_list<ProcessedTraits...>,
type_list<NonMatchingTrait, ToProcessTraits...>, NewTrait,
std::enable_if_t<!PolicyTraitMatcher<TraitSpec, NonMatchingTrait>::value>> {
using type = typename PolicyTraitAdaptorImpl<
TraitSpec, PolicyTemplate,
type_list<ProcessedTraits..., NonMatchingTrait>,
type_list<ToProcessTraits...>, NewTrait>::type;
};
// Base case: no matches found; just add the trait to the end of the list
template <class TraitSpec, template <class...> class PolicyTemplate,
class... ProcessedTraits, class NewTrait>
struct PolicyTraitAdaptorImpl<TraitSpec, PolicyTemplate,
type_list<ProcessedTraits...>, type_list<>,
NewTrait> {
static_assert(PolicyTraitMatcher<TraitSpec, NewTrait>::value, "");
using type = PolicyTemplate<ProcessedTraits..., NewTrait>;
};
// </editor-fold> end PolicyTraitAdaptorImpl specializations }}}2
//------------------------------------------------------------------------------
template <class TraitSpec, template <class...> class PolicyTemplate,
class... Traits, class NewTrait>
struct PolicyTraitAdaptor<TraitSpec, PolicyTemplate<Traits...>, NewTrait>
: PolicyTraitAdaptorImpl<TraitSpec, PolicyTemplate, type_list<>,
type_list<Traits...>, NewTrait> {};
// </editor-fold> end Adapter for replacing/adding a trait }}}1
//==============================================================================
//==============================================================================
// <editor-fold desc="CRTP Base class for trait specifications"> {{{1
template <class TraitSpec>
struct TraitSpecificationBase {
using trait_specification = TraitSpec;
template <class Policy, class Trait>
using policy_with_trait =
typename PolicyTraitAdaptor<TraitSpec, Policy, Trait>::type;
};
// </editor-fold> end CRTP Base class for trait specifications }}}1
//==============================================================================
} // end namespace Impl
} // end namespace Kokkos
#endif // KOKKOS_KOKKOS_POLICYTRAITADAPTOR_HPP
| jeremiahyan/lammps | lib/kokkos/core/src/traits/Kokkos_PolicyTraitAdaptor.hpp | C++ | gpl-2.0 | 6,825 |
/*
* Fence mechanism for dma-buf and to allow for asynchronous dma access
*
* Copyright (C) 2012 Canonical Ltd
* Copyright (C) 2012 Texas Instruments
*
* Authors:
* Rob Clark <robdclark@gmail.com>
* Maarten Lankhorst <maarten.lankhorst@canonical.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* 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/slab.h>
#include <linux/export.h>
#include <linux/atomic.h>
#include <linux/fence.h>
#define CREATE_TRACE_POINTS
#include <trace/events/fence.h>
EXPORT_TRACEPOINT_SYMBOL(fence_annotate_wait_on);
EXPORT_TRACEPOINT_SYMBOL(fence_emit);
/*
* fence context counter: each execution context should have its own
* fence context, this allows checking if fences belong to the same
* context or not. One device can have multiple separate contexts,
* and they're used if some engine can run independently of another.
*/
static atomic_t fence_context_counter = ATOMIC_INIT(0);
/**
* fence_context_alloc - allocate an array of fence contexts
* @num: [in] amount of contexts to allocate
*
* This function will return the first index of the number of fences allocated.
* The fence context is used for setting fence->context to a unique number.
*/
unsigned fence_context_alloc(unsigned num)
{
BUG_ON(!num);
return atomic_add_return(num, &fence_context_counter) - num;
}
EXPORT_SYMBOL(fence_context_alloc);
/**
* fence_signal_locked - signal completion of a fence
* @fence: the fence to signal
*
* Signal completion for software callbacks on a fence, this will unblock
* fence_wait() calls and run all the callbacks added with
* fence_add_callback(). Can be called multiple times, but since a fence
* can only go from unsignaled to signaled state, it will only be effective
* the first time.
*
* Unlike fence_signal, this function must be called with fence->lock held.
*/
int fence_signal_locked(struct fence *fence)
{
struct fence_cb *cur, *tmp;
int ret = 0;
if (WARN_ON(!fence))
return -EINVAL;
if (!ktime_to_ns(fence->timestamp)) {
fence->timestamp = ktime_get();
smp_mb();
}
if (test_and_set_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
ret = -EINVAL;
/*
* we might have raced with the unlocked fence_signal,
* still run through all callbacks
*/
} else
trace_fence_signaled(fence);
list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
list_del_init(&cur->node);
cur->func(fence, cur);
}
return ret;
}
EXPORT_SYMBOL(fence_signal_locked);
/**
* fence_signal - signal completion of a fence
* @fence: the fence to signal
*
* Signal completion for software callbacks on a fence, this will unblock
* fence_wait() calls and run all the callbacks added with
* fence_add_callback(). Can be called multiple times, but since a fence
* can only go from unsignaled to signaled state, it will only be effective
* the first time.
*/
int fence_signal(struct fence *fence)
{
unsigned long flags;
if (!fence)
return -EINVAL;
if (!ktime_to_ns(fence->timestamp)) {
fence->timestamp = ktime_get();
smp_mb();
}
if (test_and_set_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
return -EINVAL;
trace_fence_signaled(fence);
if (test_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags)) {
struct fence_cb *cur, *tmp;
spin_lock_irqsave(fence->lock, flags);
list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) {
list_del_init(&cur->node);
cur->func(fence, cur);
}
spin_unlock_irqrestore(fence->lock, flags);
}
return 0;
}
EXPORT_SYMBOL(fence_signal);
/**
* fence_wait_timeout - sleep until the fence gets signaled
* or until timeout elapses
* @fence: [in] the fence to wait on
* @intr: [in] if true, do an interruptible wait
* @timeout: [in] timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
*
* Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
* remaining timeout in jiffies on success. Other error values may be
* returned on custom implementations.
*
* Performs a synchronous wait on this fence. It is assumed the caller
* directly or indirectly (buf-mgr between reservation and committing)
* holds a reference to the fence, otherwise the fence might be
* freed before return, resulting in undefined behavior.
*/
signed long
fence_wait_timeout(struct fence *fence, bool intr, signed long timeout)
{
signed long ret;
if (WARN_ON(timeout < 0))
return -EINVAL;
trace_fence_wait_start(fence);
ret = fence->ops->wait(fence, intr, timeout);
trace_fence_wait_end(fence);
return ret;
}
EXPORT_SYMBOL(fence_wait_timeout);
void fence_release(struct kref *kref)
{
struct fence *fence =
container_of(kref, struct fence, refcount);
trace_fence_destroy(fence);
BUG_ON(!list_empty(&fence->cb_list));
if (fence->ops->release)
fence->ops->release(fence);
else
fence_free(fence);
}
EXPORT_SYMBOL(fence_release);
void fence_free(struct fence *fence)
{
kfree_rcu(fence, rcu);
}
EXPORT_SYMBOL(fence_free);
/**
* fence_enable_sw_signaling - enable signaling on fence
* @fence: [in] the fence to enable
*
* this will request for sw signaling to be enabled, to make the fence
* complete as soon as possible
*/
void fence_enable_sw_signaling(struct fence *fence)
{
unsigned long flags;
if (!test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags) &&
!test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
trace_fence_enable_signal(fence);
spin_lock_irqsave(fence->lock, flags);
if (!fence->ops->enable_signaling(fence))
fence_signal_locked(fence);
spin_unlock_irqrestore(fence->lock, flags);
}
}
EXPORT_SYMBOL(fence_enable_sw_signaling);
/**
* fence_add_callback - add a callback to be called when the fence
* is signaled
* @fence: [in] the fence to wait on
* @cb: [in] the callback to register
* @func: [in] the function to call
*
* cb will be initialized by fence_add_callback, no initialization
* by the caller is required. Any number of callbacks can be registered
* to a fence, but a callback can only be registered to one fence at a time.
*
* Note that the callback can be called from an atomic context. If
* fence is already signaled, this function will return -ENOENT (and
* *not* call the callback)
*
* Add a software callback to the fence. Same restrictions apply to
* refcount as it does to fence_wait, however the caller doesn't need to
* keep a refcount to fence afterwards: when software access is enabled,
* the creator of the fence is required to keep the fence alive until
* after it signals with fence_signal. The callback itself can be called
* from irq context.
*
*/
int fence_add_callback(struct fence *fence, struct fence_cb *cb,
fence_func_t func)
{
unsigned long flags;
int ret = 0;
bool was_set;
if (WARN_ON(!fence || !func))
return -EINVAL;
if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) {
INIT_LIST_HEAD(&cb->node);
return -ENOENT;
}
spin_lock_irqsave(fence->lock, flags);
was_set = test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags);
if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
ret = -ENOENT;
else if (!was_set) {
trace_fence_enable_signal(fence);
if (!fence->ops->enable_signaling(fence)) {
fence_signal_locked(fence);
ret = -ENOENT;
}
}
if (!ret) {
cb->func = func;
list_add_tail(&cb->node, &fence->cb_list);
} else
INIT_LIST_HEAD(&cb->node);
spin_unlock_irqrestore(fence->lock, flags);
return ret;
}
EXPORT_SYMBOL(fence_add_callback);
/**
* fence_remove_callback - remove a callback from the signaling list
* @fence: [in] the fence to wait on
* @cb: [in] the callback to remove
*
* Remove a previously queued callback from the fence. This function returns
* true if the callback is succesfully removed, or false if the fence has
* already been signaled.
*
* *WARNING*:
* Cancelling a callback should only be done if you really know what you're
* doing, since deadlocks and race conditions could occur all too easily. For
* this reason, it should only ever be done on hardware lockup recovery,
* with a reference held to the fence.
*/
bool
fence_remove_callback(struct fence *fence, struct fence_cb *cb)
{
unsigned long flags;
bool ret;
spin_lock_irqsave(fence->lock, flags);
ret = !list_empty(&cb->node);
if (ret)
list_del_init(&cb->node);
spin_unlock_irqrestore(fence->lock, flags);
return ret;
}
EXPORT_SYMBOL(fence_remove_callback);
struct default_wait_cb {
struct fence_cb base;
struct task_struct *task;
};
static void
fence_default_wait_cb(struct fence *fence, struct fence_cb *cb)
{
struct default_wait_cb *wait =
container_of(cb, struct default_wait_cb, base);
wake_up_state(wait->task, TASK_NORMAL);
}
/**
* fence_default_wait - default sleep until the fence gets signaled
* or until timeout elapses
* @fence: [in] the fence to wait on
* @intr: [in] if true, do an interruptible wait
* @timeout: [in] timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT
*
* Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the
* remaining timeout in jiffies on success.
*/
signed long
fence_default_wait(struct fence *fence, bool intr, signed long timeout)
{
struct default_wait_cb cb;
unsigned long flags;
signed long ret = timeout;
bool was_set;
if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
return timeout;
spin_lock_irqsave(fence->lock, flags);
if (intr && signal_pending(current)) {
ret = -ERESTARTSYS;
goto out;
}
was_set = test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags);
if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags))
goto out;
if (!was_set) {
trace_fence_enable_signal(fence);
if (!fence->ops->enable_signaling(fence)) {
fence_signal_locked(fence);
goto out;
}
}
cb.base.func = fence_default_wait_cb;
cb.task = current;
list_add(&cb.base.node, &fence->cb_list);
while (!test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) {
if (intr)
__set_current_state(TASK_INTERRUPTIBLE);
else
__set_current_state(TASK_UNINTERRUPTIBLE);
spin_unlock_irqrestore(fence->lock, flags);
ret = schedule_timeout(ret);
spin_lock_irqsave(fence->lock, flags);
if (ret > 0 && intr && signal_pending(current))
ret = -ERESTARTSYS;
}
if (!list_empty(&cb.base.node))
list_del(&cb.base.node);
__set_current_state(TASK_RUNNING);
out:
spin_unlock_irqrestore(fence->lock, flags);
return ret;
}
EXPORT_SYMBOL(fence_default_wait);
/**
* fence_init - Initialize a custom fence.
* @fence: [in] the fence to initialize
* @ops: [in] the fence_ops for operations on this fence
* @lock: [in] the irqsafe spinlock to use for locking this fence
* @context: [in] the execution context this fence is run on
* @seqno: [in] a linear increasing sequence number for this context
*
* Initializes an allocated fence, the caller doesn't have to keep its
* refcount after committing with this fence, but it will need to hold a
* refcount again if fence_ops.enable_signaling gets called. This can
* be used for other implementing other types of fence.
*
* context and seqno are used for easy comparison between fences, allowing
* to check which fence is later by simply using fence_later.
*/
void
fence_init(struct fence *fence, const struct fence_ops *ops,
spinlock_t *lock, unsigned context, unsigned seqno)
{
BUG_ON(!lock);
BUG_ON(!ops || !ops->wait || !ops->enable_signaling ||
!ops->get_driver_name || !ops->get_timeline_name);
kref_init(&fence->refcount);
fence->ops = ops;
INIT_LIST_HEAD(&fence->cb_list);
fence->lock = lock;
fence->context = context;
fence->seqno = seqno;
fence->flags = 0UL;
trace_fence_init(fence);
}
EXPORT_SYMBOL(fence_init);
| kofemann/linux-redpatch | drivers/base/fence.c | C | gpl-2.0 | 11,942 |
/*
* Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Felmyst
SD%Complete: 0
SDComment:
EndScriptData */
#include "ScriptMgr.h"
#include "CellImpl.h"
#include "GridNotifiersImpl.h"
#include "InstanceScript.h"
#include "MotionMaster.h"
#include "ObjectAccessor.h"
#include "ScriptedCreature.h"
#include "sunwell_plateau.h"
#include "TemporarySummon.h"
enum Yells
{
YELL_BIRTH = 0,
YELL_KILL = 1,
YELL_BREATH = 2,
YELL_TAKEOFF = 3,
YELL_BERSERK = 4,
YELL_DEATH = 5,
//YELL_KALECGOS = 6, Not used. After felmyst's death spawned and say this
};
enum Spells
{
//Aura
AURA_SUNWELL_RADIANCE = 45769,
AURA_NOXIOUS_FUMES = 47002,
//Land phase
SPELL_CLEAVE = 19983,
SPELL_CORROSION = 45866,
SPELL_GAS_NOVA = 45855,
SPELL_ENCAPSULATE_CHANNEL = 45661,
// SPELL_ENCAPSULATE_EFFECT = 45665,
// SPELL_ENCAPSULATE_AOE = 45662,
//Flight phase
SPELL_VAPOR_SELECT = 45391, // fel to player, force cast 45392, 50000y selete target
SPELL_VAPOR_SUMMON = 45392, // player summon vapor, radius around caster, 5y,
SPELL_VAPOR_FORCE = 45388, // vapor to fel, force cast 45389
SPELL_VAPOR_CHANNEL = 45389, // fel to vapor, green beam channel
SPELL_VAPOR_TRIGGER = 45411, // linked to 45389, vapor to self, trigger 45410 and 46931
SPELL_VAPOR_DAMAGE = 46931, // vapor damage, 4000
SPELL_TRAIL_SUMMON = 45410, // vapor summon trail
SPELL_TRAIL_TRIGGER = 45399, // trail to self, trigger 45402
SPELL_TRAIL_DAMAGE = 45402, // trail damage, 2000 + 2000 dot
SPELL_DEAD_SUMMON = 45400, // summon blazing dead, 5min
SPELL_DEAD_PASSIVE = 45415,
SPELL_FOG_BREATH = 45495, // fel to self, speed burst
SPELL_FOG_TRIGGER = 45582, // fog to self, trigger 45782
SPELL_FOG_FORCE = 45782, // fog to player, force cast 45714
SPELL_FOG_INFORM = 45714, // player let fel cast 45717, script effect
SPELL_FOG_CHARM = 45717, // fel to player
SPELL_FOG_CHARM2 = 45726, // link to 45717
SPELL_TRANSFORM_TRIGGER = 44885, // madrigosa to self, trigger 46350
SPELL_TRANSFORM_VISUAL = 46350, // 46411stun?
SPELL_TRANSFORM_FELMYST = 45068, // become fel
SPELL_FELMYST_SUMMON = 45069,
//Other
SPELL_BERSERK = 45078,
SPELL_CLOUD_VISUAL = 45212,
SPELL_CLOUD_SUMMON = 45884
};
enum PhaseFelmyst
{
PHASE_NONE,
PHASE_GROUND,
PHASE_FLIGHT
};
enum EventFelmyst
{
EVENT_NONE,
EVENT_BERSERK,
EVENT_CLEAVE,
EVENT_CORROSION,
EVENT_GAS_NOVA,
EVENT_ENCAPSULATE,
EVENT_FLIGHT,
EVENT_FLIGHT_SEQUENCE,
EVENT_SUMMON_DEAD,
EVENT_SUMMON_FOG
};
class boss_felmyst : public CreatureScript
{
public:
boss_felmyst() : CreatureScript("boss_felmyst") { }
struct boss_felmystAI : public ScriptedAI
{
boss_felmystAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
uiBreathCount = 0;
breathX = 0.f;
breathY = 0.f;
}
void Initialize()
{
phase = PHASE_NONE;
uiFlightCount = 0;
}
InstanceScript* instance;
PhaseFelmyst phase;
EventMap events;
uint32 uiFlightCount;
uint32 uiBreathCount;
float breathX, breathY;
void Reset() override
{
Initialize();
events.Reset();
me->SetDisableGravity(true);
me->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 10);
me->SetFloatValue(UNIT_FIELD_COMBATREACH, 10);
DespawnSummons(NPC_VAPOR_TRAIL);
me->setActive(false);
instance->SetBossState(DATA_FELMYST, NOT_STARTED);
}
void EnterCombat(Unit* /*who*/) override
{
events.ScheduleEvent(EVENT_BERSERK, 600000);
me->setActive(true);
DoZoneInCombat();
DoCast(me, AURA_SUNWELL_RADIANCE, true);
DoCast(me, AURA_NOXIOUS_FUMES, true);
EnterPhase(PHASE_GROUND);
instance->SetBossState(DATA_FELMYST, IN_PROGRESS);
}
void AttackStart(Unit* who) override
{
if (phase != PHASE_FLIGHT)
ScriptedAI::AttackStart(who);
}
void MoveInLineOfSight(Unit* who) override
{
if (phase != PHASE_FLIGHT)
ScriptedAI::MoveInLineOfSight(who);
}
void KilledUnit(Unit* /*victim*/) override
{
Talk(YELL_KILL);
}
void JustRespawned() override
{
Talk(YELL_BIRTH);
}
void JustDied(Unit* /*killer*/) override
{
Talk(YELL_DEATH);
instance->SetBossState(DATA_FELMYST, DONE);
}
void SpellHit(Unit* caster, SpellInfo const* spell) override
{
// workaround for linked aura
/*if (spell->Id == SPELL_VAPOR_FORCE)
{
caster->CastSpell(caster, SPELL_VAPOR_TRIGGER, true);
}*/
// workaround for mind control
if (spell->Id == SPELL_FOG_INFORM)
{
float x, y, z;
caster->GetPosition(x, y, z);
if (Unit* summon = me->SummonCreature(NPC_DEAD, x, y, z, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000))
{
summon->SetMaxHealth(caster->GetMaxHealth());
summon->SetHealth(caster->GetMaxHealth());
summon->CastSpell(summon, SPELL_FOG_CHARM, true);
summon->CastSpell(summon, SPELL_FOG_CHARM2, true);
}
me->DealDamage(caster, caster->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false);
}
}
void JustSummoned(Creature* summon) override
{
if (summon->GetEntry() == NPC_DEAD)
{
summon->AI()->AttackStart(SelectTarget(SELECT_TARGET_RANDOM));
DoZoneInCombat(summon);
summon->CastSpell(summon, SPELL_DEAD_PASSIVE, true);
}
}
void MovementInform(uint32, uint32) override
{
if (phase == PHASE_FLIGHT)
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 1);
}
void DamageTaken(Unit*, uint32 &damage) override
{
if (phase != PHASE_GROUND && damage >= me->GetHealth())
damage = 0;
}
void EnterPhase(PhaseFelmyst NextPhase)
{
switch (NextPhase)
{
case PHASE_GROUND:
me->CastStop(SPELL_FOG_BREATH);
me->RemoveAurasDueToSpell(SPELL_FOG_BREATH);
me->StopMoving();
me->SetSpeedRate(MOVE_RUN, 2.0f);
events.ScheduleEvent(EVENT_CLEAVE, urand(5000, 10000));
events.ScheduleEvent(EVENT_CORROSION, urand(10000, 20000));
events.ScheduleEvent(EVENT_GAS_NOVA, urand(15000, 20000));
events.ScheduleEvent(EVENT_ENCAPSULATE, urand(20000, 25000));
events.ScheduleEvent(EVENT_FLIGHT, 60000);
break;
case PHASE_FLIGHT:
me->SetDisableGravity(true);
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 1000);
uiFlightCount = 0;
uiBreathCount = 0;
break;
default:
break;
}
phase = NextPhase;
}
void HandleFlightSequence()
{
switch (uiFlightCount)
{
case 0:
//me->AttackStop();
me->GetMotionMaster()->Clear(false);
me->HandleEmoteCommand(EMOTE_ONESHOT_LIFTOFF);
me->StopMoving();
Talk(YELL_TAKEOFF);
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 2000);
break;
case 1:
me->GetMotionMaster()->MovePoint(0, me->GetPositionX()+1, me->GetPositionY(), me->GetPositionZ()+10);
break;
case 2:
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 150, true);
if (!target)
target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_PLAYER_GUID));
if (!target)
{
EnterEvadeMode();
return;
}
if (Creature* Vapor = me->SummonCreature(NPC_VAPOR, target->GetPositionX() - 5 + rand32() % 10, target->GetPositionY() - 5 + rand32() % 10, target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 9000))
{
Vapor->AI()->AttackStart(target);
me->InterruptNonMeleeSpells(false);
DoCast(Vapor, SPELL_VAPOR_CHANNEL, false); // core bug
Vapor->CastSpell(Vapor, SPELL_VAPOR_TRIGGER, true);
}
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 10000);
break;
}
case 3:
{
DespawnSummons(NPC_VAPOR_TRAIL);
//DoCast(me, SPELL_VAPOR_SELECT); need core support
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 150, true);
if (!target)
target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_PLAYER_GUID));
if (!target)
{
EnterEvadeMode();
return;
}
//target->CastSpell(target, SPELL_VAPOR_SUMMON, true); need core support
if (Creature* pVapor = me->SummonCreature(NPC_VAPOR, target->GetPositionX() - 5 + rand32() % 10, target->GetPositionY() - 5 + rand32() % 10, target->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 9000))
{
if (pVapor->AI())
pVapor->AI()->AttackStart(target);
me->InterruptNonMeleeSpells(false);
DoCast(pVapor, SPELL_VAPOR_CHANNEL, false); // core bug
pVapor->CastSpell(pVapor, SPELL_VAPOR_TRIGGER, true);
}
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 10000);
break;
}
case 4:
DespawnSummons(NPC_VAPOR_TRAIL);
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 1);
break;
case 5:
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 150, true);
if (!target)
target = ObjectAccessor::GetUnit(*me, instance->GetGuidData(DATA_PLAYER_GUID));
if (!target)
{
EnterEvadeMode();
return;
}
breathX = target->GetPositionX();
breathY = target->GetPositionY();
float x, y, z;
target->GetContactPoint(me, x, y, z, 70);
me->GetMotionMaster()->MovePoint(0, x, y, z+10);
break;
}
case 6:
me->SetFacingTo(me->GetAngle(breathX, breathY));
//DoTextEmote("takes a deep breath.", nullptr);
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 10000);
break;
case 7:
{
DoCast(me, SPELL_FOG_BREATH, true);
float x, y, z;
me->GetPosition(x, y, z);
x = 2 * breathX - x;
y = 2 * breathY - y;
me->GetMotionMaster()->MovePoint(0, x, y, z);
events.ScheduleEvent(EVENT_SUMMON_FOG, 1);
break;
}
case 8:
me->CastStop(SPELL_FOG_BREATH);
me->RemoveAurasDueToSpell(SPELL_FOG_BREATH);
++uiBreathCount;
events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 1);
if (uiBreathCount < 3)
uiFlightCount = 4;
break;
case 9:
if (Unit* target = SelectTarget(SELECT_TARGET_MAXTHREAT))
DoStartMovement(target);
else
{
EnterEvadeMode();
return;
}
break;
case 10:
me->SetDisableGravity(false);
me->HandleEmoteCommand(EMOTE_ONESHOT_LAND);
EnterPhase(PHASE_GROUND);
AttackStart(SelectTarget(SELECT_TARGET_MAXTHREAT));
break;
}
++uiFlightCount;
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
{
if (phase == PHASE_FLIGHT && !me->IsInEvadeMode())
EnterEvadeMode();
return;
}
events.Update(diff);
if (me->IsNonMeleeSpellCast(false))
return;
if (phase == PHASE_GROUND)
{
switch (events.ExecuteEvent())
{
case EVENT_BERSERK:
Talk(YELL_BERSERK);
DoCast(me, SPELL_BERSERK, true);
events.ScheduleEvent(EVENT_BERSERK, 10000);
break;
case EVENT_CLEAVE:
DoCastVictim(SPELL_CLEAVE, false);
events.ScheduleEvent(EVENT_CLEAVE, urand(5000, 10000));
break;
case EVENT_CORROSION:
DoCastVictim(SPELL_CORROSION, false);
events.ScheduleEvent(EVENT_CORROSION, urand(20000, 30000));
break;
case EVENT_GAS_NOVA:
DoCast(me, SPELL_GAS_NOVA, false);
events.ScheduleEvent(EVENT_GAS_NOVA, urand(20000, 25000));
break;
case EVENT_ENCAPSULATE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 150, true))
DoCast(target, SPELL_ENCAPSULATE_CHANNEL, false);
events.ScheduleEvent(EVENT_ENCAPSULATE, urand(25000, 30000));
break;
case EVENT_FLIGHT:
EnterPhase(PHASE_FLIGHT);
break;
default:
DoMeleeAttackIfReady();
break;
}
}
if (phase == PHASE_FLIGHT)
{
switch (events.ExecuteEvent())
{
case EVENT_BERSERK:
Talk(YELL_BERSERK);
DoCast(me, SPELL_BERSERK, true);
break;
case EVENT_FLIGHT_SEQUENCE:
HandleFlightSequence();
break;
case EVENT_SUMMON_FOG:
{
float x, y, z;
me->GetPosition(x, y, z);
me->UpdateGroundPositionZ(x, y, z);
if (Creature* Fog = me->SummonCreature(NPC_VAPOR_TRAIL, x, y, z, 0, TEMPSUMMON_TIMED_DESPAWN, 10000))
{
Fog->RemoveAurasDueToSpell(SPELL_TRAIL_TRIGGER);
Fog->CastSpell(Fog, SPELL_FOG_TRIGGER, true);
me->CastSpell(Fog, SPELL_FOG_FORCE, true);
}
}
events.ScheduleEvent(EVENT_SUMMON_FOG, 1000);
break;
}
}
}
void DespawnSummons(uint32 entry)
{
std::list<Creature*> templist;
float x, y, z;
me->GetPosition(x, y, z);
Trinity::AllCreaturesOfEntryInRange check(me, entry, 100);
Trinity::CreatureListSearcher<Trinity::AllCreaturesOfEntryInRange> searcher(me, templist, check);
Cell::VisitGridObjects(me, searcher, me->GetGridActivationRange());
for (std::list<Creature*>::const_iterator i = templist.begin(); i != templist.end(); ++i)
{
if (entry == NPC_VAPOR_TRAIL && phase == PHASE_FLIGHT)
{
(*i)->GetPosition(x, y, z);
me->SummonCreature(NPC_DEAD, x, y, z, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000);
}
(*i)->SetVisible(false);
(*i)->DespawnOrUnsummon();
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetSunwellPlateauAI<boss_felmystAI>(creature);
}
};
class npc_felmyst_vapor : public CreatureScript
{
public:
npc_felmyst_vapor() : CreatureScript("npc_felmyst_vapor") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetSunwellPlateauAI<npc_felmyst_vaporAI>(creature);
}
struct npc_felmyst_vaporAI : public ScriptedAI
{
npc_felmyst_vaporAI(Creature* creature) : ScriptedAI(creature)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetSpeedRate(MOVE_RUN, 0.8f);
}
void Reset() override { }
void EnterCombat(Unit* /*who*/) override
{
DoZoneInCombat();
//DoCast(me, SPELL_VAPOR_FORCE, true); core bug
}
void UpdateAI(uint32 /*diff*/) override
{
if (!me->GetVictim())
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
AttackStart(target);
}
};
};
class npc_felmyst_trail : public CreatureScript
{
public:
npc_felmyst_trail() : CreatureScript("npc_felmyst_trail") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetSunwellPlateauAI<npc_felmyst_trailAI>(creature);
}
struct npc_felmyst_trailAI : public ScriptedAI
{
npc_felmyst_trailAI(Creature* creature) : ScriptedAI(creature)
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
DoCast(me, SPELL_TRAIL_TRIGGER, true);
me->SetTarget(me->GetGUID());
me->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 0.01f); // core bug
}
void Reset() override { }
void EnterCombat(Unit* /*who*/) override { }
void AttackStart(Unit* /*who*/) override { }
void MoveInLineOfSight(Unit* /*who*/) override { }
void UpdateAI(uint32 /*diff*/) override { }
};
};
void AddSC_boss_felmyst()
{
new boss_felmyst();
new npc_felmyst_vapor();
new npc_felmyst_trail();
}
| MoistBaguette/mangosbot | src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp | C++ | gpl-2.0 | 21,344 |
/*
* Copyright (C) 1996-2016 The Squid Software Foundation and contributors
*
* Squid software is distributed under GPLv2+ license and includes
* contributions from numerous individuals and organizations.
* Please see the COPYING and CONTRIBUTORS files for details.
*/
#include "squid.h"
#include "anyp/PortCfg.h"
#include "comm/Connection.h"
#include "CommCalls.h"
#include "fde.h"
#include "globals.h"
/* CommCommonCbParams */
CommCommonCbParams::CommCommonCbParams(void *aData):
data(cbdataReference(aData)), conn(), flag(Comm::OK), xerrno(0), fd(-1)
{
}
CommCommonCbParams::CommCommonCbParams(const CommCommonCbParams &p):
data(cbdataReference(p.data)), conn(p.conn), flag(p.flag), xerrno(p.xerrno), fd(p.fd)
{
}
CommCommonCbParams::~CommCommonCbParams()
{
cbdataReferenceDone(data);
}
void
CommCommonCbParams::print(std::ostream &os) const
{
if (conn != NULL)
os << conn;
else
os << "FD " << fd;
if (xerrno)
os << ", errno=" << xerrno;
if (flag != Comm::OK)
os << ", flag=" << flag;
if (data)
os << ", data=" << data;
}
/* CommAcceptCbParams */
CommAcceptCbParams::CommAcceptCbParams(void *aData):
CommCommonCbParams(aData), xaction()
{
}
void
CommAcceptCbParams::print(std::ostream &os) const
{
CommCommonCbParams::print(os);
if (xaction != NULL)
os << ", " << xaction->id;
}
/* CommConnectCbParams */
CommConnectCbParams::CommConnectCbParams(void *aData):
CommCommonCbParams(aData)
{
}
bool
CommConnectCbParams::syncWithComm()
{
// drop the call if the call was scheduled before comm_close but
// is being fired after comm_close
if (fd >= 0 && fd_table[fd].closing()) {
debugs(5, 3, HERE << "dropping late connect call: FD " << fd);
return false;
}
return true; // now we are in sync and can handle the call
}
/* CommIoCbParams */
CommIoCbParams::CommIoCbParams(void *aData): CommCommonCbParams(aData),
buf(NULL), size(0)
{
}
bool
CommIoCbParams::syncWithComm()
{
// change parameters if the call was scheduled before comm_close but
// is being fired after comm_close
if ((conn->fd < 0 || fd_table[conn->fd].closing()) && flag != Comm::ERR_CLOSING) {
debugs(5, 3, HERE << "converting late call to Comm::ERR_CLOSING: " << conn);
flag = Comm::ERR_CLOSING;
}
return true; // now we are in sync and can handle the call
}
void
CommIoCbParams::print(std::ostream &os) const
{
CommCommonCbParams::print(os);
if (buf) {
os << ", size=" << size;
os << ", buf=" << (void*)buf;
}
}
/* CommCloseCbParams */
CommCloseCbParams::CommCloseCbParams(void *aData):
CommCommonCbParams(aData)
{
}
/* CommTimeoutCbParams */
CommTimeoutCbParams::CommTimeoutCbParams(void *aData):
CommCommonCbParams(aData)
{
}
/* FdeCbParams */
FdeCbParams::FdeCbParams(void *aData):
CommCommonCbParams(aData)
{
}
/* CommAcceptCbPtrFun */
CommAcceptCbPtrFun::CommAcceptCbPtrFun(IOACB *aHandler,
const CommAcceptCbParams &aParams):
CommDialerParamsT<CommAcceptCbParams>(aParams),
handler(aHandler)
{
}
CommAcceptCbPtrFun::CommAcceptCbPtrFun(const CommAcceptCbPtrFun &o):
CommDialerParamsT<CommAcceptCbParams>(o.params),
handler(o.handler)
{
}
void
CommAcceptCbPtrFun::dial()
{
handler(params);
}
void
CommAcceptCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* CommConnectCbPtrFun */
CommConnectCbPtrFun::CommConnectCbPtrFun(CNCB *aHandler,
const CommConnectCbParams &aParams):
CommDialerParamsT<CommConnectCbParams>(aParams),
handler(aHandler)
{
}
void
CommConnectCbPtrFun::dial()
{
handler(params.conn, params.flag, params.xerrno, params.data);
}
void
CommConnectCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* CommIoCbPtrFun */
CommIoCbPtrFun::CommIoCbPtrFun(IOCB *aHandler, const CommIoCbParams &aParams):
CommDialerParamsT<CommIoCbParams>(aParams),
handler(aHandler)
{
}
void
CommIoCbPtrFun::dial()
{
handler(params.conn, params.buf, params.size, params.flag, params.xerrno, params.data);
}
void
CommIoCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* CommCloseCbPtrFun */
CommCloseCbPtrFun::CommCloseCbPtrFun(CLCB *aHandler,
const CommCloseCbParams &aParams):
CommDialerParamsT<CommCloseCbParams>(aParams),
handler(aHandler)
{
}
void
CommCloseCbPtrFun::dial()
{
handler(params);
}
void
CommCloseCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* CommTimeoutCbPtrFun */
CommTimeoutCbPtrFun::CommTimeoutCbPtrFun(CTCB *aHandler,
const CommTimeoutCbParams &aParams):
CommDialerParamsT<CommTimeoutCbParams>(aParams),
handler(aHandler)
{
}
void
CommTimeoutCbPtrFun::dial()
{
handler(params);
}
void
CommTimeoutCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
/* FdeCbPtrFun */
FdeCbPtrFun::FdeCbPtrFun(FDECB *aHandler, const FdeCbParams &aParams) :
CommDialerParamsT<FdeCbParams>(aParams),
handler(aHandler)
{
}
void
FdeCbPtrFun::dial()
{
handler(params);
}
void
FdeCbPtrFun::print(std::ostream &os) const
{
os << '(';
params.print(os);
os << ')';
}
| saucelabs/squid3 | src/CommCalls.cc | C++ | gpl-2.0 | 5,412 |
/* Thread pool
Copyright (C) 2019-2020 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 "common-defs.h"
#if CXX_STD_THREAD
#include "gdbsupport/thread-pool.h"
#include "gdbsupport/alt-stack.h"
#include "gdbsupport/block-signals.h"
#include <algorithm>
/* On the off chance that we have the pthread library on a Windows
host, but std::thread is not using it, avoid calling
pthread_setname_np on Windows. */
#ifndef _WIN32
#ifdef HAVE_PTHREAD_SETNAME_NP
#define USE_PTHREAD_SETNAME_NP
#endif
#endif
#ifdef USE_PTHREAD_SETNAME_NP
#include <pthread.h>
/* Handle platform discrepancies in pthread_setname_np: macOS uses a
single-argument form, while Linux uses a two-argument form. NetBSD
takes a printf-style format and an argument. This wrapper handles the
difference. */
ATTRIBUTE_UNUSED static void
set_thread_name (int (*set_name) (pthread_t, const char *, void *),
const char *name)
{
set_name (pthread_self (), "%s", const_cast<char *> (name));
}
ATTRIBUTE_UNUSED static void
set_thread_name (int (*set_name) (pthread_t, const char *), const char *name)
{
set_name (pthread_self (), name);
}
/* The macOS man page says that pthread_setname_np returns "void", but
the headers actually declare it returning "int". */
ATTRIBUTE_UNUSED static void
set_thread_name (int (*set_name) (const char *), const char *name)
{
set_name (name);
}
#endif /* USE_PTHREAD_SETNAME_NP */
namespace gdb
{
/* The thread pool detach()s its threads, so that the threads will not
prevent the process from exiting. However, it was discovered that
if any detached threads were still waiting on a condition variable,
then the condition variable's destructor would wait for the threads
to exit -- defeating the purpose.
Allocating the thread pool on the heap and simply "leaking" it
avoids this problem.
*/
thread_pool *thread_pool::g_thread_pool = new thread_pool ();
thread_pool::~thread_pool ()
{
/* Because this is a singleton, we don't need to clean up. The
threads are detached so that they won't prevent process exit.
And, cleaning up here would be actively harmful in at least one
case -- see the comment by the definition of g_thread_pool. */
}
void
thread_pool::set_thread_count (size_t num_threads)
{
std::lock_guard<std::mutex> guard (m_tasks_mutex);
/* If the new size is larger, start some new threads. */
if (m_thread_count < num_threads)
{
/* Ensure that signals used by gdb are blocked in the new
threads. */
block_signals blocker;
for (size_t i = m_thread_count; i < num_threads; ++i)
{
std::thread thread (&thread_pool::thread_function, this);
thread.detach ();
}
}
/* If the new size is smaller, terminate some existing threads. */
if (num_threads < m_thread_count)
{
for (size_t i = num_threads; i < m_thread_count; ++i)
m_tasks.emplace ();
m_tasks_cv.notify_all ();
}
m_thread_count = num_threads;
}
std::future<void>
thread_pool::post_task (std::function<void ()> func)
{
std::packaged_task<void ()> t (func);
std::future<void> f = t.get_future ();
if (m_thread_count == 0)
{
/* Just execute it now. */
t ();
}
else
{
std::lock_guard<std::mutex> guard (m_tasks_mutex);
m_tasks.emplace (std::move (t));
m_tasks_cv.notify_one ();
}
return f;
}
void
thread_pool::thread_function ()
{
#ifdef USE_PTHREAD_SETNAME_NP
/* This must be done here, because on macOS one can only set the
name of the current thread. */
set_thread_name (pthread_setname_np, "gdb worker");
#endif
/* Ensure that SIGSEGV is delivered to an alternate signal
stack. */
gdb::alternate_signal_stack signal_stack;
while (true)
{
optional<task> t;
{
/* We want to hold the lock while examining the task list, but
not while invoking the task function. */
std::unique_lock<std::mutex> guard (m_tasks_mutex);
while (m_tasks.empty ())
m_tasks_cv.wait (guard);
t = std::move (m_tasks.front());
m_tasks.pop ();
}
if (!t.has_value ())
break;
(*t) ();
}
}
}
#endif /* CXX_STD_THREAD */
| mattstock/binutils-bexkat1 | gdbsupport/thread-pool.cc | C++ | gpl-2.0 | 4,811 |
GCC_VERSION := $(shell $(CONFIG_SHELL) $(PWD)/scripts/gcc-version.sh $(CROSS_COMPILE)gcc)
ifeq ($(GCC_VERSION),0404)
CFLAGS_REMOVE_msm_vfe8x.o = -Wframe-larger-than=1024
endif
ifeq ($(CONFIG_MSM_CAMERA_V4L2),y)
EXTRA_CFLAGS += -Idrivers/media/video/msm/csi
EXTRA_CFLAGS += -Idrivers/media/video/msm/io
EXTRA_CFLAGS += -Idrivers/media/video/msm/sensors
obj-$(CONFIG_MSM_CAMERA) += msm_isp.o msm.o msm_mem.o msm_mctl.o msm_mctl_buf.o msm_mctl_pp.o
obj-$(CONFIG_MSM_CAMERA) += rawchip-v4l2/ io/ sensors/ actuators/ csi/
else
ifeq ($(CONFIG_ARCH_MSM8X60),y)
obj-$(CONFIG_MSM_CAMERA) += msm_camera-8x60.o sensors/
ifeq ($(CONFIG_CAMERA_3D),y)
obj-$(CONFIG_MSM_CAMERA) += msm_camera_liteon.o sensors/
endif
else
ifeq ($(CONFIG_ARCH_MSM7X30),y)
obj-$(CONFIG_MSM_CAMERA) += msm_camera-7x30.o sensors/ rawchip/
else
obj-$(CONFIG_MSM_CAMERA) += msm_camera.o
endif
endif
endif
obj-$(CONFIG_MSM_CAMERA) += msm_axi_qos.o
ifeq ($(CONFIG_MSM_CAMERA_V4L2),y)
obj-$(CONFIG_MSM_CAMERA) += gemini/
obj-$(CONFIG_MSM_CAMERA_FLASH) += flash_v4l2.o
else
obj-$(CONFIG_MSM_CAMERA) += gemini_8x60/
ifeq ($(CONFIG_ARCH_MSM7X27A),y)
obj-$(CONFIG_MSM_CAMERA_FLASH) += flash.o
else
obj-$(CONFIG_MSM_CAMERA_FLASH) += flash_8x60.o
endif
endif
obj-$(CONFIG_ARCH_MSM_ARM11) += msm_vfe7x.o msm_io7x.o
obj-$(CONFIG_ARCH_MSM7X27A) += msm_vfe7x27a.o msm_io_7x27a.o
obj-$(CONFIG_ARCH_MSM7X30) += msm_vfe_7x30.o msm_io_7x30.o msm_vpe1_7x30.o
obj-$(CONFIG_ARCH_QSD8X50) += msm_vfe8x.o msm_vfe8x_proc.o msm_io8x.o
ifdef CONFIG_S5K4E5YX
obj-$(CONFIG_MACH_BLISS) += s5k4e5yx.o s5k4e5yx_reg_bls.o
obj-$(CONFIG_MACH_BLISSC) += s5k4e5yx.o s5k4e5yx_reg_bls.o
obj-$(CONFIG_MACH_PRIMOU) += s5k4e5yx.o s5k4e5yx_reg_pro.o
obj-$(CONFIG_MACH_PRIMOC) += s5k4e5yx.o s5k4e5yx_reg_pro.o
obj-$(CONFIG_MACH_KINGDOM) += s5k4e5yx.o s5k4e5yx_reg_kin.o
endif
ifdef CONFIG_MACH_VISION
obj-$(CONFIG_S5K4E1GX) += s5k4e1gx.o s5k4e1gx_reg.o
endif
ifeq ($(CONFIG_MSM_CAMERA_V4L2),y)
obj-$(CONFIG_ARCH_MSM8X60) += msm_io_8x60_v4l2.o msm_vfe31_v4l2.o msm_vpe_8x60_v4l2.o
else
ifdef CONFIG_CAMERA_ZSL
obj-$(CONFIG_ARCH_MSM8X60) += msm_io_8x60.o msm_vfe_8x60_ZSL.o msm_vpe1_8x60.o
else
ifdef CONFIG_CAMERA_3D
obj-$(CONFIG_ARCH_MSM8X60) += msm_io_8x60.o msm_vfe_8x60.o msm_vpe1_8x60.o
obj-$(CONFIG_ARCH_MSM8X60) += msm_vfe31_liteon.o msm_vpe1_liteon.o
else
obj-$(CONFIG_ARCH_MSM8X60) += msm_io_8x60.o msm_vfe_8x60.o msm_vpe1_8x60.o
endif
endif
endif
obj-$(CONFIG_ARCH_MSM8960) += msm_io_8960.o msm_ispif.o msm_vfe32.o msm_vpe.o
obj-$(CONFIG_MT9T013) += mt9t013.o mt9t013_reg.o
obj-$(CONFIG_SN12M0PZ) += sn12m0pz.o sn12m0pz_reg.o
obj-$(CONFIG_MT9P012) += mt9p012_reg.o
ifeq ($(CONFIG_S5K4E1),y)
ifdef CONFIG_MACH_PRIMOTD
obj-$(CONFIG_S5K4E1) += s5k4e1_td.o s5k4e1_reg_td.o
else
ifdef CONFIG_MACH_GOLFC
obj-$(CONFIG_S5K4E1) += s5k4e1_ff.o s5k4e1_reg_ff.o
else
obj-$(CONFIG_S5K4E1) += s5k4e1.o s5k4e1_reg.o
endif
endif
endif
obj-$(CONFIG_MSM_CAMERA_AF_FOXCONN) += mt9p012_fox.o
obj-$(CONFIG_MSM_CAMERA_AF_BAM) += mt9p012_bam.o
obj-$(CONFIG_MT9P012_KM) += mt9p012_km.o mt9p012_km_reg.o
obj-$(CONFIG_MT9E013) += mt9e013.o mt9e013_reg.o
obj-$(CONFIG_S5K3E2FX) += s5k3e2fx.o
ifdef CONFIG_MACH_PYRAMID
obj-$(CONFIG_S5K3H1GX) += s5k3h1gx.o s5k3h1gx_reg.o
endif
ifdef CONFIG_S5K3H1GX
obj-$(CONFIG_MACH_SPADE) += s5k3h1gx.o s5k3h1gx_reg.o
obj-$(CONFIG_MACH_VIVO) += s5k3h1gx.o s5k3h1gx_reg.o
obj-$(CONFIG_MACH_VIVOW) += s5k3h1gx.o s5k3h1gx_reg.o
obj-$(CONFIG_MACH_VIVOW_CT) += s5k3h1gx.o s5k3h1gx_reg.o
endif
#FIXME: Merge the two ifeq causes VX6953 preview not coming up.
ifeq ($(CONFIG_MSM_CAMERA_V4L2),y)
obj-$(CONFIG_VX6953) += vx6953_v4l2.o vx6953_reg_v4l2.o
obj-$(CONFIG_MT9V113) += mt9v113_v4l2.o mt9v113_ville_reg_lens_9251.o
else
obj-$(CONFIG_MT9V113) += mt9v113.o mt9v113_reg_lens_9251.o
obj-$(CONFIG_VX6953) += vx6953.o vx6953_reg.o
obj-$(CONFIG_IMX074) += imx074.o imx074_reg.o
endif
obj-$(CONFIG_QS_MT9P017) += qs_mt9p017.o qs_mt9p017_reg.o
obj-$(CONFIG_VB6801) += vb6801.o
obj-$(CONFIG_IMX072) += imx072.o imx072_reg.o
obj-$(CONFIG_WEBCAM_OV9726) += ov9726.o ov9726_reg.o
obj-$(CONFIG_WEBCAM_OV7692) += ov7692.o
obj-$(CONFIG_OV8810) += ov8810.o
obj-$(CONFIG_MT9D112) += mt9d112.o mt9d112_reg.o
obj-$(CONFIG_MT9D113) += mt9d113.o mt9d113_reg.o
| teamblueridge/SuperSickKernel | drivers/media/video/msm/Makefile | Makefile | gpl-2.0 | 4,241 |
require 'spec_helper'
require 'boost_trust_level'
describe BoostTrustLevel do
let(:user) { Fabricate(:user, trust_level: TrustLevel.levels[:newuser]) }
let(:logger) { StaffActionLogger.new(Fabricate(:admin)) }
it "should upgrade the trust level of a user" do
boostr = BoostTrustLevel.new(user: user, level: TrustLevel.levels[:basic], logger: logger)
boostr.save!.should be_true
user.trust_level.should == TrustLevel.levels[:basic]
end
it "should log the action" do
StaffActionLogger.any_instance.expects(:log_trust_level_change).with(user, TrustLevel.levels[:newuser], TrustLevel.levels[:basic]).once
boostr = BoostTrustLevel.new(user: user, level: TrustLevel.levels[:basic], logger: logger)
boostr.save!
end
describe "demotions" do
context "for a user that has not done the requisite things to attain their trust level" do
before do
# scenario: admin mistakenly promotes user's trust level
user.update_attributes(trust_level: TrustLevel.levels[:basic])
end
it "should demote the user and log the action" do
StaffActionLogger.any_instance.expects(:log_trust_level_change).with(user, TrustLevel.levels[:basic], TrustLevel.levels[:newuser]).once
boostr = BoostTrustLevel.new(user: user, level: TrustLevel.levels[:newuser], logger: logger)
boostr.save!.should be_true
user.trust_level.should == TrustLevel.levels[:newuser]
end
end
context "for a user that has done the requisite things to attain their trust level" do
before do
user.topics_entered = SiteSetting.basic_requires_topics_entered + 1
user.posts_read_count = SiteSetting.basic_requires_read_posts + 1
user.time_read = SiteSetting.basic_requires_time_spent_mins * 60
user.save!
user.update_attributes(trust_level: TrustLevel.levels[:basic])
end
it "should not demote the user and not log the action" do
StaffActionLogger.any_instance.expects(:log_trust_level_change).never
boostr = BoostTrustLevel.new(user: user, level: TrustLevel.levels[:newuser], logger: logger)
expect { boostr.save! }.to raise_error(Discourse::InvalidAccess, "You attempted to demote #{user.name} to 'newuser'. However their trust level is already 'basic'. #{user.name} will remain at 'basic'")
user.trust_level.should == TrustLevel.levels[:basic]
end
end
end
end
| concordia-publishing-house/discourse | spec/components/boost_trust_level_spec.rb | Ruby | gpl-2.0 | 2,430 |
/*
* ------------------------------------------------------------------------
* JA Slideshow Module for J25 & J31
* ------------------------------------------------------------------------
* Copyright (C) 2004-2011 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
* @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
* Author: J.O.O.M Solutions Co., Ltd
* Websites: http://www.joomlart.com - http://www.joomlancers.com
* ------------------------------------------------------------------------
*/
.ja-slidewrap_erio {
width: 100%;
position: relative;
}
.ja-slide-item img {
background: #fff;
}
.active .ja-slide-thumb-inner {
border: none;
color: #fff;
}
.active .ja-slide-thumb-inner img {
background: #57212A;
border: 1px solid #67373F;
}
.ja-slide-thumbs-mask-left,
.ja-slide-thumbs-mask-right,
.ja-slide-thumbs-mask-center {
float: left;
}
.ja-slide-thumbs-mask-left, .ja-slide-thumbs-mask-right {}
/* Mask Desc */
.maskDesc {
z-index: 11;
top: 0;
}
.main .maskDesc .inner {
padding: 0 0 0 510px;
position: absolute;
top: 252px;
left: 0;
z-index: 12;
}
.maskDesc a.readon {
background: #61abd6;
color: #fff;
padding: 7px 15px 6px;
display: inline-block;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
.maskDesc a.readon span { cursor: pointer; }
.maskDesc a.readmore { margin-top: 30px; }
.maskDesc a.readon:hover, .maskDesc a.readon:active, .maskDesc a.readon:focus {
background: #666;
}
.ja-slide-desc {
position: absolute;
top: 0;
right: 0;
height: 268px;
width: 390px;
background: #000;
opacity: .9;
filter: alpha(opacity = 90);
padding: 52px 40px 40px;
}
div.ja-moduletable .ja-slide-desc h3 {
color: #fff;
font-size: 300%;
}
div.ja-moduletable .ja-slide-desc h3 a { color: #fff; }
.ja-slide-desc p { color: #7b7d80; line-height: 2; }
/* Slide buttons */
#ja-slideshow .ja-slide-buttons {
height: 10px;
position: relative;
top: 10px;
width: 28px;
bottom: 0;
left: 470px !important;
z-index: 50;
}
.ja-slide-buttons .ja-slide-playback, .ja-slide-buttons .ja-slide-stop,
.ja-slide-buttons .ja-slide-play {
display: none !important;
}
.ja-slide-buttons span.ja-slide-prev, .ja-slide-buttons span.ja-slide-next {
width: 10px;
height: 10px;
font-size: 0px;
line-height: 0px;
text-indent: -9999em;
background: url("thumb.png") no-repeat scroll left top;
padding: 0px !important;
margin: 0px 0px 0px 3px !important;
}
.ja-slide-buttons span.ja-slide-prev.hover,
.ja-slide-buttons span.ja-slide-next.hover {
background: url("thumb.png") no-repeat scroll left bottom;
}
.ja-slide-buttons span {
color: #fff;
cursor: pointer;
display: block;
float: left;
margin-right: 5px;
padding: 2px 5px;
background: #61abd6;
}
/* From Articles */
.ja-articles .ja-slide-thumbs-handles,
.ja-slide-thumbs-wrap .ja-slide-thumbs-handles {
opacity: 0.001 !important;
filter: alpha(opacity = 0.10) !important;
background: #000 ;
}
.ja-slide-thumbs, .ja-slide-thumbs-mask, .ja-slide-thumbs-handles {
width: auto;
height: auto;
position: absolute;
top: 0;
left: 0 !important;
}
.ja-slide-thumb-inner {
background: none;
border: none;
margin: 0px !important;
padding: 0px !important;
}
#ja-slideshow .ja-slide-thumb img {
padding: 0px !important;
border: none;
margin: 0px !important;
}
#ja-slideshow .ja-slide-thumbs-wrap {
bottom: 0px;
right: 0px;
background: none;
}
p.ja-slide-thumbs-handles {
z-index: 1000;
}
.ja-slide-thumb .ja-slide-thumb-inner,
.ja-slide-thumbs .ja-slide-thumb {
background: #000 !important;
opacity: 0.3;
filter: alpha(opacity = 30);
}
.ja-slide-thumb.active .ja-slide-thumb-inner,
.ja-slide-thumbs .ja-slide-thumb.active {
opacity: 1;
filter: alpha(opacity = 100);
}
.ja-slide-thumb-inner h3 {
display: none;
}
.ja-slide-thumbs-mask {
background: #000;
opacity: 0.1;
filter: alpha(opacity = 10);
}
.ja-slide-desc a {
color: #fff;
font-size: 300%;
line-height: 1.2;
margin: 0px 0px 25px;
padding: 0px 0px 13px;
background: url(short_hor_line.gif) no-repeat scroll 0 100%;
display: block;
font-family: Helvetica,Arial,sans-serif;
}
.ja-slide-desc a:hover,
.ja-slide-desc a:focus,
.ja-slide-desc a:active {
color: #fff;
} | ForAEdesWeb/AEW29 | modules/mod_jaslideshow/assets/themes/erio/style.css | CSS | gpl-2.0 | 4,436 |
/*
* Copyright (c) 2015, 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.
*/
module test {
// jdk.test.resources.classes.MyResourcesProvider is in named.bundles.
requires named.bundles;
uses jdk.test.resources.classes.MyResourcesProvider;
uses jdk.test.resources.props.MyResourcesProvider;
}
| FauxFaux/jdk9-jdk | test/java/util/ResourceBundle/modules/visibility/src/test/module-info.java | Java | gpl-2.0 | 1,283 |
/*
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "OutdoorPvP.h"
#include "Language.h"
#include "World.h"
#include "ObjectMgr.h"
#include "Object.h"
#include "GameObject.h"
#include "Player.h"
/**
Function that adds a player to the players of the affected outdoor pvp zones
@param player to add
@param whether zone is main outdoor pvp zone or a affected zone
*/
void OutdoorPvP::HandlePlayerEnterZone(Player* player, bool isMainZone)
{
m_zonePlayers[player->GetObjectGuid()] = isMainZone;
}
/**
Function that removes a player from the players of the affected outdoor pvp zones
@param player to remove
@param whether zone is main outdoor pvp zone or a affected zone
*/
void OutdoorPvP::HandlePlayerLeaveZone(Player* player, bool isMainZone)
{
if (m_zonePlayers.erase(player->GetObjectGuid()))
{
// remove the world state information from the player
if (isMainZone && !player->GetSession()->PlayerLogout())
SendRemoveWorldStates(player);
sLog.outDebug("Player %s left an Outdoor PvP zone", player->GetName());
}
}
/**
Function that updates the world state for all the players of the outdoor pvp zone
@param world state to update
@param new world state value
*/
void OutdoorPvP::SendUpdateWorldState(uint32 field, uint32 value)
{
for (GuidZoneMap::const_iterator itr = m_zonePlayers.begin(); itr != m_zonePlayers.end(); ++itr)
{
// only send world state update to main zone
if (!itr->second)
continue;
if (!IsMember(itr->first))
continue;
if (Player* player = sObjectMgr.GetPlayer(itr->first))
player->SendUpdateWorldState(field, value);
}
}
/**
Function that updates world state for all the players in an outdoor pvp map
@param world state it to update
@param value which should update the world state
*/
void OutdoorPvP::SendUpdateWorldStateForMap(uint32 uiField, uint32 uiValue, Map* map)
{
Map::PlayerList const& pList = map->GetPlayers();
for (Map::PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr)
{
if (!itr->getSource() || !itr->getSource()->IsInWorld())
continue;
itr->getSource()->SendUpdateWorldState(uiField, uiValue);
}
}
void OutdoorPvP::HandleGameObjectCreate(GameObject* go)
{
// set initial data and activate capture points
if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_CAPTURE_POINT)
go->SetCapturePointSlider(sOutdoorPvPMgr.GetCapturePointSliderValue(go->GetEntry(), CAPTURE_SLIDER_MIDDLE));
}
void OutdoorPvP::HandleGameObjectRemove(GameObject* go)
{
// save capture point slider value (negative value if locked)
if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_CAPTURE_POINT)
sOutdoorPvPMgr.SetCapturePointSlider(go->GetEntry(), go->getLootState() == GO_ACTIVATED ? go->GetCapturePointSlider() : -go->GetCapturePointSlider());
}
/**
Function that handles player kills in the main outdoor pvp zones
@param player who killed another player
@param victim who was killed
*/
void OutdoorPvP::HandlePlayerKill(Player* killer, Unit* victim)
{
Player* plr = victim->GetCharmerOrOwnerPlayerOrPlayerItself();
if (plr && killer->GetTeam() == plr->GetTeam())
return;
if (Group* group = killer->GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* groupMember = itr->getSource();
if (!groupMember)
continue;
// skip if too far away
if (!groupMember->IsAtGroupRewardDistance(victim))
continue;
// creature kills must be notified, even if not inside objective / not outdoor pvp active
// player kills only count if active and inside objective
if (groupMember->CanUseCapturePoint())
HandlePlayerKillInsideArea(groupMember, victim);
}
}
else
{
// creature kills must be notified, even if not inside objective / not outdoor pvp active
if (killer && killer->CanUseCapturePoint())
HandlePlayerKillInsideArea(killer, victim);
}
}
// apply a team buff for the main and affected zones
void OutdoorPvP::BuffTeam(Team team, uint32 spellId, bool remove /*= false*/, bool onlyMembers /*= true*/, uint32 area /*= 0*/)
{
for (GuidZoneMap::const_iterator itr = m_zonePlayers.begin(); itr != m_zonePlayers.end(); ++itr)
{
Player* player = sObjectMgr.GetPlayer(itr->first);
if (!player)
continue;
if (player && (team == TEAM_NONE || player->GetTeam() == team) && (!onlyMembers || IsMember(player->GetObjectGuid())))
{
if (!area || area == player->GetAreaId())
{
if (remove)
player->RemoveAurasDueToSpell(spellId);
else
player->CastSpell(player, spellId, true);
}
}
}
}
uint32 OutdoorPvP::GetBannerArtKit(Team team, uint32 artKitAlliance /*= CAPTURE_ARTKIT_ALLIANCE*/, uint32 artKitHorde /*= CAPTURE_ARTKIT_HORDE*/, uint32 artKitNeutral /*= CAPTURE_ARTKIT_NEUTRAL*/)
{
switch (team)
{
case ALLIANCE:
return artKitAlliance;
case HORDE:
return artKitHorde;
default:
return artKitNeutral;
}
}
void OutdoorPvP::SetBannerVisual(const WorldObject* objRef, ObjectGuid goGuid, uint32 artKit, uint32 animId)
{
if (GameObject* go = objRef->GetMap()->GetGameObject(goGuid))
SetBannerVisual(go, artKit, animId);
}
void OutdoorPvP::SetBannerVisual(GameObject* go, uint32 artKit, uint32 animId)
{
go->SendGameObjectCustomAnim(go->GetObjectGuid(), animId);
go->SetGoArtKit(artKit);
go->Refresh();
}
void OutdoorPvP::RespawnGO(const WorldObject* objRef, ObjectGuid goGuid, bool respawn)
{
if (GameObject* go = objRef->GetMap()->GetGameObject(goGuid))
{
go->SetRespawnTime(7 * DAY);
if (respawn)
go->Refresh();
else if (go->isSpawned())
go->SetLootState(GO_JUST_DEACTIVATED);
}
}
| cooler-SAI/murlocs_434 | src/game/OutdoorPvP/OutdoorPvP.cpp | C++ | gpl-2.0 | 6,919 |
#!/usr/bin/env python
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software distributed under the License is distributed on an AS IS basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# By David Harrison
# I was playing with doctest when I wrote this. I still haven't
# decided how useful doctest is as opposed to implementing unit tests
# directly. --Dave
if __name__ == '__main__':
import sys
sys.path = ['.','..'] + sys.path # HACK to simplify unit testing.
from BTL.translation import _
class BEGIN: # represents special BEGIN location before first next.
pass
from UserDict import DictMixin
from cmap_swig import *
import sys
from weakref import WeakKeyDictionary
LEAK_TEST = False
class CMap(object,DictMixin):
"""In-order mapping. Provides same operations and behavior as a dict,
but provides in-order iteration. Additionally provides operations to
find the nearest key <= or >= a given key.
This provides a significantly wider set of operations than
berkeley db BTrees, but it provides no means for persistence.
LIMITATION: The key must be a python numeric type, e.g., an integer
or a float. The value can be any python object.
Operation: Time Applicable
Complexity: Methods:
---------------------------------------------------
Item insertion: O(log n) append, __setitem__
Item deletion: O(log n + k) __delitem__, erase
Key search: O(log n) __getitem__, get, find,
__contains__
Value search: n/a
Iteration step: amortized O(1), next, prev
worst-case O(log n)
Memory: O(n)
n = number of elements in map. k = number of iterators pointing
into map. CMap assumes there are few iterators in existence at
any given time.
Iterators are not invalidated by insertions. Iterators are
invalidated by deletions only when the key-value pair
referenced is deleted. Deletion has a '+k' because the
__delitem__ searches linearly through the set of iterators
pointing into this map to find any iterator pointing at the
deleted item and then invalidates the iterator.
This class is backed by the C++ STL map class, but conforms
to the Python container interface."""
class _AbstractIterator:
"""Iterates over elements in the map in order."""
def __init__(self, m, si = BEGIN ): # "s.." implies swig object.
"""Creates an iterator pointing to element si in map m.
Do not instantiate directly. Use iterkeys, itervalues, or
iteritems.
The _AbstractIterator takes ownership of any C++ iterator
(i.e., the swig object 'si') and will deallocate it when
the iterator is deallocated.
Examples of typical behavior:
>>> from CMap import *
>>> m = CMap()
>>> m[12] = 6
>>> m[9] = 4
>>> for k in m:
... print int(k)
...
9
12
>>>
Example edge cases (empty map):
>>> from CMap import *
>>> m = CMap()
>>> try:
... i = m.__iter__()
... i.value()
... except IndexError:
... print 'IndexError.'
...
IndexError.
>>> try:
... i.next()
... except StopIteration:
... print 'stopped'
...
stopped
@param map: CMap.
@param node: Node that this iterator will point at. If None
then the iterator points to end(). If BEGIN
then the iterator points to one before the beginning.
"""
assert isinstance(m, CMap)
assert not isinstance(si, CMap._AbstractIterator)
if si == None:
self._si = map_end(m._smap)
else:
self._si = si # C++ iterator wrapped by swig.
self._map = m
m._iterators[self] = 1 # using map as set of weak references.
def __hash__(self):
return id(self)
def __cmp__(self, other):
if not self._si or not other._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN and other._si == BEGIN: return 0
if self._si == BEGIN and other._si != BEGIN: return -1
elif self._si != BEGIN and other._si == BEGIN: return 1
return iter_cmp(self._map._smap, self._si, other._si )
def at_begin(self):
"""equivalent to self == m.begin() where m is a CMap.
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.begin()
>>> i == m.begin()
True
>>> i.at_begin()
True
>>> i == m.end() # no elements so begin()==end()
True
>>> i.at_end()
True
>>> m[6] = 'foo' # insertion does not invalidate iterators.
>>> i = m.begin()
>>> i == m.end()
False
>>> i.value()
'foo'
>>> try: # test at_begin when not at beginning.
... i.next()
... except StopIteration:
... print 'ok'
ok
>>> i.at_begin()
False
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN: # BEGIN is one before begin(). Yuck!!
return False
return map_iter_at_begin(self._map._smap, self._si)
def at_end(self):
"""equivalent to self == m.end() where m is a CMap, but
at_end is faster because it avoids the dynamic memory
alloation in m.end().
>>> from CMap import CMap
>>> m = CMap()
>>> m[6] = 'foo'
>>> i = m.end() # test when at end.
>>> i == m.end()
True
>>> i.at_end()
True
>>> int(i.prev())
6
>>> i.at_end() # testing when not at end.
False
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
return False
return map_iter_at_end(self._map._smap, self._si)
def key(self):
"""@return: the key of the key-value pair referenced by this
iterator.
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
raise IndexError(_("Cannot dereference iterator until after "
"first call to .next."))
elif map_iter_at_end(self._map._smap, self._si):
raise IndexError()
return iter_key(self._si)
def value(self):
"""@return: the value of the key-value pair currently referenced
by this iterator.
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
raise IndexError(_("Cannot dereference iterator until after "
"first call to next."))
elif map_iter_at_end(self._map._smap, self._si):
raise IndexError()
return iter_value(self._si)
def item(self):
"""@return the key-value pair referenced by this iterator.
"""
if not self._si:
raise RuntimeError( _("invalid iterator") )
return self.key(), self.value()
def _next(self):
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
self._si = map_begin(self._map._smap)
if map_iter_at_end(self._map._smap,self._si):
raise StopIteration
return
if map_iter_at_end(self._map._smap,self._si):
raise StopIteration
iter_incr(self._si)
if map_iter_at_end(self._map._smap,self._si):
raise StopIteration
def _prev(self):
if not self._si:
raise RuntimeError( _("invalid iterator") )
if self._si == BEGIN:
raise StopIteration()
elif map_iter_at_begin(self._map._smap, self._si):
self._si = BEGIN
raise StopIteration
iter_decr(self._si)
def __del__(self):
# Python note: if a reference to x is intentionally
# eliminated using "del x" and there are other references
# to x then __del__ does not get called at this time.
# Only when the last reference is deleted by an intentional
# "del" or when the reference goes out of scope does
# the __del__ method get called.
self._invalidate()
def _invalidate(self):
if self._si == None:
return
try:
del self._map._iterators[self]
except KeyError:
pass # could've been removed because weak reference,
# and because _invalidate is called from __del__.
if self._si != BEGIN:
iter_delete(self._si)
self._si = None
def __iter__(self):
"""If the iterator is itself iteratable then we do things like:
>>> from CMap import CMap
>>> m = CMap()
>>> m[10] = 'foo'
>>> m[11] = 'bar'
>>> for x in m.itervalues():
... print x
...
foo
bar
"""
return self
def __len__(self):
return len(self._map)
class KeyIterator(_AbstractIterator):
def next(self):
"""Returns the next key in the map.
Insertion does not invalidate iterators. Deletion only
invalidates an iterator if the iterator pointed at the
key-value pair being deleted.
This is implemented by moving the iterator and then
dereferencing it. If we dereferenced and then moved
then we would get the odd behavior:
Ex: I have keys [1,2,3]. The iterator i points at 1.
print i.next() # prints 1
print i.next() # prints 2
print i.prev() # prints 3
print i.prev() # prints 2
However, because we move and then dereference, when an
iterator is first created it points to nowhere
so that the first next moves to the first element.
Ex:
>>> from CMap import *
>>> m = CMap()
>>> m[5] = 1
>>> m[8] = 4
>>> i = m.__iter__()
>>> print int(i.next())
5
>>> print int(i.next())
8
>>> print int(i.prev())
5
We are still left with the odd behavior that an
iterator cannot be dereferenced until after the first next().
Ex edge cases:
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.__iter__()
>>> try:
... i.prev()
... except StopIteration:
... print 'StopIteration'
...
StopIteration
>>> m[5]='a'
>>> i = m.iterkeys()
>>> int(i.next())
5
>>> try: i.next()
... except StopIteration: print 'StopIteration'
...
StopIteration
>>> int(i.prev())
5
>>> try: int(i.prev())
... except StopIteration: print 'StopIteration'
...
StopIteration
>>> int(i.next())
5
"""
self._next()
return self.key()
def prev(self):
"""Returns the previous key in the map.
See next() for more detail and examples.
"""
self._prev()
return self.key()
class ValueIterator(_AbstractIterator):
def next(self):
"""@return: next value in the map.
>>> from CMap import *
>>> m = CMap()
>>> m[5] = 10
>>> m[6] = 3
>>> i = m.itervalues()
>>> int(i.next())
10
>>> int(i.next())
3
"""
self._next()
return self.value()
def prev(self):
self._prev()
return self.value()
class ItemIterator(_AbstractIterator):
def next(self):
"""@return: next item in the map's key ordering.
>>> from CMap import CMap
>>> m = CMap()
>>> m[5] = 10
>>> m[6] = 3
>>> i = m.iteritems()
>>> k,v = i.next()
>>> int(k)
5
>>> int(v)
10
>>> k,v = i.next()
>>> int(k)
6
>>> int(v)
3
"""
self._next()
return self.key(), self.value()
def prev(self):
self._prev()
return self.key(), self.value()
def __init__(self, d={} ):
"""Instantiate RBTree containing values from passed dict and
ordered based on cmp.
>>> m = CMap()
>>> len(m)
0
>>> m[5]=2
>>> len(m)
1
>>> print m[5]
2
"""
#self._index = {} # to speed up searches.
self._smap = map_constructor() # C++ map wrapped by swig.
for key, value in d.items():
self[key]=value
self._iterators = WeakKeyDictionary()
# whenever node is deleted. search iterators
# for any iterator that becomes invalid.
def __contains__(self,x):
return self.get(x) != None
def __iter__(self):
"""@return: KeyIterator positioned one before the beginning of the
key ordering so that the first next() returns the first key."""
return CMap.KeyIterator(self)
def begin(self):
"""Returns an iterator pointing at first key-value pair. This
differs from iterkeys, itervalues, and iteritems which return an
iterator pointing one before the first key-value pair.
@return: key iterator to first key-value.
>>> from CMap import *
>>> m = CMap()
>>> m[5.0] = 'a'
>>> i = m.begin()
>>> int(i.key()) # raises no IndexError.
5
>>> i = m.iterkeys()
>>> try:
... i.key()
... except IndexError:
... print 'IndexError raised'
...
IndexError raised
"""
i = CMap.KeyIterator(self, map_begin(self._smap) )
return i
def end(self):
"""Returns an iterator pointing after end of key ordering.
The iterator's prev method will move to the last
key-value pair in the ordering. This in keeping with
the notion that a range is specified as [i,j) where
j is not in the range, and the range [i,j) where i==j
is an empty range.
This operation takes O(1) time.
@return: key iterator one after end.
"""
i = CMap.KeyIterator(self,None) # None means one after last node.
return i
def iterkeys(self):
return CMap.KeyIterator(self)
def itervalues(self):
return CMap.ValueIterator(self)
def iteritems(self):
return CMap.ItemIterator(self)
def __len__(self):
return map_size(self._smap)
def __str__(self):
s = "{"
first = True
for k,v in self.items():
if first:
first = False
else:
s += ", "
if type(v) == str:
s += "%s: '%s'" % (k,v)
else:
s += "%s: %s" % (k,v)
s += "}"
return s
def __repr__(self):
return self.__str__()
def __getitem__(self, key):
# IMPL 1: without _index
return map_find(self._smap,key) # raises KeyError if key not found
# IMPL 2: with _index.
#return iter_value(self._index[key])
def __setitem__(self, key, value):
"""
>>> from CMap import CMap
>>> m = CMap()
>>> m[6] = 'bar'
>>> m[6]
'bar'
>>>
"""
assert type(key) == int or type(key) == float
# IMPL 1. without _index.
map_set(self._smap,key,value)
## IMPL 2. with _index
## If using indices following allows us to perform only one search.
#i = map_insert_iter(self._smap,key,value)
#if iter_value(i) != value:
# iter_set(i,value)
#else: self._index[key] = i
## END IMPL2
def __delitem__(self, key):
"""Deletes the item with matching key from the map.
This takes O(log n + k) where n is the number of elements
in the map and k is the number of iterators pointing into the map.
Before deleting the item it linearly searches through
all iterators pointing into the map and invalidates any that
are pointing at the item about to be deleted.
>>> from CMap import CMap
>>> m = CMap()
>>> m[12] = 'foo'
>>> m[13] = 'bar'
>>> m[14] = 'boo'
>>> del m[12]
>>> try:
... m[12]
... except KeyError:
... print 'ok'
...
ok
>>> j = m.begin()
>>> int(j.next())
14
>>> i = m.begin()
>>> i.value()
'bar'
>>> del m[13] # delete object referenced by an iterator
>>> try:
... i.value()
... except RuntimeError:
... print 'ok'
ok
>>> j.value() # deletion should not invalidate other iterators.
'boo'
"""
#map_erase( self._smap, key ) # map_erase is dangerous. It could
# delete the node causing an iterator
# to become invalid. --Dave
si = map_find_iter( self._smap, key ) # si = swig'd iterator.
if map_iter_at_end(self._smap, si):
iter_delete(si)
raise KeyError(key)
for i in list(self._iterators):
if iter_cmp( self._smap, i._si, si ) == 0:
i._invalidate()
map_iter_erase( self._smap, si )
iter_delete(si)
#iter_delete( self._index[key] ) # IMPL 2. with _index.
#del self._index[key] # IMPL 2. with _index.
def erase(self, iter):
"""Remove item pointed to by the iterator. All iterators that
point at the erased item including the passed iterator
are immediately invalidated after the deletion completes.
>>> from CMap import CMap
>>> m = CMap()
>>> m[12] = 'foo'
>>> i = m.find(12)
>>> m.erase(i)
>>> len(m) == 0
True
"""
if not iter._si:
raise RuntimeError( _("invalid iterator") )
if iter._si == BEGIN:
raise IndexError(_("Iterator does not point at key-value pair" ))
if self is not iter._map:
raise IndexError(_("Iterator points into a different CMap."))
if map_iter_at_end(self._smap, iter._si):
raise IndexError( _("Cannot erase end() iterator.") )
# invalidate iterators.
for i in list(self._iterators):
if iter._si is not i._si and iiter_cmp( self._smmap, iter._si, i._si ) == 0:
i._invalidate()
# remove item from the map.
map_iter_erase( self._smap, iter._si )
# invalidate last iterator pointing to the deleted location in the map.
iter._invalidate()
def __del__(self):
# invalidate all iterators.
for i in list(self._iterators):
i._invalidate()
map_delete(self._smap)
def get(self, key, default=None):
"""@return value corresponding to specified key or return 'default'
if the key is not found.
"""
try:
return map_find(self._smap,key) # IMPL 1. without _index.
#return iter_value(self._index[key]) # IMPL 2. with _index.
except KeyError:
return default
def keys(self):
"""
>>> from CMap import *
>>> m = CMap()
>>> m[4.0] = 7
>>> m[6.0] = 3
>>> [int(x) for x in m.keys()] # m.keys() but guaranteed integers.
[4, 6]
"""
k = []
for key in self:
k.append(key)
return k
def values(self):
"""
>>> from CMap import CMap
>>> m = CMap()
>>> m[4.0] = 7
>>> m[6.0] = 3
>>> m.values()
[7, 3]
"""
i = self.itervalues()
v = []
try:
while True:
v.append(i.next())
except StopIteration:
pass
return v
def items(self):
"""
>>> from CMap import CMap
>>> m = CMap()
>>> m[4.0] = 7
>>> m[6.0] = 3
>>> [(int(x[0]),int(x[1])) for x in m.items()]
[(4, 7), (6, 3)]
"""
i = self.iteritems()
itms = []
try:
while True:
itms.append(i.next())
except StopIteration:
pass
return itms
def has_key(self, key):
"""
>>> from CMap import CMap
>>> m = CMap()
>>> m[4.0] = 7
>>> if m.has_key(4): print 'ok'
...
ok
>>> if not m.has_key(7): print 'ok'
...
ok
"""
try:
self[key]
except KeyError:
return False
return True
def clear(self):
"""delete all entries
>>> from CMap import CMap
>>> m = CMap()
>>> m[4] = 7
>>> m.clear()
>>> print len(m)
0
"""
self.__del__()
self._smap = map_constructor()
def copy(self):
"""return shallow copy"""
return CMap(self)
def lower_bound(self,key):
"""
Finds smallest key equal to or above the lower bound.
Takes O(log n) time.
@param x: Key of (key, value) pair to be located.
@return: Key Iterator pointing to first item equal to or greater
than key, or end() if no such item exists.
>>> from CMap import CMap
>>> m = CMap()
>>> m[10] = 'foo'
>>> m[15] = 'bar'
>>> i = m.lower_bound(11) # iterator.
>>> int(i.key())
15
>>> i.value()
'bar'
Edge cases:
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.lower_bound(11)
>>> if i == m.end(): print 'ok'
...
ok
>>> m[10] = 'foo'
>>> i = m.lower_bound(11)
>>> if i == m.end(): print 'ok'
...
ok
>>> i = m.lower_bound(9)
>>> if i == m.begin(): print 'ok'
...
ok
"""
return CMap.KeyIterator(self, map_lower_bound( self._smap, key ))
def upper_bound(self, key):
"""
Finds largest key equal to or below the upper bound. In keeping
with the [begin,end) convention, the returned iterator
actually points to the key one above the upper bound.
Takes O(log n) time.
@param x: Key of (key, value) pair to be located.
@return: Iterator pointing to first element equal to or greater than
key, or end() if no such item exists.
>>> from CMap import CMap
>>> m = CMap()
>>> m[10] = 'foo'
>>> m[15] = 'bar'
>>> m[17] = 'choo'
>>> i = m.upper_bound(11) # iterator.
>>> i.value()
'bar'
Edge cases:
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.upper_bound(11)
>>> if i == m.end(): print 'ok'
...
ok
>>> m[10] = 'foo'
>>> i = m.upper_bound(9)
>>> i.value()
'foo'
>>> i = m.upper_bound(11)
>>> if i == m.end(): print 'ok'
...
ok
"""
return CMap.KeyIterator(self, map_upper_bound( self._smap, key ))
def find(self,key):
"""
Finds the item with matching key and returns a KeyIterator
pointing at the item. If no match is found then returns end().
Takes O(log n) time.
>>> from CMap import CMap
>>> m = CMap()
>>> i = m.find(10)
>>> if i == m.end(): print 'ok'
...
ok
>>> m[10] = 'foo'
>>> i = m.find(10)
>>> int(i.key())
10
>>> i.value()
'foo'
"""
return CMap.KeyIterator(self, map_find_iter( self._smap, key ))
def update_key( self, iter, key ):
"""
Modifies the key of the item referenced by iter. If the
key change is small enough that no reordering occurs then
this takes amortized O(1) time. If a reordering occurs then
this takes O(log n).
WARNING!!! The passed iterator MUST be assumed to be invalid
upon return and should be deallocated.
Typical use:
>>> from CMap import CMap
>>> m = CMap()
>>> m[10] = 'foo'
>>> m[8] = 'bar'
>>> i = m.find(10)
>>> m.update_key(i,7) # i is assumed to be invalid upon return.
>>> del i
>>> [(int(x[0]),x[1]) for x in m.items()] # reordering occurred.
[(7, 'foo'), (8, 'bar')]
>>> i = m.find(8)
>>> m.update_key(i,9) # no reordering.
>>> del i
>>> [(int(x[0]),x[1]) for x in m.items()]
[(7, 'foo'), (9, 'bar')]
Edge cases:
>>> i = m.find(7)
>>> i.value()
'foo'
>>> try: # update to key already in the map.
... m.update_key(i,9)
... except KeyError:
... print 'ok'
...
ok
>>> m[7]
'foo'
>>> i = m.iterkeys()
>>> try: # updating an iter pointing at BEGIN.
... m.update_key(i,10)
... except IndexError:
... print 'ok'
...
ok
>>> i = m.end()
>>> try: # updating an iter pointing at end().
... m.update_key(i,10)
... except IndexError:
... print 'ok'
...
ok
"""
assert isinstance(iter,CMap._AbstractIterator)
if iter._si == BEGIN:
raise IndexError( _("Iterator does not point at key-value pair") )
if self is not iter._map:
raise IndexError(_("Iterator points into a different CIndexedMap."))
if map_iter_at_end(self._smap, iter._si):
raise IndexError( _("Cannot update end() iterator.") )
map_iter_update_key(self._smap, iter._si, key)
def append(self, key, value):
"""Performs an insertion with the hint that it probably should
go at the end.
Raises KeyError if the key is already in the map.
>>> from CMap import CMap
>>> m = CMap()
>>> m.append(5.0,'foo') # append to empty map.
>>> len(m)
1
>>> [int(x) for x in m.keys()] # see note (1)
[5]
>>> m.append(10.0, 'bar') # append in-order
>>> [(int(x[0]),x[1]) for x in m.items()]
[(5, 'foo'), (10, 'bar')]
>>> m.append(3.0, 'coo') # out-of-order.
>>> [(int(x[0]),x[1]) for x in m.items()]
[(3, 'coo'), (5, 'foo'), (10, 'bar')]
>>> try:
... m.append(10.0, 'blah') # append key already in map.
... except KeyError:
... print 'ok'
...
ok
>>> [(int(x[0]),x[1]) for x in m.items()]
[(3, 'coo'), (5, 'foo'), (10, 'bar')]
>>>
note (1): int(x[0]) is used because 5.0 can appear as either 5
or 5.0 depending on the version of python.
"""
map_append(self._smap,key,value)
class CIndexedMap(CMap):
"""This is an ordered mapping, exactly like CMap except that it
provides a cross-index allowing average O(1) searches based on value.
This adds the constraint that values must be unique.
Operation: Time Applicable
Complexity: Methods:
---------------------------------------------------
Item insertion: O(log n) append, __setitem__
Item deletion: O(log n + k) __delitem__, erase
Key search: O(log n) __getitem__, get, find,
__contains__
Value search: average O(1) as per dict
Iteration step: amortized O(1), next, prev
worst-case O(log n)
Memory: O(n)
n = number of elements in map. k = number of iterators pointing
into map. CIndexedMap assumes there are few iterators in existence
at any given time.
The hash table increases the factor in the
O(n) memory cost of the Map by a constant
"""
def __init__(self, dict={} ):
CMap.__init__(self,dict)
self._value_index = {} # cross-index. maps value->iterator.
def __setitem__(self, key, value):
"""
>>> from CMap import *
>>> m = CIndexedMap()
>>> m[6] = 'bar'
>>> m[6]
'bar'
>>> int(m.get_key_by_value('bar'))
6
>>> try:
... m[7] = 'bar'
... except ValueError:
... print 'value error'
value error
>>> m[6] = 'foo'
>>> m[6]
'foo'
>>> m[7] = 'bar'
>>> m[7]
'bar'
>>> m[7] = 'bar' # should not raise exception
>>> m[7] = 'goo'
>>> m.get_key_by_value('bar') # should return None.
>>>
"""
assert type(key) == int or type(key) == float
if self._value_index.has_key(value) and \
iter_key(self._value_index[value]) != key:
raise ValueError( _("Value %s already exists. Values must be "
"unique.") % str(value) )
si = map_insert_iter(self._smap,key,value) # si points where insert
# should occur whether
# insert succeeded or not.
# si == "swig iterator"
sival = iter_value(si)
if sival != value: # if insert failed because k already exists
iter_set(si,value) # then force set.
self._value_index[value] = si
viter = self._value_index[sival]
iter_delete(viter) # remove old value from index
del self._value_index[sival]
else: # else insert succeeded so update index.
self._value_index[value] = si
#self._index[key] = si # IMPL 2. with _index.
def __delitem__(self, key):
"""
>>> from CMap import CIndexedMap
>>> m = CIndexedMap()
>>> m[6] = 'bar'
>>> m[6]
'bar'
>>> int(m.get_key_by_value('bar'))
6
>>> del m[6]
>>> if m.get_key_by_value('bar'):
... print 'found'
... else:
... print 'not found.'
not found.
"""
i = map_find_iter( self._smap, key )
if map_iter_at_end( self._smap, i ):
iter_delete(i)
raise KeyError(key)
else:
value = iter_value(i)
for i in list(self._iterators):
if iter_cmp( self._smap, i._si, iter._si ) == 0:
i._invalidate()
map_iter_erase( self._smap, i )
viter = self._value_index[value]
iter_delete(i)
iter_delete( viter )
del self._value_index[value]
#del self._index[key] # IMPL 2. with _index.
assert map_size(self._smap) == len(self._value_index)
def has_value(self, value):
return self._value_index.has_key(value)
def get_key_by_value(self, value):
"""Returns the key cross-indexed from the passed unique value, or
returns None if the value is not in the map."""
si = self._value_index.get(value) # si == "swig iterator"
if si == None: return None
return iter_key(si)
def append( self, key, value ):
"""See CMap.append
>>> from CMap import CIndexedMap
>>> m = CIndexedMap()
>>> m.append(5,'foo')
>>> [(int(x[0]),x[1]) for x in m.items()]
[(5, 'foo')]
>>> m.append(10, 'bar')
>>> [(int(x[0]),x[1]) for x in m.items()]
[(5, 'foo'), (10, 'bar')]
>>> m.append(3, 'coo') # out-of-order.
>>> [(int(x[0]),x[1]) for x in m.items()]
[(3, 'coo'), (5, 'foo'), (10, 'bar')]
>>> int(m.get_key_by_value( 'bar' ))
10
>>> try:
... m.append(10, 'blah') # append key already in map.
... except KeyError:
... print 'ok'
...
ok
>>> [(int(x[0]),x[1]) for x in m.items()]
[(3, 'coo'), (5, 'foo'), (10, 'bar')]
>>> try:
... m.append(10, 'coo') # append value already in map.
... except ValueError:
... print 'ok'
...
ok
"""
if self._value_index.has_key(value) and \
iter_key(self._value_index[value]) != key:
raise ValueError(_("Value %s already exists and value must be "
"unique.") % str(value) )
si = map_append_iter(self._smap,key,value)
if iter_value(si) != value:
iter_delete(si)
raise KeyError(key)
self._value_index[value] = si
def find_key_by_value(self, value):
"""Returns a key iterator cross-indexed from the passed unique value
or end() if no value found.
>>> from Map import *
>>> m = CIndexedMap()
>>> m[6] = 'abc'
>>> i = m.find_key_by_value('abc')
>>> int(i.key())
6
>>> i = m.find_key_by_value('xyz')
>>> if i == m.end(): print 'i points at end()'
i points at end()
"""
si = self._value_index.get(value) # si == "swig iterator."
if si != None:
si = iter_copy(si); # copy else operations like increment on the
# KeyIterator would modify the value index.
return CMap.KeyIterator(self,si)
def copy(self):
"""return shallow copy"""
return CIndexedMap(self)
def update_key( self, iter, key ):
"""
see CMap.update_key.
WARNING!! You MUST assume that the passed iterator is invalidated
upon return.
Typical use:
>>> from CMap import CIndexedMap
>>> m = CIndexedMap()
>>> m[10] = 'foo'
>>> m[8] = 'bar'
>>> i = m.find(10)
>>> m.update_key(i,7) # i is assumed to be invalid upon return.
>>> del i
>>> int(m.get_key_by_value('foo'))
7
>>> [(int(x[0]),x[1]) for x in m.items()] # reordering occurred.
[(7, 'foo'), (8, 'bar')]
>>> i = m.find(8)
>>> m.update_key(i,9) # no reordering.
>>> del i
>>> [(int(x[0]),x[1]) for x in m.items()]
[(7, 'foo'), (9, 'bar')]
Edge cases:
>>> i = m.find(7)
>>> i.value()
'foo'
>>> try:
... m.update_key(i,9)
... except KeyError:
... print 'ok'
...
ok
>>> m[7]
'foo'
>>> int(m.get_key_by_value('foo'))
7
>>> i = m.iterkeys()
>>> try: # updating an iter pointing at BEGIN.
... m.update_key(i,10)
... except IndexError:
... print 'ok'
...
ok
>>> i = m.end()
>>> try: # updating an iter pointing at end().
... m.update_key(i,10)
... except IndexError:
... print 'ok'
...
ok
"""
if not iter._si:
raise RuntimeError( _("invalid iterator") )
if iter._si == BEGIN:
raise IndexError(_("Iterator does not point at key-value pair" ))
if self is not iter._map:
raise IndexError(_("Iterator points into a different "
"CIndexedMap."))
if map_iter_at_end(self._smap, iter._si):
raise IndexError( _("Cannot update end() iterator.") )
si = map_iter_update_key_iter(self._smap, iter._si, key)
# raises KeyError if key already in map.
if si != iter._si: # if map is reordered...
value = iter.value();
val_si = self._value_index[value]
iter_delete(val_si)
self._value_index[value] = si
def erase(self, iter):
"""Remove item pointed to by the iterator. Iterator is immediately
invalidated after the deletion completes."""
if not iter._si:
raise RuntimeError( _("invalid iterator") )
if iter._si == BEGIN:
raise IndexError(_("Iterator does not point at key-value pair." ))
if self is not iter._map:
raise IndexError(_("Iterator points into a different "
"CIndexedMap."))
if map_iter_at_end(self._smap, iter._si):
raise IndexError( _("Cannot update end() iterator.") )
value = iter.value()
CMap.erase(self,iter)
del self._value_index[value]
if __name__ == "__main__":
import doctest
import random
##############################################
# UNIT TESTS
print "Testing module"
doctest.testmod(sys.modules[__name__])
print "doctest complete."
##############################################
# MEMORY LEAK TESTS
if LEAK_TEST:
i = 0
import gc
class X:
x = range(1000) # something moderately big.
# TEST 1. This does not cause memory to grow.
#m = CMap()
#map_insert(m._smap,10,X())
#while True:
# i += 1
# it = map_find_iter( m._smap, 10 )
# iter_delete(it)
# del it
# if i % 100 == 0:
# gc.collect()
# TEST 2: This does not caus a memory leak.
#m = map_constructor_double()
#while True:
# i += 1
# map_insert_double(m,10,5) # here
# it = map_find_iter_double( m, 10 )
# map_iter_erase_double( m, it ) # or here is the problem.
# iter_delete_double(it)
# del it
# #assert len(m) == 0
# assert map_size_double(m) == 0
# if i % 100 == 0:
# gc.collect()
# TEST 3. No memory leak
#m = CMap()
#while True:
# i += 1
# map_insert(m._smap,10,X()) # here
# it = map_find_iter( m._smap, 10 )
# map_iter_erase( m._smap, it ) # or here is the problem.
# iter_delete(it)
# del it
# assert len(m) == 0
# assert map_size(m._smap) == 0
# if i % 100 == 0:
# gc.collect()
# TEST 4: map creation and deletion.
#while True:
# m = map_constructor()
# map_delete(m);
# TEST 5: test iteration.
#m = map_constructor()
#for i in xrange(10):
# map_insert(m,i,X())
#while True:
# i = map_begin(m)
# while not map_iter_at_begin(m,i):
# iter_incr(i)
# iter_delete(i)
# TEST 6:
#m = map_constructor()
#for i in xrange(10):
# map_insert(m,i,X())
#while True:
# map_find( m, random.randint(0,9) )
# TEST 7:
#m = map_constructor()
#for i in xrange(50):
# map_insert( m, i, X() )
#while True:
# for i in xrange(50):
# map_set( m, i, X() )
# TEST 8
# aha! Another leak! Fixed.
#m = map_constructor()
#while True:
# i += 1
# map_insert(m,10,X())
# map_erase(m,10)
# assert map_size(m) == 0
# TEST 9
m = map_constructor()
for i in xrange(50):
map_insert( m, i, X() )
while True:
it = map_find_iter( m, 5 )
map_iter_update_key( m, it, 1000 )
iter_delete(it)
it = map_find_iter( m, 1000 )
map_iter_update_key( m, it, 5)
iter_delete(it)
| sulaweyo/torrentflux-b4rt-php7 | html/bin/clients/mainline/BTL/CMap.py | Python | gpl-2.0 | 44,894 |
/* SPDX-License-Identifier: LGPL-2.1+ */
#pragma once
#define VERB_ANY ((unsigned) -1)
typedef enum VerbFlags {
VERB_DEFAULT = 1 << 0,
VERB_ONLINE_ONLY = 1 << 1,
VERB_MUST_BE_ROOT = 1 << 2,
} VerbFlags;
typedef struct {
const char *verb;
unsigned min_args, max_args;
VerbFlags flags;
int (* const dispatch)(int argc, char *argv[], void *userdata);
} Verb;
bool running_in_chroot_or_offline(void);
int dispatch_verb(int argc, char *argv[], const Verb verbs[], void *userdata);
| martinpitt/systemd | src/basic/verbs.h | C | gpl-2.0 | 543 |
/* SPDX-License-Identifier: LGPL-2.1+ */
/***
This file is part of systemd.
Copyright 2010 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 "hostname-setup.h"
#include "util.h"
int main(int argc, char* argv[]) {
int r;
r = hostname_setup();
if (r < 0)
log_error_errno(r, "hostname: %m");
return 0;
}
| Mic92/systemd | src/test/test-hostname.c | C | gpl-2.0 | 980 |
/* NSDate+MAPIStore.h - this file is part of SOGo
*
* Copyright (C) 2010-2012 Inverse inc.
*
* Author: Wolfgang Sourdeau <wsourdeau@inverse.ca>
*
* This file 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.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef NSCALENDARDATE_MAPISTORE_H
#define NSCALENDARDATE_MAPISTORE_H
#import <Foundation/NSDate.h>
@class NSCalendarDate;
@interface NSDate (MAPIStoreDataTypes)
+ (NSCalendarDate *) dateFromMinutesSince1601: (uint32_t) minutes;
- (uint32_t) asMinutesSince1601;
+ (id) dateFromFileTime: (const struct FILETIME *) timeValue;
- (struct FILETIME *) asFileTimeInMemCtx: (void *) memCtx;
- (BOOL) isNever; /* occurs on 4500-12-31 */
+ (NSCalendarDate *) dateFromSystemTime: (struct SYSTEMTIME) date
andRuleYear: (uint16_t) rYear;
@end
NSComparisonResult NSDateCompare (id date1, id date2, void *);
#endif /* NSCALENDARDATE+MAPISTORE_H */
| SlavekB/sogo | OpenChange/NSDate+MAPIStore.h | C | gpl-2.0 | 1,545 |
### 1.7.3 - 15/04/2015
Changes:
* Fixed #114 Background image appears when page is loading
### 1.7.1 - 08/04/2015
Changes:
* Fixed XSS vulnerability with contact form
### 1.7.1 - 07/04/2015
Changes:
* Padding issue
* Fixed #104 No image appears on the blog page on IE8
### 1.6.9 - 04/04/2015
Changes:
* Fixed #85, error in js, when contact form is not displayed, which caused about us circles to stop working
* Fixed #82, problem with Our Focus widget colors
* Replaced screenshot with the new format
1200x900
.jpg -> .png
* Merge pull request #87 from DragosBubu/development
Replaced screenshot with the new format
* Fixed #80 No Compatible with IE9
* Fixed #94 WooCommerce Pagination Issue
* Fixed #95 Featured products issue
* This fixes #88
New screenshot
* Merge pull request #96 from DragosBubu/development
This fixes #88
* Fixed #99, removed sidebar from woocommerce templates
* Fixed #100, removed sidebar from checkout page
* Fixed #101, theme not loading on IE8, included scrollReveal.js for versions greater then IE8
* H tags incompatible with plugins
* Fixed large bottom padding on frontpage sections
* Introduced new (large) template for Blog
* Fixed #103 Blog alignment problem
* Fixed #105 New blog template looks very bad on IE8
### 1.6.0 - 17/03/2015
Changes:
* Woocommerce style issues
* Fixed Shop page mobile issue
* Fixed #79 Responsive menu issues
* Fixed #78, added author link for testimonial widget
### 1.5.4 - 05/03/2015
Changes:
* Latest news issue on iPad
* Woocommerce display for older versions
* Branding
- Modified background image
+ added focus images
* Branding - follow-up
removed unnecessary images
added screenshot
* Replaced screenshot
* Merge pull request #74 from DragosBubu/development
Branding
### 1.4.7 - 12/02/2015
Changes:
* Fixed #62, #51 our team widgets default alignment
* Increased version
### 1.4.6 - 06/02/2015
Changes:
* Open social links in new tab
Open social links in new tab
* added travis
added travis
* fixed travis
* fixed syntax error
* Update style.css
* Merge pull request #56 from HardeepAsrani/development
Open social links in new tab
* remove travis
### 1.4.5 - 30/01/2015
Changes:
* Update style.css
* Update customizer.php
### 1.4.5 - 30/01/2015
Changes:
* Update style.css
* Update style.css
* Update style.css
* Fixed #42, big title enclosing tag h1 , not h6
* Fixed #44, disable preloader from customizer
* Fix #38, fixed our focus section hover colors
* Fixed #48, replace wp product review by login customizer
* Fixed #41, reversed telephone and mail icons in footer
* Fixed #40, fixed team member widgets for more than 4
* Fixed #32, load customizer scripts just in customizer, not in all backend pages
* Fix #16, hover efects for our focus widgets, when more than 4
### 1.4.4 - 19/01/2015
Changes:
* This fixes #35, translate strings plus generate pot file
* Fixes our focus centering when theme is first installed
* Update style.css
### 1.4.3 - 09/01/2015
Changes:
* This fixes #31 , translation issue
* This fixes #30, wrong textdomain
* This fixes #28, header cuts of title on mobile
* This fixes #9, overlap header with text
* Aliniere compononete Our focus
* Footer apare in partea de jos a ecranului, dar nu a site-ului
* This fixes #22, .pot file
### 1.4.2 - 08/01/2015
Changes:
* This fixes #13 upsell in customizer
* This fixes #22, updated pot file
* THis fixes #15, responsive background image
* This fixes #23, changing section names in customizer
* This fixes #24, hover radio buttons, + update style version
* Cart without sidebar
* This fixes #25, remove widget customizer for wp greater versions
### 1.4.1 - 02/01/2015
Changes:
* disable fonts for some languages
* Update style.css
* Update functions.php
### 1.4.0 - 31/12/2014
Changes:
* Merge pull request #20 from Codeinwp/production
merge back-ward
* added full width page
### 1.3.5 - 19/11/2014
Changes:
* Update home.php
* Update style.css
### 1.3.4 - 19/11/2014
Changes:
* fixed form subject issue, added linkedin icon and icons for socials, our focus clickable, contact section button and email, link on read more
* Added pro extra options in customizer
* woocommerce , wpml and rtl support, fixed undefined index errors, changed description, added more themes page and fixed front page
* fixed wrong description, links and tagline
fixed wrong description, links and tagline
* Fixed fotter and added woocommerce style
* Frontpage template
* Fixed wp.org fronpage and blog
* Update home.php
### 1.1 - 23/10/2014
Changes:
* Fixed dropdown menu
* Updated theme version
### 1.0.9 - 21/10/2014
Changes:
* Fixed fonts, added fontawesome notification footer links
Fixed fonts, added fontawesome notification footer links
### 1.0.7 - 21/10/2014
Changes:
* removed widget customizer plugin
* Update style.css
### 1.0.6 - 20/10/2014
Changes:
* Update functions.php
* fixed the font issue with https websites
### 1.0.5 - 17/10/2014
Changes:
* First version
* some fixes for responsive
* I added <Product Rewiew> and <Tweet old post> plugin
* removed error.log
* sync with wp.org
| NYU-SPIKE/spikebook | wp-content/themes/zerif-lite/CHANGELOG.md | Markdown | gpl-2.0 | 5,291 |
<?php
class ITSEC_Away_Mode {
function run() {
//Execute away mode functions on admin init
add_filter( 'itsec_logger_modules', array( $this, 'register_logger' ) );
add_action( 'itsec_admin_init', array( $this, 'execute_away_mode' ) );
add_action( 'login_init', array( $this, 'execute_away_mode' ) );
//Register Sync
add_filter( 'itsec_sync_modules', array( $this, 'register_sync' ) );
}
/**
* Check if away mode is active
*
* @since 4.4
*
* @param array $input [NULL] Input of options to check if calling from form
* @param bool $remaining will return the number of seconds remaining
* @param bool $override Whether or not we're calculating override values
*
* @return mixed true if locked out else false or times until next condition (negative until lockout, positive until release)
*/
public static function check_away( $input = NULL, $remaining = false, $override = false ) {
global $itsec_globals;
ITSEC_Lib::clear_caches(); //lets try to make sure nothing is storing a bad time
$form = true;
$has_away_file = @file_exists( $itsec_globals['ithemes_dir'] . '/itsec_away.confg' );
$status = false; //assume they're not locked out to start
//Normal usage check
if ( $input === NULL ) { //if we didn't provide input to check we need to get it
$form = false;
$input = get_site_option( 'itsec_away_mode' );
}
if ( ( $form === false && ! isset( $input['enabled'] ) ) || ! isset( $input['type'] ) || ! isset( $input['start'] ) || ! isset( $input['end'] ) || ! $has_away_file ) {
return false; //if we don't have complete settings don't lock them out
}
$current_time = $itsec_globals['current_time']; //use current time
$enabled = isset( $input['enabled'] ) ? $input['enabled'] : $form;
$test_type = $input['type'];
$test_start = $input['start'];
$test_end = $input['end'];
if ( $test_type === 1 ) { //daily
$test_start -= strtotime( date( 'Y-m-d', $test_start ) );
$test_end -= strtotime( date( 'Y-m-d', $test_end ) );
$day_seconds = $current_time - strtotime( date( 'Y-m-d', $current_time ) );
if ( $test_start === $test_end ) {
$status = false;
}
if ( $test_start < $test_end ) { //same day
if ( $test_start <= $day_seconds && $test_end >= $day_seconds && $enabled === true ) {
$status = $test_end - $day_seconds;
}
} else { //overnight
if ( ( $test_start < $day_seconds || $test_end > $day_seconds ) && $enabled === true ) {
if ( $day_seconds >= $test_start ) {
$status = ( 86400 - $day_seconds ) + $test_end;
} else {
$status = $test_end - $day_seconds;
}
}
}
} else if ( $test_start !== $test_end && $test_start <= $current_time && $test_end >= $current_time && $enabled === true ) { //one time
$status = $test_end - $current_time;
}
//they are allowed to log in
if ( $status === false ) {
if ( $test_type === 1 ) {
if ( $day_seconds > $test_start ) { //actually starts tomorrow
$status = - ( ( 86400 + $test_start ) - $day_seconds );
} else { //starts today
$status = - ( $test_start - $day_seconds );
}
} else {
$status = - ( $test_start - $current_time );
if ( $status > 0 ) {
if ( $form === false && isset( $input['enabled'] ) && $input['enabled'] === true ) { //disable away mode if one-time is in the past
$input['enabled'] = false;
update_site_option( 'itsec_away_mode', $input );
}
$status = 0;
}
}
}
if ( $override === false ) {
//work in an override from sync
$override_option = get_site_option( 'itsec_away_mode_sync_override' );
$override = $override_option['intention'];
$expires = $override_option['expires'];
if ( $expires < $itsec_globals['current_time'] ) {
delete_site_option( 'itsec_away_mode_sync_override' );
} else {
if ( $override === 'activate' ) {
if ( $status <= 0 ) { //not currently locked out
$input['start'] = $current_time - 1;
$status = ITSEC_Away_Mode::check_away( $input, true, true );
} else {
delete_site_option( 'itsec_away_mode_sync_override' );
}
} elseif ( $override === 'deactivate' ) {
if ( $status > 0 ) { //currently locked out
$input['end'] = $current_time - 1;
$status = ITSEC_Away_Mode::check_away( $input, true, true );
} else {
delete_site_option( 'itsec_away_mode_sync_override' );
}
}
}
}
if ( $remaining === true ) {
return $status;
} else {
if ( $status > 0 && $status !== false ) {
return true;
}
}
return false; //always default to NOT locking folks out
}
/**
* Execute away mode functionality
*
* @return void
*/
public function execute_away_mode() {
global $itsec_logger;
//execute lockout if applicable
if ( $this->check_away() ) {
$itsec_logger->log_event(
'away_mode',
5,
array(
__( 'A host was prevented from accessing the dashboard due to away-mode restrictions being in effect',
'it-l10n-better-wp-security' ),
),
ITSEC_Lib::get_ip(),
'',
'',
'',
''
);
wp_redirect( get_option( 'siteurl' ) );
wp_clear_auth_cookie();
}
}
/**
* Register 404 and file change detection for logger
*
* @param array $logger_modules array of logger modules
*
* @return array array of logger modules
*/
public function register_logger( $logger_modules ) {
$logger_modules['away_mode'] = array(
'type' => 'away_mode',
'function' => __( 'Away Mode Triggered', 'it-l10n-better-wp-security' ),
);
return $logger_modules;
}
/**
* Register Lockouts for Sync
*
* @param array $sync_modules array of logger modules
*
* @return array array of logger modules
*/
public function register_sync( $sync_modules ) {
$sync_modules['away_mode'] = array(
'verbs' => array(
'itsec-get-away-mode' => 'Ithemes_Sync_Verb_ITSEC_Get_Away_Mode',
'itsec-override-away-mode' => 'Ithemes_Sync_Verb_ITSEC_Override_Away_Mode'
),
'everything' => 'itsec-get-away-mode',
'path' => dirname( __FILE__ ),
);
return $sync_modules;
}
}
| dantaylorseo/TailoredWebsite | wp-content/plugins/better-wp-security/modules/free/away-mode/class-itsec-away-mode.php | PHP | gpl-2.0 | 6,388 |
/*
* Altera SoCFPGA PinMux configuration
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __SOCFPGA_PINMUX_CONFIG_H__
#define __SOCFPGA_PINMUX_CONFIG_H__
const u8 sys_mgr_init_table[] = {
3, /* EMACIO0 */
2, /* EMACIO1 */
2, /* EMACIO2 */
2, /* EMACIO3 */
2, /* EMACIO4 */
2, /* EMACIO5 */
2, /* EMACIO6 */
2, /* EMACIO7 */
2, /* EMACIO8 */
3, /* EMACIO9 */
2, /* EMACIO10 */
2, /* EMACIO11 */
2, /* EMACIO12 */
2, /* EMACIO13 */
0, /* EMACIO14 */
0, /* EMACIO15 */
0, /* EMACIO16 */
0, /* EMACIO17 */
0, /* EMACIO18 */
0, /* EMACIO19 */
3, /* FLASHIO0 */
0, /* FLASHIO1 */
3, /* FLASHIO2 */
3, /* FLASHIO3 */
3, /* FLASHIO4 */
3, /* FLASHIO5 */
3, /* FLASHIO6 */
3, /* FLASHIO7 */
0, /* FLASHIO8 */
3, /* FLASHIO9 */
3, /* FLASHIO10 */
3, /* FLASHIO11 */
0, /* GENERALIO0 */
1, /* GENERALIO1 */
1, /* GENERALIO2 */
0, /* GENERALIO3 */
0, /* GENERALIO4 */
1, /* GENERALIO5 */
1, /* GENERALIO6 */
1, /* GENERALIO7 */
1, /* GENERALIO8 */
0, /* GENERALIO9 */
0, /* GENERALIO10 */
0, /* GENERALIO11 */
0, /* GENERALIO12 */
2, /* GENERALIO13 */
2, /* GENERALIO14 */
3, /* GENERALIO15 */
3, /* GENERALIO16 */
2, /* GENERALIO17 */
2, /* GENERALIO18 */
0, /* GENERALIO19 */
0, /* GENERALIO20 */
0, /* GENERALIO21 */
0, /* GENERALIO22 */
0, /* GENERALIO23 */
0, /* GENERALIO24 */
0, /* GENERALIO25 */
0, /* GENERALIO26 */
0, /* GENERALIO27 */
0, /* GENERALIO28 */
0, /* GENERALIO29 */
0, /* GENERALIO30 */
0, /* GENERALIO31 */
2, /* MIXED1IO0 */
2, /* MIXED1IO1 */
2, /* MIXED1IO2 */
2, /* MIXED1IO3 */
2, /* MIXED1IO4 */
2, /* MIXED1IO5 */
2, /* MIXED1IO6 */
2, /* MIXED1IO7 */
2, /* MIXED1IO8 */
2, /* MIXED1IO9 */
2, /* MIXED1IO10 */
2, /* MIXED1IO11 */
2, /* MIXED1IO12 */
2, /* MIXED1IO13 */
0, /* MIXED1IO14 */
3, /* MIXED1IO15 */
3, /* MIXED1IO16 */
3, /* MIXED1IO17 */
3, /* MIXED1IO18 */
3, /* MIXED1IO19 */
3, /* MIXED1IO20 */
0, /* MIXED1IO21 */
0, /* MIXED2IO0 */
0, /* MIXED2IO1 */
0, /* MIXED2IO2 */
0, /* MIXED2IO3 */
0, /* MIXED2IO4 */
0, /* MIXED2IO5 */
0, /* MIXED2IO6 */
0, /* MIXED2IO7 */
0, /* GPLINMUX48 */
0, /* GPLINMUX49 */
0, /* GPLINMUX50 */
0, /* GPLINMUX51 */
0, /* GPLINMUX52 */
0, /* GPLINMUX53 */
0, /* GPLINMUX54 */
0, /* GPLINMUX55 */
0, /* GPLINMUX56 */
0, /* GPLINMUX57 */
0, /* GPLINMUX58 */
0, /* GPLINMUX59 */
0, /* GPLINMUX60 */
0, /* GPLINMUX61 */
0, /* GPLINMUX62 */
0, /* GPLINMUX63 */
0, /* GPLINMUX64 */
0, /* GPLINMUX65 */
0, /* GPLINMUX66 */
0, /* GPLINMUX67 */
0, /* GPLINMUX68 */
0, /* GPLINMUX69 */
0, /* GPLINMUX70 */
1, /* GPLMUX0 */
1, /* GPLMUX1 */
1, /* GPLMUX2 */
1, /* GPLMUX3 */
1, /* GPLMUX4 */
1, /* GPLMUX5 */
1, /* GPLMUX6 */
1, /* GPLMUX7 */
1, /* GPLMUX8 */
1, /* GPLMUX9 */
1, /* GPLMUX10 */
1, /* GPLMUX11 */
1, /* GPLMUX12 */
1, /* GPLMUX13 */
1, /* GPLMUX14 */
1, /* GPLMUX15 */
1, /* GPLMUX16 */
1, /* GPLMUX17 */
1, /* GPLMUX18 */
1, /* GPLMUX19 */
1, /* GPLMUX20 */
1, /* GPLMUX21 */
1, /* GPLMUX22 */
1, /* GPLMUX23 */
1, /* GPLMUX24 */
1, /* GPLMUX25 */
1, /* GPLMUX26 */
1, /* GPLMUX27 */
1, /* GPLMUX28 */
1, /* GPLMUX29 */
1, /* GPLMUX30 */
1, /* GPLMUX31 */
1, /* GPLMUX32 */
1, /* GPLMUX33 */
1, /* GPLMUX34 */
1, /* GPLMUX35 */
1, /* GPLMUX36 */
1, /* GPLMUX37 */
1, /* GPLMUX38 */
1, /* GPLMUX39 */
1, /* GPLMUX40 */
1, /* GPLMUX41 */
1, /* GPLMUX42 */
1, /* GPLMUX43 */
1, /* GPLMUX44 */
1, /* GPLMUX45 */
1, /* GPLMUX46 */
1, /* GPLMUX47 */
1, /* GPLMUX48 */
1, /* GPLMUX49 */
1, /* GPLMUX50 */
1, /* GPLMUX51 */
1, /* GPLMUX52 */
1, /* GPLMUX53 */
1, /* GPLMUX54 */
1, /* GPLMUX55 */
1, /* GPLMUX56 */
1, /* GPLMUX57 */
1, /* GPLMUX58 */
1, /* GPLMUX59 */
1, /* GPLMUX60 */
1, /* GPLMUX61 */
1, /* GPLMUX62 */
1, /* GPLMUX63 */
1, /* GPLMUX64 */
1, /* GPLMUX65 */
1, /* GPLMUX66 */
1, /* GPLMUX67 */
1, /* GPLMUX68 */
1, /* GPLMUX69 */
1, /* GPLMUX70 */
0, /* NANDUSEFPGA */
0, /* UART0USEFPGA */
0, /* RGMII1USEFPGA */
0, /* SPIS0USEFPGA */
0, /* CAN0USEFPGA */
0, /* I2C0USEFPGA */
0, /* SDMMCUSEFPGA */
0, /* QSPIUSEFPGA */
0, /* SPIS1USEFPGA */
0, /* RGMII0USEFPGA */
0, /* UART1USEFPGA */
0, /* CAN1USEFPGA */
0, /* USB1USEFPGA */
0, /* I2C3USEFPGA */
0, /* I2C2USEFPGA */
0, /* I2C1USEFPGA */
0, /* SPIM1USEFPGA */
0, /* USB0USEFPGA */
0 /* SPIM0USEFPGA */
};
#endif /* __SOCFPGA_PINMUX_CONFIG_H__ */
| cosino/u-boot-enigma | board/altera/cyclone5-socdk/qts/pinmux_config.h | C | gpl-2.0 | 4,398 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* 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 license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Loader
* @subpackage Autoloader
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @version $Id: Resource.php 20096 2010-01-06 02:05:09Z bkarwin $
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/** Zend_Loader_Autoloader_Interface */
require_once 'Zend/Loader/Autoloader/Interface.php';
/**
* Resource loader
*
* @uses Zend_Loader_Autoloader_Interface
* @package Zend_Loader
* @subpackage Autoloader
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Loader_Autoloader_Resource implements Zend_Loader_Autoloader_Interface
{
/**
* @var string Base path to resource classes
*/
protected $_basePath;
/**
* @var array Components handled within this resource
*/
protected $_components = array();
/**
* @var string Default resource/component to use when using object registry
*/
protected $_defaultResourceType;
/**
* @var string Namespace of classes within this resource
*/
protected $_namespace;
/**
* @var array Available resource types handled by this resource autoloader
*/
protected $_resourceTypes = array();
/**
* Constructor
*
* @param array|Zend_Config $options Configuration options for resource autoloader
* @return void
*/
public function __construct($options)
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
}
if (!is_array($options)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Options must be passed to resource loader constructor');
}
$this->setOptions($options);
$namespace = $this->getNamespace();
if ((null === $namespace)
|| (null === $this->getBasePath())
) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Resource loader requires both a namespace and a base path for initialization');
}
if (!empty($namespace)) {
$namespace .= '_';
}
Zend_Loader_Autoloader::getInstance()->unshiftAutoloader($this, $namespace);
}
/**
* Overloading: methods
*
* Allow retrieving concrete resource object instances using 'get<Resourcename>()'
* syntax. Example:
* <code>
* $loader = new Zend_Loader_Autoloader_Resource(array(
* 'namespace' => 'Stuff_',
* 'basePath' => '/path/to/some/stuff',
* ))
* $loader->addResourceType('Model', 'models', 'Model');
*
* $foo = $loader->getModel('Foo'); // get instance of Stuff_Model_Foo class
* </code>
*
* @param string $method
* @param array $args
* @return mixed
* @throws Zend_Loader_Exception if method not beginning with 'get' or not matching a valid resource type is called
*/
public function __call($method, $args)
{
if ('get' == substr($method, 0, 3)) {
$type = strtolower(substr($method, 3));
if (!$this->hasResourceType($type)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception("Invalid resource type $type; cannot load resource");
}
if (empty($args)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception("Cannot load resources; no resource specified");
}
$resource = array_shift($args);
return $this->load($resource, $type);
}
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception("Method '$method' is not supported");
}
/**
* Helper method to calculate the correct class path
*
* @param string $class
* @return False if not matched other wise the correct path
*/
public function getClassPath($class)
{
$segments = explode('_', $class);
$namespaceTopLevel = $this->getNamespace();
$namespace = '';
if (!empty($namespaceTopLevel)) {
$namespace = array_shift($segments);
if ($namespace != $namespaceTopLevel) {
// wrong prefix? we're done
return false;
}
}
if (count($segments) < 2) {
// assumes all resources have a component and class name, minimum
return false;
}
$final = array_pop($segments);
$component = $namespace;
$lastMatch = false;
do {
$segment = array_shift($segments);
$component .= empty($component) ? $segment : '_' . $segment;
if (isset($this->_components[$component])) {
$lastMatch = $component;
}
} while (count($segments));
if (!$lastMatch) {
return false;
}
$final = substr($class, strlen($lastMatch) + 1);
$path = $this->_components[$lastMatch];
$classPath = $path . '/' . str_replace('_', '/', $final) . '.php';
if (Zend_Loader::isReadable($classPath)) {
return $classPath;
}
return false;
}
/**
* Attempt to autoload a class
*
* @param string $class
* @return mixed False if not matched, otherwise result if include operation
*/
public function autoload($class)
{
$classPath = $this->getClassPath($class);
if (false !== $classPath) {
return include $classPath;
}
return false;
}
/**
* Set class state from options
*
* @param array $options
* @return Zend_Loader_Autoloader_Resource
*/
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
/**
* Set namespace that this autoloader handles
*
* @param string $namespace
* @return Zend_Loader_Autoloader_Resource
*/
public function setNamespace($namespace)
{
$this->_namespace = rtrim((string) $namespace, '_');
return $this;
}
/**
* Get namespace this autoloader handles
*
* @return string
*/
public function getNamespace()
{
return $this->_namespace;
}
/**
* Set base path for this set of resources
*
* @param string $path
* @return Zend_Loader_Autoloader_Resource
*/
public function setBasePath($path)
{
$this->_basePath = (string) $path;
return $this;
}
/**
* Get base path to this set of resources
*
* @return string
*/
public function getBasePath()
{
return $this->_basePath;
}
/**
* Add resource type
*
* @param string $type identifier for the resource type being loaded
* @param string $path path relative to resource base path containing the resource types
* @param null|string $namespace sub-component namespace to append to base namespace that qualifies this resource type
* @return Zend_Loader_Autoloader_Resource
*/
public function addResourceType($type, $path, $namespace = null)
{
$type = strtolower($type);
if (!isset($this->_resourceTypes[$type])) {
if (null === $namespace) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Initial definition of a resource type must include a namespace');
}
$namespaceTopLevel = $this->getNamespace();
$namespace = ucfirst(trim($namespace, '_'));
$this->_resourceTypes[$type] = array(
'namespace' => empty($namespaceTopLevel) ? $namespace : $namespaceTopLevel . '_' . $namespace,
);
}
if (!is_string($path)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Invalid path specification provided; must be string');
}
$this->_resourceTypes[$type]['path'] = $this->getBasePath() . '/' . rtrim($path, '\/');
$component = $this->_resourceTypes[$type]['namespace'];
$this->_components[$component] = $this->_resourceTypes[$type]['path'];
return $this;
}
/**
* Add multiple resources at once
*
* $types should be an associative array of resource type => specification
* pairs. Each specification should be an associative array containing
* minimally the 'path' key (specifying the path relative to the resource
* base path) and optionally the 'namespace' key (indicating the subcomponent
* namespace to append to the resource namespace).
*
* As an example:
* <code>
* $loader->addResourceTypes(array(
* 'model' => array(
* 'path' => 'models',
* 'namespace' => 'Model',
* ),
* 'form' => array(
* 'path' => 'forms',
* 'namespace' => 'Form',
* ),
* ));
* </code>
*
* @param array $types
* @return Zend_Loader_Autoloader_Resource
*/
public function addResourceTypes(array $types)
{
foreach ($types as $type => $spec) {
if (!is_array($spec)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('addResourceTypes() expects an array of arrays');
}
if (!isset($spec['path'])) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('addResourceTypes() expects each array to include a paths element');
}
$paths = $spec['path'];
$namespace = null;
if (isset($spec['namespace'])) {
$namespace = $spec['namespace'];
}
$this->addResourceType($type, $paths, $namespace);
}
return $this;
}
/**
* Overwrite existing and set multiple resource types at once
*
* @see Zend_Loader_Autoloader_Resource::addResourceTypes()
* @param array $types
* @return Zend_Loader_Autoloader_Resource
*/
public function setResourceTypes(array $types)
{
$this->clearResourceTypes();
return $this->addResourceTypes($types);
}
/**
* Retrieve resource type mappings
*
* @return array
*/
public function getResourceTypes()
{
return $this->_resourceTypes;
}
/**
* Is the requested resource type defined?
*
* @param string $type
* @return bool
*/
public function hasResourceType($type)
{
return isset($this->_resourceTypes[$type]);
}
/**
* Remove the requested resource type
*
* @param string $type
* @return Zend_Loader_Autoloader_Resource
*/
public function removeResourceType($type)
{
if ($this->hasResourceType($type)) {
$namespace = $this->_resourceTypes[$type]['namespace'];
unset($this->_components[$namespace]);
unset($this->_resourceTypes[$type]);
}
return $this;
}
/**
* Clear all resource types
*
* @return Zend_Loader_Autoloader_Resource
*/
public function clearResourceTypes()
{
$this->_resourceTypes = array();
$this->_components = array();
return $this;
}
/**
* Set default resource type to use when calling load()
*
* @param string $type
* @return Zend_Loader_Autoloader_Resource
*/
public function setDefaultResourceType($type)
{
if ($this->hasResourceType($type)) {
$this->_defaultResourceType = $type;
}
return $this;
}
/**
* Get default resource type to use when calling load()
*
* @return string|null
*/
public function getDefaultResourceType()
{
return $this->_defaultResourceType;
}
/**
* Object registry and factory
*
* Loads the requested resource of type $type (or uses the default resource
* type if none provided). If the resource has been loaded previously,
* returns the previous instance; otherwise, instantiates it.
*
* @param string $resource
* @param string $type
* @return object
* @throws Zend_Loader_Exception if resource type not specified or invalid
*/
public function load($resource, $type = null)
{
if (null === $type) {
$type = $this->getDefaultResourceType();
if (empty($type)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('No resource type specified');
}
}
if (!$this->hasResourceType($type)) {
require_once 'Zend/Loader/Exception.php';
throw new Zend_Loader_Exception('Invalid resource type specified');
}
$namespace = $this->_resourceTypes[$type]['namespace'];
$class = $namespace . '_' . ucfirst($resource);
if (!isset($this->_resources[$class])) {
$this->_resources[$class] = new $class;
}
return $this->_resources[$class];
}
}
| Tpo76/centreon | lib/Zend/Loader/Autoloader/Resource.php | PHP | gpl-2.0 | 14,136 |
#!/usr/bin/python
#============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# 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
#============================================================================
# Copyright (C) 2006 XenSource Ltd.
#============================================================================
import sys
import time
import re
import os
sys.path.append('/usr/lib/python')
from xen.util.xmlrpclib2 import ServerProxy
from optparse import *
from pprint import pprint
from types import DictType
from getpass import getpass
# Get default values from the environment
SERVER_URI = os.environ.get('XAPI_SERVER_URI', 'http://localhost:9363/')
SERVER_USER = os.environ.get('XAPI_SERVER_USER', '')
SERVER_PASS = os.environ.get('XAPI_SERVER_PASS', '')
MB = 1024 * 1024
HOST_INFO_FORMAT = '%-20s: %-50s'
VM_LIST_FORMAT = '%(name_label)-18s %(memory_actual)-5s %(VCPUs_number)-5s'\
' %(power_state)-10s %(uuid)-36s'
SR_LIST_FORMAT = '%(name_label)-18s %(uuid)-36s %(physical_size)-10s' \
'%(type)-10s'
VDI_LIST_FORMAT = '%(name_label)-18s %(uuid)-36s %(virtual_size)-8s'
VBD_LIST_FORMAT = '%(device)-6s %(uuid)-36s %(VDI)-8s'
TASK_LIST_FORMAT = '%(name_label)-18s %(uuid)-36s %(status)-8s %(progress)-4s'
VIF_LIST_FORMAT = '%(name)-8s %(device)-7s %(uuid)-36s %(MAC)-10s'
CONSOLE_LIST_FORMAT = '%(uuid)-36s %(protocol)-8s %(location)-32s'
COMMANDS = {
'host-info': ('', 'Get Xen Host Info'),
'host-set-name': ('', 'Set host name'),
'pif-list': ('', 'List all PIFs'),
'sr-list': ('', 'List all SRs'),
'vbd-list': ('', 'List all VBDs'),
'vbd-create': ('<domname> <pycfg> [opts]',
'Create VBD attached to domname'),
'vdi-create': ('<pycfg> [opts]', 'Create a VDI'),
'vdi-list' : ('', 'List all VDI'),
'vdi-rename': ('<vdi_uuid> <new_name>', 'Rename VDI'),
'vdi-destroy': ('<vdi_uuid>', 'Delete VDI'),
'vif-create': ('<domname> <pycfg>', 'Create VIF attached to domname'),
'vtpm-create' : ('<domname> <pycfg>', 'Create VTPM attached to domname'),
'vm-create': ('<pycfg>', 'Create VM with python config'),
'vm-destroy': ('<domname>', 'Delete VM'),
'vm-list': ('[--long]', 'List all domains.'),
'vm-name': ('<uuid>', 'Name of UUID.'),
'vm-shutdown': ('<name> [opts]', 'Shutdown VM with name'),
'vm-start': ('<name>', 'Start VM with name'),
'vm-uuid': ('<name>', 'UUID of a domain by name.'),
'async-vm-start': ('<name>', 'Start VM asynchronously'),
}
OPTIONS = {
'sr-list': [(('-l', '--long'),
{'action':'store_true',
'help':'List all properties of SR'})
],
'vdi-list': [(('-l', '--long'),
{'action':'store_true',
'help':'List all properties of VDI'})
],
'vif-list': [(('-l', '--long'),
{'action':'store_true',
'help':'List all properties of VIF'})
],
'vm-list': [(('-l', '--long'),
{'action':'store_true',
'help':'List all properties of VMs'})
],
'vm-shutdown': [(('-f', '--force'), {'help': 'Shutdown Forcefully',
'action': 'store_true'})],
'vdi-create': [(('--name-label',), {'help': 'Name for VDI'}),
(('--name-description',), {'help': 'Description for VDI'}),
(('--virtual-size',), {'type': 'int',
'default': 0,
'help': 'Size of VDI in bytes'}),
(('--type',), {'choices': ['system', 'user', 'ephemeral'],
'default': 'system',
'help': 'VDI type'}),
(('--sharable',), {'action': 'store_true',
'help': 'VDI sharable'}),
(('--read-only',), {'action': 'store_true',
'help': 'Read only'}),
(('--sr',), {})],
'vbd-create': [(('--VDI',), {'help': 'UUID of VDI to attach to.'}),
(('--mode',), {'choices': ['RO', 'RW'],
'help': 'device mount mode'}),
(('--driver',), {'choices':['paravirtualised', 'ioemu'],
'help': 'Driver for VBD'}),
(('--device',), {'help': 'Device name on guest domain'})]
}
class OptionError(Exception):
pass
class XenAPIError(Exception):
pass
#
# Extra utility functions
#
class IterableValues(Values):
"""Better interface to the list of values from optparse."""
def __iter__(self):
for opt, val in self.__dict__.items():
if opt[0] == '_' or callable(val):
continue
yield opt, val
def parse_args(cmd_name, args, set_defaults = False):
argstring, desc = COMMANDS[cmd_name]
parser = OptionParser(usage = 'xapi %s %s' % (cmd_name, argstring),
description = desc)
if cmd_name in OPTIONS:
for optargs, optkwds in OPTIONS[cmd_name]:
parser.add_option(*optargs, **optkwds)
if set_defaults:
default_values = parser.get_default_values()
defaults = IterableValues(default_values.__dict__)
else:
defaults = IterableValues()
(opts, extraargs) = parser.parse_args(args = list(args),
values = defaults)
return opts, extraargs
def execute(server, fn, args, async = False):
if async:
func = eval('server.Async.%s' % fn)
else:
func = eval('server.%s' % fn)
result = func(*args)
if type(result) != DictType:
raise TypeError("Function returned object of type: %s" %
str(type(result)))
if 'Value' not in result:
raise XenAPIError(*result['ErrorDescription'])
return result['Value']
_initialised = False
_server = None
_session = None
def connect(*args):
global _server, _session, _initialised
if not _initialised:
# try without password or default credentials
try:
_server = ServerProxy(SERVER_URI)
_session = execute(_server.session, 'login_with_password',
(SERVER_USER, SERVER_PASS))
except:
login = raw_input("Login: ")
password = getpass()
creds = (login, password)
_server = ServerProxy(SERVER_URI)
_session = execute(_server.session, 'login_with_password',
creds)
_initialised = True
return (_server, _session)
def _stringify(adict):
return dict([(k, str(v)) for k, v in adict.items()])
def _read_python_cfg(filename):
cfg = {}
execfile(filename, {}, cfg)
return cfg
def resolve_vm(server, session, vm_name):
vm_uuid = execute(server, 'VM.get_by_name_label', (session, vm_name))
if not vm_uuid:
return None
else:
return vm_uuid[0]
def resolve_vdi(server, session, vdi_name):
vdi_uuid = execute(server, 'VDI.get_by_name_label', (session, vdi_name))
if not vdi_uuid:
return None
else:
return vdi_uuid[0]
#
# Actual commands
#
def xapi_host_info(args, async = False):
server, session = connect()
hosts = execute(server, 'host.get_all', (session,))
for host in hosts: # there is only one, but ..
hostinfo = execute(server, 'host.get_record', (session, host))
print HOST_INFO_FORMAT % ('Name', hostinfo['name_label'])
print HOST_INFO_FORMAT % ('Version', hostinfo['software_version'])
print HOST_INFO_FORMAT % ('CPUs', len(hostinfo['host_CPUs']))
print HOST_INFO_FORMAT % ('VMs', len(hostinfo['resident_VMs']))
print HOST_INFO_FORMAT % ('UUID', host)
for host_cpu_uuid in hostinfo['host_CPUs']:
host_cpu = execute(server, 'host_cpu.get_record',
(session, host_cpu_uuid))
print 'CPU %s Util: %.2f' % (host_cpu['number'],
float(host_cpu['utilisation']))
def xapi_host_set_name(args, async = False):
if len(args) < 1:
raise OptionError("No hostname specified")
server, session = connect()
hosts = execute(server, 'host.get_all', (session,))
if len(hosts) > 0:
execute(server, 'host.set_name_label', (session, hosts[0], args[0]))
print 'Hostname: %s' % execute(server, 'host.get_name_label',
(session, hosts[0]))
def xapi_vm_uuid(args, async = False):
if len(args) < 1:
raise OptionError("No domain name specified")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print vm_uuid
def xapi_vm_name(args, async = False):
if len(args) < 1:
raise OptionError("No UUID specified")
server, session = connect()
vm_name = execute(server, 'VM.get_name_label', (session, args[0]))
print vm_name
def xapi_vm_list(args, async = False):
opts, args = parse_args('vm-list', args, set_defaults = True)
is_long = opts and opts.long
list_only = args
server, session = connect()
vm_uuids = execute(server, 'VM.get_all', (session,))
if not is_long:
print VM_LIST_FORMAT % {'name_label':'Name',
'memory_actual':'Mem',
'VCPUs_number': 'VCPUs',
'power_state': 'State',
'uuid': 'UUID'}
for uuid in vm_uuids:
vm_info = execute(server, 'VM.get_record', (session, uuid))
# skip domain if we don't want
if list_only and vm_info['name_label'] not in list_only:
continue
if is_long:
vbds = vm_info['VBDs']
vifs = vm_info['VIFs']
vtpms = vm_info['VTPMs']
vif_infos = []
vbd_infos = []
vtpm_infos = []
for vbd in vbds:
vbd_info = execute(server, 'VBD.get_record', (session, vbd))
vbd_infos.append(vbd_info)
for vif in vifs:
vif_info = execute(server, 'VIF.get_record', (session, vif))
vif_infos.append(vif_info)
for vtpm in vtpms:
vtpm_info = execute(server, 'VTPM.get_record', (session, vtpm))
vtpm_infos.append(vtpm_info)
vm_info['VBDs'] = vbd_infos
vm_info['VIFs'] = vif_infos
vm_info['VTPMs'] = vtpm_infos
pprint(vm_info)
else:
print VM_LIST_FORMAT % _stringify(vm_info)
def xapi_vm_create(args, async = False):
if len(args) < 1:
raise OptionError("Configuration file not specified")
filename = args[0]
cfg = _read_python_cfg(filename)
print 'Creating VM from %s ..' % filename
server, session = connect()
uuid = execute(server, 'VM.create', (session, cfg), async = async)
print 'Done. (%s)' % uuid
print uuid
def xapi_vm_destroy(args, async = False):
if len(args) < 1:
raise OptionError("No domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Destroying VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.destroy', (session, vm_uuid), async = async)
print 'Done.'
def xapi_vm_start(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Starting VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.start', (session, vm_uuid, False), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vm_suspend(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Suspending VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.suspend', (session, vm_uuid), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vm_resume(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Resuming VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.resume', (session, vm_uuid, False), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vm_pause(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Pausing VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.pause', (session, vm_uuid), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vm_unpause(args, async = False):
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
print 'Pausing VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.unpause', (session, vm_uuid), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_task_list(args, async = False):
server, session = connect()
all_tasks = execute(server, 'task.get_all', (session,))
print TASK_LIST_FORMAT % {'name_label': 'Task Name',
'uuid': 'UUID',
'status': 'Status',
'progress': '%'}
for task_uuid in all_tasks:
task = execute(server, 'task.get_record', (session, task_uuid))
print TASK_LIST_FORMAT % task
def xapi_task_clear(args, async = False):
server, session = connect()
all_tasks = execute(server, 'task.get_all', (session,))
for task_uuid in all_tasks:
success = execute(server, 'task.destroy', (session, task_uuid))
print 'Destroyed Task %s' % task_uuid
def xapi_vm_shutdown(args, async = False):
opts, args = parse_args("vm-shutdown", args, set_defaults = True)
if len(args) < 1:
raise OptionError("No Domain name specified.")
server, session = connect()
vm_uuid = resolve_vm(server, session, args[0])
if opts.force:
print 'Forcefully shutting down VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.hard_shutdown', (session, vm_uuid), async = async)
else:
print 'Shutting down VM %s (%s)' % (args[0], vm_uuid)
success = execute(server, 'VM.clean_shutdown', (session, vm_uuid), async = async)
if async:
print 'Task started: %s' % success
else:
print 'Done.'
def xapi_vbd_create(args, async = False):
opts, args = parse_args('vbd-create', args)
if len(args) < 2:
raise OptionError("Configuration file and domain not specified")
domname = args[0]
if len(args) > 1:
filename = args[1]
cfg = _read_python_cfg(filename)
else:
cfg = {}
for opt, val in opts:
cfg[opt] = val
print 'Creating VBD ...',
server, session = connect()
vm_uuid = resolve_vm(server, session, domname)
cfg['VM'] = vm_uuid
vbd_uuid = execute(server, 'VBD.create', (session, cfg), async = async)
if async:
print 'Task started: %s' % vbd_uuid
else:
print 'Done. (%s)' % vbd_uuid
def xapi_vif_create(args, async = False):
if len(args) < 2:
raise OptionError("Configuration file not specified")
domname = args[0]
filename = args[1]
cfg = _read_python_cfg(filename)
print 'Creating VIF from %s ..' % filename
server, session = connect()
vm_uuid = resolve_vm(server, session, domname)
cfg['VM'] = vm_uuid
vif_uuid = execute(server, 'VIF.create', (session, cfg), async = async)
if async:
print 'Task started: %s' % vif_uuid
else:
print 'Done. (%s)' % vif_uuid
def xapi_vbd_list(args, async = False):
server, session = connect()
domname = args[0]
dom_uuid = resolve_vm(server, session, domname)
vbds = execute(server, 'VM.get_VBDs', (session, dom_uuid))
print VBD_LIST_FORMAT % {'device': 'Device',
'uuid' : 'UUID',
'VDI': 'VDI'}
for vbd in vbds:
vbd_struct = execute(server, 'VBD.get_record', (session, vbd))
print VBD_LIST_FORMAT % vbd_struct
def xapi_vbd_stats(args, async = False):
server, session = connect()
domname = args[0]
dom_uuid = resolve_vm(server, session, domname)
vbds = execute(server, 'VM.get_VBDs', (session, dom_uuid))
for vbd_uuid in vbds:
print execute(server, 'VBD.get_io_read_kbs', (session, vbd_uuid))
def xapi_vif_list(args, async = False):
server, session = connect()
opts, args = parse_args('vdi-list', args, set_defaults = True)
is_long = opts and opts.long
domname = args[0]
dom_uuid = resolve_vm(server, session, domname)
vifs = execute(server, 'VM.get_VIFs', (session, dom_uuid))
if not is_long:
print VIF_LIST_FORMAT % {'name': 'Name',
'device': 'Device',
'uuid' : 'UUID',
'MAC': 'MAC'}
for vif in vifs:
vif_struct = execute(server, 'VIF.get_record', (session, vif))
print VIF_LIST_FORMAT % vif_struct
else:
for vif in vifs:
vif_struct = execute(server, 'VIF.get_record', (session, vif))
pprint(vif_struct)
def xapi_console_list(args, async = False):
server, session = connect()
opts, args = parse_args('vdi-list', args, set_defaults = True)
is_long = opts and opts.long
domname = args[0]
dom_uuid = resolve_vm(server, session, domname)
consoles = execute(server, 'VM.get_consoles', (session, dom_uuid))
if not is_long:
print CONSOLE_LIST_FORMAT % {'protocol': 'Protocol',
'location': 'Location',
'uuid': 'UUID'}
for console in consoles:
console_struct = execute(server, 'console.get_record',
(session, console))
print CONSOLE_LIST_FORMAT % console_struct
else:
for console in consoles:
console_struct = execute(server, 'console.get_record',
(session, console))
pprint(console_struct)
def xapi_vdi_list(args, async = False):
opts, args = parse_args('vdi-list', args, set_defaults = True)
is_long = opts and opts.long
server, session = connect()
vdis = execute(server, 'VDI.get_all', (session,))
if not is_long:
print VDI_LIST_FORMAT % {'name_label': 'VDI Label',
'uuid' : 'UUID',
'virtual_size': 'Bytes'}
for vdi in vdis:
vdi_struct = execute(server, 'VDI.get_record', (session, vdi))
print VDI_LIST_FORMAT % vdi_struct
else:
for vdi in vdis:
vdi_struct = execute(server, 'VDI.get_record', (session, vdi))
pprint(vdi_struct)
def xapi_sr_list(args, async = False):
opts, args = parse_args('sr-list', args, set_defaults = True)
is_long = opts and opts.long
server, session = connect()
srs = execute(server, 'SR.get_all', (session,))
if not is_long:
print SR_LIST_FORMAT % {'name_label': 'SR Label',
'uuid' : 'UUID',
'physical_size': 'Size (MB)',
'type': 'Type'}
for sr in srs:
sr_struct = execute(server, 'SR.get_record', (session, sr))
sr_struct['physical_size'] = int(sr_struct['physical_size'])/MB
print SR_LIST_FORMAT % sr_struct
else:
for sr in srs:
sr_struct = execute(server, 'SR.get_record', (session, sr))
pprint(sr_struct)
def xapi_sr_rename(args, async = False):
server, session = connect()
sr = execute(server, 'SR.get_by_name_label', (session, args[0]))
execute(server, 'SR.set_name_label', (session, sr[0], args[1]))
def xapi_vdi_create(args, async = False):
opts, args = parse_args('vdi-create', args)
if len(args) > 0:
cfg = _read_python_cfg(args[0])
else:
cfg = {}
for opt, val in opts:
cfg[opt] = val
server, session = connect()
srs = []
if cfg.get('SR'):
srs = execute(server, 'SR.get_by_name_label', (session, cfg['SR']))
else:
srs = execute(server, 'SR.get_all', (session,))
sr = srs[0]
cfg['SR'] = sr
size = cfg['virtual_size']/MB
print 'Creating VDI of size: %dMB ..' % size,
uuid = execute(server, 'VDI.create', (session, cfg), async = async)
if async:
print 'Task started: %s' % uuid
else:
print 'Done. (%s)' % uuid
def xapi_vdi_destroy(args, async = False):
server, session = connect()
if len(args) < 1:
raise OptionError('Not enough arguments')
vdi_uuid = args[0]
print 'Deleting VDI %s' % vdi_uuid
result = execute(server, 'VDI.destroy', (session, vdi_uuid), async = async)
if async:
print 'Task started: %s' % result
else:
print 'Done.'
def xapi_vdi_rename(args, async = False):
server, session = connect()
if len(args) < 2:
raise OptionError('Not enough arguments')
vdi_uuid = execute(server, 'VDI.get_by_name_label', session, args[0])
vdi_name = args[1]
print 'Renaming VDI %s to %s' % (vdi_uuid[0], vdi_name)
result = execute(server, 'VDI.set_name_label',
(session, vdi_uuid[0], vdi_name), async = async)
if async:
print 'Task started: %s' % result
else:
print 'Done.'
def xapi_vtpm_create(args, async = False):
server, session = connect()
domname = args[0]
cfg = _read_python_cfg(args[1])
vm_uuid = resolve_vm(server, session, domname)
cfg['VM'] = vm_uuid
print "Creating vTPM with cfg = %s" % cfg
vtpm_uuid = execute(server, 'VTPM.create', (session, cfg))
print "Done. (%s)" % vtpm_uuid
def xapi_pif_list(args, async = False):
server, session = connect()
pif_uuids = execute(server, 'PIF.get_all', (session,))
for pif_uuid in pif_uuids:
pif = execute(server, 'PIF.get_record', (session, pif_uuid))
print pif
def xapi_debug_wait(args, async = False):
secs = 10
if len(args) > 0:
secs = int(args[0])
server, session = connect()
task_uuid = execute(server, 'debug.wait', (session, secs), async=async)
print 'Task UUID: %s' % task_uuid
def xapi_vm_stat(args, async = False):
domname = args[0]
server, session = connect()
vm_uuid = resolve_vm(server, session, domname)
vif_uuids = execute(server, 'VM.get_VIFs', (session, vm_uuid))
vbd_uuids = execute(server, 'VM.get_VBDs', (session, vm_uuid))
vcpus_utils = execute(server, 'VM.get_VCPUs_utilisation',
(session, vm_uuid))
for vcpu_num in sorted(vcpus_utils.keys()):
print 'CPU %s : %5.2f%%' % (vcpu_num, vcpus_utils[vcpu_num] * 100)
for vif_uuid in vif_uuids:
vif = execute(server, 'VIF.get_record', (session, vif_uuid))
print '%(device)s: rx: %(io_read_kbs)10.2f tx: %(io_write_kbs)10.2f' \
% vif
for vbd_uuid in vbd_uuids:
vbd = execute(server, 'VBD.get_record', (session, vbd_uuid))
print '%(device)s: rd: %(io_read_kbs)10.2f wr: %(io_write_kbs)10.2f' \
% vbd
#
# Command Line Utils
#
import cmd
import shlex
class XenAPICmd(cmd.Cmd):
def __init__(self, server, session):
cmd.Cmd.__init__(self)
self.server = server
self.session = session
self.prompt = ">>> "
def default(self, line):
words = shlex.split(line)
if len(words) > 0:
cmd_name = words[0].replace('-', '_')
is_async = 'async' in cmd_name
if is_async:
cmd_name = re.sub('async_', '', cmd_name)
func_name = 'xapi_%s' % cmd_name
func = globals().get(func_name)
if func:
try:
args = tuple(words[1:])
func(args, async = is_async)
return True
except SystemExit:
return False
except OptionError, e:
print 'Error:', str(e)
return False
except Exception, e:
import traceback
traceback.print_exc()
return False
print '*** Unknown command: %s' % words[0]
return False
def do_EOF(self, line):
print
sys.exit(0)
def do_help(self, line):
usage(print_usage = False)
def emptyline(self):
pass
def postcmd(self, stop, line):
return False
def precmd(self, line):
words = shlex.split(line)
if len(words) > 0:
words0 = words[0].replace('-', '_')
return ' '.join([words0] + words[1:])
else:
return line
def shell():
server, session = connect()
x = XenAPICmd(server, session)
x.cmdloop('Xen API Prompt. Type "help" for a list of functions')
def usage(command = None, print_usage = True):
if not command:
if print_usage:
print 'Usage: xapi <subcommand> [options] [args]'
print
print 'Subcommands:'
print
for func in sorted(globals().keys()):
if func.startswith('xapi_'):
command = func[5:].replace('_', '-')
args, description = COMMANDS.get(command, ('', ''))
print '%-16s %-40s' % (command, description)
print
else:
parse_args(command, ['-h'])
def main(args):
# poor man's optparse that doesn't abort on unrecognised opts
options = {}
remaining = []
arg_n = 0
while args:
arg = args.pop(0)
if arg in ('--help', '-h'):
options['help'] = True
elif arg in ('--server', '-s') and args:
options['server'] = args.pop(0)
elif arg in ('--user', '-u') and args:
options['user'] = args.pop(0)
elif arg in ('--password', '-p') and args:
options['password'] = args.pop(0)
else:
remaining.append(arg)
# abort here if these conditions are true
if options.get('help') and not remaining:
usage()
sys.exit(1)
if options.get('help') and remaining:
usage(remaining[0])
sys.exit(1)
if not remaining:
usage()
sys.exit(1)
if options.get('server'):
# it is ugly to use a global, but it is simple
global SERVER_URI
SERVER_URI = options['server']
if options.get('user'):
global SERVER_USER
SERVER_USER = options['user']
if options.get('password'):
global SERVER_PASS
SERVER_PASS = options['password']
subcmd = remaining[0].replace('-', '_')
is_async = 'async' in subcmd
if is_async:
subcmd = re.sub('async_', '', subcmd)
subcmd_func_name = 'xapi_' + subcmd
subcmd_func = globals().get(subcmd_func_name, None)
if subcmd == 'shell':
shell()
elif not subcmd_func or not callable(subcmd_func):
print 'Error: Unable to find subcommand \'%s\'' % subcmd
usage()
sys.exit(1)
try:
subcmd_func(remaining[1:], async = is_async)
except XenAPIError, e:
print 'Error: %s' % str(e.args[0])
sys.exit(2)
except OptionError, e:
print 'Error: %s' % e
sys.exit(0)
if __name__ == "__main__":
import sys
main(sys.argv[1:])
| mikesun/xen-cow-checkpointing | tools/python/scripts/xapi.py | Python | gpl-2.0 | 29,258 |
/* Copyright (C) 1991, 1993, 1995, 1996, 1997 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <errno.h>
#include <stdlib.h>
/* Execute LINE as a shell command. */
int
__libc_system (line)
const char *line;
{
if (line == NULL)
return 0; /* This indicates no command processor. */
__sys_errno (ENOSYS);
return -1;
}
weak_alias (__libc_system, system)
stub_warning (system)
#include <stub-tag.h>
| nslu2/glibc | sysdeps/generic/system.c | C | gpl-2.0 | 1,207 |
/* Copyright 2005,2006 Sven Reimers, Florian Vogler
*
* This file is part of the Software Quality Environment Project.
*
* The Software Quality Environment Project is free software:
* you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation,
* either version 2 of the License, or (at your option) any later version.
*
* The Software Quality Environment Project 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package org.nbheaven.sqe.codedefects.history.action;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.Collection;
import javax.swing.AbstractAction;
import javax.swing.Action;
import org.nbheaven.sqe.codedefects.core.util.SQECodedefectSupport;
import org.nbheaven.sqe.codedefects.history.util.CodeDefectHistoryPersistence;
import org.netbeans.api.project.Project;
import org.openide.util.ContextAwareAction;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
/**
*
* @author Sven Reimers
*/
public class SnapshotAction extends AbstractAction implements LookupListener, ContextAwareAction {
private Lookup context;
private Lookup.Result<Project> lkpInfo;
public SnapshotAction() {
this(Utilities.actionsGlobalContext());
}
public SnapshotAction(Lookup context) {
putValue("noIconInMenu", Boolean.TRUE); // NOI18N
putValue(Action.SHORT_DESCRIPTION,
NbBundle.getMessage(SnapshotAction.class, "HINT_Action"));
putValue(SMALL_ICON, ImageUtilities.image2Icon(ImageUtilities.loadImage("org/nbheaven/sqe/codedefects/history/resources/camera.png")));
this.context = context;
//The thing we want to listen for the presence or absence of
//on the global selection
Lookup.Template<Project> tpl = new Lookup.Template<Project>(Project.class);
lkpInfo = context.lookup(tpl);
lkpInfo.addLookupListener(this);
resultChanged(null);
}
@Override
public Action createContextAwareInstance(Lookup context) {
return new SnapshotAction(context);
}
@Override
public void resultChanged(LookupEvent ev) {
updateEnableState();
}
public String getName() {
return NbBundle.getMessage(SnapshotAction.class, "LBL_Action");
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
if (null != getActiveProject()) {
Project project = getActiveProject();
CodeDefectHistoryPersistence.addSnapshot(project);
}
}
private void updateEnableState() {
if (!EventQueue.isDispatchThread()) {
EventQueue.invokeLater(() -> updateEnableState());
return;
}
setEnabled(SQECodedefectSupport.isQualityAwareProject(getActiveProject()));
}
private Project getActiveProject() {
Collection<? extends Project> projects = lkpInfo.allInstances();
if (projects.size() == 1) {
Project project = projects.iterator().next();
return project;
}
return null;
}
}
| sqe-team/sqe | codedefects.history/src/org/nbheaven/sqe/codedefects/history/action/SnapshotAction.java | Java | gpl-2.0 | 3,600 |
/* Copyright (c) 2012, 2017, Oracle and/or its affiliates. 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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#ifndef CRYPT_HASHGEN_IMPL_H
#define CRYPT_HASHGEN_IMPL_H
#define ROUNDS_DEFAULT 5000
#define ROUNDS_MIN 1000
#define ROUNDS_MAX ROUNDS_DEFAULT
#define MIXCHARS 32
#define CRYPT_SALT_LENGTH 20
#define CRYPT_MAGIC_LENGTH 3
#define CRYPT_PARAM_LENGTH 13
#define SHA256_HASH_LENGTH 43
#define CRYPT_MAX_PASSWORD_SIZE (CRYPT_SALT_LENGTH + \
SHA256_HASH_LENGTH + \
CRYPT_MAGIC_LENGTH + \
CRYPT_PARAM_LENGTH)
#define MAX_PLAINTEXT_LENGTH 256
#include <stddef.h>
#include <my_global.h>
int extract_user_salt(char **salt_begin,
char **salt_end);
C_MODE_START
char *
my_crypt_genhash(char *ctbuffer,
size_t ctbufflen,
const char *plaintext,
int plaintext_len,
const char *switchsalt,
const char **params);
void generate_user_salt(char *buffer, int buffer_len);
void xor_string(char *to, int to_len, char *pattern, int pattern_len);
C_MODE_END
#endif
| gplessis/dotdeb-mysql | include/crypt_genhash_impl.h | C | gpl-2.0 | 1,798 |
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 2007-2008, Trinity College Computing Center
* Written by David Chappell <David.Chappell@trincoll.edu>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief Trivial application to read an extension into a variable
*
* \author David Chappell <David.Chappell@trincoll.edu>
*
* \ingroup applications
*/
/*** MODULEINFO
<support_level>core</support_level>
***/
#include "asterisk.h"
ASTERISK_REGISTER_FILE()
#include "asterisk/file.h"
#include "asterisk/pbx.h"
#include "asterisk/app.h"
#include "asterisk/module.h"
#include "asterisk/indications.h"
#include "asterisk/channel.h"
/*** DOCUMENTATION
<application name="ReadExten" language="en_US">
<synopsis>
Read an extension into a variable.
</synopsis>
<syntax>
<parameter name="variable" required="true" />
<parameter name="filename">
<para>File to play before reading digits or tone with option <literal>i</literal></para>
</parameter>
<parameter name="context">
<para>Context in which to match extensions.</para>
</parameter>
<parameter name="option">
<optionlist>
<option name="s">
<para>Return immediately if the channel is not answered.</para>
</option>
<option name="i">
<para>Play <replaceable>filename</replaceable> as an indication tone from your
<filename>indications.conf</filename> or a directly specified list of
frequencies and durations.</para>
</option>
<option name="n">
<para>Read digits even if the channel is not answered.</para>
</option>
</optionlist>
</parameter>
<parameter name="timeout">
<para>An integer number of seconds to wait for a digit response. If
greater than <literal>0</literal>, that value will override the default timeout.</para>
</parameter>
</syntax>
<description>
<para>Reads a <literal>#</literal> terminated string of digits from the user into the given variable.</para>
<para>Will set READEXTENSTATUS on exit with one of the following statuses:</para>
<variablelist>
<variable name="READEXTENSTATUS">
<value name="OK">
A valid extension exists in ${variable}.
</value>
<value name="TIMEOUT">
No extension was entered in the specified time. Also sets ${variable} to "t".
</value>
<value name="INVALID">
An invalid extension, ${INVALID_EXTEN}, was entered. Also sets ${variable} to "i".
</value>
<value name="SKIP">
Line was not up and the option 's' was specified.
</value>
<value name="ERROR">
Invalid arguments were passed.
</value>
</variable>
</variablelist>
</description>
</application>
***/
enum readexten_option_flags {
OPT_SKIP = (1 << 0),
OPT_INDICATION = (1 << 1),
OPT_NOANSWER = (1 << 2),
};
AST_APP_OPTIONS(readexten_app_options, {
AST_APP_OPTION('s', OPT_SKIP),
AST_APP_OPTION('i', OPT_INDICATION),
AST_APP_OPTION('n', OPT_NOANSWER),
});
static char *app = "ReadExten";
static int readexten_exec(struct ast_channel *chan, const char *data)
{
int res = 0;
char exten[256] = "";
int maxdigits = sizeof(exten) - 1;
int timeout = 0, digit_timeout = 0, x = 0;
char *argcopy = NULL, *status = "";
struct ast_tone_zone_sound *ts = NULL;
struct ast_flags flags = {0};
AST_DECLARE_APP_ARGS(arglist,
AST_APP_ARG(variable);
AST_APP_ARG(filename);
AST_APP_ARG(context);
AST_APP_ARG(options);
AST_APP_ARG(timeout);
);
if (ast_strlen_zero(data)) {
ast_log(LOG_WARNING, "ReadExten requires at least one argument\n");
pbx_builtin_setvar_helper(chan, "READEXTENSTATUS", "ERROR");
return 0;
}
argcopy = ast_strdupa(data);
AST_STANDARD_APP_ARGS(arglist, argcopy);
if (ast_strlen_zero(arglist.variable)) {
ast_log(LOG_WARNING, "Usage: ReadExten(variable[,filename[,context[,options[,timeout]]]])\n");
pbx_builtin_setvar_helper(chan, "READEXTENSTATUS", "ERROR");
return 0;
}
if (ast_strlen_zero(arglist.filename)) {
arglist.filename = NULL;
}
if (ast_strlen_zero(arglist.context)) {
arglist.context = ast_strdupa(ast_channel_context(chan));
}
if (!ast_strlen_zero(arglist.options)) {
ast_app_parse_options(readexten_app_options, &flags, NULL, arglist.options);
}
if (!ast_strlen_zero(arglist.timeout)) {
timeout = atoi(arglist.timeout);
if (timeout > 0)
timeout *= 1000;
}
if (timeout <= 0)
timeout = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000;
if (digit_timeout <= 0)
digit_timeout = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000;
if (ast_test_flag(&flags, OPT_INDICATION) && !ast_strlen_zero(arglist.filename)) {
ts = ast_get_indication_tone(ast_channel_zone(chan), arglist.filename);
}
do {
if (ast_channel_state(chan) != AST_STATE_UP) {
if (ast_test_flag(&flags, OPT_SKIP)) {
/* At the user's option, skip if the line is not up */
pbx_builtin_setvar_helper(chan, arglist.variable, "");
status = "SKIP";
break;
} else if (!ast_test_flag(&flags, OPT_NOANSWER)) {
/* Otherwise answer unless we're supposed to read while on-hook */
res = ast_answer(chan);
}
}
if (res < 0) {
status = "HANGUP";
break;
}
ast_playtones_stop(chan);
ast_stopstream(chan);
if (ts && ts->data[0]) {
res = ast_playtones_start(chan, 0, ts->data, 0);
} else if (arglist.filename) {
if (ast_test_flag(&flags, OPT_INDICATION) && ast_fileexists(arglist.filename, NULL, ast_channel_language(chan)) <= 0) {
/*
* We were asked to play an indication that did not exist in the config.
* If no such file exists, play it as a tonelist. With any luck they won't
* have a file named "350+440.ulaw"
* (but honestly, who would do something so silly?)
*/
res = ast_playtones_start(chan, 0, arglist.filename, 0);
} else {
res = ast_streamfile(chan, arglist.filename, ast_channel_language(chan));
}
}
for (x = 0; x < maxdigits; x++) {
ast_debug(3, "extension so far: '%s', timeout: %d\n", exten, timeout);
res = ast_waitfordigit(chan, timeout);
ast_playtones_stop(chan);
ast_stopstream(chan);
timeout = digit_timeout;
if (res < 1) { /* timeout expired or hangup */
if (ast_check_hangup(chan)) {
status = "HANGUP";
} else if (x == 0) {
pbx_builtin_setvar_helper(chan, arglist.variable, "t");
status = "TIMEOUT";
}
break;
}
exten[x] = res;
if (!ast_matchmore_extension(chan, arglist.context, exten, 1 /* priority */,
S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
if (!ast_exists_extension(chan, arglist.context, exten, 1,
S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))
&& res == '#') {
exten[x] = '\0';
}
break;
}
}
if (!ast_strlen_zero(status))
break;
if (ast_exists_extension(chan, arglist.context, exten, 1,
S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) {
ast_debug(3, "User entered valid extension '%s'\n", exten);
pbx_builtin_setvar_helper(chan, arglist.variable, exten);
status = "OK";
} else {
ast_debug(3, "User dialed invalid extension '%s' in context '%s' on %s\n", exten, arglist.context, ast_channel_name(chan));
pbx_builtin_setvar_helper(chan, arglist.variable, "i");
pbx_builtin_setvar_helper(chan, "INVALID_EXTEN", exten);
status = "INVALID";
}
} while (0);
if (ts) {
ts = ast_tone_zone_sound_unref(ts);
}
pbx_builtin_setvar_helper(chan, "READEXTENSTATUS", status);
return status[0] == 'H' ? -1 : 0;
}
static int unload_module(void)
{
int res = ast_unregister_application(app);
return res;
}
static int load_module(void)
{
int res = ast_register_application_xml(app, readexten_exec);
return res;
}
AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Read and evaluate extension validity");
| leedm777/asterisk | apps/app_readexten.c | C | gpl-2.0 | 8,312 |
<?php
/**
* Image helper class
*
* This class was derived from the show_image_in_imgtag.php and imageTools.class.php files in VM. It provides some
* image functions that are used throughout the VirtueMart shop.
*
* @package VirtueMart
* @subpackage Helpers
* @author Max Milbers
* @copyright Copyright (c) 2004-2008 Soeren Eberhardt-Biermann, 2009 VirtueMart Team. All rights reserved.
*/
defined('_JEXEC') or die();
if (!class_exists('VmMediaHandler')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'mediahandler.php');
class VmImage extends VmMediaHandler {
function processAction($data){
if(empty($data['media_action'])) return $data;
$data = parent::processAction($data);
if( $data['media_action'] == 'upload_create_thumb' ){
$oldFileUrl = $this->file_url;
$file_name = $this->uploadFile($this->file_url_folder);
if($file_name){
if($file_name!=$oldFileUrl && !empty($this->filename)){
$this->deleteFile($oldFileUrl);
}
$this->file_url = $this->file_url_folder.$file_name;
$this->filename = $file_name;
$oldFileUrlThumb = $this->file_url_thumb;
$this->file_url_thumb = $this->createThumb();
if($this->file_url_thumb!=$oldFileUrlThumb){
$this->deleteFile($oldFileUrlThumb);
}
}
} //creating the thumbnail image
else if( $data['media_action'] == 'create_thumb' ){
$this->file_url_thumb = $this->createThumb();
}
if(empty($this->file_title) && !empty($file_name)) $this->file_title = $file_name;
return $data;
}
function displayMediaFull($imageArgs='',$lightbox=true,$effect ="class='modal'",$description = true ){
if(!$this->file_is_forSale){
// Remote image URL
if( substr( $this->file_url, 0, 4) == "http" ) {
$file_url = $this->file_url;
$file_alt = $this->file_title;
} else {
$rel_path = str_replace('/',DS,$this->file_url_folder);
$fullSizeFilenamePath = JPATH_ROOT.DS.$rel_path.$this->file_name.'.'.$this->file_extension;
if (!file_exists($fullSizeFilenamePath)) {
$file_url = $this->theme_url.'assets/images/vmgeneral/'.VmConfig::get('no_image_found');
$file_alt = JText::_('COM_VIRTUEMART_NO_IMAGE_FOUND').' '.$this->file_description;
} else {
$file_url = $this->file_url;
$file_alt = $this->file_meta;
}
}
$postText = '';
if($description) $postText = $this->file_description;
return $this->displayIt($file_url, $file_alt, $imageArgs,$lightbox,'',$postText);
} else {
//Media which should be sold, show them only as thumb (works as preview)
return $this->displayMediaThumb('id="vm_display_image"',false);
}
}
/**
* a small function that ensures that we always build the thumbnail name with the same method
*/
public function createThumbName($width=0,$height=0){
if(empty($this->file_name)) return false;
if(empty($width)) $width = VmConfig::get('img_width', 90);
if(empty($height)) $height = VmConfig::get('img_height', 90);
$this->file_name_thumb = $this->file_name.'_'.$width.'x'.$height;
return $this->file_name_thumb;
}
/**
* This function actually creates the thumb
* and when it is instanciated with one of the getImage function automatically updates the db
*
* @author Max Milbers
* @param boolean $save Execute update function
* @return name of the thumbnail
*/
public function createThumb() {
$synchronise = JRequest::getString('synchronise',false);
if(!VmConfig::get('img_resize_enable') || $synchronise) return;
//now lets create the thumbnail, saving is done in this function
$width = VmConfig::get('img_width', 90);
$height = VmConfig::get('img_height', 90);
// Don't allow sizes beyond 2000 pixels //I dont think that this is good, should be config
// $width = min($width, 2000);
// $height = min($height, 2000);
$maxsize = false;
$bgred = 255;
$bggreen = 255;
$bgblue = 255;
$root = '';
if($this->file_is_forSale==0){
$rel_path = str_replace('/',DS,$this->file_url_folder);
$fullSizeFilenamePath = JPATH_ROOT.DS.$rel_path.$this->file_name.'.'.$this->file_extension;
} else {
$rel_path = str_replace('/',DS,$this->file_url_folder);
$fullSizeFilenamePath = $this->file_url_folder.$this->file_name.'.'.$this->file_extension;
}
$this->file_name_thumb = $this->createThumbName();
$file_path_thumb = str_replace('/',DS,$this->file_url_folder_thumb);
$resizedFilenamePath = JPATH_ROOT.DS.$file_path_thumb.$this->file_name_thumb.'.'.$this->file_extension;
$this->checkPathCreateFolders($file_path_thumb);
if (file_exists($fullSizeFilenamePath)) {
if (!class_exists('Img2Thumb')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'img2thumb.php');
$createdImage = new Img2Thumb($fullSizeFilenamePath, $width, $height, $resizedFilenamePath, $maxsize, $bgred, $bggreen, $bgblue);
if($createdImage){
return $this->file_url_folder_thumb.$this->file_name_thumb.'.'.$this->file_extension;
} else {
return 0;
}
} else {
vmError('Couldnt create thumb, file not found '.$fullSizeFilenamePath);
return 0;
}
}
public function checkPathCreateFolders($path){
$elements = explode(DS,$path);
$examine = JPATH_ROOT;
foreach($elements as $piece){
$examine = $examine.DS.$piece;
if(!JFolder::exists($examine)){
JFolder::create($examine);
vmInfo('create folder for resized image '.$examine);
}
}
}
/**
* Display an image icon for the given image and create a link to the given link.
*
* @param string $link Link to use in the href tag
* @param string $image Name of the image file to display
* @param string $text Text to use for the image alt text and to display under the image.
*/
public function displayImageButton($link, $imageclass, $text) {
$button = '<a title="' . $text . '" href="' . $link . '">';
$button .= '<span class="vmicon48 '.$imageclass.'"></span>';
$button .= '<br />' . $text.'</a>';
echo $button;
}
}
| Fundacion-AG/PaginaWebFAG | tmp/install_535533f62cdf3/administrator/components/com_virtuemart/helpers/image.php | PHP | gpl-2.0 | 5,890 |
#ifndef __GEDIT_FILE_BROWER_MESSAGES_MESSAGES_H__
#define __GEDIT_FILE_BROWER_MESSAGES_MESSAGES_H__
#include "gedit-file-browser-message-activation.h"
#include "gedit-file-browser-message-add-context-item.h"
#include "gedit-file-browser-message-add-filter.h"
#include "gedit-file-browser-message-get-root.h"
#include "gedit-file-browser-message-get-view.h"
#include "gedit-file-browser-message-id.h"
#include "gedit-file-browser-message-id-location.h"
#include "gedit-file-browser-message-set-emblem.h"
#include "gedit-file-browser-message-set-root.h"
#endif /* __GEDIT_FILE_BROWER_MESSAGES_MESSAGES_H__ */
| dtrebbien/gedit | plugins/filebrowser/messages/messages.h | C | gpl-2.0 | 610 |
/*-
* #%L
* Fiji distribution of ImageJ for the life sciences.
* %%
* Copyright (C) 2007 - 2017 Fiji developers.
* %%
* 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/gpl-2.0.html>.
* #L%
*/
package spim.fiji.plugin;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import mpicbg.spim.data.sequence.Channel;
import mpicbg.spim.data.sequence.ViewDescription;
import mpicbg.spim.data.sequence.ViewId;
import mpicbg.spim.data.sequence.VoxelDimensions;
import mpicbg.spim.io.IOFunctions;
import net.imglib2.KDTree;
import net.imglib2.RealPoint;
import net.imglib2.neighborsearch.KNearestNeighborSearchOnKDTree;
import spim.fiji.plugin.queryXML.LoadParseQueryXML;
import spim.fiji.plugin.thinout.ChannelProcessThinOut;
import spim.fiji.plugin.thinout.Histogram;
import spim.fiji.spimdata.SpimData2;
import spim.fiji.spimdata.interestpoints.InterestPoint;
import spim.fiji.spimdata.interestpoints.InterestPointList;
import spim.fiji.spimdata.interestpoints.ViewInterestPointLists;
import spim.fiji.spimdata.interestpoints.ViewInterestPoints;
public class ThinOut_Detections implements PlugIn
{
public static boolean[] defaultShowHistogram;
public static int[] defaultSubSampling;
public static String[] defaultNewLabels;
public static int[] defaultRemoveKeep;
public static double[] defaultCutoffThresholdMin, defaultCutoffThresholdMax;
public static String[] removeKeepChoice = new String[]{ "Remove Range", "Keep Range" };
public static double defaultThresholdMinValue = 0;
public static double defaultThresholdMaxValue = 5;
public static int defaultSubSamplingValue = 1;
public static String defaultNewLabelText = "thinned-out";
public static int defaultRemoveKeepValue = 0; // 0 == remove, 1 == keep
@Override
public void run( final String arg )
{
final LoadParseQueryXML xml = new LoadParseQueryXML();
if ( !xml.queryXML( "", true, false, true, true ) )
return;
final SpimData2 data = xml.getData();
final List< ViewId > viewIds = SpimData2.getAllViewIdsSorted( data, xml.getViewSetupsToProcess(), xml.getTimePointsToProcess() );
// ask which channels have the objects we are searching for
final List< ChannelProcessThinOut > channels = getChannelsAndLabels( data, viewIds );
if ( channels == null )
return;
// get the actual min/max thresholds for cutting out
if ( !getThinOutThresholds( data, viewIds, channels ) )
return;
// thin out detections and save the new interestpoint files
if ( !thinOut( data, viewIds, channels, true ) )
return;
// write new xml
SpimData2.saveXML( data, xml.getXMLFileName(), xml.getClusterExtension() );
}
public static boolean thinOut( final SpimData2 spimData, final List< ViewId > viewIds, final List< ChannelProcessThinOut > channels, final boolean save )
{
final ViewInterestPoints vip = spimData.getViewInterestPoints();
for ( final ChannelProcessThinOut channel : channels )
{
final double minDistance = channel.getMin();
final double maxDistance = channel.getMax();
final boolean keepRange = channel.keepRange();
for ( final ViewId viewId : viewIds )
{
final ViewDescription vd = spimData.getSequenceDescription().getViewDescription( viewId );
if ( !vd.isPresent() || vd.getViewSetup().getChannel().getId() != channel.getChannel().getId() )
continue;
final ViewInterestPointLists vipl = vip.getViewInterestPointLists( viewId );
final InterestPointList oldIpl = vipl.getInterestPointList( channel.getLabel() );
if ( oldIpl.getInterestPoints() == null )
oldIpl.loadInterestPoints();
final VoxelDimensions voxelSize = vd.getViewSetup().getVoxelSize();
// assemble the list of points (we need two lists as the KDTree sorts the list)
// we assume that the order of list2 and points is preserved!
final List< RealPoint > list1 = new ArrayList< RealPoint >();
final List< RealPoint > list2 = new ArrayList< RealPoint >();
final List< double[] > points = new ArrayList< double[] >();
for ( final InterestPoint ip : oldIpl.getInterestPoints() )
{
list1.add ( new RealPoint(
ip.getL()[ 0 ] * voxelSize.dimension( 0 ),
ip.getL()[ 1 ] * voxelSize.dimension( 1 ),
ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) );
list2.add ( new RealPoint(
ip.getL()[ 0 ] * voxelSize.dimension( 0 ),
ip.getL()[ 1 ] * voxelSize.dimension( 1 ),
ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) );
points.add( ip.getL() );
}
// make the KDTree
final KDTree< RealPoint > tree = new KDTree< RealPoint >( list1, list1 );
// Nearest neighbor for each point, populate the new list
final KNearestNeighborSearchOnKDTree< RealPoint > nn = new KNearestNeighborSearchOnKDTree< RealPoint >( tree, 2 );
final InterestPointList newIpl = new InterestPointList(
oldIpl.getBaseDir(),
new File(
oldIpl.getFile().getParentFile(),
"tpId_" + viewId.getTimePointId() + "_viewSetupId_" + viewId.getViewSetupId() + "." + channel.getNewLabel() ) );
newIpl.setInterestPoints( new ArrayList< InterestPoint >() );
int id = 0;
for ( int j = 0; j < list2.size(); ++j )
{
final RealPoint p = list2.get( j );
nn.search( p );
// first nearest neighbor is the point itself, we need the second nearest
final double d = nn.getDistance( 1 );
if ( ( keepRange && d >= minDistance && d <= maxDistance ) || ( !keepRange && ( d < minDistance || d > maxDistance ) ) )
{
newIpl.getInterestPoints().add( new InterestPoint( id++, points.get( j ).clone() ) );
}
}
if ( keepRange )
newIpl.setParameters( "thinned-out '" + channel.getLabel() + "', kept range from " + minDistance + " to " + maxDistance );
else
newIpl.setParameters( "thinned-out '" + channel.getLabel() + "', removed range from " + minDistance + " to " + maxDistance );
vipl.addInterestPointList( channel.getNewLabel(), newIpl );
IOFunctions.println( new Date( System.currentTimeMillis() ) + ": TP=" + vd.getTimePointId() + " ViewSetup=" + vd.getViewSetupId() +
", Detections: " + oldIpl.getInterestPoints().size() + " >>> " + newIpl.getInterestPoints().size() );
if ( save && !newIpl.saveInterestPoints() )
{
IOFunctions.println( "Error saving interest point list: " + new File( newIpl.getBaseDir(), newIpl.getFile().toString() + newIpl.getInterestPointsExt() ) );
return false;
}
}
}
return true;
}
public static boolean getThinOutThresholds( final SpimData2 spimData, final List< ViewId > viewIds, final List< ChannelProcessThinOut > channels )
{
for ( final ChannelProcessThinOut channel : channels )
if ( channel.showHistogram() )
plotHistogram( spimData, viewIds, channel );
if ( defaultCutoffThresholdMin == null || defaultCutoffThresholdMin.length != channels.size() ||
defaultCutoffThresholdMax == null || defaultCutoffThresholdMax.length != channels.size() )
{
defaultCutoffThresholdMin = new double[ channels.size() ];
defaultCutoffThresholdMax = new double[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
{
defaultCutoffThresholdMin[ i ] = defaultThresholdMinValue;
defaultCutoffThresholdMax[ i ] = defaultThresholdMaxValue;
}
}
if ( defaultRemoveKeep == null || defaultRemoveKeep.length != channels.size() )
{
defaultRemoveKeep = new int[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultRemoveKeep[ i ] = defaultRemoveKeepValue;
}
final GenericDialog gd = new GenericDialog( "Define cut-off threshold" );
for ( int c = 0; c < channels.size(); ++c )
{
final ChannelProcessThinOut channel = channels.get( c );
gd.addChoice( "Channel_" + channel.getChannel().getName() + "_", removeKeepChoice, removeKeepChoice[ defaultRemoveKeep[ c ] ] );
gd.addNumericField( "Channel_" + channel.getChannel().getName() + "_range_lower_threshold", defaultCutoffThresholdMin[ c ], 2 );
gd.addNumericField( "Channel_" + channel.getChannel().getName() + "_range_upper_threshold", defaultCutoffThresholdMax[ c ], 2 );
gd.addMessage( "" );
}
gd.showDialog();
if ( gd.wasCanceled() )
return false;
for ( int c = 0; c < channels.size(); ++c )
{
final ChannelProcessThinOut channel = channels.get( c );
final int removeKeep = defaultRemoveKeep[ c ] = gd.getNextChoiceIndex();
if ( removeKeep == 1 )
channel.setKeepRange( true );
else
channel.setKeepRange( false );
channel.setMin( defaultCutoffThresholdMin[ c ] = gd.getNextNumber() );
channel.setMax( defaultCutoffThresholdMax[ c ] = gd.getNextNumber() );
if ( channel.getMin() >= channel.getMax() )
{
IOFunctions.println( "You selected the minimal threshold larger than the maximal threshold for channel " + channel.getChannel().getName() );
IOFunctions.println( "Stopping." );
return false;
}
else
{
if ( channel.keepRange() )
IOFunctions.println( "Channel " + channel.getChannel().getName() + ": keep only distances from " + channel.getMin() + " >>> " + channel.getMax() );
else
IOFunctions.println( "Channel " + channel.getChannel().getName() + ": remove distances from " + channel.getMin() + " >>> " + channel.getMax() );
}
}
return true;
}
public static Histogram plotHistogram( final SpimData2 spimData, final List< ViewId > viewIds, final ChannelProcessThinOut channel )
{
final ViewInterestPoints vip = spimData.getViewInterestPoints();
// list of all distances
final ArrayList< Double > distances = new ArrayList< Double >();
final Random rnd = new Random( System.currentTimeMillis() );
String unit = null;
for ( final ViewId viewId : viewIds )
{
final ViewDescription vd = spimData.getSequenceDescription().getViewDescription( viewId );
if ( !vd.isPresent() || vd.getViewSetup().getChannel().getId() != channel.getChannel().getId() )
continue;
final ViewInterestPointLists vipl = vip.getViewInterestPointLists( viewId );
final InterestPointList ipl = vipl.getInterestPointList( channel.getLabel() );
final VoxelDimensions voxelSize = vd.getViewSetup().getVoxelSize();
if ( ipl.getInterestPoints() == null )
ipl.loadInterestPoints();
if ( unit == null )
unit = vd.getViewSetup().getVoxelSize().unit();
// assemble the list of points
final List< RealPoint > list = new ArrayList< RealPoint >();
for ( final InterestPoint ip : ipl.getInterestPoints() )
{
list.add ( new RealPoint(
ip.getL()[ 0 ] * voxelSize.dimension( 0 ),
ip.getL()[ 1 ] * voxelSize.dimension( 1 ),
ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) );
}
// make the KDTree
final KDTree< RealPoint > tree = new KDTree< RealPoint >( list, list );
// Nearest neighbor for each point
final KNearestNeighborSearchOnKDTree< RealPoint > nn = new KNearestNeighborSearchOnKDTree< RealPoint >( tree, 2 );
for ( final RealPoint p : list )
{
// every n'th point only
if ( rnd.nextDouble() < 1.0 / (double)channel.getSubsampling() )
{
nn.search( p );
// first nearest neighbor is the point itself, we need the second nearest
distances.add( nn.getDistance( 1 ) );
}
}
}
final Histogram h = new Histogram( distances, 100, "Distance Histogram [Channel=" + channel.getChannel().getName() + "]", unit );
h.showHistogram();
IOFunctions.println( "Channel " + channel.getChannel().getName() + ": min distance=" + h.getMin() + ", max distance=" + h.getMax() );
return h;
}
public static ArrayList< ChannelProcessThinOut > getChannelsAndLabels(
final SpimData2 spimData,
final List< ViewId > viewIds )
{
// build up the dialog
final GenericDialog gd = new GenericDialog( "Choose segmentations to thin out" );
final List< Channel > channels = SpimData2.getAllChannelsSorted( spimData, viewIds );
final int nAllChannels = spimData.getSequenceDescription().getAllChannelsOrdered().size();
if ( Interest_Point_Registration.defaultChannelLabels == null || Interest_Point_Registration.defaultChannelLabels.length != nAllChannels )
Interest_Point_Registration.defaultChannelLabels = new int[ nAllChannels ];
if ( defaultShowHistogram == null || defaultShowHistogram.length != channels.size() )
{
defaultShowHistogram = new boolean[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultShowHistogram[ i ] = true;
}
if ( defaultSubSampling == null || defaultSubSampling.length != channels.size() )
{
defaultSubSampling = new int[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultSubSampling[ i ] = defaultSubSamplingValue;
}
if ( defaultNewLabels == null || defaultNewLabels.length != channels.size() )
{
defaultNewLabels = new String[ channels.size() ];
for ( int i = 0; i < channels.size(); ++i )
defaultNewLabels[ i ] = defaultNewLabelText;
}
// check which channels and labels are available and build the choices
final ArrayList< String[] > channelLabels = new ArrayList< String[] >();
int j = 0;
for ( final Channel channel : channels )
{
final String[] labels = Interest_Point_Registration.getAllInterestPointLabelsForChannel(
spimData,
viewIds,
channel,
"thin out" );
if ( Interest_Point_Registration.defaultChannelLabels[ j ] >= labels.length )
Interest_Point_Registration.defaultChannelLabels[ j ] = 0;
String ch = channel.getName().replace( ' ', '_' );
gd.addCheckbox( "Channel_" + ch + "_Display_distance_histogram", defaultShowHistogram[ j ] );
gd.addChoice( "Channel_" + ch + "_Interest_points", labels, labels[ Interest_Point_Registration.defaultChannelLabels[ j ] ] );
gd.addStringField( "Channel_" + ch + "_New_label", defaultNewLabels[ j ], 20 );
gd.addNumericField( "Channel_" + ch + "_Subsample histogram", defaultSubSampling[ j ], 0, 5, "times" );
channelLabels.add( labels );
++j;
}
gd.showDialog();
if ( gd.wasCanceled() )
return null;
// assemble which channels have been selected with with label
final ArrayList< ChannelProcessThinOut > channelsToProcess = new ArrayList< ChannelProcessThinOut >();
j = 0;
for ( final Channel channel : channels )
{
final boolean showHistogram = defaultShowHistogram[ j ] = gd.getNextBoolean();
final int channelChoice = Interest_Point_Registration.defaultChannelLabels[ j ] = gd.getNextChoiceIndex();
final String newLabel = defaultNewLabels[ j ] = gd.getNextString();
final int subSampling = defaultSubSampling[ j ] = (int)Math.round( gd.getNextNumber() );
if ( channelChoice < channelLabels.get( j ).length - 1 )
{
String label = channelLabels.get( j )[ channelChoice ];
if ( label.contains( Interest_Point_Registration.warningLabel ) )
label = label.substring( 0, label.indexOf( Interest_Point_Registration.warningLabel ) );
channelsToProcess.add( new ChannelProcessThinOut( channel, label, newLabel, showHistogram, subSampling ) );
}
++j;
}
return channelsToProcess;
}
public static void main( final String[] args )
{
new ThinOut_Detections().run( null );
}
}
| bigdataviewer/SPIM_Registration | src/main/java/spim/fiji/plugin/ThinOut_Detections.java | Java | gpl-2.0 | 15,827 |
<?
require_once("pdfoprdesubi.php");
$obj= new pdfreporte();
# $obj->AddPage();
# $obj->AliasNbPages();
# $obj->Cuerpo();
# $obj->Output();
$tb=$obj->bd->select($obj->sql);
if (!$tb->EOF)
{ //HAY DATOS
$obj->AliasNbPages();
$obj->AddPage();
$obj->Cuerpo();
$obj->Output();
}
else
{ //NO HAY DATOS
?>
<script>
alert('No hay informacion para procesar este reporte...');
location=("oprdesubi.php");
</script>
<?
}
?> | cidesa/roraima | web/reportes/reportes/tesoreria/roprdesubi.php | PHP | gpl-2.0 | 463 |
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2022 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
namespace Glpi\Tests\Api\Deprecated;
interface DeprecatedInterface
{
/**
* Get deprecated type
* @return string
*/
public static function getDeprecatedType(): string;
/**
* Get current type
* @return string
*/
public static function getCurrentType(): string;
/**
* Get deprecated expected fields
* @return array
*/
public static function getDeprecatedFields(): array;
/**
* Get current add input
* @return array
*/
public static function getCurrentAddInput(): array;
/**
* Get deprecated add input
* @return array
*/
public static function getDeprecatedAddInput(): array;
/**
* Get deprecated update input
* @return array
*/
public static function getDeprecatedUpdateInput(): array;
/**
* Get expected data after insert
* @return array
*/
public static function getExpectedAfterInsert(): array;
/**
* Get expected data after update
* @return array
*/
public static function getExpectedAfterUpdate(): array;
/**
* Get deprecated search query
* @return string
*/
public static function getDeprecatedSearchQuery(): string;
/**
* Get current search query
* @return string
*/
public static function getCurrentSearchQuery(): string;
}
| stweil/glpi | tests/src/Api/Deprecated/DeprecatedInterface.php | PHP | gpl-2.0 | 2,534 |
/*
* arch/arm/mach-tegra/board-smba1002.c
*
* Copyright (C) 2011 Eduardo José Tagle <ejtagle@tutopia.com>
*
* 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/console.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/version.h>
#include <linux/platform_device.h>
#include <linux/serial_8250.h>
#include <linux/clk.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/dma-mapping.h>
#include <linux/fsl_devices.h>
#include <linux/platform_data/tegra_usb.h>
#include <linux/pda_power.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/reboot.h>
#include <linux/i2c-tegra.h>
#include <linux/memblock.h>
#include <linux/antares_dock.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <asm/setup.h>
#include <mach/io.h>
#include <mach/w1.h>
#include <mach/iomap.h>
#include <mach/irqs.h>
#include <mach/nand.h>
#include <mach/iomap.h>
#include <mach/sdhci.h>
#include <mach/gpio.h>
#include <mach/clk.h>
#include <mach/usb_phy.h>
#include <mach/i2s.h>
#include <mach/system.h>
#include <linux/nvmap.h>
#include "board.h"
#include "board-smba1002.h"
#include "clock.h"
#include "gpio-names.h"
#include "devices.h"
#include "pm.h"
#include "wakeups-t2.h"
#include "wdt-recovery.h"
#include <linux/rfkill-gpio.h>
#define PMC_CTRL 0x0
#define PMC_CTRL_INTR_LOW (1 << 17)
static struct rfkill_gpio_platform_data bluetooth_rfkill = {
.name = "bluetooth_rfkill",
.shutdown_gpio = -1,
.reset_gpio = SMBA1002_BT_RESET,
.type = RFKILL_TYPE_BLUETOOTH,
};
static struct platform_device bluetooth_rfkill_device = {
.name = "rfkill_gpio",
.id = -1,
.dev = {
.platform_data = &bluetooth_rfkill,
},
};
#ifdef CONFIG_BT_BLUEDROID
extern void bluesleep_setup_uart_port(struct platform_device *uart_dev);
#endif
void __init smba_setup_bluesleep(void)
{
/*Add Clock Resource*/
clk_add_alias("bcm4329_32k_clk", bluetooth_rfkill_device.name, \
"blink", NULL);
#ifdef CONFIG_BT_BLUEDROID
bluesleep_setup_uart_port(&tegra_uartc_device);
#endif
return;
}
static struct resource smba_bluesleep_resources[] = {
[0] = {
.name = "gpio_host_wake",
.start = SMBA1002_BT_IRQ,
.end = SMBA1002_BT_IRQ,
.flags = IORESOURCE_IO,
},
[1] = {
.name = "gpio_ext_wake",
.start = SMBA1002_BT_WAKEUP,
.end = SMBA1002_BT_WAKEUP,
.flags = IORESOURCE_IO,
},
[2] = {
.name = "host_wake",
.start = TEGRA_GPIO_TO_IRQ(SMBA1002_BT_IRQ),
.end = TEGRA_GPIO_TO_IRQ(SMBA1002_BT_IRQ),
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWEDGE,
},
};
static struct platform_device smba_bluesleep_device = {
.name = "bluesleep",
.id = -1,
.num_resources = ARRAY_SIZE(smba_bluesleep_resources),
.resource = smba_bluesleep_resources,
};
static struct dock_platform_data dock_on_platform_data = {
.irq = TEGRA_GPIO_TO_IRQ(SMBA1002_DOCK),
.gpio_num = SMBA1002_DOCK,
};
static struct platform_device tegra_dock_device =
{
.name = "tegra_dock",
.id = -1,
.dev = {
.platform_data = &dock_on_platform_data,
},
};
static struct platform_device *smba_devices[] __initdata = {
&tegra_pmu_device,
&tegra_gart_device,
&tegra_aes_device,
&bluetooth_rfkill_device,
&smba_bluesleep_device,
&tegra_wdt_device,
&tegra_avp_device,
&tegra_dock_device
};
static void __init tegra_smba_init(void)
{
/* Initialize the pinmux */
smba_pinmux_init();
/* Initialize the clocks - clocks require the pinmux to be initialized first */
smba_clks_init();
platform_add_devices(smba_devices,ARRAY_SIZE(smba_devices));
/* Register i2c devices - required for Power management and MUST be done before the power register */
smba_i2c_register_devices();
/* Register the power subsystem - Including the poweroff handler - Required by all the others */
smba_charge_init();
smba_regulator_init();
/* Register the USB device */
smba_usb_register_devices();
/* Register UART devices */
smba_uart_register_devices();
/* Register RAM Console */
tegra_ram_console_debug_init();
/* Register GPU devices */
smba_panel_init();
/* Register Audio devices */
smba_audio_register_devices();
/* Register all the keyboard devices */
smba_keys_init();
/* Register touchscreen devices */
smba_touch_register_devices();
/* Register accelerometer device */
smba_sensors_register_devices();
/* Register Camera powermanagement devices */
smba_camera_register_devices();
/* Register NAND flash devices */
smba_nand_register_devices();
/* Register SDHCI devices */
smba_sdhci_init();
/* Register Bluetooth powermanagement devices */
smba_setup_bluesleep();
/* Release the tegra bootloader framebuffer */
tegra_release_bootloader_fb();
}
static void __init tegra_smba_reserve(void)
{
if (memblock_reserve(0x0, 4096) < 0)
pr_warn("Cannot reserve first 4K of memory for safety\n");
/* Reserve the graphics memory */
tegra_reserve(SMBA1002_GPU_MEM_SIZE, SMBA1002_FB1_MEM_SIZE, SMBA1002_FB2_MEM_SIZE);
tegra_ram_console_debug_reserve(SZ_1M);
}
static void __init tegra_smba_fixup(struct machine_desc *desc,
struct tag *tags, char **cmdline, struct meminfo *mi)
{
mi->nr_banks = SMBA1002_MEM_BANKS;
mi->bank[0].start = PHYS_OFFSET;
mi->bank[0].size = SMBA1002_MEM_SIZE - SMBA1002_TOTAL_GPU_MEM_SIZE;
}
MACHINE_START(HARMONY, "harmony")
.boot_params = 0x00000100,
.fixup = tegra_smba_fixup,
.map_io = tegra_map_common_io,
.reserve = tegra_smba_reserve,
.init_early = tegra_init_early,
.init_irq = tegra_init_irq,
.timer = &tegra_timer,
.init_machine = tegra_smba_init,
MACHINE_END
| fosser2/android-tegra-nv-3.1.10-rel-15r7 | arch/arm/mach-tegra/board-smba1002.c | C | gpl-2.0 | 6,001 |
/*
* Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/** \file
\ingroup u2w
*/
#include "WorldSocket.h" // must be first to make ACE happy with ACE includes in it
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "Log.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Player.h"
#include "ObjectMgr.h"
#include "Group.h"
#include "Guild.h"
#include "World.h"
#include "BattleGroundMgr.h"
#include "MapManager.h"
#include "SocialMgr.h"
#include "Auth/AuthCrypt.h"
#include "Auth/HMACSHA1.h"
#include "zlib/zlib.h"
// select opcodes appropriate for processing in Map::Update context for current session state
static bool MapSessionFilterHelper(WorldSession* session, OpcodeHandler const& opHandle)
{
// we do not process thread-unsafe packets
if (opHandle.packetProcessing == PROCESS_THREADUNSAFE)
return false;
// we do not process not loggined player packets
Player * plr = session->GetPlayer();
if (!plr)
return false;
// in Map::Update() we do not process packets where player is not in world!
return plr->IsInWorld();
}
bool MapSessionFilter::Process(WorldPacket * packet)
{
OpcodeHandler const& opHandle = opcodeTable[packet->GetOpcode()];
if (opHandle.packetProcessing == PROCESS_INPLACE)
return true;
// let's check if our opcode can be really processed in Map::Update()
return MapSessionFilterHelper(m_pSession, opHandle);
}
// we should process ALL packets when player is not in world/logged in
// OR packet handler is not thread-safe!
bool WorldSessionFilter::Process(WorldPacket* packet)
{
OpcodeHandler const& opHandle = opcodeTable[packet->GetOpcode()];
// check if packet handler is supposed to be safe
if (opHandle.packetProcessing == PROCESS_INPLACE)
return true;
// let's check if our opcode can't be processed in Map::Update()
return !MapSessionFilterHelper(m_pSession, opHandle);
}
/// WorldSession constructor
WorldSession::WorldSession(uint32 id, WorldSocket *sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale) :
LookingForGroup_auto_join(false), LookingForGroup_auto_add(false), m_muteTime(mute_time),
_player(NULL), m_Socket(sock),_security(sec), _accountId(id), m_expansion(expansion), _logoutTime(0),
m_inQueue(false), m_playerLoading(false), m_playerLogout(false), m_playerRecentlyLogout(false), m_playerSave(false),
m_sessionDbcLocale(sWorld.GetAvailableDbcLocale(locale)), m_sessionDbLocaleIndex(sObjectMgr.GetIndexForLocale(locale)),
m_latency(0), m_tutorialState(TUTORIALDATA_UNCHANGED)
{
if (sock)
{
m_Address = sock->GetRemoteAddress ();
sock->AddReference ();
}
}
/// WorldSession destructor
WorldSession::~WorldSession()
{
///- unload player if not unloaded
if (_player)
LogoutPlayer (true);
/// - If have unclosed socket, close it
if (m_Socket)
{
m_Socket->CloseSocket ();
m_Socket->RemoveReference ();
m_Socket = NULL;
}
///- empty incoming packet queue
WorldPacket* packet;
while(_recvQueue.next(packet))
delete packet;
}
void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const
{
sLog.outError("Client (account %u) send packet %s (%u) with size " SIZEFMTD " but expected %u (attempt crash server?), skipped",
GetAccountId(),LookupOpcodeName(packet.GetOpcode()),packet.GetOpcode(),packet.size(),size);
}
/// Get the player name
char const* WorldSession::GetPlayerName() const
{
return GetPlayer() ? GetPlayer()->GetName() : "<none>";
}
/// Send a packet to the client
void WorldSession::SendPacket(WorldPacket const* packet)
{
if (!m_Socket)
return;
#ifdef MANGOS_DEBUG
// Code for network use statistic
static uint64 sendPacketCount = 0;
static uint64 sendPacketBytes = 0;
static time_t firstTime = time(NULL);
static time_t lastTime = firstTime; // next 60 secs start time
static uint64 sendLastPacketCount = 0;
static uint64 sendLastPacketBytes = 0;
time_t cur_time = time(NULL);
if((cur_time - lastTime) < 60)
{
sendPacketCount+=1;
sendPacketBytes+=packet->size();
sendLastPacketCount+=1;
sendLastPacketBytes+=packet->size();
}
else
{
uint64 minTime = uint64(cur_time - lastTime);
uint64 fullTime = uint64(lastTime - firstTime);
DETAIL_LOG("Send all time packets count: " UI64FMTD " bytes: " UI64FMTD " avr.count/sec: %f avr.bytes/sec: %f time: %u",sendPacketCount,sendPacketBytes,float(sendPacketCount)/fullTime,float(sendPacketBytes)/fullTime,uint32(fullTime));
DETAIL_LOG("Send last min packets count: " UI64FMTD " bytes: " UI64FMTD " avr.count/sec: %f avr.bytes/sec: %f",sendLastPacketCount,sendLastPacketBytes,float(sendLastPacketCount)/minTime,float(sendLastPacketBytes)/minTime);
lastTime = cur_time;
sendLastPacketCount = 1;
sendLastPacketBytes = packet->wpos(); // wpos is real written size
}
#endif // !MANGOS_DEBUG
if (m_Socket->SendPacket (*packet) == -1)
m_Socket->CloseSocket ();
}
/// Add an incoming packet to the queue
void WorldSession::QueuePacket(WorldPacket* new_packet)
{
_recvQueue.add(new_packet);
}
/// Logging helper for unexpected opcodes
void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char *reason)
{
sLog.outError( "SESSION: received unexpected opcode %s (0x%.4X) %s",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode(),
reason);
}
/// Logging helper for unexpected opcodes
void WorldSession::LogUnprocessedTail(WorldPacket *packet)
{
sLog.outError( "SESSION: opcode %s (0x%.4X) have unprocessed tail data (read stop at " SIZEFMTD " from " SIZEFMTD ")",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode(),
packet->rpos(),packet->wpos());
}
/// Update the WorldSession (triggered by World update)
bool WorldSession::Update(uint32 diff, PacketFilter& updater)
{
///- Retrieve packets from the receive queue and call the appropriate handlers
/// not process packets if socket already closed
WorldPacket* packet;
while (m_Socket && !m_Socket->IsClosed() && _recvQueue.next(packet, updater))
{
/*#if 1
sLog.outError( "MOEP: %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
#endif*/
OpcodeHandler const& opHandle = opcodeTable[packet->GetOpcode()];
try
{
switch (opHandle.status)
{
case STATUS_LOGGEDIN:
if(!_player)
{
// skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
if(!m_playerRecentlyLogout)
LogUnexpectedOpcode(packet, "the player has not logged in yet");
}
else if(_player->IsInWorld())
ExecuteOpcode(opHandle, packet);
// lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
break;
case STATUS_LOGGEDIN_OR_RECENTLY_LOGGEDOUT:
if(!_player && !m_playerRecentlyLogout)
{
LogUnexpectedOpcode(packet, "the player has not logged in yet and not recently logout");
}
else
// not expected _player or must checked in packet hanlder
ExecuteOpcode(opHandle, packet);
break;
case STATUS_TRANSFER:
if(!_player)
LogUnexpectedOpcode(packet, "the player has not logged in yet");
else if(_player->IsInWorld())
LogUnexpectedOpcode(packet, "the player is still in world");
else
ExecuteOpcode(opHandle, packet);
break;
case STATUS_AUTHED:
// prevent cheating with skip queue wait
if(m_inQueue)
{
LogUnexpectedOpcode(packet, "the player not pass queue yet");
break;
}
// single from authed time opcodes send in to after logout time
// and before other STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT opcodes.
if (packet->GetOpcode() != CMSG_SET_ACTIVE_VOICE_CHANNEL)
m_playerRecentlyLogout = false;
ExecuteOpcode(opHandle, packet);
break;
case STATUS_NEVER:
sLog.outError( "SESSION: received not allowed opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
break;
case STATUS_UNHANDLED:
DEBUG_LOG("SESSION: received not handled opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
break;
default:
sLog.outError("SESSION: received wrong-status-req opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
break;
}
}
catch (ByteBufferException &)
{
sLog.outError("WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i.",
packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId());
if (sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG))
{
sLog.outDebug("Dumping error causing packet:");
packet->hexlike();
}
if (sWorld.getConfig(CONFIG_BOOL_KICK_PLAYER_ON_BAD_PACKET))
{
DETAIL_LOG("Disconnecting session [account id %u / address %s] for badly formatted packet.",
GetAccountId(), GetRemoteAddress().c_str());
KickPlayer();
}
}
delete packet;
}
///- Cleanup socket pointer if need
if (m_Socket && m_Socket->IsClosed ())
{
m_Socket->RemoveReference ();
m_Socket = NULL;
}
//check if we are safe to proceed with logout
//logout procedure should happen only in World::UpdateSessions() method!!!
if(updater.ProcessLogout())
{
///- If necessary, log the player out
time_t currTime = time(NULL);
if (!m_Socket || (ShouldLogOut(currTime) && !m_playerLoading))
LogoutPlayer(true);
if (!m_Socket)
return false; //Will remove this session from the world session map
}
return true;
}
/// %Log the player out
void WorldSession::LogoutPlayer(bool Save)
{
// finish pending transfers before starting the logout
while(_player && _player->IsBeingTeleportedFar())
HandleMoveWorldportAckOpcode();
m_playerLogout = true;
m_playerSave = Save;
if (_player)
{
sLog.outChar("Account: %d (IP: %s) Logout Character:[%s] (guid: %u)", GetAccountId(), GetRemoteAddress().c_str(), _player->GetName() ,_player->GetGUIDLow());
if (uint64 lguid = GetPlayer()->GetLootGUID())
DoLootRelease(lguid);
///- If the player just died before logging out, make him appear as a ghost
//FIXME: logout must be delayed in case lost connection with client in time of combat
if (_player->GetDeathTimer())
{
_player->getHostileRefManager().deleteReferences();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
else if (!_player->getAttackers().empty())
{
_player->CombatStop();
_player->getHostileRefManager().setOnlineOfflineState(false);
_player->RemoveAllAurasOnDeath();
// build set of player who attack _player or who have pet attacking of _player
std::set<Player*> aset;
for(Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr)
{
Unit* owner = (*itr)->GetOwner(); // including player controlled case
if(owner)
{
if(owner->GetTypeId()==TYPEID_PLAYER)
aset.insert((Player*)owner);
}
else
if((*itr)->GetTypeId()==TYPEID_PLAYER)
aset.insert((Player*)(*itr));
}
_player->SetPvPDeath(!aset.empty());
_player->KillPlayer();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
// give honor to all attackers from set like group case
for(std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
(*itr)->RewardHonor(_player,aset.size());
// give bg rewards and update counters like kill by first from attackers
// this can't be called for all attackers.
if(!aset.empty())
if(BattleGround *bg = _player->GetBattleGround())
bg->HandleKillPlayer(_player,*aset.begin());
}
else if(_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
{
// this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
_player->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
//_player->SetDeathPvP(*); set at SPELL_AURA_SPIRIT_OF_REDEMPTION apply time
_player->KillPlayer();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
//drop a flag if player is carrying it
if(BattleGround *bg = _player->GetBattleGround())
bg->EventPlayerLoggedOut(_player);
///- Teleport to home if the player is in an invalid instance
if(!_player->m_InstanceValid && !_player->isGameMaster())
{
_player->TeleportToHomebind();
//this is a bad place to call for far teleport because we need player to be in world for successful logout
//maybe we should implement delayed far teleport logout?
}
// FG: finish pending transfers after starting the logout
// this should fix players beeing able to logout and login back with full hp at death position
while(_player->IsBeingTeleportedFar())
HandleMoveWorldportAckOpcode();
for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
{
if(BattleGroundQueueTypeId bgQueueTypeId = _player->GetBattleGroundQueueTypeId(i))
{
_player->RemoveBattleGroundQueueId(bgQueueTypeId);
sBattleGroundMgr.m_BattleGroundQueues[ bgQueueTypeId ].RemovePlayer(_player->GetObjectGuid(), true);
}
}
///- Reset the online field in the account table
// no point resetting online in character table here as Player::SaveToDB() will set it to 1 since player has not been removed from world at this stage
// No SQL injection as AccountID is uint32
LoginDatabase.PExecute("UPDATE account SET active_realm_id = 0 WHERE id = '%u'", GetAccountId());
///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
if (Guild *guild = sObjectMgr.GetGuildById(_player->GetGuildId()))
{
if (MemberSlot* slot = guild->GetMemberSlot(_player->GetObjectGuid()))
{
slot->SetMemberStats(_player);
slot->UpdateLogoutTime();
}
guild->BroadcastEvent(GE_SIGNED_OFF, _player->GetGUID(), _player->GetName());
}
///- Remove pet
_player->RemovePet(PET_SAVE_AS_CURRENT);
///- empty buyback items and save the player in the database
// some save parts only correctly work in case player present in map/player_lists (pets, etc)
if(Save)
{
uint32 eslot;
for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; ++j)
{
eslot = j - BUYBACK_SLOT_START;
_player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
}
_player->SaveToDB();
}
///- Leave all channels before player delete...
_player->CleanupChannels();
///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
_player->UninviteFromGroup();
// remove player from the group if he is:
// a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
if(_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
_player->RemoveFromGroup();
///- Send update to group
if(_player->GetGroup())
_player->GetGroup()->SendUpdate();
///- Broadcast a logout message to the player's friends
sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetObjectGuid(), true);
sSocialMgr.RemovePlayerSocial (_player->GetGUIDLow ());
///- Remove the player from the world
// the player may not be in the world when logging out
// e.g if he got disconnected during a transfer to another map
// calls to GetMap in this case may cause crashes
Map* _map = _player->GetMap();
_map->Remove(_player, true);
SetPlayer(NULL); // deleted in Remove call
///- Send the 'logout complete' packet to the client
WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 );
SendPacket( &data );
///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
//No SQL injection as AccountId is uint32
CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'",
GetAccountId());
DEBUG_LOG( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
}
m_playerLogout = false;
m_playerSave = false;
m_playerRecentlyLogout = true;
LogoutRequest(0);
}
/// Kick a player out of the World
void WorldSession::KickPlayer()
{
if (m_Socket)
m_Socket->CloseSocket ();
}
/// Cancel channeling handler
void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
{
va_list ap;
char szStr [1024];
szStr[0] = '\0';
va_start(ap, Text);
vsnprintf( szStr, 1024, Text, ap );
va_end(ap);
uint32 length = strlen(szStr)+1;
WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length);
data << length;
data << szStr;
SendPacket(&data);
}
void WorldSession::SendNotification(const char *format,...)
{
if(format)
{
va_list ap;
char szStr [1024];
szStr[0] = '\0';
va_start(ap, format);
vsnprintf( szStr, 1024, format, ap );
va_end(ap);
WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
data << szStr;
SendPacket(&data);
}
}
void WorldSession::SendNotification(int32 string_id,...)
{
char const* format = GetMangosString(string_id);
if(format)
{
va_list ap;
char szStr [1024];
szStr[0] = '\0';
va_start(ap, string_id);
vsnprintf( szStr, 1024, format, ap );
va_end(ap);
WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
data << szStr;
SendPacket(&data);
}
}
void WorldSession::SendSetPhaseShift(uint32 PhaseShift)
{
WorldPacket data(SMSG_SET_PHASE_SHIFT, 4);
data << uint32(PhaseShift);
SendPacket(&data);
}
const char * WorldSession::GetMangosString( int32 entry ) const
{
return sObjectMgr.GetMangosString(entry,GetSessionDbLocaleIndex());
}
void WorldSession::Handle_NULL( WorldPacket& recvPacket )
{
DEBUG_LOG("SESSION: received unimplemented opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::Handle_EarlyProccess( WorldPacket& recvPacket )
{
sLog.outError( "SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::Handle_ServerSide( WorldPacket& recvPacket )
{
sLog.outError("SESSION: received server-side opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::Handle_Deprecated( WorldPacket& recvPacket )
{
sLog.outError( "SESSION: received deprecated opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::SendAuthWaitQue(uint32 position)
{
if(position == 0)
{
WorldPacket packet( SMSG_AUTH_RESPONSE, 1 );
packet << uint8( AUTH_OK );
SendPacket(&packet);
}
else
{
WorldPacket packet( SMSG_AUTH_RESPONSE, 1+4+1 );
packet << uint8(AUTH_WAIT_QUEUE);
packet << uint32(position);
packet << uint8(0); // unk 3.3.0
SendPacket(&packet);
}
}
void WorldSession::LoadGlobalAccountData()
{
LoadAccountData(
CharacterDatabase.PQuery("SELECT type, time, data FROM account_data WHERE account='%u'", GetAccountId()),
GLOBAL_CACHE_MASK
);
}
void WorldSession::LoadAccountData(QueryResult* result, uint32 mask)
{
for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
if (mask & (1 << i))
m_accountData[i] = AccountData();
if(!result)
return;
do
{
Field *fields = result->Fetch();
uint32 type = fields[0].GetUInt32();
if (type >= NUM_ACCOUNT_DATA_TYPES)
{
sLog.outError("Table `%s` have invalid account data type (%u), ignore.",
mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue;
}
if ((mask & (1 << type))==0)
{
sLog.outError("Table `%s` have non appropriate for table account data type (%u), ignore.",
mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue;
}
m_accountData[type].Time = time_t(fields[1].GetUInt64());
m_accountData[type].Data = fields[2].GetCppString();
} while (result->NextRow());
delete result;
}
void WorldSession::SetAccountData(AccountDataType type, time_t time_, std::string data)
{
if ((1 << type) & GLOBAL_CACHE_MASK)
{
uint32 acc = GetAccountId();
CharacterDatabase.BeginTransaction ();
CharacterDatabase.PExecute("DELETE FROM account_data WHERE account='%u' AND type='%u'", acc, type);
std::string safe_data = data;
CharacterDatabase.escape_string(safe_data);
CharacterDatabase.PExecute("INSERT INTO account_data VALUES ('%u','%u','" UI64FMTD "','%s')", acc, type, uint64(time_), safe_data.c_str());
CharacterDatabase.CommitTransaction ();
}
else
{
// _player can be NULL and packet received after logout but m_GUID still store correct guid
if(!m_GUIDLow)
return;
CharacterDatabase.BeginTransaction ();
CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid='%u' AND type='%u'", m_GUIDLow, type);
std::string safe_data = data;
CharacterDatabase.escape_string(safe_data);
CharacterDatabase.PExecute("INSERT INTO character_account_data VALUES ('%u','%u','" UI64FMTD "','%s')", m_GUIDLow, type, uint64(time_), safe_data.c_str());
CharacterDatabase.CommitTransaction ();
}
m_accountData[type].Time = time_;
m_accountData[type].Data = data;
}
void WorldSession::SendAccountDataTimes(uint32 mask)
{
WorldPacket data( SMSG_ACCOUNT_DATA_TIMES, 4+1+4+8*4 ); // changed in WotLK
data << uint32(time(NULL)); // unix time of something
data << uint8(1);
data << uint32(mask); // type mask
for(uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
if(mask & (1 << i))
data << uint32(GetAccountData(AccountDataType(i))->Time);// also unix time
SendPacket(&data);
}
void WorldSession::LoadTutorialsData()
{
for ( int aX = 0 ; aX < 8 ; ++aX )
m_Tutorials[ aX ] = 0;
QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u'", GetAccountId());
if(!result)
{
m_tutorialState = TUTORIALDATA_NEW;
return;
}
do
{
Field *fields = result->Fetch();
for (int iI = 0; iI < 8; ++iI)
m_Tutorials[iI] = fields[iI].GetUInt32();
}
while( result->NextRow() );
delete result;
m_tutorialState = TUTORIALDATA_UNCHANGED;
}
void WorldSession::SendTutorialsData()
{
WorldPacket data(SMSG_TUTORIAL_FLAGS, 4*8);
for(uint32 i = 0; i < 8; ++i)
data << m_Tutorials[i];
SendPacket(&data);
}
void WorldSession::SaveTutorialsData()
{
switch(m_tutorialState)
{
case TUTORIALDATA_CHANGED:
CharacterDatabase.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u'",
m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7], GetAccountId());
break;
case TUTORIALDATA_NEW:
CharacterDatabase.PExecute("INSERT INTO character_tutorial (account,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
GetAccountId(), m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
break;
case TUTORIALDATA_UNCHANGED:
break;
}
m_tutorialState = TUTORIALDATA_UNCHANGED;
}
void WorldSession::ReadAddonsInfo(WorldPacket &data)
{
if (data.rpos() + 4 > data.size())
return;
uint32 size;
data >> size;
if(!size)
return;
if(size > 0xFFFFF)
{
sLog.outError("WorldSession::ReadAddonsInfo addon info too big, size %u", size);
return;
}
uLongf uSize = size;
uint32 pos = data.rpos();
ByteBuffer addonInfo;
addonInfo.resize(size);
if (uncompress(const_cast<uint8*>(addonInfo.contents()), &uSize, const_cast<uint8*>(data.contents() + pos), data.size() - pos) == Z_OK)
{
uint32 addonsCount;
addonInfo >> addonsCount; // addons count
for(uint32 i = 0; i < addonsCount; ++i)
{
std::string addonName;
uint8 enabled;
uint32 crc, unk1;
// check next addon data format correctness
if(addonInfo.rpos()+1 > addonInfo.size())
return;
addonInfo >> addonName;
addonInfo >> enabled >> crc >> unk1;
DEBUG_LOG("ADDON: Name: %s, Enabled: 0x%x, CRC: 0x%x, Unknown2: 0x%x", addonName.c_str(), enabled, crc, unk1);
m_addonsList.push_back(AddonInfo(addonName, enabled, crc));
}
uint32 unk2;
addonInfo >> unk2;
if(addonInfo.rpos() != addonInfo.size())
DEBUG_LOG("packet under read!");
}
else
sLog.outError("Addon packet uncompress error!");
}
void WorldSession::SendAddonsInfo()
{
unsigned char tdata[256] =
{
0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54,
0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75,
0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34,
0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8,
0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8,
0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A,
0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3,
0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9,
0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22,
0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E,
0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB,
0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7,
0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0,
0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6,
0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A,
0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2
};
WorldPacket data(SMSG_ADDON_INFO, 4);
for(AddonsList::iterator itr = m_addonsList.begin(); itr != m_addonsList.end(); ++itr)
{
uint8 state = 2; // 2 is sent here
data << uint8(state);
uint8 unk1 = 1; // 1 is sent here
data << uint8(unk1);
if (unk1)
{
uint8 unk2 = (itr->CRC != 0x4c1c776d); // If addon is Standard addon CRC
data << uint8(unk2); // if 1, than add addon public signature
if (unk2) // if CRC is wrong, add public key (client need it)
data.append(tdata, sizeof(tdata));
data << uint32(0);
}
uint8 unk3 = 0; // 0 is sent here
data << uint8(unk3); // use <Addon>\<Addon>.url file or not
if (unk3)
{
// String, 256 (null terminated?)
data << uint8(0);
}
}
m_addonsList.clear();
uint32 count = 0;
data << uint32(count); // BannedAddons count
/*for(uint32 i = 0; i < count; ++i)
{
uint32
string (16 bytes)
string (16 bytes)
uint32
uint32
uint32
}*/
SendPacket(&data);
}
void WorldSession::SetPlayer( Player *plr )
{
_player = plr;
// set m_GUID that can be used while player loggined and later until m_playerRecentlyLogout not reset
if(_player)
m_GUIDLow = _player->GetGUIDLow();
}
void WorldSession::SendRedirectClient(std::string& ip, uint16 port)
{
uint32 ip2 = ACE_OS::inet_addr(ip.c_str());
WorldPacket pkt(SMSG_REDIRECT_CLIENT, 4 + 2 + 4 + 20);
pkt << uint32(ip2); // inet_addr(ipstr)
pkt << uint16(port); // port
pkt << uint32(GetLatency()); // latency-related?
HMACSHA1 sha1(20, m_Socket->GetSessionKey().AsByteArray());
sha1.UpdateData((uint8*)&ip2, 4);
sha1.UpdateData((uint8*)&port, 2);
sha1.Finalize();
pkt.append(sha1.GetDigest(), 20); // hmacsha1(ip+port) w/ sessionkey as seed
SendPacket(&pkt);
}
void WorldSession::ExecuteOpcode( OpcodeHandler const& opHandle, WorldPacket* packet )
{
// need prevent do internal far teleports in handlers because some handlers do lot steps
// or call code that can do far teleports in some conditions unexpectedly for generic way work code
if (_player)
_player->SetCanDelayTeleport(true);
(this->*opHandle.handler)(*packet);
if (_player)
{
// can be not set in fact for login opcode, but this not create porblems.
_player->SetCanDelayTeleport(false);
//we should execute delayed teleports only for alive(!) players
//because we don't want player's ghost teleported from graveyard
if (_player->IsHasDelayedTeleport())
_player->TeleportTo(_player->m_teleport_dest, _player->m_teleport_options);
}
if (packet->rpos() < packet->wpos() && sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG))
LogUnprocessedTail(packet);
}
| koksneo/MangosBack | src/game/WorldSession.cpp | C++ | gpl-2.0 | 34,123 |
function ValidarPuntaje(id)
{
var aux = id.split("_");
var name=aux[0];
var fil=parseInt(aux[1]);
var col=parseInt(aux[2]);
var colpuntaje=col;
var colpuntajereal=col+1;
var puntaje=name+"_"+fil+"_"+colpuntaje;
var puntajereal=name+"_"+fil+"_"+colpuntajereal;
var num1=toFloat(puntaje);
var num2=toFloat(puntajereal);
if (num1>num2)
{
alert("El puntaje introducido no puede ser mayor al definido: "+$(puntajereal).value);
$(puntaje).value="0.00";
}
}
function totalizar()
{
var monrec=toFloat('cobdocume_recdoc');
var dscdoc=toFloat('cobdocume_dscdoc');
var abodoc=toFloat('cobdocume_abodoc');
var mondoc=toFloat('cobdocume_mondoc');
var tototal= mondoc+monrec-dscdoc+abodoc;
$('cobdocume_saldoc').value=format(tototal.toFixed(2),'.',',','.');
}
| cidesa/roraima | web/js/licitaciones/liasptecanalisis.js | JavaScript | gpl-2.0 | 835 |
/*
* XMIResultFormatter.java
*
* Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU General Public License.
*
* authors: Andreas Fay, Jannik Strötgen
* email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de
*
* HeidelTime is a multilingual, cross-domain temporal tagger.
* For details, see http://dbs.ifi.uni-heidelberg.de/heideltime
*/
package de.unihd.dbs.heideltime.standalone.components.impl;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.uima.cas.impl.XmiCasSerializer;
import org.apache.uima.jcas.JCas;
import org.apache.uima.util.XMLSerializer;
import de.unihd.dbs.heideltime.standalone.components.ResultFormatter;
/**
* Result formatter based on XMI.
*
* @see {@link org.apache.uima.examples.xmi.XmiWriterCasConsumer}
*
* @author Andreas Fay, University of Heidelberg
* @version 1.0
*/
public class XMIResultFormatter implements ResultFormatter {
@Override
public String format(JCas jcas) throws Exception {
ByteArrayOutputStream outStream = null;
try {
// Write XMI
outStream = new ByteArrayOutputStream();
XmiCasSerializer ser = new XmiCasSerializer(jcas.getTypeSystem());
XMLSerializer xmlSer = new XMLSerializer(outStream, false);
ser.serialize(jcas.getCas(), xmlSer.getContentHandler());
// Convert output stream to string
// String newOut = outStream.toString("UTF-8");
String newOut = outStream.toString();
// System.err.println("NEWOUT:"+newOut);
//
// if (newOut.matches("^<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>.*$")){
// newOut = newOut.replaceFirst("<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>",
// "<\\?xml version=\"1.0\" encoding=\""+Charset.defaultCharset().name()+"\"\\?>");
// }
// if (newOut.matches("^.*?sofaString=\"(.*?)\".*$")){
// for (MatchResult r : findMatches(Pattern.compile("^(.*?sofaString=\")(.*?)(\".*)$"), newOut)){
// String stringBegin = r.group(1);
// String sofaString = r.group(2);
// System.err.println("SOFASTRING:"+sofaString);
// String stringEnd = r.group(3);
// // The sofaString is encoded as UTF-8.
// // However, at this point it has to be translated back into the defaultCharset.
// byte[] defaultDocText = new String(sofaString.getBytes(), "UTF-8").getBytes(Charset.defaultCharset().name());
// String docText = new String(defaultDocText);
// System.err.println("DOCTEXT:"+docText);
// newOut = stringBegin + docText + stringEnd;
//// newOut = newOut.replaceFirst("sofaString=\".*?\"", "sofaString=\"" + docText + "\"");
// }
// }
// System.err.println("NEWOUT:"+newOut);
return newOut;
} finally {
if (outStream != null) {
outStream.close();
}
}
}
/**
* Find all the matches of a pattern in a charSequence and return the
* results as list.
*
* @param pattern
* @param s
* @return
*/
public static Iterable<MatchResult> findMatches(Pattern pattern,
CharSequence s) {
List<MatchResult> results = new ArrayList<MatchResult>();
for (Matcher m = pattern.matcher(s); m.find();)
results.add(m.toMatchResult());
return results;
}
}
| reboutli-crim/heideltime | src/main/java/de/unihd/dbs/heideltime/standalone/components/impl/XMIResultFormatter.java | Java | gpl-3.0 | 3,537 |
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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/>.
*
*/
/**
* Arduino SdFat Library
* Copyright (C) 2009 by William Greiman
*
* This file is part of the Arduino Sd2Card Library
*/
#include "../inc/MarlinConfig.h"
#if ENABLED(SDSUPPORT)
#include "SdFile.h"
/**
* Create a file object and open it in the current working directory.
*
* \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
*
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
*/
SdFile::SdFile(const char* path, uint8_t oflag) : SdBaseFile(path, oflag) { }
/**
* Write data to an open file.
*
* \note Data is moved to the cache but may not be written to the
* storage device until sync() is called.
*
* \param[in] buf Pointer to the location of the data to be written.
*
* \param[in] nbyte Number of bytes to write.
*
* \return For success write() returns the number of bytes written, always
* \a nbyte. If an error occurs, write() returns -1. Possible errors
* include write() is called before a file has been opened, write is called
* for a read-only file, device is full, a corrupt file system or an I/O error.
*
*/
int16_t SdFile::write(const void* buf, uint16_t nbyte) { return SdBaseFile::write(buf, nbyte); }
/**
* Write a byte to a file. Required by the Arduino Print class.
* \param[in] b the byte to be written.
* Use writeError to check for errors.
*/
#if ARDUINO >= 100
size_t SdFile::write(uint8_t b) { return SdBaseFile::write(&b, 1); }
#else
void SdFile::write(uint8_t b) { SdBaseFile::write(&b, 1); }
#endif
/**
* Write a string to a file. Used by the Arduino Print class.
* \param[in] str Pointer to the string.
* Use writeError to check for errors.
*/
void SdFile::write(const char* str) { SdBaseFile::write(str, strlen(str)); }
/**
* Write a PROGMEM string to a file.
* \param[in] str Pointer to the PROGMEM string.
* Use writeError to check for errors.
*/
void SdFile::write_P(PGM_P str) {
for (uint8_t c; (c = pgm_read_byte(str)); str++) write(c);
}
/**
* Write a PROGMEM string followed by CR/LF to a file.
* \param[in] str Pointer to the PROGMEM string.
* Use writeError to check for errors.
*/
void SdFile::writeln_P(PGM_P str) {
write_P(str);
write_P(PSTR("\r\n"));
}
#endif // SDSUPPORT
| MoonshineSG/Marlin | Marlin/src/sd/SdFile.cpp | C++ | gpl-3.0 | 3,173 |
<html><body>Karuda:<br>
You can earn the following rewards:<br>
<font color="LEVEL">S80 weapon recipe</font> - Requires 500 Cursed Grave Goods<br>
<font color="LEVEL">Leonard</font> - Requires 8 Cursed Grave Goods<br>
<font color="LEVEL">Adamantine</font> - Requires 15 Cursed Grave Goods<br>
<font color="LEVEL">Orichalcum</font> - Requires 12 Cursed Grave Goods<br>
Remember, I'm counting on you!
</body></html> | karolusw/l2j | game/data/scripts/quests/Q00645_GhostsOfBatur/32017-06.html | HTML | gpl-3.0 | 413 |
/***********************************************************************
*
* Copyright (C) 2011, 2014 Graeme Gott <graeme@gottcode.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 "clipboard_windows.h"
#include <QMimeData>
//-----------------------------------------------------------------------------
RTF::Clipboard::Clipboard() :
QWinMime()
{
CF_RTF = QWinMime::registerMimeType(QLatin1String("Rich Text Format"));
}
//-----------------------------------------------------------------------------
bool RTF::Clipboard::canConvertFromMime(const FORMATETC& format, const QMimeData* mime_data) const
{
return (format.cfFormat == CF_RTF) && mime_data->hasFormat(QLatin1String("text/rtf"));
}
//-----------------------------------------------------------------------------
bool RTF::Clipboard::canConvertToMime(const QString& mime_type, IDataObject* data_obj) const
{
bool result = false;
if (mime_type == QLatin1String("text/rtf")) {
FORMATETC format = initFormat();
format.tymed |= TYMED_ISTREAM;
result = (data_obj->QueryGetData(&format) == S_OK);
}
return result;
}
//-----------------------------------------------------------------------------
bool RTF::Clipboard::convertFromMime(const FORMATETC& format, const QMimeData* mime_data, STGMEDIUM* storage_medium) const
{
if (canConvertFromMime(format, mime_data)) {
QByteArray data = mime_data->data(QLatin1String("text/rtf"));
HANDLE data_handle = GlobalAlloc(0, data.size());
if (!data_handle) {
return false;
}
void* data_ptr = GlobalLock(data_handle);
memcpy(data_ptr, data.data(), data.size());
GlobalUnlock(data_handle);
storage_medium->tymed = TYMED_HGLOBAL;
storage_medium->hGlobal = data_handle;
storage_medium->pUnkForRelease = NULL;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
QVariant RTF::Clipboard::convertToMime(const QString& mime_type, IDataObject* data_obj, QVariant::Type preferred_type) const
{
Q_UNUSED(preferred_type);
QVariant result;
if (canConvertToMime(mime_type, data_obj)) {
QByteArray data;
FORMATETC format = initFormat();
format.tymed |= TYMED_ISTREAM;
STGMEDIUM storage_medium;
if (data_obj->GetData(&format, &storage_medium) == S_OK) {
if (storage_medium.tymed == TYMED_HGLOBAL) {
char* data_ptr = reinterpret_cast<char*>(GlobalLock(storage_medium.hGlobal));
data = QByteArray::fromRawData(data_ptr, GlobalSize(storage_medium.hGlobal));
data.detach();
GlobalUnlock(storage_medium.hGlobal);
} else if (storage_medium.tymed == TYMED_ISTREAM) {
char buffer[4096];
ULONG amount_read = 0;
LARGE_INTEGER pos = {{0, 0}};
HRESULT stream_result = storage_medium.pstm->Seek(pos, STREAM_SEEK_SET, NULL);
while (SUCCEEDED(stream_result)) {
stream_result = storage_medium.pstm->Read(buffer, sizeof(buffer), &amount_read);
if (SUCCEEDED(stream_result) && (amount_read > 0)) {
data += QByteArray::fromRawData(buffer, amount_read);
}
if (amount_read != sizeof(buffer)) {
break;
}
}
data.detach();
}
ReleaseStgMedium(&storage_medium);
}
if (!data.isEmpty()) {
result = data;
}
}
return result;
}
//-----------------------------------------------------------------------------
QVector<FORMATETC> RTF::Clipboard::formatsForMime(const QString& mime_type, const QMimeData* mime_data) const
{
QVector<FORMATETC> result;
if ((mime_type == QLatin1String("text/rtf")) && mime_data->hasFormat(QLatin1String("text/rtf"))) {
result += initFormat();
}
return result;
}
//-----------------------------------------------------------------------------
QString RTF::Clipboard::mimeForFormat(const FORMATETC& format) const
{
if (format.cfFormat == CF_RTF) {
return QLatin1String("text/rtf");
}
return QString();
}
//-----------------------------------------------------------------------------
FORMATETC RTF::Clipboard::initFormat() const
{
FORMATETC format;
format.cfFormat = CF_RTF;
format.ptd = NULL;
format.dwAspect = DVASPECT_CONTENT;
format.lindex = -1;
format.tymed = TYMED_HGLOBAL;
return format;
}
//-----------------------------------------------------------------------------
| barak/focuswriter | src/fileformats/clipboard_windows.cpp | C++ | gpl-3.0 | 4,898 |
# -*- coding: utf-8 -*-
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**metadata module.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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.
"""
__author__ = 'ismail@kartoza.com'
__revision__ = '$Format:%H$'
__date__ = '10/12/15'
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
'Disaster Reduction')
import json
from types import NoneType
from safe.common.exceptions import MetadataCastError
from safe.metadata.property import BaseProperty
class ListProperty(BaseProperty):
"""A property that accepts list input."""
# if you edit this you need to adapt accordingly xml_value and is_valid
_allowed_python_types = [list, NoneType]
def __init__(self, name, value, xml_path):
super(ListProperty, self).__init__(
name, value, xml_path, self._allowed_python_types)
@classmethod
def is_valid(cls, value):
return True
def cast_from_str(self, value):
try:
return json.loads(value)
except ValueError as e:
raise MetadataCastError(e)
@property
def xml_value(self):
if self.python_type is list:
return json.dumps(self.value)
elif self.python_type is NoneType:
return ''
else:
raise RuntimeError('self._allowed_python_types and self.xml_value'
'are out of sync. This should never happen')
| Gustry/inasafe | safe/metadata/property/list_property.py | Python | gpl-3.0 | 1,695 |
<?php defined('PHALAPI_INSTALL') || die('no access'); ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="http://webtools.qiniudn.com/dog_catch.png">
<title>快速安装 - PhalApi</title>
<link href="./static/css/pintuer.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- <script src="../../assets/js/ie-emulation-modes-warning.js"></script> -->
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<style>
body{
background-color:#333;
color: #fff;
}
.window{
height: auto; margin: 0px auto;margin-top: 50px
}
.window_big{
width: 800px;
}
.window_small{
width: 600px;
}
.window_title{
border-radius: 4px 4px 0px 0px;padding: 20px;
}
.t_normal{
background-color: #FCB244 !important;
}
.t_error{
background-color: #DE4E4E
}
.t_success{
background-color: #7AC997
}
.footer{text-align: center;color: #333;}
</style>
<body>
<div class="container">
| xiaolovecai/PhalApi | Public/install/_header.php | PHP | gpl-3.0 | 1,762 |
/*****************************************************************************
* Copyright (c) 2014-2018 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#pragma once
#include "../scenario/Scenario.h"
#include "Object.h"
class StexObject final : public Object
{
private:
rct_stex_entry _legacyType = {};
public:
explicit StexObject(const rct_object_entry& entry)
: Object(entry)
{
}
void* GetLegacyData() override
{
return &_legacyType;
}
void ReadLegacy(IReadObjectContext* context, IStream* stream) override;
void Load() override;
void Unload() override;
void DrawPreview(rct_drawpixelinfo* dpi, int32_t width, int32_t height) const override;
std::string GetName() const override;
std::string GetScenarioName() const;
std::string GetScenarioDetails() const;
std::string GetParkName() const;
};
| wolfreak99/OpenRCT2 | src/openrct2/object/StexObject.h | C | gpl-3.0 | 1,156 |
/*
* Copyright 2011-2019 Arx Libertatis Team (see the AUTHORS file)
*
* This file is part of Arx Libertatis.
*
* Arx Libertatis 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.
*
* Arx Libertatis 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 Arx Libertatis. If not, see <http://www.gnu.org/licenses/>.
*
* Based on:
*
* blast.c
* Copyright (C) 2003 Mark Adler
* For conditions of distribution and use, see copyright notice in Blast.h
* version 1.1, 16 Feb 2003
*
* blast.c decompresses data compressed by the PKWare Compression Library.
* This function provides functionality similar to the explode() function of
* the PKWare library, hence the name "blast".
*
* This decompressor is based on the excellent format description provided by
* Ben Rudiak-Gould in comp.compression on August 13, 2001. Interestingly, the
* example Ben provided in the post is incorrect. The distance 110001 should
* instead be 111000. When corrected, the example byte stream becomes:
*
* 00 04 82 24 25 8f 80 7f
*
* which decompresses to "AIAIAIAIAIAIA" (without the quotes).
*/
#include "io/Blast.h"
#include <cstring>
#include <cstdlib>
#include <exception>
#include "io/log/Logger.h"
#define MAXBITS 13 /* maximum code length */
#define MAXWIN 4096 /* maximum window size */
namespace {
struct blast_truncated_error : public std::exception { };
} // anonymous namespace
/* input and output state */
struct state {
/* input state */
blast_in infun; /* input function provided by user */
void * inhow; /* opaque information passed to infun() */
const unsigned char * in; /* next input location */
unsigned left; /* available input at in */
int bitbuf; /* bit buffer */
int bitcnt; /* number of bits in bit buffer */
/* output state */
blast_out outfun; /* output function provided by user */
void * outhow; /* opaque information passed to outfun() */
unsigned next; /* index of next write location in out[] */
int first; /* true to check distances (for first 4K) */
unsigned char out[MAXWIN]; /* output buffer and sliding window */
};
/*
* Return need bits from the input stream. This always leaves less than
* eight bits in the buffer. bits() works properly for need == 0.
*
* Format notes:
*
* - Bits are stored in bytes from the least significant bit to the most
* significant bit. Therefore bits are dropped from the bottom of the bit
* buffer, using shift right, and new bytes are appended to the top of the
* bit buffer, using shift left.
*/
static int bits(state * s, int need) {
int val; /* bit accumulator */
/* load at least need bits into val */
val = s->bitbuf;
while(s->bitcnt < need) {
if(s->left == 0) {
s->left = s->infun(s->inhow, &(s->in));
if (s->left == 0) throw blast_truncated_error(); /* out of input */
}
val |= int(*(s->in)++) << s->bitcnt; /* load eight bits */
s->left--;
s->bitcnt += 8;
}
/* drop need bits and update buffer, always zero to seven bits left */
s->bitbuf = val >> need;
s->bitcnt -= need;
/* return need bits, zeroing the bits above that */
return val & ((1 << need) - 1);
}
/*
* Huffman code decoding tables. count[1..MAXBITS] is the number of symbols of
* each length, which for a canonical code are stepped through in order.
* symbol[] are the symbol values in canonical order, where the number of
* entries is the sum of the counts in count[]. The decoding process can be
* seen in the function decode() below.
*/
struct huffman {
short * count; /* number of symbols of each length */
short * symbol; /* canonically ordered symbols */
};
/*
* Decode a code from the stream s using huffman table h. Return the symbol or
* a negative value if there is an error. If all of the lengths are zero, i.e.
* an empty code, or if the code is incomplete and an invalid code is received,
* then -9 is returned after reading MAXBITS bits.
*
* Format notes:
*
* - The codes as stored in the compressed data are bit-reversed relative to
* a simple integer ordering of codes of the same lengths. Hence below the
* bits are pulled from the compressed data one at a time and used to
* build the code value reversed from what is in the stream in order to
* permit simple integer comparisons for decoding.
*
* - The first code for the shortest length is all ones. Subsequent codes of
* the same length are simply integer decrements of the previous code. When
* moving up a length, a one bit is appended to the code. For a complete
* code, the last code of the longest length will be all zeros. To support
* this ordering, the bits pulled during decoding are inverted to apply the
* more "natural" ordering starting with all zeros and incrementing.
*/
static int decode(state * s, huffman * h) {
int len; /* current number of bits in code */
int code; /* len bits being decoded */
int first; /* first code of length len */
int count; /* number of codes of length len */
int index; /* index of first code of length len in symbol table */
int bitbuf; /* bits from stream */
int left; /* bits left in next or left to process */
short * next; /* next number of codes */
bitbuf = s->bitbuf;
left = s->bitcnt;
code = first = index = 0;
len = 1;
next = h->count + 1;
while(true) {
while(left--) {
code |= (bitbuf & 1) ^ 1; /* invert code */
bitbuf >>= 1;
count = *next++;
if(code < first + count) { /* if length len, return symbol */
s->bitbuf = bitbuf;
s->bitcnt = (s->bitcnt - len) & 7;
return h->symbol[index + (code - first)];
}
index += count; /* else update for next length */
first += count;
first <<= 1;
code <<= 1;
len++;
}
left = (MAXBITS + 1) - len;
if(left == 0) break;
if(s->left == 0) {
s->left = s->infun(s->inhow, &(s->in));
if (s->left == 0) throw blast_truncated_error(); /* out of input */
}
bitbuf = *(s->in)++;
s->left--;
if (left > 8) left = 8;
}
return -9; /* ran out of codes */
}
/*
* Given a list of repeated code lengths rep[0..n-1], where each byte is a
* count (high four bits + 1) and a code length (low four bits), generate the
* list of code lengths. This compaction reduces the size of the object code.
* Then given the list of code lengths length[0..n-1] representing a canonical
* Huffman code for n symbols, construct the tables required to decode those
* codes. Those tables are the number of codes of each length, and the symbols
* sorted by length, retaining their original order within each length. The
* return value is zero for a complete code set, negative for an over-
* subscribed code set, and positive for an incomplete code set. The tables
* can be used if the return value is zero or positive, but they cannot be used
* if the return value is negative. If the return value is zero, it is not
* possible for decode() using that table to return an error--any stream of
* enough bits will resolve to a symbol. If the return value is positive, then
* it is possible for decode() using that table to return an error for received
* codes past the end of the incomplete lengths.
*/
static int construct(huffman * h, const unsigned char * rep, int n) {
int symbol; /* current symbol when stepping through length[] */
int len; /* current length when stepping through h->count[] */
int left; /* number of possible codes left of current length */
short offs[MAXBITS + 1]; /* offsets in symbol table for each length */
short length[256]; /* code lengths */
/* convert compact repeat counts into symbol bit length list */
symbol = 0;
do {
len = *rep++;
left = (len >> 4) + 1;
len &= 15;
do {
length[symbol++] = len;
} while(--left);
} while(--n);
n = symbol;
/* count number of codes of each length */
for(len = 0; len <= MAXBITS; len++) {
h->count[len] = 0;
}
for(symbol = 0; symbol < n; symbol++) {
(h->count[length[symbol]])++; /* assumes lengths are within bounds */
}
if(h->count[0] == n) { /* no codes! */
return 0; /* complete, but decode() will fail */
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1; /* one possible code of zero length */
for(len = 1; len <= MAXBITS; len++) {
left <<= 1; /* one more bit, double codes left */
left -= h->count[len]; /* deduct count from possible codes */
if(left < 0) return left; /* over-subscribed--return negative */
} /* left > 0 means incomplete */
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for(len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + h->count[len];
}
/*
* put symbols in table sorted by length, by symbol order within each
* length
*/
for(symbol = 0; symbol < n; symbol++) {
if(length[symbol] != 0) {
h->symbol[offs[length[symbol]]++] = symbol;
}
}
/* return zero for complete set, positive for incomplete set */
return left;
}
/*
* Decode PKWare Compression Library stream.
*
* Format notes:
*
* - First byte is 0 if literals are uncoded or 1 if they are coded. Second
* byte is 4, 5, or 6 for the number of extra bits in the distance code.
* This is the base-2 logarithm of the dictionary size minus six.
*
* - Compressed data is a combination of literals and length/distance pairs
* terminated by an end code. Literals are either Huffman coded or
* uncoded bytes. A length/distance pair is a coded length followed by a
* coded distance to represent a string that occurs earlier in the
* uncompressed data that occurs again at the current location.
*
* - A bit preceding a literal or length/distance pair indicates which comes
* next, 0 for literals, 1 for length/distance.
*
* - If literals are uncoded, then the next eight bits are the literal, in the
* normal bit order in th stream, i.e. no bit-reversal is needed. Similarly,
* no bit reversal is needed for either the length extra bits or the distance
* extra bits.
*
* - Literal bytes are simply written to the output. A length/distance pair is
* an instruction to copy previously uncompressed bytes to the output. The
* copy is from distance bytes back in the output stream, copying for length
* bytes.
*
* - Distances pointing before the beginning of the output data are not
* permitted.
*
* - Overlapped copies, where the length is greater than the distance, are
* allowed and common. For example, a distance of one and a length of 518
* simply copies the last byte 518 times. A distance of four and a length of
* twelve copies the last four bytes three times. A simple forward copy
* ignoring whether the length is greater than the distance or not implements
* this correctly.
*/
static BlastResult blastDecompress(state * s) {
int lit; /* true if literals are coded */
int dict; /* log2(dictionary size) - 6 */
int symbol; /* decoded symbol, extra bits for distance */
int len; /* length for copy */
int dist; /* distance for copy */
int copy; /* copy counter */
unsigned char * from, *to; /* copy pointers */
static int virgin = 1; /* build tables once */
static short litcnt[MAXBITS + 1], litsym[256]; /* litcode memory */
static short lencnt[MAXBITS + 1], lensym[16]; /* lencode memory */
static short distcnt[MAXBITS + 1], distsym[64]; /* distcode memory */
static huffman litcode = {litcnt, litsym}; /* length code */
static huffman lencode = {lencnt, lensym}; /* length code */
static huffman distcode = {distcnt, distsym};/* distance code */
/* bit lengths of literal codes */
static const unsigned char litlen[] = {
11, 124, 8, 7, 28, 7, 188, 13, 76, 4, 10, 8, 12, 10, 12, 10, 8, 23, 8,
9, 7, 6, 7, 8, 7, 6, 55, 8, 23, 24, 12, 11, 7, 9, 11, 12, 6, 7, 22, 5,
7, 24, 6, 11, 9, 6, 7, 22, 7, 11, 38, 7, 9, 8, 25, 11, 8, 11, 9, 12,
8, 12, 5, 38, 5, 38, 5, 11, 7, 5, 6, 21, 6, 10, 53, 8, 7, 24, 10, 27,
44, 253, 253, 253, 252, 252, 252, 13, 12, 45, 12, 45, 12, 61, 12, 45,
44, 173
};
/* bit lengths of length codes 0..15 */
static const unsigned char lenlen[] = {2, 35, 36, 53, 38, 23};
/* bit lengths of distance codes 0..63 */
static const unsigned char distlen[] = {2, 20, 53, 230, 247, 151, 248};
static const short base[16] = { /* base for length codes */
3, 2, 4, 5, 6, 7, 8, 9, 10, 12, 16, 24, 40, 72, 136, 264
};
static const char extra[16] = { /* extra bits for length codes */
0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8
};
/* set up decoding tables (once--might not be thread-safe) */
if(virgin) {
construct(&litcode, litlen, sizeof(litlen));
construct(&lencode, lenlen, sizeof(lenlen));
construct(&distcode, distlen, sizeof(distlen));
virgin = 0;
}
/* read header */
lit = bits(s, 8);
if (lit > 1) return BLAST_INVALID_LITERAL_FLAG;
dict = bits(s, 8);
if (dict < 4 || dict > 6) return BLAST_INVALID_DIC_SIZE;
/* decode literals and length/distance pairs */
do {
if(bits(s, 1)) {
/* get length */
symbol = decode(s, &lencode);
len = base[symbol] + bits(s, extra[symbol]);
if (len == 519) break; /* end code */
/* get distance */
symbol = len == 2 ? 2 : dict;
dist = decode(s, &distcode) << symbol;
dist += bits(s, symbol);
dist++;
if(s->first && dist > int(s->next)) {
return BLAST_INVALID_OFFSET;
}
/* copy length bytes from distance bytes back */
do {
to = s->out + s->next;
from = to - dist;
copy = MAXWIN;
if(int(s->next) < dist) {
from += copy;
copy = dist;
}
copy -= s->next;
if (copy > len) copy = len;
len -= copy;
s->next += copy;
do {
*to++ = *from++;
} while(--copy);
if(s->next == MAXWIN) {
if(s->outfun(s->outhow, s->out, s->next)) return BLAST_OUTPUT_ERROR;
s->next = 0;
s->first = 0;
}
} while(len != 0);
} else {
/* get literal and write it */
symbol = lit ? decode(s, &litcode) : bits(s, 8);
s->out[s->next++] = symbol;
if(s->next == MAXWIN) {
if(s->outfun(s->outhow, s->out, s->next)) return BLAST_OUTPUT_ERROR;
s->next = 0;
s->first = 0;
}
}
} while(true);
return BLAST_SUCCESS;
}
BlastResult blast(blast_in infun, void * inhow, blast_out outfun, void * outhow) {
state s;
// initialize input state
s.infun = infun;
s.inhow = inhow;
s.left = 0;
s.bitbuf = 0;
s.bitcnt = 0;
// initialize output state
s.outfun = outfun;
s.outhow = outhow;
s.next = 0;
s.first = 1;
BlastResult err;
try {
err = blastDecompress(&s);
} catch(const blast_truncated_error &) {
err = BLAST_TRUNCATED_INPUT;
}
// write any leftover output and update the error code if needed
if(err != 1 && s.next && s.outfun(s.outhow, s.out, s.next) && err == 0) {
err = BLAST_OUTPUT_ERROR;
}
return err;
}
// Additional functions.
size_t blastInMem(void * param, const unsigned char ** buf) {
BlastMemInBuffer * p = static_cast<BlastMemInBuffer *>(param);
*buf = reinterpret_cast<const unsigned char *>(p->buf);
size_t size = p->size;
p->buf += size;
p->size = 0;
return size;
}
int blastOutString(void * param, unsigned char * buf, size_t len) {
BlastMemOutString * p = static_cast<BlastMemOutString *>(param);
p->buffer.append(reinterpret_cast<const char *>(buf), len);
return 0;
}
std::string blast(const char * from, size_t fromSize, size_t toSizeHint) {
std::string uncompressed;
uncompressed.reserve(toSizeHint == size_t(-1) ? fromSize : toSizeHint);
BlastMemInBuffer in(from, fromSize);
BlastMemOutString out(uncompressed);
BlastResult error = blast(blastInMem, &in, blastOutString, &out);
if(error) {
LogError << "blast error " << int(error) << " for " << fromSize;
uncompressed.clear();
}
return uncompressed;
}
| Thoronador/ArxLibertatis | src/io/Blast.cpp | C++ | gpl-3.0 | 16,642 |
IMAGES="test-r test-python"
IMAGE_VERSION="0.1"
DOCKER_REGISTRY="localhost:5000"
for IMAGE in ${IMAGES} ; do
docker build --tag ${DOCKER_REGISTRY}/dpa/${IMAGE}:${IMAGE_VERSION} tasks/${IMAGE}
docker push ${DOCKER_REGISTRY}/dpa/${IMAGE}:${IMAGE_VERSION}
done
| nanounanue/rita-pipeline | rita/registrar.sh | Shell | gpl-3.0 | 267 |
from django.conf.urls.defaults import *
"""
Also used in cms.tests.ApphooksTestCase
"""
urlpatterns = patterns('cms.test_utils.project.sampleapp.views',
url(r'^$', 'sample_view', {'message': 'sample root page',}, name='sample-root'),
url(r'^settings/$', 'sample_view', kwargs={'message': 'sample settings page'}, name='sample-settings'),
url(r'^account/$', 'sample_view', {'message': 'sample account page'}, name='sample-account'),
url(r'^account/my_profile/$', 'sample_view', {'message': 'sample my profile page'}, name='sample-profile'),
url(r'^(?P<id>[0-9]+)/$', 'category_view', name='category_view'),
url(r'^notfound/$', 'notfound', name='notfound'),
url(r'^extra_1/$', 'extra_view', {'message': 'test urlconf'}, name='extra_first'),
url(r'^', include('cms.test_utils.project.sampleapp.urls_extra')),
)
| hzlf/openbroadcast | website/cms/test_utils/project/sampleapp/urls.py | Python | gpl-3.0 | 842 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.