code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php /** * The main template file. * * This is the most generic template file in a WordPress theme * and one of the two required files for a theme (the other being style.css). * It is used to display a page when nothing more specific matches a query. * E.g., it puts together the home page when no home.php file exists. * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package Colouralia * @subpackage Emily Armstrong */ global $hello; $hello = get_post(27); setup_postdata($hello); //echo var_export($hello); ?> <div id="hello"> <div class="infinite"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="title"> <h2><?php echo $hello->post_title; ?></h2> <div class="content"> <?php echo the_content(); ?> </div> </div> </div> </div> </div> </div> </div>
marcosposada/emily
wp-content/themes/emily/hello-section.php
PHP
gpl-2.0
868
?php /** * @version * @package MosPrayer - COAddOns for Mambo & Jommla - Prayers on Articles based on COMBO by Phil Taylor * @copyright (C) 2008 ongetc.com * @info ongetc@ongetc.com http://ongetc.com * @license GNU/GPL http://ongetc.com/gpl.html. */ // translated by Fuga http://dndon.net defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); //admin.mosprayer.html.php define('_PRY_A_KEEPUPTODATE','ÅÐÇ ÃÑÏÊ ÇáÅÔÊÑÇß Ýí ÞÇÆãÉ ÇáÊÍÏíËÇÊ ÅÖÛØ Úáì ÇáÒÑ'); define('_PRY_A_SUBSCRIBE','ÅÔÊÑÇß'); define('_PRY_A_UNSUBSCRIBE','ÅäÓÍÇÈ'); define('_PRY_A_BACKUP','äÓÎÉ ÅÍÊíÇØíÉ'); define('_PRY_A_BACKUP_DESC','Úãá äÓÎÉ ÇÍÊíÇØíÉ ãä #__content_mosprayer_requests'); define('_PRY_A_RESTORE','ÅÓÊÚÇÏÉ'); define('_PRY_A_RESTORE_DESC','ÅÓÊÚÇÏÉ ÇáäÓÎÉ ÇáÅÍÊíÇØíÉ ãä #__content_mosprayer_requests'); define('_PRY_A_CONFIG','ÇáÊÚÏíáÇÊ'); define('_PRY_A_CONFIG_DESC','ÍÝÙ ÇáÊÚÏíáÇÊ'); define('_PRY_A_INSTRUCTIONS','ÇáÊÚáíãÇÊ'); define('_PRY_A_INSTRUCTIONS_DESC','ØÑíÞÉ ÊäÕíÈ ÇáÈÑäÇãÌ'); define('_PRY_A_ABOUT','Úä ÇáÈÑäÇãÌ'); define('_PRY_A_ABOUT_DESC','Úä åÐÇ ÇáÈÑäÇãÌ'); define('_PRY_A_LINK','ÑÇÈØ'); define('_PRY_A_LINK_DESC','áãäÊÌ ÇáÈÑäÇãÌ'); define('_PRY_A_CHECK','ÇáÊÃßÏ ãä æÌæÏ ÊÍÏíËÇÊ'); define('_PRY_A_VERSION','ÅÕÏÇÑß åæ '); define('_PRY_A_DONATE','íÑÌì ÇáÖÛØ Úáì ÃÚáÇä ÇáíÇåæ Ãæ Úáì ÇáÃÞá Þã ÈÏÚã ÇáÈÑäÇãÌ ÈÊÈÑÚ ÈÓíØ'); define('_PRY_A_REVIEW','ÚÑÖ ÇáÊÚáíÞÇÊ ( ÇáÃÍÏË ÃæáÇ )'); define('_PRY_A_DISPLAY','ÚÑÖ #'); define('_PRY_A_NAME_SUB','ÇáÅÓã'); define('_PRY_A_EMAIL_SUB','ÇáÈÑíÏ'); define('_PRY_A_HOMEPAGE','ÇáãæÞÚ'); define('_PRY_A_PRAYER','ÇáÊÚáíÞ'); define('_PRY_A_ARTICLE','ÇáãÞÇáÉ'); define('_PRY_A_PUBLISHED','ãäÔæÑ'); define('_PRY_A_MOS_BY','ÈÑäÇãÌ ÇáÊÚáíÞÇÊ ÈæÇÓØÉ'); define('_PRY_A_CURRENT_SETTINGS','ÇáÎÕÇÆÕ ÇáÍÇáíÉ'); define('_PRY_A_EXPLANATION','ÇáÔÑÍ'); define('_PRY_A_ADMIN_EMAIL','ÈÑíÏ ÇáãÏíÑ'); define('_PRY_A_ADMIN_EMAIL_DESC','ÈÑíÏ ÇáãÏíÑ ÇáÐí ÊÕá Çáíå ÇáÊÚáíÞÇÊ Úáì ÇáÈÑíÏ'); define('_PRY_A_ADMIN_ALERTS','ÅÈáÇÛ ÈÑíÏí'); define('_PRY_A_ADMIN_EMAIL_ENABLE','åá ÊÑíÏ ÊÈáíÛ ÈÑíÏí ÚäÏ ßá ÊÚáíÞ'); define('_PRY_A_VISITOR_EMAIL','ÈÑíÏ ááÒÇÆÑ'); define('_PRY_A_VISITOR_EMAIL_DESC','åá ÊÑíÏ ÅÑÓÇá ÈÑíÏ áßá ÒÇÆÑ Ãæ ÚÖæ ÞÇã ÈÅÖÇÝÉ ÊÚáíÞ'); define('_PRY_A_REVIEW_SUBM','ÊÝÞÏ ÞÈá ÇáäÔÑ'); define('_PRY_A_REVIEW_DESC','ÅÐÇ ÅÎÊÑÊ äÚã ÝÐáß íÚäí Ãä ÇáÊÚáíÞ íÖÇÝ Ýí ÞÇÚÏÉ ÇáÈíÇäÇÊ æáÇ íäÔÑ ÇáÇ ÈÚÏ ÊÕÑíÍß áå ÈÇáäÔÑ .íãßäß ÊÍÏíÏ ÎíÇÑ ÅÈáÇÛ ÈÑíÏí ááãÏíÑ ÃÚáÇå æÐáß áÅÎÈÇÑß Èßá ÇáÊÚÇáíÞ ÇáÊí ÊäÊÙÑ ÇáäÔÑ'); define('_PRY_A_REGISTERED_ONLY','ÝÞØ ÇáÃÚÖÇÁ'); define('_PRY_A_REG_ONLY_DESC','ÅÎÊÑ äÚã áÅÊÇÍÉ ÇáÊÚáíÞÇÊ ááÃÚÖÇÁ ÝÞØ .. áÇ ÊÎÝ ÓíÊã ÚÑÖ ÇáÊÚáíÞÇÊ ááÚÇãÉ æáßä áÇ íãßäåã ÇáÊÚáíÞ ÇáÇ ÇÐÇ ßÇä áÏíåã ÚÖæíÉ Ýí ÇáãÌáÉ'); define('_PRY_A_NOTIFY_VERSION','ÊÈáíÛ ÚäÏ æÌæÏ äÓÎÉ ÌÏíÏÉ'); define('_PRY_A_NOT_VER_DESC','ÅÎÊÑ äÚã ÅÐÇ ÃÑÏÊ Ãä ÊÕáß ÇáÊÍÏíËÇÊ ÚäÏ æÌæÏ äÓÎÉ ÌÏíÏÉ ãä ÇáÈÑäÇãÌ'); define('_PRY_A_HAVE_DONATED','åá ÞãÊ ÈÇáÊÈÑÚ ¿'); define('_PRY_A_DONATE2','ÅÐÇ ÅÎÊÑÊ äÚã Ýáä íÙåÑ ãÑÈÚ ÇáÊÈÑÚ ÊÍÊ ÇáÊÚáíÞÇÊ .. ÇÐÇ ÅÎÊÑÊ áÇ ÝÓíÙåÑ ãÑÈÚ ÇáÊÈÑÚ ÃÓÝá ÇáÊÚáíÞÇÊ'); define('_PRY_A_IMPORTANT_NOTE','ãÚáæãÇÊ ãåãÉ'); define('_PRY_A_TEMPLATE','íÌÈ Úáíß ÊÍÑíÑ ÃãÑ Ýí ÇáÞÇáÈ æÐáß áÊÝÚíá ÇáÊÚáíÞÇÊ Ýí ãÌáÊß<br><a href="index2.php?option=templates&task=edit">ÅäÊÞá Çáì ÇáÞæÇáÈ</a>'); define('_PRY_A_CHANGE_TO','ÅÓÊÈÏá ÇáßæÏ ÇáÊÇáí'); define('_PRY_A_HAVE_FUN','Thats it! ~ (I will not be answering emails along the line of &quot;<em>I&quot;ve installed your component but the form doesn&quot;t show.....</em>&quot; :-)</p> <p> Have Fun!</p> <p>~<a href="http://ongetc.com" target="_blank">Chanh Ong</a>. </p>'); define('_PRY_A_FORCE_PREVIEW','ãÔÇåÏÉ Ãæ ÈÑæÝÉ'); define('_PRY_A_FORCE_PREVIEW_TEXT','ÅÎÊÑ äÚã ÇÐÇ ÃÑÏÊ ÚÑÖ ÈÑæÝÉ ãä ÇáÊÚáíÞ ÞÈá ÇáÅÖÇÝÉ áãÖíÝ ÇáÊÚáíÞ'); define('_PRY_A_HIDE','ÅÎÝÇÁ ÇáÍÞæá'); define('_PRY_A_HIDE_DESC','ÚÑÖ ÑæÇÈØ áÅÖÇÝÉ ÇáÊÚáíÞ æ ãÔÇÏÉ ÇáÊÚáíÞÇÊ ÈÏáÇ ãä ÚÑÖ ÇáÝæÑã ÊÍÊ ÇáãÞÇáÉ'); define('_PRY_A_DATE','ÇáÊÇÑíÎ'); define('_PRY_A_HIDE_URL','ÅÎÝÇÁ ÇáÑÇÈØ'); define('_PRY_A_HIDE_URL_DESC','åá ÊæÏ ÅÎÝÇÁ ÍÞá ÚäæÇä ãæÞÚ ãÖíÝ ÇáÊÚáíÞ'); define('_PRY_A_EMAIL_REQ','Email Required'); define('_PRY_A_EMAIL_REQ_DESC','Use to set either email is required or not on the prayers form by default'); define('_PRY_A_EXCL_SEC','Exclude Section'); define('_PRY_A_EXCL_SEC_DESC','Use to exclude section not to show prayers form by default, eg: 0,1'); define('_PRY_A_PER_PAGE','Prayers per page'); define('_PRY_A_PER_PAGE_DESC','Use to show number of prayers per page, eg: 3'); define('_PRY_A_NEW_1ST','New Prayers First'); define('_PRY_A_NEW_1ST_DESC','List new prayer entries first'); define('_PRY_A_FORM_ABOVE','Comment Form Above'); define('_PRY_A_FORM_ABOVE_DESC','Show prayer form above prayer entries'); define('_PRY_A_USE_DIVCSS','Use DIV CSS'); define('_PRY_A_USE_DIVCSS_DESC','Show prayer form using DIV CSS from template'); define('_PRY_A_EXCL_CONT','Exclude Contents'); define('_PRY_A_EXCL_CONT_DESC','Use to exclude contents via article id not to show prayers form, eg: 0,1'); define('_PRY_A_IP','IP'); define('_PRY_A_USE_USERNAME','Use username'); define('_PRY_A_USE_USERNAME_DESC','Show username instead of name'); define('_PRY_A_CLOSE_CONT','Close Contents'); define('_PRY_A_CLOSE_CONT_DESC','Use to close contents via article id not to show prayers form, eg: 0,1'); define('_PRY_A_USE_SECTOKEN','Use security token'); define('_PRY_A_USE_SECTOKEN_DESC','Check for security token when submit prayer (invisible Captcha)'); //mosprayer.php define('_PRY_A_NO',"áÇ"); define('_PRY_A_YES',"äÚã"); define('_PRY_R_COM_NUMBER',"ÚÏÏ ÇáÊÚáíÞÇÊ"); define('_PRY_R_NO_COM',"áÇ íæÌÏ Ãí ÊÚáíÞ Çáì ÇáÂä .. íãßäß ÇáÈÏà ÈÅÖÇÝÉ Ãæá ÊÚáíÞ"); define('_PRY_R_POST',"ÈæÇÓØÉ"); define('_PRY_R_HOMEPAGE',"ÕÍÇÈ ãæÞÚ"); define('_PRY_R_DATE_ON',"Ýí"); define('_PRY_R_DATE_AT',"Ýí"); define('_PRY_R_ADD_PRAYER',"ÃÖÝ ÊÚáíÞß ááãÞÇáÉ Ãæ ÇáÏÑÓ"); define('_PRY_R_ADD_COM2'," ..."); define('_PRY_R_NAME',"ÇáÅÓã"); define('_PRY_R_EMAIL',"ÇáÈÑíÏ"); define('_PRY_R_EMAIL_NOT',"ÓÊÊã ÍãÇíÉ ÈÑíÏß ãä ÇáÚÑÖ Ýí ÇáãæÞÚ"); define('_PRY_R_HOMEPAGE_IN',"ÇáãæÞÚ"); define('_PRY_R_COM',"ÇáÊÚáíÞ"); define('_PRY_R_FULLY',"íÑÌì ãáà ÇáÍÞæá !"); define('_PRY_R_NEW_COM',"ÊÚáíÞ ÌÏíÏ Ýí"); define('_PRY_R_HAVE_NEW',"áÏíß ÊÚáíÞ Úáì ÇáãÞÇáÉ ÇáÊÇáíÉ :"); define('_PRY_R_LOGIN',"íÑÌì ÇáÏÎæá ááæÍÉ ÇáÊÍßã áäÔÑ ÇáãÞÇáÉ Ãæ ÍÐÝåÇ"); define('_PRY_R_QUICKLINK',"åÐÇ ÑÇÈØ ÓÑíÚ áÏÎæá áæÍÉ ÇáÊÍßã"); define('_PRY_R_THANKS',"ÔßÑÇ áÊÚáíÞß"); define('_PRY_R_THANKS2',"ÔßÑÇ áÊÚáíÞß Úáì ÇáÏÑÓ Ãæ ÇáãÞÇáÉ ÇáÊÇáíÉ"); define('_PRY_R_ADMIN_REV',"ÓíÞæã ÇáãÏíÑ ÈÊÝÞÏ ÇáÊÚáíÞ ÞÈá äÔÑå"); define('_PRY_R_ENTERED',"ÃäÊ ÃÏÎáÊ"); define('_PRY_R_VISIT',"íÑÌì ÒíÇÑÉ ÇáãæÞÚ ÞÑíÈÇ"); define('_PRY_R_THANKS3',"ÔßÑÇ áÅÖÇÝÊß ÇáÊÚáíÞ"); define('_PRY_R_THANKS4',"ÔßÑÇ áß Úáì ÇáÊÚáíÞ ... ÓÊÊã ãÔÇåÏÉ ÇáÊÚáíÞ ÞÈá äÔÑå ãä ÞÈá ÇáãÏíÑ"); define('_PRY_R_SUBMIT',"ÃÖÝ"); define('_PRY_R_RESET',"ãÓÍ"); define('_PRY_R_NOT_AUTH',"áÇ íãßäß ÅÖÇÝÉ ÊÚáíÞ íÑÌì ÊÓÌíá ÏÎæá"); define('_PRY_R_PREV_PAGE',"Prev Page"); define('_PRY_R_NEXT_PAGE',"Next Page"); define('_PRY_R_PAGE',"Page"); define('_PRY_R_REQUEST',"User Prayers"); define('_PRY_R_OF',"of"); define('_PRY_R_CANCEL',"Cancel"); define('_PRY_R_FORM_INTRO',"Enter your prayer below."); define('_PRY_R_PREVIEW_HEAD',"Please check your entry..."); define('_PRY_R_PREVIEW_INTRO',"Is the below correct? <p />Please make any necessary changes before submitting. Warning: Cancelling will erase your prayer!"); define('_PRY_R_REQ',"<small><i> (ãØáæÈ)</i></small>"); define('_PRY_R_OPT',"<small><i>(optional)</i></small>"); define('_PRY_R_HOMEURL',"here"); define('_PRY_R_CHECKLINK',"CHECK LINK"); define('_PRY_R_QUICKPOST',"Quick Post"); ?>
chanhong/mosprayer
language/arabic.php
PHP
gpl-2.0
7,522
/****************************************************************************** * cxacru.c - driver for USB ADSL modems based on * Conexant AccessRunner chipset * * Copyright (C) 2004 David Woodhouse, Duncan Sands, Roman Kagan * Copyright (C) 2005 Duncan Sands, Roman Kagan (rkagan % mail ! ru) * Copyright (C) 2007 Simon Arlott * Copyright (C) 2009 Simon Arlott * * 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. * ******************************************************************************/ /* * Credit is due for Josep Comas, who created the original patch to speedtch.c * to support the different padding used by the AccessRunner (now generalized * into usbatm), and the userspace firmware loading utility. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/device.h> #include <linux/firmware.h> #include <linux/mutex.h> #include <asm/unaligned.h> #include "usbatm.h" #define DRIVER_AUTHOR "Roman Kagan, David Woodhouse, Duncan Sands, Simon Arlott" #define DRIVER_VERSION "0.4" #define DRIVER_DESC "Conexant AccessRunner ADSL USB modem driver" static const char cxacru_driver_name[] = "cxacru"; #define CXACRU_EP_CMD 0x01 /* Bulk/interrupt in/out */ #define CXACRU_EP_DATA 0x02 /* Bulk in/out */ #define CMD_PACKET_SIZE 64 /* Should be maxpacket(ep)? */ #define CMD_MAX_CONFIG ((CMD_PACKET_SIZE / 4 - 1) / 2) /* Addresses */ #define PLLFCLK_ADDR 0x00350068 #define PLLBCLK_ADDR 0x0035006c #define SDRAMEN_ADDR 0x00350010 #define FW_ADDR 0x00801000 #define BR_ADDR 0x00180600 #define SIG_ADDR 0x00180500 #define BR_STACK_ADDR 0x00187f10 /* Values */ #define SDRAM_ENA 0x1 #define CMD_TIMEOUT 2000 /* msecs */ #define POLL_INTERVAL 1 /* secs */ /* commands for interaction with the modem through the control channel before * firmware is loaded */ enum cxacru_fw_request { FW_CMD_ERR, FW_GET_VER, FW_READ_MEM, FW_WRITE_MEM, FW_RMW_MEM, FW_CHECKSUM_MEM, FW_GOTO_MEM, }; /* commands for interaction with the modem through the control channel once * firmware is loaded */ enum cxacru_cm_request { CM_REQUEST_UNDEFINED = 0x80, CM_REQUEST_TEST, CM_REQUEST_CHIP_GET_MAC_ADDRESS, CM_REQUEST_CHIP_GET_DP_VERSIONS, CM_REQUEST_CHIP_ADSL_LINE_START, CM_REQUEST_CHIP_ADSL_LINE_STOP, CM_REQUEST_CHIP_ADSL_LINE_GET_STATUS, CM_REQUEST_CHIP_ADSL_LINE_GET_SPEED, CM_REQUEST_CARD_INFO_GET, CM_REQUEST_CARD_DATA_GET, CM_REQUEST_CARD_DATA_SET, CM_REQUEST_COMMAND_HW_IO, CM_REQUEST_INTERFACE_HW_IO, CM_REQUEST_CARD_SERIAL_DATA_PATH_GET, CM_REQUEST_CARD_SERIAL_DATA_PATH_SET, CM_REQUEST_CARD_CONTROLLER_VERSION_GET, CM_REQUEST_CARD_GET_STATUS, CM_REQUEST_CARD_GET_MAC_ADDRESS, CM_REQUEST_CARD_GET_DATA_LINK_STATUS, CM_REQUEST_MAX, }; /* commands for interaction with the flash memory * * read: response is the contents of the first 60 bytes of flash memory * write: request contains the 60 bytes of data to write to flash memory * response is the contents of the first 60 bytes of flash memory * * layout: PP PP VV VV MM MM MM MM MM MM ?? ?? SS SS SS SS SS SS SS SS * SS SS SS SS SS SS SS SS 00 00 00 00 00 00 00 00 00 00 00 00 * 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 * * P: le16 USB Product ID * V: le16 USB Vendor ID * M: be48 MAC Address * S: le16 ASCII Serial Number */ enum cxacru_cm_flash { CM_FLASH_READ = 0xa1, CM_FLASH_WRITE = 0xa2 }; /* reply codes to the commands above */ enum cxacru_cm_status { CM_STATUS_UNDEFINED, CM_STATUS_SUCCESS, CM_STATUS_ERROR, CM_STATUS_UNSUPPORTED, CM_STATUS_UNIMPLEMENTED, CM_STATUS_PARAMETER_ERROR, CM_STATUS_DBG_LOOPBACK, CM_STATUS_MAX, }; /* indices into CARD_INFO_GET return array */ enum cxacru_info_idx { CXINF_DOWNSTREAM_RATE, CXINF_UPSTREAM_RATE, CXINF_LINK_STATUS, CXINF_LINE_STATUS, CXINF_MAC_ADDRESS_HIGH, CXINF_MAC_ADDRESS_LOW, CXINF_UPSTREAM_SNR_MARGIN, CXINF_DOWNSTREAM_SNR_MARGIN, CXINF_UPSTREAM_ATTENUATION, CXINF_DOWNSTREAM_ATTENUATION, CXINF_TRANSMITTER_POWER, CXINF_UPSTREAM_BITS_PER_FRAME, CXINF_DOWNSTREAM_BITS_PER_FRAME, CXINF_STARTUP_ATTEMPTS, CXINF_UPSTREAM_CRC_ERRORS, CXINF_DOWNSTREAM_CRC_ERRORS, CXINF_UPSTREAM_FEC_ERRORS, CXINF_DOWNSTREAM_FEC_ERRORS, CXINF_UPSTREAM_HEC_ERRORS, CXINF_DOWNSTREAM_HEC_ERRORS, CXINF_LINE_STARTABLE, CXINF_MODULATION, CXINF_ADSL_HEADEND, CXINF_ADSL_HEADEND_ENVIRONMENT, CXINF_CONTROLLER_VERSION, /* dunno what the missing two mean */ CXINF_MAX = 0x1c, }; enum cxacru_poll_state { CXPOLL_STOPPING, CXPOLL_STOPPED, CXPOLL_POLLING, CXPOLL_SHUTDOWN }; struct cxacru_modem_type { u32 pll_f_clk; u32 pll_b_clk; int boot_rom_patch; }; struct cxacru_data { struct usbatm_data *usbatm; const struct cxacru_modem_type *modem_type; int line_status; struct mutex adsl_state_serialize; int adsl_status; struct delayed_work poll_work; u32 card_info[CXINF_MAX]; struct mutex poll_state_serialize; enum cxacru_poll_state poll_state; /* contol handles */ struct mutex cm_serialize; u8 *rcv_buf; u8 *snd_buf; struct urb *rcv_urb; struct urb *snd_urb; struct completion rcv_done; struct completion snd_done; }; static int cxacru_cm(struct cxacru_data *instance, enum cxacru_cm_request cm, u8 *wdata, int wsize, u8 *rdata, int rsize); static void cxacru_poll_status(struct work_struct *work); /* Card info exported through sysfs */ #define CXACRU__ATTR_INIT(_name) \ static DEVICE_ATTR(_name, S_IRUGO, cxacru_sysfs_show_##_name, NULL) #define CXACRU_CMD_INIT(_name) \ static DEVICE_ATTR(_name, S_IWUSR | S_IRUGO, \ cxacru_sysfs_show_##_name, cxacru_sysfs_store_##_name) #define CXACRU_SET_INIT(_name) \ static DEVICE_ATTR(_name, S_IWUSR, \ NULL, cxacru_sysfs_store_##_name) #define CXACRU_ATTR_INIT(_value, _type, _name) \ static ssize_t cxacru_sysfs_show_##_name(struct device *dev, \ struct device_attribute *attr, char *buf) \ { \ struct cxacru_data *instance = to_usbatm_driver_data(\ to_usb_interface(dev)); \ \ if (instance == NULL) \ return -ENODEV; \ \ return cxacru_sysfs_showattr_##_type(instance->card_info[_value], buf); \ } \ CXACRU__ATTR_INIT(_name) #define CXACRU_ATTR_CREATE(_v, _t, _name) CXACRU_DEVICE_CREATE_FILE(_name) #define CXACRU_CMD_CREATE(_name) CXACRU_DEVICE_CREATE_FILE(_name) #define CXACRU_SET_CREATE(_name) CXACRU_DEVICE_CREATE_FILE(_name) #define CXACRU__ATTR_CREATE(_name) CXACRU_DEVICE_CREATE_FILE(_name) #define CXACRU_ATTR_REMOVE(_v, _t, _name) CXACRU_DEVICE_REMOVE_FILE(_name) #define CXACRU_CMD_REMOVE(_name) CXACRU_DEVICE_REMOVE_FILE(_name) #define CXACRU_SET_REMOVE(_name) CXACRU_DEVICE_REMOVE_FILE(_name) #define CXACRU__ATTR_REMOVE(_name) CXACRU_DEVICE_REMOVE_FILE(_name) static ssize_t cxacru_sysfs_showattr_u32(u32 value, char *buf) { return snprintf(buf, PAGE_SIZE, "%u\n", value); } static ssize_t cxacru_sysfs_showattr_s8(s8 value, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", value); } static ssize_t cxacru_sysfs_showattr_dB(s16 value, char *buf) { if (likely(value >= 0)) { return snprintf(buf, PAGE_SIZE, "%u.%02u\n", value / 100, value % 100); } else { value = -value; return snprintf(buf, PAGE_SIZE, "-%u.%02u\n", value / 100, value % 100); } } static ssize_t cxacru_sysfs_showattr_bool(u32 value, char *buf) { static char *str[] = { "no", "yes" }; if (unlikely(value >= ARRAY_SIZE(str))) return snprintf(buf, PAGE_SIZE, "%u\n", value); return snprintf(buf, PAGE_SIZE, "%s\n", str[value]); } static ssize_t cxacru_sysfs_showattr_LINK(u32 value, char *buf) { static char *str[] = { NULL, "not connected", "connected", "lost" }; if (unlikely(value >= ARRAY_SIZE(str) || str[value] == NULL)) return snprintf(buf, PAGE_SIZE, "%u\n", value); return snprintf(buf, PAGE_SIZE, "%s\n", str[value]); } static ssize_t cxacru_sysfs_showattr_LINE(u32 value, char *buf) { static char *str[] = { "down", "attempting to activate", "training", "channel analysis", "exchange", "up", "waiting", "initialising" }; if (unlikely(value >= ARRAY_SIZE(str))) return snprintf(buf, PAGE_SIZE, "%u\n", value); return snprintf(buf, PAGE_SIZE, "%s\n", str[value]); } static ssize_t cxacru_sysfs_showattr_MODU(u32 value, char *buf) { static char *str[] = { "", "ANSI T1.413", "ITU-T G.992.1 (G.DMT)", "ITU-T G.992.2 (G.LITE)" }; if (unlikely(value >= ARRAY_SIZE(str))) return snprintf(buf, PAGE_SIZE, "%u\n", value); return snprintf(buf, PAGE_SIZE, "%s\n", str[value]); } /* * This could use MAC_ADDRESS_HIGH and MAC_ADDRESS_LOW, but since * this data is already in atm_dev there's no point. * * MAC_ADDRESS_HIGH = 0x????5544 * MAC_ADDRESS_LOW = 0x33221100 * Where 00-55 are bytes 0-5 of the MAC. */ static ssize_t cxacru_sysfs_show_mac_address(struct device *dev, struct device_attribute *attr, char *buf) { struct cxacru_data *instance = to_usbatm_driver_data( to_usb_interface(dev)); if (instance == NULL || instance->usbatm->atm_dev == NULL) return -ENODEV; return snprintf(buf, PAGE_SIZE, "%pM\n", instance->usbatm->atm_dev->esi); } static ssize_t cxacru_sysfs_show_adsl_state(struct device *dev, struct device_attribute *attr, char *buf) { static char *str[] = { "running", "stopped" }; struct cxacru_data *instance = to_usbatm_driver_data( to_usb_interface(dev)); u32 value; if (instance == NULL) return -ENODEV; value = instance->card_info[CXINF_LINE_STARTABLE]; if (unlikely(value >= ARRAY_SIZE(str))) return snprintf(buf, PAGE_SIZE, "%u\n", value); return snprintf(buf, PAGE_SIZE, "%s\n", str[value]); } static ssize_t cxacru_sysfs_store_adsl_state(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct cxacru_data *instance = to_usbatm_driver_data( to_usb_interface(dev)); int ret; int poll = -1; char str_cmd[8]; int len = strlen(buf); if (!capable(CAP_NET_ADMIN)) return -EACCES; ret = sscanf(buf, "%7s", str_cmd); if (ret != 1) return -EINVAL; ret = 0; if (instance == NULL) return -ENODEV; if (mutex_lock_interruptible(&instance->adsl_state_serialize)) return -ERESTARTSYS; if (!strcmp(str_cmd, "stop") || !strcmp(str_cmd, "restart")) { ret = cxacru_cm(instance, CM_REQUEST_CHIP_ADSL_LINE_STOP, NULL, 0, NULL, 0); if (ret < 0) { atm_err(instance->usbatm, "change adsl state:" " CHIP_ADSL_LINE_STOP returned %d\n", ret); ret = -EIO; } else { ret = len; poll = CXPOLL_STOPPED; } } /* Line status is only updated every second * and the device appears to only react to * START/STOP every second too. Wait 1.5s to * be sure that restart will have an effect. */ if (!strcmp(str_cmd, "restart")) msleep(1500); if (!strcmp(str_cmd, "start") || !strcmp(str_cmd, "restart")) { ret = cxacru_cm(instance, CM_REQUEST_CHIP_ADSL_LINE_START, NULL, 0, NULL, 0); if (ret < 0) { atm_err(instance->usbatm, "change adsl state:" " CHIP_ADSL_LINE_START returned %d\n", ret); ret = -EIO; } else { ret = len; poll = CXPOLL_POLLING; } } if (!strcmp(str_cmd, "poll")) { ret = len; poll = CXPOLL_POLLING; } if (ret == 0) { ret = -EINVAL; poll = -1; } if (poll == CXPOLL_POLLING) { mutex_lock(&instance->poll_state_serialize); switch (instance->poll_state) { case CXPOLL_STOPPED: /* start polling */ instance->poll_state = CXPOLL_POLLING; break; case CXPOLL_STOPPING: /* abort stop request */ instance->poll_state = CXPOLL_POLLING; case CXPOLL_POLLING: case CXPOLL_SHUTDOWN: /* don't start polling */ poll = -1; } mutex_unlock(&instance->poll_state_serialize); } else if (poll == CXPOLL_STOPPED) { mutex_lock(&instance->poll_state_serialize); /* request stop */ if (instance->poll_state == CXPOLL_POLLING) instance->poll_state = CXPOLL_STOPPING; mutex_unlock(&instance->poll_state_serialize); } mutex_unlock(&instance->adsl_state_serialize); if (poll == CXPOLL_POLLING) cxacru_poll_status(&instance->poll_work.work); return ret; } /* CM_REQUEST_CARD_DATA_GET times out, so no show attribute */ static ssize_t cxacru_sysfs_store_adsl_config(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct cxacru_data *instance = to_usbatm_driver_data( to_usb_interface(dev)); int len = strlen(buf); int ret, pos, num; __le32 data[CMD_PACKET_SIZE / 4]; if (!capable(CAP_NET_ADMIN)) return -EACCES; if (instance == NULL) return -ENODEV; pos = 0; num = 0; while (pos < len) { int tmp; u32 index; u32 value; ret = sscanf(buf + pos, "%x=%x%n", &index, &value, &tmp); if (ret < 2) return -EINVAL; if (index < 0 || index > 0x7f) return -EINVAL; pos += tmp; /* skip trailing newline */ if (buf[pos] == '\n' && pos == len-1) pos++; data[num * 2 + 1] = cpu_to_le32(index); data[num * 2 + 2] = cpu_to_le32(value); num++; /* send config values when data buffer is full * or no more data */ if (pos >= len || num >= CMD_MAX_CONFIG) { char log[CMD_MAX_CONFIG * 12 + 1]; /* %02x=%08x */ data[0] = cpu_to_le32(num); ret = cxacru_cm(instance, CM_REQUEST_CARD_DATA_SET, (u8 *) data, 4 + num * 8, NULL, 0); if (ret < 0) { atm_err(instance->usbatm, "set card data returned %d\n", ret); return -EIO; } for (tmp = 0; tmp < num; tmp++) snprintf(log + tmp*12, 13, " %02x=%08x", le32_to_cpu(data[tmp * 2 + 1]), le32_to_cpu(data[tmp * 2 + 2])); atm_info(instance->usbatm, "config%s\n", log); num = 0; } } return len; } /* * All device attributes are included in CXACRU_ALL_FILES * so that the same list can be used multiple times: * INIT (define the device attributes) * CREATE (create all the device files) * REMOVE (remove all the device files) * * With the last two being defined as needed in the functions * they are used in before calling CXACRU_ALL_FILES() */ #define CXACRU_ALL_FILES(_action) \ CXACRU_ATTR_##_action(CXINF_DOWNSTREAM_RATE, u32, downstream_rate); \ CXACRU_ATTR_##_action(CXINF_UPSTREAM_RATE, u32, upstream_rate); \ CXACRU_ATTR_##_action(CXINF_LINK_STATUS, LINK, link_status); \ CXACRU_ATTR_##_action(CXINF_LINE_STATUS, LINE, line_status); \ CXACRU__ATTR_##_action( mac_address); \ CXACRU_ATTR_##_action(CXINF_UPSTREAM_SNR_MARGIN, dB, upstream_snr_margin); \ CXACRU_ATTR_##_action(CXINF_DOWNSTREAM_SNR_MARGIN, dB, downstream_snr_margin); \ CXACRU_ATTR_##_action(CXINF_UPSTREAM_ATTENUATION, dB, upstream_attenuation); \ CXACRU_ATTR_##_action(CXINF_DOWNSTREAM_ATTENUATION, dB, downstream_attenuation); \ CXACRU_ATTR_##_action(CXINF_TRANSMITTER_POWER, s8, transmitter_power); \ CXACRU_ATTR_##_action(CXINF_UPSTREAM_BITS_PER_FRAME, u32, upstream_bits_per_frame); \ CXACRU_ATTR_##_action(CXINF_DOWNSTREAM_BITS_PER_FRAME, u32, downstream_bits_per_frame); \ CXACRU_ATTR_##_action(CXINF_STARTUP_ATTEMPTS, u32, startup_attempts); \ CXACRU_ATTR_##_action(CXINF_UPSTREAM_CRC_ERRORS, u32, upstream_crc_errors); \ CXACRU_ATTR_##_action(CXINF_DOWNSTREAM_CRC_ERRORS, u32, downstream_crc_errors); \ CXACRU_ATTR_##_action(CXINF_UPSTREAM_FEC_ERRORS, u32, upstream_fec_errors); \ CXACRU_ATTR_##_action(CXINF_DOWNSTREAM_FEC_ERRORS, u32, downstream_fec_errors); \ CXACRU_ATTR_##_action(CXINF_UPSTREAM_HEC_ERRORS, u32, upstream_hec_errors); \ CXACRU_ATTR_##_action(CXINF_DOWNSTREAM_HEC_ERRORS, u32, downstream_hec_errors); \ CXACRU_ATTR_##_action(CXINF_LINE_STARTABLE, bool, line_startable); \ CXACRU_ATTR_##_action(CXINF_MODULATION, MODU, modulation); \ CXACRU_ATTR_##_action(CXINF_ADSL_HEADEND, u32, adsl_headend); \ CXACRU_ATTR_##_action(CXINF_ADSL_HEADEND_ENVIRONMENT, u32, adsl_headend_environment); \ CXACRU_ATTR_##_action(CXINF_CONTROLLER_VERSION, u32, adsl_controller_version); \ CXACRU_CMD_##_action( adsl_state); \ CXACRU_SET_##_action( adsl_config); CXACRU_ALL_FILES(INIT); /* the following three functions are stolen from drivers/usb/core/message.c */ static void cxacru_blocking_completion(struct urb *urb) { complete(urb->context); } static void cxacru_timeout_kill(unsigned long data) { usb_unlink_urb((struct urb *) data); } static int cxacru_start_wait_urb(struct urb *urb, struct completion *done, int *actual_length) { struct timer_list timer; init_timer(&timer); timer.expires = jiffies + msecs_to_jiffies(CMD_TIMEOUT); timer.data = (unsigned long) urb; timer.function = cxacru_timeout_kill; add_timer(&timer); wait_for_completion(done); del_timer_sync(&timer); if (actual_length) *actual_length = urb->actual_length; return urb->status; /* must read status after completion */ } static int cxacru_cm(struct cxacru_data *instance, enum cxacru_cm_request cm, u8 *wdata, int wsize, u8 *rdata, int rsize) { int ret, actlen; int offb, offd; const int stride = CMD_PACKET_SIZE - 4; u8 *wbuf = instance->snd_buf; u8 *rbuf = instance->rcv_buf; int wbuflen = ((wsize - 1) / stride + 1) * CMD_PACKET_SIZE; int rbuflen = ((rsize - 1) / stride + 1) * CMD_PACKET_SIZE; if (wbuflen > PAGE_SIZE || rbuflen > PAGE_SIZE) { if (printk_ratelimit()) usb_err(instance->usbatm, "requested transfer size too large (%d, %d)\n", wbuflen, rbuflen); ret = -ENOMEM; goto err; } mutex_lock(&instance->cm_serialize); /* submit reading urb before the writing one */ init_completion(&instance->rcv_done); ret = usb_submit_urb(instance->rcv_urb, GFP_KERNEL); if (ret < 0) { if (printk_ratelimit()) usb_err(instance->usbatm, "submit of read urb for cm %#x failed (%d)\n", cm, ret); goto fail; } memset(wbuf, 0, wbuflen); /* handle wsize == 0 */ wbuf[0] = cm; for (offb = offd = 0; offd < wsize; offd += stride, offb += CMD_PACKET_SIZE) { wbuf[offb] = cm; memcpy(wbuf + offb + 4, wdata + offd, min_t(int, stride, wsize - offd)); } instance->snd_urb->transfer_buffer_length = wbuflen; init_completion(&instance->snd_done); ret = usb_submit_urb(instance->snd_urb, GFP_KERNEL); if (ret < 0) { if (printk_ratelimit()) usb_err(instance->usbatm, "submit of write urb for cm %#x failed (%d)\n", cm, ret); goto fail; } ret = cxacru_start_wait_urb(instance->snd_urb, &instance->snd_done, NULL); if (ret < 0) { if (printk_ratelimit()) usb_err(instance->usbatm, "send of cm %#x failed (%d)\n", cm, ret); goto fail; } ret = cxacru_start_wait_urb(instance->rcv_urb, &instance->rcv_done, &actlen); if (ret < 0) { if (printk_ratelimit()) usb_err(instance->usbatm, "receive of cm %#x failed (%d)\n", cm, ret); goto fail; } if (actlen % CMD_PACKET_SIZE || !actlen) { if (printk_ratelimit()) usb_err(instance->usbatm, "invalid response length to cm %#x: %d\n", cm, actlen); ret = -EIO; goto fail; } /* check the return status and copy the data to the output buffer, if needed */ for (offb = offd = 0; offd < rsize && offb < actlen; offb += CMD_PACKET_SIZE) { if (rbuf[offb] != cm) { if (printk_ratelimit()) usb_err(instance->usbatm, "wrong cm %#x in response to cm %#x\n", rbuf[offb], cm); ret = -EIO; goto fail; } if (rbuf[offb + 1] != CM_STATUS_SUCCESS) { if (printk_ratelimit()) usb_err(instance->usbatm, "response to cm %#x failed: %#x\n", cm, rbuf[offb + 1]); ret = -EIO; goto fail; } if (offd >= rsize) break; memcpy(rdata + offd, rbuf + offb + 4, min_t(int, stride, rsize - offd)); offd += stride; } ret = offd; usb_dbg(instance->usbatm, "cm %#x\n", cm); fail: mutex_unlock(&instance->cm_serialize); err: return ret; } static int cxacru_cm_get_array(struct cxacru_data *instance, enum cxacru_cm_request cm, u32 *data, int size) { int ret, len; __le32 *buf; int offb; unsigned int offd; const int stride = CMD_PACKET_SIZE / (4 * 2) - 1; int buflen = ((size - 1) / stride + 1 + size * 2) * 4; buf = kmalloc(buflen, GFP_KERNEL); if (!buf) return -ENOMEM; ret = cxacru_cm(instance, cm, NULL, 0, (u8 *) buf, buflen); if (ret < 0) goto cleanup; /* len > 0 && len % 4 == 0 guaranteed by cxacru_cm() */ len = ret / 4; for (offb = 0; offb < len; ) { int l = le32_to_cpu(buf[offb++]); if (l < 0 || l > stride || l > (len - offb) / 2) { if (printk_ratelimit()) usb_err(instance->usbatm, "invalid data length from cm %#x: %d\n", cm, l); ret = -EIO; goto cleanup; } while (l--) { offd = le32_to_cpu(buf[offb++]); if (offd >= size) { if (printk_ratelimit()) usb_err(instance->usbatm, "wrong index %#x in response to cm %#x\n", offd, cm); ret = -EIO; goto cleanup; } data[offd] = le32_to_cpu(buf[offb++]); } } ret = 0; cleanup: kfree(buf); return ret; } static int cxacru_card_status(struct cxacru_data *instance) { int ret = cxacru_cm(instance, CM_REQUEST_CARD_GET_STATUS, NULL, 0, NULL, 0); if (ret < 0) { /* firmware not loaded */ usb_dbg(instance->usbatm, "cxacru_adsl_start: CARD_GET_STATUS returned %d\n", ret); return ret; } return 0; } static void cxacru_remove_device_files(struct usbatm_data *usbatm_instance, struct atm_dev *atm_dev) { struct usb_interface *intf = usbatm_instance->usb_intf; #define CXACRU_DEVICE_REMOVE_FILE(_name) \ device_remove_file(&intf->dev, &dev_attr_##_name); CXACRU_ALL_FILES(REMOVE); #undef CXACRU_DEVICE_REMOVE_FILE } static int cxacru_atm_start(struct usbatm_data *usbatm_instance, struct atm_dev *atm_dev) { struct cxacru_data *instance = usbatm_instance->driver_data; struct usb_interface *intf = usbatm_instance->usb_intf; int ret; int start_polling = 1; dev_dbg(&intf->dev, "%s\n", __func__); /* Read MAC address */ ret = cxacru_cm(instance, CM_REQUEST_CARD_GET_MAC_ADDRESS, NULL, 0, atm_dev->esi, sizeof(atm_dev->esi)); if (ret < 0) { atm_err(usbatm_instance, "cxacru_atm_start: CARD_GET_MAC_ADDRESS returned %d\n", ret); return ret; } #define CXACRU_DEVICE_CREATE_FILE(_name) \ ret = device_create_file(&intf->dev, &dev_attr_##_name); \ if (unlikely(ret)) \ goto fail_sysfs; CXACRU_ALL_FILES(CREATE); #undef CXACRU_DEVICE_CREATE_FILE /* start ADSL */ mutex_lock(&instance->adsl_state_serialize); ret = cxacru_cm(instance, CM_REQUEST_CHIP_ADSL_LINE_START, NULL, 0, NULL, 0); if (ret < 0) atm_err(usbatm_instance, "cxacru_atm_start: CHIP_ADSL_LINE_START returned %d\n", ret); /* Start status polling */ mutex_lock(&instance->poll_state_serialize); switch (instance->poll_state) { case CXPOLL_STOPPED: /* start polling */ instance->poll_state = CXPOLL_POLLING; break; case CXPOLL_STOPPING: /* abort stop request */ instance->poll_state = CXPOLL_POLLING; case CXPOLL_POLLING: case CXPOLL_SHUTDOWN: /* don't start polling */ start_polling = 0; } mutex_unlock(&instance->poll_state_serialize); mutex_unlock(&instance->adsl_state_serialize); printk(KERN_INFO "%s%d: %s %pM\n", atm_dev->type, atm_dev->number, usbatm_instance->description, atm_dev->esi); if (start_polling) cxacru_poll_status(&instance->poll_work.work); return 0; fail_sysfs: usb_err(usbatm_instance, "cxacru_atm_start: device_create_file failed (%d)\n", ret); cxacru_remove_device_files(usbatm_instance, atm_dev); return ret; } static void cxacru_poll_status(struct work_struct *work) { struct cxacru_data *instance = container_of(work, struct cxacru_data, poll_work.work); u32 buf[CXINF_MAX] = {}; struct usbatm_data *usbatm = instance->usbatm; struct atm_dev *atm_dev = usbatm->atm_dev; int keep_polling = 1; int ret; ret = cxacru_cm_get_array(instance, CM_REQUEST_CARD_INFO_GET, buf, CXINF_MAX); if (ret < 0) { if (ret != -ESHUTDOWN) atm_warn(usbatm, "poll status: error %d\n", ret); mutex_lock(&instance->poll_state_serialize); if (instance->poll_state != CXPOLL_SHUTDOWN) { instance->poll_state = CXPOLL_STOPPED; if (ret != -ESHUTDOWN) atm_warn(usbatm, "polling disabled, set adsl_state" " to 'start' or 'poll' to resume\n"); } mutex_unlock(&instance->poll_state_serialize); goto reschedule; } memcpy(instance->card_info, buf, sizeof(instance->card_info)); if (instance->adsl_status != buf[CXINF_LINE_STARTABLE]) { instance->adsl_status = buf[CXINF_LINE_STARTABLE]; switch (instance->adsl_status) { case 0: atm_printk(KERN_INFO, usbatm, "ADSL state: running\n"); break; case 1: atm_printk(KERN_INFO, usbatm, "ADSL state: stopped\n"); break; default: atm_printk(KERN_INFO, usbatm, "Unknown adsl status %02x\n", instance->adsl_status); break; } } if (instance->line_status == buf[CXINF_LINE_STATUS]) goto reschedule; instance->line_status = buf[CXINF_LINE_STATUS]; switch (instance->line_status) { case 0: atm_dev_signal_change(atm_dev, ATM_PHY_SIG_LOST); atm_info(usbatm, "ADSL line: down\n"); break; case 1: atm_dev_signal_change(atm_dev, ATM_PHY_SIG_LOST); atm_info(usbatm, "ADSL line: attempting to activate\n"); break; case 2: atm_dev_signal_change(atm_dev, ATM_PHY_SIG_LOST); atm_info(usbatm, "ADSL line: training\n"); break; case 3: atm_dev_signal_change(atm_dev, ATM_PHY_SIG_LOST); atm_info(usbatm, "ADSL line: channel analysis\n"); break; case 4: atm_dev_signal_change(atm_dev, ATM_PHY_SIG_LOST); atm_info(usbatm, "ADSL line: exchange\n"); break; case 5: atm_dev->link_rate = buf[CXINF_DOWNSTREAM_RATE] * 1000 / 424; atm_dev_signal_change(atm_dev, ATM_PHY_SIG_FOUND); atm_info(usbatm, "ADSL line: up (%d kb/s down | %d kb/s up)\n", buf[CXINF_DOWNSTREAM_RATE], buf[CXINF_UPSTREAM_RATE]); break; case 6: atm_dev_signal_change(atm_dev, ATM_PHY_SIG_LOST); atm_info(usbatm, "ADSL line: waiting\n"); break; case 7: atm_dev_signal_change(atm_dev, ATM_PHY_SIG_LOST); atm_info(usbatm, "ADSL line: initializing\n"); break; default: atm_dev_signal_change(atm_dev, ATM_PHY_SIG_UNKNOWN); atm_info(usbatm, "Unknown line state %02x\n", instance->line_status); break; } reschedule: mutex_lock(&instance->poll_state_serialize); if (instance->poll_state == CXPOLL_STOPPING && instance->adsl_status == 1 && /* stopped */ instance->line_status == 0) /* down */ instance->poll_state = CXPOLL_STOPPED; if (instance->poll_state == CXPOLL_STOPPED) keep_polling = 0; mutex_unlock(&instance->poll_state_serialize); if (keep_polling) schedule_delayed_work(&instance->poll_work, round_jiffies_relative(POLL_INTERVAL*HZ)); } static int cxacru_fw(struct usb_device *usb_dev, enum cxacru_fw_request fw, u8 code1, u8 code2, u32 addr, const u8 *data, int size) { int ret; u8 *buf; int offd, offb; const int stride = CMD_PACKET_SIZE - 8; buf = (u8 *) __get_free_page(GFP_KERNEL); if (!buf) return -ENOMEM; offb = offd = 0; do { int l = min_t(int, stride, size - offd); buf[offb++] = fw; buf[offb++] = l; buf[offb++] = code1; buf[offb++] = code2; put_unaligned(cpu_to_le32(addr), (__le32 *)(buf + offb)); offb += 4; addr += l; if (l) memcpy(buf + offb, data + offd, l); if (l < stride) memset(buf + offb + l, 0, stride - l); offb += stride; offd += stride; if ((offb >= PAGE_SIZE) || (offd >= size)) { ret = usb_bulk_msg(usb_dev, usb_sndbulkpipe(usb_dev, CXACRU_EP_CMD), buf, offb, NULL, CMD_TIMEOUT); if (ret < 0) { dev_dbg(&usb_dev->dev, "sending fw %#x failed\n", fw); goto cleanup; } offb = 0; } } while (offd < size); dev_dbg(&usb_dev->dev, "sent fw %#x\n", fw); ret = 0; cleanup: free_page((unsigned long) buf); return ret; } static void cxacru_upload_firmware(struct cxacru_data *instance, const struct firmware *fw, const struct firmware *bp) { int ret; struct usbatm_data *usbatm = instance->usbatm; struct usb_device *usb_dev = usbatm->usb_dev; __le16 signature[] = { usb_dev->descriptor.idVendor, usb_dev->descriptor.idProduct }; __le32 val; usb_dbg(usbatm, "%s\n", __func__); /* FirmwarePllFClkValue */ val = cpu_to_le32(instance->modem_type->pll_f_clk); ret = cxacru_fw(usb_dev, FW_WRITE_MEM, 0x2, 0x0, PLLFCLK_ADDR, (u8 *) &val, 4); if (ret) { usb_err(usbatm, "FirmwarePllFClkValue failed: %d\n", ret); return; } /* FirmwarePllBClkValue */ val = cpu_to_le32(instance->modem_type->pll_b_clk); ret = cxacru_fw(usb_dev, FW_WRITE_MEM, 0x2, 0x0, PLLBCLK_ADDR, (u8 *) &val, 4); if (ret) { usb_err(usbatm, "FirmwarePllBClkValue failed: %d\n", ret); return; } /* Enable SDRAM */ val = cpu_to_le32(SDRAM_ENA); ret = cxacru_fw(usb_dev, FW_WRITE_MEM, 0x2, 0x0, SDRAMEN_ADDR, (u8 *) &val, 4); if (ret) { usb_err(usbatm, "Enable SDRAM failed: %d\n", ret); return; } /* Firmware */ usb_info(usbatm, "loading firmware\n"); ret = cxacru_fw(usb_dev, FW_WRITE_MEM, 0x2, 0x0, FW_ADDR, fw->data, fw->size); if (ret) { usb_err(usbatm, "Firmware upload failed: %d\n", ret); return; } /* Boot ROM patch */ if (instance->modem_type->boot_rom_patch) { usb_info(usbatm, "loading boot ROM patch\n"); ret = cxacru_fw(usb_dev, FW_WRITE_MEM, 0x2, 0x0, BR_ADDR, bp->data, bp->size); if (ret) { usb_err(usbatm, "Boot ROM patching failed: %d\n", ret); return; } } /* Signature */ ret = cxacru_fw(usb_dev, FW_WRITE_MEM, 0x2, 0x0, SIG_ADDR, (u8 *) signature, 4); if (ret) { usb_err(usbatm, "Signature storing failed: %d\n", ret); return; } usb_info(usbatm, "starting device\n"); if (instance->modem_type->boot_rom_patch) { val = cpu_to_le32(BR_ADDR); ret = cxacru_fw(usb_dev, FW_WRITE_MEM, 0x2, 0x0, BR_STACK_ADDR, (u8 *) &val, 4); } else { ret = cxacru_fw(usb_dev, FW_GOTO_MEM, 0x0, 0x0, FW_ADDR, NULL, 0); } if (ret) { usb_err(usbatm, "Passing control to firmware failed: %d\n", ret); return; } /* Delay to allow firmware to start up. */ msleep_interruptible(1000); usb_clear_halt(usb_dev, usb_sndbulkpipe(usb_dev, CXACRU_EP_CMD)); usb_clear_halt(usb_dev, usb_rcvbulkpipe(usb_dev, CXACRU_EP_CMD)); usb_clear_halt(usb_dev, usb_sndbulkpipe(usb_dev, CXACRU_EP_DATA)); usb_clear_halt(usb_dev, usb_rcvbulkpipe(usb_dev, CXACRU_EP_DATA)); ret = cxacru_cm(instance, CM_REQUEST_CARD_GET_STATUS, NULL, 0, NULL, 0); if (ret < 0) { usb_err(usbatm, "modem failed to initialize: %d\n", ret); return; } } static int cxacru_find_firmware(struct cxacru_data *instance, char *phase, const struct firmware **fw_p) { struct usbatm_data *usbatm = instance->usbatm; struct device *dev = &usbatm->usb_intf->dev; char buf[16]; sprintf(buf, "/*(DEBLOBBED)*/", phase); usb_dbg(usbatm, "cxacru_find_firmware: looking for %s\n", buf); if (reject_firmware(fw_p, buf, dev)) { usb_dbg(usbatm, "no stage %s firmware found\n", phase); return -ENOENT; } usb_info(usbatm, "found firmware %s\n", buf); return 0; } static int cxacru_heavy_init(struct usbatm_data *usbatm_instance, struct usb_interface *usb_intf) { const struct firmware *fw, *bp; struct cxacru_data *instance = usbatm_instance->driver_data; int ret = cxacru_find_firmware(instance, "fw", &fw); if (ret) { usb_warn(usbatm_instance, "firmware (/*(DEBLOBBED)*/) unavailable (system misconfigured?)\n"); return ret; } if (instance->modem_type->boot_rom_patch) { ret = cxacru_find_firmware(instance, "bp", &bp); if (ret) { usb_warn(usbatm_instance, "boot ROM patch (/*(DEBLOBBED)*/) unavailable (system misconfigured?)\n"); release_firmware(fw); return ret; } } cxacru_upload_firmware(instance, fw, bp); if (instance->modem_type->boot_rom_patch) release_firmware(bp); release_firmware(fw); ret = cxacru_card_status(instance); if (ret) usb_dbg(usbatm_instance, "modem initialisation failed\n"); else usb_dbg(usbatm_instance, "done setting up the modem\n"); return ret; } static int cxacru_bind(struct usbatm_data *usbatm_instance, struct usb_interface *intf, const struct usb_device_id *id) { struct cxacru_data *instance; struct usb_device *usb_dev = interface_to_usbdev(intf); struct usb_host_endpoint *cmd_ep = usb_dev->ep_in[CXACRU_EP_CMD]; int ret; /* instance init */ instance = kzalloc(sizeof(*instance), GFP_KERNEL); if (!instance) { usb_dbg(usbatm_instance, "cxacru_bind: no memory for instance data\n"); return -ENOMEM; } instance->usbatm = usbatm_instance; instance->modem_type = (struct cxacru_modem_type *) id->driver_info; mutex_init(&instance->poll_state_serialize); instance->poll_state = CXPOLL_STOPPED; instance->line_status = -1; instance->adsl_status = -1; mutex_init(&instance->adsl_state_serialize); instance->rcv_buf = (u8 *) __get_free_page(GFP_KERNEL); if (!instance->rcv_buf) { usb_dbg(usbatm_instance, "cxacru_bind: no memory for rcv_buf\n"); ret = -ENOMEM; goto fail; } instance->snd_buf = (u8 *) __get_free_page(GFP_KERNEL); if (!instance->snd_buf) { usb_dbg(usbatm_instance, "cxacru_bind: no memory for snd_buf\n"); ret = -ENOMEM; goto fail; } instance->rcv_urb = usb_alloc_urb(0, GFP_KERNEL); if (!instance->rcv_urb) { usb_dbg(usbatm_instance, "cxacru_bind: no memory for rcv_urb\n"); ret = -ENOMEM; goto fail; } instance->snd_urb = usb_alloc_urb(0, GFP_KERNEL); if (!instance->snd_urb) { usb_dbg(usbatm_instance, "cxacru_bind: no memory for snd_urb\n"); ret = -ENOMEM; goto fail; } if (!cmd_ep) { usb_dbg(usbatm_instance, "cxacru_bind: no command endpoint\n"); ret = -ENODEV; goto fail; } if ((cmd_ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT) { usb_fill_int_urb(instance->rcv_urb, usb_dev, usb_rcvintpipe(usb_dev, CXACRU_EP_CMD), instance->rcv_buf, PAGE_SIZE, cxacru_blocking_completion, &instance->rcv_done, 1); usb_fill_int_urb(instance->snd_urb, usb_dev, usb_sndintpipe(usb_dev, CXACRU_EP_CMD), instance->snd_buf, PAGE_SIZE, cxacru_blocking_completion, &instance->snd_done, 4); } else { usb_fill_bulk_urb(instance->rcv_urb, usb_dev, usb_rcvbulkpipe(usb_dev, CXACRU_EP_CMD), instance->rcv_buf, PAGE_SIZE, cxacru_blocking_completion, &instance->rcv_done); usb_fill_bulk_urb(instance->snd_urb, usb_dev, usb_sndbulkpipe(usb_dev, CXACRU_EP_CMD), instance->snd_buf, PAGE_SIZE, cxacru_blocking_completion, &instance->snd_done); } mutex_init(&instance->cm_serialize); INIT_DELAYED_WORK(&instance->poll_work, cxacru_poll_status); usbatm_instance->driver_data = instance; usbatm_instance->flags = (cxacru_card_status(instance) ? 0 : UDSL_SKIP_HEAVY_INIT); return 0; fail: free_page((unsigned long) instance->snd_buf); free_page((unsigned long) instance->rcv_buf); usb_free_urb(instance->snd_urb); usb_free_urb(instance->rcv_urb); kfree(instance); return ret; } static void cxacru_unbind(struct usbatm_data *usbatm_instance, struct usb_interface *intf) { struct cxacru_data *instance = usbatm_instance->driver_data; int is_polling = 1; usb_dbg(usbatm_instance, "cxacru_unbind entered\n"); if (!instance) { usb_dbg(usbatm_instance, "cxacru_unbind: NULL instance!\n"); return; } mutex_lock(&instance->poll_state_serialize); BUG_ON(instance->poll_state == CXPOLL_SHUTDOWN); /* ensure that status polling continues unless * it has already stopped */ if (instance->poll_state == CXPOLL_STOPPED) is_polling = 0; /* stop polling from being stopped or started */ instance->poll_state = CXPOLL_SHUTDOWN; mutex_unlock(&instance->poll_state_serialize); if (is_polling) cancel_delayed_work_sync(&instance->poll_work); usb_kill_urb(instance->snd_urb); usb_kill_urb(instance->rcv_urb); usb_free_urb(instance->snd_urb); usb_free_urb(instance->rcv_urb); free_page((unsigned long) instance->snd_buf); free_page((unsigned long) instance->rcv_buf); kfree(instance); usbatm_instance->driver_data = NULL; } static const struct cxacru_modem_type cxacru_cafe = { .pll_f_clk = 0x02d874df, .pll_b_clk = 0x0196a51a, .boot_rom_patch = 1, }; static const struct cxacru_modem_type cxacru_cb00 = { .pll_f_clk = 0x5, .pll_b_clk = 0x3, .boot_rom_patch = 0, }; static const struct usb_device_id cxacru_usb_ids[] = { { /* V = Conexant P = ADSL modem (Euphrates project) */ USB_DEVICE(0x0572, 0xcafe), .driver_info = (unsigned long) &cxacru_cafe }, { /* V = Conexant P = ADSL modem (Hasbani project) */ USB_DEVICE(0x0572, 0xcb00), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Conexant P = ADSL modem */ USB_DEVICE(0x0572, 0xcb01), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Conexant P = ADSL modem (Well PTI-800) */ USB_DEVICE(0x0572, 0xcb02), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Conexant P = ADSL modem */ USB_DEVICE(0x0572, 0xcb06), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Conexant P = ADSL modem (ZTE ZXDSL 852) */ USB_DEVICE(0x0572, 0xcb07), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Olitec P = ADSL modem version 2 */ USB_DEVICE(0x08e3, 0x0100), .driver_info = (unsigned long) &cxacru_cafe }, { /* V = Olitec P = ADSL modem version 3 */ USB_DEVICE(0x08e3, 0x0102), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Trust/Amigo Technology Co. P = AMX-CA86U */ USB_DEVICE(0x0eb0, 0x3457), .driver_info = (unsigned long) &cxacru_cafe }, { /* V = Zoom P = 5510 */ USB_DEVICE(0x1803, 0x5510), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Draytek P = Vigor 318 */ USB_DEVICE(0x0675, 0x0200), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Zyxel P = 630-C1 aka OMNI ADSL USB (Annex A) */ USB_DEVICE(0x0586, 0x330a), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Zyxel P = 630-C3 aka OMNI ADSL USB (Annex B) */ USB_DEVICE(0x0586, 0x330b), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Aethra P = Starmodem UM1020 */ USB_DEVICE(0x0659, 0x0020), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Aztech Systems P = ? AKA Pirelli AUA-010 */ USB_DEVICE(0x0509, 0x0812), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Netopia P = Cayman 3341(Annex A)/3351(Annex B) */ USB_DEVICE(0x100d, 0xcb01), .driver_info = (unsigned long) &cxacru_cb00 }, { /* V = Netopia P = Cayman 3342(Annex A)/3352(Annex B) */ USB_DEVICE(0x100d, 0x3342), .driver_info = (unsigned long) &cxacru_cb00 }, {} }; MODULE_DEVICE_TABLE(usb, cxacru_usb_ids); static struct usbatm_driver cxacru_driver = { .driver_name = cxacru_driver_name, .bind = cxacru_bind, .heavy_init = cxacru_heavy_init, .unbind = cxacru_unbind, .atm_start = cxacru_atm_start, .atm_stop = cxacru_remove_device_files, .bulk_in = CXACRU_EP_DATA, .bulk_out = CXACRU_EP_DATA, .rx_padding = 3, .tx_padding = 11, }; static int cxacru_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *usb_dev = interface_to_usbdev(intf); char buf[15]; /* Avoid ADSL routers (cx82310_eth). * Abort if bDeviceClass is 0xff and iProduct is "USB NET CARD". */ if (usb_dev->descriptor.bDeviceClass == USB_CLASS_VENDOR_SPEC && usb_string(usb_dev, usb_dev->descriptor.iProduct, buf, sizeof(buf)) > 0) { if (!strcmp(buf, "USB NET CARD")) { dev_info(&intf->dev, "ignoring cx82310_eth device\n"); return -ENODEV; } } return usbatm_usb_probe(intf, id, &cxacru_driver); } static struct usb_driver cxacru_usb_driver = { .name = cxacru_driver_name, .probe = cxacru_usb_probe, .disconnect = usbatm_usb_disconnect, .id_table = cxacru_usb_ids }; module_usb_driver(cxacru_usb_driver); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); MODULE_VERSION(DRIVER_VERSION);
mason-hock/CHIP-linux-libre
CHIP-linux-libre/drivers/usb/atm/cxacru.c
C
gpl-2.0
40,281
cloudmess =========
violet42/cloudmess
README.md
Markdown
gpl-2.0
20
from PyQt4 import QtCore, uic from PyQt4.QtGui import * from subprocess import call from grafo import Grafo from uis.uiMainwindow import Ui_MainWindow from sobre import SobreUi import pdb from resultado import Resultado def debug_trace(): '''Set a tracepoint in the Python debugger that works with Qt''' from PyQt4.QtCore import pyqtRemoveInputHook from pdb import set_trace pyqtRemoveInputHook() set_trace() class MainWindow(QMainWindow, Ui_MainWindow): matrizAdjacencia = {} grafo = Grafo() def closeEvent(self, event): if False: event = QCloseEvent def alert(self): QMessageBox.about(self, "TESTE", "TESTE") def addVertice(self, vertice): if not vertice: return self.modelVertice.appendRow(QStandardItem(vertice)) self.listVertices.setModel(self.modelVertice) self.addToComboVertice(vertice) self.grafo.addVertice(vertice) def buttonAddVertice(self): self.addVertice(self.lineNomeVertice.text()) def addAresta(self, aresta): if not aresta: return self.modelAresta.appendRow(QStandardItem(aresta)) self.listArestas.setModel(self.modelAresta) self.comboAresta.addItem(aresta) self.grafo.addAresta(aresta) def buttonAddAresta(self): self.addAresta(self.lineNomeAresta.text()) def addToComboVertice(self, text): self.comboVertice1.addItem(text) self.comboVertice2.addItem(text) self.comboCaminhoInicio.addItem(text) self.comboCaminhoFim.addItem(text) def addConexao(self, v1, aresta, v2, peso = 1): if not v1 or not aresta or not v2: return conexao = v1 + '|' + aresta + '|' + v2 + '|' + str(peso) self.modelConexao.appendRow(QStandardItem(conexao)) self.grafo.addConexao(v1, aresta, v2, peso) self.listConexoes.setModel(self.modelConexao) def buttonAddConexao(self): try: peso = int(self.linePesoNo.text()) except: peso = 1 v1, v2 = self.comboVertice1.currentText(), self.comboVertice2.currentText() aresta = self.comboAresta.currentText() self.addConexao(v1, aresta, v2, peso) def gerar(self): # ['1|2|1|1'] # v1 | a | v2 | peso resList = [] if self.checkDirecionado.isChecked(): self.grafo.setDirecionado(True) else: self.grafo.setDirecionado(False) if self.checkExisteLaco.isChecked(): if self.grafo.existeLaco(): resList.append("- Existem os seguintes laços:\n" + "\n".join(self.grafo.getLaco())) else: resList.append("- Nao existem lacos no grafo.") if self.checkExisteParalela.isChecked(): if self.grafo.existeArestaParalela(): resList.append("- Existem arestas paralelas") else: resList.append("- Nao existem arestas paralelas") if self.checkExisteIsolado.isChecked(): if self.grafo.existeVerticeIsolado(): resList.append("- Existem vertices isolados") else: resList.append("- Nao existem vertices isolados") if self.checkOrdem.isChecked(): resList.append("- Ordem do grafo: " + str(self.grafo.getOrdem())) if self.checkExisteCiclo.isChecked(): ciclos = self.grafo.getCiclos() if ciclos: resList.append("- Existe(m) ciclo(s) para o(s) vértice(s): " + ", ".join(ciclos)) else: resList.append("- Nao existem ciclos no grafo") if self.checkConexo.isChecked(): if self.grafo.isConexo(): resList.append("- Grafo é conexo") else: resList.append("- Grafo não é conexo") if self.checkCaminhoCurto.isChecked(): v1 = self.comboCaminhoInicio.currentText() v2 = self.comboCaminhoFim.currentText() if self.grafo.existeCaminho(v1, v2, []): resList.append("- Existe caminho entre o vértice '" + v1 + "' e '" + v2 +"'") else: resList.append("- Nao existe caminho entre o vértice '" + v1 + "' e '" + v2 +"'") if self.checkGrau.isChecked(): graus = self.grafo.getTodosGraus() if self.grafo.isDirecionado: resList.append("- Grau de cada vértice (emissão, recepção):") else: resList.append("- Grau de cada vértice:") for v in graus.keys(): if self.grafo.isDirecionado: resList.append(" '" + v + "': " + str(graus[v][0]) + ", " + str(graus[v][1])) else: resList.append(" '" + v + "': " + str(graus[v])) resList.append("") if self.checkAdjacencia.isChecked(): adjacencias = self.grafo.getTodasAdjacencias() resList.append("- Adjacências de cada vértice:") for v in adjacencias.keys(): strAdj = "" + v + ": " verticesAdj = [] for arestaAdj, vertAdj in adjacencias[v]: verticesAdj.append(vertAdj) if verticesAdj: resList.append(strAdj + ", ".join(verticesAdj)) else: resList.append(strAdj + "Nenhum") resultado = Resultado("\n".join(resList), self) resultado.centerToMainWindow() self.resultados.append(resultado) def buttonRemoveVertice(self): index = self.listVertices.currentIndex() text = self.modelVertice.itemFromIndex(index).text() self.removeVertice({'index': index.row(), 'value': text}) def removeVertice(self, v): self.grafo.removeVertice(v['value']) self.modelVertice.removeRow(v['index']) eraseFrom = [self.comboVertice1,self.comboVertice2,self.comboCaminhoInicio,self.comboCaminhoFim] for combo in eraseFrom: combo.removeItem(combo.findText(v['value'])) # for i in self.comboVertice1.count(): # pass toErase = [] for i in range(self.modelConexao.rowCount()): item = self.modelConexao.item(i) values = item.text().split('|') if values[0] == str(v['value']) or values[2] == str(v['value']): toErase.append(item) for item in toErase: index = self.modelConexao.indexFromItem(item) if False: index = QStandardItem self.modelConexao.removeRow(index.row()) def removeConexao(self, a): self.grafo.removeConexao(a['value'].split('|')[1]) self.modelConexao.removeRow(a['index']) def removeAresta(self, a): self.grafo.removeAresta(a['value']) self.modelAresta.removeRow(a['index']) self.comboAresta.removeItem(self.comboAresta.findText(a['value'])) toErase = [] for i in range(self.modelConexao.rowCount()): item = self.modelConexao.item(i) values = item.text().split('|') print(values) if values[1] == str(a['value']): toErase.append(item) for item in toErase: index = self.modelConexao.indexFromItem(item) if False: index = QStandardItem self.modelConexao.removeRow(index.row()) def listVerticesClicked(self, model): if False: model = QStandardItem self.modelVertice.removeRow(model.row()) def __init__(self, parent=None, name=None, fl=0): self.resultados = [] QMainWindow.__init__(self) Ui_MainWindow.__init__(self) Ui_MainWindow.setupUi(self, self) self.menuArquivo.setTitle("&Arquivo") # uic.loadUi('mainwindow.ui', self) # self.listVertices.setEditTriggers(QApplication.NoEditTriggers) self.modelVertice = QStandardItemModel(self.listVertices) self.modelAresta = QStandardItemModel(self.listArestas) self.modelConexao = QStandardItemModel(self.listConexoes) self.sobreUi = SobreUi(self) self.sobreUi.tbAbout.setText(open('sobre.txt').read()) self.events() def buttonRemoveAresta(self): index = self.listArestas.currentIndex() text = self.modelAresta.itemFromIndex(index).text() self.removeAresta({'index': index.row(), 'value': text}) def buttonRemoveConexao(self): index = self.listConexoes.currentIndex() text = self.modelConexao.itemFromIndex(index).text() self.removeConexao({'index': index.row(), 'value': text}) def events(self): QtCore.QObject.connect(self.pushAddVertice, QtCore.SIGNAL("clicked()"), self.buttonAddVertice) QtCore.QObject.connect(self.pushAddAresta, QtCore.SIGNAL("clicked()"), self.buttonAddAresta) QtCore.QObject.connect(self.pushAddConexao, QtCore.SIGNAL("clicked()"), self.buttonAddConexao) QtCore.QObject.connect(self.pushRemoverVertice, QtCore.SIGNAL("clicked()"), self.buttonRemoveVertice) QtCore.QObject.connect(self.pushRemoverAresta, QtCore.SIGNAL("clicked()"), self.buttonRemoveAresta) QtCore.QObject.connect(self.pushRemoveConexao, QtCore.SIGNAL("clicked()"), self.buttonRemoveConexao) QtCore.QObject.connect(self.pushGerar, QtCore.SIGNAL("clicked()"), self.gerar) self.actionSobre.triggered.connect(self.showSobreUi) self.actionSair.triggered.connect(self.sair) def showSobreUi(self): self.sobreUi.show() self.sobreUi.centerToMainWindow() def sair(self): self.close() def show(self): super().show()
sollidsnake/grafo
mainwindow.py
Python
gpl-2.0
10,057
<?php $lang['0comments'] = '%d Kommentare'; $lang['1comments'] = '%d Kommentar'; $lang['Xcomments'] = '%d Kommentare'; $lang['readmore'] = 'Weiter lesen...'; $lang['prev'] = '&lt; Neuere Beiträge';; $lang['next'] = 'Ältere Beiträge &gt;'; $lang['title'] = 'Titel:'; $lang['create'] = 'Anlegen'; $lang['comment_mail'] = 'E-Mail'; $lang['comment_name'] = 'Name'; $lang['comment_web'] = 'Webseite'; $lang['comment_preview'] = 'Vorschau'; $lang['comment_submit'] = 'Kommentieren'; $lang['comment_subscribe'] = 'Neue Kommentare abbonieren'; $lang['err_notitle'] = 'Kein Beitragstitel angegeben!';
foozzi/linuxeed.org
lib/plugins/blogtng/lang/de/lang.php
PHP
gpl-2.0
633
<?php /** * @category Virtue Theme * @package Metaboxes * @license http://www.opensource.org/licenses/gpl-license.php GPL v2.0 (or later) * @link https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress */ add_filter( 'cmb_meta_boxes', 'virtue_metaboxes' ); /** * Define the metabox and field configurations. * * @param array $meta_boxes * @return array */ //add_filter('cmb_icomoon', 'cmb_icomoon'); add_filter( 'cmb_render_imag_select_taxonomy', 'imag_render_imag_select_taxonomy', 10, 2 ); function imag_render_imag_select_taxonomy( $field, $meta ) { wp_dropdown_categories(array( 'show_option_none' => __( "All", 'virtue' ), 'hierarchical' => 1, 'taxonomy' => $field['taxonomy'], 'orderby' => 'name', 'hide_empty' => 0, 'name' => $field['id'], 'selected' => $meta )); if ( !empty( $field['desc'] ) ) echo '<p class="cmb_metabox_description">' . $field['desc'] . '</p>'; } add_filter( 'cmb_render_imag_select_category', 'imag_render_imag_select_category', 10, 2 ); function imag_render_imag_select_category( $field, $meta ) { wp_dropdown_categories(array( 'show_option_none' => __( "All Blog Posts", 'virtue' ), 'hierarchical' => 1, 'taxonomy' => 'category', 'orderby' => 'name', 'hide_empty' => 0, 'name' => $field['id'], 'selected' => $meta )); if ( !empty( $field['desc'] ) ) echo '<p class="cmb_metabox_description">' . $field['desc'] . '</p>'; } add_filter( 'cmb_render_imag_select_sidebars', 'imag_render_imag_select_sidebars', 10, 2 ); function imag_render_imag_select_sidebars( $field, $meta ) { global $vir_sidebars; echo '<select name="', $field['id'], '" id="', $field['id'], '">'; foreach ($vir_sidebars as $side) { echo '<option value="', $side['id'], '"', $meta == $side['id'] ? ' selected="selected"' : '', '>', $side['name'], '</option>'; } echo '</select>'; if ( !empty( $field['desc'] ) ) echo '<p class="cmb_metabox_description">' . $field['desc'] . '</p>'; } function virtue_metaboxes( array $meta_boxes ) { // Start with an underscore to hide fields from custom fields list $prefix = '_kad_'; $meta_boxes[] = array( 'id' => 'subtitle_metabox', 'title' => __( "Page Title and Subtitle", 'virtue' ), 'pages' => array( 'page', ), // Post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __( "Subtitle", 'virtue' ), 'desc' => __( "Subtitle will go below page title", 'virtue' ), 'id' => $prefix . 'subtitle', 'type' => 'textarea_small', ), ) ); $meta_boxes[] = array( 'id' => 'post_metabox', 'title' => __("Post Options", 'virtue'), 'pages' => array( 'post',), // Post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __("Head Content", 'virtue' ), 'desc' => '', 'id' => $prefix . 'blog_head', 'type' => 'select', 'options' => array( array( 'name' => __("None", 'virtue' ), 'value' => 'none', ), array( 'name' => __("Image Slider", 'virtue' ), 'value' => 'flex', ), array( 'name' => __("Video", 'virtue' ), 'value' => 'video', ), array( 'name' => __("Image", 'virtue' ), 'value' => 'image', ), ), ), array( 'name' => __("Max Image/Slider Height", 'virtue' ), 'desc' => __("Default is: 400 <b>(Note: just input number, example: 350)</b>", 'virtue' ), 'id' => $prefix . 'posthead_height', 'type' => 'text_small', ), array( 'name' => __("Max Image/Slider Width", 'virtue' ), 'desc' => __("Default is: 770 or 1140 on fullwidth posts <b>(Note: just input number, example: 650, does not apply to carousel slider)</b>", 'virtue' ), 'id' => $prefix . 'posthead_width', 'type' => 'text_small', ), array( 'name' => __("Post Summary", 'virtue' ), 'desc' => '', 'id' => $prefix . 'post_summery', 'type' => 'select', 'options' => array( array( 'name' => __('Default', 'virtue' ), 'value' => 'default', ), array( 'name' => __('Text', 'virtue' ), 'value' => 'text', ), array( 'name' => __('Portrait Image', 'virtue'), 'value' => 'img_portrait', ), array( 'name' => __('Landscape Image', 'virtue'), 'value' => 'img_landscape', ), array( 'name' => __('Portrait Image Slider', 'virtue'), 'value' => 'slider_portrait', ), array( 'name' => __('Landscape Image Slider', 'virtue'), 'value' => 'slider_landscape', ), array( 'name' => __('Video', 'virtue'), 'value' => 'video', ), ), ), array( 'name' => __('Display Sidebar?', 'virtue'), 'desc' => __('Choose if layout is fullwidth or sidebar', 'virtue'), 'id' => $prefix . 'post_sidebar', 'type' => 'select', 'options' => array( array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ), array( 'name' => __('No', 'virtue'), 'value' => 'no', ), ), ), array( 'name' => __('Choose Sidebar', 'virtue'), 'desc' => '', 'id' => $prefix . 'sidebar_choice', 'type' => 'imag_select_sidebars', ), array( 'name' => __('Author Info', 'virtue'), 'desc' => __('Display an author info box?', 'virtue'), 'id' => $prefix . 'blog_author', 'type' => 'select', 'options' => array( array( 'name' => __('No', 'virtue'), 'value' => 'no', ), array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ), ), ), array( 'name' => __('Posts Carousel', 'virtue'), 'desc' => __('Display a carousel with similar or recent posts?', 'virtue'), 'id' => $prefix . 'blog_carousel_similar', 'type' => 'select', 'options' => array( array( 'name' => __('No', 'virtue'), 'value' => 'no', ), array( 'name' => __('Yes - Display Recent Posts', 'virtue'), 'value' => 'recent', ), array( 'name' => __('Yes - Display Similar Posts', 'virtue'), 'value' => 'similar', ) ), ), array( 'name' => __('Carousel Title', 'virtue'), 'desc' => __('ex. Similar Posts', 'virtue'), 'id' => $prefix . 'blog_carousel_title', 'type' => 'text_medium', ), ), ); $meta_boxes[] = array( 'id' => 'post_video_metabox', 'title' => __('Post Video Box', 'virtue'), 'pages' => array( 'post',), // Post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, 'fields' => array( array( 'name' => __('If Video Post', 'virtue'), 'desc' => __('Place Embed Code Here, works with youtube, vimeo...', 'virtue'), 'id' => $prefix . 'post_video', 'type' => 'textarea_code', ), ), ); $meta_boxes[] = array( 'id' => 'portfolio_post_metabox', 'title' => __('Portfolio Post Options', 'virtue'), 'pages' => array( 'portfolio' ), // Post type 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __('Project Layout', 'virtue'), 'desc' => '<a href="http://docs.kadencethemes.com/virtue/#portfolio_posts" target="_new" >Whats the difference?</a>', 'id' => $prefix . 'ppost_layout', 'type' => 'radio_inline', 'options' => array( array( 'name' => __('Beside', 'virtue'), 'value' => 'beside', ), array( 'name' => __('Above', 'virtue'), 'value' => 'above', ), array( 'name' => __('Three Rows', 'virtue'), 'value' => 'three', ), ), ), array( 'name' => __('Project Options', 'virtue'), 'desc' => '', 'id' => $prefix . 'ppost_type', 'type' => 'select', 'options' => array( array( 'name' => __('Image', 'virtue'), 'value' => 'image', ), array( 'name' => __('Image Slider', 'virtue'), 'value' => 'flex', ), array( 'name' => __('Carousel Slider', 'virtue'), 'value' => 'carousel', ), array( 'name' => __('Video', 'virtue'), 'value' => 'video', ), array( 'name' => __('None', 'virtue'), 'value' => 'none', ), ), ), array( 'name' => __("Max Image/Slider Height", 'virtue' ), 'desc' => __("Default is: 450 <b>(Note: just input number, example: 350)</b>", 'virtue' ), 'id' => $prefix . 'posthead_height', 'type' => 'text_small', ), array( 'name' => __("Max Image/Slider Width", 'virtue' ), 'desc' => __("Default is: 670 or 1140 on <b>above</b> or <b>three row</b> layouts (Note: just input number, example: 650)</b>", 'virtue' ), 'id' => $prefix . 'posthead_width', 'type' => 'text_small', ), array( 'name' => __('Value 01 Title', 'virtue'), 'desc' => __('ex. Project Type:', 'virtue'), 'id' => $prefix . 'project_val01_title', 'type' => 'text_medium', ), array( 'name' => __('Value 01 Description', 'virtue'), 'desc' => __('ex. Character Illustration', 'virtue'), 'id' => $prefix . 'project_val01_description', 'type' => 'text_medium', ), array( 'name' => __('Value 02 Title', 'virtue'), 'desc' => __('ex. Skills Needed:', 'virtue'), 'id' => $prefix . 'project_val02_title', 'type' => 'text_medium', ), array( 'name' => __('Value 02 Description', 'virtue'), 'desc' => __('ex. Photoshop, Illustrator', 'virtue'), 'id' => $prefix . 'project_val02_description', 'type' => 'text_medium', ), array( 'name' => __('Value 03 Title', 'virtue'), 'desc' => __('ex. Customer:', 'virtue'), 'id' => $prefix . 'project_val03_title', 'type' => 'text_medium', ), array( 'name' => __('Value 03 Description', 'virtue'), 'desc' => __('ex. Example Inc', 'virtue'), 'id' => $prefix . 'project_val03_description', 'type' => 'text_medium', ), array( 'name' => __('Value 04 Title', 'virtue'), 'desc' => __('ex. Project Year:', 'virtue'), 'id' => $prefix . 'project_val04_title', 'type' => 'text_medium', ), array( 'name' => __('Value 04 Description', 'virtue'), 'desc' => __('ex. 2013', 'virtue'), 'id' => $prefix . 'project_val04_description', 'type' => 'text_medium', ), array( 'name' => __('External Website', 'virtue'), 'desc' => __('ex. Website:', 'virtue'), 'id' => $prefix . 'project_val05_title', 'type' => 'text_medium', ), array( 'name' => __('Website Address', 'virtue'), 'desc' => __('ex. http://www.example.com', 'virtue'), 'id' => $prefix . 'project_val05_description', 'type' => 'text_medium', ), array( 'name' => __('If Video Project', 'virtue'), 'desc' => __('Place Embed Code Here, works with youtube, vimeo...', 'virtue'), 'id' => $prefix . 'post_video', 'type' => 'textarea_code', ), array( 'name' => __('Similar Portfolio Item Carousel', 'virtue'), 'desc' => __('Display a carousel with similar portfolio items below project?', 'virtue'), 'id' => $prefix . 'portfolio_carousel_recent', 'type' => 'select', 'options' => array( array( 'name' => __('No', 'virtue'), 'value' => 'no', ), array( 'name' => __('Yes - Display Recent Projects', 'virtue'), 'value' => 'recent', ), ), ), array( 'name' => __('Carousel Title', 'virtue'), 'desc' => __('ex. Similar Projects', 'virtue'), 'id' => $prefix . 'portfolio_carousel_title', 'type' => 'text_medium', ), ), ); $meta_boxes[] = array( 'id' => 'portfolio_metabox', 'title' => __('Portfolio Page Options', 'virtue'), 'pages' => array( 'page' ), // Post type 'show_on' => array('key' => 'page-template', 'value' => array( 'page-portfolio.php' )), 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __('Columns', 'virtue'), 'desc' => '', 'id' => $prefix . 'portfolio_columns', 'type' => 'select', 'options' => array( array( 'name' => __('Four Column', 'virtue'), 'value' => '4', ), array( 'name' => __('Three Column', 'virtue'), 'value' => '3', ), array( 'name' => __('Two Column', 'virtue'), 'value' => '2', ), ), ), array( 'name' => __('Portfolio Work Types', 'virtue'), 'desc' => '', 'id' => $prefix .'portfolio_type', 'type' => 'imag_select_taxonomy', 'taxonomy' => 'portfolio-type', ), array( 'name' => __('Order Items By', 'virtue'), 'desc' => '', 'id' => $prefix . 'portfolio_order', 'type' => 'select', 'options' => array( array( 'name' => __('Menu Order', 'virtue'), 'value' => 'menu_order', ), array( 'name' => __('Title', 'virtue'), 'value' => 'title', ), array( 'name' => __('Date', 'virtue'), 'value' => 'date', ), array( 'name' => __('Random', 'virtue'), 'value' => 'rand', ), ), ), array( 'name' => __('Items per Page', 'virtue'), 'desc' => __('How many portfolio items per page', 'virtue'), 'id' => $prefix . 'portfolio_items', 'type' => 'select', 'options' => array( array( 'name' => __('All', 'virtue'), 'value' => 'all', ), array( 'name' => '3', 'value' => '3', ), array( 'name' => '4', 'value' => '4', ), array( 'name' => '5', 'value' => '5', ), array( 'name' => '6', 'value' => '6', ), array( 'name' => '7', 'value' => '7', ), array( 'name' => '8', 'value' => '8', ), array( 'name' => '9', 'value' => '9', ), array( 'name' => '10', 'value' => '10', ), array( 'name' => '11', 'value' => '11', ), array( 'name' => '12', 'value' => '12', ), array( 'name' => '13', 'value' => '13', ), array( 'name' => '14', 'value' => '14', ), array( 'name' => '15', 'value' => '15', ), array( 'name' => '16', 'value' => '16', ), ), ), array( 'name' => __('Set image height', 'virtue'), 'desc' => __('Default is 1:1 ratio <b>(Note: just input number, example: 350)</b>', 'virtue'), 'id' => $prefix . 'portfolio_img_crop', 'type' => 'text_small', ), array( 'name' => __('Display Item Work Types', 'virtue'), 'desc' => '', 'id' => $prefix . 'portfolio_item_types', 'type' => 'checkbox', 'std' => '1' ), array( 'name' => __('Display Item Excerpt', 'virtue'), 'desc' => '', 'id' => $prefix . 'portfolio_item_excerpt', 'type' => 'checkbox', 'std' => '1' ), array( 'name' => __('Add Lightbox link in the top right of each item', 'virtue'), 'desc' => '', 'id' => $prefix . 'portfolio_lightbox', 'type' => 'select', 'options' => array( array( 'name' => __('No', 'virtue'), 'value' => 'no', ), array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ), ), ), )); $meta_boxes[] = array( 'id' => 'pagefeature_metabox', 'title' => __('Feature Page Options', 'virtue'), 'pages' => array( 'page' ), // Post type 'show_on' => array('key' => 'page-template', 'value' => array( 'page-feature.php', 'page-feature-sidebar.php')), 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __('Feature Options', 'virtue'), 'desc' => __('If image slider make sure images uploaded are at least 1140px wide.', 'virtue'), 'id' => $prefix . 'page_head', 'type' => 'select', 'options' => array( array( 'name' => __('Image Slider', 'virtue'), 'value' => 'flex', ), array( 'name' => __('Video', 'virtue'), 'value' => 'video', ), array( 'name' => __('Image', 'virtue'), 'value' => 'image', ), ), ), array( 'name' => __('Max Image/Slider Height', 'virtue'), 'desc' => __('Default is: 400 <b>(Note: just input number, example: 350)</b>', 'virtue'), 'id' => $prefix . 'posthead_height', 'type' => 'text_small', ), array( 'name' => __("Max Image/Slider Width", 'virtue' ), 'desc' => __("Default is: 1140 <b>(Note: just input number, example: 650, does not apply to Carousel slider)</b>", 'virtue' ), 'id' => $prefix . 'posthead_width', 'type' => 'text_small', ), array( 'name' => __('Use Lightbox for Feature Image', 'virtue'), 'desc' => __("If feature option is set to image, choose to use lightbox link with image.", 'virtue' ), 'id' => $prefix . 'feature_img_lightbox', 'type' => 'select', 'options' => array( array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ), array( 'name' => __('No', 'virtue'), 'value' => 'no', ), ), ), array( 'name' => __('If Video Post', 'virtue'), 'desc' => __('Place Embed Code Here, works with youtube, vimeo...', 'virtue'), 'id' => $prefix . 'post_video', 'type' => 'textarea_code', ), )); $meta_boxes[] = array( 'id' => 'bloglist_metabox', 'title' => __('Blog List Options', 'virtue'), 'pages' => array( 'page' ), // Post type 'show_on' => array('key' => 'page-template', 'value' => array( 'page-blog.php')), 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __('Blog Category', 'virtue'), 'desc' => __('Select all blog posts or a specific category to show', 'virtue'), 'id' => $prefix .'blog_cat', 'type' => 'imag_select_category', 'taxonomy' => 'category', ), array( 'name' => __('How Many Posts Per Page', 'virtue'), 'desc' => '', 'id' => $prefix . 'blog_items', 'type' => 'select', 'options' => array( array( 'name' => __('All', 'virtue'), 'value' => 'all', ), array( 'name' => '2', 'value' => '2', ), array( 'name' => '3', 'value' => '3', ), array( 'name' => '4', 'value' => '4', ), array( 'name' => '5', 'value' => '5', ), array( 'name' => '6', 'value' => '6', ), array( 'name' => '7', 'value' => '7', ), array( 'name' => '8', 'value' => '8', ), array( 'name' => '9', 'value' => '9', ), array( 'name' => '10', 'value' => '10', ), array( 'name' => '11', 'value' => '11', ), array( 'name' => '12', 'value' => '12', ), array( 'name' => '13', 'value' => '13', ), array( 'name' => '14', 'value' => '14', ), array( 'name' => '15', 'value' => '15', ), array( 'name' => '16', 'value' => '16', ), ), ), array( 'name' => __('Display Post Content as:', 'virtue'), 'desc' => '', 'id' => $prefix . 'blog_summery', 'type' => 'select', 'options' => array( array( 'name' => __('Summary', 'virtue'), 'value' => 'summery', ), array( 'name' => __('Full', 'virtue'), 'value' => 'full', ), ), ), array( 'name' => __('Display Sidebar?', 'virtue'), 'desc' => __('Choose if layout is fullwidth or sidebar', 'virtue'), 'id' => $prefix . 'page_sidebar', 'type' => 'select', 'options' => array( array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ), array( 'name' => __('No', 'virtue'), 'value' => 'no', ), ), ), array( 'name' => __('Choose Sidebar', 'virtue'), 'desc' => '', 'id' => $prefix . 'sidebar_choice', 'type' => 'imag_select_sidebars', ), )); $meta_boxes[] = array( 'id' => 'contact_metabox', 'title' => __('Contact Page Options', 'virtue'), 'pages' => array( 'page' ), // Post type 'show_on' => array('key' => 'page-template', 'value' => array( 'page-contact.php')), 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __('Use Contact Form', 'virtue'), 'desc' => '', 'id' => $prefix .'contact_form', 'type' => 'select', 'options' => array( array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ), array( 'name' => __('No', 'virtue'), 'value' => 'no', ), ), ), array( 'name' => __('Contact Form Title', 'virtue'), 'desc' => __('ex. Send us an Email', 'virtue'), 'id' => $prefix . 'contact_form_title', 'type' => 'text', ), array( 'name' => __('Use Map', 'virtue'), 'desc' => '', 'id' => $prefix .'contact_map', 'type' => 'select', 'options' => array( array( 'name' => __('No', 'virtue'), 'value' => 'no', ), array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ), ), ), array( 'name' => __('Address', 'virtue'), 'desc' => __('Enter your Location', 'virtue'), 'id' => $prefix . 'contact_address', 'type' => 'text', ), array( 'name' => __('Map Type', 'virtue'), 'desc' => '', 'id' => $prefix . 'contact_maptype', 'type' => 'select', 'options' => array( array( 'name' => __('ROADMAP', 'virtue'), 'value' => 'ROADMAP', ), array( 'name' => __('HYBRID', 'virtue'), 'value' => 'HYBRID', ), array( 'name' => __('TERRAIN', 'virtue'), 'value' => 'TERRAIN', ), array( 'name' => __('SATELLITE', 'virtue'), 'value' => 'SATELLITE', ), ), ), array( 'name' => __('Map Zoom Level', 'virtue'), 'desc' => __('A good place to start is 15', 'virtue'), 'id' => $prefix . 'contact_zoom', 'std' => '15', 'type' => 'select', 'options' => array( array( 'name' => __('1 (World View)', 'virtue'), 'value' => '1', ), array( 'name' => '2', 'value' => '2', ), array( 'name' => '3', 'value' => '3', ), array( 'name' => '4', 'value' => '4', ), array( 'name' => '5', 'value' => '5', ), array( 'name' => '6', 'value' => '6', ), array( 'name' => '7', 'value' => '7', ), array( 'name' => '8', 'value' => '8', ), array( 'name' => '9', 'value' => '9', ), array( 'name' => '10', 'value' => '10', ), array( 'name' => '11', 'value' => '11', ), array( 'name' => '12', 'value' => '12', ), array( 'name' => '13', 'value' => '13', ), array( 'name' => '14', 'value' => '14', ), array( 'name' => '15', 'value' => '15', ), array( 'name' => '16', 'value' => '16', ), array( 'name' => '17', 'value' => '17', ), array( 'name' => '18', 'value' => '18', ), array( 'name' => '19', 'value' => '19', ), array( 'name' => '20', 'value' => '20', ), array( 'name' => __('21 (Street View)', 'virtue'), 'value' => '21', ), ), ), array( 'name' => __('Map Height', 'virtue'), 'desc' => __('Default is 300', 'virtue'), 'id' => $prefix . 'contact_mapheight', 'type' => 'text_small', ), )); $meta_boxes[] = array( 'id' => 'page_sidebar', 'title' => __('Sidebar Options', 'virtue'), 'pages' => array( 'page' ), // Post type 'show_on' => array( 'key' => 'page-template', 'value' => array('page-sidebar.php','page-feature-sidebar.php')), 'context' => 'normal', 'priority' => 'high', 'show_names' => true, // Show field names on the left 'fields' => array( array( 'name' => __('Choose Sidebar', 'virtue'), 'desc' => '', 'id' => $prefix . 'sidebar_choice', 'type' => 'imag_select_sidebars', ), )); // Add other metaboxes as needed return $meta_boxes; } add_action( 'init', 'initialize_showcase_meta_boxes', 9999 ); /** * Initialize the metabox class. */ function initialize_showcase_meta_boxes() { if ( ! class_exists( 'cmb_Meta_Box' ) ) require_once 'cmb/init.php'; }
pcostan/mscm
wp-content/themes/virtue/lib/metaboxes.php
PHP
gpl-2.0
24,075
import numpy as np from collections import namedtuple import interp epi0 = 1. # Epsilon0 Species = namedtuple("Species", ["q", "m", "N", "x0", "vx0", "vy0"]) __cache_one_d_poisson = {} def one_d_poisson(n): if n in __cache_one_d_poisson: return __cache_one_d_poisson[n] a = np.zeros((n,n)) np.fill_diagonal(a, -2.) np.fill_diagonal(a[:-1,1:], 1.) np.fill_diagonal(a[1:,:-1], 1.) __cache_one_d_poisson[n] = a return a # Dict of solver functions with string keys __solver = {} def poisson_solve_fd(b, dx): """ Assume V0=0 """ nx = len(b) A = one_d_poisson(nx-1) p = -b*(dx**2) x = np.zeros_like(p) x[1:] = np.linalg.solve(A, p[1:]) return x __solver["FD"] = poisson_solve_fd def poisson_solve_fft(rho, dx): nx = len(rho) rhok = np.fft.fft(rho) k = np.fft.fftfreq(nx)*2*np.pi/dx kd = (k[1:]**2)*(np.sin(k[1:]*dx/2.)/(k[1:]*dx/2))**2 phik = np.zeros_like(rhok) phik[1:] = rhok[1:]/kd sol = np.real(np.fft.ifft(phik)) return sol __solver["FFT"] = poisson_solve_fft def poisson_solve(b, dx, method="FFT"): if method in __solver: return __solver[method](b, dx) else: return method(b, dx) # Dicts of weight/interp functions with string keys __weight = {} __interp = {} __weight["CIC"] = interp.weight_cic def interp_cic(E, xp, nx, L): """ Interpolate E to particle positions (CIC) """ xps = xp*nx/L left = np.floor(xps).astype(np.int) right = np.mod(np.ceil(xps), nx).astype(np.int) E_interp = E[left]*(left+1-xps) + E[right]*(xps-left) return E_interp __interp["CIC"] = interp_cic def weight_ngp(xp, q, nx, L): """ Weighting to grid (NGP) """ rho = np.zeros(nx) xps = np.round(xp*nx/L).astype(np.int) xps[xps==nx] = 0 for i in xrange(len(xps)): rho[xps[i]] += q[i] return rho __weight["NGP"] = weight_ngp def interp_ngp(E, xp, nx, L): """ Interpolate E to particle positions (NGP) """ xps = np.round(xp*nx/L).astype(np.int) xps[xps==nx] = 0 return E[xps] __interp["NGP"] = interp_ngp def weight(xp, q, nx, L, method="CIC"): if method in __weight: dx = L/nx return __weight[method](xp, q, nx, L) else: return method(xp, q, nx, L) def interp(E, xp, nx, L, method="CIC"): if method in __interp: return __interp[method](E, xp, nx, L) else: return method(E, xp, nx, L) def calc_E(phi, dx): """ Calc E at the particle positions Centered difference (second order) """ E = np.zeros_like(phi) E[1:-1] = -(phi[2:]-phi[:-2]) E[0] = -(phi[1]-phi[-1]) E[-1] = -(phi[0]-phi[-2]) return E/(2*dx) def accel(vx, vy, E, alpha, dt): """ Accel in place """ vx[:] = vx + alpha*E*dt/2. # vy is unchanged def rotate(vx, vy, wc, dt): """ Rotate in place """ c = np.cos(wc*dt) s = np.sin(wc*dt) vx_new = c*vx + s*vy vy_new = -s*vx + c*vy vx[:] = vx_new vy[:] = vy_new def normalize(x, L): """ Keep x in [0,L), assuming a periodic domain """ # The order here is significant because of rounding # If x<0 is very close to 0, then float(x+L)=L while len(x[x<0])>0 or len(x[x>=L])>0: x[x<0] = x[x<0] + L x[x>=L] = x[x>=L] - L def move(xp, vx, vy, dt, L, do_move=None): """ Move in place """ if do_move is None: xp[:] = xp + dt*vx else: xp[do_move] = xp[do_move] + dt*vx[do_move] normalize(xp, L) def pic(species, nx, dx, nt, dt, L, B0, solver_method="FFT", weight_method="CIC", interp_method="CIC"): N = 0 for s in species: N += s.N q, qm, wc, xp, vx, vy = [np.zeros(N) for _ in range(6)] do_move = np.ndarray((N,), dtype=np.bool) do_move[:] = False count = 0 # Trailing count for s in species: q[count:count+s.N] = s.q qm[count:count+s.N] = s.q/s.m wc[count:count+s.N] = (s.q/s.m)*B0 xp[count:count+s.N] = s.x0 vx[count:count+s.N] = s.vx0 vy[count:count+s.N] = s.vy0 do_move[count:count+s.N] = s.m>0 count += s.N # store the results at each time step xpa = np.zeros((nt+1, N)) vxa = np.zeros((nt+1, N)) vya = np.zeros((nt+1, N)) Ea = np.zeros((nt+1, nx)) phia = np.zeros((nt+1, nx)) rhoa = np.zeros((nt+1, nx)) # Main solution loop # Init half step back rho = weight(xp, q, nx, L, method=weight_method)/dx phi = poisson_solve(rho/epi0, dx, method=solver_method) E0 = calc_E(phi, dx) E = interp(E0, xp, nx, L, method=interp_method) rotate(vx, vy, -wc, dt) accel(vx, vy, E, -qm, dt) xpa[0], vxa[0], vya[0] = xp, vx, vy Ea[0], phia[0], rhoa[0] = E0, phi, rho for i in range(1, nt+1): # Update velocity accel(vx, vy, E, qm, dt) rotate(vx, vy, wc, dt) accel(vx, vy, E, qm, dt) # Update position move(xp, vx, vy, dt, L, do_move=do_move) rho = weight(xp, q, nx, L, method=weight_method)/dx phi = poisson_solve(rho/epi0, dx, method=solver_method) E0 = calc_E(phi, dx) E = interp(E0, xp, nx, L, method=interp_method) xpa[i], vxa[i], vya[i] = xp, vx, vy Ea[i], phia[i], rhoa[i] = E0, phi, rho return (xpa, vxa, vya, Ea, phia, rhoa)
shigh/pyes1
pyes1/pic1d2v.py
Python
gpl-2.0
5,516
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2017 Michael Zanetti <michael.zanetti@guh.io> * * * * This file is part of guh. * * * * Guh 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. * * * * Guh 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 guh. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef JANUSCONNECTOR_H #define JANUSCONNECTOR_H #include <QObject> #include <QLocalSocket> #include <QTimer> class JanusConnector : public QObject { Q_OBJECT public: class WebRtcSession { public: QString sessionId; // This should be unique but persistent for each remote device qint64 janusSessionId = -1; // the session id for the janus session. qint64 janusChannelId = -1; bool connectedToJanus = false; QVariantMap offer; bool offerSent = false; QVariantList trickles; QVariantMap webRtcUp; bool webRtcConnected = false; bool matchJanusSessionId(qint64 id) { return (janusSessionId == id) || (janusSessionId == id +1) || (janusSessionId == id -1); } }; explicit JanusConnector(QObject *parent = nullptr); void sendWebRtcHandshakeMessage(const QString &sessionId, const QVariantMap &message); bool sendKeepAliveMessage(const QString &sessionId); signals: void connected(); void webRtcHandshakeMessageReceived(const QString &sessionId, const QVariantMap &message); private slots: void onDisconnected(); void onError(QLocalSocket::LocalSocketError socketError); void onReadyRead(); void heartbeat(); void processQueue(); private: QHash<QString, WebRtcSession*> m_pendingRequests; bool connectToJanus(); void createSession(WebRtcSession *session); void createChannel(WebRtcSession *session); void writeToJanus(const QByteArray &data); private: QLocalSocket *m_socket = nullptr; QHash<QString, WebRtcSession*> m_sessions; QStringList m_wantedAcks; }; QDebug operator<<(QDebug debug, const JanusConnector::WebRtcSession &session); QDebug operator<<(QDebug debug, JanusConnector::WebRtcSession *session); #endif // JANUSCONNECTOR_H
guh/guh
libguh-core/janusconnector.h
C
gpl-2.0
3,301
package com.kamildanak.minecraft.safe.init; import com.kamildanak.minecraft.safe.block.BlockSafe; import net.minecraft.block.Block; import net.minecraft.block.material.Material; public class SafeBlocks { public static final BlockSafe SAFE; static final Block[] BLOCKS; static { SAFE = new BlockSafe("safe", Material.GLASS); BLOCKS = new Block[]{SAFE}; } }
kamilx3/Safe
src/main/java/com/kamildanak/minecraft/safe/init/SafeBlocks.java
Java
gpl-2.0
391
'use strict'; angular.module('<%=project.name.a()%>App') .config(function ($stateProvider) { $stateProvider .state('entity', { abstract: true, parent: 'site' }); });
gen-js-bundles/angularjs-springboot-mongodb
templates/{srcWeb}/scripts/app/entities/entity.js
JavaScript
gpl-2.0
239
/* * fs/f2fs/data.c * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * http://www.samsung.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. */ #include <linux/fs.h> #include <linux/f2fs_fs.h> #include <linux/buffer_head.h> #include <linux/mpage.h> #include <linux/aio.h> #include <linux/writeback.h> #include <linux/backing-dev.h> #include <linux/blkdev.h> #include <linux/bio.h> #include <linux/prefetch.h> #include <linux/uio.h> #include <linux/cleancache.h> #include "f2fs.h" #include "node.h" #include "segment.h" #include "trace.h" #include <trace/events/f2fs.h> static struct kmem_cache *extent_tree_slab; static struct kmem_cache *extent_node_slab; static void f2fs_read_end_io(struct bio *bio, int err) { struct bio_vec *bvec; int i; if (f2fs_bio_encrypted(bio)) { if (err) { f2fs_release_crypto_ctx(bio->bi_private); } else { f2fs_end_io_crypto_work(bio->bi_private, bio); return; } } __bio_for_each_segment(bvec, bio, i, 0) { struct page *page = bvec->bv_page; if (!err) { SetPageUptodate(page); } else { ClearPageUptodate(page); SetPageError(page); } unlock_page(page); } bio_put(bio); } static void f2fs_write_end_io(struct bio *bio, int err) { struct f2fs_sb_info *sbi = bio->bi_private; struct bio_vec *bvec; int i; __bio_for_each_segment(bvec, bio, i, 0) { struct page *page = bvec->bv_page; f2fs_restore_and_release_control_page(&page); if (unlikely(err)) { set_page_dirty(page); set_bit(AS_EIO, &page->mapping->flags); f2fs_stop_checkpoint(sbi); } end_page_writeback(page); dec_page_count(sbi, F2FS_WRITEBACK); } if (!get_pages(sbi, F2FS_WRITEBACK) && !list_empty(&sbi->cp_wait.task_list)) wake_up(&sbi->cp_wait); bio_put(bio); } /* * Low-level block read/write IO operations. */ static struct bio *__bio_alloc(struct f2fs_sb_info *sbi, block_t blk_addr, int npages, bool is_read) { struct bio *bio; /* No failure on bio allocation */ bio = bio_alloc(GFP_NOIO, npages); bio->bi_bdev = sbi->sb->s_bdev; bio->bi_sector = SECTOR_FROM_BLOCK(blk_addr); bio->bi_end_io = is_read ? f2fs_read_end_io : f2fs_write_end_io; bio->bi_private = is_read ? NULL : sbi; return bio; } static void __submit_merged_bio(struct f2fs_bio_info *io) { struct f2fs_io_info *fio = &io->fio; if (!io->bio) return; if (is_read_io(fio->rw)) trace_f2fs_submit_read_bio(io->sbi->sb, fio, io->bio); else trace_f2fs_submit_write_bio(io->sbi->sb, fio, io->bio); submit_bio(fio->rw, io->bio); io->bio = NULL; } void f2fs_submit_merged_bio(struct f2fs_sb_info *sbi, enum page_type type, int rw) { enum page_type btype = PAGE_TYPE_OF_BIO(type); struct f2fs_bio_info *io; io = is_read_io(rw) ? &sbi->read_io : &sbi->write_io[btype]; down_write(&io->io_rwsem); /* change META to META_FLUSH in the checkpoint procedure */ if (type >= META_FLUSH) { io->fio.type = META_FLUSH; if (test_opt(sbi, NOBARRIER)) io->fio.rw = WRITE_FLUSH | REQ_META | REQ_PRIO; else io->fio.rw = WRITE_FLUSH_FUA | REQ_META | REQ_PRIO; } __submit_merged_bio(io); up_write(&io->io_rwsem); } /* * Fill the locked page with data located in the block address. * Return unlocked page. */ int f2fs_submit_page_bio(struct f2fs_io_info *fio) { struct bio *bio; struct page *page = fio->encrypted_page ? fio->encrypted_page : fio->page; trace_f2fs_submit_page_bio(page, fio); f2fs_trace_ios(fio, 0); /* Allocate a new bio */ bio = __bio_alloc(fio->sbi, fio->blk_addr, 1, is_read_io(fio->rw)); if (bio_add_page(bio, page, PAGE_CACHE_SIZE, 0) < PAGE_CACHE_SIZE) { bio_put(bio); f2fs_put_page(page, 1); return -EFAULT; } submit_bio(fio->rw, bio); return 0; } void f2fs_submit_page_mbio(struct f2fs_io_info *fio) { struct f2fs_sb_info *sbi = fio->sbi; enum page_type btype = PAGE_TYPE_OF_BIO(fio->type); struct f2fs_bio_info *io; bool is_read = is_read_io(fio->rw); struct page *bio_page; io = is_read ? &sbi->read_io : &sbi->write_io[btype]; verify_block_addr(sbi, fio->blk_addr); down_write(&io->io_rwsem); if (!is_read) inc_page_count(sbi, F2FS_WRITEBACK); if (io->bio && (io->last_block_in_bio != fio->blk_addr - 1 || io->fio.rw != fio->rw)) __submit_merged_bio(io); alloc_new: if (io->bio == NULL) { int bio_blocks = MAX_BIO_BLOCKS(sbi); io->bio = __bio_alloc(sbi, fio->blk_addr, bio_blocks, is_read); io->fio = *fio; } bio_page = fio->encrypted_page ? fio->encrypted_page : fio->page; if (bio_add_page(io->bio, bio_page, PAGE_CACHE_SIZE, 0) < PAGE_CACHE_SIZE) { __submit_merged_bio(io); goto alloc_new; } io->last_block_in_bio = fio->blk_addr; f2fs_trace_ios(fio, 0); up_write(&io->io_rwsem); trace_f2fs_submit_page_mbio(fio->page, fio); } /* * Lock ordering for the change of data block address: * ->data_page * ->node_page * update block addresses in the node page */ void set_data_blkaddr(struct dnode_of_data *dn) { struct f2fs_node *rn; __le32 *addr_array; struct page *node_page = dn->node_page; unsigned int ofs_in_node = dn->ofs_in_node; f2fs_wait_on_page_writeback(node_page, NODE); rn = F2FS_NODE(node_page); /* Get physical address of data block */ addr_array = blkaddr_in_node(rn); addr_array[ofs_in_node] = cpu_to_le32(dn->data_blkaddr); set_page_dirty(node_page); } int reserve_new_block(struct dnode_of_data *dn) { struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode); if (unlikely(is_inode_flag_set(F2FS_I(dn->inode), FI_NO_ALLOC))) return -EPERM; if (unlikely(!inc_valid_block_count(sbi, dn->inode, 1))) return -ENOSPC; trace_f2fs_reserve_new_block(dn->inode, dn->nid, dn->ofs_in_node); dn->data_blkaddr = NEW_ADDR; set_data_blkaddr(dn); mark_inode_dirty(dn->inode); sync_inode_page(dn); return 0; } int f2fs_reserve_block(struct dnode_of_data *dn, pgoff_t index) { bool need_put = dn->inode_page ? false : true; int err; err = get_dnode_of_data(dn, index, ALLOC_NODE); if (err) return err; if (dn->data_blkaddr == NULL_ADDR) err = reserve_new_block(dn); if (err || need_put) f2fs_put_dnode(dn); return err; } static bool lookup_extent_info(struct inode *inode, pgoff_t pgofs, struct extent_info *ei) { struct f2fs_inode_info *fi = F2FS_I(inode); pgoff_t start_fofs, end_fofs; block_t start_blkaddr; read_lock(&fi->ext_lock); if (fi->ext.len == 0) { read_unlock(&fi->ext_lock); return false; } stat_inc_total_hit(inode->i_sb); start_fofs = fi->ext.fofs; end_fofs = fi->ext.fofs + fi->ext.len - 1; start_blkaddr = fi->ext.blk; if (pgofs >= start_fofs && pgofs <= end_fofs) { *ei = fi->ext; stat_inc_read_hit(inode->i_sb); read_unlock(&fi->ext_lock); return true; } read_unlock(&fi->ext_lock); return false; } static bool update_extent_info(struct inode *inode, pgoff_t fofs, block_t blkaddr) { struct f2fs_inode_info *fi = F2FS_I(inode); pgoff_t start_fofs, end_fofs; block_t start_blkaddr, end_blkaddr; int need_update = true; write_lock(&fi->ext_lock); start_fofs = fi->ext.fofs; end_fofs = fi->ext.fofs + fi->ext.len - 1; start_blkaddr = fi->ext.blk; end_blkaddr = fi->ext.blk + fi->ext.len - 1; /* Drop and initialize the matched extent */ if (fi->ext.len == 1 && fofs == start_fofs) fi->ext.len = 0; /* Initial extent */ if (fi->ext.len == 0) { if (blkaddr != NULL_ADDR) { fi->ext.fofs = fofs; fi->ext.blk = blkaddr; fi->ext.len = 1; } goto end_update; } /* Front merge */ if (fofs == start_fofs - 1 && blkaddr == start_blkaddr - 1) { fi->ext.fofs--; fi->ext.blk--; fi->ext.len++; goto end_update; } /* Back merge */ if (fofs == end_fofs + 1 && blkaddr == end_blkaddr + 1) { fi->ext.len++; goto end_update; } /* Split the existing extent */ if (fi->ext.len > 1 && fofs >= start_fofs && fofs <= end_fofs) { if ((end_fofs - fofs) < (fi->ext.len >> 1)) { fi->ext.len = fofs - start_fofs; } else { fi->ext.fofs = fofs + 1; fi->ext.blk = start_blkaddr + fofs - start_fofs + 1; fi->ext.len -= fofs - start_fofs + 1; } } else { need_update = false; } /* Finally, if the extent is very fragmented, let's drop the cache. */ if (fi->ext.len < F2FS_MIN_EXTENT_LEN) { fi->ext.len = 0; set_inode_flag(fi, FI_NO_EXTENT); need_update = true; } end_update: write_unlock(&fi->ext_lock); return need_update; } static struct extent_node *__attach_extent_node(struct f2fs_sb_info *sbi, struct extent_tree *et, struct extent_info *ei, struct rb_node *parent, struct rb_node **p) { struct extent_node *en; en = kmem_cache_alloc(extent_node_slab, GFP_ATOMIC); if (!en) return NULL; en->ei = *ei; INIT_LIST_HEAD(&en->list); rb_link_node(&en->rb_node, parent, p); rb_insert_color(&en->rb_node, &et->root); et->count++; atomic_inc(&sbi->total_ext_node); return en; } static void __detach_extent_node(struct f2fs_sb_info *sbi, struct extent_tree *et, struct extent_node *en) { rb_erase(&en->rb_node, &et->root); et->count--; atomic_dec(&sbi->total_ext_node); if (et->cached_en == en) et->cached_en = NULL; } static struct extent_tree *__find_extent_tree(struct f2fs_sb_info *sbi, nid_t ino) { struct extent_tree *et; down_read(&sbi->extent_tree_lock); et = radix_tree_lookup(&sbi->extent_tree_root, ino); if (!et) { up_read(&sbi->extent_tree_lock); return NULL; } atomic_inc(&et->refcount); up_read(&sbi->extent_tree_lock); return et; } static struct extent_tree *__grab_extent_tree(struct inode *inode) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct extent_tree *et; nid_t ino = inode->i_ino; down_write(&sbi->extent_tree_lock); et = radix_tree_lookup(&sbi->extent_tree_root, ino); if (!et) { et = f2fs_kmem_cache_alloc(extent_tree_slab, GFP_NOFS); f2fs_radix_tree_insert(&sbi->extent_tree_root, ino, et); memset(et, 0, sizeof(struct extent_tree)); et->ino = ino; et->root = RB_ROOT; et->cached_en = NULL; rwlock_init(&et->lock); atomic_set(&et->refcount, 0); et->count = 0; sbi->total_ext_tree++; } atomic_inc(&et->refcount); up_write(&sbi->extent_tree_lock); return et; } static struct extent_node *__lookup_extent_tree(struct extent_tree *et, unsigned int fofs) { struct rb_node *node = et->root.rb_node; struct extent_node *en; if (et->cached_en) { struct extent_info *cei = &et->cached_en->ei; if (cei->fofs <= fofs && cei->fofs + cei->len > fofs) return et->cached_en; } while (node) { en = rb_entry(node, struct extent_node, rb_node); if (fofs < en->ei.fofs) { node = node->rb_left; } else if (fofs >= en->ei.fofs + en->ei.len) { node = node->rb_right; } else { et->cached_en = en; return en; } } return NULL; } static struct extent_node *__try_back_merge(struct f2fs_sb_info *sbi, struct extent_tree *et, struct extent_node *en) { struct extent_node *prev; struct rb_node *node; node = rb_prev(&en->rb_node); if (!node) return NULL; prev = rb_entry(node, struct extent_node, rb_node); if (__is_back_mergeable(&en->ei, &prev->ei)) { en->ei.fofs = prev->ei.fofs; en->ei.blk = prev->ei.blk; en->ei.len += prev->ei.len; __detach_extent_node(sbi, et, prev); return prev; } return NULL; } static struct extent_node *__try_front_merge(struct f2fs_sb_info *sbi, struct extent_tree *et, struct extent_node *en) { struct extent_node *next; struct rb_node *node; node = rb_next(&en->rb_node); if (!node) return NULL; next = rb_entry(node, struct extent_node, rb_node); if (__is_front_mergeable(&en->ei, &next->ei)) { en->ei.len += next->ei.len; __detach_extent_node(sbi, et, next); return next; } return NULL; } static struct extent_node *__insert_extent_tree(struct f2fs_sb_info *sbi, struct extent_tree *et, struct extent_info *ei, struct extent_node **den) { struct rb_node **p = &et->root.rb_node; struct rb_node *parent = NULL; struct extent_node *en; while (*p) { parent = *p; en = rb_entry(parent, struct extent_node, rb_node); if (ei->fofs < en->ei.fofs) { if (__is_front_mergeable(ei, &en->ei)) { f2fs_bug_on(sbi, !den); en->ei.fofs = ei->fofs; en->ei.blk = ei->blk; en->ei.len += ei->len; *den = __try_back_merge(sbi, et, en); return en; } p = &(*p)->rb_left; } else if (ei->fofs >= en->ei.fofs + en->ei.len) { if (__is_back_mergeable(ei, &en->ei)) { f2fs_bug_on(sbi, !den); en->ei.len += ei->len; *den = __try_front_merge(sbi, et, en); return en; } p = &(*p)->rb_right; } else { f2fs_bug_on(sbi, 1); } } return __attach_extent_node(sbi, et, ei, parent, p); } static unsigned int __free_extent_tree(struct f2fs_sb_info *sbi, struct extent_tree *et, bool free_all) { struct rb_node *node, *next; struct extent_node *en; unsigned int count = et->count; node = rb_first(&et->root); while (node) { next = rb_next(node); en = rb_entry(node, struct extent_node, rb_node); if (free_all) { spin_lock(&sbi->extent_lock); if (!list_empty(&en->list)) list_del_init(&en->list); spin_unlock(&sbi->extent_lock); } if (free_all || list_empty(&en->list)) { __detach_extent_node(sbi, et, en); kmem_cache_free(extent_node_slab, en); } node = next; } return count - et->count; } static void f2fs_init_extent_tree(struct inode *inode, struct f2fs_extent *i_ext) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct extent_tree *et; struct extent_node *en; struct extent_info ei; if (le32_to_cpu(i_ext->len) < F2FS_MIN_EXTENT_LEN) return; et = __grab_extent_tree(inode); write_lock(&et->lock); if (et->count) goto out; set_extent_info(&ei, le32_to_cpu(i_ext->fofs), le32_to_cpu(i_ext->blk), le32_to_cpu(i_ext->len)); en = __insert_extent_tree(sbi, et, &ei, NULL); if (en) { et->cached_en = en; spin_lock(&sbi->extent_lock); list_add_tail(&en->list, &sbi->extent_list); spin_unlock(&sbi->extent_lock); } out: write_unlock(&et->lock); atomic_dec(&et->refcount); } static bool f2fs_lookup_extent_tree(struct inode *inode, pgoff_t pgofs, struct extent_info *ei) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct extent_tree *et; struct extent_node *en; trace_f2fs_lookup_extent_tree_start(inode, pgofs); et = __find_extent_tree(sbi, inode->i_ino); if (!et) return false; read_lock(&et->lock); en = __lookup_extent_tree(et, pgofs); if (en) { *ei = en->ei; spin_lock(&sbi->extent_lock); if (!list_empty(&en->list)) list_move_tail(&en->list, &sbi->extent_list); spin_unlock(&sbi->extent_lock); stat_inc_read_hit(sbi->sb); } stat_inc_total_hit(sbi->sb); read_unlock(&et->lock); trace_f2fs_lookup_extent_tree_end(inode, pgofs, en); atomic_dec(&et->refcount); return en ? true : false; } static void f2fs_update_extent_tree(struct inode *inode, pgoff_t fofs, block_t blkaddr) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct extent_tree *et; struct extent_node *en = NULL, *en1 = NULL, *en2 = NULL, *en3 = NULL; struct extent_node *den = NULL; struct extent_info ei, dei; unsigned int endofs; trace_f2fs_update_extent_tree(inode, fofs, blkaddr); et = __grab_extent_tree(inode); write_lock(&et->lock); /* 1. lookup and remove existing extent info in cache */ en = __lookup_extent_tree(et, fofs); if (!en) goto update_extent; dei = en->ei; __detach_extent_node(sbi, et, en); /* 2. if extent can be split more, split and insert the left part */ if (dei.len > 1) { /* insert left part of split extent into cache */ if (fofs - dei.fofs >= F2FS_MIN_EXTENT_LEN) { set_extent_info(&ei, dei.fofs, dei.blk, fofs - dei.fofs); en1 = __insert_extent_tree(sbi, et, &ei, NULL); } /* insert right part of split extent into cache */ endofs = dei.fofs + dei.len - 1; if (endofs - fofs >= F2FS_MIN_EXTENT_LEN) { set_extent_info(&ei, fofs + 1, fofs - dei.fofs + dei.blk, endofs - fofs); en2 = __insert_extent_tree(sbi, et, &ei, NULL); } } update_extent: /* 3. update extent in extent cache */ if (blkaddr) { set_extent_info(&ei, fofs, blkaddr, 1); en3 = __insert_extent_tree(sbi, et, &ei, &den); } /* 4. update in global extent list */ spin_lock(&sbi->extent_lock); if (en && !list_empty(&en->list)) list_del(&en->list); /* * en1 and en2 split from en, they will become more and more smaller * fragments after splitting several times. So if the length is smaller * than F2FS_MIN_EXTENT_LEN, we will not add them into extent tree. */ if (en1) list_add_tail(&en1->list, &sbi->extent_list); if (en2) list_add_tail(&en2->list, &sbi->extent_list); if (en3) { if (list_empty(&en3->list)) list_add_tail(&en3->list, &sbi->extent_list); else list_move_tail(&en3->list, &sbi->extent_list); } if (den && !list_empty(&den->list)) list_del(&den->list); spin_unlock(&sbi->extent_lock); /* 5. release extent node */ if (en) kmem_cache_free(extent_node_slab, en); if (den) kmem_cache_free(extent_node_slab, den); write_unlock(&et->lock); atomic_dec(&et->refcount); } void f2fs_preserve_extent_tree(struct inode *inode) { struct extent_tree *et; struct extent_info *ext = &F2FS_I(inode)->ext; bool sync = false; if (!test_opt(F2FS_I_SB(inode), EXTENT_CACHE)) return; et = __find_extent_tree(F2FS_I_SB(inode), inode->i_ino); if (!et) { if (ext->len) { ext->len = 0; update_inode_page(inode); } return; } read_lock(&et->lock); if (et->count) { struct extent_node *en; if (et->cached_en) { en = et->cached_en; } else { struct rb_node *node = rb_first(&et->root); if (!node) node = rb_last(&et->root); en = rb_entry(node, struct extent_node, rb_node); } if (__is_extent_same(ext, &en->ei)) goto out; *ext = en->ei; sync = true; } else if (ext->len) { ext->len = 0; sync = true; } out: read_unlock(&et->lock); atomic_dec(&et->refcount); if (sync) update_inode_page(inode); } void f2fs_shrink_extent_tree(struct f2fs_sb_info *sbi, int nr_shrink) { struct extent_tree *treevec[EXT_TREE_VEC_SIZE]; struct extent_node *en, *tmp; unsigned long ino = F2FS_ROOT_INO(sbi); struct radix_tree_iter iter; void **slot; unsigned int found; unsigned int node_cnt = 0, tree_cnt = 0; if (!test_opt(sbi, EXTENT_CACHE)) return; if (available_free_memory(sbi, EXTENT_CACHE)) return; spin_lock(&sbi->extent_lock); list_for_each_entry_safe(en, tmp, &sbi->extent_list, list) { if (!nr_shrink--) break; list_del_init(&en->list); } spin_unlock(&sbi->extent_lock); down_read(&sbi->extent_tree_lock); while ((found = radix_tree_gang_lookup(&sbi->extent_tree_root, (void **)treevec, ino, EXT_TREE_VEC_SIZE))) { unsigned i; ino = treevec[found - 1]->ino + 1; for (i = 0; i < found; i++) { struct extent_tree *et = treevec[i]; atomic_inc(&et->refcount); write_lock(&et->lock); node_cnt += __free_extent_tree(sbi, et, false); write_unlock(&et->lock); atomic_dec(&et->refcount); } } up_read(&sbi->extent_tree_lock); down_write(&sbi->extent_tree_lock); radix_tree_for_each_slot(slot, &sbi->extent_tree_root, &iter, F2FS_ROOT_INO(sbi)) { struct extent_tree *et = (struct extent_tree *)*slot; if (!atomic_read(&et->refcount) && !et->count) { radix_tree_delete(&sbi->extent_tree_root, et->ino); kmem_cache_free(extent_tree_slab, et); sbi->total_ext_tree--; tree_cnt++; } } up_write(&sbi->extent_tree_lock); trace_f2fs_shrink_extent_tree(sbi, node_cnt, tree_cnt); } void f2fs_destroy_extent_tree(struct inode *inode) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct extent_tree *et; unsigned int node_cnt = 0; if (!test_opt(sbi, EXTENT_CACHE)) return; et = __find_extent_tree(sbi, inode->i_ino); if (!et) goto out; /* free all extent info belong to this extent tree */ write_lock(&et->lock); node_cnt = __free_extent_tree(sbi, et, true); write_unlock(&et->lock); atomic_dec(&et->refcount); /* try to find and delete extent tree entry in radix tree */ down_write(&sbi->extent_tree_lock); et = radix_tree_lookup(&sbi->extent_tree_root, inode->i_ino); if (!et) { up_write(&sbi->extent_tree_lock); goto out; } f2fs_bug_on(sbi, atomic_read(&et->refcount) || et->count); radix_tree_delete(&sbi->extent_tree_root, inode->i_ino); kmem_cache_free(extent_tree_slab, et); sbi->total_ext_tree--; up_write(&sbi->extent_tree_lock); out: trace_f2fs_destroy_extent_tree(inode, node_cnt); return; } void f2fs_init_extent_cache(struct inode *inode, struct f2fs_extent *i_ext) { if (test_opt(F2FS_I_SB(inode), EXTENT_CACHE)) f2fs_init_extent_tree(inode, i_ext); write_lock(&F2FS_I(inode)->ext_lock); get_extent_info(&F2FS_I(inode)->ext, *i_ext); write_unlock(&F2FS_I(inode)->ext_lock); } static bool f2fs_lookup_extent_cache(struct inode *inode, pgoff_t pgofs, struct extent_info *ei) { if (is_inode_flag_set(F2FS_I(inode), FI_NO_EXTENT)) return false; if (test_opt(F2FS_I_SB(inode), EXTENT_CACHE)) return f2fs_lookup_extent_tree(inode, pgofs, ei); return lookup_extent_info(inode, pgofs, ei); } void f2fs_update_extent_cache(struct dnode_of_data *dn) { struct f2fs_inode_info *fi = F2FS_I(dn->inode); pgoff_t fofs; f2fs_bug_on(F2FS_I_SB(dn->inode), dn->data_blkaddr == NEW_ADDR); if (is_inode_flag_set(fi, FI_NO_EXTENT)) return; fofs = start_bidx_of_node(ofs_of_node(dn->node_page), fi) + dn->ofs_in_node; if (test_opt(F2FS_I_SB(dn->inode), EXTENT_CACHE)) return f2fs_update_extent_tree(dn->inode, fofs, dn->data_blkaddr); if (update_extent_info(dn->inode, fofs, dn->data_blkaddr)) sync_inode_page(dn); } struct page *get_read_data_page(struct inode *inode, pgoff_t index, int rw) { struct address_space *mapping = inode->i_mapping; struct dnode_of_data dn; struct page *page; struct extent_info ei; int err; struct f2fs_io_info fio = { .sbi = F2FS_I_SB(inode), .type = DATA, .rw = rw, .encrypted_page = NULL, }; if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode)) return read_mapping_page(mapping, index, NULL); page = grab_cache_page(mapping, index); if (!page) return ERR_PTR(-ENOMEM); if (f2fs_lookup_extent_cache(inode, index, &ei)) { dn.data_blkaddr = ei.blk + index - ei.fofs; goto got_it; } set_new_dnode(&dn, inode, NULL, NULL, 0); err = get_dnode_of_data(&dn, index, LOOKUP_NODE); if (err) { f2fs_put_page(page, 1); return ERR_PTR(err); } f2fs_put_dnode(&dn); if (unlikely(dn.data_blkaddr == NULL_ADDR)) { f2fs_put_page(page, 1); return ERR_PTR(-ENOENT); } got_it: if (PageUptodate(page)) { unlock_page(page); return page; } /* * A new dentry page is allocated but not able to be written, since its * new inode page couldn't be allocated due to -ENOSPC. * In such the case, its blkaddr can be remained as NEW_ADDR. * see, f2fs_add_link -> get_new_data_page -> init_inode_metadata. */ if (dn.data_blkaddr == NEW_ADDR) { zero_user_segment(page, 0, PAGE_CACHE_SIZE); SetPageUptodate(page); unlock_page(page); return page; } fio.blk_addr = dn.data_blkaddr; fio.page = page; err = f2fs_submit_page_bio(&fio); if (err) return ERR_PTR(err); return page; } struct page *find_data_page(struct inode *inode, pgoff_t index) { struct address_space *mapping = inode->i_mapping; struct page *page; page = find_get_page(mapping, index); if (page && PageUptodate(page)) return page; f2fs_put_page(page, 0); page = get_read_data_page(inode, index, READ_SYNC); if (IS_ERR(page)) return page; if (PageUptodate(page)) return page; wait_on_page_locked(page); if (unlikely(!PageUptodate(page))) { f2fs_put_page(page, 0); return ERR_PTR(-EIO); } return page; } /* * If it tries to access a hole, return an error. * Because, the callers, functions in dir.c and GC, should be able to know * whether this page exists or not. */ struct page *get_lock_data_page(struct inode *inode, pgoff_t index) { struct address_space *mapping = inode->i_mapping; struct page *page; repeat: page = get_read_data_page(inode, index, READ_SYNC); if (IS_ERR(page)) return page; /* wait for read completion */ lock_page(page); if (unlikely(!PageUptodate(page))) { f2fs_put_page(page, 1); return ERR_PTR(-EIO); } if (unlikely(page->mapping != mapping)) { f2fs_put_page(page, 1); goto repeat; } return page; } /* * Caller ensures that this data page is never allocated. * A new zero-filled data page is allocated in the page cache. * * Also, caller should grab and release a rwsem by calling f2fs_lock_op() and * f2fs_unlock_op(). * Note that, ipage is set only by make_empty_dir. */ struct page *get_new_data_page(struct inode *inode, struct page *ipage, pgoff_t index, bool new_i_size) { struct address_space *mapping = inode->i_mapping; struct page *page; struct dnode_of_data dn; int err; repeat: page = grab_cache_page(mapping, index); if (!page) return ERR_PTR(-ENOMEM); set_new_dnode(&dn, inode, ipage, NULL, 0); err = f2fs_reserve_block(&dn, index); if (err) { f2fs_put_page(page, 1); return ERR_PTR(err); } if (!ipage) f2fs_put_dnode(&dn); if (PageUptodate(page)) goto got_it; if (dn.data_blkaddr == NEW_ADDR) { zero_user_segment(page, 0, PAGE_CACHE_SIZE); SetPageUptodate(page); } else { f2fs_put_page(page, 1); page = get_read_data_page(inode, index, READ_SYNC); if (IS_ERR(page)) goto repeat; /* wait for read completion */ lock_page(page); } got_it: if (new_i_size && i_size_read(inode) < ((index + 1) << PAGE_CACHE_SHIFT)) { i_size_write(inode, ((index + 1) << PAGE_CACHE_SHIFT)); /* Only the directory inode sets new_i_size */ set_inode_flag(F2FS_I(inode), FI_UPDATE_DIR); } return page; } static int __allocate_data_block(struct dnode_of_data *dn) { struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode); struct f2fs_inode_info *fi = F2FS_I(dn->inode); struct f2fs_summary sum; struct node_info ni; int seg = CURSEG_WARM_DATA; pgoff_t fofs; if (unlikely(is_inode_flag_set(F2FS_I(dn->inode), FI_NO_ALLOC))) return -EPERM; dn->data_blkaddr = datablock_addr(dn->node_page, dn->ofs_in_node); if (dn->data_blkaddr == NEW_ADDR) goto alloc; if (unlikely(!inc_valid_block_count(sbi, dn->inode, 1))) return -ENOSPC; alloc: get_node_info(sbi, dn->nid, &ni); set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version); if (dn->ofs_in_node == 0 && dn->inode_page == dn->node_page) seg = CURSEG_DIRECT_IO; allocate_data_block(sbi, NULL, dn->data_blkaddr, &dn->data_blkaddr, &sum, seg); /* direct IO doesn't use extent cache to maximize the performance */ set_data_blkaddr(dn); /* update i_size */ fofs = start_bidx_of_node(ofs_of_node(dn->node_page), fi) + dn->ofs_in_node; if (i_size_read(dn->inode) < ((fofs + 1) << PAGE_CACHE_SHIFT)) i_size_write(dn->inode, ((fofs + 1) << PAGE_CACHE_SHIFT)); return 0; } static void __allocate_data_blocks(struct inode *inode, loff_t offset, size_t count) { struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct dnode_of_data dn; u64 start = F2FS_BYTES_TO_BLK(offset); u64 len = F2FS_BYTES_TO_BLK(count); bool allocated; u64 end_offset; while (len) { f2fs_balance_fs(sbi); f2fs_lock_op(sbi); /* When reading holes, we need its node page */ set_new_dnode(&dn, inode, NULL, NULL, 0); if (get_dnode_of_data(&dn, start, ALLOC_NODE)) goto out; allocated = false; end_offset = ADDRS_PER_PAGE(dn.node_page, F2FS_I(inode)); while (dn.ofs_in_node < end_offset && len) { block_t blkaddr; blkaddr = datablock_addr(dn.node_page, dn.ofs_in_node); if (blkaddr == NULL_ADDR || blkaddr == NEW_ADDR) { if (__allocate_data_block(&dn)) goto sync_out; allocated = true; } len--; start++; dn.ofs_in_node++; } if (allocated) sync_inode_page(&dn); f2fs_put_dnode(&dn); f2fs_unlock_op(sbi); } return; sync_out: if (allocated) sync_inode_page(&dn); f2fs_put_dnode(&dn); out: f2fs_unlock_op(sbi); return; } /* * f2fs_map_blocks() now supported readahead/bmap/rw direct_IO with * f2fs_map_blocks structure. * If original data blocks are allocated, then give them to blockdev. * Otherwise, * a. preallocate requested block addresses * b. do not use extent cache for better performance * c. give the block addresses to blockdev */ static int f2fs_map_blocks(struct inode *inode, struct f2fs_map_blocks *map, int create, bool fiemap) { unsigned int maxblocks = map->m_len; struct dnode_of_data dn; int mode = create ? ALLOC_NODE : LOOKUP_NODE_RA; pgoff_t pgofs, end_offset; int err = 0, ofs = 1; struct extent_info ei; bool allocated = false; map->m_len = 0; map->m_flags = 0; /* it only supports block size == page size */ pgofs = (pgoff_t)map->m_lblk; if (f2fs_lookup_extent_cache(inode, pgofs, &ei)) { map->m_pblk = ei.blk + pgofs - ei.fofs; map->m_len = min((pgoff_t)maxblocks, ei.fofs + ei.len - pgofs); map->m_flags = F2FS_MAP_MAPPED; goto out; } if (create) f2fs_lock_op(F2FS_I_SB(inode)); /* When reading holes, we need its node page */ set_new_dnode(&dn, inode, NULL, NULL, 0); err = get_dnode_of_data(&dn, pgofs, mode); if (err) { if (err == -ENOENT) err = 0; goto unlock_out; } if (dn.data_blkaddr == NEW_ADDR && !fiemap) goto put_out; if (dn.data_blkaddr != NULL_ADDR) { map->m_flags = F2FS_MAP_MAPPED; map->m_pblk = dn.data_blkaddr; if (dn.data_blkaddr == NEW_ADDR) map->m_flags |= F2FS_MAP_UNWRITTEN; } else if (create) { err = __allocate_data_block(&dn); if (err) goto put_out; allocated = true; map->m_flags = F2FS_MAP_NEW | F2FS_MAP_MAPPED; map->m_pblk = dn.data_blkaddr; } else { goto put_out; } end_offset = ADDRS_PER_PAGE(dn.node_page, F2FS_I(inode)); map->m_len = 1; dn.ofs_in_node++; pgofs++; get_next: if (dn.ofs_in_node >= end_offset) { if (allocated) sync_inode_page(&dn); allocated = false; f2fs_put_dnode(&dn); set_new_dnode(&dn, inode, NULL, NULL, 0); err = get_dnode_of_data(&dn, pgofs, mode); if (err) { if (err == -ENOENT) err = 0; goto unlock_out; } if (dn.data_blkaddr == NEW_ADDR && !fiemap) goto put_out; end_offset = ADDRS_PER_PAGE(dn.node_page, F2FS_I(inode)); } if (maxblocks > map->m_len) { block_t blkaddr = datablock_addr(dn.node_page, dn.ofs_in_node); if (blkaddr == NULL_ADDR && create) { err = __allocate_data_block(&dn); if (err) goto sync_out; allocated = true; map->m_flags |= F2FS_MAP_NEW; blkaddr = dn.data_blkaddr; } /* Give more consecutive addresses for the readahead */ if ((map->m_pblk != NEW_ADDR && blkaddr == (map->m_pblk + ofs)) || (map->m_pblk == NEW_ADDR && blkaddr == NEW_ADDR)) { ofs++; dn.ofs_in_node++; pgofs++; map->m_len++; goto get_next; } } sync_out: if (allocated) sync_inode_page(&dn); put_out: f2fs_put_dnode(&dn); unlock_out: if (create) f2fs_unlock_op(F2FS_I_SB(inode)); out: trace_f2fs_map_blocks(inode, map, err); return err; } static int __get_data_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create, bool fiemap) { struct f2fs_map_blocks map; int ret; map.m_lblk = iblock; map.m_len = bh->b_size >> inode->i_blkbits; ret = f2fs_map_blocks(inode, &map, create, fiemap); if (!ret) { map_bh(bh, inode->i_sb, map.m_pblk); bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags; bh->b_size = map.m_len << inode->i_blkbits; } return ret; } static int get_data_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { return __get_data_block(inode, iblock, bh_result, create, false); } static int get_data_block_fiemap(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { return __get_data_block(inode, iblock, bh_result, create, true); } static inline sector_t logical_to_blk(struct inode *inode, loff_t offset) { return (offset >> inode->i_blkbits); } static inline loff_t blk_to_logical(struct inode *inode, sector_t blk) { return (blk << inode->i_blkbits); } int f2fs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, u64 start, u64 len) { struct buffer_head map_bh; sector_t start_blk, last_blk; loff_t isize = i_size_read(inode); u64 logical = 0, phys = 0, size = 0; u32 flags = 0; bool past_eof = false, whole_file = false; int ret = 0; ret = fiemap_check_flags(fieinfo, FIEMAP_FLAG_SYNC); if (ret) return ret; mutex_lock(&inode->i_mutex); if (len >= isize) { whole_file = true; len = isize; } if (logical_to_blk(inode, len) == 0) len = blk_to_logical(inode, 1); start_blk = logical_to_blk(inode, start); last_blk = logical_to_blk(inode, start + len - 1); next: memset(&map_bh, 0, sizeof(struct buffer_head)); map_bh.b_size = len; ret = get_data_block_fiemap(inode, start_blk, &map_bh, 0); if (ret) goto out; /* HOLE */ if (!buffer_mapped(&map_bh)) { start_blk++; if (!past_eof && blk_to_logical(inode, start_blk) >= isize) past_eof = 1; if (past_eof && size) { flags |= FIEMAP_EXTENT_LAST; ret = fiemap_fill_next_extent(fieinfo, logical, phys, size, flags); } else if (size) { ret = fiemap_fill_next_extent(fieinfo, logical, phys, size, flags); size = 0; } /* if we have holes up to/past EOF then we're done */ if (start_blk > last_blk || past_eof || ret) goto out; } else { if (start_blk > last_blk && !whole_file) { ret = fiemap_fill_next_extent(fieinfo, logical, phys, size, flags); goto out; } /* * if size != 0 then we know we already have an extent * to add, so add it. */ if (size) { ret = fiemap_fill_next_extent(fieinfo, logical, phys, size, flags); if (ret) goto out; } logical = blk_to_logical(inode, start_blk); phys = blk_to_logical(inode, map_bh.b_blocknr); size = map_bh.b_size; flags = 0; if (buffer_unwritten(&map_bh)) flags = FIEMAP_EXTENT_UNWRITTEN; start_blk += logical_to_blk(inode, size); /* * If we are past the EOF, then we need to make sure as * soon as we find a hole that the last extent we found * is marked with FIEMAP_EXTENT_LAST */ if (!past_eof && logical + size >= isize) past_eof = true; } cond_resched(); if (fatal_signal_pending(current)) ret = -EINTR; else goto next; out: if (ret == 1) ret = 0; mutex_unlock(&inode->i_mutex); return ret; } /* * This function was originally taken from fs/mpage.c, and customized for f2fs. * Major change was from block_size == page_size in f2fs by default. */ static int f2fs_mpage_readpages(struct address_space *mapping, struct list_head *pages, struct page *page, unsigned nr_pages) { struct bio *bio = NULL; unsigned page_idx; sector_t last_block_in_bio = 0; struct inode *inode = mapping->host; const unsigned blkbits = inode->i_blkbits; const unsigned blocksize = 1 << blkbits; sector_t block_in_file; sector_t last_block; sector_t last_block_in_file; sector_t block_nr; struct block_device *bdev = inode->i_sb->s_bdev; struct f2fs_map_blocks map; map.m_pblk = 0; map.m_lblk = 0; map.m_len = 0; map.m_flags = 0; for (page_idx = 0; nr_pages; page_idx++, nr_pages--) { prefetchw(&page->flags); if (pages) { page = list_entry(pages->prev, struct page, lru); list_del(&page->lru); if (add_to_page_cache_lru(page, mapping, page->index, GFP_KERNEL)) goto next_page; } block_in_file = (sector_t)page->index; last_block = block_in_file + nr_pages; last_block_in_file = (i_size_read(inode) + blocksize - 1) >> blkbits; if (last_block > last_block_in_file) last_block = last_block_in_file; /* * Map blocks using the previous result first. */ if ((map.m_flags & F2FS_MAP_MAPPED) && block_in_file > map.m_lblk && block_in_file < (map.m_lblk + map.m_len)) goto got_it; /* * Then do more f2fs_map_blocks() calls until we are * done with this page. */ map.m_flags = 0; if (block_in_file < last_block) { map.m_lblk = block_in_file; map.m_len = last_block - block_in_file; if (f2fs_map_blocks(inode, &map, 0, false)) goto set_error_page; } got_it: if ((map.m_flags & F2FS_MAP_MAPPED)) { block_nr = map.m_pblk + block_in_file - map.m_lblk; SetPageMappedToDisk(page); if (!PageUptodate(page) && !cleancache_get_page(page)) { SetPageUptodate(page); goto confused; } } else { zero_user_segment(page, 0, PAGE_CACHE_SIZE); SetPageUptodate(page); unlock_page(page); goto next_page; } /* * This page will go to BIO. Do we need to send this * BIO off first? */ if (bio && (last_block_in_bio != block_nr - 1)) { submit_and_realloc: submit_bio(READ, bio); bio = NULL; } if (bio == NULL) { struct f2fs_crypto_ctx *ctx = NULL; if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode)) { struct page *cpage; ctx = f2fs_get_crypto_ctx(inode); if (IS_ERR(ctx)) goto set_error_page; /* wait the page to be moved by cleaning */ cpage = find_lock_page( META_MAPPING(F2FS_I_SB(inode)), block_nr); if (cpage) { f2fs_wait_on_page_writeback(cpage, DATA); f2fs_put_page(cpage, 1); } } bio = bio_alloc(GFP_KERNEL, min_t(int, nr_pages, bio_get_nr_vecs(bdev))); if (!bio) { if (ctx) f2fs_release_crypto_ctx(ctx); goto set_error_page; } bio->bi_bdev = bdev; bio->bi_sector = SECTOR_FROM_BLOCK(block_nr); bio->bi_end_io = f2fs_read_end_io; bio->bi_private = ctx; } if (bio_add_page(bio, page, blocksize, 0) < blocksize) goto submit_and_realloc; last_block_in_bio = block_nr; goto next_page; set_error_page: SetPageError(page); zero_user_segment(page, 0, PAGE_CACHE_SIZE); unlock_page(page); goto next_page; confused: if (bio) { submit_bio(READ, bio); bio = NULL; } unlock_page(page); next_page: if (pages) page_cache_release(page); } BUG_ON(pages && !list_empty(pages)); if (bio) submit_bio(READ, bio); return 0; } static int f2fs_read_data_page(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; int ret = -EAGAIN; trace_f2fs_readpage(page, DATA); /* If the file has inline data, try to read it directly */ if (f2fs_has_inline_data(inode)) ret = f2fs_read_inline_data(inode, page); if (ret == -EAGAIN) ret = f2fs_mpage_readpages(page->mapping, NULL, page, 1); return ret; } static int f2fs_read_data_pages(struct file *file, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { struct inode *inode = file->f_mapping->host; /* If the file has inline data, skip readpages */ if (f2fs_has_inline_data(inode)) return 0; return f2fs_mpage_readpages(mapping, pages, NULL, nr_pages); } int do_write_data_page(struct f2fs_io_info *fio) { struct page *page = fio->page; struct inode *inode = page->mapping->host; struct dnode_of_data dn; int err = 0; set_new_dnode(&dn, inode, NULL, NULL, 0); err = get_dnode_of_data(&dn, page->index, LOOKUP_NODE); if (err) return err; fio->blk_addr = dn.data_blkaddr; /* This page is already truncated */ if (fio->blk_addr == NULL_ADDR) { ClearPageUptodate(page); goto out_writepage; } if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode)) { fio->encrypted_page = f2fs_encrypt(inode, fio->page); if (IS_ERR(fio->encrypted_page)) { err = PTR_ERR(fio->encrypted_page); goto out_writepage; } } set_page_writeback(page); /* * If current allocation needs SSR, * it had better in-place writes for updated data. */ if (unlikely(fio->blk_addr != NEW_ADDR && !is_cold_data(page) && need_inplace_update(inode))) { rewrite_data_page(fio); set_inode_flag(F2FS_I(inode), FI_UPDATE_WRITE); trace_f2fs_do_write_data_page(page, IPU); } else { write_data_page(&dn, fio); set_data_blkaddr(&dn); f2fs_update_extent_cache(&dn); trace_f2fs_do_write_data_page(page, OPU); set_inode_flag(F2FS_I(inode), FI_APPEND_WRITE); if (page->index == 0) set_inode_flag(F2FS_I(inode), FI_FIRST_BLOCK_WRITTEN); } out_writepage: f2fs_put_dnode(&dn); return err; } static int f2fs_write_data_page(struct page *page, struct writeback_control *wbc) { struct inode *inode = page->mapping->host; struct f2fs_sb_info *sbi = F2FS_I_SB(inode); loff_t i_size = i_size_read(inode); const pgoff_t end_index = ((unsigned long long) i_size) >> PAGE_CACHE_SHIFT; unsigned offset = 0; bool need_balance_fs = false; int err = 0; struct f2fs_io_info fio = { .sbi = sbi, .type = DATA, .rw = (wbc->sync_mode == WB_SYNC_ALL) ? WRITE_SYNC : WRITE, .page = page, .encrypted_page = NULL, }; trace_f2fs_writepage(page, DATA); if (page->index < end_index) goto write; /* * If the offset is out-of-range of file size, * this page does not have to be written to disk. */ offset = i_size & (PAGE_CACHE_SIZE - 1); if ((page->index >= end_index + 1) || !offset) goto out; zero_user_segment(page, offset, PAGE_CACHE_SIZE); write: if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING))) goto redirty_out; if (f2fs_is_drop_cache(inode)) goto out; if (f2fs_is_volatile_file(inode) && !wbc->for_reclaim && available_free_memory(sbi, BASE_CHECK)) goto redirty_out; /* Dentry blocks are controlled by checkpoint */ if (S_ISDIR(inode->i_mode)) { if (unlikely(f2fs_cp_error(sbi))) goto redirty_out; err = do_write_data_page(&fio); goto done; } /* we should bypass data pages to proceed the kworkder jobs */ if (unlikely(f2fs_cp_error(sbi))) { SetPageError(page); goto out; } if (!wbc->for_reclaim) need_balance_fs = true; else if (has_not_enough_free_secs(sbi, 0)) goto redirty_out; err = -EAGAIN; f2fs_lock_op(sbi); if (f2fs_has_inline_data(inode)) err = f2fs_write_inline_data(inode, page); if (err == -EAGAIN) err = do_write_data_page(&fio); f2fs_unlock_op(sbi); done: if (err && err != -ENOENT) goto redirty_out; clear_cold_data(page); out: inode_dec_dirty_pages(inode); if (err) ClearPageUptodate(page); unlock_page(page); if (need_balance_fs) f2fs_balance_fs(sbi); if (wbc->for_reclaim) f2fs_submit_merged_bio(sbi, DATA, WRITE); return 0; redirty_out: redirty_page_for_writepage(wbc, page); return AOP_WRITEPAGE_ACTIVATE; } static int __f2fs_writepage(struct page *page, struct writeback_control *wbc, void *data) { struct address_space *mapping = data; int ret = mapping->a_ops->writepage(page, wbc); mapping_set_error(mapping, ret); return ret; } static int f2fs_write_data_pages(struct address_space *mapping, struct writeback_control *wbc) { struct inode *inode = mapping->host; struct f2fs_sb_info *sbi = F2FS_I_SB(inode); bool locked = false; int ret; long diff; trace_f2fs_writepages(mapping->host, wbc, DATA); /* deal with chardevs and other special file */ if (!mapping->a_ops->writepage) return 0; if (S_ISDIR(inode->i_mode) && wbc->sync_mode == WB_SYNC_NONE && get_dirty_pages(inode) < nr_pages_to_skip(sbi, DATA) && available_free_memory(sbi, DIRTY_DENTS)) goto skip_write; /* during POR, we don't need to trigger writepage at all. */ if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING))) goto skip_write; diff = nr_pages_to_write(sbi, DATA, wbc); if (!S_ISDIR(inode->i_mode)) { mutex_lock(&sbi->writepages); locked = true; } ret = write_cache_pages(mapping, wbc, __f2fs_writepage, mapping); if (locked) mutex_unlock(&sbi->writepages); f2fs_submit_merged_bio(sbi, DATA, WRITE); remove_dirty_dir_inode(inode); wbc->nr_to_write = max((long)0, wbc->nr_to_write - diff); return ret; skip_write: wbc->pages_skipped += get_dirty_pages(inode); return 0; } static void f2fs_write_failed(struct address_space *mapping, loff_t to) { struct inode *inode = mapping->host; if (to > inode->i_size) { truncate_pagecache(inode, 0, inode->i_size); truncate_blocks(inode, inode->i_size, true); } } static int f2fs_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { struct inode *inode = mapping->host; struct f2fs_sb_info *sbi = F2FS_I_SB(inode); struct page *page, *ipage; pgoff_t index = ((unsigned long long) pos) >> PAGE_CACHE_SHIFT; struct dnode_of_data dn; int err = 0; trace_f2fs_write_begin(inode, pos, len, flags); f2fs_balance_fs(sbi); /* * We should check this at this moment to avoid deadlock on inode page * and #0 page. The locking rule for inline_data conversion should be: * lock_page(page #0) -> lock_page(inode_page) */ if (index != 0) { err = f2fs_convert_inline_inode(inode); if (err) goto fail; } repeat: page = grab_cache_page_write_begin(mapping, index, flags); if (!page) { err = -ENOMEM; goto fail; } *pagep = page; f2fs_lock_op(sbi); /* check inline_data */ ipage = get_node_page(sbi, inode->i_ino); if (IS_ERR(ipage)) { err = PTR_ERR(ipage); goto unlock_fail; } set_new_dnode(&dn, inode, ipage, ipage, 0); if (f2fs_has_inline_data(inode)) { if (pos + len <= MAX_INLINE_DATA) { read_inline_data(page, ipage); set_inode_flag(F2FS_I(inode), FI_DATA_EXIST); sync_inode_page(&dn); goto put_next; } err = f2fs_convert_inline_page(&dn, page); if (err) goto put_fail; } err = f2fs_reserve_block(&dn, index); if (err) goto put_fail; put_next: f2fs_put_dnode(&dn); f2fs_unlock_op(sbi); if ((len == PAGE_CACHE_SIZE) || PageUptodate(page)) return 0; f2fs_wait_on_page_writeback(page, DATA); if ((pos & PAGE_CACHE_MASK) >= i_size_read(inode)) { unsigned start = pos & (PAGE_CACHE_SIZE - 1); unsigned end = start + len; /* Reading beyond i_size is simple: memset to zero */ zero_user_segments(page, 0, start, end, PAGE_CACHE_SIZE); goto out; } if (dn.data_blkaddr == NEW_ADDR) { zero_user_segment(page, 0, PAGE_CACHE_SIZE); } else { struct f2fs_io_info fio = { .sbi = sbi, .type = DATA, .rw = READ_SYNC, .blk_addr = dn.data_blkaddr, .page = page, .encrypted_page = NULL, }; err = f2fs_submit_page_bio(&fio); if (err) goto fail; lock_page(page); if (unlikely(!PageUptodate(page))) { f2fs_put_page(page, 1); err = -EIO; goto fail; } if (unlikely(page->mapping != mapping)) { f2fs_put_page(page, 1); goto repeat; } /* avoid symlink page */ if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode)) { err = f2fs_decrypt_one(inode, page); if (err) { f2fs_put_page(page, 1); goto fail; } } } out: SetPageUptodate(page); clear_cold_data(page); return 0; put_fail: f2fs_put_dnode(&dn); unlock_fail: f2fs_unlock_op(sbi); f2fs_put_page(page, 1); fail: f2fs_write_failed(mapping, pos + len); return err; } static int f2fs_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { struct inode *inode = page->mapping->host; trace_f2fs_write_end(inode, pos, len, copied); set_page_dirty(page); if (pos + copied > i_size_read(inode)) { i_size_write(inode, pos + copied); mark_inode_dirty(inode); update_inode_page(inode); } f2fs_put_page(page, 1); return copied; } static int check_direct_IO(struct inode *inode, int rw, struct iov_iter *iter, loff_t offset) { unsigned blocksize_mask = inode->i_sb->s_blocksize - 1; int i; if (rw == READ) return 0; if (offset & blocksize_mask) return -EINVAL; for (i = 0; i < iter->nr_segs; i++) { const struct iovec *iov = iov_iter_iovec(iter); if (iov[i].iov_len & blocksize_mask) return -EINVAL; } return 0; } static ssize_t f2fs_direct_IO(int rw, struct kiocb *iocb, struct iov_iter *iter, loff_t offset) { struct file *file = iocb->ki_filp; struct address_space *mapping = file->f_mapping; struct inode *inode = mapping->host; size_t count = iov_iter_count(iter); int err; /* we don't need to use inline_data strictly */ if (f2fs_has_inline_data(inode)) { err = f2fs_convert_inline_inode(inode); if (err) return err; } if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode)) return 0; if (check_direct_IO(inode, rw, iter, offset)) return 0; trace_f2fs_direct_IO_enter(inode, offset, count, rw); if (rw & WRITE) __allocate_data_blocks(inode, offset, count); err = blockdev_direct_IO(rw, iocb, inode, iter, offset, get_data_block); if (err < 0 && (rw & WRITE)) f2fs_write_failed(mapping, offset + count); trace_f2fs_direct_IO_exit(inode, offset, count, rw, err); return err; } void f2fs_invalidate_page(struct page *page, unsigned long offset) { struct inode *inode = page->mapping->host; struct f2fs_sb_info *sbi = F2FS_I_SB(inode); if (inode->i_ino >= F2FS_ROOT_INO(sbi) && (offset % PAGE_CACHE_SIZE)) return; if (PageDirty(page)) { if (inode->i_ino == F2FS_META_INO(sbi)) dec_page_count(sbi, F2FS_DIRTY_META); else if (inode->i_ino == F2FS_NODE_INO(sbi)) dec_page_count(sbi, F2FS_DIRTY_NODES); else inode_dec_dirty_pages(inode); } ClearPagePrivate(page); } int f2fs_release_page(struct page *page, gfp_t wait) { /* If this is dirty page, keep PagePrivate */ if (PageDirty(page)) return 0; ClearPagePrivate(page); return 1; } static int f2fs_set_data_page_dirty(struct page *page) { struct address_space *mapping = page->mapping; struct inode *inode = mapping->host; trace_f2fs_set_page_dirty(page, DATA); SetPageUptodate(page); if (f2fs_is_atomic_file(inode)) { register_inmem_page(inode, page); return 1; } mark_inode_dirty(inode); if (!PageDirty(page)) { __set_page_dirty_nobuffers(page); update_dirty_page(inode, page); return 1; } return 0; } static sector_t f2fs_bmap(struct address_space *mapping, sector_t block) { struct inode *inode = mapping->host; /* we don't need to use inline_data strictly */ if (f2fs_has_inline_data(inode)) { int err = f2fs_convert_inline_inode(inode); if (err) return err; } return generic_block_bmap(mapping, block, get_data_block); } void init_extent_cache_info(struct f2fs_sb_info *sbi) { INIT_RADIX_TREE(&sbi->extent_tree_root, GFP_NOIO); init_rwsem(&sbi->extent_tree_lock); INIT_LIST_HEAD(&sbi->extent_list); spin_lock_init(&sbi->extent_lock); sbi->total_ext_tree = 0; atomic_set(&sbi->total_ext_node, 0); } int __init create_extent_cache(void) { extent_tree_slab = f2fs_kmem_cache_create("f2fs_extent_tree", sizeof(struct extent_tree)); if (!extent_tree_slab) return -ENOMEM; extent_node_slab = f2fs_kmem_cache_create("f2fs_extent_node", sizeof(struct extent_node)); if (!extent_node_slab) { kmem_cache_destroy(extent_tree_slab); return -ENOMEM; } return 0; } void destroy_extent_cache(void) { kmem_cache_destroy(extent_node_slab); kmem_cache_destroy(extent_tree_slab); } const struct address_space_operations f2fs_dblock_aops = { .readpage = f2fs_read_data_page, .readpages = f2fs_read_data_pages, .writepage = f2fs_write_data_page, .writepages = f2fs_write_data_pages, .write_begin = f2fs_write_begin, .write_end = f2fs_write_end, .set_page_dirty = f2fs_set_data_page_dirty, .invalidatepage = f2fs_invalidate_page, .releasepage = f2fs_release_page, .direct_IO = f2fs_direct_IO, .bmap = f2fs_bmap, };
NStep/android_kernel_motorola_msm8226
fs/f2fs/data.c
C
gpl-2.0
51,157
#include "./downloaditemdelegate.h" #include <syncthingmodel/syncthingdownloadmodel.h> #include <syncthingmodel/syncthingicons.h> #include <qtforkawesome/icon.h> #include <qtforkawesome/renderer.h> #include <QApplication> #include <QBrush> #include <QFontMetrics> #include <QPainter> #include <QPalette> #include <QPixmap> #include <QStyle> #include <QStyleOptionViewItem> #include <QTextOption> #include <iostream> using namespace std; using namespace Data; namespace QtGui { inline int centerObj(int avail, int size) { return (avail - size) / 2; } DownloadItemDelegate::DownloadItemDelegate(QObject *parent) : QStyledItemDelegate(parent) { } void DownloadItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { // init style options to use drawControl(), except for the text QStyleOptionViewItem opt = option; initStyleOption(&opt, index); opt.textElideMode = Qt::ElideNone; // elide manually opt.features = QStyleOptionViewItem::None; if (index.parent().isValid()) { opt.displayAlignment = Qt::AlignTop | Qt::AlignLeft; opt.decorationSize = QSize(option.rect.height(), option.rect.height()); opt.features |= QStyleOptionViewItem::HasDecoration; opt.text = option.fontMetrics.elidedText(opt.text, Qt::ElideMiddle, opt.rect.width() - opt.rect.height() - 26); } else { opt.text = option.fontMetrics.elidedText(opt.text, Qt::ElideMiddle, opt.rect.width() / 2 - 4); } QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &opt, painter); // draw progress bar const QAbstractItemModel *model = index.model(); QStyleOptionProgressBar progressBarOption; progressBarOption.state = option.state; progressBarOption.direction = option.direction; progressBarOption.rect = option.rect; if (index.parent().isValid()) { progressBarOption.rect.setX(opt.rect.x() + opt.rect.height() + 4); progressBarOption.rect.setY(opt.rect.y() + opt.rect.height() / 2); } else { #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)) progressBarOption.rect.setX(opt.rect.x() + opt.fontMetrics.horizontalAdvance(opt.text) + 6); #else progressBarOption.rect.setX(opt.rect.x() + opt.fontMetrics.width(opt.text) + 6); #endif progressBarOption.rect.setWidth(progressBarOption.rect.width() - 18); } progressBarOption.textAlignment = Qt::AlignCenter; progressBarOption.textVisible = true; if (option.state & QStyle::State_Selected) { progressBarOption.palette.setBrush(QPalette::WindowText, option.palette.brush(QPalette::HighlightedText)); } progressBarOption.progress = model->data(index, SyncthingDownloadModel::ItemPercentage).toInt(); progressBarOption.minimum = 0; progressBarOption.maximum = 100; progressBarOption.text = model->data(index, SyncthingDownloadModel::ItemProgressLabel).toString(); QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter); // draw buttons int buttonY = option.rect.y(); if (!index.parent().isValid()) { buttonY += centerObj(progressBarOption.rect.height(), 16); } IconManager::instance().forkAwesomeRenderer().render( QtForkAwesome::Icon::Folder, painter, QRect(option.rect.right() - 16, buttonY, 16, 16), QGuiApplication::palette().color(QPalette::Text)); // draw file icon if (index.parent().isValid()) { const int fileIconHeight = option.rect.height() - 2; painter->drawPixmap(option.rect.left(), option.rect.y() + 1, fileIconHeight, fileIconHeight, model->data(index, Qt::DecorationRole).value<QIcon>().pixmap(fileIconHeight)); } } QSize DownloadItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QSize defaultSize(QStyledItemDelegate::sizeHint(option, index)); if (index.parent().isValid()) { defaultSize.setHeight(defaultSize.height() + defaultSize.height() - 12); } return defaultSize; } } // namespace QtGui
Martchus/syncthingtray
tray/gui/downloaditemdelegate.cpp
C++
gpl-2.0
4,059
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "FastMixer" //#define LOG_NDEBUG 0 #include <sys/atomics.h> #include <time.h> #include <utils/Log.h> #include <utils/Trace.h> #include <system/audio.h> #ifdef FAST_MIXER_STATISTICS #include <cpustats/CentralTendencyStatistics.h> #ifdef CPU_FREQUENCY_STATISTICS #include <cpustats/ThreadCpuUsage.h> #endif #endif #include "AudioMixer.h" #include "FastMixer.h" #define FAST_HOT_IDLE_NS 1000000L // 1 ms: time to sleep while hot idling #define FAST_DEFAULT_NS 999999999L // ~1 sec: default time to sleep #define MIN_WARMUP_CYCLES 2 // minimum number of loop cycles to wait for warmup #define MAX_WARMUP_CYCLES 10 // maximum number of loop cycles to wait for warmup namespace android { // Fast mixer thread bool FastMixer::threadLoop() { static const FastMixerState initial; const FastMixerState *previous = &initial, *current = &initial; FastMixerState preIdle; // copy of state before we went into idle struct timespec oldTs = {0, 0}; bool oldTsValid = false; long slopNs = 0; // accumulated time we've woken up too early (> 0) or too late (< 0) long sleepNs = -1; // -1: busy wait, 0: sched_yield, > 0: nanosleep int fastTrackNames[FastMixerState::kMaxFastTracks]; // handles used by mixer to identify tracks int generations[FastMixerState::kMaxFastTracks]; // last observed mFastTracks[i].mGeneration unsigned i; for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) { fastTrackNames[i] = -1; generations[i] = 0; } NBAIO_Sink *outputSink = NULL; int outputSinkGen = 0; AudioMixer* mixer = NULL; short *mixBuffer = NULL; enum {UNDEFINED, MIXED, ZEROED} mixBufferState = UNDEFINED; NBAIO_Format format = Format_Invalid; unsigned sampleRate = 0; int fastTracksGen = 0; long periodNs = 0; // expected period; the time required to render one mix buffer long underrunNs = 0; // underrun likely when write cycle is greater than this value long overrunNs = 0; // overrun likely when write cycle is less than this value long forceNs = 0; // if overrun detected, force the write cycle to take this much time long warmupNs = 0; // warmup complete when write cycle is greater than to this value FastMixerDumpState dummyDumpState, *dumpState = &dummyDumpState; bool ignoreNextOverrun = true; // used to ignore initial overrun and first after an underrun #ifdef FAST_MIXER_STATISTICS struct timespec oldLoad = {0, 0}; // previous value of clock_gettime(CLOCK_THREAD_CPUTIME_ID) bool oldLoadValid = false; // whether oldLoad is valid uint32_t bounds = 0; bool full = false; // whether we have collected at least kSamplingN samples #ifdef CPU_FREQUENCY_STATISTICS ThreadCpuUsage tcu; // for reading the current CPU clock frequency in kHz #endif #endif unsigned coldGen = 0; // last observed mColdGen bool isWarm = false; // true means ready to mix, false means wait for warmup before mixing struct timespec measuredWarmupTs = {0, 0}; // how long did it take for warmup to complete uint32_t warmupCycles = 0; // counter of number of loop cycles required to warmup NBAIO_Sink* teeSink = NULL; // if non-NULL, then duplicate write() to this non-blocking sink for (;;) { // either nanosleep, sched_yield, or busy wait if (sleepNs >= 0) { if (sleepNs > 0) { ALOG_ASSERT(sleepNs < 1000000000); const struct timespec req = {0, sleepNs}; nanosleep(&req, NULL); } else { sched_yield(); } } // default to long sleep for next cycle sleepNs = FAST_DEFAULT_NS; // poll for state change const FastMixerState *next = mSQ.poll(); if (next == NULL) { // continue to use the default initial state until a real state is available ALOG_ASSERT(current == &initial && previous == &initial); next = current; } FastMixerState::Command command = next->mCommand; if (next != current) { // As soon as possible of learning of a new dump area, start using it dumpState = next->mDumpState != NULL ? next->mDumpState : &dummyDumpState; teeSink = next->mTeeSink; // We want to always have a valid reference to the previous (non-idle) state. // However, the state queue only guarantees access to current and previous states. // So when there is a transition from a non-idle state into an idle state, we make a // copy of the last known non-idle state so it is still available on return from idle. // The possible transitions are: // non-idle -> non-idle update previous from current in-place // non-idle -> idle update previous from copy of current // idle -> idle don't update previous // idle -> non-idle don't update previous if (!(current->mCommand & FastMixerState::IDLE)) { if (command & FastMixerState::IDLE) { preIdle = *current; current = &preIdle; oldTsValid = false; #ifdef FAST_MIXER_STATISTICS oldLoadValid = false; #endif ignoreNextOverrun = true; } previous = current; } current = next; } #if !LOG_NDEBUG next = NULL; // not referenced again #endif dumpState->mCommand = command; switch (command) { case FastMixerState::INITIAL: case FastMixerState::HOT_IDLE: sleepNs = FAST_HOT_IDLE_NS; continue; case FastMixerState::COLD_IDLE: // only perform a cold idle command once // FIXME consider checking previous state and only perform if previous != COLD_IDLE if (current->mColdGen != coldGen) { int32_t *coldFutexAddr = current->mColdFutexAddr; ALOG_ASSERT(coldFutexAddr != NULL); int32_t old = android_atomic_dec(coldFutexAddr); if (old <= 0) { __futex_syscall4(coldFutexAddr, FUTEX_WAIT_PRIVATE, old - 1, NULL); } // This may be overly conservative; there could be times that the normal mixer // requests such a brief cold idle that it doesn't require resetting this flag. isWarm = false; measuredWarmupTs.tv_sec = 0; measuredWarmupTs.tv_nsec = 0; warmupCycles = 0; sleepNs = -1; coldGen = current->mColdGen; #ifdef FAST_MIXER_STATISTICS bounds = 0; full = false; #endif oldTsValid = !clock_gettime(CLOCK_MONOTONIC, &oldTs); } else { sleepNs = FAST_HOT_IDLE_NS; } continue; case FastMixerState::EXIT: delete mixer; delete[] mixBuffer; return false; case FastMixerState::MIX: case FastMixerState::WRITE: case FastMixerState::MIX_WRITE: break; default: LOG_FATAL("bad command %d", command); } // there is a non-idle state available to us; did the state change? size_t frameCount = current->mFrameCount; if (current != previous) { // handle state change here, but since we want to diff the state, // we're prepared for previous == &initial the first time through unsigned previousTrackMask; // check for change in output HAL configuration NBAIO_Format previousFormat = format; if (current->mOutputSinkGen != outputSinkGen) { outputSink = current->mOutputSink; outputSinkGen = current->mOutputSinkGen; if (outputSink == NULL) { format = Format_Invalid; sampleRate = 0; } else { format = outputSink->format(); sampleRate = Format_sampleRate(format); ALOG_ASSERT(Format_channelCount(format) == 2); } dumpState->mSampleRate = sampleRate; } if ((format != previousFormat) || (frameCount != previous->mFrameCount)) { // FIXME to avoid priority inversion, don't delete here delete mixer; mixer = NULL; delete[] mixBuffer; mixBuffer = NULL; if (frameCount > 0 && sampleRate > 0) { // FIXME new may block for unbounded time at internal mutex of the heap // implementation; it would be better to have normal mixer allocate for us // to avoid blocking here and to prevent possible priority inversion mixer = new AudioMixer(frameCount, sampleRate, FastMixerState::kMaxFastTracks); mixBuffer = new short[frameCount * 2]; periodNs = (frameCount * 1000000000LL) / sampleRate; // 1.00 underrunNs = (frameCount * 1750000000LL) / sampleRate; // 1.75 overrunNs = (frameCount * 500000000LL) / sampleRate; // 0.50 forceNs = (frameCount * 950000000LL) / sampleRate; // 0.95 warmupNs = (frameCount * 500000000LL) / sampleRate; // 0.50 } else { periodNs = 0; underrunNs = 0; overrunNs = 0; forceNs = 0; warmupNs = 0; } mixBufferState = UNDEFINED; #if !LOG_NDEBUG for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) { fastTrackNames[i] = -1; } #endif // we need to reconfigure all active tracks previousTrackMask = 0; fastTracksGen = current->mFastTracksGen - 1; dumpState->mFrameCount = frameCount; } else { previousTrackMask = previous->mTrackMask; } // check for change in active track set unsigned currentTrackMask = current->mTrackMask; dumpState->mTrackMask = currentTrackMask; if (current->mFastTracksGen != fastTracksGen) { ALOG_ASSERT(mixBuffer != NULL); int name; // process removed tracks first to avoid running out of track names unsigned removedTracks = previousTrackMask & ~currentTrackMask; while (removedTracks != 0) { i = __builtin_ctz(removedTracks); removedTracks &= ~(1 << i); const FastTrack* fastTrack = &current->mFastTracks[i]; ALOG_ASSERT(fastTrack->mBufferProvider == NULL); if (mixer != NULL) { name = fastTrackNames[i]; ALOG_ASSERT(name >= 0); mixer->deleteTrackName(name); } #if !LOG_NDEBUG fastTrackNames[i] = -1; #endif // don't reset track dump state, since other side is ignoring it generations[i] = fastTrack->mGeneration; } // now process added tracks unsigned addedTracks = currentTrackMask & ~previousTrackMask; while (addedTracks != 0) { i = __builtin_ctz(addedTracks); addedTracks &= ~(1 << i); const FastTrack* fastTrack = &current->mFastTracks[i]; AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider; ALOG_ASSERT(bufferProvider != NULL && fastTrackNames[i] == -1); if (mixer != NULL) { // calling getTrackName with default channel mask and a random invalid // sessionId (no effects here) name = mixer->getTrackName(AUDIO_CHANNEL_OUT_STEREO, -555); ALOG_ASSERT(name >= 0); fastTrackNames[i] = name; mixer->setBufferProvider(name, bufferProvider); mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER, (void *) mixBuffer); // newly allocated track names default to full scale volume if (fastTrack->mSampleRate != 0 && fastTrack->mSampleRate != sampleRate) { mixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate); } mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK, (void *) fastTrack->mChannelMask); mixer->enable(name); } generations[i] = fastTrack->mGeneration; } // finally process modified tracks; these use the same slot // but may have a different buffer provider or volume provider unsigned modifiedTracks = currentTrackMask & previousTrackMask; while (modifiedTracks != 0) { i = __builtin_ctz(modifiedTracks); modifiedTracks &= ~(1 << i); const FastTrack* fastTrack = &current->mFastTracks[i]; if (fastTrack->mGeneration != generations[i]) { AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider; ALOG_ASSERT(bufferProvider != NULL); if (mixer != NULL) { name = fastTrackNames[i]; ALOG_ASSERT(name >= 0); mixer->setBufferProvider(name, bufferProvider); if (fastTrack->mVolumeProvider == NULL) { mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0, (void *)0x1000); mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1, (void *)0x1000); } if (fastTrack->mSampleRate != 0 && fastTrack->mSampleRate != sampleRate) { mixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate); } else { mixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::REMOVE, NULL); } mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK, (void *) fastTrack->mChannelMask); // already enabled } generations[i] = fastTrack->mGeneration; } } fastTracksGen = current->mFastTracksGen; dumpState->mNumTracks = popcount(currentTrackMask); } #if 1 // FIXME shouldn't need this // only process state change once previous = current; #endif } // do work using current state here if ((command & FastMixerState::MIX) && (mixer != NULL) && isWarm) { ALOG_ASSERT(mixBuffer != NULL); // for each track, update volume and check for underrun unsigned currentTrackMask = current->mTrackMask; while (currentTrackMask != 0) { i = __builtin_ctz(currentTrackMask); currentTrackMask &= ~(1 << i); const FastTrack* fastTrack = &current->mFastTracks[i]; int name = fastTrackNames[i]; ALOG_ASSERT(name >= 0); if (fastTrack->mVolumeProvider != NULL) { uint32_t vlr = fastTrack->mVolumeProvider->getVolumeLR(); mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0, (void *)(vlr & 0xFFFF)); mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1, (void *)(vlr >> 16)); } // FIXME The current implementation of framesReady() for fast tracks // takes a tryLock, which can block // up to 1 ms. If enough active tracks all blocked in sequence, this would result // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO. size_t framesReady = fastTrack->mBufferProvider->framesReady(); #if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) // I wish we had formatted trace names char traceName[16]; strcpy(traceName, "framesReady"); traceName[11] = i + (i < 10 ? '0' : 'A' - 10); traceName[12] = '\0'; ATRACE_INT(traceName, framesReady); #endif FastTrackDump *ftDump = &dumpState->mTracks[i]; FastTrackUnderruns underruns = ftDump->mUnderruns; if (framesReady < frameCount) { if (framesReady == 0) { underruns.mBitFields.mEmpty++; underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY; mixer->disable(name); } else { // allow mixing partial buffer underruns.mBitFields.mPartial++; underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL; mixer->enable(name); } } else { underruns.mBitFields.mFull++; underruns.mBitFields.mMostRecent = UNDERRUN_FULL; mixer->enable(name); } ftDump->mUnderruns = underruns; ftDump->mFramesReady = framesReady; } int64_t pts; if (outputSink == NULL || (OK != outputSink->getNextWriteTimestamp(&pts))) pts = AudioBufferProvider::kInvalidPTS; // process() is CPU-bound mixer->process(pts); mixBufferState = MIXED; } else if (mixBufferState == MIXED) { mixBufferState = UNDEFINED; } bool attemptedWrite = false; //bool didFullWrite = false; // dumpsys could display a count of partial writes if ((command & FastMixerState::WRITE) && (outputSink != NULL) && (mixBuffer != NULL)) { if (mixBufferState == UNDEFINED) { memset(mixBuffer, 0, frameCount * 2 * sizeof(short)); mixBufferState = ZEROED; } if (teeSink != NULL) { (void) teeSink->write(mixBuffer, frameCount); } // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink, // but this code should be modified to handle both non-blocking and blocking sinks dumpState->mWriteSequence++; #if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) Tracer::traceBegin(ATRACE_TAG, "write"); #endif ssize_t framesWritten = outputSink->write(mixBuffer, frameCount); #if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) Tracer::traceEnd(ATRACE_TAG); #endif dumpState->mWriteSequence++; if (framesWritten >= 0) { ALOG_ASSERT(framesWritten <= frameCount); dumpState->mFramesWritten += framesWritten; //if ((size_t) framesWritten == frameCount) { // didFullWrite = true; //} } else { dumpState->mWriteErrors++; } attemptedWrite = true; // FIXME count # of writes blocked excessively, CPU usage, etc. for dump } // To be exactly periodic, compute the next sleep time based on current time. // This code doesn't have long-term stability when the sink is non-blocking. // FIXME To avoid drift, use the local audio clock or watch the sink's fill status. struct timespec newTs; int rc = clock_gettime(CLOCK_MONOTONIC, &newTs); if (rc == 0) { if (oldTsValid) { time_t sec = newTs.tv_sec - oldTs.tv_sec; long nsec = newTs.tv_nsec - oldTs.tv_nsec; ALOGE_IF(sec < 0 || (sec == 0 && nsec < 0), "clock_gettime(CLOCK_MONOTONIC) failed: was %ld.%09ld but now %ld.%09ld", oldTs.tv_sec, oldTs.tv_nsec, newTs.tv_sec, newTs.tv_nsec); if (nsec < 0) { --sec; nsec += 1000000000; } // To avoid an initial underrun on fast tracks after exiting standby, // do not start pulling data from tracks and mixing until warmup is complete. // Warmup is considered complete after the earlier of: // MIN_WARMUP_CYCLES write() attempts and last one blocks for at least warmupNs // MAX_WARMUP_CYCLES write() attempts. // This is overly conservative, but to get better accuracy requires a new HAL API. if (!isWarm && attemptedWrite) { measuredWarmupTs.tv_sec += sec; measuredWarmupTs.tv_nsec += nsec; if (measuredWarmupTs.tv_nsec >= 1000000000) { measuredWarmupTs.tv_sec++; measuredWarmupTs.tv_nsec -= 1000000000; } ++warmupCycles; if ((nsec > warmupNs && warmupCycles >= MIN_WARMUP_CYCLES) || (warmupCycles >= MAX_WARMUP_CYCLES)) { isWarm = true; dumpState->mMeasuredWarmupTs = measuredWarmupTs; dumpState->mWarmupCycles = warmupCycles; } } sleepNs = -1; if (isWarm) { if (sec > 0 || nsec > underrunNs) { #if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) ScopedTrace st(ATRACE_TAG, "underrun"); #endif // FIXME only log occasionally ALOGV("underrun: time since last cycle %d.%03ld sec", (int) sec, nsec / 1000000L); dumpState->mUnderruns++; ignoreNextOverrun = true; } else if (nsec < overrunNs) { if (ignoreNextOverrun) { ignoreNextOverrun = false; } else { // FIXME only log occasionally ALOGV("overrun: time since last cycle %d.%03ld sec", (int) sec, nsec / 1000000L); dumpState->mOverruns++; } // This forces a minimum cycle time. It: // - compensates for an audio HAL with jitter due to sample rate conversion // - works with a variable buffer depth audio HAL that never pulls at a rate // < than overrunNs per buffer. // - recovers from overrun immediately after underrun // It doesn't work with a non-blocking audio HAL. sleepNs = forceNs - nsec; } else { ignoreNextOverrun = false; } } #ifdef FAST_MIXER_STATISTICS if (isWarm) { // advance the FIFO queue bounds size_t i = bounds & (FastMixerDumpState::kSamplingN - 1); bounds = (bounds & 0xFFFF0000) | ((bounds + 1) & 0xFFFF); if (full) { bounds += 0x10000; } else if (!(bounds & (FastMixerDumpState::kSamplingN - 1))) { full = true; } // compute the delta value of clock_gettime(CLOCK_MONOTONIC) uint32_t monotonicNs = nsec; if (sec > 0 && sec < 4) { monotonicNs += sec * 1000000000; } // compute the raw CPU load = delta value of clock_gettime(CLOCK_THREAD_CPUTIME_ID) uint32_t loadNs = 0; struct timespec newLoad; rc = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &newLoad); if (rc == 0) { if (oldLoadValid) { sec = newLoad.tv_sec - oldLoad.tv_sec; nsec = newLoad.tv_nsec - oldLoad.tv_nsec; if (nsec < 0) { --sec; nsec += 1000000000; } loadNs = nsec; if (sec > 0 && sec < 4) { loadNs += sec * 1000000000; } } else { // first time through the loop oldLoadValid = true; } oldLoad = newLoad; } #ifdef CPU_FREQUENCY_STATISTICS // get the absolute value of CPU clock frequency in kHz int cpuNum = sched_getcpu(); uint32_t kHz = tcu.getCpukHz(cpuNum); kHz = (kHz << 4) | (cpuNum & 0xF); #endif // save values in FIFO queues for dumpsys // these stores #1, #2, #3 are not atomic with respect to each other, // or with respect to store #4 below dumpState->mMonotonicNs[i] = monotonicNs; dumpState->mLoadNs[i] = loadNs; #ifdef CPU_FREQUENCY_STATISTICS dumpState->mCpukHz[i] = kHz; #endif // this store #4 is not atomic with respect to stores #1, #2, #3 above, but // the newest open and oldest closed halves are atomic with respect to each other dumpState->mBounds = bounds; #if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER) ATRACE_INT("cycle_ms", monotonicNs / 1000000); ATRACE_INT("load_us", loadNs / 1000); #endif } #endif } else { // first time through the loop oldTsValid = true; sleepNs = periodNs; ignoreNextOverrun = true; } oldTs = newTs; } else { // monotonic clock is broken oldTsValid = false; sleepNs = periodNs; } } // for (;;) // never return 'true'; Thread::_threadLoop() locks mutex which can result in priority inversion } FastMixerDumpState::FastMixerDumpState() : mCommand(FastMixerState::INITIAL), mWriteSequence(0), mFramesWritten(0), mNumTracks(0), mWriteErrors(0), mUnderruns(0), mOverruns(0), mSampleRate(0), mFrameCount(0), /* mMeasuredWarmupTs({0, 0}), */ mWarmupCycles(0), mTrackMask(0) #ifdef FAST_MIXER_STATISTICS , mBounds(0) #endif { mMeasuredWarmupTs.tv_sec = 0; mMeasuredWarmupTs.tv_nsec = 0; #ifdef FAST_MIXER_STATISTICS // sample arrays aren't accessed atomically with respect to the bounds, // so clearing reduces chance for dumpsys to read random uninitialized samples memset(&mMonotonicNs, 0, sizeof(mMonotonicNs)); memset(&mLoadNs, 0, sizeof(mLoadNs)); #ifdef CPU_FREQUENCY_STATISTICS memset(&mCpukHz, 0, sizeof(mCpukHz)); #endif #endif } FastMixerDumpState::~FastMixerDumpState() { } // helper function called by qsort() static int compare_uint32_t(const void *pa, const void *pb) { uint32_t a = *(const uint32_t *)pa; uint32_t b = *(const uint32_t *)pb; if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } } void FastMixerDumpState::dump(int fd) { if (mCommand == FastMixerState::INITIAL) { fdprintf(fd, "FastMixer not initialized\n"); return; } #define COMMAND_MAX 32 char string[COMMAND_MAX]; switch (mCommand) { case FastMixerState::INITIAL: strcpy(string, "INITIAL"); break; case FastMixerState::HOT_IDLE: strcpy(string, "HOT_IDLE"); break; case FastMixerState::COLD_IDLE: strcpy(string, "COLD_IDLE"); break; case FastMixerState::EXIT: strcpy(string, "EXIT"); break; case FastMixerState::MIX: strcpy(string, "MIX"); break; case FastMixerState::WRITE: strcpy(string, "WRITE"); break; case FastMixerState::MIX_WRITE: strcpy(string, "MIX_WRITE"); break; default: snprintf(string, COMMAND_MAX, "%d", mCommand); break; } double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) + (mMeasuredWarmupTs.tv_nsec / 1000000.0); double mixPeriodSec = (double) mFrameCount / (double) mSampleRate; fdprintf(fd, "FastMixer command=%s writeSequence=%u framesWritten=%u\n" " numTracks=%u writeErrors=%u underruns=%u overruns=%u\n" " sampleRate=%u frameCount=%u measuredWarmup=%.3g ms, warmupCycles=%u\n" " mixPeriod=%.2f ms\n", string, mWriteSequence, mFramesWritten, mNumTracks, mWriteErrors, mUnderruns, mOverruns, mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles, mixPeriodSec * 1e3); #ifdef FAST_MIXER_STATISTICS // find the interval of valid samples uint32_t bounds = mBounds; uint32_t newestOpen = bounds & 0xFFFF; uint32_t oldestClosed = bounds >> 16; uint32_t n = (newestOpen - oldestClosed) & 0xFFFF; if (n > kSamplingN) { ALOGE("too many samples %u", n); n = kSamplingN; } // statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency, // and adjusted CPU load in MHz normalized for CPU clock frequency CentralTendencyStatistics wall, loadNs; #ifdef CPU_FREQUENCY_STATISTICS CentralTendencyStatistics kHz, loadMHz; uint32_t previousCpukHz = 0; #endif // Assuming a normal distribution for cycle times, three standard deviations on either side of // the mean account for 99.73% of the population. So if we take each tail to be 1/1000 of the // sample set, we get 99.8% combined, or close to three standard deviations. static const uint32_t kTailDenominator = 1000; uint32_t *tail = n >= kTailDenominator ? new uint32_t[n] : NULL; // loop over all the samples for (uint32_t j = 0; j < n; ++j) { size_t i = oldestClosed++ & (kSamplingN - 1); uint32_t wallNs = mMonotonicNs[i]; if (tail != NULL) { tail[j] = wallNs; } wall.sample(wallNs); uint32_t sampleLoadNs = mLoadNs[i]; loadNs.sample(sampleLoadNs); #ifdef CPU_FREQUENCY_STATISTICS uint32_t sampleCpukHz = mCpukHz[i]; // skip bad kHz samples if ((sampleCpukHz & ~0xF) != 0) { kHz.sample(sampleCpukHz >> 4); if (sampleCpukHz == previousCpukHz) { double megacycles = (double) sampleLoadNs * (double) (sampleCpukHz >> 4) * 1e-12; double adjMHz = megacycles / mixPeriodSec; // _not_ wallNs * 1e9 loadMHz.sample(adjMHz); } } previousCpukHz = sampleCpukHz; #endif } fdprintf(fd, "Simple moving statistics over last %.1f seconds:\n", wall.n() * mixPeriodSec); fdprintf(fd, " wall clock time in ms per mix cycle:\n" " mean=%.2f min=%.2f max=%.2f stddev=%.2f\n", wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6, wall.stddev()*1e-6); fdprintf(fd, " raw CPU load in us per mix cycle:\n" " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n", loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3, loadNs.stddev()*1e-3); #ifdef CPU_FREQUENCY_STATISTICS fdprintf(fd, " CPU clock frequency in MHz:\n" " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n", kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3); fdprintf(fd, " adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n" " mean=%.1f min=%.1f max=%.1f stddev=%.1f\n", loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev()); #endif if (tail != NULL) { qsort(tail, n, sizeof(uint32_t), compare_uint32_t); // assume same number of tail samples on each side, left and right uint32_t count = n / kTailDenominator; CentralTendencyStatistics left, right; for (uint32_t i = 0; i < count; ++i) { left.sample(tail[i]); right.sample(tail[n - (i + 1)]); } fdprintf(fd, "Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n" " left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n" " right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n", left.mean()*1e-6, left.minimum()*1e-6, left.maximum()*1e-6, left.stddev()*1e-6, right.mean()*1e-6, right.minimum()*1e-6, right.maximum()*1e-6, right.stddev()*1e-6); delete[] tail; } #endif // The active track mask and track states are updated non-atomically. // So if we relied on isActive to decide whether to display, // then we might display an obsolete track or omit an active track. // Instead we always display all tracks, with an indication // of whether we think the track is active. uint32_t trackMask = mTrackMask; fdprintf(fd, "Fast tracks: kMaxFastTracks=%u activeMask=%#x\n", FastMixerState::kMaxFastTracks, trackMask); fdprintf(fd, "Index Active Full Partial Empty Recent Ready\n"); for (uint32_t i = 0; i < FastMixerState::kMaxFastTracks; ++i, trackMask >>= 1) { bool isActive = trackMask & 1; const FastTrackDump *ftDump = &mTracks[i]; const FastTrackUnderruns& underruns = ftDump->mUnderruns; const char *mostRecent; switch (underruns.mBitFields.mMostRecent) { case UNDERRUN_FULL: mostRecent = "full"; break; case UNDERRUN_PARTIAL: mostRecent = "partial"; break; case UNDERRUN_EMPTY: mostRecent = "empty"; break; default: mostRecent = "?"; break; } fdprintf(fd, "%5u %6s %4u %7u %5u %7s %5u\n", i, isActive ? "yes" : "no", (underruns.mBitFields.mFull) & UNDERRUN_MASK, (underruns.mBitFields.mPartial) & UNDERRUN_MASK, (underruns.mBitFields.mEmpty) & UNDERRUN_MASK, mostRecent, ftDump->mFramesReady); } } } // namespace android
rex-xxx/mt6572_x201
frameworks/av/services/audioflinger/FastMixer.cpp
C++
gpl-2.0
36,413
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-02-09 08:44 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('statusboard', '0005_merge'), ] operations = [ migrations.CreateModel( name='Maintenance', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('scheduled', models.DateTimeField()), ('name', models.CharField(max_length=255)), ('description', models.TextField()), ], options={ 'abstract': False, }, ), ]
edigiacomo/django-statusboard
statusboard/migrations/0006_maintenance.py
Python
gpl-2.0
1,099
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import the Joomla modellist library jimport('joomla.application.component.modeladmin'); /** * HelloWorldList Model */ class RentalModelPayment extends JModelAdmin { /* * Method to get the payment form * */ public function getPaymentForm($data = array(), $loadData = true) { JForm::addFormPath(JPATH_LIBRARIES . '/frenchconnections/forms'); $form = $this->loadForm('com_rental.helloworld', 'payment', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } // TO DO - This is a bit messy - most likely should remove this method simply use // if then else logic in getForm to determine the form to use. A separate // method could be called to determine form to load based on layout etc $data = JFactory::getApplication()->getUserState('com_rental.renewal.data', array()); $data['id'] = $id = $this->getState($this->getName() . '.id', ''); $form->bind($data); return $form; } public function getForm($data = array(), $loadData = true) { JForm::addFormPath(JPATH_LIBRARIES . '/frenchconnections/forms'); $form = $this->loadForm('com_rental.helloworld', 'account', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } public function getBillingDetails($data = array()) { $model = JModelLegacy::getInstance('Property', 'RentalModel', array('ignore_request' => true)); $property_id = $data['id']; $property = $model->getItem($property_id); $owner_id = $property->created_by; if (!$owner_id) { // Uh oh, no owner id. With out card billing details payment will fail anyway... return $data; } $user = JFactory::getUser($owner_id); // Get the dispatcher and load the user's plugins. $dispatcher = JEventDispatcher::getInstance(); JPluginHelper::importPlugin('user'); $user_data = new JObject; $user_data->id = $owner_id; // Trigger the data preparation event. $dispatcher->trigger('onContentPrepareData', array('com_users.user', &$user_data)); $data['BillingFirstnames'] = $user_data->firstname; $data['BillingSurname'] = $user_data->surname; $data['BillingAddress1'] = $user_data->address1; $data['BillingAddress2'] = $user_data->address2; $data['BillingCity'] = $user_data->city; $data['BillingPostCode'] = $user_data->postal_code; $data['BillingEmailAddress'] = $user->email; $data['BillingCountry'] = $user_data->country; $data['BillingState'] = $user_data->state; return $data; } private function _getOWnerID(int $property_id = null) { } public function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_rental.edit.listing.data', array()); // Which layout are we working on? $layout = JFactory::getApplication()->input->get('layout', '', 'string'); // If this is a the payment layout/view then we need to pre-load some data into the form. // In particular, we need the property listing id. if ($layout == 'payment') { } return $data; } /* * param JForm $form The JForm instance for the view being edited * param array $data The form data as derived from the view (may be empty) * * @return void * */ protected function preprocessForm(JForm $form, $data) { // Get the input form data $input = JFactory::getApplication()->input; // And tease out whether the use_invoice_address field is ticked or not $formData = $input->get('jform', array(), 'array'); $filter = JFilterInput::getInstance(); $use_invoice_address = $filter->clean($formData['use_invoice_address'], 'int'); if ($use_invoice_address) { // Make the billing details optional $fieldset = $form->getFieldset('billing-details'); foreach ($fieldset as $field) { $form->setFieldAttribute($field->fieldname, 'required', 'false'); } } } public function getTable($type = 'Property', $prefix = 'RentalTable', $options = array()) { return JTable::getInstance($type, $prefix, $options); } }
adster101/French-Connections-
administrator/components/com_rental/models/payment.php
PHP
gpl-2.0
4,322
<html lang="en"> <head> <title>Gforth Manual</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Gforth Manual"> <meta name="generator" content="makeinfo 4.9"> <link title="Top" rel="start" href="index.html#Top"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This manual is for Gforth (version 0.7.0, November 2, 2008), a fast and portable implementation of the ANS Forth language. It serves as reference manual, but it also contains an introduction to Forth and a Forth tutorial. Copyright (C) 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with the Front-Cover texts being "A GNU Manual," and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled "GNU Free Documentation License." (a) The FSF's Back-Cover Text is: "You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development." --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <h1 class="settitle">Gforth Manual</h1> <div class="contents"> <h2>Table of Contents</h2> <ul> <li><a name="toc_Top" href="index.html#Top">Gforth</a> <li><a name="toc_Goals" href="Goals.html#Goals">1 Goals of Gforth</a> <li><a name="toc_Gforth-Environment" href="Gforth-Environment.html#Gforth-Environment">2 Gforth Environment</a> <ul> <li><a href="Invoking-Gforth.html#Invoking-Gforth">2.1 Invoking Gforth</a> <li><a href="Leaving-Gforth.html#Leaving-Gforth">2.2 Leaving Gforth</a> <li><a href="Command_002dline-editing.html#Command_002dline-editing">2.3 Command-line editing</a> <li><a href="Environment-variables.html#Environment-variables">2.4 Environment variables</a> <li><a href="Gforth-Files.html#Gforth-Files">2.5 Gforth files</a> <li><a href="Gforth-in-pipes.html#Gforth-in-pipes">2.6 Gforth in pipes</a> <li><a href="Startup-speed.html#Startup-speed">2.7 Startup speed</a> </li></ul> <li><a name="toc_Tutorial" href="Tutorial.html#Tutorial">3 Forth Tutorial</a> <ul> <li><a href="Starting-Gforth-Tutorial.html#Starting-Gforth-Tutorial">3.1 Starting Gforth</a> <li><a href="Syntax-Tutorial.html#Syntax-Tutorial">3.2 Syntax</a> <li><a href="Crash-Course-Tutorial.html#Crash-Course-Tutorial">3.3 Crash Course</a> <li><a href="Stack-Tutorial.html#Stack-Tutorial">3.4 Stack</a> <li><a href="Arithmetics-Tutorial.html#Arithmetics-Tutorial">3.5 Arithmetics</a> <li><a href="Stack-Manipulation-Tutorial.html#Stack-Manipulation-Tutorial">3.6 Stack Manipulation</a> <li><a href="Using-files-for-Forth-code-Tutorial.html#Using-files-for-Forth-code-Tutorial">3.7 Using files for Forth code</a> <li><a href="Comments-Tutorial.html#Comments-Tutorial">3.8 Comments</a> <li><a href="Colon-Definitions-Tutorial.html#Colon-Definitions-Tutorial">3.9 Colon Definitions</a> <li><a href="Decompilation-Tutorial.html#Decompilation-Tutorial">3.10 Decompilation</a> <li><a href="Stack_002dEffect-Comments-Tutorial.html#Stack_002dEffect-Comments-Tutorial">3.11 Stack-Effect Comments</a> <li><a href="Types-Tutorial.html#Types-Tutorial">3.12 Types</a> <li><a href="Factoring-Tutorial.html#Factoring-Tutorial">3.13 Factoring</a> <li><a href="Designing-the-stack-effect-Tutorial.html#Designing-the-stack-effect-Tutorial">3.14 Designing the stack effect</a> <li><a href="Local-Variables-Tutorial.html#Local-Variables-Tutorial">3.15 Local Variables</a> <li><a href="Conditional-execution-Tutorial.html#Conditional-execution-Tutorial">3.16 Conditional execution</a> <li><a href="Flags-and-Comparisons-Tutorial.html#Flags-and-Comparisons-Tutorial">3.17 Flags and Comparisons</a> <li><a href="General-Loops-Tutorial.html#General-Loops-Tutorial">3.18 General Loops</a> <li><a href="Counted-loops-Tutorial.html#Counted-loops-Tutorial">3.19 Counted loops</a> <li><a href="Recursion-Tutorial.html#Recursion-Tutorial">3.20 Recursion</a> <li><a href="Leaving-definitions-or-loops-Tutorial.html#Leaving-definitions-or-loops-Tutorial">3.21 Leaving definitions or loops</a> <li><a href="Return-Stack-Tutorial.html#Return-Stack-Tutorial">3.22 Return Stack</a> <li><a href="Memory-Tutorial.html#Memory-Tutorial">3.23 Memory</a> <li><a href="Characters-and-Strings-Tutorial.html#Characters-and-Strings-Tutorial">3.24 Characters and Strings</a> <li><a href="Alignment-Tutorial.html#Alignment-Tutorial">3.25 Alignment</a> <li><a href="Floating-Point-Tutorial.html#Floating-Point-Tutorial">3.26 Floating Point</a> <li><a href="Files-Tutorial.html#Files-Tutorial">3.27 Files</a> <ul> <li><a href="Files-Tutorial.html#Files-Tutorial">3.27.1 Open file for input</a> <li><a href="Files-Tutorial.html#Files-Tutorial">3.27.2 Create file for output</a> <li><a href="Files-Tutorial.html#Files-Tutorial">3.27.3 Scan file for a particular line</a> <li><a href="Files-Tutorial.html#Files-Tutorial">3.27.4 Copy input to output</a> <li><a href="Files-Tutorial.html#Files-Tutorial">3.27.5 Close files</a> </li></ul> <li><a href="Interpretation-and-Compilation-Semantics-and-Immediacy-Tutorial.html#Interpretation-and-Compilation-Semantics-and-Immediacy-Tutorial">3.28 Interpretation and Compilation Semantics and Immediacy</a> <li><a href="Execution-Tokens-Tutorial.html#Execution-Tokens-Tutorial">3.29 Execution Tokens</a> <li><a href="Exceptions-Tutorial.html#Exceptions-Tutorial">3.30 Exceptions</a> <li><a href="Defining-Words-Tutorial.html#Defining-Words-Tutorial">3.31 Defining Words</a> <li><a href="Arrays-and-Records-Tutorial.html#Arrays-and-Records-Tutorial">3.32 Arrays and Records</a> <li><a href="POSTPONE-Tutorial.html#POSTPONE-Tutorial">3.33 <code>POSTPONE</code></a> <li><a href="Literal-Tutorial.html#Literal-Tutorial">3.34 <code>Literal</code></a> <li><a href="Advanced-macros-Tutorial.html#Advanced-macros-Tutorial">3.35 Advanced macros</a> <li><a href="Compilation-Tokens-Tutorial.html#Compilation-Tokens-Tutorial">3.36 Compilation Tokens</a> <li><a href="Wordlists-and-Search-Order-Tutorial.html#Wordlists-and-Search-Order-Tutorial">3.37 Wordlists and Search Order</a> </li></ul> <li><a name="toc_Introduction" href="Introduction.html#Introduction">4 An Introduction to ANS Forth</a> <ul> <li><a href="Introducing-the-Text-Interpreter.html#Introducing-the-Text-Interpreter">4.1 Introducing the Text Interpreter</a> <li><a href="Stacks-and-Postfix-notation.html#Stacks-and-Postfix-notation">4.2 Stacks, postfix notation and parameter passing</a> <li><a href="Your-first-definition.html#Your-first-definition">4.3 Your first Forth definition</a> <li><a href="How-does-that-work_003f.html#How-does-that-work_003f">4.4 How does that work?</a> <li><a href="Forth-is-written-in-Forth.html#Forth-is-written-in-Forth">4.5 Forth is written in Forth</a> <li><a href="Review-_002d-elements-of-a-Forth-system.html#Review-_002d-elements-of-a-Forth-system">4.6 Review - elements of a Forth system</a> <li><a href="Where-to-go-next.html#Where-to-go-next">4.7 Where To Go Next</a> <li><a href="Exercises.html#Exercises">4.8 Exercises</a> </li></ul> <li><a name="toc_Words" href="Words.html#Words">5 Forth Words</a> <ul> <li><a href="Notation.html#Notation">5.1 Notation</a> <li><a href="Case-insensitivity.html#Case-insensitivity">5.2 Case insensitivity</a> <li><a href="Comments.html#Comments">5.3 Comments</a> <li><a href="Boolean-Flags.html#Boolean-Flags">5.4 Boolean Flags</a> <li><a href="Arithmetic.html#Arithmetic">5.5 Arithmetic</a> <ul> <li><a href="Single-precision.html#Single-precision">5.5.1 Single precision</a> <li><a href="Double-precision.html#Double-precision">5.5.2 Double precision</a> <li><a href="Bitwise-operations.html#Bitwise-operations">5.5.3 Bitwise operations</a> <li><a href="Numeric-comparison.html#Numeric-comparison">5.5.4 Numeric comparison</a> <li><a href="Mixed-precision.html#Mixed-precision">5.5.5 Mixed precision</a> <li><a href="Floating-Point.html#Floating-Point">5.5.6 Floating Point</a> </li></ul> <li><a href="Stack-Manipulation.html#Stack-Manipulation">5.6 Stack Manipulation</a> <ul> <li><a href="Data-stack.html#Data-stack">5.6.1 Data stack</a> <li><a href="Floating-point-stack.html#Floating-point-stack">5.6.2 Floating point stack</a> <li><a href="Return-stack.html#Return-stack">5.6.3 Return stack</a> <li><a href="Locals-stack.html#Locals-stack">5.6.4 Locals stack</a> <li><a href="Stack-pointer-manipulation.html#Stack-pointer-manipulation">5.6.5 Stack pointer manipulation</a> </li></ul> <li><a href="Memory.html#Memory">5.7 Memory</a> <ul> <li><a href="Memory-model.html#Memory-model">5.7.1 ANS Forth and Gforth memory models</a> <li><a href="Dictionary-allocation.html#Dictionary-allocation">5.7.2 Dictionary allocation</a> <li><a href="Heap-Allocation.html#Heap-Allocation">5.7.3 Heap allocation</a> <li><a href="Memory-Access.html#Memory-Access">5.7.4 Memory Access</a> <li><a href="Address-arithmetic.html#Address-arithmetic">5.7.5 Address arithmetic</a> <li><a href="Memory-Blocks.html#Memory-Blocks">5.7.6 Memory Blocks</a> </li></ul> <li><a href="Control-Structures.html#Control-Structures">5.8 Control Structures</a> <ul> <li><a href="Selection.html#Selection">5.8.1 Selection</a> <li><a href="Simple-Loops.html#Simple-Loops">5.8.2 Simple Loops</a> <li><a href="Counted-Loops.html#Counted-Loops">5.8.3 Counted Loops</a> <li><a href="Arbitrary-control-structures.html#Arbitrary-control-structures">5.8.4 Arbitrary control structures</a> <ul> <li><a href="Arbitrary-control-structures.html#Arbitrary-control-structures">5.8.4.1 Programming Style</a> </li></ul> <li><a href="Calls-and-returns.html#Calls-and-returns">5.8.5 Calls and returns</a> <li><a href="Exception-Handling.html#Exception-Handling">5.8.6 Exception Handling</a> </li></ul> <li><a href="Defining-Words.html#Defining-Words">5.9 Defining Words</a> <ul> <li><a href="CREATE.html#CREATE">5.9.1 <code>CREATE</code></a> <li><a href="Variables.html#Variables">5.9.2 Variables</a> <li><a href="Constants.html#Constants">5.9.3 Constants</a> <li><a href="Values.html#Values">5.9.4 Values</a> <li><a href="Colon-Definitions.html#Colon-Definitions">5.9.5 Colon Definitions</a> <li><a href="Anonymous-Definitions.html#Anonymous-Definitions">5.9.6 Anonymous Definitions</a> <li><a href="Supplying-names.html#Supplying-names">5.9.7 Supplying the name of a defined word</a> <li><a href="User_002ddefined-Defining-Words.html#User_002ddefined-Defining-Words">5.9.8 User-defined Defining Words</a> <ul> <li><a href="CREATE_002e_002eDOES_003e-applications.html#CREATE_002e_002eDOES_003e-applications">5.9.8.1 Applications of <code>CREATE..DOES&gt;</code></a> <li><a href="CREATE_002e_002eDOES_003e-details.html#CREATE_002e_002eDOES_003e-details">5.9.8.2 The gory details of <code>CREATE..DOES&gt;</code></a> <li><a href="Advanced-does_003e-usage-example.html#Advanced-does_003e-usage-example">5.9.8.3 Advanced does&gt; usage example</a> <li><a href="Const_002ddoes_003e.html#Const_002ddoes_003e">5.9.8.4 <code>Const-does&gt;</code></a> </li></ul> <li><a href="Deferred-Words.html#Deferred-Words">5.9.9 Deferred Words</a> <li><a href="Aliases.html#Aliases">5.9.10 Aliases</a> </li></ul> <li><a href="Interpretation-and-Compilation-Semantics.html#Interpretation-and-Compilation-Semantics">5.10 Interpretation and Compilation Semantics</a> <ul> <li><a href="Combined-words.html#Combined-words">5.10.1 Combined Words</a> </li></ul> <li><a href="Tokens-for-Words.html#Tokens-for-Words">5.11 Tokens for Words</a> <ul> <li><a href="Execution-token.html#Execution-token">5.11.1 Execution token</a> <li><a href="Compilation-token.html#Compilation-token">5.11.2 Compilation token</a> <li><a href="Name-token.html#Name-token">5.11.3 Name token</a> </li></ul> <li><a href="Compiling-words.html#Compiling-words">5.12 Compiling words</a> <ul> <li><a href="Literals.html#Literals">5.12.1 Literals</a> <li><a href="Macros.html#Macros">5.12.2 Macros</a> </li></ul> <li><a href="The-Text-Interpreter.html#The-Text-Interpreter">5.13 The Text Interpreter</a> <ul> <li><a href="Input-Sources.html#Input-Sources">5.13.1 Input Sources</a> <li><a href="Number-Conversion.html#Number-Conversion">5.13.2 Number Conversion</a> <li><a href="Interpret_002fCompile-states.html#Interpret_002fCompile-states">5.13.3 Interpret/Compile states</a> <li><a href="Interpreter-Directives.html#Interpreter-Directives">5.13.4 Interpreter Directives</a> </li></ul> <li><a href="The-Input-Stream.html#The-Input-Stream">5.14 The Input Stream</a> <li><a href="Word-Lists.html#Word-Lists">5.15 Word Lists</a> <ul> <li><a href="Vocabularies.html#Vocabularies">5.15.1 Vocabularies</a> <li><a href="Why-use-word-lists_003f.html#Why-use-word-lists_003f">5.15.2 Why use word lists?</a> <li><a href="Word-list-example.html#Word-list-example">5.15.3 Word list example</a> </li></ul> <li><a href="Environmental-Queries.html#Environmental-Queries">5.16 Environmental Queries</a> <li><a href="Files.html#Files">5.17 Files</a> <ul> <li><a href="Forth-source-files.html#Forth-source-files">5.17.1 Forth source files</a> <li><a href="General-files.html#General-files">5.17.2 General files</a> <li><a href="Redirection.html#Redirection">5.17.3 Redirection</a> <li><a href="Search-Paths.html#Search-Paths">5.17.4 Search Paths</a> <ul> <li><a href="Source-Search-Paths.html#Source-Search-Paths">5.17.4.1 Source Search Paths</a> <li><a href="General-Search-Paths.html#General-Search-Paths">5.17.4.2 General Search Paths</a> </li></ul> </li></ul> <li><a href="Blocks.html#Blocks">5.18 Blocks</a> <li><a href="Other-I_002fO.html#Other-I_002fO">5.19 Other I/O</a> <ul> <li><a href="Simple-numeric-output.html#Simple-numeric-output">5.19.1 Simple numeric output</a> <li><a href="Formatted-numeric-output.html#Formatted-numeric-output">5.19.2 Formatted numeric output</a> <li><a href="String-Formats.html#String-Formats">5.19.3 String Formats</a> <li><a href="Displaying-characters-and-strings.html#Displaying-characters-and-strings">5.19.4 Displaying characters and strings</a> <li><a href="Terminal-output.html#Terminal-output">5.19.5 Terminal output</a> <li><a href="Single_002dkey-input.html#Single_002dkey-input">5.19.6 Single-key input</a> <li><a href="Line-input-and-conversion.html#Line-input-and-conversion">5.19.7 Line input and conversion</a> <li><a href="Pipes.html#Pipes">5.19.8 Pipes</a> <li><a href="Xchars-and-Unicode.html#Xchars-and-Unicode">5.19.9 Xchars and Unicode</a> </li></ul> <li><a href="OS-command-line-arguments.html#OS-command-line-arguments">5.20 OS command line arguments</a> <li><a href="Locals.html#Locals">5.21 Locals</a> <ul> <li><a href="Gforth-locals.html#Gforth-locals">5.21.1 Gforth locals</a> <ul> <li><a href="Where-are-locals-visible-by-name_003f.html#Where-are-locals-visible-by-name_003f">5.21.1.1 Where are locals visible by name?</a> <li><a href="How-long-do-locals-live_003f.html#How-long-do-locals-live_003f">5.21.1.2 How long do locals live?</a> <li><a href="Locals-programming-style.html#Locals-programming-style">5.21.1.3 Locals programming style</a> <li><a href="Locals-implementation.html#Locals-implementation">5.21.1.4 Locals implementation</a> </li></ul> <li><a href="ANS-Forth-locals.html#ANS-Forth-locals">5.21.2 ANS Forth locals</a> </li></ul> <li><a href="Structures.html#Structures">5.22 Structures</a> <ul> <li><a href="Why-explicit-structure-support_003f.html#Why-explicit-structure-support_003f">5.22.1 Why explicit structure support?</a> <li><a href="Structure-Usage.html#Structure-Usage">5.22.2 Structure Usage</a> <li><a href="Structure-Naming-Convention.html#Structure-Naming-Convention">5.22.3 Structure Naming Convention</a> <li><a href="Structure-Implementation.html#Structure-Implementation">5.22.4 Structure Implementation</a> <li><a href="Structure-Glossary.html#Structure-Glossary">5.22.5 Structure Glossary</a> <li><a href="Forth200x-Structures.html#Forth200x-Structures">5.22.6 Forth200x Structures</a> </li></ul> <li><a href="Object_002doriented-Forth.html#Object_002doriented-Forth">5.23 Object-oriented Forth</a> <ul> <li><a href="Why-object_002doriented-programming_003f.html#Why-object_002doriented-programming_003f">5.23.1 Why object-oriented programming?</a> <li><a href="Object_002dOriented-Terminology.html#Object_002dOriented-Terminology">5.23.2 Object-Oriented Terminology</a> <li><a href="Objects.html#Objects">5.23.3 The <samp><span class="file">objects.fs</span></samp> model</a> <ul> <li><a href="Properties-of-the-Objects-model.html#Properties-of-the-Objects-model">5.23.3.1 Properties of the <samp><span class="file">objects.fs</span></samp> model</a> <li><a href="Basic-Objects-Usage.html#Basic-Objects-Usage">5.23.3.2 Basic <samp><span class="file">objects.fs</span></samp> Usage</a> <li><a href="The-Objects-base-class.html#The-Objects-base-class">5.23.3.3 The <samp><span class="file">object.fs</span></samp> base class</a> <li><a href="Creating-objects.html#Creating-objects">5.23.3.4 Creating objects</a> <li><a href="Object_002dOriented-Programming-Style.html#Object_002dOriented-Programming-Style">5.23.3.5 Object-Oriented Programming Style</a> <li><a href="Class-Binding.html#Class-Binding">5.23.3.6 Class Binding</a> <li><a href="Method-conveniences.html#Method-conveniences">5.23.3.7 Method conveniences</a> <li><a href="Classes-and-Scoping.html#Classes-and-Scoping">5.23.3.8 Classes and Scoping</a> <li><a href="Dividing-classes.html#Dividing-classes">5.23.3.9 Dividing classes</a> <li><a href="Object-Interfaces.html#Object-Interfaces">5.23.3.10 Object Interfaces</a> <li><a href="Objects-Implementation.html#Objects-Implementation">5.23.3.11 <samp><span class="file">objects.fs</span></samp> Implementation</a> <li><a href="Objects-Glossary.html#Objects-Glossary">5.23.3.12 <samp><span class="file">objects.fs</span></samp> Glossary</a> </li></ul> <li><a href="OOF.html#OOF">5.23.4 The <samp><span class="file">oof.fs</span></samp> model</a> <ul> <li><a href="Properties-of-the-OOF-model.html#Properties-of-the-OOF-model">5.23.4.1 Properties of the <samp><span class="file">oof.fs</span></samp> model</a> <li><a href="Basic-OOF-Usage.html#Basic-OOF-Usage">5.23.4.2 Basic <samp><span class="file">oof.fs</span></samp> Usage</a> <li><a href="The-OOF-base-class.html#The-OOF-base-class">5.23.4.3 The <samp><span class="file">oof.fs</span></samp> base class</a> <li><a href="Class-Declaration.html#Class-Declaration">5.23.4.4 Class Declaration</a> <li><a href="Class-Implementation.html#Class-Implementation">5.23.4.5 Class Implementation</a> </li></ul> <li><a href="Mini_002dOOF.html#Mini_002dOOF">5.23.5 The <samp><span class="file">mini-oof.fs</span></samp> model</a> <ul> <li><a href="Basic-Mini_002dOOF-Usage.html#Basic-Mini_002dOOF-Usage">5.23.5.1 Basic <samp><span class="file">mini-oof.fs</span></samp> Usage</a> <li><a href="Mini_002dOOF-Example.html#Mini_002dOOF-Example">5.23.5.2 Mini-OOF Example</a> <li><a href="Mini_002dOOF-Implementation.html#Mini_002dOOF-Implementation">5.23.5.3 <samp><span class="file">mini-oof.fs</span></samp> Implementation</a> </li></ul> <li><a href="Comparison-with-other-object-models.html#Comparison-with-other-object-models">5.23.6 Comparison with other object models</a> </li></ul> <li><a href="Programming-Tools.html#Programming-Tools">5.24 Programming Tools</a> <ul> <li><a href="Examining.html#Examining">5.24.1 Examining data and code</a> <li><a href="Forgetting-words.html#Forgetting-words">5.24.2 Forgetting words</a> <li><a href="Debugging.html#Debugging">5.24.3 Debugging</a> <li><a href="Assertions.html#Assertions">5.24.4 Assertions</a> <li><a href="Singlestep-Debugger.html#Singlestep-Debugger">5.24.5 Singlestep Debugger</a> </li></ul> <li><a href="C-Interface.html#C-Interface">5.25 C Interface</a> <ul> <li><a href="Calling-C-Functions.html#Calling-C-Functions">5.25.1 Calling C functions</a> <li><a href="Declaring-C-Functions.html#Declaring-C-Functions">5.25.2 Declaring C Functions</a> <li><a href="Calling-C-function-pointers.html#Calling-C-function-pointers">5.25.3 Calling C function pointers from Forth</a> <li><a href="Defining-library-interfaces.html#Defining-library-interfaces">5.25.4 Defining library interfaces</a> <li><a href="Declaring-OS_002dlevel-libraries.html#Declaring-OS_002dlevel-libraries">5.25.5 Declaring OS-level libraries</a> <li><a href="Callbacks.html#Callbacks">5.25.6 Callbacks</a> <li><a href="C-interface-internals.html#C-interface-internals">5.25.7 How the C interface works</a> <li><a href="Low_002dLevel-C-Interface-Words.html#Low_002dLevel-C-Interface-Words">5.25.8 Low-Level C Interface Words</a> </li></ul> <li><a href="Assembler-and-Code-Words.html#Assembler-and-Code-Words">5.26 Assembler and Code Words</a> <ul> <li><a href="Code-and-_003bcode.html#Code-and-_003bcode">5.26.1 <code>Code</code> and <code>;code</code></a> <li><a href="Common-Assembler.html#Common-Assembler">5.26.2 Common Assembler</a> <li><a href="Common-Disassembler.html#Common-Disassembler">5.26.3 Common Disassembler</a> <li><a href="386-Assembler.html#386-Assembler">5.26.4 386 Assembler</a> <li><a href="Alpha-Assembler.html#Alpha-Assembler">5.26.5 Alpha Assembler</a> <li><a href="MIPS-assembler.html#MIPS-assembler">5.26.6 MIPS assembler</a> <li><a href="PowerPC-assembler.html#PowerPC-assembler">5.26.7 PowerPC assembler</a> <li><a href="ARM-Assembler.html#ARM-Assembler">5.26.8 ARM Assembler</a> <li><a href="Other-assemblers.html#Other-assemblers">5.26.9 Other assemblers</a> </li></ul> <li><a href="Threading-Words.html#Threading-Words">5.27 Threading Words</a> <li><a href="Passing-Commands-to-the-OS.html#Passing-Commands-to-the-OS">5.28 Passing Commands to the Operating System</a> <li><a href="Keeping-track-of-Time.html#Keeping-track-of-Time">5.29 Keeping track of Time</a> <li><a href="Miscellaneous-Words.html#Miscellaneous-Words">5.30 Miscellaneous Words</a> </li></ul> <li><a name="toc_Error-messages" href="Error-messages.html#Error-messages">6 Error messages</a> <li><a name="toc_Tools" href="Tools.html#Tools">7 Tools</a> <ul> <li><a href="ANS-Report.html#ANS-Report">7.1 <samp><span class="file">ans-report.fs</span></samp>: Report the words used, sorted by wordset</a> <ul> <li><a href="ANS-Report.html#ANS-Report">7.1.1 Caveats</a> </li></ul> <li><a href="Stack-depth-changes.html#Stack-depth-changes">7.2 Stack depth changes during interpretation</a> </li></ul> <li><a name="toc_ANS-conformance" href="ANS-conformance.html#ANS-conformance">8 ANS conformance</a> <ul> <li><a href="The-Core-Words.html#The-Core-Words">8.1 The Core Words</a> <ul> <li><a href="core_002didef.html#core_002didef">8.1.1 Implementation Defined Options</a> <li><a href="core_002dambcond.html#core_002dambcond">8.1.2 Ambiguous conditions</a> <li><a href="core_002dother.html#core_002dother">8.1.3 Other system documentation</a> </li></ul> <li><a href="The-optional-Block-word-set.html#The-optional-Block-word-set">8.2 The optional Block word set</a> <ul> <li><a href="block_002didef.html#block_002didef">8.2.1 Implementation Defined Options</a> <li><a href="block_002dambcond.html#block_002dambcond">8.2.2 Ambiguous conditions</a> <li><a href="block_002dother.html#block_002dother">8.2.3 Other system documentation</a> </li></ul> <li><a href="The-optional-Double-Number-word-set.html#The-optional-Double-Number-word-set">8.3 The optional Double Number word set</a> <ul> <li><a href="double_002dambcond.html#double_002dambcond">8.3.1 Ambiguous conditions</a> </li></ul> <li><a href="The-optional-Exception-word-set.html#The-optional-Exception-word-set">8.4 The optional Exception word set</a> <ul> <li><a href="exception_002didef.html#exception_002didef">8.4.1 Implementation Defined Options</a> </li></ul> <li><a href="The-optional-Facility-word-set.html#The-optional-Facility-word-set">8.5 The optional Facility word set</a> <ul> <li><a href="facility_002didef.html#facility_002didef">8.5.1 Implementation Defined Options</a> <li><a href="facility_002dambcond.html#facility_002dambcond">8.5.2 Ambiguous conditions</a> </li></ul> <li><a href="The-optional-File_002dAccess-word-set.html#The-optional-File_002dAccess-word-set">8.6 The optional File-Access word set</a> <ul> <li><a href="file_002didef.html#file_002didef">8.6.1 Implementation Defined Options</a> <li><a href="file_002dambcond.html#file_002dambcond">8.6.2 Ambiguous conditions</a> </li></ul> <li><a href="The-optional-Floating_002dPoint-word-set.html#The-optional-Floating_002dPoint-word-set">8.7 The optional Floating-Point word set</a> <ul> <li><a href="floating_002didef.html#floating_002didef">8.7.1 Implementation Defined Options</a> <li><a href="floating_002dambcond.html#floating_002dambcond">8.7.2 Ambiguous conditions</a> </li></ul> <li><a href="The-optional-Locals-word-set.html#The-optional-Locals-word-set">8.8 The optional Locals word set</a> <ul> <li><a href="locals_002didef.html#locals_002didef">8.8.1 Implementation Defined Options</a> <li><a href="locals_002dambcond.html#locals_002dambcond">8.8.2 Ambiguous conditions</a> </li></ul> <li><a href="The-optional-Memory_002dAllocation-word-set.html#The-optional-Memory_002dAllocation-word-set">8.9 The optional Memory-Allocation word set</a> <ul> <li><a href="memory_002didef.html#memory_002didef">8.9.1 Implementation Defined Options</a> </li></ul> <li><a href="The-optional-Programming_002dTools-word-set.html#The-optional-Programming_002dTools-word-set">8.10 The optional Programming-Tools word set</a> <ul> <li><a href="programming_002didef.html#programming_002didef">8.10.1 Implementation Defined Options</a> <li><a href="programming_002dambcond.html#programming_002dambcond">8.10.2 Ambiguous conditions</a> </li></ul> <li><a href="The-optional-Search_002dOrder-word-set.html#The-optional-Search_002dOrder-word-set">8.11 The optional Search-Order word set</a> <ul> <li><a href="search_002didef.html#search_002didef">8.11.1 Implementation Defined Options</a> <li><a href="search_002dambcond.html#search_002dambcond">8.11.2 Ambiguous conditions</a> </li></ul> </li></ul> <li><a name="toc_Standard-vs-Extensions" href="Standard-vs-Extensions.html#Standard-vs-Extensions">9 Should I use Gforth extensions?</a> <li><a name="toc_Model" href="Model.html#Model">10 Model</a> <li><a name="toc_Integrating-Gforth" href="Integrating-Gforth.html#Integrating-Gforth">11 Integrating Gforth into C programs</a> <li><a name="toc_Emacs-and-Gforth" href="Emacs-and-Gforth.html#Emacs-and-Gforth">12 Emacs and Gforth</a> <ul> <li><a href="Installing-gforth_002eel.html#Installing-gforth_002eel">12.1 Installing gforth.el</a> <li><a href="Emacs-Tags.html#Emacs-Tags">12.2 Emacs Tags</a> <li><a href="Hilighting.html#Hilighting">12.3 Hilighting</a> <li><a href="Auto_002dIndentation.html#Auto_002dIndentation">12.4 Auto-Indentation</a> <li><a href="Blocks-Files.html#Blocks-Files">12.5 Blocks Files</a> </li></ul> <li><a name="toc_Image-Files" href="Image-Files.html#Image-Files">13 Image Files</a> <ul> <li><a href="Image-Licensing-Issues.html#Image-Licensing-Issues">13.1 Image Licensing Issues</a> <li><a href="Image-File-Background.html#Image-File-Background">13.2 Image File Background</a> <li><a href="Non_002dRelocatable-Image-Files.html#Non_002dRelocatable-Image-Files">13.3 Non-Relocatable Image Files</a> <li><a href="Data_002dRelocatable-Image-Files.html#Data_002dRelocatable-Image-Files">13.4 Data-Relocatable Image Files</a> <li><a href="Fully-Relocatable-Image-Files.html#Fully-Relocatable-Image-Files">13.5 Fully Relocatable Image Files</a> <ul> <li><a href="gforthmi.html#gforthmi">13.5.1 <samp><span class="file">gforthmi</span></samp></a> <li><a href="cross_002efs.html#cross_002efs">13.5.2 <samp><span class="file">cross.fs</span></samp></a> </li></ul> <li><a href="Stack-and-Dictionary-Sizes.html#Stack-and-Dictionary-Sizes">13.6 Stack and Dictionary Sizes</a> <li><a href="Running-Image-Files.html#Running-Image-Files">13.7 Running Image Files</a> <li><a href="Modifying-the-Startup-Sequence.html#Modifying-the-Startup-Sequence">13.8 Modifying the Startup Sequence</a> </li></ul> <li><a name="toc_Engine" href="Engine.html#Engine">14 Engine</a> <ul> <li><a href="Portability.html#Portability">14.1 Portability</a> <li><a href="Threading.html#Threading">14.2 Threading</a> <ul> <li><a href="Scheduling.html#Scheduling">14.2.1 Scheduling</a> <li><a href="Direct-or-Indirect-Threaded_003f.html#Direct-or-Indirect-Threaded_003f">14.2.2 Direct or Indirect Threaded?</a> <li><a href="Dynamic-Superinstructions.html#Dynamic-Superinstructions">14.2.3 Dynamic Superinstructions</a> <li><a href="DOES_003e.html#DOES_003e">14.2.4 DOES&gt;</a> </li></ul> <li><a href="Primitives.html#Primitives">14.3 Primitives</a> <ul> <li><a href="Automatic-Generation.html#Automatic-Generation">14.3.1 Automatic Generation</a> <li><a href="TOS-Optimization.html#TOS-Optimization">14.3.2 TOS Optimization</a> <li><a href="Produced-code.html#Produced-code">14.3.3 Produced code</a> </li></ul> <li><a href="Performance.html#Performance">14.4 Performance</a> </li></ul> <li><a name="toc_Cross-Compiler" href="Cross-Compiler.html#Cross-Compiler">15 Cross Compiler</a> <ul> <li><a href="Using-the-Cross-Compiler.html#Using-the-Cross-Compiler">15.1 Using the Cross Compiler</a> <li><a href="How-the-Cross-Compiler-Works.html#How-the-Cross-Compiler-Works">15.2 How the Cross Compiler Works</a> </li></ul> <li><a name="toc_Bugs" href="Bugs.html#Bugs">Appendix A Bugs</a> <li><a name="toc_Origin" href="Origin.html#Origin">Appendix B Authors and Ancestors of Gforth</a> <ul> <li><a href="Origin.html#Origin">B.1 Authors and Contributors</a> <li><a href="Origin.html#Origin">B.2 Pedigree</a> </li></ul> <li><a name="toc_Forth_002drelated-information" href="Forth_002drelated-information.html#Forth_002drelated-information">Appendix C Other Forth-related information</a> <li><a name="toc_Licenses" href="Licenses.html#Licenses">Appendix D Licenses</a> <ul> <li><a href="GNU-Free-Documentation-License.html#GNU-Free-Documentation-License">D.1 GNU Free Documentation License</a> <ul> <li><a href="GNU-Free-Documentation-License.html#GNU-Free-Documentation-License">D.1.1 ADDENDUM: How to use this License for your documents</a> </li></ul> <li><a href="Copying.html#Copying">D.2 GNU GENERAL PUBLIC LICENSE</a> </li></ul> <li><a name="toc_Word-Index" href="Word-Index.html#Word-Index">Word Index</a> <li><a name="toc_Concept-Index" href="Concept-Index.html#Concept-Index">Concept and Word Index</a> </li></ul> </div> <div class="node"> <p> <a name="Top"></a> Next:&nbsp;<a rel="next" accesskey="n" href="Goals.html#Goals">Goals</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="http://www.complang.tuwien.ac.at/forth/gforth/index.html#dir">(dir)</a>, Up:&nbsp;<a rel="up" accesskey="u" href="http://www.complang.tuwien.ac.at/forth/gforth/index.html#dir">(dir)</a> <hr> </div> <h2 class="unnumbered">Gforth</h2> <p>This manual is for Gforth (version 0.7.0, November 2, 2008), a fast and portable implementation of the ANS Forth language. It serves as reference manual, but it also contains an introduction to Forth and a Forth tutorial. <p>Copyright &copy; 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008 Free Software Foundation, Inc. <blockquote> Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with the Front-Cover texts being &ldquo;A GNU Manual,&rdquo; and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled &ldquo;GNU Free Documentation License.&rdquo; <p>(a) The FSF's Back-Cover Text is: &ldquo;You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.&rdquo; </blockquote> <ul class="menu"> <li><a accesskey="1" href="Goals.html#Goals">Goals</a>: About the Gforth Project <li><a accesskey="2" href="Gforth-Environment.html#Gforth-Environment">Gforth Environment</a>: Starting (and exiting) Gforth <li><a accesskey="3" href="Tutorial.html#Tutorial">Tutorial</a>: Hands-on Forth Tutorial <li><a accesskey="4" href="Introduction.html#Introduction">Introduction</a>: An introduction to ANS Forth <li><a accesskey="5" href="Words.html#Words">Words</a>: Forth words available in Gforth <li><a accesskey="6" href="Error-messages.html#Error-messages">Error messages</a>: How to interpret them <li><a accesskey="7" href="Tools.html#Tools">Tools</a>: Programming tools <li><a accesskey="8" href="ANS-conformance.html#ANS-conformance">ANS conformance</a>: Implementation-defined options etc. <li><a accesskey="9" href="Standard-vs-Extensions.html#Standard-vs-Extensions">Standard vs Extensions</a>: Should I use extensions? <li><a href="Model.html#Model">Model</a>: The abstract machine of Gforth <li><a href="Integrating-Gforth.html#Integrating-Gforth">Integrating Gforth</a>: Forth as scripting language for applications <li><a href="Emacs-and-Gforth.html#Emacs-and-Gforth">Emacs and Gforth</a>: The Gforth Mode <li><a href="Image-Files.html#Image-Files">Image Files</a>: <code>.fi</code> files contain compiled code <li><a href="Engine.html#Engine">Engine</a>: The inner interpreter and the primitives <li><a href="Cross-Compiler.html#Cross-Compiler">Cross Compiler</a>: The Cross Compiler <li><a href="Bugs.html#Bugs">Bugs</a>: How to report them <li><a href="Origin.html#Origin">Origin</a>: Authors and ancestors of Gforth <li><a href="Forth_002drelated-information.html#Forth_002drelated-information">Forth-related information</a>: Books and places to look on the WWW <li><a href="Licenses.html#Licenses">Licenses</a> <li><a href="Word-Index.html#Word-Index">Word Index</a>: An item for each Forth word <li><a href="Concept-Index.html#Concept-Index">Concept Index</a>: A menu covering many topics </li></ul> <p>--- The Detailed Node Listing --- <p>Gforth Environment </p> <ul class="menu"> <li><a href="Invoking-Gforth.html#Invoking-Gforth">Invoking Gforth</a>: Getting in <li><a href="Leaving-Gforth.html#Leaving-Gforth">Leaving Gforth</a>: Getting out <li><a href="Command_002dline-editing.html#Command_002dline-editing">Command-line editing</a> <li><a href="Environment-variables.html#Environment-variables">Environment variables</a>: that affect how Gforth starts up <li><a href="Gforth-Files.html#Gforth-Files">Gforth Files</a>: What gets installed and where <li><a href="Gforth-in-pipes.html#Gforth-in-pipes">Gforth in pipes</a> <li><a href="Startup-speed.html#Startup-speed">Startup speed</a>: When 35ms is not fast enough ... </li></ul> <p>Forth Tutorial </p> <ul class="menu"> <li><a href="Starting-Gforth-Tutorial.html#Starting-Gforth-Tutorial">Starting Gforth Tutorial</a> <li><a href="Syntax-Tutorial.html#Syntax-Tutorial">Syntax Tutorial</a> <li><a href="Crash-Course-Tutorial.html#Crash-Course-Tutorial">Crash Course Tutorial</a> <li><a href="Stack-Tutorial.html#Stack-Tutorial">Stack Tutorial</a> <li><a href="Arithmetics-Tutorial.html#Arithmetics-Tutorial">Arithmetics Tutorial</a> <li><a href="Stack-Manipulation-Tutorial.html#Stack-Manipulation-Tutorial">Stack Manipulation Tutorial</a> <li><a href="Using-files-for-Forth-code-Tutorial.html#Using-files-for-Forth-code-Tutorial">Using files for Forth code Tutorial</a> <li><a href="Comments-Tutorial.html#Comments-Tutorial">Comments Tutorial</a> <li><a href="Colon-Definitions-Tutorial.html#Colon-Definitions-Tutorial">Colon Definitions Tutorial</a> <li><a href="Decompilation-Tutorial.html#Decompilation-Tutorial">Decompilation Tutorial</a> <li><a href="Stack_002dEffect-Comments-Tutorial.html#Stack_002dEffect-Comments-Tutorial">Stack-Effect Comments Tutorial</a> <li><a href="Types-Tutorial.html#Types-Tutorial">Types Tutorial</a> <li><a href="Factoring-Tutorial.html#Factoring-Tutorial">Factoring Tutorial</a> <li><a href="Designing-the-stack-effect-Tutorial.html#Designing-the-stack-effect-Tutorial">Designing the stack effect Tutorial</a> <li><a href="Local-Variables-Tutorial.html#Local-Variables-Tutorial">Local Variables Tutorial</a> <li><a href="Conditional-execution-Tutorial.html#Conditional-execution-Tutorial">Conditional execution Tutorial</a> <li><a href="Flags-and-Comparisons-Tutorial.html#Flags-and-Comparisons-Tutorial">Flags and Comparisons Tutorial</a> <li><a href="General-Loops-Tutorial.html#General-Loops-Tutorial">General Loops Tutorial</a> <li><a href="Counted-loops-Tutorial.html#Counted-loops-Tutorial">Counted loops Tutorial</a> <li><a href="Recursion-Tutorial.html#Recursion-Tutorial">Recursion Tutorial</a> <li><a href="Leaving-definitions-or-loops-Tutorial.html#Leaving-definitions-or-loops-Tutorial">Leaving definitions or loops Tutorial</a> <li><a href="Return-Stack-Tutorial.html#Return-Stack-Tutorial">Return Stack Tutorial</a> <li><a href="Memory-Tutorial.html#Memory-Tutorial">Memory Tutorial</a> <li><a href="Characters-and-Strings-Tutorial.html#Characters-and-Strings-Tutorial">Characters and Strings Tutorial</a> <li><a href="Alignment-Tutorial.html#Alignment-Tutorial">Alignment Tutorial</a> <li><a href="Floating-Point-Tutorial.html#Floating-Point-Tutorial">Floating Point Tutorial</a> <li><a href="Files-Tutorial.html#Files-Tutorial">Files Tutorial</a> <li><a href="Interpretation-and-Compilation-Semantics-and-Immediacy-Tutorial.html#Interpretation-and-Compilation-Semantics-and-Immediacy-Tutorial">Interpretation and Compilation Semantics and Immediacy Tutorial</a> <li><a href="Execution-Tokens-Tutorial.html#Execution-Tokens-Tutorial">Execution Tokens Tutorial</a> <li><a href="Exceptions-Tutorial.html#Exceptions-Tutorial">Exceptions Tutorial</a> <li><a href="Defining-Words-Tutorial.html#Defining-Words-Tutorial">Defining Words Tutorial</a> <li><a href="Arrays-and-Records-Tutorial.html#Arrays-and-Records-Tutorial">Arrays and Records Tutorial</a> <li><a href="POSTPONE-Tutorial.html#POSTPONE-Tutorial">POSTPONE Tutorial</a> <li><a href="Literal-Tutorial.html#Literal-Tutorial">Literal Tutorial</a> <li><a href="Advanced-macros-Tutorial.html#Advanced-macros-Tutorial">Advanced macros Tutorial</a> <li><a href="Compilation-Tokens-Tutorial.html#Compilation-Tokens-Tutorial">Compilation Tokens Tutorial</a> <li><a href="Wordlists-and-Search-Order-Tutorial.html#Wordlists-and-Search-Order-Tutorial">Wordlists and Search Order Tutorial</a> </li></ul> <p>An Introduction to ANS Forth </p> <ul class="menu"> <li><a href="Introducing-the-Text-Interpreter.html#Introducing-the-Text-Interpreter">Introducing the Text Interpreter</a> <li><a href="Stacks-and-Postfix-notation.html#Stacks-and-Postfix-notation">Stacks and Postfix notation</a> <li><a href="Your-first-definition.html#Your-first-definition">Your first definition</a> <li><a href="How-does-that-work_003f.html#How-does-that-work_003f">How does that work?</a> <li><a href="Forth-is-written-in-Forth.html#Forth-is-written-in-Forth">Forth is written in Forth</a> <li><a href="Review-_002d-elements-of-a-Forth-system.html#Review-_002d-elements-of-a-Forth-system">Review - elements of a Forth system</a> <li><a href="Where-to-go-next.html#Where-to-go-next">Where to go next</a> <li><a href="Exercises.html#Exercises">Exercises</a> </li></ul> <p>Forth Words </p> <ul class="menu"> <li><a href="Notation.html#Notation">Notation</a> <li><a href="Case-insensitivity.html#Case-insensitivity">Case insensitivity</a> <li><a href="Comments.html#Comments">Comments</a> <li><a href="Boolean-Flags.html#Boolean-Flags">Boolean Flags</a> <li><a href="Arithmetic.html#Arithmetic">Arithmetic</a> <li><a href="Stack-Manipulation.html#Stack-Manipulation">Stack Manipulation</a> <li><a href="Memory.html#Memory">Memory</a> <li><a href="Control-Structures.html#Control-Structures">Control Structures</a> <li><a href="Defining-Words.html#Defining-Words">Defining Words</a> <li><a href="Interpretation-and-Compilation-Semantics.html#Interpretation-and-Compilation-Semantics">Interpretation and Compilation Semantics</a> <li><a href="Tokens-for-Words.html#Tokens-for-Words">Tokens for Words</a> <li><a href="Compiling-words.html#Compiling-words">Compiling words</a> <li><a href="The-Text-Interpreter.html#The-Text-Interpreter">The Text Interpreter</a> <li><a href="The-Input-Stream.html#The-Input-Stream">The Input Stream</a> <li><a href="Word-Lists.html#Word-Lists">Word Lists</a> <li><a href="Environmental-Queries.html#Environmental-Queries">Environmental Queries</a> <li><a href="Files.html#Files">Files</a> <li><a href="Blocks.html#Blocks">Blocks</a> <li><a href="Other-I_002fO.html#Other-I_002fO">Other I/O</a> <li><a href="OS-command-line-arguments.html#OS-command-line-arguments">OS command line arguments</a> <li><a href="Locals.html#Locals">Locals</a> <li><a href="Structures.html#Structures">Structures</a> <li><a href="Object_002doriented-Forth.html#Object_002doriented-Forth">Object-oriented Forth</a> <li><a href="Programming-Tools.html#Programming-Tools">Programming Tools</a> <li><a href="C-Interface.html#C-Interface">C Interface</a> <li><a href="Assembler-and-Code-Words.html#Assembler-and-Code-Words">Assembler and Code Words</a> <li><a href="Threading-Words.html#Threading-Words">Threading Words</a> <li><a href="Passing-Commands-to-the-OS.html#Passing-Commands-to-the-OS">Passing Commands to the OS</a> <li><a href="Keeping-track-of-Time.html#Keeping-track-of-Time">Keeping track of Time</a> <li><a href="Miscellaneous-Words.html#Miscellaneous-Words">Miscellaneous Words</a> </li></ul> <p>Arithmetic </p> <ul class="menu"> <li><a href="Single-precision.html#Single-precision">Single precision</a> <li><a href="Double-precision.html#Double-precision">Double precision</a>: Double-cell integer arithmetic <li><a href="Bitwise-operations.html#Bitwise-operations">Bitwise operations</a> <li><a href="Numeric-comparison.html#Numeric-comparison">Numeric comparison</a> <li><a href="Mixed-precision.html#Mixed-precision">Mixed precision</a>: Operations with single and double-cell integers <li><a href="Floating-Point.html#Floating-Point">Floating Point</a> </li></ul> <p>Stack Manipulation </p> <ul class="menu"> <li><a href="Data-stack.html#Data-stack">Data stack</a> <li><a href="Floating-point-stack.html#Floating-point-stack">Floating point stack</a> <li><a href="Return-stack.html#Return-stack">Return stack</a> <li><a href="Locals-stack.html#Locals-stack">Locals stack</a> <li><a href="Stack-pointer-manipulation.html#Stack-pointer-manipulation">Stack pointer manipulation</a> </li></ul> <p>Memory </p> <ul class="menu"> <li><a href="Memory-model.html#Memory-model">Memory model</a> <li><a href="Dictionary-allocation.html#Dictionary-allocation">Dictionary allocation</a> <li><a href="Heap-Allocation.html#Heap-Allocation">Heap Allocation</a> <li><a href="Memory-Access.html#Memory-Access">Memory Access</a> <li><a href="Address-arithmetic.html#Address-arithmetic">Address arithmetic</a> <li><a href="Memory-Blocks.html#Memory-Blocks">Memory Blocks</a> </li></ul> <p>Control Structures </p> <ul class="menu"> <li><a href="Selection.html#Selection">Selection</a>: IF ... ELSE ... ENDIF <li><a href="Simple-Loops.html#Simple-Loops">Simple Loops</a>: BEGIN ... <li><a href="Counted-Loops.html#Counted-Loops">Counted Loops</a>: DO <li><a href="Arbitrary-control-structures.html#Arbitrary-control-structures">Arbitrary control structures</a> <li><a href="Calls-and-returns.html#Calls-and-returns">Calls and returns</a> <li><a href="Exception-Handling.html#Exception-Handling">Exception Handling</a> </li></ul> <p>Defining Words </p> <ul class="menu"> <li><a href="CREATE.html#CREATE">CREATE</a> <li><a href="Variables.html#Variables">Variables</a>: Variables and user variables <li><a href="Constants.html#Constants">Constants</a> <li><a href="Values.html#Values">Values</a>: Initialised variables <li><a href="Colon-Definitions.html#Colon-Definitions">Colon Definitions</a> <li><a href="Anonymous-Definitions.html#Anonymous-Definitions">Anonymous Definitions</a>: Definitions without names <li><a href="Supplying-names.html#Supplying-names">Supplying names</a>: Passing definition names as strings <li><a href="User_002ddefined-Defining-Words.html#User_002ddefined-Defining-Words">User-defined Defining Words</a> <li><a href="Deferred-Words.html#Deferred-Words">Deferred Words</a>: Allow forward references <li><a href="Aliases.html#Aliases">Aliases</a> </li></ul> <p>User-defined Defining Words </p> <ul class="menu"> <li><a href="CREATE_002e_002eDOES_003e-applications.html#CREATE_002e_002eDOES_003e-applications">CREATE..DOES&gt; applications</a> <li><a href="CREATE_002e_002eDOES_003e-details.html#CREATE_002e_002eDOES_003e-details">CREATE..DOES&gt; details</a> <li><a href="Advanced-does_003e-usage-example.html#Advanced-does_003e-usage-example">Advanced does&gt; usage example</a> <li><a href="Const_002ddoes_003e.html#Const_002ddoes_003e">Const-does&gt;</a> </li></ul> <p>Interpretation and Compilation Semantics </p> <ul class="menu"> <li><a href="Combined-words.html#Combined-words">Combined words</a> </li></ul> <p>Tokens for Words </p> <ul class="menu"> <li><a href="Execution-token.html#Execution-token">Execution token</a>: represents execution/interpretation semantics <li><a href="Compilation-token.html#Compilation-token">Compilation token</a>: represents compilation semantics <li><a href="Name-token.html#Name-token">Name token</a>: represents named words </li></ul> <p>Compiling words </p> <ul class="menu"> <li><a href="Literals.html#Literals">Literals</a>: Compiling data values <li><a href="Macros.html#Macros">Macros</a>: Compiling words </li></ul> <p>The Text Interpreter </p> <ul class="menu"> <li><a href="Input-Sources.html#Input-Sources">Input Sources</a> <li><a href="Number-Conversion.html#Number-Conversion">Number Conversion</a> <li><a href="Interpret_002fCompile-states.html#Interpret_002fCompile-states">Interpret/Compile states</a> <li><a href="Interpreter-Directives.html#Interpreter-Directives">Interpreter Directives</a> </li></ul> <p>Word Lists </p> <ul class="menu"> <li><a href="Vocabularies.html#Vocabularies">Vocabularies</a> <li><a href="Why-use-word-lists_003f.html#Why-use-word-lists_003f">Why use word lists?</a> <li><a href="Word-list-example.html#Word-list-example">Word list example</a> </li></ul> <p>Files </p> <ul class="menu"> <li><a href="Forth-source-files.html#Forth-source-files">Forth source files</a> <li><a href="General-files.html#General-files">General files</a> <li><a href="Redirection.html#Redirection">Redirection</a> <li><a href="Search-Paths.html#Search-Paths">Search Paths</a> </li></ul> <p>Search Paths </p> <ul class="menu"> <li><a href="Source-Search-Paths.html#Source-Search-Paths">Source Search Paths</a> <li><a href="General-Search-Paths.html#General-Search-Paths">General Search Paths</a> </li></ul> <p>Other I/O </p> <ul class="menu"> <li><a href="Simple-numeric-output.html#Simple-numeric-output">Simple numeric output</a>: Predefined formats <li><a href="Formatted-numeric-output.html#Formatted-numeric-output">Formatted numeric output</a>: Formatted (pictured) output <li><a href="String-Formats.html#String-Formats">String Formats</a>: How Forth stores strings in memory <li><a href="Displaying-characters-and-strings.html#Displaying-characters-and-strings">Displaying characters and strings</a>: Other stuff <li><a href="Terminal-output.html#Terminal-output">Terminal output</a>: Cursor positioning etc. <li><a href="Single_002dkey-input.html#Single_002dkey-input">Single-key input</a> <li><a href="Line-input-and-conversion.html#Line-input-and-conversion">Line input and conversion</a> <li><a href="Pipes.html#Pipes">Pipes</a>: How to create your own pipes <li><a href="Xchars-and-Unicode.html#Xchars-and-Unicode">Xchars and Unicode</a>: Non-ASCII characters </li></ul> <p>Locals </p> <ul class="menu"> <li><a href="Gforth-locals.html#Gforth-locals">Gforth locals</a> <li><a href="ANS-Forth-locals.html#ANS-Forth-locals">ANS Forth locals</a> </li></ul> <p>Gforth locals </p> <ul class="menu"> <li><a href="Where-are-locals-visible-by-name_003f.html#Where-are-locals-visible-by-name_003f">Where are locals visible by name?</a> <li><a href="How-long-do-locals-live_003f.html#How-long-do-locals-live_003f">How long do locals live?</a> <li><a href="Locals-programming-style.html#Locals-programming-style">Locals programming style</a> <li><a href="Locals-implementation.html#Locals-implementation">Locals implementation</a> </li></ul> <p>Structures </p> <ul class="menu"> <li><a href="Why-explicit-structure-support_003f.html#Why-explicit-structure-support_003f">Why explicit structure support?</a> <li><a href="Structure-Usage.html#Structure-Usage">Structure Usage</a> <li><a href="Structure-Naming-Convention.html#Structure-Naming-Convention">Structure Naming Convention</a> <li><a href="Structure-Implementation.html#Structure-Implementation">Structure Implementation</a> <li><a href="Structure-Glossary.html#Structure-Glossary">Structure Glossary</a> <li><a href="Forth200x-Structures.html#Forth200x-Structures">Forth200x Structures</a> </li></ul> <p>Object-oriented Forth </p> <ul class="menu"> <li><a href="Why-object_002doriented-programming_003f.html#Why-object_002doriented-programming_003f">Why object-oriented programming?</a> <li><a href="Object_002dOriented-Terminology.html#Object_002dOriented-Terminology">Object-Oriented Terminology</a> <li><a href="Objects.html#Objects">Objects</a> <li><a href="OOF.html#OOF">OOF</a> <li><a href="Mini_002dOOF.html#Mini_002dOOF">Mini-OOF</a> <li><a href="Comparison-with-other-object-models.html#Comparison-with-other-object-models">Comparison with other object models</a> </li></ul> <p>The <samp><span class="file">objects.fs</span></samp> model </p> <ul class="menu"> <li><a href="Properties-of-the-Objects-model.html#Properties-of-the-Objects-model">Properties of the Objects model</a> <li><a href="Basic-Objects-Usage.html#Basic-Objects-Usage">Basic Objects Usage</a> <li><a href="The-Objects-base-class.html#The-Objects-base-class">The Objects base class</a> <li><a href="Creating-objects.html#Creating-objects">Creating objects</a> <li><a href="Object_002dOriented-Programming-Style.html#Object_002dOriented-Programming-Style">Object-Oriented Programming Style</a> <li><a href="Class-Binding.html#Class-Binding">Class Binding</a> <li><a href="Method-conveniences.html#Method-conveniences">Method conveniences</a> <li><a href="Classes-and-Scoping.html#Classes-and-Scoping">Classes and Scoping</a> <li><a href="Dividing-classes.html#Dividing-classes">Dividing classes</a> <li><a href="Object-Interfaces.html#Object-Interfaces">Object Interfaces</a> <li><a href="Objects-Implementation.html#Objects-Implementation">Objects Implementation</a> <li><a href="Objects-Glossary.html#Objects-Glossary">Objects Glossary</a> </li></ul> <p>The <samp><span class="file">oof.fs</span></samp> model </p> <ul class="menu"> <li><a href="Properties-of-the-OOF-model.html#Properties-of-the-OOF-model">Properties of the OOF model</a> <li><a href="Basic-OOF-Usage.html#Basic-OOF-Usage">Basic OOF Usage</a> <li><a href="The-OOF-base-class.html#The-OOF-base-class">The OOF base class</a> <li><a href="Class-Declaration.html#Class-Declaration">Class Declaration</a> <li><a href="Class-Implementation.html#Class-Implementation">Class Implementation</a> </li></ul> <p>The <samp><span class="file">mini-oof.fs</span></samp> model </p> <ul class="menu"> <li><a href="Basic-Mini_002dOOF-Usage.html#Basic-Mini_002dOOF-Usage">Basic Mini-OOF Usage</a> <li><a href="Mini_002dOOF-Example.html#Mini_002dOOF-Example">Mini-OOF Example</a> <li><a href="Mini_002dOOF-Implementation.html#Mini_002dOOF-Implementation">Mini-OOF Implementation</a> </li></ul> <p>Programming Tools </p> <ul class="menu"> <li><a href="Examining.html#Examining">Examining</a>: Data and Code. <li><a href="Forgetting-words.html#Forgetting-words">Forgetting words</a>: Usually before reloading. <li><a href="Debugging.html#Debugging">Debugging</a>: Simple and quick. <li><a href="Assertions.html#Assertions">Assertions</a>: Making your programs self-checking. <li><a href="Singlestep-Debugger.html#Singlestep-Debugger">Singlestep Debugger</a>: Executing your program word by word. </li></ul> <p>C Interface </p> <ul class="menu"> <li><a href="Calling-C-Functions.html#Calling-C-Functions">Calling C Functions</a> <li><a href="Declaring-C-Functions.html#Declaring-C-Functions">Declaring C Functions</a> <li><a href="Calling-C-function-pointers.html#Calling-C-function-pointers">Calling C function pointers</a> <li><a href="Defining-library-interfaces.html#Defining-library-interfaces">Defining library interfaces</a> <li><a href="Declaring-OS_002dlevel-libraries.html#Declaring-OS_002dlevel-libraries">Declaring OS-level libraries</a> <li><a href="Callbacks.html#Callbacks">Callbacks</a> <li><a href="C-interface-internals.html#C-interface-internals">C interface internals</a> <li><a href="Low_002dLevel-C-Interface-Words.html#Low_002dLevel-C-Interface-Words">Low-Level C Interface Words</a> </li></ul> <p>Assembler and Code Words </p> <ul class="menu"> <li><a href="Code-and-_003bcode.html#Code-and-_003bcode">Code and ;code</a> <li><a href="Common-Assembler.html#Common-Assembler">Common Assembler</a>: Assembler Syntax <li><a href="Common-Disassembler.html#Common-Disassembler">Common Disassembler</a> <li><a href="386-Assembler.html#g_t386-Assembler">386 Assembler</a>: Deviations and special cases <li><a href="Alpha-Assembler.html#Alpha-Assembler">Alpha Assembler</a>: Deviations and special cases <li><a href="MIPS-assembler.html#MIPS-assembler">MIPS assembler</a>: Deviations and special cases <li><a href="PowerPC-assembler.html#PowerPC-assembler">PowerPC assembler</a>: Deviations and special cases <li><a href="ARM-Assembler.html#ARM-Assembler">ARM Assembler</a>: Deviations and special cases <li><a href="Other-assemblers.html#Other-assemblers">Other assemblers</a>: How to write them </li></ul> <p>Tools </p> <ul class="menu"> <li><a href="ANS-Report.html#ANS-Report">ANS Report</a>: Report the words used, sorted by wordset. <li><a href="Stack-depth-changes.html#Stack-depth-changes">Stack depth changes</a>: Where does this stack item come from? </li></ul> <p>ANS conformance </p> <ul class="menu"> <li><a href="The-Core-Words.html#The-Core-Words">The Core Words</a> <li><a href="The-optional-Block-word-set.html#The-optional-Block-word-set">The optional Block word set</a> <li><a href="The-optional-Double-Number-word-set.html#The-optional-Double-Number-word-set">The optional Double Number word set</a> <li><a href="The-optional-Exception-word-set.html#The-optional-Exception-word-set">The optional Exception word set</a> <li><a href="The-optional-Facility-word-set.html#The-optional-Facility-word-set">The optional Facility word set</a> <li><a href="The-optional-File_002dAccess-word-set.html#The-optional-File_002dAccess-word-set">The optional File-Access word set</a> <li><a href="The-optional-Floating_002dPoint-word-set.html#The-optional-Floating_002dPoint-word-set">The optional Floating-Point word set</a> <li><a href="The-optional-Locals-word-set.html#The-optional-Locals-word-set">The optional Locals word set</a> <li><a href="The-optional-Memory_002dAllocation-word-set.html#The-optional-Memory_002dAllocation-word-set">The optional Memory-Allocation word set</a> <li><a href="The-optional-Programming_002dTools-word-set.html#The-optional-Programming_002dTools-word-set">The optional Programming-Tools word set</a> <li><a href="The-optional-Search_002dOrder-word-set.html#The-optional-Search_002dOrder-word-set">The optional Search-Order word set</a> </li></ul> <p>The Core Words </p> <ul class="menu"> <li><a href="core_002didef.html#core_002didef">core-idef</a>: Implementation Defined Options <li><a href="core_002dambcond.html#core_002dambcond">core-ambcond</a>: Ambiguous Conditions <li><a href="core_002dother.html#core_002dother">core-other</a>: Other System Documentation </li></ul> <p>The optional Block word set </p> <ul class="menu"> <li><a href="block_002didef.html#block_002didef">block-idef</a>: Implementation Defined Options <li><a href="block_002dambcond.html#block_002dambcond">block-ambcond</a>: Ambiguous Conditions <li><a href="block_002dother.html#block_002dother">block-other</a>: Other System Documentation </li></ul> <p>The optional Double Number word set </p> <ul class="menu"> <li><a href="double_002dambcond.html#double_002dambcond">double-ambcond</a>: Ambiguous Conditions </li></ul> <p>The optional Exception word set </p> <ul class="menu"> <li><a href="exception_002didef.html#exception_002didef">exception-idef</a>: Implementation Defined Options </li></ul> <p>The optional Facility word set </p> <ul class="menu"> <li><a href="facility_002didef.html#facility_002didef">facility-idef</a>: Implementation Defined Options <li><a href="facility_002dambcond.html#facility_002dambcond">facility-ambcond</a>: Ambiguous Conditions </li></ul> <p>The optional File-Access word set </p> <ul class="menu"> <li><a href="file_002didef.html#file_002didef">file-idef</a>: Implementation Defined Options <li><a href="file_002dambcond.html#file_002dambcond">file-ambcond</a>: Ambiguous Conditions </li></ul> <p>The optional Floating-Point word set </p> <ul class="menu"> <li><a href="floating_002didef.html#floating_002didef">floating-idef</a>: Implementation Defined Options <li><a href="floating_002dambcond.html#floating_002dambcond">floating-ambcond</a>: Ambiguous Conditions </li></ul> <p>The optional Locals word set </p> <ul class="menu"> <li><a href="locals_002didef.html#locals_002didef">locals-idef</a>: Implementation Defined Options <li><a href="locals_002dambcond.html#locals_002dambcond">locals-ambcond</a>: Ambiguous Conditions </li></ul> <p>The optional Memory-Allocation word set </p> <ul class="menu"> <li><a href="memory_002didef.html#memory_002didef">memory-idef</a>: Implementation Defined Options </li></ul> <p>The optional Programming-Tools word set </p> <ul class="menu"> <li><a href="programming_002didef.html#programming_002didef">programming-idef</a>: Implementation Defined Options <li><a href="programming_002dambcond.html#programming_002dambcond">programming-ambcond</a>: Ambiguous Conditions </li></ul> <p>The optional Search-Order word set </p> <ul class="menu"> <li><a href="search_002didef.html#search_002didef">search-idef</a>: Implementation Defined Options <li><a href="search_002dambcond.html#search_002dambcond">search-ambcond</a>: Ambiguous Conditions </li></ul> <p>Emacs and Gforth </p> <ul class="menu"> <li><a href="Installing-gforth_002eel.html#Installing-gforth_002eel">Installing gforth.el</a>: Making Emacs aware of Forth. <li><a href="Emacs-Tags.html#Emacs-Tags">Emacs Tags</a>: Viewing the source of a word in Emacs. <li><a href="Hilighting.html#Hilighting">Hilighting</a>: Making Forth code look prettier. <li><a href="Auto_002dIndentation.html#Auto_002dIndentation">Auto-Indentation</a>: Customizing auto-indentation. <li><a href="Blocks-Files.html#Blocks-Files">Blocks Files</a>: Reading and writing blocks files. </li></ul> <p>Image Files </p> <ul class="menu"> <li><a href="Image-Licensing-Issues.html#Image-Licensing-Issues">Image Licensing Issues</a>: Distribution terms for images. <li><a href="Image-File-Background.html#Image-File-Background">Image File Background</a>: Why have image files? <li><a href="Non_002dRelocatable-Image-Files.html#Non_002dRelocatable-Image-Files">Non-Relocatable Image Files</a>: don't always work. <li><a href="Data_002dRelocatable-Image-Files.html#Data_002dRelocatable-Image-Files">Data-Relocatable Image Files</a>: are better. <li><a href="Fully-Relocatable-Image-Files.html#Fully-Relocatable-Image-Files">Fully Relocatable Image Files</a>: better yet. <li><a href="Stack-and-Dictionary-Sizes.html#Stack-and-Dictionary-Sizes">Stack and Dictionary Sizes</a>: Setting the default sizes for an image. <li><a href="Running-Image-Files.html#Running-Image-Files">Running Image Files</a>: <code>gforth -i </code><i>file</i> or <i>file</i>. <li><a href="Modifying-the-Startup-Sequence.html#Modifying-the-Startup-Sequence">Modifying the Startup Sequence</a>: and turnkey applications. </li></ul> <p>Fully Relocatable Image Files </p> <ul class="menu"> <li><a href="gforthmi.html#gforthmi">gforthmi</a>: The normal way <li><a href="cross_002efs.html#cross_002efs">cross.fs</a>: The hard way </li></ul> <p>Engine </p> <ul class="menu"> <li><a href="Portability.html#Portability">Portability</a> <li><a href="Threading.html#Threading">Threading</a> <li><a href="Primitives.html#Primitives">Primitives</a> <li><a href="Performance.html#Performance">Performance</a> </li></ul> <p>Threading </p> <ul class="menu"> <li><a href="Scheduling.html#Scheduling">Scheduling</a> <li><a href="Direct-or-Indirect-Threaded_003f.html#Direct-or-Indirect-Threaded_003f">Direct or Indirect Threaded?</a> <li><a href="Dynamic-Superinstructions.html#Dynamic-Superinstructions">Dynamic Superinstructions</a> <li><a href="DOES_003e.html#DOES_003e">DOES&gt;</a> </li></ul> <p>Primitives </p> <ul class="menu"> <li><a href="Automatic-Generation.html#Automatic-Generation">Automatic Generation</a> <li><a href="TOS-Optimization.html#TOS-Optimization">TOS Optimization</a> <li><a href="Produced-code.html#Produced-code">Produced code</a> </li></ul> <p>Cross Compiler </p> <ul class="menu"> <li><a href="Using-the-Cross-Compiler.html#Using-the-Cross-Compiler">Using the Cross Compiler</a> <li><a href="How-the-Cross-Compiler-Works.html#How-the-Cross-Compiler-Works">How the Cross Compiler Works</a> </li></ul> <p>Licenses </p> <ul class="menu"> <li><a href="GNU-Free-Documentation-License.html#GNU-Free-Documentation-License">GNU Free Documentation License</a>: License for copying this manual. <li><a href="Copying.html#Copying">Copying</a>: GPL (for copying this software). </ul> <!-- --> <!-- TODO much more blurb here. --> <!-- ****************************************************************** --> </body></html>
mpgirro/gforth-dash-docset
gforth.docset/Contents/Resources/Documents/index.html
HTML
gpl-2.0
63,897
<?php class E_Register_NowLog__Admin { public function __construct() { add_action( 'wp_ajax_tribe_logging_controls', array( $this, 'listen' ) ); add_action( 'init', array( $this, 'serve_log_downloads' ) ); add_action( 'init', array( $this, 'register_script' ) ); } /** * Returns the HTML comprising the event log section for use in the * Events > Settings > Help screen. * * @return string */ public function display_log() { $log_choices = $this->get_available_logs(); $log_engines = $this->get_log_engines(); $log_levels = $this->get_logging_levels(); $log_entries = $this->get_log_entries(); $download_url = $this->get_log_url(); $this->setup_script(); ob_start(); include trailingslashit( E_Register_NowMain::instance()->plugin_path ) . 'src/admin-views/event-log.php'; return ob_get_clean(); } /** * Listens for changes to the event log settings updating and returning * an appropriate response. */ public function listen() { $fields = wp_parse_args( $_POST, array( 'check' => '', 'log-level' => '', 'log-engine' => '', ) ); foreach ( $fields as &$single_field ) { $single_field = sanitize_text_field( $single_field ); } if ( ! wp_verify_nonce( $fields['check'], 'logging-controls' ) ) { return; } /** * Fires before log settings are committed. * * This will not happen unless a nonce check has already passed. */ do_action( 'tribe_common_update_log_settings' ); $this->update_logging_level( $fields['log-level'] ); $this->update_logging_engine( $fields['log-engine'] ); /** * Fires immediately after log settings have been committed. */ do_action( 'tribe_common_updated_log_settings' ); $data = array( 'logs' => $this->get_available_logs(), ); if ( ! empty( $fields['log-view'] ) ) { $data['entries'] = $this->get_log_entries( $fields['log-view'] ); } wp_send_json_success( $data ); } /** * Sets the current logging level to the provided level (if it is a valid * level, else will set the level to 'default'). * * @param string $level */ protected function update_logging_level( $level ) { $this->log_manager()->set_level( $level ); } /** * Sets the current logging engine to the provided class (if it is a valid * and currently available logging class, else will set this to null - ie * no logging). * * @param string $engine */ protected function update_logging_engine( $engine ) { try { $this->log_manager()->set_current_logger( $engine ); } catch ( Exception $e ) { // The class name did not relate to a valid logging engine } } /** * Register our script early. */ public function register_script() { wp_register_script( 'tribe-common-logging-controls', tribe_resource_url( 'admin-log-controls.js', false, 'common' ), array( 'jquery' ), E_Register_NowMain::VERSION, true ); } /** * Adds a script to handle the event log settings. */ protected function setup_script() { wp_enqueue_script( 'tribe-common-logging-controls' ); wp_localize_script( 'tribe-common-logging-controls', 'tribe_logger_data', array( 'check' => wp_create_nonce( 'logging-controls' ) ) ); } /** * Returns a list of logs that are available for perusal. * * @return array */ protected function get_available_logs() { $available_logs = $this->current_logger()->list_available_logs(); if ( empty( $available_logs ) ) { return array( '' => _x( 'None currently available', 'log selector', 'tribe-common' ) ); } return $available_logs; } /** * Returns a list of logging engines that are available for use. * * @return array */ protected function get_log_engines(){ $available_engines = $this->log_manager()->get_logging_engines(); if ( empty( $available_engines ) ) { return array( '' => _x( 'None currently available', 'log engines', 'tribe-common' ) ); } $engine_list = array(); foreach ( $available_engines as $class_name => $engine ) { /** * @var E_Register_NowLog__Logger $engine */ $engine_list[ $class_name ] = $engine->get_name(); } return $engine_list; } /** * Returns all log entries for the current or specified log. * * @return array */ protected function get_log_entries( $log = null ) { $logger = $this->current_logger(); $logger->use_log( $log ); return $logger->retrieve(); } /** * Returns an array of logging levels arranged as key:value pairs, with * each key being the level code and the value being the human-friendly * description. * * @return array */ protected function get_logging_levels() { $levels = array(); $available_levels = $this->log_manager()->get_logging_levels(); foreach ( $available_levels as $logging_level ) { $levels[ $logging_level[0] ] = $logging_level[1]; } return $levels; } /** * Provides a URL that can be used to download the current or specified * log. * * @param $log * * @return string */ protected function get_log_url( $log = null ) { $query = array( 'tribe-common-log' => 'download', 'check' => wp_create_nonce( 'download_log' ) ); $log_download_url = add_query_arg( $query, get_admin_url( null, 'edit.php' ) ); return esc_url( $log_download_url ); } /** * Facilitate downloading of logs. */ public function serve_log_downloads() { if ( empty( $_GET['tribe-common-log'] ) || 'download' !== $_GET['tribe-common-log'] ) { return; } if ( ! wp_verify_nonce( @$_GET['check'], 'download_log' ) ) { return; } if ( empty( $_GET['log'] ) || ! in_array( $_GET['log'], $this->get_available_logs() ) ) { return; } $log_name = sanitize_file_name( $_GET['log'] ); $this->current_logger()->use_log( $log_name ); /** * Provides an opportunity to modify the recommended filename for a downloaded * log file. * * @param string $log_name */ $log_name = apply_filters( 'tribe_common_log_download_filename', $log_name ); header( 'Content-Disposition: attachment; filename="tribe-log-' . $log_name . '"' ); $output = fopen( 'php://output', 'w' ); foreach ( $this->current_logger()->retrieve() as $log_entry ) { fputcsv( $output, $log_entry ); } fclose( $output ); exit(); } /** * Returns a reference to the main log management object. * * @return E_Register_NowLog */ protected function log_manager() { return E_Register_NowMain::instance()->log(); } /** * Returns the currently enabled logging object or null if it is not * available. * * @return E_Register_NowLog__Logger|null */ protected function current_logger() { return E_Register_NowMain::instance()->log()->get_current_logger(); } }
romangrb/register-now-plugin
backup/event-tickets 1.2.3/common/src/e_register_now/Log/Admin.php
PHP
gpl-2.0
6,686
#ifndef UTIL_FACTORY_HPP #define UTIL_FACTORY_HPP #include "base.hpp" #include <map> #include "typeinfo.hpp" namespace util { //////////////////////////////////////////////////////////////////////////////// // class template DefaultFactoryError // Manages the "Unknown Type" error in an object factory //////////////////////////////////////////////////////////////////////////////// template <typename IdentifierType, class AbstractProduct> struct DefaultFactoryError { static AbstractProduct* onUnknownType(IdentifierType) { throw Exception("Unknown Type"); } }; //////////////////////////////////////////////////////////////////////////////// // class template DefaultFactoryError // Manages the "Unknown Type" error in an object factory //////////////////////////////////////////////////////////////////////////////// template <typename IdentifierType, class AbstractProduct> struct FactoryCreateFail { static AbstractProduct* onUnknownType(IdentifierType) { return 0; } }; //////////////////////////////////////////////////////////////////////////////// // class template Factory // Implements a generic object factory //////////////////////////////////////////////////////////////////////////////// //AbstractProduct* (*)() template < class AbstractProduct, typename IdentifierType, typename ProductCreator = UtilFunction<AbstractProduct* ()>, template<typename, class> class FactoryErrorPolicy = FactoryCreateFail > class Factory : public FactoryErrorPolicy<IdentifierType, AbstractProduct> { public: bool Register(const IdentifierType& id, ProductCreator creator) { return associations_.insert( typename IdToProductMap::value_type(id, creator)).second; } bool unRegister(const IdentifierType& id) { return associations_.erase(id) == 1; } AbstractProduct* createObject(const IdentifierType& id) { ProductCreator product_creator = creator(id); return product_creator ? product_creator() : FactoryErrorPolicy<IdentifierType, AbstractProduct>::onUnknownType(id); } private: ProductCreator creator(const IdentifierType& id) { typename IdToProductMap::const_iterator i = associations_.find(id); if (i != associations_.end()) return i->second; return ProductCreator(); } private: typedef std::map<IdentifierType, ProductCreator> IdToProductMap; IdToProductMap associations_; }; //////////////////////////////////////////////////////////////////////////////// // class template CloneFactory // Implements a generic cloning factory //////////////////////////////////////////////////////////////////////////////// template < class AbstractProduct, class ProductCreator = UtilFunction<AbstractProduct* (AbstractProduct*)>, template<typename, class> class FactoryErrorPolicy = FactoryCreateFail > class CloneFactory : public FactoryErrorPolicy<TypeInfo, AbstractProduct> { public: bool Register(const TypeInfo& ti, ProductCreator creator) { return associations_.insert( typename IdToProductMap::value_type(ti, creator)).second; } bool unRegister(const TypeInfo& id) { return associations_.erase(id) == 1; } AbstractProduct* createObject(AbstractProduct* model) { if (model == 0) return 0; typename IdToProductMap::iterator i = associations_.find(TypeInfo(typeid(*model))); if (i != associations_.end()) return (i->second)(model); return FactoryErrorPolicy<TypeInfo, AbstractProduct>::onUnknownType(typeid(*model)); } private: typedef std::map<TypeInfo, ProductCreator> IdToProductMap; IdToProductMap associations_; }; } // namespace util #endif // UTIL_FACTORY_HPP
joshua-meng/Util
src/util/factory.hpp
C++
gpl-2.0
3,863
/* note: this requires gstreamer 0.10.x and a big list of plugins. */ /* it's currently hardcoded to use a big-endian alsasink as sink. */ #include <lib/base/ebase.h> #include <lib/base/eerror.h> #include <lib/base/init_num.h> #include <lib/base/init.h> #include <lib/base/nconfig.h> #include <lib/base/object.h> #include <lib/dvb/epgcache.h> #include <lib/dvb/decoder.h> #include <lib/components/file_eraser.h> #include <lib/gui/esubtitle.h> #include <lib/service/servicemp3.h> #include <lib/service/service.h> #include <lib/gdi/gpixmap.h> #include <string> #include <gst/gst.h> #include <gst/pbutils/missing-plugins.h> #include <sys/stat.h> #define HTTP_TIMEOUT 30 /* * UNUSED variable from service reference is now used as buffer flag for gstreamer * REFTYPE:FLAGS:STYPE:SID:TSID:ONID:NS:PARENT_SID:PARENT_TSID:UNUSED * D D X X X X X X X X * 4097:0:1:0:0:0:0:0:0:0:URL:NAME (no buffering) * 4097:0:1:0:0:0:0:0:0:1:URL:NAME (buffering enabled) * 4097:0:1:0:0:0:0:0:0:3:URL:NAME (progressive download and buffering enabled) * * Progressive download requires buffering enabled, so it's mandatory to use flag 3 not 2 */ typedef enum { BUFFERING_ENABLED = 0x00000001, PROGRESSIVE_DOWNLOAD = 0x00000002 } eServiceMP3Flags; typedef enum { GST_PLAY_FLAG_VIDEO = 0x00000001, GST_PLAY_FLAG_AUDIO = 0x00000002, GST_PLAY_FLAG_TEXT = 0x00000004, GST_PLAY_FLAG_VIS = 0x00000008, GST_PLAY_FLAG_SOFT_VOLUME = 0x00000010, GST_PLAY_FLAG_NATIVE_AUDIO = 0x00000020, GST_PLAY_FLAG_NATIVE_VIDEO = 0x00000040, GST_PLAY_FLAG_DOWNLOAD = 0x00000080, GST_PLAY_FLAG_BUFFERING = 0x00000100 } GstPlayFlags; // eServiceFactoryMP3 /* * gstreamer suffers from a bug causing sparse streams to loose sync, after pause/resume / skip * see: https://bugzilla.gnome.org/show_bug.cgi?id=619434 * As a workaround, we run the subsink in sync=false mode */ #if GST_VERSION_MAJOR >= 1 #undef GSTREAMER_SUBTITLE_SYNC_MODE_BUG #else #define GSTREAMER_SUBTITLE_SYNC_MODE_BUG #endif /**/ eServiceFactoryMP3::eServiceFactoryMP3() { ePtr<eServiceCenter> sc; eServiceCenter::getPrivInstance(sc); if (sc) { std::list<std::string> extensions; extensions.push_back("dts"); extensions.push_back("mp2"); extensions.push_back("mp3"); extensions.push_back("ogg"); extensions.push_back("ogm"); extensions.push_back("ogv"); extensions.push_back("mpg"); extensions.push_back("vob"); extensions.push_back("wav"); extensions.push_back("wave"); extensions.push_back("m4v"); extensions.push_back("mkv"); extensions.push_back("avi"); extensions.push_back("divx"); extensions.push_back("dat"); extensions.push_back("flac"); extensions.push_back("flv"); extensions.push_back("mp4"); extensions.push_back("mov"); extensions.push_back("m4a"); extensions.push_back("3gp"); extensions.push_back("3g2"); extensions.push_back("asf"); extensions.push_back("wmv"); extensions.push_back("wma"); sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions); } m_service_info = new eStaticServiceMP3Info(); } eServiceFactoryMP3::~eServiceFactoryMP3() { ePtr<eServiceCenter> sc; eServiceCenter::getPrivInstance(sc); if (sc) sc->removeServiceFactory(eServiceFactoryMP3::id); } DEFINE_REF(eServiceFactoryMP3) // iServiceHandler RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr) { // check resources... ptr = new eServiceMP3(ref); return 0; } RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr) { ptr=0; return -1; } RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr) { ptr=0; return -1; } RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr) { ptr = m_service_info; return 0; } class eMP3ServiceOfflineOperations: public iServiceOfflineOperations { DECLARE_REF(eMP3ServiceOfflineOperations); eServiceReference m_ref; public: eMP3ServiceOfflineOperations(const eServiceReference &ref); RESULT deleteFromDisk(int simulate); RESULT getListOfFilenames(std::list<std::string> &); RESULT reindex(); }; DEFINE_REF(eMP3ServiceOfflineOperations); eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref) { } RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate) { if (!simulate) { std::list<std::string> res; if (getListOfFilenames(res)) return -1; eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance(); if (!eraser) eDebug("FATAL !! can't get background file eraser"); for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i) { // eDebug("Removing %s...", i->c_str()); if (eraser) eraser->erase(i->c_str()); else ::unlink(i->c_str()); } } return 0; } RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res) { res.clear(); res.push_back(m_ref.path); return 0; } RESULT eMP3ServiceOfflineOperations::reindex() { return -1; } RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr) { ptr = new eMP3ServiceOfflineOperations(ref); return 0; } // eStaticServiceMP3Info // eStaticServiceMP3Info is seperated from eServiceMP3 to give information // about unopened files. // probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info // should have a database backend where ID3-files etc. are cached. // this would allow listing the mp3 database based on certain filters. DEFINE_REF(eStaticServiceMP3Info) eStaticServiceMP3Info::eStaticServiceMP3Info() { } RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name) { if ( ref.name.length() ) name = ref.name; else { size_t last = ref.path.rfind('/'); if (last != std::string::npos) name = ref.path.substr(last+1); else name = ref.path; } return 0; } int eStaticServiceMP3Info::getLength(const eServiceReference &ref) { return -1; } int eStaticServiceMP3Info::getInfo(const eServiceReference &ref, int w) { switch (w) { case iServiceInformation::sTimeCreate: { struct stat s; if (stat(ref.path.c_str(), &s) == 0) { return s.st_mtime; } } break; case iServiceInformation::sFileSize: { struct stat s; if (stat(ref.path.c_str(), &s) == 0) { return s.st_size; } } break; } return iServiceInformation::resNA; } long long eStaticServiceMP3Info::getFileSize(const eServiceReference &ref) { struct stat s; if (stat(ref.path.c_str(), &s) == 0) { return s.st_size; } return 0; } RESULT eStaticServiceMP3Info::getEvent(const eServiceReference &ref, ePtr<eServiceEvent> &evt, time_t start_time) { if (ref.path.find("://") != std::string::npos) { eServiceReference equivalentref(ref); equivalentref.type = eServiceFactoryMP3::id; equivalentref.path.clear(); return eEPGCache::getInstance()->lookupEventTime(equivalentref, start_time, evt); } evt = 0; return -1; } DEFINE_REF(eStreamBufferInfo) eStreamBufferInfo::eStreamBufferInfo(int percentage, int inputrate, int outputrate, int space, int size) : bufferPercentage(percentage), inputRate(inputrate), outputRate(outputrate), bufferSpace(space), bufferSize(size) { } int eStreamBufferInfo::getBufferPercentage() const { return bufferPercentage; } int eStreamBufferInfo::getAverageInputRate() const { return inputRate; } int eStreamBufferInfo::getAverageOutputRate() const { return outputRate; } int eStreamBufferInfo::getBufferSpace() const { return bufferSpace; } int eStreamBufferInfo::getBufferSize() const { return bufferSize; } DEFINE_REF(eServiceMP3InfoContainer); eServiceMP3InfoContainer::eServiceMP3InfoContainer() : doubleValue(0.0), bufferValue(NULL), bufferData(NULL), bufferSize(0) { } eServiceMP3InfoContainer::~eServiceMP3InfoContainer() { if (bufferValue) { #if GST_VERSION_MAJOR >= 1 gst_buffer_unmap(bufferValue, &map); #endif gst_buffer_unref(bufferValue); bufferValue = NULL; bufferData = NULL; bufferSize = 0; } } double eServiceMP3InfoContainer::getDouble(unsigned int index) const { return doubleValue; } unsigned char *eServiceMP3InfoContainer::getBuffer(unsigned int &size) const { size = bufferSize; return bufferData; } void eServiceMP3InfoContainer::setDouble(double value) { doubleValue = value; } void eServiceMP3InfoContainer::setBuffer(GstBuffer *buffer) { bufferValue = buffer; gst_buffer_ref(bufferValue); #if GST_VERSION_MAJOR < 1 bufferData = GST_BUFFER_DATA(bufferValue); bufferSize = GST_BUFFER_SIZE(bufferValue); #else gst_buffer_map(bufferValue, &map, GST_MAP_READ); bufferData = map.data; bufferSize = map.size; #endif } // eServiceMP3 int eServiceMP3::ac3_delay = 0, eServiceMP3::pcm_delay = 0; eServiceMP3::eServiceMP3(eServiceReference ref): m_nownext_timer(eTimer::create(eApp)), m_ref(ref), m_pump(eApp, 1) { m_subtitle_sync_timer = eTimer::create(eApp); m_streamingsrc_timeout = 0; m_stream_tags = 0; m_currentAudioStream = -1; m_currentSubtitleStream = -1; m_cachedSubtitleStream = 0; /* report the first subtitle stream to be 'cached'. TODO: use an actual cache. */ m_subtitle_widget = 0; m_currentTrickRatio = 1.0; m_buffer_size = 5 * 1024 * 1024; m_ignore_buffering_messages = 0; m_is_live = false; m_use_prefillbuffer = false; m_paused = false; m_seek_paused = false; m_extra_headers = ""; m_download_buffer_path = ""; m_prev_decoder_time = -1; m_decoder_time_valid_state = 0; m_errorInfo.missing_codec = ""; audioSink = videoSink = NULL; CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles); CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll); CONNECT(m_nownext_timer->timeout, eServiceMP3::updateEpgCacheNowNext); m_aspect = m_width = m_height = m_framerate = m_progressive = -1; m_state = stIdle; m_subtitles_paused = false; // eDebug("eServiceMP3::construct!"); const char *filename = m_ref.path.c_str(); const char *ext = strrchr(filename, '.'); if (!ext) ext = filename + strlen(filename); m_sourceinfo.is_video = FALSE; m_sourceinfo.audiotype = atUnknown; if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 ) { m_sourceinfo.containertype = ctMPEGPS; m_sourceinfo.is_video = TRUE; } else if ( strcasecmp(ext, ".ts") == 0 ) { m_sourceinfo.containertype = ctMPEGTS; m_sourceinfo.is_video = TRUE; } else if ( strcasecmp(ext, ".mkv") == 0 ) { m_sourceinfo.containertype = ctMKV; m_sourceinfo.is_video = TRUE; } else if ( strcasecmp(ext, ".ogm") == 0 || strcasecmp(ext, ".ogv") == 0) { m_sourceinfo.containertype = ctOGG; m_sourceinfo.is_video = TRUE; } else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0) { m_sourceinfo.containertype = ctAVI; m_sourceinfo.is_video = TRUE; } else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0 || strcasecmp(ext, ".m4v") == 0 || strcasecmp(ext, ".3gp") == 0 || strcasecmp(ext, ".3g2") == 0) { m_sourceinfo.containertype = ctMP4; m_sourceinfo.is_video = TRUE; } else if ( strcasecmp(ext, ".asf") == 0 || strcasecmp(ext, ".wmv") == 0) { m_sourceinfo.containertype = ctASF; m_sourceinfo.is_video = TRUE; } else if ( strcasecmp(ext, ".m4a") == 0 ) { m_sourceinfo.containertype = ctMP4; m_sourceinfo.audiotype = atAAC; } else if ( strcasecmp(ext, ".mp3") == 0 ) m_sourceinfo.audiotype = atMP3; else if ( strcasecmp(ext, ".wma") == 0 ) m_sourceinfo.audiotype = atWMA; else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 ) m_sourceinfo.containertype = ctCDA; if ( strcasecmp(ext, ".dat") == 0 ) { m_sourceinfo.containertype = ctVCD; m_sourceinfo.is_video = TRUE; } if ( strstr(filename, "://") ) m_sourceinfo.is_streaming = TRUE; gchar *uri; if ( m_sourceinfo.is_streaming ) { uri = g_strdup_printf ("%s", filename); m_streamingsrc_timeout = eTimer::create(eApp);; CONNECT(m_streamingsrc_timeout->timeout, eServiceMP3::sourceTimeout); std::string config_str; if (eConfigManager::getConfigBoolValue("config.mediaplayer.useAlternateUserAgent")) { m_useragent = eConfigManager::getConfigValue("config.mediaplayer.alternateUserAgent"); } if (m_useragent.empty()) m_useragent = "Enigma2 Mediaplayer"; m_extra_headers = eConfigManager::getConfigValue("config.mediaplayer.extraHeaders"); if ( m_ref.getData(7) & BUFFERING_ENABLED ) { m_use_prefillbuffer = true; if ( m_ref.getData(7) & PROGRESSIVE_DOWNLOAD ) { /* progressive download buffering */ if (::access("/hdd/movie", X_OK) >= 0) { /* It looks like /hdd points to a valid mount, so we can store a download buffer on it */ m_download_buffer_path = "/hdd/gstreamer_XXXXXXXXXX"; } } } } else if ( m_sourceinfo.containertype == ctCDA ) { int i_track = atoi(filename+18); uri = g_strdup_printf ("cdda://%i", i_track); } else if ( m_sourceinfo.containertype == ctVCD ) { int ret = -1; int fd = open(filename,O_RDONLY); if (fd >= 0) { char* tmp = new char[128*1024]; ret = read(fd, tmp, 128*1024); close(fd); delete [] tmp; } if ( ret == -1 ) // this is a "REAL" VCD uri = g_strdup_printf ("vcd://"); else uri = g_filename_to_uri(filename, NULL, NULL); } else uri = g_filename_to_uri(filename, NULL, NULL); // eDebug("eServiceMP3::playbin uri=%s", uri); #if GST_VERSION_MAJOR < 1 m_gst_playbin = gst_element_factory_make("playbin2", "playbin"); #else m_gst_playbin = gst_element_factory_make("playbin", "playbin"); #endif if ( m_gst_playbin ) { guint flags; g_object_get(G_OBJECT (m_gst_playbin), "flags", &flags, NULL); /* avoid video conversion, let the (hardware) sinks handle that */ flags |= GST_PLAY_FLAG_NATIVE_VIDEO; /* volume control is done by hardware */ flags &= ~GST_PLAY_FLAG_SOFT_VOLUME; if ( m_sourceinfo.is_streaming ) { g_signal_connect (G_OBJECT (m_gst_playbin), "notify::source", G_CALLBACK (playbinNotifySource), this); if (m_download_buffer_path != "") { /* use progressive download buffering */ flags |= GST_PLAY_FLAG_DOWNLOAD; g_signal_connect(G_OBJECT(m_gst_playbin), "element-added", G_CALLBACK(handleElementAdded), this); /* limit file size */ g_object_set(m_gst_playbin, "ring-buffer-max-size", (guint64)(8LL * 1024LL * 1024LL), NULL); } /* * regardless whether or not we configured a progressive download file, use a buffer as well * (progressive download might not work for all formats) */ flags |= GST_PLAY_FLAG_BUFFERING; /* increase the default 2 second / 2 MB buffer limitations to 5s / 5MB */ g_object_set(G_OBJECT(m_gst_playbin), "buffer-duration", 5LL * GST_SECOND, NULL); g_object_set(G_OBJECT(m_gst_playbin), "buffer-size", m_buffer_size, NULL); } g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL); g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL); GstElement *subsink = gst_element_factory_make("subsink", "subtitle_sink"); if (!subsink) eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-subsink"); else { m_subs_to_pull_handler_id = g_signal_connect (subsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this); g_object_set (G_OBJECT (subsink), "caps", gst_caps_from_string("text/plain; text/x-plain; text/x-raw; text/x-pango-markup; video/x-dvd-subpicture; subpicture/x-pgs"), NULL); g_object_set (G_OBJECT (m_gst_playbin), "text-sink", subsink, NULL); g_object_set (G_OBJECT (m_gst_playbin), "current-text", m_currentSubtitleStream, NULL); } GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE (m_gst_playbin)); #if GST_VERSION_MAJOR < 1 gst_bus_set_sync_handler(bus, gstBusSyncHandler, this); #else gst_bus_set_sync_handler(bus, gstBusSyncHandler, this, NULL); #endif gst_object_unref(bus); char srt_filename[ext - filename + 5]; strncpy(srt_filename,filename, ext - filename); srt_filename[ext - filename] = '\0'; strcat(srt_filename, ".srt"); if (::access(srt_filename, R_OK) >= 0) { eDebug("eServiceMP3::subtitle uri: %s", g_filename_to_uri(srt_filename, NULL, NULL)); g_object_set (G_OBJECT (m_gst_playbin), "suburi", g_filename_to_uri(srt_filename, NULL, NULL), NULL); } } else { m_event((iPlayableService*)this, evUser+12); m_gst_playbin = 0; m_errorInfo.error_message = "failed to create GStreamer pipeline!\n"; eDebug("eServiceMP3::sorry, can't play: %s",m_errorInfo.error_message.c_str()); } g_free(uri); } eServiceMP3::~eServiceMP3() { // disconnect subtitle callback GstElement *subsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink"); if (subsink) { g_signal_handler_disconnect (subsink, m_subs_to_pull_handler_id); gst_object_unref(subsink); } if (m_subtitle_widget) m_subtitle_widget->destroy(); m_subtitle_widget = 0; if (m_gst_playbin) { // disconnect sync handler callback GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE (m_gst_playbin)); #if GST_VERSION_MAJOR < 1 gst_bus_set_sync_handler(bus, NULL, NULL); #else gst_bus_set_sync_handler(bus, NULL, NULL, NULL); #endif gst_object_unref(bus); } if (m_state == stRunning) stop(); if (m_stream_tags) gst_tag_list_free(m_stream_tags); if (audioSink) { gst_object_unref(GST_OBJECT(audioSink)); audioSink = NULL; } if (videoSink) { gst_object_unref(GST_OBJECT(videoSink)); videoSink = NULL; } if (m_gst_playbin) { gst_object_unref (GST_OBJECT (m_gst_playbin)); // eDebug("eServiceMP3::destruct!"); } } void eServiceMP3::updateEpgCacheNowNext() { bool update = false; ePtr<eServiceEvent> next = 0; ePtr<eServiceEvent> ptr = 0; eServiceReference ref(m_ref); ref.type = eServiceFactoryMP3::id; ref.path.clear(); if (eEPGCache::getInstance() && eEPGCache::getInstance()->lookupEventTime(ref, -1, ptr) >= 0) { ePtr<eServiceEvent> current = m_event_now; if (!current || !ptr || current->getEventId() != ptr->getEventId()) { update = true; m_event_now = ptr; time_t next_time = ptr->getBeginTime() + ptr->getDuration(); if (eEPGCache::getInstance()->lookupEventTime(ref, next_time, ptr) >= 0) { next = ptr; m_event_next = ptr; } } } int refreshtime = 60; if (!next) { next = m_event_next; } if (next) { time_t now = eDVBLocalTimeHandler::getInstance()->nowTime(); refreshtime = (int)(next->getBeginTime() - now) + 3; if (refreshtime <= 0 || refreshtime > 60) { refreshtime = 60; } } m_nownext_timer->startLongTimer(refreshtime); if (update) { m_event((iPlayableService*)this, evUpdatedEventInfo); } } DEFINE_REF(eServiceMP3); DEFINE_REF(eServiceMP3::GstMessageContainer); RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection) { connection = new eConnection((iPlayableService*)this, m_event.connect(event)); return 0; } RESULT eServiceMP3::start() { ASSERT(m_state == stIdle); m_state = stRunning; m_subtitles_paused = false; if (m_gst_playbin) { // eDebug("eServiceMP3::starting pipeline"); gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING); updateEpgCacheNowNext(); } m_event(this, evStart); return 0; } void eServiceMP3::sourceTimeout() { eDebug("eServiceMP3::http source timeout! issuing eof..."); m_event((iPlayableService*)this, evEOF); } RESULT eServiceMP3::stop() { ASSERT(m_state != stIdle); if (m_state == stStopped) return -1; eDebug("eServiceMP3::stop %s", m_ref.path.c_str()); gst_element_set_state(m_gst_playbin, GST_STATE_NULL); m_state = stStopped; m_subtitles_paused = false; m_nownext_timer->stop(); if (m_streamingsrc_timeout) m_streamingsrc_timeout->stop(); return 0; } RESULT eServiceMP3::setTarget(int target) { return -1; } RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr) { ptr=this; return 0; } RESULT eServiceMP3::setSlowMotion(int ratio) { if (!ratio) return 0; eDebug("eServiceMP3::setSlowMotion ratio=%f",1.0/(gdouble)ratio); return trickSeek(1.0/(gdouble)ratio); } RESULT eServiceMP3::setFastForward(int ratio) { eDebug("eServiceMP3::setFastForward ratio=%i",ratio); return trickSeek(ratio); } // iPausableService RESULT eServiceMP3::pause() { if (!m_gst_playbin || m_state != stRunning) return -1; m_subtitles_paused = true; m_subtitle_sync_timer->start(1, true); trickSeek(0.0); return 0; } RESULT eServiceMP3::unpause() { if (!m_gst_playbin || m_state != stRunning) return -1; m_subtitles_paused = false; m_subtitle_sync_timer->start(1, true); trickSeek(1.0); return 0; } /* iSeekableService */ RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr) { ptr = this; return 0; } RESULT eServiceMP3::getLength(pts_t &pts) { if (!m_gst_playbin) return -1; if (m_state != stRunning) return -1; GstFormat fmt = GST_FORMAT_TIME; gint64 len; #if GST_VERSION_MAJOR < 1 if (!gst_element_query_duration(m_gst_playbin, &fmt, &len)) #else if (!gst_element_query_duration(m_gst_playbin, fmt, &len)) #endif return -1; /* len is in nanoseconds. we have 90 000 pts per second. */ pts = len / 11111LL; return 0; } RESULT eServiceMP3::seekToImpl(pts_t to) { /* convert pts to nanoseconds */ gint64 time_nanoseconds = to * 11111LL; if (!gst_element_seek (m_gst_playbin, m_currentTrickRatio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT), GST_SEEK_TYPE_SET, time_nanoseconds, GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE)) { eDebug("eServiceMP3::seekTo failed"); return -1; } if (m_paused) { m_seek_paused = true; gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING); } return 0; } RESULT eServiceMP3::seekTo(pts_t to) { RESULT ret = -1; if (m_gst_playbin) { m_prev_decoder_time = -1; m_decoder_time_valid_state = 0; ret = seekToImpl(to); } return ret; } RESULT eServiceMP3::trickSeek(gdouble ratio) { if (!m_gst_playbin) return -1; if (ratio > -0.01 && ratio < 0.01) { gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED); return 0; } m_currentTrickRatio = ratio; bool validposition = false; gint64 pos = 0; pts_t pts; if (getPlayPosition(pts) >= 0) { validposition = true; pos = pts * 11111LL; } gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING); if (validposition) { if (ratio >= 0.0) { gst_element_seek(m_gst_playbin, ratio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT | GST_SEEK_FLAG_SKIP), GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, -1); } else { /* note that most elements will not support negative speed */ gst_element_seek(m_gst_playbin, ratio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_SKIP), GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_SET, pos); } } m_prev_decoder_time = -1; m_decoder_time_valid_state = 0; return 0; } RESULT eServiceMP3::seekRelative(int direction, pts_t to) { if (!m_gst_playbin) return -1; pts_t ppos; if (getPlayPosition(ppos) < 0) return -1; ppos += to * direction; if (ppos < 0) ppos = 0; return seekTo(ppos); } #if GST_VERSION_MAJOR < 1 gint eServiceMP3::match_sinktype(GstElement *element, gpointer type) { return strcmp(g_type_name(G_OBJECT_TYPE(element)), (const char*)type); } #else gint eServiceMP3::match_sinktype(const GValue *velement, const gchar *type) { GstElement *element = GST_ELEMENT_CAST(g_value_get_object(velement)); return strcmp(g_type_name(G_OBJECT_TYPE(element)), type); } #endif RESULT eServiceMP3::getPlayPosition(pts_t &pts) { gint64 pos; pts = 0; if (!m_gst_playbin) return -1; if (m_state != stRunning) return -1; if (audioSink || videoSink) { g_signal_emit_by_name(audioSink ? audioSink : videoSink, "get-decoder-time", &pos); if (!GST_CLOCK_TIME_IS_VALID(pos)) return -1; } else { GstFormat fmt = GST_FORMAT_TIME; #if GST_VERSION_MAJOR < 1 if (!gst_element_query_position(m_gst_playbin, &fmt, &pos)) #else if (!gst_element_query_position(m_gst_playbin, fmt, &pos)) #endif { // eDebug("gst_element_query_position failed in getPlayPosition"); return -1; } } /* pos is in nanoseconds. we have 90 000 pts per second. */ pts = pos / 11111LL; return 0; } RESULT eServiceMP3::setTrickmode(int trick) { /* trickmode is not yet supported by our dvbmediasinks. */ return -1; } RESULT eServiceMP3::isCurrentlySeekable() { int ret = 3; /* just assume that seeking and fast/slow winding are possible */ if (!m_gst_playbin) return 0; if (m_state != stRunning) return 0; return ret; } RESULT eServiceMP3::info(ePtr<iServiceInformation>&i) { i = this; return 0; } RESULT eServiceMP3::getName(std::string &name) { std::string title = m_ref.getName(); if (title.empty()) { name = m_ref.path; size_t n = name.rfind('/'); if (n != std::string::npos) name = name.substr(n + 1); } else name = title; return 0; } RESULT eServiceMP3::getEvent(ePtr<eServiceEvent> &evt, int nownext) { evt = nownext ? m_event_next : m_event_now; if (!evt) return -1; return 0; } int eServiceMP3::getInfo(int w) { const gchar *tag = 0; switch (w) { case sServiceref: return m_ref; case sVideoHeight: return m_height; case sVideoWidth: return m_width; case sFrameRate: return m_framerate; case sProgressive: return m_progressive; case sAspect: return m_aspect; case sTagTitle: case sTagArtist: case sTagAlbum: case sTagTitleSortname: case sTagArtistSortname: case sTagAlbumSortname: case sTagDate: case sTagComposer: case sTagGenre: case sTagComment: case sTagExtendedComment: case sTagLocation: case sTagHomepage: case sTagDescription: case sTagVersion: case sTagISRC: case sTagOrganization: case sTagCopyright: case sTagCopyrightURI: case sTagContact: case sTagLicense: case sTagLicenseURI: case sTagCodec: case sTagAudioCodec: case sTagVideoCodec: case sTagEncoder: case sTagLanguageCode: case sTagKeywords: case sTagChannelMode: case sUser+12: return resIsString; case sTagTrackGain: case sTagTrackPeak: case sTagAlbumGain: case sTagAlbumPeak: case sTagReferenceLevel: case sTagBeatsPerMinute: case sTagImage: case sTagPreviewImage: case sTagAttachment: return resIsPyObject; case sTagTrackNumber: tag = GST_TAG_TRACK_NUMBER; break; case sTagTrackCount: tag = GST_TAG_TRACK_COUNT; break; case sTagAlbumVolumeNumber: tag = GST_TAG_ALBUM_VOLUME_NUMBER; break; case sTagAlbumVolumeCount: tag = GST_TAG_ALBUM_VOLUME_COUNT; break; case sTagBitrate: tag = GST_TAG_BITRATE; break; case sTagNominalBitrate: tag = GST_TAG_NOMINAL_BITRATE; break; case sTagMinimumBitrate: tag = GST_TAG_MINIMUM_BITRATE; break; case sTagMaximumBitrate: tag = GST_TAG_MAXIMUM_BITRATE; break; case sTagSerial: tag = GST_TAG_SERIAL; break; case sTagEncoderVersion: tag = GST_TAG_ENCODER_VERSION; break; case sTagCRC: tag = "has-crc"; break; default: return resNA; } if (!m_stream_tags || !tag) return 0; guint value; if (gst_tag_list_get_uint(m_stream_tags, tag, &value)) return (int) value; return 0; } std::string eServiceMP3::getInfoString(int w) { if ( m_sourceinfo.is_streaming ) { switch (w) { case sProvider: return "IPTV"; case sServiceref: { eServiceReference ref(m_ref); ref.type = eServiceFactoryMP3::id; ref.path.clear(); return ref.toString(); } default: break; } } if ( !m_stream_tags && w < sUser && w > 26 ) return ""; const gchar *tag = 0; switch (w) { case sTagTitle: tag = GST_TAG_TITLE; break; case sTagArtist: tag = GST_TAG_ARTIST; break; case sTagAlbum: tag = GST_TAG_ALBUM; break; case sTagTitleSortname: tag = GST_TAG_TITLE_SORTNAME; break; case sTagArtistSortname: tag = GST_TAG_ARTIST_SORTNAME; break; case sTagAlbumSortname: tag = GST_TAG_ALBUM_SORTNAME; break; case sTagDate: GDate *date; GstDateTime *date_time; if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date)) { gchar res[5]; snprintf(res, sizeof(res), "%04d", g_date_get_year(date)); g_date_free(date); return (std::string)res; } #if GST_VERSION_MAJOR >= 1 else if (gst_tag_list_get_date_time(m_stream_tags, GST_TAG_DATE_TIME, &date_time)) { if (gst_date_time_has_year(date_time)) { gchar res[5]; snprintf(res, sizeof(res), "%04d", gst_date_time_get_year(date_time)); gst_date_time_unref(date_time); return (std::string)res; } gst_date_time_unref(date_time); } #endif break; case sTagComposer: tag = GST_TAG_COMPOSER; break; case sTagGenre: tag = GST_TAG_GENRE; break; case sTagComment: tag = GST_TAG_COMMENT; break; case sTagExtendedComment: tag = GST_TAG_EXTENDED_COMMENT; break; case sTagLocation: tag = GST_TAG_LOCATION; break; case sTagHomepage: tag = GST_TAG_HOMEPAGE; break; case sTagDescription: tag = GST_TAG_DESCRIPTION; break; case sTagVersion: tag = GST_TAG_VERSION; break; case sTagISRC: tag = GST_TAG_ISRC; break; case sTagOrganization: tag = GST_TAG_ORGANIZATION; break; case sTagCopyright: tag = GST_TAG_COPYRIGHT; break; case sTagCopyrightURI: tag = GST_TAG_COPYRIGHT_URI; break; case sTagContact: tag = GST_TAG_CONTACT; break; case sTagLicense: tag = GST_TAG_LICENSE; break; case sTagLicenseURI: tag = GST_TAG_LICENSE_URI; break; case sTagCodec: tag = GST_TAG_CODEC; break; case sTagAudioCodec: tag = GST_TAG_AUDIO_CODEC; break; case sTagVideoCodec: tag = GST_TAG_VIDEO_CODEC; break; case sTagEncoder: tag = GST_TAG_ENCODER; break; case sTagLanguageCode: tag = GST_TAG_LANGUAGE_CODE; break; case sTagKeywords: tag = GST_TAG_KEYWORDS; break; case sTagChannelMode: tag = "channel-mode"; break; case sUser+12: return m_errorInfo.error_message; default: return ""; } if ( !tag ) return ""; gchar *value; if (m_stream_tags && gst_tag_list_get_string(m_stream_tags, tag, &value)) { std::string res = value; g_free(value); return res; } return ""; } ePtr<iServiceInfoContainer> eServiceMP3::getInfoObject(int w) { eServiceMP3InfoContainer *container = new eServiceMP3InfoContainer; ePtr<iServiceInfoContainer> retval = container; const gchar *tag = 0; bool isBuffer = false; switch (w) { case sTagTrackGain: tag = GST_TAG_TRACK_GAIN; break; case sTagTrackPeak: tag = GST_TAG_TRACK_PEAK; break; case sTagAlbumGain: tag = GST_TAG_ALBUM_GAIN; break; case sTagAlbumPeak: tag = GST_TAG_ALBUM_PEAK; break; case sTagReferenceLevel: tag = GST_TAG_REFERENCE_LEVEL; break; case sTagBeatsPerMinute: tag = GST_TAG_BEATS_PER_MINUTE; break; case sTagImage: tag = GST_TAG_IMAGE; isBuffer = true; break; case sTagPreviewImage: tag = GST_TAG_PREVIEW_IMAGE; isBuffer = true; break; case sTagAttachment: tag = GST_TAG_ATTACHMENT; isBuffer = true; break; default: break; } if (m_stream_tags && tag) { if (isBuffer) { const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0); if ( gv_buffer ) { GstBuffer *buffer; buffer = gst_value_get_buffer (gv_buffer); container->setBuffer(buffer); } } else { gdouble value = 0.0; gst_tag_list_get_double(m_stream_tags, tag, &value); container->setDouble(value); } } return retval; } RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr) { ptr = this; return 0; } RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr) { ptr = this; return 0; } RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr) { ptr = this; return 0; } RESULT eServiceMP3::audioDelay(ePtr<iAudioDelay> &ptr) { ptr = this; return 0; } int eServiceMP3::getNumberOfTracks() { return m_audioStreams.size(); } int eServiceMP3::getCurrentTrack() { if (m_currentAudioStream == -1) g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &m_currentAudioStream, NULL); return m_currentAudioStream; } RESULT eServiceMP3::selectTrack(unsigned int i) { bool validposition = false; pts_t ppos = 0; if (getPlayPosition(ppos) >= 0) { validposition = true; ppos -= 90000; if (ppos < 0) ppos = 0; } int ret = selectAudioStream(i); if (!ret) { if (validposition) { /* flush */ seekTo(ppos); } } return ret; } int eServiceMP3::selectAudioStream(int i) { int current_audio; g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL); g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &current_audio, NULL); if ( current_audio == i ) { eDebug ("eServiceMP3::switched to audio stream %i", current_audio); m_currentAudioStream = i; return 0; } return -1; } int eServiceMP3::getCurrentChannel() { return STEREO; } RESULT eServiceMP3::selectChannel(int i) { eDebug("eServiceMP3::selectChannel(%i)",i); return 0; } RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i) { if (i >= m_audioStreams.size()) return -2; info.m_description = m_audioStreams[i].codec; /* if (m_audioStreams[i].type == atMPEG) info.m_description = "MPEG"; else if (m_audioStreams[i].type == atMP3) info.m_description = "MP3"; else if (m_audioStreams[i].type == atAC3) info.m_description = "AC3"; else if (m_audioStreams[i].type == atAAC) info.m_description = "AAC"; else if (m_audioStreams[i].type == atDTS) info.m_description = "DTS"; else if (m_audioStreams[i].type == atPCM) info.m_description = "PCM"; else if (m_audioStreams[i].type == atOGG) info.m_description = "OGG"; else if (m_audioStreams[i].type == atFLAC) info.m_description = "FLAC"; else info.m_description = "???";*/ if (info.m_language.empty()) info.m_language = m_audioStreams[i].language_code; return 0; } subtype_t getSubtitleType(GstPad* pad, gchar *g_codec=NULL) { subtype_t type = stUnknown; #if GST_VERSION_MAJOR < 1 GstCaps* caps = gst_pad_get_negotiated_caps(pad); #else GstCaps* caps = gst_pad_get_current_caps(pad); #endif if (!caps && !g_codec) { caps = gst_pad_get_allowed_caps(pad); } if (caps && !gst_caps_is_empty(caps)) { GstStructure* str = gst_caps_get_structure(caps, 0); if (str) { const gchar *g_type = gst_structure_get_name(str); // eDebug("getSubtitleType::subtitle probe caps type=%s", g_type ? g_type : "(null)"); if (g_type) { if ( !strcmp(g_type, "video/x-dvd-subpicture") ) type = stVOB; else if ( !strcmp(g_type, "text/x-pango-markup") ) type = stSRT; else if ( !strcmp(g_type, "text/plain") || !strcmp(g_type, "text/x-plain") || !strcmp(g_type, "text/x-raw") ) type = stPlainText; else if ( !strcmp(g_type, "subpicture/x-pgs") ) type = stPGS; else eDebug("getSubtitleType::unsupported subtitle caps %s (%s)", g_type, g_codec ? g_codec : "(null)"); } } } else if ( g_codec ) { // eDebug("getSubtitleType::subtitle probe codec tag=%s", g_codec); if ( !strcmp(g_codec, "VOB") ) type = stVOB; else if ( !strcmp(g_codec, "SubStation Alpha") || !strcmp(g_codec, "SSA") ) type = stSSA; else if ( !strcmp(g_codec, "ASS") ) type = stASS; else if ( !strcmp(g_codec, "SRT") ) type = stSRT; else if ( !strcmp(g_codec, "UTF-8 plain text") ) type = stPlainText; else eDebug("getSubtitleType::unsupported subtitle codec %s", g_codec); } else eDebug("getSubtitleType::unidentifiable subtitle stream!"); return type; } void eServiceMP3::gstBusCall(GstMessage *msg) { if (!msg) return; gchar *sourceName; GstObject *source; source = GST_MESSAGE_SRC(msg); if (!GST_IS_OBJECT(source)) return; sourceName = gst_object_get_name(source); #if 0 gchar *string; if (gst_message_get_structure(msg)) string = gst_structure_to_string(gst_message_get_structure(msg)); else string = g_strdup(GST_MESSAGE_TYPE_NAME(msg)); // eDebug("eTsRemoteSource::gst_message from %s: %s", sourceName, string); g_free(string); #endif switch (GST_MESSAGE_TYPE (msg)) { case GST_MESSAGE_EOS: m_event((iPlayableService*)this, evEOF); break; case GST_MESSAGE_STATE_CHANGED: { if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin)) break; GstState old_state, new_state; gst_message_parse_state_changed(msg, &old_state, &new_state, NULL); if(old_state == new_state) break; eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state)); GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state); switch(transition) { case GST_STATE_CHANGE_NULL_TO_READY: { } break; case GST_STATE_CHANGE_READY_TO_PAUSED: { #if GST_VERSION_MAJOR >= 1 GValue result = { 0, }; #endif GstIterator *children; GstElement *subsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink"); if (subsink) { #ifdef GSTREAMER_SUBTITLE_SYNC_MODE_BUG /* * HACK: disable sync mode for now, gstreamer suffers from a bug causing sparse streams to loose sync, after pause/resume / skip * see: https://bugzilla.gnome.org/show_bug.cgi?id=619434 * Sideeffect of using sync=false is that we receive subtitle buffers (far) ahead of their * display time. * Not too far ahead for subtitles contained in the media container. * But for external srt files, we could receive all subtitles at once. * And not just once, but after each pause/resume / skip. * So as soon as gstreamer has been fixed to keep sync in sparse streams, sync needs to be re-enabled. */ g_object_set (G_OBJECT (subsink), "sync", FALSE, NULL); #endif #if 0 /* we should not use ts-offset to sync with the decoder time, we have to do our own decoder timekeeping */ g_object_set (G_OBJECT (subsink), "ts-offset", -2LL * GST_SECOND, NULL); /* late buffers probably will not occur very often */ g_object_set (G_OBJECT (subsink), "max-lateness", 0LL, NULL); /* avoid prerolling (it might not be a good idea to preroll a sparse stream) */ g_object_set (G_OBJECT (subsink), "async", TRUE, NULL); #endif // eDebug("eServiceMP3::subsink properties set!"); gst_object_unref(subsink); } if (audioSink) { gst_object_unref(GST_OBJECT(audioSink)); audioSink = NULL; } if (videoSink) { gst_object_unref(GST_OBJECT(videoSink)); videoSink = NULL; } children = gst_bin_iterate_recurse(GST_BIN(m_gst_playbin)); #if GST_VERSION_MAJOR < 1 audioSink = GST_ELEMENT_CAST(gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, (gpointer)"GstDVBAudioSink")); #else if (gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, &result, (gpointer)"GstDVBAudioSink")) { audioSink = GST_ELEMENT_CAST(g_value_dup_object(&result)); g_value_unset(&result); } #endif gst_iterator_free(children); children = gst_bin_iterate_recurse(GST_BIN(m_gst_playbin)); #if GST_VERSION_MAJOR < 1 videoSink = GST_ELEMENT_CAST(gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, (gpointer)"GstDVBVideoSink")); #else if (gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, &result, (gpointer)"GstDVBVideoSink")) { videoSink = GST_ELEMENT_CAST(g_value_dup_object(&result)); g_value_unset(&result); } #endif gst_iterator_free(children); m_is_live = (gst_element_get_state(m_gst_playbin, NULL, NULL, 0LL) == GST_STATE_CHANGE_NO_PREROLL); setAC3Delay(ac3_delay); setPCMDelay(pcm_delay); } break; case GST_STATE_CHANGE_PAUSED_TO_PLAYING: { if ( m_sourceinfo.is_streaming && m_streamingsrc_timeout ) m_streamingsrc_timeout->stop(); m_paused = false; if (m_seek_paused) { m_seek_paused = false; gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED); } } break; case GST_STATE_CHANGE_PLAYING_TO_PAUSED: { m_paused = true; } break; case GST_STATE_CHANGE_PAUSED_TO_READY: { if (audioSink) { gst_object_unref(GST_OBJECT(audioSink)); audioSink = NULL; } if (videoSink) { gst_object_unref(GST_OBJECT(videoSink)); videoSink = NULL; } } break; case GST_STATE_CHANGE_READY_TO_NULL: { } break; } break; } case GST_MESSAGE_ERROR: { gchar *debug; GError *err; gst_message_parse_error (msg, &err, &debug); g_free (debug); eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName ); if ( err->domain == GST_STREAM_ERROR ) { if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND ) { if ( g_strrstr(sourceName, "videosink") ) m_event((iPlayableService*)this, evUser+11); else if ( g_strrstr(sourceName, "audiosink") ) m_event((iPlayableService*)this, evUser+10); } } g_error_free(err); break; } case GST_MESSAGE_INFO: { gchar *debug; GError *inf; gst_message_parse_info (msg, &inf, &debug); g_free (debug); if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE ) { if ( g_strrstr(sourceName, "videosink") ) m_event((iPlayableService*)this, evUser+14); } g_error_free(inf); break; } case GST_MESSAGE_TAG: { GstTagList *tags, *result; gst_message_parse_tag(msg, &tags); result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE); if (result) { if (m_stream_tags) gst_tag_list_free(m_stream_tags); m_stream_tags = result; } const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0); if ( gv_image ) { GstBuffer *buf_image; buf_image = gst_value_get_buffer (gv_image); int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644); if (fd >= 0) { guint8 *data; gsize size; #if GST_VERSION_MAJOR < 1 data = GST_BUFFER_DATA(buf_image); size = GST_BUFFER_SIZE(buf_image); #else GstMapInfo map; gst_buffer_map(buf_image, &map, GST_MAP_READ); data = map.data; size = map.size; #endif int ret = write(fd, data, size); #if GST_VERSION_MAJOR >= 1 gst_buffer_unmap(buf_image, &map); #endif close(fd); // eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret); } m_event((iPlayableService*)this, evUser+13); } gst_tag_list_free(tags); m_event((iPlayableService*)this, evUpdatedInfo); break; } case GST_MESSAGE_ASYNC_DONE: { if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin)) break; gint i, n_video = 0, n_audio = 0, n_text = 0; g_object_get (m_gst_playbin, "n-video", &n_video, NULL); g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL); g_object_get (m_gst_playbin, "n-text", &n_text, NULL); eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text); if ( n_video + n_audio <= 0 ) stop(); m_audioStreams.clear(); m_subtitleStreams.clear(); for (i = 0; i < n_audio; i++) { audioStream audio; gchar *g_codec, *g_lang; GstTagList *tags = NULL; GstPad* pad = 0; g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad); #if GST_VERSION_MAJOR < 1 GstCaps* caps = gst_pad_get_negotiated_caps(pad); #else GstCaps* caps = gst_pad_get_current_caps(pad); #endif if (!caps) continue; GstStructure* str = gst_caps_get_structure(caps, 0); const gchar *g_type = gst_structure_get_name(str); eDebug("AUDIO STRUCT=%s", g_type); audio.type = gstCheckAudioPad(str); audio.language_code = "und"; audio.codec = g_type; g_codec = NULL; g_lang = NULL; g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags); #if GST_VERSION_MAJOR < 1 if (tags && gst_is_tag_list(tags)) #else if (tags && GST_IS_TAG_LIST(tags)) #endif { if (gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec)) { audio.codec = std::string(g_codec); g_free(g_codec); } if (gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang)) { audio.language_code = std::string(g_lang); g_free(g_lang); } gst_tag_list_free(tags); } eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, audio.codec.c_str(), audio.language_code.c_str()); m_audioStreams.push_back(audio); gst_caps_unref(caps); } for (i = 0; i < n_text; i++) { gchar *g_codec = NULL, *g_lang = NULL; GstTagList *tags = NULL; g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags); subtitleStream subs; subs.language_code = "und"; #if GST_VERSION_MAJOR < 1 if (tags && gst_is_tag_list(tags)) #else if (tags && GST_IS_TAG_LIST(tags)) #endif { if (gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang)) { subs.language_code = g_lang; g_free(g_lang); } gst_tag_list_get_string(tags, GST_TAG_SUBTITLE_CODEC, &g_codec); gst_tag_list_free(tags); } eDebug("eServiceMP3::subtitle stream=%i language=%s codec=%s", i, subs.language_code.c_str(), g_codec ? g_codec : "(null)"); GstPad* pad = 0; g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad); if ( pad ) g_signal_connect (G_OBJECT (pad), "notify::caps", G_CALLBACK (gstTextpadHasCAPS), this); subs.type = getSubtitleType(pad, g_codec); g_free(g_codec); m_subtitleStreams.push_back(subs); } m_event((iPlayableService*)this, evUpdatedInfo); if ( m_errorInfo.missing_codec != "" ) { if (m_errorInfo.missing_codec.find("video/") == 0 || (m_errorInfo.missing_codec.find("audio/") == 0 && m_audioStreams.empty())) m_event((iPlayableService*)this, evUser+12); } break; } case GST_MESSAGE_ELEMENT: { const GstStructure *msgstruct = gst_message_get_structure(msg); if (msgstruct) { if ( gst_is_missing_plugin_message(msg) ) { GstCaps *caps = NULL; gst_structure_get (msgstruct, "detail", GST_TYPE_CAPS, &caps, NULL); if (caps) { std::string codec = (const char*) gst_caps_to_string(caps); gchar *description = gst_missing_plugin_message_get_description(msg); if ( description ) { eDebug("eServiceMP3::m_errorInfo.missing_codec = %s", codec.c_str()); m_errorInfo.error_message = "GStreamer plugin " + (std::string)description + " not available!\n"; m_errorInfo.missing_codec = codec.substr(0,(codec.find_first_of(','))); g_free(description); } gst_caps_unref(caps); } } else { const gchar *eventname = gst_structure_get_name(msgstruct); if ( eventname ) { if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail")) { gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect); gst_structure_get_int (msgstruct, "width", &m_width); gst_structure_get_int (msgstruct, "height", &m_height); if (strstr(eventname, "Changed")) m_event((iPlayableService*)this, evVideoSizeChanged); } else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail")) { gst_structure_get_int (msgstruct, "frame_rate", &m_framerate); if (strstr(eventname, "Changed")) m_event((iPlayableService*)this, evVideoFramerateChanged); } else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail")) { gst_structure_get_int (msgstruct, "progressive", &m_progressive); if (strstr(eventname, "Changed")) m_event((iPlayableService*)this, evVideoProgressiveChanged); } else if (!strcmp(eventname, "redirect")) { const char *uri = gst_structure_get_string(msgstruct, "new-location"); // eDebug("redirect to %s", uri); gst_element_set_state (m_gst_playbin, GST_STATE_NULL); g_object_set(G_OBJECT (m_gst_playbin), "uri", uri, NULL); gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING); } } } } break; } case GST_MESSAGE_BUFFERING: if (m_state == stRunning && m_sourceinfo.is_streaming) { GstBufferingMode mode; gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent)); // eDebug("Buffering %u percent done", m_bufferInfo.bufferPercent); gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft)); m_event((iPlayableService*)this, evBuffering); /* * we don't react to buffer level messages, unless we are configured to use a prefill buffer * (even if we are not configured to, we still use the buffer, but we rely on it to remain at the * healthy level at all times, without ever having to pause the stream) * * Also, it does not make sense to pause the stream if it is a live stream * (in which case the sink will not produce data while paused, so we won't * recover from an empty buffer) */ if (m_use_prefillbuffer && !m_is_live && --m_ignore_buffering_messages <= 0) { if (m_bufferInfo.bufferPercent == 100) { GstState state; gst_element_get_state(m_gst_playbin, &state, NULL, 0LL); if (state != GST_STATE_PLAYING) { // eDebug("start playing"); gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING); } /* * when we start the pipeline, the contents of the buffer will immediately drain * into the (hardware buffers of the) sinks, so we will receive low buffer level * messages right away. * Ignore the first few buffering messages, giving the buffer the chance to recover * a bit, before we start handling empty buffer states again. */ m_ignore_buffering_messages = 5; } else if (m_bufferInfo.bufferPercent == 0) { // eDebug("start pause"); gst_element_set_state (m_gst_playbin, GST_STATE_PAUSED); m_ignore_buffering_messages = 0; } else { m_ignore_buffering_messages = 0; } } } break; case GST_MESSAGE_STREAM_STATUS: { GstStreamStatusType type; GstElement *owner; gst_message_parse_stream_status (msg, &type, &owner); if ( type == GST_STREAM_STATUS_TYPE_CREATE && m_sourceinfo.is_streaming ) { if ( GST_IS_PAD(source) ) owner = gst_pad_get_parent_element(GST_PAD(source)); else if ( GST_IS_ELEMENT(source) ) owner = GST_ELEMENT(source); else owner = 0; if ( owner ) { GstState state; gst_element_get_state(m_gst_playbin, &state, NULL, 0LL); GstElementFactory *factory = gst_element_get_factory(GST_ELEMENT(owner)); const gchar *name = gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory)); if (!strcmp(name, "souphttpsrc") && (state == GST_STATE_READY) && !m_streamingsrc_timeout->isActive()) { m_streamingsrc_timeout->start(HTTP_TIMEOUT*1000, true); g_object_set (G_OBJECT (owner), "timeout", HTTP_TIMEOUT, NULL); // eDebug("eServiceMP3::GST_STREAM_STATUS_TYPE_CREATE -> setting timeout on %s to %is", name, HTTP_TIMEOUT); } } if ( GST_IS_PAD(source) ) gst_object_unref(owner); } break; } default: break; } g_free (sourceName); } void eServiceMP3::handleMessage(GstMessage *msg) { if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_STATE_CHANGED && GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin)) { /* * ignore verbose state change messages for all active elements; * we only need to handle state-change events for the playbin */ gst_message_unref(msg); return; } m_pump.send(new GstMessageContainer(1, msg, NULL, NULL)); } GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data) { eServiceMP3 *_this = (eServiceMP3*)user_data; if (_this) _this->handleMessage(message); return GST_BUS_DROP; } void eServiceMP3::playbinNotifySource(GObject *object, GParamSpec *unused, gpointer user_data) { GstElement *source = NULL; eServiceMP3 *_this = (eServiceMP3*)user_data; g_object_get(object, "source", &source, NULL); if (source) { if (g_object_class_find_property(G_OBJECT_GET_CLASS(source), "ssl-strict") != 0) { g_object_set(G_OBJECT(source), "ssl-strict", FALSE, NULL); } if (g_object_class_find_property(G_OBJECT_GET_CLASS(source), "user-agent") != 0 && !_this->m_useragent.empty()) { g_object_set(G_OBJECT(source), "user-agent", _this->m_useragent.c_str(), NULL); } if (g_object_class_find_property(G_OBJECT_GET_CLASS(source), "extra-headers") != 0 && !_this->m_extra_headers.empty()) { #if GST_VERSION_MAJOR < 1 GstStructure *extras = gst_structure_empty_new("extras"); #else GstStructure *extras = gst_structure_new_empty("extras"); #endif size_t pos = 0; while (pos != std::string::npos) { std::string name, value; size_t start = pos; size_t len = std::string::npos; pos = _this->m_extra_headers.find(':', pos); if (pos != std::string::npos) { len = pos - start; pos++; name = _this->m_extra_headers.substr(start, len); start = pos; len = std::string::npos; pos = _this->m_extra_headers.find('|', pos); if (pos != std::string::npos) { len = pos - start; pos++; } value = _this->m_extra_headers.substr(start, len); } if (!name.empty() && !value.empty()) { GValue header; // eDebug("setting extra-header '%s:%s'", name.c_str(), value.c_str()); memset(&header, 0, sizeof(GValue)); g_value_init(&header, G_TYPE_STRING); g_value_set_string(&header, value.c_str()); gst_structure_set_value(extras, name.c_str(), &header); } else { eDebug("Invalid header format %s", _this->m_extra_headers.c_str()); break; } } if (gst_structure_n_fields(extras) > 0) { g_object_set(G_OBJECT(source), "extra-headers", extras, NULL); } gst_structure_free(extras); } gst_object_unref(source); } } void eServiceMP3::handleElementAdded(GstBin *bin, GstElement *element, gpointer user_data) { eServiceMP3 *_this = (eServiceMP3*)user_data; if (_this) { gchar *elementname = gst_element_get_name(element); if (g_str_has_prefix(elementname, "queue2")) { if (_this->m_download_buffer_path != "") { g_object_set(G_OBJECT(element), "temp-template", _this->m_download_buffer_path.c_str(), NULL); } else { g_object_set(G_OBJECT(element), "temp-template", NULL, NULL); } } else if (g_str_has_prefix(elementname, "uridecodebin") #if GST_VERSION_MAJOR < 1 || g_str_has_prefix(elementname, "decodebin2")) #else || g_str_has_prefix(elementname, "decodebin")) #endif { /* * Listen for queue2 element added to uridecodebin/decodebin2 as well. * Ignore other bins since they may have unrelated queues */ g_signal_connect(element, "element-added", G_CALLBACK(handleElementAdded), user_data); } g_free(elementname); } } audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure) { if (!structure) return atUnknown; if ( gst_structure_has_name (structure, "audio/mpeg")) { gint mpegversion, layer = -1; if (!gst_structure_get_int (structure, "mpegversion", &mpegversion)) return atUnknown; switch (mpegversion) { case 1: { gst_structure_get_int (structure, "layer", &layer); if ( layer == 3 ) return atMP3; else return atMPEG; break; } case 2: return atAAC; case 4: return atAAC; default: return atUnknown; } } else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") ) return atAC3; else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") ) return atDTS; #if GST_VERSION_MAJOR < 1 else if ( gst_structure_has_name (structure, "audio/x-raw-int") ) #else else if ( gst_structure_has_name (structure, "audio/x-raw") ) #endif return atPCM; return atUnknown; } void eServiceMP3::gstPoll(ePtr<GstMessageContainer> const &msg) { switch (msg->getType()) { case 1: { GstMessage *gstmessage = *((GstMessageContainer*)msg); if (gstmessage) { gstBusCall(gstmessage); } break; } case 2: { GstBuffer *buffer = *((GstMessageContainer*)msg); if (buffer) { pullSubtitle(buffer); } break; } case 3: { GstPad *pad = *((GstMessageContainer*)msg); gstTextpadHasCAPS_synced(pad); break; } } } eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3"); void eServiceMP3::gstCBsubtitleAvail(GstElement *subsink, GstBuffer *buffer, gpointer user_data) { eServiceMP3 *_this = (eServiceMP3*)user_data; if (_this->m_currentSubtitleStream < 0) { if (buffer) gst_buffer_unref(buffer); return; } _this->m_pump.send(new GstMessageContainer(2, NULL, NULL, buffer)); } void eServiceMP3::gstTextpadHasCAPS(GstPad *pad, GParamSpec * unused, gpointer user_data) { eServiceMP3 *_this = (eServiceMP3*)user_data; gst_object_ref (pad); _this->m_pump.send(new GstMessageContainer(3, NULL, pad, NULL)); } void eServiceMP3::gstTextpadHasCAPS_synced(GstPad *pad) { GstCaps *caps = NULL; g_object_get (G_OBJECT (pad), "caps", &caps, NULL); if (caps) { subtitleStream subs; // eDebug("gstTextpadHasCAPS:: signal::caps = %s", gst_caps_to_string(caps)); // eDebug("gstGhostpadHasCAPS_synced %p %d", pad, m_subtitleStreams.size()); if (m_currentSubtitleStream >= 0 && m_currentSubtitleStream < (int)m_subtitleStreams.size()) subs = m_subtitleStreams[m_currentSubtitleStream]; else { subs.type = stUnknown; subs.pad = pad; } if ( subs.type == stUnknown ) { GstTagList *tags = NULL; gchar *g_lang = NULL; g_signal_emit_by_name (m_gst_playbin, "get-text-tags", m_currentSubtitleStream, &tags); subs.language_code = "und"; subs.type = getSubtitleType(pad); #if GST_VERSION_MAJOR < 1 if (tags && gst_is_tag_list(tags)) #else if (tags && GST_IS_TAG_LIST(tags)) #endif { if (gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang)) { subs.language_code = std::string(g_lang); g_free(g_lang); } } if (m_currentSubtitleStream >= 0 && m_currentSubtitleStream < (int)m_subtitleStreams.size()) m_subtitleStreams[m_currentSubtitleStream] = subs; else m_subtitleStreams.push_back(subs); } // eDebug("gstGhostpadHasCAPS:: m_gst_prev_subtitle_caps=%s equal=%i",gst_caps_to_string(m_gst_prev_subtitle_caps),gst_caps_is_equal(m_gst_prev_subtitle_caps, caps)); gst_caps_unref (caps); } } void eServiceMP3::pullSubtitle(GstBuffer *buffer) { if (buffer && m_currentSubtitleStream >= 0 && m_currentSubtitleStream < (int)m_subtitleStreams.size()) { #if GST_VERSION_MAJOR < 1 gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer); size_t len = GST_BUFFER_SIZE(buffer); #else GstMapInfo map; if(!gst_buffer_map(buffer, &map, GST_MAP_READ)) { eDebug("eServiceMP3::pullSubtitle gst_buffer_map failed"); return; } gint64 buf_pos = GST_BUFFER_PTS(buffer); size_t len = map.size; eDebug("gst_buffer_get_size %zu map.size %zu", gst_buffer_get_size(buffer), len); #endif gint64 duration_ns = GST_BUFFER_DURATION(buffer); int subType = m_subtitleStreams[m_currentSubtitleStream].type; // eDebug("pullSubtitle type=%d size=%zu", subType, len); if ( subType ) { if ( subType < stVOB ) { int delay = eConfigManager::getConfigIntValue("config.subtitles.pango_subtitles_delay"); int subtitle_fps = eConfigManager::getConfigIntValue("config.subtitles.pango_subtitles_fps"); double convert_fps = 1.0; if (subtitle_fps > 1 && m_framerate > 0) convert_fps = subtitle_fps / (double)m_framerate; #if GST_VERSION_MAJOR < 1 std::string line((const char*)GST_BUFFER_DATA(buffer), len); #else std::string line((const char*)map.data, len); #endif // eDebug("got new text subtitle @ buf_pos = %lld ns (in pts=%lld), dur=%lld: '%s' ", buf_pos, buf_pos/11111, duration_ns, line.c_str()); uint32_t start_ms = ((buf_pos / 1000000ULL) * convert_fps) + delay; uint32_t end_ms = start_ms + (duration_ns / 1000000ULL); m_subtitle_pages.insert(subtitle_pages_map_pair_t(end_ms, subtitle_page_t(start_ms, end_ms, line))); m_subtitle_sync_timer->start(1, true); } else { eDebug("unsupported subpicture... ignoring"); } } #if GST_VERSION_MAJOR >= 1 gst_buffer_unmap(buffer, &map); #endif } } void eServiceMP3::pushSubtitles() { pts_t running_pts = 0; int32_t next_timer = 0, decoder_ms, start_ms, end_ms, diff_start_ms, diff_end_ms; subtitle_pages_map_t::iterator current; // wait until clock is stable if (getPlayPosition(running_pts) < 0) m_decoder_time_valid_state = 0; if (m_decoder_time_valid_state < 4) { m_decoder_time_valid_state++; if (m_prev_decoder_time == running_pts) m_decoder_time_valid_state = 0; if (m_decoder_time_valid_state < 4) { //eDebug("*** push subtitles, waiting for clock to stabilise"); m_prev_decoder_time = running_pts; next_timer = 50; goto exit; } //eDebug("*** push subtitles, clock stable"); } decoder_ms = running_pts / 90; #if 0 // eDebug("\n*** all subs: "); for (current = m_subtitle_pages.begin(); current != m_subtitle_pages.end(); current++) { start_ms = current->second.start_ms; end_ms = current->second.end_ms; diff_start_ms = start_ms - decoder_ms; diff_end_ms = end_ms - decoder_ms; // eDebug(" start: %d, end: %d, diff_start: %d, diff_end: %d: %s", start_ms, end_ms, diff_start_ms, diff_end_ms, current->second.text.c_str()); } // eDebug("\n\n"); #endif for (current = m_subtitle_pages.lower_bound(decoder_ms); current != m_subtitle_pages.end(); current++) { start_ms = current->second.start_ms; end_ms = current->second.end_ms; diff_start_ms = start_ms - decoder_ms; diff_end_ms = end_ms - decoder_ms; #if 0 // eDebug("*** next subtitle: decoder: %d, start: %d, end: %d, duration_ms: %d, diff_start: %d, diff_end: %d : %s", decoder_ms, start_ms, end_ms, end_ms - start_ms, diff_start_ms, diff_end_ms, current->second.text.c_str()); #endif if (diff_end_ms < 0) { //eDebug("*** current sub has already ended, skip: %d\n", diff_end_ms); continue; } if (diff_start_ms > 20) { //eDebug("*** current sub in the future, start timer, %d\n", diff_start_ms); next_timer = diff_start_ms; goto exit; } // showtime if (m_subtitle_widget) { //eDebug("*** current sub actual, show!"); ePangoSubtitlePage pango_page; gRGB rgbcol(0xD0,0xD0,0xD0); pango_page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, current->second.text.c_str())); pango_page.m_show_pts = start_ms * 90; // actually completely unused by widget! if (!m_subtitles_paused) pango_page.m_timeout = end_ms - decoder_ms; // take late start into account else pango_page.m_timeout = 60000; //paused, subs must stay on (60s for now), avoid timeout in lib/gui/esubtitle.cpp: m_hide_subtitles_timer->start(m_pango_page.m_timeout, true); m_subtitle_widget->setPage(pango_page); } //eDebug("*** no next sub scheduled, check NEXT subtitle"); } // no more subs in cache, fall through exit: if (next_timer == 0) { //eDebug("*** next timer = 0, set default timer!"); next_timer = 1000; } m_subtitle_sync_timer->start(next_timer, true); // eDebug("\n\n"); } RESULT eServiceMP3::enableSubtitles(iSubtitleUser *user, struct SubtitleTrack &track) { if (m_currentSubtitleStream != track.pid) { g_object_set (G_OBJECT (m_gst_playbin), "current-text", -1, NULL); m_subtitle_sync_timer->stop(); m_subtitle_pages.clear(); m_prev_decoder_time = -1; m_decoder_time_valid_state = 0; m_currentSubtitleStream = track.pid; m_cachedSubtitleStream = m_currentSubtitleStream; g_object_set (G_OBJECT (m_gst_playbin), "current-text", m_currentSubtitleStream, NULL); m_subtitle_widget = user; eDebug ("eServiceMP3::switched to subtitle stream %i", m_currentSubtitleStream); #ifdef GSTREAMER_SUBTITLE_SYNC_MODE_BUG /* * when we're running the subsink in sync=false mode, * we have to force a seek, before the new subtitle stream will start */ seekRelative(-1, 90000); #endif } return 0; } RESULT eServiceMP3::disableSubtitles() { eDebug("eServiceMP3::disableSubtitles"); m_currentSubtitleStream = -1; m_cachedSubtitleStream = m_currentSubtitleStream; g_object_set (G_OBJECT (m_gst_playbin), "current-text", m_currentSubtitleStream, NULL); m_subtitle_sync_timer->stop(); m_subtitle_pages.clear(); m_prev_decoder_time = -1; m_decoder_time_valid_state = 0; if (m_subtitle_widget) m_subtitle_widget->destroy(); m_subtitle_widget = 0; return 0; } RESULT eServiceMP3::getCachedSubtitle(struct SubtitleTrack &track) { bool autoturnon = eConfigManager::getConfigBoolValue("config.subtitles.pango_autoturnon", true); if (!autoturnon) return -1; if (m_cachedSubtitleStream >= 0 && m_cachedSubtitleStream < (int)m_subtitleStreams.size()) { track.type = 2; track.pid = m_cachedSubtitleStream; track.page_number = int(m_subtitleStreams[m_cachedSubtitleStream].type); track.magazine_number = 0; return 0; } return -1; } RESULT eServiceMP3::getSubtitleList(std::vector<struct SubtitleTrack> &subtitlelist) { // eDebug("eServiceMP3::getSubtitleList"); int stream_idx = 0; for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream) { subtype_t type = IterSubtitleStream->type; switch(type) { case stUnknown: case stVOB: case stPGS: break; default: { struct SubtitleTrack track; track.type = 2; track.pid = stream_idx; track.page_number = int(type); track.magazine_number = 0; track.language_code = IterSubtitleStream->language_code; subtitlelist.push_back(track); } } stream_idx++; } // eDebug("eServiceMP3::getSubtitleList finished"); return 0; } RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr) { ptr = this; return 0; } ePtr<iStreamBufferInfo> eServiceMP3::getBufferCharge() { return new eStreamBufferInfo(m_bufferInfo.bufferPercent, m_bufferInfo.avgInRate, m_bufferInfo.avgOutRate, m_bufferInfo.bufferingLeft, m_buffer_size); } int eServiceMP3::setBufferSize(int size) { m_buffer_size = size; g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL); return 0; } int eServiceMP3::getAC3Delay() { return ac3_delay; } int eServiceMP3::getPCMDelay() { return pcm_delay; } void eServiceMP3::setAC3Delay(int delay) { ac3_delay = delay; if (!m_gst_playbin || m_state != stRunning) return; else { int config_delay_int = delay; /* * NOTE: We only look for dvbmediasinks. * If either the video or audio sink is of a different type, * we have no chance to get them synced anyway. */ if (videoSink) { config_delay_int += eConfigManager::getConfigIntValue("config.av.generalAC3delay"); } else { // eDebug("dont apply ac3 delay when no video is running!"); config_delay_int = 0; } if (audioSink) { eTSMPEGDecoder::setHwAC3Delay(config_delay_int); } } } void eServiceMP3::setPCMDelay(int delay) { pcm_delay = delay; if (!m_gst_playbin || m_state != stRunning) return; else { int config_delay_int = delay; /* * NOTE: We only look for dvbmediasinks. * If either the video or audio sink is of a different type, * we have no chance to get them synced anyway. */ if (videoSink) { config_delay_int += eConfigManager::getConfigIntValue("config.av.generalPCMdelay"); } else { // eDebug("dont apply pcm delay when no video is running!"); config_delay_int = 0; } if (audioSink) { eTSMPEGDecoder::setHwPCMDelay(config_delay_int); } } }
opendroid-Team/enigma2-4.1
lib/service/servicemp3.cpp
C++
gpl-2.0
67,814
# The Widget system This document explains how to define, place and manage widgets. ## The default configuration This is what the widgets present in the default configuration are named: @DOC_awful_popup_defaultconfig_EXAMPLE@ ## The default widgets ### Widgets Awesome provides 2 collections of widgets: * `wibox.widget`: Generic widgets, containers and layouts * `awful.widget`: The Awesome specific widgets @DOC_widget_WIDGET_LIST@ ### Containers A container is a widget that wraps another widget. It can be used to add decorations or to modify the content of the child widget. @DOC_container_WIDGET_LIST@ ### Layouts Layouts are collections of children widgets. They are placed according to configurable rules. @DOC_layout_WIDGET_LIST@ ### Awful widgets This modules contains the higher level window manager widgets. Since most of them are used by the default config, here is how it maps: @DOC_awful_wibar_defaultwibar_EXAMPLE@ @DOC_awidget_WIDGET_LIST@ ### Titlebar widgets The titlebar comes with some convinient default widgets. It simplify the most basic "Windows/macOS" like titlebars. @DOC_awful_titlebar_defaulttitlebar_EXAMPLE@ Note that titlebars can also be added on each side. This is how "active" titlebars (click to resize) can be implemented. The default `rc.lua` does not add active borders: ![](../images/client_geo.svg) <table class="widget_list" border="1"> <tr> <th>Widget</th><th>Description</th> </tr> <tr> <td>`awful.titlebar.widget.iconwidget`</td><td>The client icon (see `client.icon`)</td> </tr> <tr> <td>`awful.titlebar.widget.titlewidget`</td><td>The client title (see `client.name`)</td> </tr> <tr> <td>`awful.titlebar.widget.floatingbutton`</td><td> Toggle the floating (toggled) vs. tiling mode (untoggled). </td> </tr> <tr> <td>`awful.titlebar.widget.maximizedbutton`</td><td>Toggle the maximized mode (toggled). Note that this is the<br/>"full" maximized mode, not vertical or horizontal maximization.<br/>See `client.maximized`.</td> </tr> <tr> <td>`awful.titlebar.widget.stickybutton`</td><td>When toggled, a client will be displayed in all (screen) tags. See `client.sticky`)</td> </tr> <tr> <td>`awful.titlebar.widget.ontopbutton`</td><td>When toggled, the client will be part of the `ontop` layer (see `client.ontop`).</td> </tr> <tr> <td>`awful.titlebar.widget.closebutton`</td><td></td> </tr> <tr> <td>`titlebar.widget.minimizebutton`</td><td></td> </tr> </table> ### Notification widgets Notifications also have their own widgets. <img src="../images/AUTOGEN_wibox_nwidget_default.svg" /> More information about the notification widgets can be found on the `naughty.notification` documentation page. ### The different type of widget boxes (Wibox) The Awesome API uses the word "wibox" (widget box) to describe an area of the screen filled with widgets. There are many subvariants of wiboxes with specialized roles such as widget bars or tooltips. All variants mostly share the same characteristics, but add some extra features to make those specialized widget boxes easier to work with. @DOC_awful_popup_wiboxtypes_EXAMPLE@ The normal `wibox` is the base class for each of these types. It is extremely flexible and allows to place just about anything on the screen. However it requires a lot of repetitive boilerplate code to use directly. For example, the user needs to compute the optimal size by hand or use `awful.placement`. The `awful.wibar` specialization allows to attach a `wibox` to a screen edge and prevents clients from using this area when tiled. The `awful.popup` allows to easily place widgets on the screen. It automatically resizes itself to fit the optimal widget size. It also has helper properties and methods to make it easy to place it on the screen. It supports absolute positioning, relative positioning, and manual positioning. The `awful.tooltip` is a very simple `wibox` that allows to display text next to an object such as the mouse. The `naughty.layout.box` allows to provide custom widgets to use within the notifications. The `awful.wallpaper` provides a non-intereactive "backgroud" for one or more `screen`. While it uses normal widget, it will not automatically be repainted if they change. It will also not provide any mouse events. Finally, the `awful.titlebar`, while not technically a real `wibox`, acts exactly the same way and allows to attach widgets on each side of clients. ## The different syntaxes to initiate widgets Awesome provides 2 totally different API access styles to manage widgets. Both suit different use cases. Under the hood, both produce the exact same code. Consider the declarative API to be compiled into the imperative syntax when loaded. Also note that in contrast to technologies such as QML, it is interpreted only once and isn't automatically updated when values change. The **imperative** widget initialization is similar to QtWidgets, GTK and Win32. You create the object, then set the property and add the widget as a child to another already declared widget. It is quite simple to use but very verbose and full of boilerplate code. The imperative API also offers properties both with accessors or directly. It is useful when creating highly dynamic layouts where widgets are added and removed over the course of their lifecycle. The **declarative** syntax resembles HTML style code written in JSON or YAML. The widget instances are created automatically and the hierarchy is related to the table nesting (indentation). It is preferred when creating static layouts that won't change over the course of their lifecycle. Here is the same code written in both the imperative and declarative style **Imperative with accessors** Code: local bg = wibox.container.background() bg:set_bg("#ff0000") local tb1 = wibox.widget.textbox() local tb2 = wibox.widget.textbox("bar") tb1:set_text("foo") tb2:set_text("bar") local l = wibox.layout.fixed.vertical() l:add(tb1) l:add(tb2) bg:set_widget(l) **Imperative with properties** Code: local bg = wibox.container.background() bg.bg = "#ff0000" local tb1 = wibox.widget.textbox("foo") local tb2 = wibox.widget.textbox("bar") tb1.text = "foo" tb2.text = "bar" local l = wibox.layout.fixed.vertical() l:add(tb1) l:add(tb2) bg.widget = l **Declarative** Code: local bg = wibox.widget { { { text = "foo", widget = wibox.widget.textbox }, { text = "bar", widget = wibox.widget.textbox }, layout = wibox.layout.fixed.vertical }, bg = "#ff0000", widget = wibox.container.background } The Awesome documentation mostly uses the declarative style for consistency, but both are **always** available. Note that each style can be mixed with other styles, but this creates very confusing code and should be avoided. ## Creating and placing widgets using the declarative style The examples below explain in detail how to use the declarative layout system. The imperative system is quite self explanatory and the respective widget API documentation should be enough for most. ### A simple layout * Display `my_first_widget` only on primary screen * Display `my_second_widget` only on screen two * Add a background color to `my_fourth_widget` * Dispose in a `wibox.layout.fixed.horizontal` layout Code: s.mywibox : setup { { layout = awful.widget.only_on_screen, screen = "primary", -- Only display on primary screen my_first_widget, }, { layout = awful.widget.only_on_screen, screen = 2, -- Only display on screen 2 my_second_widget, }, my_third_widget, -- Displayed on all screens { -- Add a background color/pattern for my_fourth_widget my_fourth_widget, bg = beautiful.bg_focus, widget = wibox.container.background, }, layout = wibox.layout.fixed.horizontal, } This examples uses the `awful.widget.only_on_screen` container to display widgets only on some screens. ### Composite widgets @DOC_wibox_widget_progressbar_encapsulation_EXAMPLE@ ### Define widgets inline and place them * Create a `wibox.widget.textbox` with various properties * Force the textbox size using `wibox.layout.constraint` * Add a margin around another textbox * Add a `wibox.container.background` (for visualization) Code: s.mywibox : setup { { -- Force the textbox to always be 300 pixel long { { markup = "<b>Hello World!</b>", align = "center", widget = wibox.widget.textbox }, bg = "#ff0000", widget = wibox.container.background, }, width = 300, strategy = "min", layout = wibox.layout.constraint }, { -- Add a border around the background { { markup = "Foobar", widget = wibox.widget.textbox }, bg = "#0000ff", widget = wibox.container.background }, left = 10, right = 10, top = 1, bottom = 2, layout = wibox.container.margin }, layout = wibox.layout.fixed.horizontal, } Result: ![Example2 screenshot](../images/widgetlayout1.png) ### Use a `wibox.layout.align` layout The `wibox.layout.align` is a little different. While most layouts will ignore any `nil` lines, the `align` layout relies on them so `left`, `middle` and `right` can be defined. Code: s.mywibox : setup { my_textbox1, -- Left nil, -- Nothing in the middle my_textbox2, -- Right layout = wibox.layout.align.horizontal, } ### Define new widgets New trivial widgets can be created directly in the layout declaration. Here is a simple circle widget: Code: s.mywibox : setup { fit = function(self, context, width, height) return height, height -- A square taking the full height end, draw = function(self, context, cr, width, height) cr:set_source_rgb(1, 0, 0) -- Red cr:arc(height/2, height/2, height/2, 0, math.pi*2) cr:fill() end, layout = wibox.widget.base.make_widget, } Result: ![Example4 screenshot](../images/widgetlayout2.png) For more information about how to draw widgets, refer to the `Cairo` API: * [Path](http://cairographics.org/manual/cairo-Paths.html) * [Context](http://cairographics.org/manual/cairo-cairo-t.html) * [Pattern](http://cairographics.org/manual/cairo-cairo-pattern-t.html) * [transformation](http://cairographics.org/manual/cairo-Transformations.html) * [Operator](http://cairographics.org/operators/) * [Pango text](https://developer.gnome.org/pango/stable/) ### Externally defined widgets and layouts This is useful when the widget is provided by an external module or when it requires complex manipulations which would make the declaration unreadable. Code: local tb = wibox.widget.textbox() tb:set_markup("Hello world! ") -- Repeat "tb" 3 times s.mywibox : setup { tb, tb, tb, layout = wibox.layout.fixed.horizontal, } ### Accessing widgets For each widget or container, it is possible to add an `identifier` attribute so that it can be accessed later. Widgets defined using `setup` can be accessed using these methods: * Avoiding the issue by using externally created widgets * Using `my_wibox.my_first_widget.my_second_widget` style access * Using JavaScript like `my_wibox:get_children_by_id("my_second_widget")[1]` The first method mixes the imperative and declarative syntax, and makes the code less readable. The second is a little verbose and only works if every node in the chain has a valid identifier. The last one doesn't require long paths, but it is not easy to get a specific instance if multiple widgets have the same identifier. WARNING: The widget identifier must not use a reserved name. This includes all method names, existing widget attributes, `layout` and `widget`. Names should also respect the Lua variable conventions (case-sensitive, alphanumeric, underscore characters and non-numeric first character). Code: s.mywibox : setup { { id = "second", widget = wibox.widget.textbox }, { id = "third", widget = wibox.widget.textbox }, id = "first", layout = wibox.layout.fixed.horizontal, } s.mywibox.first.second:set_markup("changed!") s.mywibox:get_children_by_id("third")[1]:set_markup("Also changed!") ### Extending the system This system is very flexible. Each section attribute (the entries with string keys) is directly linked to the layout or widget API. When setting the imaginary `myproperty`, it will first check if `set_myproperty` exists. If it doesn't, it will check if there is a `myproperty` method. Finally, it will just set the `mywidget.myproperty` directly in case it is used later or caught by a Lua `metatable` (operator overload). Code: -- "Monkeypatch" a new function to 3 widget classes to add vicious -- extension support for _, wdg in ipairs { wibox.widget.textbox , wibox.widget.progressbar, wibox.widget.graph } do function wdg:vicious(args) local f = unpack or table.unpack -- Lua 5.1 compat vicious.register(self, f(args)) end end s.mywibox : setup { { vicious = {vicious.widgets.cpu, "CPU: $1%", 3}, widget = wibox.widget.textbox }, layout = wibox.layout.fixed.horizontal, } In this example, the system is extended so that the popular [Vicious](https://github.com/vicious-widgets/vicious) extension module can be used directly in the layout declaration. This example will update the textbox every 3 seconds to show the CPU usage. ### Handling sections The system allows sections to be defined externally, then composed into the final layout declaration. Here is an example re-using one of the above example: Code: local circle = { fit = function(self, context, width, height) return height, height -- A square taking the full height end, draw = function(self, context, cr, width, height) cr:set_source_rgb(1, 0, 0) -- Red cr:arc(height/2, height/2, height/2, 0, math.pi*2) cr:fill() end, layout = wibox.widget.base.make_widget, } -- Define a layout with the imperative syntax local l = wibox.widget.align() -- 3 circle s.mywibox : setup { circle, circle, circle, l, layout = wibox.layout.align.horizontal } -- This can be done instead local three_circle = {layout = wibox.layout.align.horizontal} for i=1, 3 do table.insert(three_circle, circle) end s.mywibox : setup (three_circle) ### Instantiation rules Whenever it can, Awesome tries to be asynchronous. This can take various form depending on the situation. For example, the `connect_signal` method allows to execute code when an event arrives. `awful.screen.connect_for_each_screen` also allows to instantiate various elements when a new screen is added. In the later case, it is why some widgets are added as properties to other objects instead of being global variables like in previous versions of Awesome. However, there is a case where this isn't enough and another abstract widget has to be used. This concept is called the `widget_template` and is an optional property of many widgets such as the `awful.widget.taglist`, `awful.widget.tasklist` and `naughty.layout.box`. These templates are a **table** using the exact same syntax as the declarative widgets, but without the `wibox.widget` prefix in front of the curly braces. These templates represents future widgets that will be created by their parent widget. This is necessary for three reasons: * The widget must create many instances of the template at different points in time. * The widget data is only partially available and other fields must be set at a later time (by the parent widget). * The code is highly redundant and some of the logic is delegated to the parent widget to simplify everything.
awesomeWM/awesome
docs/03-declarative-layout.md
Markdown
gpl-2.0
16,715
<?php function plugin_beforescript_convert() { global $vars; $qm = get_qm(); $page = $vars['page']; if (! (PKWK_READONLY > 0 or is_freeze($page) or plugin_beforescript_is_edit_auth($page))) { return $qm->replace('fmt_err_not_editable', '#html', $page); } $args = func_get_args(); $addscript = array_pop($args); $qt = get_qt(); $qt->appendv('beforescript', $addscript); return ""; } function plugin_beforescript_is_edit_auth($page, $user = '') { global $edit_auth, $edit_auth_pages, $auth_method_type; if (! $edit_auth) { return FALSE; } // Checked by: $target_str = ''; if ($auth_method_type == 'pagename') { $target_str = $page; // Page name } else if ($auth_method_type == 'contents') { $target_str = join('', get_source($page)); // Its contents } foreach($edit_auth_pages as $regexp => $users) { if (preg_match($regexp, $target_str)) { if ($user == '' || in_array($user, explode(',', $users))) { return TRUE; } } } return FALSE; } ?>
open-qhm/qhm
plugin/beforescript.inc.php
PHP
gpl-2.0
990
<?php /************** * @package WordPress * @subpackage Cuckoothemes * @since Cuckoothemes 1.0 * URL http://cuckoothemes.com ************** * * * ** Name : Button shortcodes */ function shortcode_button( $atts, $content = null) { extract(shortcode_atts(array( "title" => 'Button Title', "color" => '#4F4F4F', "titlecolor" => '#ffffff', "width" => '225px', "url" => 'http://www.cuckoothemes.com', "target" => '', "left" => '', "top" => '', "right" => '', "bottom"=> '' ), $atts)); switch(isset($atts["align"]) ? $atts["align"] : ''){ case 'left': $align = 'alignleft'; break; case 'right': $align = 'alignright'; break; default : $align = 'alignnone'; break; } $left = ($left == null ? '' : ' margin-left:'.$left.';'); $right = ($right == null ? '' : ' margin-right:'.$right.';'); $top = ($top == null ? '' : ' margin-top:'.$top.';'); $bottom = ($bottom == null ? '' : ' margin-bottom:'.$bottom.';'); $color = ($color == null ? '' : ' background-color:'.$color.';'); $titlecolor = ( $titlecolor == null ? '' : ' color:'.$titlecolor.'!important;' ); $width = ( $width == null ? '' : ' width:'.$width.';' ); $style = 'style="' .$titlecolor.$color.$left.$right.$top.$bottom.$width. '"'; $target_show = ($target == null ? '' : 'target="'.$target.'"'); return '<a class="btn-short '.$align.'" '.$style.' title="'.$title.'" '.$target_show.' href="'.$url.'">'.wptexturize($title).'</a>'; } add_shortcode('btn', 'shortcode_button'); ?>
rlhardrock/buhos
wp-content/themes/cuckootap/cuckootap/admin/shortcodes/button/button_shortcodes.php
PHP
gpl-2.0
1,544
/* $OpenBSD: printjob.c,v 1.44 2007/09/10 14:29:53 tobias Exp $ */ /* $NetBSD: printjob.c,v 1.31 2002/01/21 14:42:30 wiz Exp $ */ /* * Copyright (c) 1983, 1993 * 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. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1983, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint static const char sccsid[] = "@(#)printjob.c 8.7 (Berkeley) 5/10/95"; #endif /* not lint */ /* * printjob -- print jobs in the queue. * * NOTE: the lock file is used to pass information to lpq and lprm. * it does not need to be removed because file locks are dynamic. */ #include <sys/param.h> #include <sys/wait.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/file.h> #include <pwd.h> #include <unistd.h> #include <signal.h> #include <termios.h> #include <syslog.h> #include <fcntl.h> #include <dirent.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <ctype.h> #include <time.h> #include "lp.h" #include "lp.local.h" #include "pathnames.h" #include "extern.h" #define DORETURN 0 /* absorb fork error */ #define DOABORT 1 /* abort if dofork fails */ /* * Error tokens */ #define REPRINT -2 #define ERROR -1 #define OK 0 #define FATALERR 1 #define NOACCT 2 #define FILTERERR 3 #define ACCESS 4 static dev_t fdev; /* device of file pointed to by symlink */ static ino_t fino; /* inode of file pointed to by symlink */ static FILE *cfp; /* control file */ static pid_t child; /* pid of any filters */ static int lfd; /* lock file descriptor */ static int ofd; /* output filter file descriptor */ static pid_t ofilter; /* pid of output filter, if any */ static int pfd; /* prstatic inter file descriptor */ static pid_t pid; /* pid of lpd process */ static pid_t prchild; /* pid of pr process */ static char title[80]; /* ``pr'' title */ static int tof; /* true if at top of form */ static char class[32]; /* classification field */ static char fromhost[MAXHOSTNAMELEN]; /* user's host machine */ /* indentation size in static characters */ static char indent[10] = "-i0"; static char jobname[NAME_MAX]; /* job or file name */ static char length[10] = "-l"; /* page length in lines */ static char logname[LOGIN_NAME_MAX /*MAXLOGNAME*/]; /* user's login name */ static char pxlength[10] = "-y"; /* page length in pixels */ static char pxwidth[10] = "-x"; /* page width in pixels */ static char tempfile[] = "errsXXXXXXXXXX"; /* file name for filter output */ static char width[10] = "-w"; /* page width in static characters */ static void abortpr(int); static void banner(char *, char *); static pid_t dofork(int); static int dropit(int); static void init(void); static void openpr(void); static void opennet(char *); static void opentty(void); static void openrem(void); static int print(int, char *); static int printit(char *); static void pstatus(const char *, ...) __attribute__((__format__(__printf__, 1, 2))); static char response(void); static void scan_out(int, char *, int); static char *scnline(int, char *, int); static int sendfile(int, char *); static int sendit(char *); static void sendmail(char *, int); static void setty(void); static void alarmer(int); void printjob(void) { struct stat stb; struct queue *q, **qp; struct queue **queue; struct sigaction sa; int i, fd, nitems; off_t pidoff; int errcnt, count = 0; init(); /* set up capabilities */ (void)write(STDOUT_FILENO, "", 1); /* ack that daemon is started */ PRIV_START; fd = open(LF, O_WRONLY|O_APPEND, 0664); /* set up log file */ PRIV_END; if (fd < 0) { syslog(LOG_ERR, "%s: %m", LF); if ((fd = open(_PATH_DEVNULL, O_WRONLY)) < 0) exit(1); } if (fd != STDERR_FILENO) { if (dup2(fd, STDERR_FILENO) < 0) { syslog(LOG_ERR, "dup2: %m"); exit(1); } (void)close(fd); } pid = getpid(); /* for use with lprm */ setpgid(0, pid); /*setpgrp(0, pid);*/ /* we add SIGINT to the mask so abortpr() doesn't kill itself */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = abortpr; sa.sa_flags = SA_RESTART; sigemptyset(&sa.sa_mask); sigaddset(&sa.sa_mask, SIGINT); sigaction(SIGHUP, &sa, NULL); sigaction(SIGINT, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); /* so we can use short form file names */ if (chdir(SD) < 0) { syslog(LOG_ERR, "%s: %m", SD); exit(1); } (void)mktemp(tempfile); /* safe */ lfd = safe_open(LO, O_WRONLY|O_CREAT|O_NOFOLLOW/*|O_EXLOCK*/, 0640); if (lfd < 0 || flock(lfd,LOCK_EX|LOCK_NB)<0) { if (errno == EWOULDBLOCK) /* active daemon present */ exit(0); syslog(LOG_ERR, "%s: %s: %m", printer, LO); exit(1); } if (fstat(lfd, &stb) == 0 && (stb.st_mode & S_IXUSR)) exit(0); /* printing disabled */ ftruncate(lfd, 0); /* * write process id for others to know */ if ((pidoff = i = snprintf(line, sizeof(line), "%d\n", pid)) >= sizeof(line) || pidoff == -1) { syslog(LOG_ERR, "impossibly large pid: %u", pid); exit(1); } if (write(lfd, line, i) != i) { syslog(LOG_ERR, "%s: %s: %m", printer, LO); exit(1); } /* * search the spool directory for work and sort by queue order. */ if ((nitems = getq(&queue)) < 0) { syslog(LOG_ERR, "%s: can't scan %s", printer, SD); exit(1); } if (nitems == 0) /* no work to do */ exit(0); if (stb.st_mode & S_IXOTH) { /* reset queue flag */ stb.st_mode &= ~S_IXOTH; if (fchmod(lfd, stb.st_mode & 0777) < 0) syslog(LOG_ERR, "%s: %s: %m", printer, LO); } PRIV_START; openpr(); /* open printer or remote */ PRIV_END; again: /* * we found something to do now do it -- * write the name of the current control file into the lock file * so the spool queue program can tell what we're working on */ for (qp = queue; nitems--; free(q)) { q = *qp++; if (stat(q->q_name, &stb) < 0) continue; errcnt = 0; restart: (void)lseek(lfd, pidoff, 0); if ((i = snprintf(line, sizeof(line), "%s\n", q->q_name)) >= sizeof(line) || i == -1) i = sizeof(line) - 1; /* can't happen */ if (write(lfd, line, i) != i) syslog(LOG_ERR, "%s: %s: %m", printer, LO); if (!remote) i = printit(q->q_name); else i = sendit(q->q_name); /* * Check to see if we are supposed to stop printing or * if we are to rebuild the queue. */ if (fstat(lfd, &stb) == 0) { /* stop printing before starting next job? */ if (stb.st_mode & S_IXUSR) goto done; /* rebuild queue (after lpc topq) */ if (stb.st_mode & S_IXOTH) { for (free(q); nitems--; free(q)) q = *qp++; stb.st_mode &= ~S_IXOTH; if (fchmod(lfd, stb.st_mode & 0777) < 0) syslog(LOG_WARNING, "%s: %s: %m", printer, LO); break; } } if (i == OK) /* file ok and printed */ count++; else if (i == REPRINT && ++errcnt < 5) { /* try reprinting the job */ syslog(LOG_INFO, "restarting %s", printer); if (ofilter > 0) { kill(ofilter, SIGCONT); /* to be sure */ (void)close(ofd); while ((i = wait(NULL)) > 0 && i != ofilter) ; ofilter = 0; } (void)close(pfd); /* close printer */ if (ftruncate(lfd, pidoff) < 0) syslog(LOG_WARNING, "%s: %s: %m", printer, LO); PRIV_START; openpr(); /* try to reopen printer */ PRIV_END; goto restart; } else { syslog(LOG_WARNING, "%s: job could not be %s (%s)", printer, remote ? "sent to remote host" : "printed", q->q_name); if (i == REPRINT) { /* ensure we don't attempt this job again */ PRIV_START; (void)unlink(q->q_name); q->q_name[0] = 'd'; (void)unlink(q->q_name); PRIV_END; if (logname[0]) sendmail(logname, FATALERR); } } } free(queue); /* * search the spool directory for more work. */ if ((nitems = getq(&queue)) < 0) { syslog(LOG_ERR, "%s: can't scan %s", printer, SD); exit(1); } if (nitems == 0) { /* no more work to do */ done: if (count > 0) { /* Files actually printed */ if (!SF && !tof) (void)write(ofd, FF, strlen(FF)); if (TR != NULL) /* output trailer */ (void)write(ofd, TR, strlen(TR)); } (void)close(ofd); (void)wait(NULL); (void)unlink(tempfile); exit(0); } goto again; } #define FONTLEN 50 char fonts[4][FONTLEN]; /* fonts for troff */ char ifonts[4][40] = { _PATH_VFONTR, _PATH_VFONTI, _PATH_VFONTB, _PATH_VFONTS, }; /* * The remaining part is the reading of the control file (cf) * and performing the various actions. */ static int printit(char *file) { int i, fd; char *cp; int bombed = OK; /* * open control file; ignore if no longer there. */ fd = safe_open(file, O_RDONLY|O_NOFOLLOW, 0); if (fd < 0 || (cfp = fdopen(fd, "r")) == NULL) { syslog(LOG_INFO, "%s: %s: %m", printer, file); if (fd >= 0) (void)close(fd); return(OK); } /* * Reset troff fonts. */ for (i = 0; i < 4; i++) strlcpy(fonts[i], ifonts[i], FONTLEN); (void)snprintf(&width[2], sizeof(width) - 2, "%ld", PW); indent[2] = '0'; indent[3] = '\0'; /* * read the control file for work to do * * file format -- first character in the line is a command * rest of the line is the argument. * valid commands are: * * S -- "stat info" for symbolic link protection * J -- "job name" on banner page * C -- "class name" on banner page * L -- "literal" user's name to print on banner * T -- "title" for pr * H -- "host name" of machine where lpr was done * P -- "person" user's login name * I -- "indent" amount to indent output * R -- laser dpi "resolution" * f -- "file name" name of text file to print * l -- "file name" text file with control chars * p -- "file name" text file to print with pr(1) * t -- "file name" troff(1) file to print * n -- "file name" ditroff(1) file to print * d -- "file name" dvi file to print * g -- "file name" plot(1G) file to print * v -- "file name" plain raster file to print * c -- "file name" cifplot file to print * 1 -- "R font file" for troff * 2 -- "I font file" for troff * 3 -- "B font file" for troff * 4 -- "S font file" for troff * N -- "name" of file (used by lpq) * U -- "unlink" name of file to remove * (after we print it. (Pass 2 only)). * M -- "mail" to user when done printing * * getline reads a line and expands tabs to blanks */ /* pass 1 */ while (getcfline(cfp)) switch (line[0]) { case 'H': strlcpy(fromhost, line+1, sizeof(fromhost)); if (class[0] == '\0') strlcpy(class, line+1, sizeof(class)); continue; case 'P': strlcpy(logname, line+1, sizeof(logname)); if (RS) { /* restricted */ if (getpwnam(logname) == NULL) { bombed = NOACCT; sendmail(line+1, bombed); goto pass2; } } continue; case 'S': cp = line+1; i = 0; while (*cp >= '0' && *cp <= '9') i = i * 10 + (*cp++ - '0'); fdev = i; cp++; i = 0; while (*cp >= '0' && *cp <= '9') i = i * 10 + (*cp++ - '0'); fino = i; continue; case 'J': if (line[1] != '\0') strlcpy(jobname, line+1, sizeof(jobname)); else { jobname[0] = ' '; jobname[1] = '\0'; } continue; case 'C': if (line[1] != '\0') strlcpy(class, line+1, sizeof(class)); else if (class[0] == '\0') gethostname(class, sizeof(class)); continue; case 'T': /* header title for pr */ strlcpy(title, line+1, sizeof(title)); continue; case 'L': /* identification line */ if (!SH && !HL) banner(line+1, jobname); continue; case '1': /* troff fonts */ case '2': case '3': case '4': if (line[1] != '\0') strlcpy(fonts[line[0]-'1'], line+1, FONTLEN); continue; case 'W': /* page width */ strlcpy(width+2, line+1, sizeof(width) - 2); continue; case 'I': /* indent amount */ strlcpy(indent+2, line+1, sizeof(indent) - 2); continue; default: /* some file to print */ switch (i = print(line[0], line+1)) { case ERROR: if (bombed == OK) bombed = FATALERR; break; case REPRINT: (void)fclose(cfp); return(REPRINT); case FILTERERR: case ACCESS: bombed = i; sendmail(logname, bombed); } title[0] = '\0'; continue; case 'N': case 'U': case 'M': case 'R': continue; } /* pass 2 */ pass2: fseek(cfp, 0L, SEEK_SET); while (getcfline(cfp)) switch (line[0]) { case 'L': /* identification line */ if (!SH && HL) banner(line+1, jobname); continue; case 'M': if (bombed < NOACCT) /* already sent if >= NOACCT */ sendmail(line+1, bombed); continue; case 'U': if (strchr(line+1, '/')) continue; (void)unlink(line+1); } /* * clean-up in case another control file exists */ (void)fclose(cfp); (void)unlink(file); return(bombed == OK ? OK : ERROR); } /* * Print a file. * Set up the chain [ PR [ | {IF, OF} ] ] or {IF, RF, TF, NF, DF, CF, VF}. * Return -1 if a non-recoverable error occurred, * 2 if the filter detected some errors (but printed the job anyway), * 1 if we should try to reprint this job and * 0 if all is well. * Note: all filters take stdin as the file, stdout as the printer, * stderr as the log file, and must not ignore SIGINT. */ static int print(int format, char *file) { ssize_t nread; struct stat stb; pid_t pid; char *prog, *av[17], buf[BUFSIZ]; int fd, status, serrno; int n, fi, fo, p[2], stopped = 0, nofile; PRIV_START; if (lstat(file, &stb) < 0 || (fi = safe_open(file, O_RDONLY, 0)) < 0) { PRIV_END; return(ERROR); } PRIV_END; /* * Check to see if data file is a symbolic link. If so, it should * still point to the same file or someone is trying to print * something he shouldn't. */ if (S_ISLNK(stb.st_mode) && fstat(fi, &stb) == 0 && (stb.st_dev != fdev || stb.st_ino != fino)) return(ACCESS); if (!SF && !tof) { /* start on a fresh page */ (void)write(ofd, FF, strlen(FF)); tof = 1; } if (IF == NULL && (format == 'f' || format == 'l' || format == 'o')) { tof = 0; while ((n = read(fi, buf, BUFSIZ)) > 0) if (write(ofd, buf, n) != n) { (void)close(fi); return(REPRINT); } (void)close(fi); return(OK); } switch (format) { case 'p': /* print file using 'pr' */ if (IF == NULL) { /* use output filter */ prog = _PATH_PR; av[0] = "pr"; av[1] = width; av[2] = length; av[3] = "-h"; av[4] = *title ? title : " "; av[5] = "-f"; av[6] = NULL; fo = ofd; goto start; } pipe(p); if ((prchild = dofork(DORETURN)) == 0) { /* child */ dup2(fi, 0); /* file is stdin */ dup2(p[1], 1); /* pipe is stdout */ closelog(); nofile = sysconf(_SC_OPEN_MAX); for (n = 3; n < nofile; n++) (void)close(n); execl(_PATH_PR, "pr", width, length, "-f", "-h", *title ? title : " ", (char *)NULL); syslog(LOG_ERR, "cannot execl %s", _PATH_PR); exit(2); } (void)close(p[1]); /* close output side */ (void)close(fi); if (prchild < 0) { prchild = 0; (void)close(p[0]); return(ERROR); } fi = p[0]; /* use pipe for input */ case 'f': /* print plain text file */ prog = IF; av[1] = width; av[2] = length; av[3] = indent; n = 4; break; case 'o': /* print postscript file */ /* * Treat this as a "plain file with control characters", and * assume the standard LPF_INPUT filter will recognize that * the data is postscript and know what to do with it. These * 'o'-file requests could come from MacOS 10.1 systems. * (later versions of MacOS 10 will explicitly use 'l') * A postscript file can contain binary data, which is why 'l' * is somewhat more appropriate than 'f'. */ /* FALLTHROUGH */ case 'l': /* like 'f' but pass control characters */ prog = IF; av[1] = "-c"; av[2] = width; av[3] = length; av[4] = indent; n = 5; break; case 'r': /* print a fortran text file */ prog = RF; av[1] = width; av[2] = length; n = 3; break; case 't': /* print troff output */ case 'n': /* print ditroff output */ case 'd': /* print tex output */ (void)unlink(".railmag"); if ((fo = open(".railmag", O_CREAT|O_WRONLY|O_EXCL, FILMOD)) < 0) { syslog(LOG_ERR, "%s: cannot create .railmag", printer); (void)unlink(".railmag"); } else { for (n = 0; n < 4; n++) { if (fonts[n][0] != '/') (void)write(fo, _PATH_VFONT, sizeof(_PATH_VFONT) - 1); (void)write(fo, fonts[n], strlen(fonts[n])); (void)write(fo, "\n", 1); } (void)close(fo); } prog = (format == 't') ? TF : (format == 'n') ? NF : DF; av[1] = pxwidth; av[2] = pxlength; n = 3; break; case 'c': /* print cifplot output */ prog = CF; av[1] = pxwidth; av[2] = pxlength; n = 3; break; case 'g': /* print plot(1G) output */ prog = GF; av[1] = pxwidth; av[2] = pxlength; n = 3; break; case 'v': /* print raster output */ prog = VF; av[1] = pxwidth; av[2] = pxlength; n = 3; break; default: (void)close(fi); syslog(LOG_ERR, "%s: illegal format character '%c'", printer, format); return(ERROR); } if (prog == NULL) { (void)close(fi); syslog(LOG_ERR, "%s: no filter found in printcap for format character '%c'", printer, format); return(ERROR); } if ((av[0] = strrchr(prog, '/')) != NULL) av[0]++; else av[0] = prog; av[n++] = "-n"; av[n++] = logname; if (*jobname != '\0' && strcmp(jobname, " ") != 0) { av[n++] = "-j"; av[n++] = jobname; } av[n++] = "-h"; av[n++] = fromhost; av[n++] = AF; av[n] = 0; fo = pfd; if (ofilter > 0) { /* stop output filter */ write(ofd, "\031\1", 2); while ((pid = waitpid((pid_t)-1, &status, WUNTRACED)) > 0 && pid != ofilter) ; if (WIFSTOPPED(status) == 0) { (void)close(fi); syslog(LOG_WARNING, "%s: output filter died (retcode=%d termsig=%d prog=%s)", printer, WEXITSTATUS(status), WTERMSIG(status), prog); return(REPRINT); } stopped++; } start: if ((child = dofork(DORETURN)) == 0) { /* child */ dup2(fi, 0); dup2(fo, 1); unlink(tempfile); n = open(tempfile, O_WRONLY|O_CREAT|O_EXCL, 0664); if (n >= 0) dup2(n, 2); closelog(); nofile = sysconf(_SC_OPEN_MAX); for (n = 3; n < nofile; n++) (void)close(n); execv(prog, av); syslog(LOG_ERR, "cannot execv %s", prog); _exit(2); } serrno = errno; (void)close(fi); errno = serrno; if (child < 0) { child = prchild = tof = 0; syslog(LOG_ERR, "cannot start child process: %m"); return (ERROR); } while ((pid = wait(&status)) > 0 && pid != child) ; child = 0; prchild = 0; if (stopped) { /* restart output filter */ if (kill(ofilter, SIGCONT) < 0) { syslog(LOG_ERR, "cannot restart output filter"); exit(1); } } tof = 0; /* Copy filter output to "lf" logfile */ fd = safe_open(tempfile, O_RDONLY|O_NOFOLLOW, 0); if (fd >= 0) { while ((nread = read(fd, buf, sizeof(buf))) > 0) (void)write(STDERR_FILENO, buf, nread); (void)close(fd); } if (!WIFEXITED(status)) { syslog(LOG_WARNING, "%s: filter '%c' terminated (termsig=%d prog=%s)", printer, format, WTERMSIG(status), prog); return(ERROR); } switch (WEXITSTATUS(status)) { case 0: tof = 1; return(OK); case 1: return(REPRINT); case 2: return(ERROR); default: syslog(LOG_WARNING, "%s: filter '%c' exited (retcode=%d prog=%s)", printer, format, WEXITSTATUS(status), prog); return(FILTERERR); } } /* * Send the daemon control file (cf) and any data files. * Return -1 if a non-recoverable error occurred, 1 if a recoverable error and * 0 if all is well. */ static int sendit(char *file) { int fd, i, err = OK; char *cp, last[BUFSIZ]; /* open control file */ fd = safe_open(file, O_RDONLY|O_NOFOLLOW, 0); if (fd < 0 || (cfp = fdopen(fd, "r")) == NULL) return(OK); /* * read the control file for work to do * * file format -- first character in the line is a command * rest of the line is the argument. * commands of interest are: * * a-z -- "file name" name of file to print * U -- "unlink" name of file to remove * (after we print it. (Pass 2 only)). */ /* * pass 1 */ while (getcfline(cfp)) { again: if (line[0] == 'S') { cp = line+1; i = 0; while (*cp >= '0' && *cp <= '9') i = i * 10 + (*cp++ - '0'); fdev = i; cp++; i = 0; while (*cp >= '0' && *cp <= '9') i = i * 10 + (*cp++ - '0'); fino = i; continue; } if (line[0] >= 'a' && line[0] <= 'z') { strlcpy(last, line, sizeof(last)); while ((i = getcfline(cfp)) != 0) if (strcmp(last, line)) break; switch (sendfile('\3', last+1)) { case OK: if (i) goto again; break; case REPRINT: (void)fclose(cfp); return(REPRINT); case ACCESS: sendmail(logname, ACCESS); case ERROR: err = ERROR; } break; } } if (err == OK && sendfile('\2', file) > 0) { (void)fclose(cfp); return(REPRINT); } /* * pass 2 */ fseek(cfp, 0L, SEEK_SET); while (getcfline(cfp)) if (line[0] == 'U' && strchr(line+1, '/') == 0) (void)unlink(line+1); /* * clean-up in case another control file exists */ (void)fclose(cfp); (void)unlink(file); return(err); } /* * Send a data file to the remote machine and spool it. * Return positive if we should try resending. */ static int sendfile(int type, char *file) { int f, i, amt; struct stat stb; char buf[BUFSIZ]; int sizerr, resp; PRIV_START; if (lstat(file, &stb) < 0 || (f = safe_open(file, O_RDONLY, 0)) < 0) { PRIV_END; return(ERROR); } PRIV_END; /* * Check to see if data file is a symbolic link. If so, it should * still point to the same file or someone is trying to print something * he shouldn't. */ if (S_ISLNK(stb.st_mode) && fstat(f, &stb) == 0 && (stb.st_dev != fdev || stb.st_ino != fino)) return(ACCESS); if ((amt = snprintf(buf, sizeof(buf), "%c%lld %s\n", type, (long long)stb.st_size, file)) >= sizeof(buf) || amt == -1) return (ACCESS); /* XXX hack */ for (i = 0; ; i++) { if (write(pfd, buf, amt) != amt || (resp = response()) < 0 || resp == '\1') { (void)close(f); return(REPRINT); } else if (resp == '\0') break; if (i == 0) pstatus("no space on remote; waiting for queue to drain"); if (i == 10) syslog(LOG_ALERT, "%s: can't send to %s; queue full", printer, RM); sleep(5 * 60); } if (i) pstatus("sending to %s", RM); sizerr = 0; for (i = 0; i < stb.st_size; i += BUFSIZ) { struct sigaction osa, nsa; amt = BUFSIZ; if (i + amt > stb.st_size) amt = stb.st_size - i; if (sizerr == 0 && read(f, buf, amt) != amt) sizerr = 1; memset(&nsa, 0, sizeof(nsa)); nsa.sa_handler = alarmer; sigemptyset(&nsa.sa_mask); nsa.sa_flags = 0; (void)sigaction(SIGALRM, &nsa, &osa); alarm(wait_time); if (write(pfd, buf, amt) != amt) { alarm(0); (void)sigaction(SIGALRM, &osa, NULL); (void)close(f); return(REPRINT); } alarm(0); (void)sigaction(SIGALRM, &osa, NULL); } (void)close(f); if (sizerr) { syslog(LOG_INFO, "%s: %s: changed size", printer, file); /* tell recvjob to ignore this file */ (void)write(pfd, "\1", 1); return(ERROR); } if (write(pfd, "", 1) != 1 || response()) return(REPRINT); return(OK); } /* * Check to make sure there have been no errors and that both programs * are in sync with eachother. * Return non-zero if the connection was lost. */ static char response(void) { struct sigaction osa, nsa; char resp; memset(&nsa, 0, sizeof(nsa)); nsa.sa_handler = alarmer; sigemptyset(&nsa.sa_mask); nsa.sa_flags = 0; (void)sigaction(SIGALRM, &nsa, &osa); alarm(wait_time); if (read(pfd, &resp, 1) != 1) { syslog(LOG_INFO, "%s: lost connection", printer); resp = -1; } alarm(0); (void)sigaction(SIGALRM, &osa, NULL); return (resp); } /* * Banner printing stuff */ static void banner(char *name1, char *name2) { time_t tvec; time(&tvec); if (!SF && !tof) (void)write(ofd, FF, strlen(FF)); if (SB) { /* short banner only */ if (class[0]) { (void)write(ofd, class, strlen(class)); (void)write(ofd, ":", 1); } (void)write(ofd, name1, strlen(name1)); (void)write(ofd, " Job: ", 7); (void)write(ofd, name2, strlen(name2)); (void)write(ofd, " Date: ", 8); (void)write(ofd, ctime(&tvec), 24); (void)write(ofd, "\n\r", 2); } else { /* normal banner */ (void)write(ofd, "\n\r\n\r\n\r", 6); scan_out(ofd, name1, '\0'); (void)write(ofd, "\n\r\n\r", 4); scan_out(ofd, name2, '\0'); if (class[0]) { (void)write(ofd, "\n\r\n\r\n\r", 6); scan_out(ofd, class, '\0'); } (void)write(ofd, "\n\r\n\r\n\r\n\r\t\t\t\t\tJob: ", 19); (void)write(ofd, name2, strlen(name2)); (void)write(ofd, "\n\r\t\t\t\t\tDate: ", 13); (void)write(ofd, ctime(&tvec), 24); (void)write(ofd, "\n\r", 2); } if (!SF) (void)write(ofd, FF, strlen(FF)); tof = 1; } static char * scnline(int key, char *p, int c) { int scnwidth; for (scnwidth = WIDTH; --scnwidth;) { key <<= 1; *p++ = key & 0200 ? c : BACKGND; } return (p); } #define TRC(q) (((q)-' ')&0177) static void scan_out(int scfd, char *scsp, int dlm) { char *strp; int nchrs, j; char outbuf[LINELEN+2], *sp, c, cc; int d, scnhgt; extern char scnkey[][HEIGHT]; /* in lpdchar.c */ for (scnhgt = 0; scnhgt++ < HEIGHT+DROP; ) { strp = &outbuf[0]; sp = scsp; for (nchrs = 0; ; ) { d = dropit(c = TRC(cc = *sp++)); if ((!d && scnhgt > HEIGHT) || (scnhgt <= DROP && d)) for (j = WIDTH; --j;) *strp++ = BACKGND; else strp = scnline(scnkey[(int)c][scnhgt-1-d], strp, cc); if (*sp == dlm || *sp == '\0' || nchrs++ >= PW/(WIDTH+1)-1) break; *strp++ = BACKGND; *strp++ = BACKGND; } while (*--strp == BACKGND && strp >= outbuf) ; strp++; *strp++ = '\n'; *strp++ = '\r'; (void)write(scfd, outbuf, strp-outbuf); } } static int dropit(int c) { switch(c) { case TRC('_'): case TRC(';'): case TRC(','): case TRC('g'): case TRC('j'): case TRC('p'): case TRC('q'): case TRC('y'): return (DROP); default: return (0); } } /* * sendmail --- * tell people about job completion */ static void sendmail(char *user, int bombed) { int i, p[2], s, nofile; char *cp = NULL; struct stat stb; FILE *fp; if (user[0] == '-' || user[0] == '/' || !isprint(user[0])) return; pipe(p); if ((s = dofork(DORETURN)) == 0) { /* child */ dup2(p[0], 0); closelog(); nofile = sysconf(_SC_OPEN_MAX); for (i = 3; i < nofile; i++) (void)close(i); if ((cp = strrchr(_PATH_SENDMAIL, '/')) != NULL) cp++; else cp = _PATH_SENDMAIL; execl(_PATH_SENDMAIL, cp, "-t", (char *)NULL); _exit(0); } else if (s > 0) { /* parent */ dup2(p[1], 1); printf("Auto-Submitted: auto-generated\n"); printf("To: %s@%s\n", user, fromhost); printf("Subject: %s printer job \"%s\"\n", printer, *jobname ? jobname : "<unknown>"); printf("Reply-To: root@%s\n\n", host); printf("Your printer job "); if (*jobname) printf("(%s) ", jobname); switch (bombed) { case OK: printf("\ncompleted successfully\n"); cp = "OK"; break; default: case FATALERR: printf("\ncould not be printed\n"); cp = "FATALERR"; break; case NOACCT: printf("\ncould not be printed without an account on %s\n", host); cp = "NOACCT"; break; case FILTERERR: if (stat(tempfile, &stb) < 0 || stb.st_size == 0 || (fp = fopen(tempfile, "r")) == NULL) { printf("\nhad some errors and may not have printed\n"); break; } printf("\nhad the following errors and may not have printed:\n"); while ((i = getc(fp)) != EOF) putchar(i); (void)fclose(fp); cp = "FILTERERR"; break; case ACCESS: printf("\nwas not printed because it was not linked to the original file\n"); cp = "ACCESS"; } fflush(stdout); (void)close(1); } else { syslog(LOG_ERR, "fork for sendmail failed: %m"); } (void)close(p[0]); (void)close(p[1]); if (s != -1) { wait(NULL); syslog(LOG_INFO, "mail sent to user %s about job %s on printer %s (%s)", user, *jobname ? jobname : "<unknown>", printer, cp); } } /* * dofork - fork with retries on failure */ static pid_t dofork(int action) { struct passwd *pw; pid_t pid; int i; for (i = 0; i < 20; i++) { if ((pid = fork()) < 0) { sleep((unsigned)(i*i)); continue; } /* * Child should run as daemon instead of root */ if (pid == 0) { (void)close(lfd); PRIV_START; pw = getpwuid(DU); if (pw == 0) { syslog(LOG_ERR, "uid %ld not in password file", DU); break; } initgroups(pw->pw_name, pw->pw_gid); setgid(pw->pw_gid); setuid(DU); } return (pid); } syslog(LOG_ERR, "can't fork"); switch (action) { case DORETURN: return (-1); default: syslog(LOG_ERR, "bad action (%d) to dofork", action); /*FALL THRU*/ case DOABORT: exit(1); } /*NOTREACHED*/ } /* * Kill child processes to abort current job. */ static void abortpr(int signo) { (void)close(lfd); (void)unlink(tempfile); (void)kill(0, SIGINT); if (ofilter > 0) kill(ofilter, SIGCONT); while (wait(NULL) > 0) ; _exit(0); } static void init(void) { int status; char *s; PRIV_START; status = cgetent(&bp, printcapdb, printer); PRIV_END; switch (status) { case -1: syslog(LOG_ERR, "unknown printer: %s", printer); exit(1); case -2: syslog(LOG_ERR, "can't open printer description file"); exit(1); case -3: fatal("potential reference loop detected in printcap file"); default: break; } if (cgetstr(bp, DEFLP, &LP) == -1) LP = _PATH_DEFDEVLP; if (cgetstr(bp, "rp", &RP) == -1) RP = DEFLP; if (cgetstr(bp, "lo", &LO) == -1) LO = DEFLOCK; if (cgetstr(bp, "st", &ST) == -1) ST = DEFSTAT; if (cgetstr(bp, "lf", &LF) == -1) LF = _PATH_CONSOLE; if (cgetstr(bp, "sd", &SD) == -1) SD = _PATH_DEFSPOOL; if (cgetnum(bp, "du", &DU) < 0) DU = DEFNUID; if (cgetstr(bp, "ff", &FF) == -1) FF = DEFFF; if (cgetnum(bp, "pw", &PW) < 0) PW = DEFWIDTH; (void)snprintf(&width[2], sizeof(width) - 2, "%ld", PW); if (cgetnum(bp, "pl", &PL) < 0) PL = DEFLENGTH; (void)snprintf(&length[2], sizeof(length) - 2, "%ld", PL); if (cgetnum(bp, "px", &PX) < 0) PX = 0; (void)snprintf(&pxwidth[2], sizeof(pxwidth) - 2, "%ld", PX); if (cgetnum(bp, "py", &PY) < 0) PY = 0; (void)snprintf(&pxlength[2], sizeof(pxlength) - 2, "%ld", PY); cgetstr(bp, "rm", &RM); if ((s = checkremote()) != NULL) syslog(LOG_WARNING, "%s", s); cgetstr(bp, "af", &AF); cgetstr(bp, "of", &OF); cgetstr(bp, "if", &IF); cgetstr(bp, "rf", &RF); cgetstr(bp, "tf", &TF); cgetstr(bp, "nf", &NF); cgetstr(bp, "df", &DF); cgetstr(bp, "gf", &GF); cgetstr(bp, "vf", &VF); cgetstr(bp, "cf", &CF); cgetstr(bp, "tr", &TR); RS = (cgetcap(bp, "rs", ':') != NULL); SF = (cgetcap(bp, "sf", ':') != NULL); SH = (cgetcap(bp, "sh", ':') != NULL); SB = (cgetcap(bp, "sb", ':') != NULL); HL = (cgetcap(bp, "hl", ':') != NULL); RW = (cgetcap(bp, "rw", ':') != NULL); cgetnum(bp, "br", &BR); if (cgetnum(bp, "fc", &FC) < 0) FC = 0; if (cgetnum(bp, "fs", &FS) < 0) FS = 0; if (cgetnum(bp, "xc", &XC) < 0) XC = 0; if (cgetnum(bp, "xs", &XS) < 0) XS = 0; cgetstr(bp, "ms", &MS); tof = (cgetcap(bp, "fo", ':') == NULL); } /* * Acquire line printer or remote connection. * XXX - should push down privs in here */ static void openpr(void) { int i, nofile; char *cp; extern int rflag; if (!remote && *LP) { if ((cp = strchr(LP, '@'))) opennet(cp); else opentty(); } else if (remote) { openrem(); } else { syslog(LOG_ERR, "%s: no line printer device or host name", printer); exit(1); } /* * Start up an output filter, if needed. */ if ((!remote || rflag) && OF) { int p[2]; pipe(p); if ((ofilter = dofork(DOABORT)) == 0) { /* child */ dup2(p[0], 0); /* pipe is std in */ dup2(pfd, 1); /* printer is std out */ closelog(); nofile = sysconf(_SC_OPEN_MAX); for (i = 3; i < nofile; i++) (void)close(i); if ((cp = strrchr(OF, '/')) == NULL) cp = OF; else cp++; execl(OF, cp, width, length, (char *)NULL); syslog(LOG_ERR, "%s: %s: %m", printer, OF); exit(1); } (void)close(p[0]); /* close input side */ ofd = p[1]; /* use pipe for output */ } else { ofd = pfd; ofilter = 0; } } /* * Printer connected directly to the network * or to a terminal server on the net */ static void opennet(char *cp) { int i; int resp, port; char save_ch; save_ch = *cp; *cp = '\0'; port = atoi(LP); if (port <= 0) { syslog(LOG_ERR, "%s: bad port number: %s", printer, LP); exit(1); } *cp++ = save_ch; for (i = 1; ; i = i < 256 ? i << 1 : i) { resp = -1; pfd = getport(cp, port); if (pfd < 0 && errno == ECONNREFUSED) resp = 1; else if (pfd >= 0) { /* * need to delay a bit for rs232 lines * to stabilize in case printer is * connected via a terminal server */ delay(500); break; } if (i == 1) { if (resp < 0) pstatus("waiting for %s to come up", LP); else pstatus("waiting for access to printer on %s", LP); } sleep(i); } pstatus("sending to %s port %d", cp, port); } /* * Printer is connected to an RS232 port on this host */ static void opentty(void) { int i; for (i = 1; ; i = i < 32 ? i << 1 : i) { pfd = open(LP, RW ? O_RDWR : O_WRONLY); if (pfd >= 0) { delay(500); break; } if (errno == ENOENT) { syslog(LOG_ERR, "%s: %m", LP); exit(1); } if (i == 1) pstatus("waiting for %s to become ready (offline ?)", printer); sleep(i); } if (isatty(pfd)) setty(); pstatus("%s is ready and printing", printer); } /* * Printer is on a remote host */ static void openrem(void) { int i, n; int resp; for (i = 1; ; i = i < 256 ? i << 1 : i) { resp = -1; pfd = getport(RM, 0); if (pfd >= 0) { if ((n = snprintf(line, sizeof(line), "\2%s\n", RP)) >= sizeof(line) || n == -1) n = sizeof(line) - 1; if (write(pfd, line, n) == n && (resp = response()) == '\0') break; (void)close(pfd); } if (i == 1) { if (resp < 0) pstatus("waiting for %s to come up", RM); else { pstatus("waiting for queue to be enabled on %s", RM); i = 256; } } sleep(i); } pstatus("sending to %s", RM); } static void alarmer(int s) { /* nothing */ } #if !defined(__NetBSD__) && !defined(__OpenBSD__) struct bauds { int baud; int speed; } bauds[] = { {50, B50}, {75, B75}, {110, B110}, {134, B134}, {150, B150}, {200, B200}, {300, B300}, {600, B600}, {1200, B1200}, {1800, B1800}, {2400, B2400}, {4800, B4800}, {9600, B9600}, {19200, B19200}, {38400, B38400}, {57600, B57600}, {115200, B115200}, {0, 0} }; #endif /* * setup tty lines. */ static void setty(void) { struct info i; char **argv, **ap, **ep, *p, *val; i.fd = pfd; i.set = i.wset = 0; if (ioctl(i.fd, TIOCEXCL, (char *)0) < 0) { syslog(LOG_ERR, "%s: ioctl(TIOCEXCL): %m", printer); exit(1); } if (tcgetattr(i.fd, &i.t) < 0) { syslog(LOG_ERR, "%s: tcgetattr: %m", printer); exit(1); } if (BR > 0) { #if defined(__NetBSD__) || defined(__OpenBSD__) cfsetspeed(&i.t, BR); #else struct bauds *bp; for (bp = bauds; bp->baud; bp++) if (BR == bp->baud) break; if (!bp->baud) { syslog(LOG_ERR, "%s: illegal baud rate %d", printer, (int)BR); exit(1); } cfsetspeed(&i.t, bp->speed); #endif i.set = 1; } if (MS) { if (ioctl(i.fd, TIOCGETD, &i.ldisc) < 0) { syslog(LOG_ERR, "%s: ioctl(TIOCGETD): %m", printer); exit(1); } if (ioctl(i.fd, TIOCGWINSZ, &i.win) < 0) syslog(LOG_INFO, "%s: ioctl(TIOCGWINSZ): %m", printer); argv = (char **)calloc(256, sizeof(char *)); if (argv == NULL) { syslog(LOG_ERR, "%s: malloc: %m", printer); exit(1); } p = strdup(MS); ap = argv; ep = argv + 255; while ((val = strsep(&p, " \t,")) != NULL) { if ((*ap++ = strdup(val)) == NULL) { syslog(LOG_ERR, "%s: strdup: %m", printer); exit(1); } if (ap == ep) { syslog(LOG_ERR, "%s: too many \"ms\" entries", printer); exit(1); } } *ap = NULL; for (; *argv; ++argv) { if (ksearch(&argv, &i)) continue; if (msearch(&argv, &i)) continue; syslog(LOG_INFO, "%s: unknown stty flag: %s", printer, *argv); } } else { if (FC) { i.t.c_cflag &= ~FC; i.set = 1; } if (FS) { i.t.c_cflag |= FS; i.set = 1; } if (XC) { i.t.c_lflag &= ~XC; i.set = 1; } if (XS) { i.t.c_lflag |= XS; i.set = 1; } } if (i.set && tcsetattr(i.fd, TCSANOW, &i.t) < 0) { syslog(LOG_ERR, "%s: tcsetattr: %m", printer); exit(1); } if (i.wset && ioctl(i.fd, TIOCSWINSZ, &i.win) < 0) syslog(LOG_INFO, "%s: ioctl(TIOCSWINSZ): %m", printer); return; } static void pstatus(const char *msg, ...) { int fd, len; char buf[BUFSIZ]; va_list ap; va_start(ap, msg); umask(0); fd = open(ST, O_WRONLY|O_CREAT|O_NOFOLLOW /*|O_EXLOCK*/, 0660); if (fd < 0 || flock(fd,LOCK_EX|LOCK_NB)<0) { syslog(LOG_ERR, "%s: %s: %m", printer, ST); exit(1); } ftruncate(fd, 0); len = vsnprintf(buf, sizeof(buf), msg, ap); va_end(ap); if (len < 0) /* Output error */ return; if (len >= sizeof(buf)) len = sizeof(buf) - 1; buf[len++] = '\n'; /* replace NUL with newline */ (void)write(fd, buf, len); (void)close(fd); }
gestiweb/eneboo
src/posprinter/lpr/lpd/printjob.c
C
gpl-2.0
38,923
jQuery('.js_mobile_menu').click(function(){ jQuery('body').toggleClass('mobile_menu_opened'); });
saintcode/cenotexplore
src/wordpress/wp-content/themes/cenotexplore/js/main.js
JavaScript
gpl-2.0
101
package org.itomi.kakuro.model; import java.util.Observable; import org.itomi.kakuro.integer.Tuple; import org.itomi.kakuro.model.grid.Density; import org.itomi.kakuro.model.grid.Grid; import org.itomi.kakuro.model.grid.ImmutableSubMatrix; public class KakuroInstance extends Observable { private int horizontal; private int vertical; private Grid grid; public KakuroInstance(int x, int y) { this.horizontal = x; this.vertical = y; grid = new Grid().initialize(x, y); } public Grid getGrid() { return grid; } public int getHorizontalLength() { return horizontal; } public int getVerticalLength() { return vertical; } public void notifyObservers() { notifyObservers(this); } public Density getDensity() { return grid.getFillProportion(); } public ImmutableSubMatrix getNeighbours(Tuple<Integer, Integer> position) { return grid.getNeighbours(position); } }
itomi/kakuro
CommonFiles/src/org/itomi/kakuro/model/KakuroInstance.java
Java
gpl-2.0
955
import Vue from 'vue' import App from './App.vue' import vuetify from './plugins/vuetify'; import store from './plugins/store' import router from './plugins/router' import '@mdi/font/css/materialdesignicons.css' import './style.scss' Vue.config.productionTip = false new Vue({ vuetify, store, router, render: h => h(App) }).$mount('#app')
kevashcraft/EagleLogger
app/src/main.js
JavaScript
gpl-2.0
350
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en"> <head> <meta name="generator" content="AWStats 6.95 (build 1.943) from config file awstats.ckbran.ru.conf (http://awstats.sourceforge.net)"> <meta name="robots" content="noindex,nofollow"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="description" content="Awstats - Advanced Web Statistics for ckbran.ru (2014-03) - allemails"> <title>Statistics for ckbran.ru (2014-03) - allemails</title> <style type="text/css"> <!-- body { font: 11px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; margin-top: 0; margin-bottom: 0; } .aws_bodyl { } .aws_border { border-collapse: collapse; background-color: #CCCCDD; padding: 1px 1px 1px 1px; margin-top: 0px; margin-bottom: 0px; } .aws_title { font: 13px verdana, arial, helvetica, sans-serif; font-weight: bold; background-color: #CCCCDD; text-align: center; margin-top: 0; margin-bottom: 0; padding: 1px 1px 1px 1px; color: #000000; } .aws_blank { font: 13px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; text-align: center; margin-bottom: 0; padding: 1px 1px 1px 1px; } .aws_data { background-color: #FFFFFF; border-top-width: 1px; border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; } .aws_formfield { font: 13px verdana, arial, helvetica; } .aws_button { font-family: arial,verdana,helvetica, sans-serif; font-size: 12px; border: 1px solid #ccd7e0; background-image : url(/awstatsicons/other/button.gif); } th { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } th.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font-size: 13px; font-weight: bold; } td { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } td.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px;} td.awsm { border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px; } b { font-weight: bold; } a { font: 11px verdana, arial, helvetica, sans-serif; } a:link { color: #0011BB; text-decoration: none; } a:visited { color: #0011BB; text-decoration: none; } a:hover { color: #605040; text-decoration: underline; } .currentday { font-weight: bold; } //--> </style> </head> <body style="margin-top: 0px"> <a name="top"></a> <a name="menu">&nbsp;</a> <form name="FormDateFilter" action="/cgi-bin/awstats.pl?config=ckbran.ru&amp;output=allemails" style="padding: 0px 0px 0px 0px; margin-top: 0"> <table class="aws_border" border="0" cellpadding="2" cellspacing="0" width="100%"> <tr><td> <table class="aws_data sortable" border="0" cellpadding="1" cellspacing="0" width="100%"> <tr><td class="aws" valign="middle"><b>Statistics for:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 14px;">ckbran.ru</span></td><td align="right" rowspan="3"><a href="http://awstats.sourceforge.net" target="awstatshome"><img src="/awstatsicons/other/awstats_logo6.png" border="0" alt='Awstats Web Site' title='Awstats Web Site' /></a></td></tr> <tr valign="middle"><td class="aws" valign="middle" width="150"><b>Last Update:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 12px;">30 Apr 2014 - 00:01</span></td></tr> <tr><td class="aws" valign="middle"><b>Reported period:</b></td><td class="aws" valign="middle"><span style="font-size: 14px;">Month Mar 2014</span></td></tr> </table> </td></tr></table> </form> <table> <tr><td class="aws"><a href="javascript:parent.window.close();">Close window</a></td></tr> </table> <a name="emailsenders">&nbsp;</a><br /> <table class="aws_border sortable" border="0" cellpadding="2" cellspacing="0" width="100%"> <tr><td class="aws_title" width="70%">Sender EMail </td><td class="aws_blank">&nbsp;</td></tr> <tr><td colspan="2"> <table class="aws_data" border="1" cellpadding="2" cellspacing="0" width="100%"> <tr bgcolor="#ECECEC"><th colspan="3">Sender EMail : 0</th></tr> <tr bgcolor="#ECECEC"><th width="30%">Local</th><th>&nbsp;</th><th width="30%">External</th></tr><tr><td colspan="3"><span style="color: #666688">Others</span></td></tr> </table></td></tr></table><br /> <br /><br /> <span dir="ltr" style="font: 11px verdana, arial, helvetica; color: #000000;"><b>Advanced Web Statistics 6.95 (build 1.943)</b> - <a href="http://awstats.sourceforge.net" target="awstatshome">Created by awstats</a></span><br /> <br /> </body> </html>
AxelFG/ckbran-inf
old/webstat/awstats.ckbran.ru.allemails.032014.html
HTML
gpl-2.0
5,074
<?php namespace Intraxia\Gistpen\View; use Intraxia\Gistpen\Contract\Templating; use Intraxia\Gistpen\Params\Repository as Params; use Intraxia\Jaxion\Contract\Core\HasActions; use Intraxia\Jaxion\Contract\Core\HasFilters; /** * This class registers all of the settings page views * * @package WP_Gistpen * @author James DiGioia <jamesorodig@gmail.com> * @link http://jamesdigioia.com/wp-gistpen/ * @since 0.5.0 */ class Settings implements HasActions, HasFilters { /** * Params service. * * @var Params */ private $params; /** * Templating service. * * @var Templating */ protected $template; /** * Plugin basename. * * @var string */ protected $basename; /** * Site URL. * * @var string */ protected $url; /** * Initialize the class and set its properties. * * @param Params $params * @param Templating $template * @param string $basename * @param string $url * * @internal param Site $site * @internal param EntityManager $em * @since 0.5.0 */ public function __construct( Params $params, Templating $template, $basename, $url ) { $this->params = $params; $this->template = $template; $this->basename = $basename; $this->url = $url; } /** * Register the administration menu for this plugin into the WordPress Dashboard menu. * * @since 0.1.0 */ public function add_plugin_admin_menu() { add_options_page( __( 'WP-Gistpen Settings', 'wp-gistpen' ), __( 'Gistpens', 'wp-gistpen' ), 'edit_posts', 'wp-gistpen', array( $this, 'display_plugin_admin_page' ) ); } /** * Render the settings page for this plugin. * * @since 0.1.0 */ public function display_plugin_admin_page() { echo '<div id="settings-app"></div>'; } /** * Add settings action link to the plugins page. * * @since 0.1.0 * * @param array $links * * @return array */ public function add_action_links( $links ) { return array_merge( array( 'settings' => '<a href="' . admin_url( 'options-general.php?page=wp-gistpen' ) . '">' . __( 'Settings', 'wp-gistpen' ) . '</a>', ), $links ); } /** * Register the settings page (obviously) * * @since 0.3.0 */ public function register_setting() { register_setting( 'wp-gistpen', 'wp-gistpen' ); } /** * {@inheritDoc} * * @return array[] */ public function action_hooks() { return array( array( 'hook' => 'admin_menu', 'method' => 'add_plugin_admin_menu', ), array( 'hook' => 'admin_init', 'method' => 'register_setting', ), ); } /** * {@inheritDoc} * * @return array[] */ public function filter_hooks() { return array( array( 'hook' => 'plugin_action_links_' . $this->basename, 'method' => 'add_action_links', ), ); } }
mAAdhaTTah/WP-Gistpen
app/View/Settings.php
PHP
gpl-2.0
2,831
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.client.hook; /** * Factory for {@link VirtualDataWindow}. * <p> * Register an implementation of this interface with the engine before use: * configuration.addPlugInVirtualDataWindow("test", "vdw", SupportVirtualDWFactory.class.getName()); */ public interface VirtualDataWindowFactory { /** * Return a virtual data window to handle the specific event type, named window or paramaters * as provided in the context. * @param context provides contextual information such as event type, named window name and parameters. * @return virtual data window */ public VirtualDataWindow create(VirtualDataWindowContext context); }
intelie/esper
esper/src/main/java/com/espertech/esper/client/hook/VirtualDataWindowFactory.java
Java
gpl-2.0
1,433
/* * Copyright (C) 2010 Red Hat, Inc. All rights reserved. * * This file is part of LVM2. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License v.2.1. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef _LVM_PROPERTIES_H #define _LVM_PROPERTIES_H #include "libdevmapper.h" #include "lvm-types.h" #include "metadata.h" #include "report.h" struct lvm_property_type { report_type_t type; const char *id; unsigned is_settable:1; unsigned is_string:1; union { char *string; uint64_t integer; } value; int (*get) (const void *obj, struct lvm_property_type *prop); int (*set) (void *obj, struct lvm_property_type *prop); }; int lv_get_property(const struct logical_volume *lv, struct lvm_property_type *prop); int vg_get_property(const struct volume_group *vg, struct lvm_property_type *prop); int pv_get_property(const struct physical_volume *pv, struct lvm_property_type *prop); #endif
SteamMOD/android_bootable_steam_device-mapper
lib/report/properties.h
C
gpl-2.0
1,235
package de.hsbremen.kss.genetic.selection; import java.util.List; import org.apache.commons.lang3.Validate; import de.hsbremen.kss.model.Plan; import de.hsbremen.kss.util.RandomUtils; public class OnlyTheBestSelection implements Selection { private final RandomUtils randomUtils; private final double best; public OnlyTheBestSelection(final RandomUtils randomUtils, final double best) { Validate.inclusiveBetween(0, 1, best); this.randomUtils = randomUtils; this.best = best; } @Override public Plan select(final List<Plan> sortedPopulation) { final int num = (int) (sortedPopulation.size() * this.best); return this.randomUtils.randomElement(sortedPopulation.subList(0, num)); } }
hvoss/logistik
src/main/java/de/hsbremen/kss/genetic/selection/OnlyTheBestSelection.java
Java
gpl-2.0
760
<?php App::uses('Planet', 'Model'); /** * Planet Test Case * */ class PlanetTest extends CakeTestCase { /** * Fixtures * * @var array */ public $fixtures = array( 'app.planet' ); /** * setUp method * * @return void */ public function setUp() { parent::setUp(); $this->Planet = ClassRegistry::init('Planet'); } /** * tearDown method * * @return void */ public function tearDown() { unset($this->Planet); parent::tearDown(); } }
tommykrueger/ExoPlanetSystems
backend/app/Test/Case/Model/PlanetTest.php
PHP
gpl-2.0
464
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Paypal\Test\Unit\Model\Payflow; use Magento\Paypal\Model\Config; use Magento\Paypal\Model\Info; use Magento\Paypal\Model\Payflow\AvsEmsCodeMapper; use Magento\Sales\Api\Data\OrderPaymentInterface; use PHPUnit_Framework_MockObject_MockObject as MockObject; class AvsEmsCodeMapperTest extends \PHPUnit\Framework\TestCase { /** * @var AvsEmsCodeMapper */ private $mapper; /** * @inheritdoc */ protected function setUp() { $this->mapper = new AvsEmsCodeMapper(); } /** * Checks different variations for AVS codes mapping. * * @covers \Magento\Paypal\Model\Payflow\AvsEmsCodeMapper::getCode * @param string $avsZip * @param string $avsStreet * @param string $expected * @dataProvider getCodeDataProvider */ public function testGetCode($avsZip, $avsStreet, $expected) { /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() ->getMock(); $orderPayment->expects(self::once()) ->method('getMethod') ->willReturn(Config::METHOD_PAYFLOWPRO); $orderPayment->expects(self::once()) ->method('getAdditionalInformation') ->willReturn([ Info::PAYPAL_AVSZIP => $avsZip, Info::PAYPAL_AVSADDR => $avsStreet ]); self::assertEquals($expected, $this->mapper->getCode($orderPayment)); } /** * Checks a test case, when payment order is not Payflow payment method. * * @covers \Magento\Paypal\Model\Payflow\AvsEmsCodeMapper::getCode * @expectedException \InvalidArgumentException * @expectedExceptionMessage The "some_payment" does not supported by Payflow AVS mapper. */ public function testGetCodeWithException() { /** @var OrderPaymentInterface|MockObject $orderPayment */ $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) ->disableOriginalConstructor() ->getMock(); $orderPayment->expects(self::exactly(2)) ->method('getMethod') ->willReturn('some_payment'); $this->mapper->getCode($orderPayment); } /** * Gets list of AVS codes. * * @return array */ public function getCodeDataProvider() { return [ ['avsZip' => null, 'avsStreet' => null, 'expected' => ''], ['avsZip' => null, 'avsStreet' => 'Y', 'expected' => ''], ['avsZip' => 'Y', 'avsStreet' => null, 'expected' => ''], ['avsZip' => 'Y', 'avsStreet' => 'Y', 'expected' => 'Y'], ['avsZip' => 'N', 'avsStreet' => 'Y', 'expected' => 'A'], ['avsZip' => 'Y', 'avsStreet' => 'N', 'expected' => 'Z'], ['avsZip' => 'N', 'avsStreet' => 'N', 'expected' => 'N'], ['avsZip' => 'X', 'avsStreet' => 'Y', 'expected' => ''], ['avsZip' => 'N', 'avsStreet' => 'X', 'expected' => ''], ['avsZip' => '', 'avsStreet' => 'Y', 'expected' => ''], ['avsZip' => 'N', 'avsStreet' => '', 'expected' => ''] ]; } }
kunj1988/Magento2
app/code/Magento/Paypal/Test/Unit/Model/Payflow/AvsEmsCodeMapperTest.php
PHP
gpl-2.0
3,347
<?php // +--------------------------------------------------------------------------+ // | Image_Graph aka GraPHPite | // +--------------------------------------------------------------------------+ // | Copyright (C) 2003, 2004 Jesper Veggerby Hansen | // | Email pear.nosey@veggerby.dk | // | Web http://graphpite.sourceforge.net | // | PEAR http://pear.php.net/pepr/pepr-proposal-show.php?id=145 | // +--------------------------------------------------------------------------+ // | This library is free software; you can redistribute it and/or | // | modify it under the terms of the GNU Lesser General Public | // | License as published by the Free Software Foundation; either | // | version 2.1 of the License, or (at your option) any later version. | // | | // | This library is distributed in the hope that it will be useful, | // | but WITHOUT ANY WARRANTY; without even the implied warranty of | // | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // | Lesser General Public License for more details. | // | | // | You should have received a copy of the GNU Lesser General Public | // | License along with this library; if not, write to the Free Software | // | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | // +--------------------------------------------------------------------------+ /** * Image_Graph aka GraPHPite - PEAR PHP OO Graph Rendering Utility. * @package layout * @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen * @license http://www.gnu.org/licenses/lgpl.txt GNU Lesser General Public License * @author Jesper Veggerby Hansen <pear.nosey@veggerby.dk> * @version $Id: Constants.php,v 1.1 2008/01/24 01:06:07 tye Exp $ */ /** * Define the area to be maximized */ define("IMAGE_GRAPH_AREA_MAX", 0); /** * Define the area to be left aligned */ define("IMAGE_GRAPH_AREA_LEFT", 1); /** * Define the area to be top aligned */ define("IMAGE_GRAPH_AREA_TOP", 2); /** * Define the area to be right aligned */ define("IMAGE_GRAPH_AREA_RIGHT", 3); /** * Define the area to be bottom aligned */ define("IMAGE_GRAPH_AREA_BOTTOM", 4); /** * Define the area to have an absoute position */ define("IMAGE_GRAPH_AREA_ABSOLUTE", 5); /** * Define an area size to be absolute, ie. exact pixel size */ define("IMAGE_GRAPH_POS_ABSOLUTE", 0); /** * Define an area size to be relative, ie. percentage of "total size" */ define("IMAGE_GRAPH_POS_RELATIVE", 1); ?>
cuong09m/krwe
emailmarketer/admin/functions/amcharts/graphpite/Image/Graph/Layout/Constants.php
PHP
gpl-2.0
2,942
class UserPrizesController < UserResourcesController end
ifunam/salva
app/controllers/user_prizes_controller.rb
Ruby
gpl-2.0
57
#!/usr/bin/env python # This is the MIT License # http://www.opensource.org/licenses/mit-license.php # # Copyright (c) 2007,2008 Nick Galbreath # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # # Version 1.0 - 21-Apr-2007 # initial # Version 2.0 - 16-Nov-2008 # made class Gmetric thread safe # made gmetrix xdr writers _and readers_ # Now this only works for gmond 2.X packets, not tested with 3.X # # Version 3.0 - 09-Jan-2011 Author: Vladimir Vuksan # Made it work with the Ganglia 3.1 data format # # Version 3.1 - 30-Apr-2011 Author: Adam Tygart # Added Spoofing support from xdrlib import Packer, Unpacker import socket, re slope_str2int = {'zero':0, 'positive':1, 'negative':2, 'both':3, 'unspecified':4} # could be autogenerated from previous but whatever slope_int2str = {0: 'zero', 1: 'positive', 2: 'negative', 3: 'both', 4: 'unspecified'} class Gmetric: """ Class to send gmetric/gmond 2.X packets Thread safe """ type = ('', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float', 'double', 'timestamp') protocol = ('udp', 'multicast') def __init__(self, host, port, protocol): if protocol not in self.protocol: raise ValueError("Protocol must be one of: " + str(self.protocol)) self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if protocol == 'multicast': self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20) self.hostport = (host, int(port)) #self.socket.connect(self.hostport) def send(self, NAME, VAL, TYPE='', UNITS='', SLOPE='both', TMAX=60, DMAX=0, GROUP="", SPOOF=""): if SLOPE not in slope_str2int: raise ValueError("Slope must be one of: " + str(self.slope.keys())) if TYPE not in self.type: raise ValueError("Type must be one of: " + str(self.type)) if len(NAME) == 0: raise ValueError("Name must be non-empty") ( meta_msg, data_msg ) = gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP, SPOOF) # print msg self.socket.sendto(meta_msg, self.hostport) self.socket.sendto(data_msg, self.hostport) def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP, SPOOF): """ Arguments are in all upper-case to match XML """ packer = Packer() HOSTNAME="test" if SPOOF == "": SPOOFENABLED=0 else : SPOOFENABLED=1 # Meta data about a metric packer.pack_int(128) if SPOOFENABLED == 1: packer.pack_string(SPOOF) else: packer.pack_string(HOSTNAME) packer.pack_string(NAME) packer.pack_int(SPOOFENABLED) packer.pack_string(TYPE) packer.pack_string(NAME) packer.pack_string(UNITS) packer.pack_int(slope_str2int[SLOPE]) # map slope string to int packer.pack_uint(int(TMAX)) packer.pack_uint(int(DMAX)) # Magic number. Indicates number of entries to follow. Put in 1 for GROUP if GROUP == "": packer.pack_int(0) else: packer.pack_int(1) packer.pack_string("GROUP") packer.pack_string(GROUP) # Actual data sent in a separate packet data = Packer() data.pack_int(128+5) if SPOOFENABLED == 1: data.pack_string(SPOOF) else: data.pack_string(HOSTNAME) data.pack_string(NAME) data.pack_int(SPOOFENABLED) data.pack_string("%s") data.pack_string(str(VAL)) return ( packer.get_buffer() , data.get_buffer() ) def gmetric_read(msg): unpacker = Unpacker(msg) values = dict() unpacker.unpack_int() values['TYPE'] = unpacker.unpack_string() values['NAME'] = unpacker.unpack_string() values['VAL'] = unpacker.unpack_string() values['UNITS'] = unpacker.unpack_string() values['SLOPE'] = slope_int2str[unpacker.unpack_int()] values['TMAX'] = unpacker.unpack_uint() values['DMAX'] = unpacker.unpack_uint() unpacker.done() return values def get_gmetrics(path): data = open(path).read() start = 0 out = [] while True: m = re.search('udp_send_channel +\{([^}]+)\}', data[start:], re.M) if not m: break start += m.end() tokens = re.split('\s+', m.group(1).strip()) host = tokens[tokens.index('host')+2] port = int(tokens[tokens.index('port')+2]) out.append(Gmetric(host, port, 'udp')) return out if __name__ == '__main__': import optparse parser = optparse.OptionParser() parser.add_option("", "--protocol", dest="protocol", default="udp", help="The gmetric internet protocol, either udp or multicast, default udp") parser.add_option("", "--host", dest="host", default="127.0.0.1", help="GMond aggregator hostname to send data to") parser.add_option("", "--port", dest="port", default="8649", help="GMond aggregator port to send data to") parser.add_option("", "--name", dest="name", default="", help="The name of the metric") parser.add_option("", "--value", dest="value", default="", help="The value of the metric") parser.add_option("", "--units", dest="units", default="", help="The units for the value, e.g. 'kb/sec'") parser.add_option("", "--slope", dest="slope", default="both", help="The sign of the derivative of the value over time, one of zero, positive, negative, both, default both") parser.add_option("", "--type", dest="type", default="", help="The value data type, one of string, int8, uint8, int16, uint16, int32, uint32, float, double") parser.add_option("", "--tmax", dest="tmax", default="60", help="The maximum time in seconds between gmetric calls, default 60") parser.add_option("", "--dmax", dest="dmax", default="0", help="The lifetime in seconds of this metric, default=0, meaning unlimited") parser.add_option("", "--group", dest="group", default="", help="Group metric belongs to. If not specified Ganglia will show it as no_group") parser.add_option("", "--spoof", dest="spoof", default="", help="the address to spoof (ip:host). If not specified the metric will not be spoofed") (options,args) = parser.parse_args() g = Gmetric(options.host, options.port, options.protocol) g.send(options.name, options.value, options.type, options.units, options.slope, options.tmax, options.dmax, options.group, options.spoof)
vollmerk/sysadm-tools
ganglia/lib/gmetric.py
Python
gpl-2.0
7,815
<?php namespace ResponsiveMenu\Repositories; use ResponsiveMenu\Models\Option; use ResponsiveMenu\Collections\OptionsCollection; use ResponsiveMenu\Database\Database; use ResponsiveMenu\Factories\OptionFactory; class OptionRepository { protected static $table = 'responsive_menu'; public function __construct(Database $db, OptionFactory $factory, array $defaults) { $this->db = $db; $this->factory = $factory; $this->defaults = $defaults; } public function all() { $options = $this->db->all(self::$table); $collection = new OptionsCollection; foreach($options as $option) $collection->add($this->factory->build($option->name, $option->value)); return $collection; } public function update(Option $option) { return $this->db->update(self::$table, ['value' => $option->getFiltered()], ['name' => $option->getName()] ); } public function create(Option $option) { $arguments['name'] = $option->getName(); $arguments['value'] = $option->getFiltered(); $arguments['created_at'] = $this->db->mySqlTime(); return $this->db->insert(self::$table, $arguments); } public function remove($name) { return $this->db->delete(self::$table, $name); } public function buildFromArray(array $array) { $collection = new OptionsCollection; foreach(array_merge($this->defaults, $array) as $name => $value): $option = $this->factory->build($name, $value); $option->setValue($option->getFiltered()); $collection->add($option); endforeach; return $collection; } }
dans-lweb/immunoconcept
wp-content/plugins/responsive-menu/src/app/Repositories/OptionRepository.php
PHP
gpl-2.0
1,582
<?php /* * This file is part of EC-CUBE * * Copyright(c) 2000-2015 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. */ namespace Eccube\Controller\Admin\Content; use Eccube\Application; use Symfony\Component\HttpFoundation\Request; class LayoutController { public function index(Application $app, Request $request, $id = 1) { $device_type_id = $app['config']['device_type_pc']; // 一覧表示用 $PageLayouts = $app['eccube.repository.page_layout'] ->findBy(array( 'device_type_id' => $device_type_id, )); $Targets = $app['eccube.repository.master.target']->getAll(); // 編集対象ページ /* @var $TargetPageLayout \Eccube\Entity\PageLayout */ $TargetPageLayout = $app['eccube.repository.page_layout']->get($device_type_id, $id); // 未使用ブロックの取得 $Blocs = $app['orm.em']->getRepository('Eccube\Entity\Bloc') ->findBy(array( 'device_type_id' => $device_type_id, )); $BlocPositions = $TargetPageLayout->getBlocPositions(); foreach ($Blocs as $Bloc) { if (!$BlocPositions->containsKey($Bloc->getBlocId())) { $UnuseBlocPosition = new \Eccube\Entity\BlocPosition(); $UnuseBlocPosition ->setDeviceTypeId($device_type_id) ->setPageId($id) ->setTargetId($app['config']['target_id_unused']) ->setAnywhere(0) ->setBlocRow(0) ->setBlocId($Bloc->getBlocId()) ->setBloc($Bloc) ->setPageLayout($TargetPageLayout); $TargetPageLayout->addBlocPosition($UnuseBlocPosition); } } $form = $app['form.factory'] ->createBuilder() ->getForm(); if ('POST' === $request->getMethod()) { $form->handleRequest($request); if ($form->isValid()) { // 消す $blocCount = count($BlocPositions); foreach ($BlocPositions as $BlocPosition) { if ($BlocPosition->getPageId() == $id || $BlocPosition->getAnywhere() == 0) { $TargetPageLayout->removeBlocPosition($BlocPosition); $app['orm.em']->remove($BlocPosition); } } $app['orm.em']->flush(); $TargetHash = $this->getTragetHash($Targets); // TODO: collection を利用 $data = $request->request->all(); for ($i = 1; $i <= $blocCount; $i++) { // bloc_id が取得できない場合は INSERT しない if (!isset($data['id_' . $i])) { continue; } // 未使用は INSERT しない if ($TargetHash[$data['target_id_' . $i]] === $app['config']['target_id_unused']) { continue; } // 他のページに anywhere が存在する場合は INSERT しない $anywhere = (isset($data['anywhere_' . $i]) && $data['anywhere_' . $i] == 1) ? 1 : 0; if (isset($data['anywhere_' . $i]) && $data['anywhere_' . $i] == 1) { $Other = $app['orm.em']->getRepository('Eccube\Entity\BlocPosition') ->findBy(array( 'anywhere' => 1, 'bloc_id' => $data['id_' . $i], 'device_type_id' => $device_type_id, )); if (count($Other) > 0) { continue; } } $BlocPosition = new \Eccube\Entity\BlocPosition(); $Bloc = $app['orm.em']->getRepository('Eccube\Entity\Bloc') ->findOneBy(array( 'bloc_id' => $data['id_' . $i], 'device_type_id' => $device_type_id, )); $BlocPosition ->setDeviceTypeId($device_type_id) ->setPageId($id) ->setBlocId($data['id_' . $i]) ->setBlocRow($data['top_' . $i]) ->setTargetId($TargetHash[$data['target_id_' . $i]]) ->setBloc($Bloc) ->setPageLayout($TargetPageLayout) ->setAnywhere($anywhere); if ($id == 0) { $BlocPosition->setAnywhere(0); } $TargetPageLayout->addBlocPosition($BlocPosition); } $app['orm.em']->persist($TargetPageLayout); $app['orm.em']->flush(); $app['session']->getFlashBag()->add('admin.success', 'admin.register.complete'); return $app->redirect($app['url_generator']->generate('admin_content_layout_edit', array('id' => $id))); } } return $app['view']->render('Content/layout.twig', array( 'form' => $form->createView(), 'TargetPageLayout' => $TargetPageLayout, 'Targets' => $Targets, 'PageLayouts' => $PageLayouts, )); } public function getTragetHash($Targets) { $TargetHash = array(); foreach ($Targets as $key => $Target) { $TargetHash[$Target->getName()] = $key; } return $TargetHash; } }
Yammy/ec-cube
src/Eccube/Controller/Admin/Content/LayoutController.php
PHP
gpl-2.0
6,478
package corgis.energy.domain; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * */ public class Industrial { // Natural gas price in the industrial sector (including supplemental gaseous fuels) in dollars per million BTU. private Integer naturalGas; // Distillate fuel oil price in the industrial sector in dollars per million BTU. private Integer distillateFuelOil; // Other petroleum products average price in the industrial sector in dollars per million BTU. private Integer otherPetroleumProducts; // Coal price in the industrial sector in dollars per million BTU. private Integer coal; // Kerosene price in the industrial sector in dollars per million BTU. private Integer kerosene; // LPG price in the industrial sector in dollars per million BTU. private Integer liquefiedPetroleumGases; /** * Natural gas price in the industrial sector (including supplemental gaseous fuels) in dollars per million BTU. * @return Integer */ public Integer getNaturalGas() { return this.naturalGas; } /** * Distillate fuel oil price in the industrial sector in dollars per million BTU. * @return Integer */ public Integer getDistillateFuelOil() { return this.distillateFuelOil; } /** * Other petroleum products average price in the industrial sector in dollars per million BTU. * @return Integer */ public Integer getOtherPetroleumProducts() { return this.otherPetroleumProducts; } /** * Coal price in the industrial sector in dollars per million BTU. * @return Integer */ public Integer getCoal() { return this.coal; } /** * Kerosene price in the industrial sector in dollars per million BTU. * @return Integer */ public Integer getKerosene() { return this.kerosene; } /** * LPG price in the industrial sector in dollars per million BTU. * @return Integer */ public Integer getLiquefiedPetroleumGases() { return this.liquefiedPetroleumGases; } /** * Creates a string based representation of this Industrial. * @return String */ public String toString() { return "Industrial[" +naturalGas+", "+distillateFuelOil+", "+otherPetroleumProducts+", "+coal+", "+kerosene+", "+liquefiedPetroleumGases+"]"; } /** * Internal constructor to create a Industrial from a representation. * @param json_data The raw json data that will be parsed. */ public Industrial(JSONObject json_data) { //System.out.println(json_data); try { // Natural Gas this.naturalGas = ((Number)json_data.get("Natural Gas")).intValue(); } catch (NullPointerException e) { System.err.println("Could not convert the response to a Industrial; the field naturalGas was missing."); e.printStackTrace(); } catch (ClassCastException e) { System.err.println("Could not convert the response to a Industrial; the field naturalGas had the wrong structure."); e.printStackTrace(); } try { // Distillate Fuel Oil this.distillateFuelOil = ((Number)json_data.get("Distillate Fuel Oil")).intValue(); } catch (NullPointerException e) { System.err.println("Could not convert the response to a Industrial; the field distillateFuelOil was missing."); e.printStackTrace(); } catch (ClassCastException e) { System.err.println("Could not convert the response to a Industrial; the field distillateFuelOil had the wrong structure."); e.printStackTrace(); } try { // Other Petroleum Products this.otherPetroleumProducts = ((Number)json_data.get("Other Petroleum Products")).intValue(); } catch (NullPointerException e) { System.err.println("Could not convert the response to a Industrial; the field otherPetroleumProducts was missing."); e.printStackTrace(); } catch (ClassCastException e) { System.err.println("Could not convert the response to a Industrial; the field otherPetroleumProducts had the wrong structure."); e.printStackTrace(); } try { // Coal this.coal = ((Number)json_data.get("Coal")).intValue(); } catch (NullPointerException e) { System.err.println("Could not convert the response to a Industrial; the field coal was missing."); e.printStackTrace(); } catch (ClassCastException e) { System.err.println("Could not convert the response to a Industrial; the field coal had the wrong structure."); e.printStackTrace(); } try { // Kerosene this.kerosene = ((Number)json_data.get("Kerosene")).intValue(); } catch (NullPointerException e) { System.err.println("Could not convert the response to a Industrial; the field kerosene was missing."); e.printStackTrace(); } catch (ClassCastException e) { System.err.println("Could not convert the response to a Industrial; the field kerosene had the wrong structure."); e.printStackTrace(); } try { // Liquefied Petroleum Gases this.liquefiedPetroleumGases = ((Number)json_data.get("Liquefied Petroleum Gases")).intValue(); } catch (NullPointerException e) { System.err.println("Could not convert the response to a Industrial; the field liquefiedPetroleumGases was missing."); e.printStackTrace(); } catch (ClassCastException e) { System.err.println("Could not convert the response to a Industrial; the field liquefiedPetroleumGases had the wrong structure."); e.printStackTrace(); } } }
RealTimeWeb/datasets
datasets/java/energy/src/corgis/energy/domain/Industrial.java
Java
gpl-2.0
6,075
using System; using System.Linq; using System.Collections.Generic; using Foundation; using UIKit; namespace SaveData.UI { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; set; } // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { } } }
aragorn55/ClassSampleCode
mobiledev/SaveData/SaveData.UI/AppDelegate.cs
C#
gpl-2.0
1,413
#!/bin/bash ################################################ # Tool to program a polytouchdemo on Karo TX # # Please send feedback to: # # dominik.peuker@glyn.de # # Dominik Peuker November 2014 # # Glyn GmbH & Co. KG # # # #History # #----------------------------------------------# #0.1 - - Initial Version # ################################################ clear echo "Program Polytouchdemo to TX28" echo "-----------------------------" echo #Presetting . /$HOME/PycharmProjects/practice/flasher.conf #IPH=192.168.15.176 #Host #IPT=192.168.15.205 #Target #port=/dev/ttyUSB0 #serial port for console uboot= #Bootloader image= #Environment dtb= #Device Tree kernel= #Linux kernel rootfs= #...demo echo #preparation echo "Please check:" echo "tftp - server running?" echo "serial cable connected?" echo "ethernet connected?" echo "module TXxx (TX-XXXX) inserted?" echo "power supply connected?" echo "continue (y/n)" read continue if [ "$continue" != y ] then echo "exiting now!" exit 0 else clear fi #Keep or set IP adresses / serial port? echo "IP adresses currently set to:" echo "Host: "${IPH} echo "Target: "${IPT} echo "Serial port is currently set to "${port} echo echo "Keep these settings (y) or enter new adresses (n)?" read settings if [ "$settings" != y ] then #Host echo "Please enter IP of your host (serverip):" read IPH echo #Target echo "Please enter IP of your target (ipaddr):" read IPT echo #serial port echo "Please enter your serial like this: /dev/ttyS0:" read port echo #correct? echo "Host:"${IPH} echo "Target:"${IPT} echo "Port:"${port} #wait and clear screen sleep 4 clear else #clear screen clear fi #Mainfunction #cleanup echo " 1/20 - Clean Partitions" #delete kernel echo 'nand erase.part linux' > ${port} sleep 3 #delete rootfs echo 'nand erase.part rootfs' > ${port} sleep 3 echo " 2/20 - Set IP adresses" echo 'setenv serverip '${IPH} > ${port} echo 'setenv ipaddr '${IPT} > ${port} echo " 3/20 - Change autostart / autoload" echo 'setenv autoload no' > ${port} echo 'setenv autostart no' > ${port} echo 'saveenv' > ${port} echo " 4/20 - Update Bootloader" sleep 5 echo 'tftp ${loadaddr}' ${uboot} > ${port} echo " 5/20 - Transfer Bootloader" sleep 10 echo " 6/20 - Install Bootloader" sleep 5 echo 'romupdate ${fileaddr}' > ${port} sleep 5 echo " 7/20 - Reset" echo 'reset' > ${port} sleep 5 echo " 8/20 - Set default environment" echo 'env default -f -a' > ${port} echo " 9/20 - Set IP adresses" sleep 5 echo 'setenv serverip '${IPH} > ${port} echo 'setenv ipaddr '${IPT} > ${port} echo "10/20 - Transfer Environment" #copy and source predefinded environment echo 'tftp ${loadaddr}' ${image} > ${port} sleep 8 echo 'source ${fileaddr}' > ${port} sleep 5 #override IP - Settings in predefined Environment echo 'setenv serverip '${IPH} > ${port} echo 'setenv ipaddr '${IPT} > ${port} echo 'saveenv' > ${port} echo "11/20 - Transfer device tree" echo 'tftp ${loadaddr}' ${dtb} > ${port} echo > ${port} sleep 3 echo > ${port} echo "12/20 - Save device tree" echo 'nand erase.part dtb' > ${port} echo > ${port} sleep 3 echo 'nand write.jffs2 ${fileaddr} dtb ${filesize}' > ${port} echo > ${port} sleep 3 echo 'reset' > ${port} echo > ${port} sleep 5 echo > ${port} #copy and install kernel echo "13/20 - Transfer Linux Kernel" echo 'tftp ${loadaddr}' ${kernel} > ${port} sleep 15 echo 'nand erase.part linux' > ${port} sleep 5 echo "14/20 - Save Linux Kernel" echo 'nand write.jffs2 ${fileaddr} linux ${filesize}' > ${port} sleep 5 #copy and install filesystem echo "15/20 - Transfer Filesystem" echo 'tftp ${loadaddr}' ${rootfs} > ${port} sleep 25 echo 'nand erase.part rootfs' > ${port} sleep 5 echo "16/20 - Save Filesystem" echo 'nand write.trimffs ${fileaddr} rootfs ${filesize}' > ${port} sleep 15 echo "17/20 - Reset and Reboot" echo 'reset' > ${port} sleep 3 echo > ${port} echo > ${port} #backlight is only 50% so far, set it to 100% echo "18/20 - Set backlight to full brightness" sleep 2 echo 'fdt set /backlight default-brightness-level <0x01>' > ${port} sleep 2 echo > ${port} echo "19/20 - Save Environment" echo 'run fdtsave' > ${port} echo > ${port} sleep 3 echo "20/20 - Finished Programming!" #ready for start #change displaysettings echo "Display currently set to EDT 5,7 (ETV570)" echo "possible other video modes are:" echo "1: ET0350 ET0350G0DH6" echo "2: ET0430 ET0430G0DH6" echo "3: ET0500 ET0500G0DH6" echo "4: ETQ570 ETQ570G0DH6 or ETQ570G2DH6" #add ETV570 if "y" was entered unintentionally echo "5: ETV570 ETMV570" echo "6: ET0700 ET0700G0DH6 or ET0700G0BDH6" echo "7: VGA standard VGA" echo "change video mode? (y/n)" read video_decision if [ "$video_decision" != y ] then echo "Video resolution set to ETV570, exiting now!" exit 0 else echo "Please enter number of desired video mode (1-6)" read video_mode if [ "$video_mode" = 1 ] then echo 'setenv video_mode ET0350' > ${port} echo 'saveenv' > ${port} sleep 3 echo "Finished!" exit 0 elif [ "$video_mode" = 2 ] then echo 'setenv video_mode ET0430' > ${port} echo 'saveenv' > ${port} sleep 3 echo "Finished!" exit 0 elif [ "$video_mode" = 3 ] then echo 'setenv video_mode ET0500' > ${port} echo 'saveenv' > ${port} sleep 3 echo "Finished!" exit 0 elif [ "$video_mode" = 4 ] then echo 'setenv video_mode ETQ570' > ${port} echo 'saveenv' > ${port} sleep 3 echo "Finished!" exit 0 elif [ "$video_mode" = 5 ] then echo 'setenv video_mode ETV570' > ${port} echo 'saveenv' > ${port} sleep 3 echo "Finished!" exit 0 elif [ "$video_mode" = 6 ] then echo 'setenv video_mode ET0700' > ${port} echo 'saveenv' > ${port} echo > ${port} sleep 3 #we need to invert the pixelclock for the newer 7" #Otherwise the output won't be correct and some pixels are strange echo "For newer EDT 7 inch Displays pixelclock needs to be inverted" echo "Partnumber is: (G-)ETM0700G0BDH6" echo "Invert pixelclock? (y/n)" read invert if [ ${invert} = y ] then echo 'fdt set display/display-timings/timing4/ pixelclk-active <0>' > ${port} sleep 3 echo 'run fdtsave' > ${port} echo > ${port} echo "Finished!" exit 0 else echo "Finished!" exit 0 fi else [ "$video_mode" = 7 ] echo 'setenv video_mode VGA' > ${port} echo 'saveenv' sleep 3 echo "Finished!" exit 0 fi fi
jitter77/practice
template.sh
Shell
gpl-2.0
7,612
# -*- coding: utf-8 -*- import pcapy import Storage_Classes from collections import defaultdict #from scapy.layers.all import * from scapy.layers.dot11 import Dot11, RadioTap ################################################################ VERBOSE = 1 ### auxiliary functions ### def show_short(p, label): if ( VERBOSE >= 1 ): ## show #print p.num, p.timestamp, p.dot11.addr2, \ #label, "[" + str(p.dot11.type) + ", " + str(p.dot11.subtype) + "]", \ #p.get_rssi(), "dBm" ################################################################################### ### modified: # ETH- 'public': 00:0f:61:5d:5c:01 / ETH - 'eth':00:0f:61:5d:5c:00 'eth':00:0f:61:53:1f:00 if (str(p.dot11.addr2) == '00:0b:0e:84:00:46'): print p.timestamp, p.get_rssi(), "dBm" # das time-format hier sind microseconds als kleinste Einheit. Damit ist die letzte Zahl vor dem Komma die Sekunde. ################################################################ ### ANALYZE FUNCTIONS ### def analyze_beacon(p): #print p.num, p.timestamp, p.dot11.addr2, "BEACON:", p.get_rssi(), "dBm" show_short(p, "BEACON") # ## sanity check ## FIXME won't work!! is this a wrong sanity check..? # if ( not p.dot11.addr2 == p.dot11.addr3 ): # print # print "ERR: BEACON INVALID" # p.show() # raise Exception("ERR: BEACON INVALID") # if ( p.dot11.addr2 == "00:00:00:00:00:00" ): # print # print "ERR: BEACON INVALID" # p.show() # raise Exception("ERR: BEACON INVALID") ## store senders[p.dot11.addr2].store(p) def analyze_regular(p): ## some packet types are not correctly dissected ## ---> e.g. Block ACK Req ## ---> TODO (what shall we do with them?) if ( not p.dot11.addr2 ): ##################################### ##### THIS IS COMPLETELY UNCOMMENTED TO STOP THIS DISSECTION EXCEPTTION !!! (stephan) ##################################### #show_short(p, "<<not recognized>>.") #p.show_stephan() #show_short(p, "Packet.") ############################## ##was: show(p.dot11) ... just guessing ############################## #print # dat = raw_input() ######################raise Exception("uncorrect dissection exception") return ## BRANCH: "no" sender.. ## ---> some packets have no proper sender information ## ---> just ignore them!! if ( p.dot11.addr2 == "00:00:00:00:00:00" ): show_short(p, "<<ignored>>") return ## BRANCH: regular packet else: show_short(p, "Packet.") ## store senders[p.dot11.addr2].store(p) ### general analyze function ### --> hands packets over to specialized ones def analyze(p): ## Control frames have no useful sender information ## ---> we don't want them. just drop it. ## BRANCH: control frames try: if ( p.dot11.type == 1 ): # BRANCH: ACK (sender unclear...) if ( p.dot11.subtype == 13 ): if ( VERBOSE >= 1 ): macheNix=1 ################################################################################################ ###modified: #print p.num, "ignoring ACK (1, 13)", p.get_rssi(), "dBm" ################################################################################################ return if ( p.dot11.subtype == 12 ): if ( VERBOSE >= 1 ): macheNix=1 ################################################################################################ ###modified: #print p.num, "ignoring CTS (1, 12)", p.get_rssi(), "dBm" ################################################################################################ return if ( p.dot11.subtype == 8 ): if ( VERBOSE >= 1 ): macheNix=1 ################################################################################################ ###modified: #print p.num, "ignoring Block ACK Req (1, 12)", p.get_rssi(), "dBm" ################################################################################################ return ## BRANCH: managemet frames if ( p.dot11.type == 0 ): # BRANCH: BEACON if ( p.dot11.subtype == 8 ): analyze_beacon(p) return # elif ( p.dot11.type == 2 ): # if ( p.dot11.subtype == 4 ): # analyze_regular(p) # dat = raw_input() # return except AttributeError: if ( VERBOSE >= 1 ): print p.num, "ignoring malformed packet", p.get_rssi(), "dBm" return ## default ## ---> most packets can just be treated the same.. analyze_regular(p) # show(p.dot11) # print # dat = raw_input() ################################################################ ### PCAP READING AND DECODING ### ## TODO do they have to be global? pcapy_reader = False packet_num = False senders = False def get_next(): global packet_num pkt = pcapy_reader.next() if ( type(pkt[0]) == type(None)): return None p = Storage_Classes.Packet() packet_num += 1 p.num = packet_num p.timestamp = pkt[0].getts() p.tap = RadioTap() p.tap.dissect(pkt[1]) p.dot11 = p.tap.payload #print "----->", ord(pkt[1][14]) p.rssi = ord(pkt[1][14]) - 256 return p ### public ### def parse(file_name, num=100): global pcapy_reader global senders ## init pcapy_reader = pcapy.open_offline(file_name) packet_num = 0 senders = defaultdict(Storage_Classes.Sender) print "Reading", file_name, "..." i = 0 while ( i != num): ## like a for loop, but e.g. -1 means "to infinity" if ( i % 20000 == 0 ): print i p = get_next() if ( p == None ): print "EOF", i break analyze(p) i += 1 # dat = raw_input() ## FIXME how to close this? #pcapy.close() ### statictics print print "----------------------------------------" print "Senders:", len(senders) ## TODO count total in this module not in the Sender class print "used packets:", Storage_Classes.Sender.total ## TODO maybe this shuld also be returned from "parse" return senders
stephansigg/IPSN_localisation_passive-DF
Data_CaseStudies/CaseStudy_1312_initial/pcap_analyzer/Pcap_Parser.py
Python
gpl-2.0
6,609
# Rekall Memory Forensics # # Copyright 2016 Google Inc. All Rights Reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # 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 """Plugins to inspect flows.""" import base64 import json import os import time import arrow from rekall import plugin from rekall import utils from rekall_agent import common from rekall_agent import flow from rekall_agent import result_collections from rekall_agent import serializer from rekall_agent.locations import files from rekall_agent.ui import renderers CANNED_CONDITIONS = dict( OS_WINDOWS="any from agent_info() where key=='system' and value=='Windows'", OS_LINUX="any from agent_info() where key=='system' and value=='Linux'", OS_OSX="any from agent_info() where key=='system' and value=='Darwin'", ) class AgentControllerShowFlows(common.AbstractControllerCommand): name = "show_flows" __args = [ dict(name="limit", type="IntParser", default=20, help="Total results to display"), ] table_header = [ dict(name="state", width=8), dict(name="flow_id", width=14), dict(name="type", width=18), dict(name="created", width=19), dict(name="last_active", width=19), dict(name="collections"), ] def collect_db(self, collection): # Now show all the flows. for i, row in enumerate(collection.query(order_by="created desc")): if i > self.plugin_args.limit: break ticket = flow.FlowStatus.from_json( row["ticket_data"], session=self.session) last_active = row["last_active"] if last_active: last_active = arrow.Arrow.fromtimestamp(last_active) collections = [x.location.get_canonical().to_path() for x in ticket.collections] yield dict(state=row["status"], flow_id=row["flow_id"], type=row["type"], created=arrow.Arrow.fromtimestamp(row["created"]), last_active=last_active, collections=collections) def _check_pending_flow(self, row): """Check for flow tickets. For pending flows, it is possible that the worker just has not caught up. We try to show it anyway by checking for the tickets. """ if row["state"] == "Pending": ticket_location = self._config.server.ticket_for_server( "FlowStatus", row["flow_id"], self.client_id) # The client will actually add a nonce to this so we need to find # all subobjects. for sub_object in ticket_location.list_files(): # The subobject is a canonical path, we need to authorize it. data = self._config.server.canonical_for_server( sub_object.location).read_file() if data: ticket = flow.FlowStatus.from_json( data, session=self.session) row["state"] = "%s(*)" % ticket.status row["collections"] = [sub_object.location.to_path()] row["last_active"] = ticket.timestamp def collect(self): if not self.client_id: raise plugin.PluginError("Client ID must be specified.") with flow.FlowStatsCollection.load_from_location( self._config.server.flow_db_for_server(self.client_id), session=self.session) as collection: rows = list(self.collect_db(collection)) common.THREADPOOL.map(self._check_pending_flow, rows) for row in rows: row["collections"] = [ renderers.UILink("gs", x) for x in row["collections"]] row["flow_id"] = renderers.UILink("f", row["flow_id"]) yield row class AgentControllerShowHunts(AgentControllerShowFlows): name = "show_hunts" __args = [ dict(name="queue", default="All", help="The hunt queue."), ] def collect(self): with flow.FlowStatsCollection.load_from_location( self._config.server.flow_db_for_server( queue=self.plugin_args.queue), session=self.session) as collection: for row in self.collect_db(collection): row["flow_id"] = renderers.UILink("h", row["flow_id"]) yield row class SerializedObjectInspectorMixin(object): """A plugin Mixin which inspects a SerializedObject.""" __args = [ dict(name="verbosity", type="IntParser", default=0, help="If non zero show all fields."), ] table_header = [ dict(name="Field", type="TreeNode", max_depth=5, width=20), dict(name="Value", width=60), dict(name="Description") ] def _explain(self, obj, depth=0, ignore_fields=None): if isinstance(obj, serializer.SerializedObject): for x in self._collect_serialized_object( obj, depth=depth, ignore_fields=ignore_fields): yield x elif isinstance(obj, basestring): yield dict(Value=obj) elif isinstance(obj, list): yield dict(Value=", ".join(obj)) else: raise RuntimeError("Unable to render object %r" % obj) def _collect_list(self, list_obj, field, descriptor, depth): yield dict( Field=field, Value="(Array)", Description=descriptor.get("doc", ""), highlight="important" if descriptor.get("user") else "", depth=depth) for i, value in enumerate(list_obj): for row in self._explain(value, depth=depth): row["Field"] = "[%s] %s" % (i, row.get("Field", "")) if descriptor.get("user"): row["highlight"] = "important" yield row def _collect_dict(self, dict_obj, field, descriptor, depth): yield dict( Field=field, Value="(Dict)", Description=descriptor.get("doc", ""), highlight="important" if descriptor.get("user") else "", depth=depth) for key, value in sorted(dict_obj.iteritems()): for row in self._explain(value, depth=depth+1): row["Field"] = ". " + key if descriptor.get("user"): row["highlight"] = "important" yield row def _collect_serialized_object(self, flow_obj, depth=0, ignore_fields=None): for descriptor in flow_obj.get_descriptors(): # Skip hidden fields if verbosity is low. if self.plugin_args.verbosity < 2 and descriptor.get("hidden"): continue field = descriptor["name"] # Only show requested fields in non-verbose mode. if (not self.plugin_args.verbosity and ignore_fields and field in ignore_fields): continue if not flow_obj.HasMember(field): continue value = flow_obj.GetMember(field) if isinstance(value, serializer.SerializedObject): display_value = "(%s)" % value.__class__.__name__ elif isinstance(value, str): display_value = base64.b64encode(value) elif isinstance(value, unicode): display_value = value elif isinstance(value, list): for x in self._collect_list(value, field, descriptor, depth): yield x continue elif isinstance(value, dict): for x in self._collect_dict(value, field, descriptor, depth): yield x continue else: display_value = utils.SmartUnicode(value) if (not self.plugin_args.verbosity and len(display_value) > 45): display_value = display_value[:45] + " ..." yield dict( Field=field, Value=display_value, Description=descriptor.get("doc", ""), highlight="important" if descriptor.get("user") else "", depth=depth) if (isinstance(value, serializer.SerializedObject)): for row in self._explain(value, depth=depth+1): yield row class InspectFlow(SerializedObjectInspectorMixin, common.AbstractControllerCommand): name = "inspect_flow" __args = [ dict(name="flow_id", required=True, positional=True, help="The flow to examine"), ] table_header = [ dict(name="divider", type="Divider") ] + SerializedObjectInspectorMixin.table_header def _get_collection(self, client_id): return flow.FlowStatsCollection.load_from_location( self._config.server.flow_db_for_server(client_id), session=self.session) def get_flow_object(self, flow_id=None): if flow_id is None: flow_id = self.plugin_args.flow_id return flow.Flow.from_json( self._config.server.flows_for_server(flow_id).read_file(), session=self.session) def collect(self): flow_obj = self.get_flow_object(self.plugin_args.flow_id) with self._get_collection(flow_obj.client_id) as collection: yield dict(divider="Flow Object (%s)" % flow_obj.__class__.__name__) for x in self._explain(flow_obj, ignore_fields=set([ "ticket", "actions" ])): yield x for row in collection.query(flow_id=self.plugin_args.flow_id): ticket = flow.FlowStatus.from_json(row["ticket_data"], session=self.session) yield dict(divider="Flow Status Ticket") for x in self._explain(ticket, ignore_fields=set([ "location", "client_id", "flow_id", "collections" ])): yield x if ticket.collections: yield dict(divider="Collections") for collection in ticket.collections: link = renderers.UILink( "gs", collection.location.get_canonical().to_path()) yield dict( Field=collection.__class__.__name__, Value=link, Description="", nowrap=True) if ticket.files: yield dict(divider="Uploads") for upload in ticket.files: link = renderers.UILink( "gs", upload.get_canonical().to_path()) yield dict(Value=link, nowrap=True) if ticket.error: yield dict(divider="Error") yield dict(Field="ticket.error", Value=ticket.error) if ticket.backtrace: yield dict(divider="Backtrace") yield dict(Field="ticket.backtrace", Value=ticket.backtrace) class InspectHunt(InspectFlow): name = "inspect_hunt" __args = [ dict(name="limit", type="IntParser", default=20, help="Limit of rows to display"), dict(name="graph_clients", type="Bool", help="Also plot a graph of client participation."), ] table_header = [ dict(name="divider", type="Divider"), dict(name="Field", width=20), dict(name="Time", width=20), dict(name="Value", width=20), dict(name="Description") ] def _get_collection(self): return flow.HuntStatsCollection.load_from_location( self._config.server.hunt_db_for_server(self.plugin_args.flow_id), session=self.session) def graph_clients(self, collection): """Draw a graph of client engagement.""" # This is optionally dependent on presence of matplotlib. try: from matplotlib import pyplot except ImportError: raise plugin.PluginError( "You must have matplotlib installed to plot graphs.") total_clients = 0 base = None data_x = [] data_y = [] for row in collection.query(order_by="executed"): total_clients += 1 if base is None: base = row["executed"] data_x.append(row["executed"] - base) data_y.append(total_clients) fig = pyplot.figure() ax = fig.add_subplot(111) ax.plot(data_x, data_y) start_time = arrow.Arrow.fromtimestamp(base) ax.set_title("Clients in Hunt %s" % self.plugin_args.flow_id) ax.set_xlabel("Seconds after %s (%s)" % ( start_time.ctime(), start_time.humanize())) ax.set_ylabel("Total Client Count") pyplot.show() def collect(self): with self._get_collection() as collection: flow_obj = self.get_flow_object(self.plugin_args.flow_id) if self.plugin_args.graph_clients: self.graph_clients(collection) yield dict(divider="Flow Object (%s)" % flow_obj.__class__.__name__) for x in self._explain(flow_obj, ignore_fields=set([ "ticket", "actions" ])): yield x yield dict(divider="Summary") yield dict(Field="Total Clients", Value=list(collection.query( "select count(*) as c from tbl_default" ))[0]["c"]) yield dict(Field="Successful Clients", Value=list(collection.query( "select count(*) as c from tbl_default " "where status = 'Done'"))[0]["c"]) yield dict(Field="Errors Clients", Value=list(collection.query( "select count(*) as c from tbl_default " "where status = 'Error'"))[0]["c"]) total = 0 yield dict(divider="Results") for row in collection.query( status="Done", limit=self.plugin_args.limit): ticket = flow.FlowStatus.from_json(row["ticket_data"], session=self.session) for result in ticket.collections: if total > self.plugin_args.limit: break yield dict(Field=ticket.client_id, Time=ticket.timestamp, Value=renderers.UILink( "gs", result.location.to_path()), nowrap=True) total += 1 yield dict(divider="Uploads") total = 0 for row in collection.query( status="Done", limit=self.plugin_args.limit): ticket = flow.FlowStatus.from_json(row["ticket_data"], session=self.session) for result in ticket.files: if total > self.plugin_args.limit: break yield dict(Field=ticket.client_id, Time=ticket.timestamp, Value=renderers.UILink( "gs", result.to_path()), nowrap=True) total += 1 for row in collection.query( status="Error", limit=self.plugin_args.limit): ticket = flow.FlowStatus.from_json(row["ticket_data"], session=self.session) yield dict(Field=ticket.client_id, Time=ticket.timestamp, Value=ticket.error, nowrap=True) class AgentControllerRunFlow(SerializedObjectInspectorMixin, common.AbstractControllerCommand): name = "launch_flow" __args = [ dict(name="flow", type="Choices", positional=True, required=True, choices=utils.JITIteratorCallable( utils.get_all_subclasses, flow.Flow), help="The flow to launch"), dict(name="args", type="Any", positional=True, default={}, help="Arguments to the flow (use explain_flow to see valid args)." "This may also be a JSON encoded string"), dict(name="queue", help="Which queue to schedule the hunt on."), dict(name="condition", help="An EFilter query to evaluate if the flow should be run."), # This should only be set if no condition is specified. dict(name="canned_condition", type="Choices", default=None, choices=CANNED_CONDITIONS, help="Canned conditions for the hunt."), dict(name="live", type="Choices", default="API", choices=["API", "Memory"], help="Live mode to use"), dict(name="quota", type="IntParser", default=3600, help="Total number of CPU seconds allowed for this flow."), ] def make_flow_object(self): flow_cls = flow.Flow.ImplementationByClass(self.plugin_args.flow) if not flow_cls: raise plugin.PluginError("Unknown flow %s" % self.plugin_args.flow) args = self.plugin_args.args if isinstance(args, basestring): try: args = json.loads(args) except Exception as e: raise plugin.PluginError( "args should be a JSON string of a dict: %s" % e) if not isinstance(args, dict): raise plugin.PluginError("args should be a dict") flow_obj = flow_cls.from_primitive(args, session=self.session) flow_obj.client_id = self.client_id flow_obj.queue = self.plugin_args.queue flow_obj.session.live = self.plugin_args.live # If a canned condition was specified automatically add it. if self.plugin_args.canned_condition: flow_obj.condition = CANNED_CONDITIONS[ self.plugin_args.canned_condition] elif self.plugin_args.condition: flow_obj.condition = self.plugin_args.condition # Specify flow quota. flow_obj.quota.user_time = self.plugin_args.quota return flow_obj def collect(self): # Now launch the flow. flow_obj = self.make_flow_object() flow_obj.start() for x in self._explain(flow_obj): yield x class AgentControllerRunHunt(AgentControllerRunFlow): """Launch a hunt on many clients at once. Rekall does not treat hunts as different or special entities - a hunt is just a flow which targets multiple systems. However, for users it is sometimes helpful to think in terms of a "hunt". This plugin makes it easier to launch the hunt. """ name = "launch_hunt" __args = [ # Flows are scheduled on the client's flow queue but hunts are generally # scheduled on a Label Queue (e.g. the All queue schedules to all # agents). dict(name="queue", default="All", help="Which queue to schedule the hunt on."), ] class AgentControllerExplainFlows(common.AbstractControllerCommand): """Explain all the parameters a flow may take.""" name = "explain_flow" __args = [ dict(name="flow", type="Choices", positional=True, required=True, choices=utils.JITIteratorCallable( utils.get_all_subclasses, flow.Flow), help="The flow to explain"), dict(name="verbosity", type="IntParser", default=0, help="If non zero show all fields."), dict(name="recursive", type="Bool", help="Show recursively nested fields."), ] table_header = [ dict(name="Field", type="TreeNode", max_depth=5), dict(name="Type"), dict(name="Description") ] table_options = dict( auto_widths=True, ) def _explain(self, flow_cls, depth=0): for descriptor in flow_cls.get_descriptors(): user_accessible = descriptor.get("user") if self.plugin_args.verbosity < 1 and not user_accessible: continue field = descriptor["name"] field_type = descriptor.get("type", "string") field_description = field_type if isinstance(field_type, type): field_description = "(%s)" % field_type.__name__ yield dict(Field=field, Type=field_description, Description=descriptor.get("doc", ""), depth=depth) if (self.plugin_args.recursive and isinstance(field_type, type) and issubclass(field_type, serializer.SerializedObject)): for row in self._explain(field_type, depth=depth+1): #row["Field"] = "%s.%s" % (field, row["Field"]) yield row def collect(self): flow_cls = flow.Flow.ImplementationByClass(self.plugin_args.flow) for x in self._explain(flow_cls): yield x class AgentControllerExportCollections(common.AbstractControllerCommand): """Exports all collections from the hunt or flow.""" name = "export" __args = [ dict(name="flow_id", positional=True, required=True, help="The flow or hunt ID we should export."), dict(name="dumpdir", positional=True, required=True, help="The output directory we use export to.") ] table_header = [ dict(name="divider", type="Divider"), dict(name="Message") ] def _collect_hunts(self, flow_obj): with flow.HuntStatsCollection.load_from_location( self._config.server.hunt_db_for_server(flow_obj.flow_id), session=self.session) as hunt_db: collections_by_type = {} uploads = [] for row in hunt_db.query(): status = flow.HuntStatus.from_json(row["ticket_data"], session=self.session) for collection in status.collections: collections_by_type.setdefault( collection.collection_type, []).append( (collection, status.client_id)) uploads.extend(status.files) yield dict(divider="Exporting Collections") # Now create a new collection by type into the output directory. for output_location in common.THREADPOOL.imap_unordered( self._dump_collection, collections_by_type.iteritems()): yield dict(Message=output_location.to_path()) yield dict(divider="Exporting files") for output_location in common.THREADPOOL.imap_unordered( self._dump_uploads, uploads): yield dict(Message=output_location.to_path()) def _collect_flows(self, flow_obj): with flow.FlowStatsCollection.load_from_location( self._config.server.flow_db_for_server(flow_obj.client_id), session=self.session) as flow_db: collections_by_type = {} uploads = [] for row in flow_db.query(flow_id=flow_obj.flow_id): status = flow.FlowStatus.from_json(row["ticket_data"], session=self.session) for collection in status.collections: collections_by_type.setdefault( collection.collection_type, []).append( (collection, status.client_id)) uploads.extend(status.files) yield dict(divider="Exporting Collections") # Now create a new collection by type into the output directory. for output_location in common.THREADPOOL.imap_unordered( self._dump_collection, collections_by_type.iteritems()): yield dict(Message=output_location.to_path()) yield dict(divider="Exporting files") for output_location in common.THREADPOOL.imap_unordered( self._dump_uploads, uploads): yield dict(Message=output_location.to_path()) def _dump_uploads(self, download_location): output_location = files.FileLocation.from_keywords( path=os.path.join(self.plugin_args.dumpdir, self.flow_id, "files", download_location.to_path()), session=self.session) local_filename = self._config.server.canonical_for_server( download_location).get_local_filename() output_location.upload_local_file(local_filename) return output_location def _dump_collection(self, args): type, collections = args output_location = files.FileLocation.from_keywords( path=os.path.join(self.plugin_args.dumpdir, self.flow_id, "collections", type), session=self.session) # We assume all the collections of the same type are the same so we can # just take the first one as the template for the output collection. output_collection = collections[0][0].copy() # Add another column for client_id. output_collection.tables[0].columns.append( result_collections.ColumnSpec.from_keywords( name="client_id", session=self.session)) output_collection.location = output_location with output_collection.create_temp_file(): common.THREADPOOL.map( self._copy_single_location, ((output_collection, x, y) for x, y in collections)) return output_location def _copy_single_location(self, args): output_collection, canonical_collection, client_id = args with canonical_collection.load_from_location( self._config.server.canonical_for_server( canonical_collection.location), session=self.session) as collection: for row in collection: output_collection.insert(client_id=client_id, **row) def collect(self): self.flow_id = self.plugin_args.flow_id if self.flow_id.startswith("f:") or self.flow_id.startswith("h:"): self.flow_id = self.flow_id[2:] flow_obj = flow.Flow.from_json( self._config.server.flows_for_server(self.flow_id).read_file(), session=self.session) if flow_obj.is_hunt(): return self._collect_hunts(flow_obj) else: return self._collect_flows(flow_obj) return [] class FlowLauncherAndWaiterMixin(object): """A mixin to implement launching and waiting for flows to complete.""" def launch_and_wait(self, flow_obj): """A Generator of messages.""" flow_db_location = self._config.server.flow_db_for_server( self.client_id) flow_db_stat = flow_db_location.stat() flow_obj.start() # Wait until the flow arrives. while 1: new_stat = flow_db_location.stat() if flow_db_stat and new_stat.generation > flow_db_stat.generation: with flow.FlowStatsCollection.load_from_location( flow_db_location, session=self.session) as flow_db: tickets = [] for row in flow_db.query(flow_id=flow_obj.flow_id): if row["status"] in ["Done", "Error"]: tickets.append( flow.FlowStatus.from_json(row["ticket_data"], session=self.session)) if tickets: return tickets time.sleep(2)
rlugojr/rekall
rekall-agent/rekall_agent/ui/flows.py
Python
gpl-2.0
29,082
/* Copyright (c) 2014, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #define pr_fmt(fmt) "%s: " fmt, __func__ #include <linux/kernel.h> #include <linux/err.h> #include <linux/delay.h> #include <linux/clk/msm-clk-provider.h> #include <linux/clk/msm-clk.h> #include <linux/clk/msm-clock-generic.h> #include <dt-bindings/clock/msm-clocks-8994.h> #include "mdss-pll.h" #include "mdss-dsi-pll.h" #define VCO_DELAY_USEC 1 static struct clk_ops bypass_lp_div_mux_clk_ops; static struct clk_ops pixel_clk_src_ops; static struct clk_ops byte_clk_src_ops; static struct clk_ops ndiv_clk_ops; static int vco_set_rate_20nm(struct clk *c, unsigned long rate) { int rc; struct dsi_pll_vco_clk *vco = to_vco_clk(c); struct mdss_pll_resources *dsi_pll_res = vco->priv; rc = mdss_pll_resource_enable(dsi_pll_res, true); if (rc) { pr_err("Failed to enable mdss dsi pll resources\n"); return rc; } rc = pll_20nm_vco_set_rate(vco, rate); mdss_pll_resource_enable(dsi_pll_res, false); return rc; } static int dsi_pll_enable_seq_8994(struct mdss_pll_resources *dsi_pll_res) { int rc = 0; int pll_locked; /* * PLL power up sequence. * Add necessary delays recommeded by hardware. */ MDSS_PLL_REG_W(dsi_pll_res->pll_base, MMSS_DSI_PHY_PLL_PLLLOCK_CMP_EN, 0x0D); MDSS_PLL_REG_W(dsi_pll_res->pll_base, MMSS_DSI_PHY_PLL_PLL_CNTRL, 0x07); MDSS_PLL_REG_W(dsi_pll_res->pll_base, MMSS_DSI_PHY_PLL_PLL_BKG_KVCO_CAL_EN, 0x00); udelay(500); pll_20nm_dsi_phy_ctrl_config(dsi_pll_res, 0x200); /* Ctrl 0 */ pll_locked = dsi_20nm_pll_lock_status(dsi_pll_res); if (!pll_locked) { pr_err("DSI PLL lock failed\n"); rc = -EINVAL; } else { pr_debug("DSI PLL Lock success\n"); } return rc; } /* Op structures */ static struct clk_ops clk_ops_dsi_vco = { .set_rate = vco_set_rate_20nm, .round_rate = pll_20nm_vco_round_rate, .handoff = pll_20nm_vco_handoff, .prepare = pll_20nm_vco_prepare, .unprepare = pll_20nm_vco_unprepare, }; static struct clk_div_ops fixed_hr_oclk2_div_ops = { .set_div = fixed_hr_oclk2_set_div, .get_div = fixed_hr_oclk2_get_div, }; static struct clk_div_ops ndiv_ops = { .set_div = ndiv_set_div, .get_div = ndiv_get_div, }; static struct clk_div_ops hr_oclk3_div_ops = { .set_div = hr_oclk3_set_div, .get_div = hr_oclk3_get_div, }; static struct clk_mux_ops bypass_lp_div_mux_ops = { .set_mux_sel = set_bypass_lp_div_mux_sel, .get_mux_sel = get_bypass_lp_div_mux_sel, }; static struct dsi_pll_vco_clk dsi_vco_clk_8994 = { .ref_clk_rate = 19200000, .min_rate = 1000000000, .max_rate = 2000000000, .pll_en_seq_cnt = 1, .pll_enable_seqs[0] = dsi_pll_enable_seq_8994, .c = { .dbg_name = "dsi_vco_clk_8994", .ops = &clk_ops_dsi_vco, CLK_INIT(dsi_vco_clk_8994.c), }, }; static struct div_clk ndiv_clk_8994 = { .data = { .max_div = 15, .min_div = 1, }, .ops = &ndiv_ops, .c = { .parent = &dsi_vco_clk_8994.c, .dbg_name = "ndiv_clk_8994", .ops = &ndiv_clk_ops, .flags = CLKFLAG_NO_RATE_CACHE, CLK_INIT(ndiv_clk_8994.c), }, }; static struct div_clk indirect_path_div2_clk_8994 = { .data = { .div = 2, .min_div = 2, .max_div = 2, }, .c = { .parent = &ndiv_clk_8994.c, .dbg_name = "indirect_path_div2_clk_8994", .ops = &clk_ops_div, .flags = CLKFLAG_NO_RATE_CACHE, CLK_INIT(indirect_path_div2_clk_8994.c), }, }; static struct div_clk hr_oclk3_div_clk_8994 = { .data = { .max_div = 255, .min_div = 1, }, .ops = &hr_oclk3_div_ops, .c = { .parent = &dsi_vco_clk_8994.c, .dbg_name = "hr_oclk3_div_clk_8994", .ops = &pixel_clk_src_ops, .flags = CLKFLAG_NO_RATE_CACHE, CLK_INIT(hr_oclk3_div_clk_8994.c), }, }; static struct div_clk pixel_clk_src = { .data = { .div = 2, .min_div = 2, .max_div = 2, }, .c = { .parent = &hr_oclk3_div_clk_8994.c, .dbg_name = "pixel_clk_src", .ops = &clk_ops_div, .flags = CLKFLAG_NO_RATE_CACHE, CLK_INIT(pixel_clk_src.c), }, }; static struct mux_clk bypass_lp_div_mux_8994 = { .num_parents = 2, .parents = (struct clk_src[]){ {&dsi_vco_clk_8994.c, 0}, {&indirect_path_div2_clk_8994.c, 1}, }, .ops = &bypass_lp_div_mux_ops, .c = { .parent = &dsi_vco_clk_8994.c, .dbg_name = "bypass_lp_div_mux_8994", .ops = &bypass_lp_div_mux_clk_ops, CLK_INIT(bypass_lp_div_mux_8994.c), }, }; static struct div_clk fixed_hr_oclk2_div_clk_8994 = { .ops = &fixed_hr_oclk2_div_ops, .data = { .min_div = 4, .max_div = 4, }, .c = { .parent = &bypass_lp_div_mux_8994.c, .dbg_name = "fixed_hr_oclk2_div_clk_8994", .ops = &byte_clk_src_ops, CLK_INIT(fixed_hr_oclk2_div_clk_8994.c), }, }; static struct div_clk byte_clk_src = { .data = { .div = 2, .min_div = 2, .max_div = 2, }, .c = { .parent = &fixed_hr_oclk2_div_clk_8994.c, .dbg_name = "byte_clk_src", .ops = &clk_ops_div, CLK_INIT(byte_clk_src.c), }, }; static struct clk_lookup mdss_dsi_pllcc_8994[] = { CLK_LIST(pixel_clk_src), CLK_LIST(byte_clk_src), CLK_LIST(fixed_hr_oclk2_div_clk_8994), CLK_LIST(bypass_lp_div_mux_8994), CLK_LIST(hr_oclk3_div_clk_8994), CLK_LIST(indirect_path_div2_clk_8994), CLK_LIST(ndiv_clk_8994), CLK_LIST(dsi_vco_clk_8994), }; int dsi_pll_clock_register_20nm(struct platform_device *pdev, struct mdss_pll_resources *pll_res) { int rc; if (!pdev || !pdev->dev.of_node) { pr_err("Invalid input parameters\n"); return -EINVAL; } if (!pll_res || !pll_res->pll_base) { pr_err("Invalid PLL resources\n"); return -EPROBE_DEFER; } /* Set client data to mux, div and vco clocks */ byte_clk_src.priv = pll_res; pixel_clk_src.priv = pll_res; bypass_lp_div_mux_8994.priv = pll_res; indirect_path_div2_clk_8994.priv = pll_res; ndiv_clk_8994.priv = pll_res; fixed_hr_oclk2_div_clk_8994.priv = pll_res; hr_oclk3_div_clk_8994.priv = pll_res; dsi_vco_clk_8994.priv = pll_res; pll_res->vco_delay = VCO_DELAY_USEC; /* Set clock source operations */ pixel_clk_src_ops = clk_ops_slave_div; pixel_clk_src_ops.prepare = dsi_pll_div_prepare; ndiv_clk_ops = clk_ops_div; ndiv_clk_ops.prepare = dsi_pll_div_prepare; byte_clk_src_ops = clk_ops_div; byte_clk_src_ops.prepare = dsi_pll_div_prepare; bypass_lp_div_mux_clk_ops = clk_ops_gen_mux; bypass_lp_div_mux_clk_ops.prepare = dsi_pll_mux_prepare; if (pll_res->target_id == MDSS_PLL_TARGET_8994) { rc = of_msm_clock_register(pdev->dev.of_node, mdss_dsi_pllcc_8994, ARRAY_SIZE(mdss_dsi_pllcc_8994)); if (rc) { pr_err("Clock register failed\n"); rc = -EPROBE_DEFER; } } else { pr_err("Invalid target ID\n"); rc = -EINVAL; } if (!rc) pr_info("Registered DSI PLL clocks successfully\n"); return rc; }
ipaccess/fsm99xx-kernel-sources
drivers/clk/qcom/mdss/mdss-dsi-pll-20nm.c
C
gpl-2.0
7,051
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ /* * preferences.h * Copyright (C) 2000 - 2003 Naba Kumar <naba@gnome.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _ANJUTA_PREFERENCES_H_ #define _ANJUTA_PREFERENCES_H_ #include <gtk/gtk.h> #include <glib/gi18n.h> #include <gdk/gdkkeysyms.h> #include <libanjuta/anjuta-preferences-dialog.h> #include <libanjuta/anjuta-plugin-manager.h> G_BEGIN_DECLS typedef enum { ANJUTA_PROPERTY_OBJECT_TYPE_TOGGLE, ANJUTA_PROPERTY_OBJECT_TYPE_SPIN, ANJUTA_PROPERTY_OBJECT_TYPE_ENTRY, ANJUTA_PROPERTY_OBJECT_TYPE_COMBO, ANJUTA_PROPERTY_OBJECT_TYPE_TEXT, ANJUTA_PROPERTY_OBJECT_TYPE_COLOR, ANJUTA_PROPERTY_OBJECT_TYPE_FONT, ANJUTA_PROPERTY_OBJECT_TYPE_FILE, ANJUTA_PROPERTY_OBJECT_TYPE_FOLDER } AnjutaPropertyObjectType; typedef enum { ANJUTA_PROPERTY_DATA_TYPE_BOOL, ANJUTA_PROPERTY_DATA_TYPE_INT, ANJUTA_PROPERTY_DATA_TYPE_TEXT, ANJUTA_PROPERTY_DATA_TYPE_COLOR, ANJUTA_PROPERTY_DATA_TYPE_FONT } AnjutaPropertyDataType; typedef struct _AnjutaProperty AnjutaProperty; /* Get functions. Add more get functions for AnjutaProperty, if required */ /* Gets the widget associated with the property */ GtkWidget* anjuta_property_get_widget (AnjutaProperty *prop); #define ANJUTA_TYPE_PREFERENCES (anjuta_preferences_get_type ()) #define ANJUTA_PREFERENCES(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), ANJUTA_TYPE_PREFERENCES, AnjutaPreferences)) #define ANJUTA_PREFERENCES_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), ANJUTA_TYPE_PREFERENCES, AnjutaPreferencesClass)) #define ANJUTA_IS_PREFERENCES(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), ANJUTA_TYPE_PREFERENCES)) #define ANJUTA_IS_PREFERENCES_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), ANJUTA_TYPE_PREFERENCES)) typedef struct _AnjutaPreferences AnjutaPreferences; typedef struct _AnjutaPreferencesClass AnjutaPreferencesClass; typedef struct _AnjutaPreferencesPriv AnjutaPreferencesPriv; struct _AnjutaPreferences { GObject parent; /*< private >*/ AnjutaPreferencesPriv *priv; }; struct _AnjutaPreferencesClass { GObjectClass parent; }; typedef gboolean (*AnjutaPreferencesCallback) (AnjutaPreferences *pr, const gchar *key, gpointer data); GType anjuta_preferences_get_type (void); AnjutaPreferences *anjuta_preferences_new (AnjutaPluginManager *plugin_manager); AnjutaPreferences *anjuta_preferences_default (void); void anjuta_preferences_add_from_builder (AnjutaPreferences* pr,GtkBuilder *builder, const gchar* glade_widget_name, const gchar* title, const gchar *icon_filename); void anjuta_preferences_remove_page (AnjutaPreferences *pr, const gchar *page_name); /* * Registers all properties defined for widgets below the 'parent' widget * in the given gtkbuilder UI tree */ void anjuta_preferences_register_all_properties_from_builder_xml (AnjutaPreferences* pr, GtkBuilder* builder, GtkWidget *parent); gboolean anjuta_preferences_register_property_from_string (AnjutaPreferences *pr, GtkWidget *object, const gchar *property_desc); gboolean anjuta_preferences_register_property_raw (AnjutaPreferences *pr, GtkWidget *object, const gchar *key, const gchar *default_value, guint flags, AnjutaPropertyObjectType object_type, AnjutaPropertyDataType data_type); gboolean anjuta_preferences_register_property_custom (AnjutaPreferences *pr, GtkWidget *object, const gchar *key, const gchar *default_value, AnjutaPropertyDataType data_type, guint flags, void (*set_property) (AnjutaProperty *prop, const gchar *value), gchar * (*get_property) (AnjutaProperty *)); void anjuta_preferences_reset_defaults (AnjutaPreferences *pr); /* Calls the callback function for each of the properties with the flags * matching with the given filter */ void anjuta_preferences_foreach (AnjutaPreferences *pr, AnjutaPreferencesCallback callback, gpointer data); /* This will transfer all the properties values from the main properties database to the parent session properties database */ void anjuta_preferences_sync_to_session (AnjutaPreferences *pr); /* Sets the value (string) of a key */ void anjuta_preferences_set (AnjutaPreferences *pr, const gchar *key, const gchar *value); /* Sets the value (int) of a key */ void anjuta_preferences_set_int (AnjutaPreferences *pr, const gchar *key, const gint value); void anjuta_preferences_set_bool (AnjutaPreferences *pr, const gchar *key, const gboolean value); /* Gets the value (string) of a key */ /* Must free the return string */ gchar * anjuta_preferences_get (AnjutaPreferences *pr, const gchar *key); /* Gets the value (int) of a key. If not found, 0 is returned */ gint anjuta_preferences_get_int (AnjutaPreferences *pr, const gchar *key); gboolean anjuta_preferences_get_bool (AnjutaPreferences *pr, const gchar *key); /* Gets the value (int) of a key. If not found, the default_value is returned */ gint anjuta_preferences_get_int_with_default (AnjutaPreferences* pr, const gchar *key, gint default_value); gint anjuta_preferences_get_bool_with_default (AnjutaPreferences* pr, const gchar *key, gint default_value); gchar * anjuta_preferences_default_get (AnjutaPreferences *pr, const gchar *key); /* Gets the value (int) of a key */ gint anjuta_preferences_default_get_int (AnjutaPreferences *pr, const gchar *key); gint anjuta_preferences_default_get_bool (AnjutaPreferences *pr, const gchar *key); /* Dialog methods */ GtkWidget *anjuta_preferences_get_dialog (AnjutaPreferences *pr); gboolean anjuta_preferences_is_dialog_created (AnjutaPreferences *pr); /* Key notifications */ typedef void (*AnjutaPreferencesNotify) (AnjutaPreferences *pr, const gchar* key, const gchar* value, gpointer data); typedef void (*AnjutaPreferencesNotifyInt) (AnjutaPreferences *pr, const gchar* key, gint value, gpointer data); typedef void (*AnjutaPreferencesNotifyBool) (AnjutaPreferences *pr, const gchar* key, gboolean value, gpointer data); guint anjuta_preferences_notify_add_int (AnjutaPreferences *pr, const gchar *key, AnjutaPreferencesNotifyInt func, gpointer data, GFreeFunc destroy_notify); guint anjuta_preferences_notify_add_string (AnjutaPreferences *pr, const gchar *key, AnjutaPreferencesNotify func, gpointer data, GFreeFunc destroy_notify); guint anjuta_preferences_notify_add_bool (AnjutaPreferences *pr, const gchar *key, AnjutaPreferencesNotifyBool func, gpointer data, GFreeFunc destroy_notify); void anjuta_preferences_notify_remove (AnjutaPreferences *pr, guint notify_id); const gchar* anjuta_preferences_get_prefix (AnjutaPreferences *pr); G_END_DECLS #endif
abderrahim/anjuta
libanjuta/anjuta-preferences.h
C
gpl-2.0
9,795
#ifndef NEOGEO_H #define NEOGEO_H /* UPCB - Universal Programmed Controller Board Copyright (C) 2007 Marcus Post marcus@marcuspost.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* UPCB module for Neogeo support From GameSX.com: Pin Description - Pin Description 1 Common (GND)- 9 D Button 2 NC - 10 NC 3 Select - 11 Start 4 D Button - 12 C Button 5 B Button - 13 A Button 6 Right - 14 Left 7 Down - 15 Up 8 +5v - This is the commonly accepted pinout for the Neogeo, but Razoola has made it pretty clear that this isn't truly the case. The Neo-Geo uses a banking system similar to the Saturn and Genesis. The format is actually like this: Pin Description - Pin Description 1 Common (GND) - 9 Bank Select 2 2 Bank Select 1 - 10 Bank Select 3 3 Select - 11 Start 4 D Button - 12 C Button 5 B Button - 13 A Button 6 Right - 14 Left 7 Down - 15 Up 8 +5v - - - The game in the Neogeo controls which bank is checked. Each one of the pins listed as an A-D button or direction are actually the 8 data bit lines. Since the far majority of the games don't require anything more than the 4 directions, 4 buttons, Start and Select, they are rarely used but exist when more exotic controls are needed, such as Mahjong controllers, Irritating Maze trackball, dual sticks for Kizuna Encounter, etc. UPCB has no plans for supporting any of these inputs, so there is no need to detail them here. The banking is not used on the UPCB. The format used is a modified Neogeo pinout, that allows full use of the Neogeo system when directly connected, and also supports the two additional buttons so the UPCB can be used with project box setups and superguns. The pinout is like this: Pin Description - Pin Description 1 Common (GND) - 9 GND (For Neogeo system detection) 2 F Button (Roundhouse) - 10 E Button (Fierce) 3 Select - 11 Start 4 D Button (Forward) - 12 C Button (Strong) 5 B Button (Short) - 13 A Button (Jab) 6 Right - 14 Left 7 Down - 15 Up 8 +5v - - - For connecting to a NeoGeo system, hacking a cable is not required. A direct 15 pin extension cable will work perfectly. Because of the simplicity of the communication, many older systems are immediately supported by the UPCB using the NeoGeo module. Sega Mastersystem uses the same D-Sub 9 like almost every system in the 80's used, so just wire it up to the matching NeoGeo pins, make sure pin 9 on the UPCB side is connected to GND, and you're done. Like So: (Sega SG-1000/Mk3/Mastersystem pinout from GameSX.com) 1 Up 2 Down 3 Left 4 Right 5 +5v 6 Button I 7 NC 8 Common 9 Button II So making a UPCB cable for the Mastersystem is easy: D-Sub 15 Pin Mastersystem Pin 1 (GND) 8 (GND) 4 (Forward) 9 (Button 2) 5 (Short) 6 (Button 1) 6 (Right) 4 (Right) 7 (Down) 2 (Down) 8 (VCC) 5 (VCC) 9 Low (tied to ground) 14 (Left) 3 (Left) 15 (Up) 1 (Up) Short and Forward as used as Button 1 and Button 2 because they are the most comfortable to use in a two button situation. You can of course swap them with any button of you choice. The MSX and X68000 (two button) both use the same pinout, which is slightly different from the Mastersystem above. IF YOU INTEND ON MAKING A 9 PIN CABLE FOR ALL OF YOUR ANCIENT SYSTEMS, USE THE PINOUT ABOVE. ONLY USE THIS PINOUT IF YOU'RE SO HARD CORE YOU OWN A MSX, X68000 or FM-Towns! (data from GameSX.com) Pin Function 1 Up 2 Down 3 Left 4 Right 5 +5v 6 Button I 7 Button II 8 Out (?) //I'll ignore this until I get clarification WTF it is 9 Ground D-Sub 15 Pin MSX/X68000 Pin 1 (GND) 9 (GND) 4 (Forward) 7 (Button 2) 5 (Short) 6 (Button 1) 6 (Right) 4 (Right) 7 (Down) 2 (Down) 8 (VCC) 5 (VCC) 9 Low (tied to ground) 14 (Left) 3 (Left) 15 (Up) 1 (Up) The additional 2 buttons on the FM-Towns controller require a pair of diodes each, like this: D-Sub 15 Pin FM-Towns Pin 1 (GND) 9 (GND) 4 (Forward) 7 (Button 2) 5 (Short) 6 (Button 1) 6 (Right) 4 (Right) 7 (Down) 2 (Down) 8 (VCC) 5 (VCC) 9 Low (tied to ground) 14 (Left) 3 (Left) 15 (Up) 1 (Up) 11 (Start) ---|<|--- 2 (Down) 11 (Start) ---|<|--- 1 (Up) 3 (Select) ---|<|--- 4 (Right) 3 (Select) ---|<|--- 3 (Left) The information and pinouts available here are from usually reliable internet sources like GameSX.com, however they are UNTESTED. Please use with caution and always check with a multimeter. The only one tested by the auther is the NeoGeo, tested on a consolized MVS. */ #define Con_Neo_A LATCbits.LATC6 #define Con_Neo_B LATAbits.LATA5 #define Con_Neo_C LATBbits.LATB0 #define Con_Neo_D LATEbits.LATE0 #define Con_Neo_E LATBbits.LATB3 #define Con_Neo_F LATEbits.LATE2 #define Con_Neo_Start LATBbits.LATB2 #define Con_Neo_Select LATEbits.LATE1 #define Con_Neo_Up LATBbits.LATB1 #define Con_Neo_Down LATAbits.LATA2 #define Con_Neo_Left LATCbits.LATC7 #define Con_Neo_Right LATAbits.LATA3 /* Prototypes */ void NEOGEO_main(void); #endif //NEOGEO_H
fluxcorenz/UPCB
neogeo.h
C
gpl-2.0
5,629
<div class="wrap" id="of_container"> <h2 style="display:none"></h2> <div id="of-popup-save" class="of-save-popup"> <div class="of-save-save">Options Updated</div> </div> <div id="of-popup-reset" class="of-save-popup"> <div class="of-save-reset">Options Reset</div> </div> <div id="of-popup-fail" class="of-save-popup"> <div class="of-save-fail">Error!</div> </div> <span style="display: none;" id="hooks"><?php echo json_encode(of_get_header_classes_array()); ?></span> <input type="hidden" id="reset" value="<?php if(isset($_REQUEST['reset'])) echo $_REQUEST['reset']; ?>" /> <input type="hidden" id="security" name="security" value="<?php echo wp_create_nonce('of_ajax_nonce'); ?>" /> <form id="of_form" method="post" action="<?php echo esc_attr( $_SERVER['REQUEST_URI'] ) ?>" enctype="multipart/form-data" > <div id="header"> <div class="logo"> <h2><?php echo THEMENAME; ?></h2> </div> <div id="js-warning">Warning- This options panel will not work properly without javascript!</div> <div class="icon-option"></div> <div class="clear"></div> </div> <div id="info_bar"> <a> <div id="expand_options" class="expand">Expand</div> </a> <img style="display:none" src="<?php echo ADMIN_DIR; ?>assets/images/loading-bottom.gif" class="ajax-loading-img ajax-loading-img-bottom" alt="Working..." /> <!-- Start of Support Button --> <a href="http://bit.ly/1e0FkzU" target="blank"><button id="of_docs" type="button" class="button-primary" style="text-decoration: none;"> Buyer Support Forums </button></a> <!-- End of Support Button --> <!-- Start of Support Button --> <a href="http://bit.ly/1hjPhXZ" target="blank"><button id="of_docs" type="button" class="button-primary" style="text-decoration: none;"> Video Tutorials </button></a> <!-- End of Support Button --> <!-- Start of Support Button --> <a href="<?php echo get_template_directory_uri(); ?>/documentation/help.html" target="blank"><button id="of_docs" type="button" class="button-primary" style="text-decoration: none;"> Documentation </button></a> <!-- End of Support Button --> <button id="of_save" type="button" class="button-primary"> <?php _e('Save All Changes');?> </button> </div><!--.info_bar--> <div id="main"> <div id="of-nav"> <ul> <?php echo $options_machine->Menu ?> </ul> </div> <div id="content"> <?php echo $options_machine->Inputs /* Settings */ ?> </div> <div class="clear"></div> </div> <div class="save_bar"> <img style="display:none" src="<?php echo ADMIN_DIR; ?>assets/images/loading-bottom.gif" class="ajax-loading-img ajax-loading-img-bottom" alt="Working..." /> <button id ="of_save" type="button" class="button-primary"><?php _e('Save All Changes');?></button> <button id ="of_reset" type="button" class="button submit-button reset-button" ><?php _e('Options Reset');?></button> <img style="display:none" src="<?php echo ADMIN_DIR; ?>assets/images/loading-bottom.gif" class="ajax-reset-loading-img ajax-loading-img-bottom" alt="Working..." /> </div><!--.save_bar--> </form> <div style="clear:both;"></div> </div><!--wrap-->
m-godefroid76/devrestofactory
wp-content/themes/kingsize/admin/front-end/options.php
PHP
gpl-2.0
3,266
/********************************************************************** Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include <fc_config.h> #endif #include <stdio.h> #include <stdlib.h> #include <X11/Intrinsic.h> #include <X11/StringDefs.h> #include <X11/Xaw/Form.h> #include <X11/Xaw/Label.h> #include <X11/Xaw/Command.h> #include <X11/Xaw/MenuButton.h> #include <X11/Xaw/SimpleMenu.h> #include <X11/Xaw/SmeBSB.h> #include <X11/Xaw/List.h> #include <X11/Xaw/Viewport.h> #include <X11/Xaw/AsciiText.h> #include <X11/Xaw/Toggle.h> #include <X11/IntrinsicP.h> /* utility */ #include "bitvector.h" #include "fcintl.h" #include "log.h" #include "mem.h" #include "genlist.h" #include "shared.h" #include "support.h" /* common */ #include "city.h" #include "connection.h" /* can_conn_edit */ #include "game.h" #include "map.h" #include "packets.h" #include "player.h" #include "specialist.h" #include "traderoutes.h" #include "unitlist.h" /* client */ #include "client_main.h" #include "climap.h" #include "climisc.h" #include "control.h" /* request_xxx and unit_focus_set */ #include "options.h" #include "text.h" #include "tilespec.h" #include "cma_fec.h" #include "canvas.h" #include "cityrep.h" #include "cma_fe.h" #include "colors.h" #include "dialogs.h" #include "graphics.h" #include "gui_main.h" #include "gui_stuff.h" #include "helpdlg.h" #include "inputdlg.h" #include "mapctrl.h" #include "mapview.h" #include "optiondlg.h" /* for toggle_callback */ #include "pixcomm.h" #include "repodlgs.h" #include "wldlg.h" #include "citydlg_common.h" #include "citydlg.h" #define MIN_NUM_CITIZENS 22 #define MAX_NUM_CITIZENS 50 #define DEFAULT_NUM_CITIZENS 38 #define MIN_NUM_UNITS 8 #define MAX_NUM_UNITS 20 #define DEFAULT_NUM_UNITS 11 struct city_dialog { struct city *pcity; int num_citizens_shown; int num_units_shown; Widget shell; Widget main_form; Widget left_form; Widget cityname_label; Widget *citizen_labels; Widget production_label; Widget output_label; Widget storage_label; Widget pollution_label; Widget sub_form; Widget map_canvas; Widget sell_command; Widget close_command, rename_command, trade_command, activate_command; Widget show_units_command, cityopt_command, cma_command; Widget building_label, progress_label, buy_command, change_command, worklist_command, worklist_label; Widget improvement_viewport, improvement_list; Widget support_unit_label; Widget *support_unit_pixcomms; Widget support_unit_next_command; Widget support_unit_prev_command; Widget present_unit_label; Widget *present_unit_pixcomms; Widget present_unit_next_command; Widget present_unit_prev_command; Widget change_list; Widget rename_input; Widget worklist_shell; Impr_type_id sell_id; int support_unit_base; int present_unit_base; char improvlist_names[B_LAST+1][64]; char *improvlist_names_ptrs[B_LAST+1]; char *change_list_names_ptrs[B_LAST+1+U_LAST+1+1]; char change_list_names[B_LAST+1+U_LAST+1][200]; int change_list_ids[B_LAST+1+U_LAST+1]; int change_list_num_improvements; /*int is_modal;*/ }; #define SPECLIST_TAG dialog #define SPECLIST_TYPE struct city_dialog #include "speclist.h" #define dialog_list_iterate(dialoglist, pdialog) \ TYPED_LIST_ITERATE(struct city_dialog, dialoglist, pdialog) #define dialog_list_iterate_end LIST_ITERATE_END static struct dialog_list *dialog_list = NULL; static bool dialog_list_has_been_initialised = FALSE; static struct city_dialog *get_city_dialog(struct city *pcity); static struct city_dialog *create_city_dialog(struct city *pcity); static void close_city_dialog(struct city_dialog *pdialog); static void city_dialog_update_improvement_list(struct city_dialog *pdialog); static void city_dialog_update_title(struct city_dialog *pdialog); static void city_dialog_update_supported_units(struct city_dialog *pdialog, int id); static void city_dialog_update_present_units(struct city_dialog *pdialog, int id); static void city_dialog_update_citizens(struct city_dialog *pdialog); static void city_dialog_update_production(struct city_dialog *pdialog); static void city_dialog_update_output(struct city_dialog *pdialog); static void city_dialog_update_building(struct city_dialog *pdialog); static void city_dialog_update_storage(struct city_dialog *pdialog); static void city_dialog_update_pollution(struct city_dialog *pdialog); static void sell_callback(Widget w, XtPointer client_data, XtPointer call_data); static void buy_callback(Widget w, XtPointer client_data, XtPointer call_data); static void change_callback(Widget w, XtPointer client_data, XtPointer call_data); static void worklist_callback(Widget w, XtPointer client_data, XtPointer call_data); void commit_city_worklist(struct worklist *pwl, void *data); void cancel_city_worklist(void *data); static void close_callback(Widget w, XtPointer client_data, XtPointer call_data); static void rename_callback(Widget w, XtPointer client_data, XtPointer call_data); static void trade_callback(Widget w, XtPointer client_data, XtPointer call_data); static void activate_callback(Widget w, XtPointer client_data, XtPointer call_data); static void show_units_callback(Widget W, XtPointer client_data, XtPointer call_data); static void units_next_prev_callback(Widget W, XtPointer client_data, XtPointer call_data); static void unitupgrade_callback_yes(Widget w, XtPointer client_data, XtPointer call_data); static void unitupgrade_callback_no(Widget w, XtPointer client_data, XtPointer call_data); static void upgrade_callback(Widget w, XtPointer client_data, XtPointer call_data); static void disband_callback(Widget w, XtPointer client_data, XtPointer call_data); static void present_units_callback(Widget w, XtPointer client_data, XtPointer call_data); static void cityopt_callback(Widget w, XtPointer client_data, XtPointer call_data); static void cma_callback(Widget w, XtPointer client_data, XtPointer call_data); static void popdown_cityopt_dialog(void); /**************************************************************** ... *****************************************************************/ static void get_contents_of_pollution(struct city_dialog *pdialog, char *retbuf, int n) { struct city *pcity; int pollution=0; int corruption=0; int waste=0; int illness=0; char buf[512]; if (pdialog) { pcity=pdialog->pcity; corruption=pcity->waste[O_TRADE]; waste=pcity->waste[O_SHIELD]; pollution=pcity->pollution; if (!game.info.illness_on) { fc_snprintf(buf, sizeof(buf), " -.-"); } else { illness = city_illness_calc(pcity, NULL, NULL, NULL, NULL); /* illness is in tenth of percent */ fc_snprintf(buf, sizeof(buf), "%4.1f", (float)illness / 10.0); } } fc_snprintf(retbuf, n, _("Corruption: %4d\n" "Waste: %4d\n" "Pollution: %4d\n" "Plague Risk: %s"), corruption, waste, pollution, buf); } /**************************************************************** ... *****************************************************************/ static void get_contents_of_storage(struct city_dialog *pdialog, char *retbuf, int n) { struct city *pcity; int foodstock=0; int foodbox=0; int granaryturns=0; char buf[512]; if (pdialog) { pcity=pdialog->pcity; foodstock=pcity->food_stock; foodbox=city_granary_size(city_size_get(pcity)); granaryturns = city_turns_to_grow(pcity); if (granaryturns == 0) { fc_snprintf(buf, sizeof(buf), _("blocked")); } else if (granaryturns == FC_INFINITY) { fc_snprintf(buf, sizeof(buf), _("never")); } else { /* A negative value means we'll have famine in that many turns. But that's handled down below. */ fc_snprintf(buf, sizeof(buf), PL_("%d turn", "%d turns", abs(granaryturns)), abs(granaryturns)); } } /* We used to mark cities with a granary with a "*" here. */ fc_snprintf(retbuf, n, _("Granary: %3d/%-3d\n" "Change in: %s"), foodstock, foodbox, buf); } /**************************************************************** ... *****************************************************************/ static void get_contents_of_production(struct city_dialog *pdialog, char *retbuf, int n) { struct city *pcity; int foodprod=0; int foodsurplus=0; int shieldprod=0; int shieldsurplus=0; int tradeprod=0; int tradesurplus=0; if (pdialog) { pcity=pdialog->pcity; foodprod=pcity->prod[O_FOOD]; foodsurplus = pcity->surplus[O_FOOD]; shieldprod=pcity->prod[O_SHIELD] + pcity->waste[O_SHIELD]; shieldsurplus = pcity->surplus[O_SHIELD]; tradeprod = pcity->surplus[O_TRADE] + pcity->waste[O_TRADE]; tradesurplus = pcity->surplus[O_TRADE]; } fc_snprintf(retbuf, n, _("Food: %3d (%+-4d)\n" "Prod: %3d (%+-4d)\n" "Trade: %3d (%+-4d)"), foodprod, foodsurplus, shieldprod, shieldsurplus, tradeprod, tradesurplus); } /**************************************************************** ... *****************************************************************/ static void get_contents_of_output(struct city_dialog *pdialog, char *retbuf, int n) { struct city *pcity; int goldtotal=0; int goldsurplus=0; int luxtotal=0; int scitotal=0; if (pdialog) { pcity=pdialog->pcity; goldtotal=pcity->prod[O_GOLD]; goldsurplus = pcity->surplus[O_GOLD]; luxtotal=pcity->prod[O_LUXURY]; scitotal=pcity->prod[O_SCIENCE]; } fc_snprintf(retbuf, n, _("Gold: %3d (%+-4d)\n" "Lux: %3d\n" "Sci: %3d"), goldtotal, goldsurplus, luxtotal, scitotal); } /**************************************************************** ... *****************************************************************/ static void get_contents_of_progress(struct city_dialog *pdialog, char *retbuf, int n) { get_city_dialog_production(pdialog ? pdialog->pcity : NULL, retbuf, n); } /**************************************************************** ... *****************************************************************/ static void get_contents_of_worklist(struct city_dialog *pdialog, char *retbuf, int n) { struct city *pcity = pdialog ? pdialog->pcity : NULL; if (pcity && worklist_is_empty(&pcity->worklist)) { fc_strlcpy(retbuf, _("(is empty)"), n); } else { fc_strlcpy(retbuf, _("(in prog.)"), n); } } /**************************************************************** ... *****************************************************************/ struct city_dialog *get_city_dialog(struct city *pcity) { if (!dialog_list_has_been_initialised) { dialog_list = dialog_list_new(); dialog_list_has_been_initialised = TRUE; } dialog_list_iterate(dialog_list, pdialog) { if (pdialog->pcity == pcity) { return pdialog; } } dialog_list_iterate_end; return NULL; } /**************************************************************** ... *****************************************************************/ bool city_dialog_is_open(struct city *pcity) { return get_city_dialog(pcity) != NULL; } /**************************************************************** ... *****************************************************************/ void real_city_dialog_refresh(struct city *pcity) { struct city_dialog *pdialog; if((pdialog=get_city_dialog(pcity))) { struct canvas store = {XtWindow(pdialog->map_canvas)}; city_dialog_update_improvement_list(pdialog); city_dialog_update_title(pdialog); city_dialog_update_supported_units(pdialog, 0); city_dialog_update_present_units(pdialog, 0); city_dialog_update_citizens(pdialog); city_dialog_redraw_map(pdialog->pcity, &store); city_dialog_update_production(pdialog); city_dialog_update_output(pdialog); city_dialog_update_building(pdialog); city_dialog_update_storage(pdialog); city_dialog_update_pollution(pdialog); XtSetSensitive(pdialog->trade_command, city_num_trade_routes(pcity)?True:False); XtSetSensitive(pdialog->activate_command, unit_list_size(pcity->tile->units) ?True:False); XtSetSensitive(pdialog->show_units_command, unit_list_size(pcity->tile->units) ?True:False); XtSetSensitive(pdialog->cma_command, True); XtSetSensitive(pdialog->cityopt_command, True); } if (NULL == client.conn.playing || city_owner(pcity) == client.conn.playing) { city_report_dialog_update_city(pcity); economy_report_dialog_update(); } else { if (pdialog) { /* Set the buttons we do not want live while a Diplomat investigates */ XtSetSensitive(pdialog->buy_command, FALSE); XtSetSensitive(pdialog->change_command, FALSE); XtSetSensitive(pdialog->worklist_command, FALSE); XtSetSensitive(pdialog->sell_command, FALSE); XtSetSensitive(pdialog->rename_command, FALSE); XtSetSensitive(pdialog->activate_command, FALSE); XtSetSensitive(pdialog->show_units_command, FALSE); XtSetSensitive(pdialog->cma_command, FALSE); XtSetSensitive(pdialog->cityopt_command, FALSE); } } } /************************************************************************** Updates supported and present units views in city dialogs for given unit **************************************************************************/ void refresh_unit_city_dialogs(struct unit *punit) { struct city *pcity_sup, *pcity_pre; struct city_dialog *pdialog; pcity_sup = player_city_by_number(client_player(), punit->homecity); pcity_pre=tile_city(unit_tile(punit)); if(pcity_sup && (pdialog=get_city_dialog(pcity_sup))) city_dialog_update_supported_units(pdialog, 0); if(pcity_pre && (pdialog=get_city_dialog(pcity_pre))) city_dialog_update_present_units(pdialog, 0); } /**************************************************************** popup the dialog 10% inside the main-window *****************************************************************/ void real_city_dialog_popup(struct city *pcity) { struct city_dialog *pdialog; if(!(pdialog=get_city_dialog(pcity))) pdialog=create_city_dialog(pcity); xaw_set_relative_position(toplevel, pdialog->shell, 10, 10); XtPopup(pdialog->shell, XtGrabNone); } /**************************************************************** popdown the dialog *****************************************************************/ void popdown_city_dialog(struct city *pcity) { struct city_dialog *pdialog; if((pdialog=get_city_dialog(pcity))) close_city_dialog(pdialog); } /**************************************************************** popdown all dialogs *****************************************************************/ void popdown_all_city_dialogs(void) { if(!dialog_list_has_been_initialised) { return; } while (dialog_list_size(dialog_list) > 0) { close_city_dialog(dialog_list_get(dialog_list, 0)); } popdown_cityopt_dialog(); popdown_cma_dialog(); } /**************************************************************** ... *****************************************************************/ static void city_map_canvas_expose(Widget w, XEvent *event, Region exposed, void *client_data) { struct city_dialog *pdialog = client_data; struct canvas store = {XtWindow(pdialog->map_canvas)}; city_dialog_redraw_map(pdialog->pcity, &store); } /**************************************************************** ... *****************************************************************/ #define LAYOUT_DEBUG 0 struct city_dialog *create_city_dialog(struct city *pcity) { char *dummy_improvement_list[]={ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "2", "3", "4", "5", "6", "7", "8", "9", 0 }; int i, itemWidth; struct city_dialog *pdialog; char lblbuf[512]; Widget first_citizen, first_support, first_present; XtWidgetGeometry geom; Dimension widthTotal; Dimension widthCitizen, borderCitizen, internalCitizen, spaceCitizen; Dimension widthUnit, borderUnit, internalUnit, spaceUnit; Dimension widthNext, borderNext, internalNext, spaceNext; Dimension widthPrev, borderPrev, internalPrev, spacePrev; Widget relative; enum citizen_category c = CITIZEN_SPECIALIST + DEFAULT_SPECIALIST; if (tileset_tile_height(tileset)<45) dummy_improvement_list[5]=0; if (concise_city_production) { dummy_improvement_list[0] = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"; } pdialog=fc_malloc(sizeof(struct city_dialog)); pdialog->pcity=pcity; pdialog->support_unit_base=0; pdialog->present_unit_base=0; pdialog->worklist_shell = NULL; pdialog->shell= XtVaCreatePopupShell(city_name(pcity), /* make_modal ? transientShellWidgetClass :*/ topLevelShellWidgetClass, toplevel, XtNallowShellResize, True, NULL); pdialog->main_form= XtVaCreateManagedWidget("citymainform", formWidgetClass, pdialog->shell, NULL); pdialog->cityname_label= XtVaCreateManagedWidget("citynamelabel", labelWidgetClass, pdialog->main_form, NULL); first_citizen= XtVaCreateManagedWidget("citizenlabels", commandWidgetClass, pdialog->main_form, XtNfromVert, pdialog->cityname_label, XtNbitmap, get_citizen_pixmap(c, 0, pcity), NULL); pdialog->sub_form= XtVaCreateManagedWidget("citysubform", formWidgetClass, pdialog->main_form, XtNfromVert, (XtArgVal)first_citizen, NULL); pdialog->left_form= XtVaCreateManagedWidget("cityleftform", formWidgetClass, pdialog->sub_form, NULL); get_contents_of_production(NULL, lblbuf, sizeof(lblbuf)); pdialog->production_label= XtVaCreateManagedWidget("cityprodlabel", labelWidgetClass, pdialog->left_form, XtNlabel, lblbuf, NULL); get_contents_of_output(NULL, lblbuf, sizeof(lblbuf)); pdialog->output_label= XtVaCreateManagedWidget("cityoutputlabel", labelWidgetClass, pdialog->left_form, XtNlabel, lblbuf, XtNfromVert, (XtArgVal)pdialog->production_label, NULL); get_contents_of_storage(NULL, lblbuf, sizeof(lblbuf)); pdialog->storage_label= XtVaCreateManagedWidget("citystoragelabel", labelWidgetClass, pdialog->left_form, XtNlabel, lblbuf, XtNfromVert, (XtArgVal)pdialog->output_label, NULL); get_contents_of_pollution(NULL, lblbuf, sizeof(lblbuf)); pdialog->pollution_label= XtVaCreateManagedWidget("citypollutionlabel", labelWidgetClass, pdialog->left_form, XtNlabel, lblbuf, XtNfromVert, (XtArgVal)pdialog->storage_label, NULL); pdialog->map_canvas= XtVaCreateManagedWidget("citymapcanvas", xfwfcanvasWidgetClass, pdialog->sub_form, "exposeProc", (XtArgVal)city_map_canvas_expose, "exposeProcData", (XtArgVal)pdialog, XtNfromHoriz, (XtArgVal)pdialog->left_form, XtNwidth, get_citydlg_canvas_width(), XtNheight, get_citydlg_canvas_height(), NULL); pdialog->building_label= XtVaCreateManagedWidget("citybuildinglabel", labelWidgetClass, pdialog->sub_form, XtNfromHoriz, (XtArgVal)pdialog->map_canvas, XtNlabel, concise_city_production ? "XXXXXXXXXXXXXXXXXXXXXXXXXXXX" : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", NULL); get_contents_of_progress(NULL, lblbuf, sizeof(lblbuf)); pdialog->progress_label= XtVaCreateManagedWidget("cityprogresslabel", labelWidgetClass, pdialog->sub_form, XtNfromHoriz, (XtArgVal)pdialog->map_canvas, XtNfromVert, pdialog->building_label, XtNlabel, lblbuf, NULL); pdialog->buy_command= I_L(XtVaCreateManagedWidget("citybuycommand", commandWidgetClass, pdialog->sub_form, XtNfromVert, pdialog->building_label, XtNfromHoriz, pdialog->progress_label, NULL)); pdialog->change_command= I_L(XtVaCreateManagedWidget("citychangecommand", commandWidgetClass, pdialog->sub_form, XtNfromVert, pdialog->building_label, XtNfromHoriz, pdialog->buy_command, NULL)); pdialog->improvement_viewport= XtVaCreateManagedWidget("cityimprovview", viewportWidgetClass, pdialog->sub_form, XtNfromHoriz, (XtArgVal)pdialog->map_canvas, XtNfromVert, pdialog->change_command, NULL); pdialog->improvement_list= XtVaCreateManagedWidget("cityimprovlist", listWidgetClass, pdialog->improvement_viewport, XtNforceColumns, 1, XtNdefaultColumns,1, XtNlist, (XtArgVal)dummy_improvement_list, XtNverticalList, False, NULL); pdialog->sell_command= I_L(XtVaCreateManagedWidget("citysellcommand", commandWidgetClass, pdialog->sub_form, XtNfromVert, pdialog->improvement_viewport, XtNfromHoriz, (XtArgVal)pdialog->map_canvas, NULL)); pdialog->worklist_command= I_L(XtVaCreateManagedWidget("cityworklistcommand", commandWidgetClass, pdialog->sub_form, XtNfromVert, pdialog->improvement_viewport, XtNfromHoriz, pdialog->sell_command, NULL)); get_contents_of_worklist(NULL, lblbuf, sizeof(lblbuf)); pdialog->worklist_label= XtVaCreateManagedWidget("cityworklistlabel", labelWidgetClass, pdialog->sub_form, XtNfromVert, pdialog->improvement_viewport, XtNfromHoriz, pdialog->worklist_command, XtNlabel, lblbuf, NULL); pdialog->support_unit_label= I_L(XtVaCreateManagedWidget("supportunitlabel", labelWidgetClass, pdialog->main_form, XtNfromVert, pdialog->sub_form, NULL)); first_support= XtVaCreateManagedWidget("supportunitcanvas", pixcommWidgetClass, pdialog->main_form, XtNfromVert, pdialog->support_unit_label, XtNwidth, tileset_full_tile_width(tileset), XtNheight, 3 * tileset_tile_height(tileset) / 2, NULL); pdialog->present_unit_label= I_L(XtVaCreateManagedWidget("presentunitlabel", labelWidgetClass, pdialog->main_form, XtNfromVert, first_support, NULL)); first_present= XtVaCreateManagedWidget("presentunitcanvas", pixcommWidgetClass, pdialog->main_form, XtNfromVert, pdialog->present_unit_label, XtNwidth, tileset_full_tile_width(tileset), XtNheight, tileset_full_tile_height(tileset), NULL); pdialog->support_unit_next_command= XtVaCreateManagedWidget("supportunitnextcommand", commandWidgetClass, pdialog->main_form, NULL); pdialog->support_unit_prev_command= XtVaCreateManagedWidget("supportunitprevcommand", commandWidgetClass, pdialog->main_form, NULL); pdialog->present_unit_next_command= XtVaCreateManagedWidget("presentunitnextcommand", commandWidgetClass, pdialog->main_form, NULL); pdialog->present_unit_prev_command= XtVaCreateManagedWidget("presentunitprevcommand", commandWidgetClass, pdialog->main_form, NULL); pdialog->close_command= I_L(XtVaCreateManagedWidget("cityclosecommand", commandWidgetClass, pdialog->main_form, XtNfromVert, first_present, NULL)); pdialog->rename_command= I_L(XtVaCreateManagedWidget("cityrenamecommand", commandWidgetClass, pdialog->main_form, XtNfromVert, first_present, XtNfromHoriz, pdialog->close_command, NULL)); pdialog->trade_command= I_L(XtVaCreateManagedWidget("citytradecommand", commandWidgetClass, pdialog->main_form, XtNfromVert, first_present, XtNfromHoriz, pdialog->rename_command, NULL)); pdialog->activate_command= I_L(XtVaCreateManagedWidget("cityactivatecommand", commandWidgetClass, pdialog->main_form, XtNfromVert, first_present, XtNfromHoriz, pdialog->trade_command, NULL)); pdialog->show_units_command= I_L(XtVaCreateManagedWidget("cityshowunitscommand", commandWidgetClass, pdialog->main_form, XtNfromVert, first_present, XtNfromHoriz, pdialog->activate_command, NULL)); pdialog->cma_command = I_L(XtVaCreateManagedWidget("cmacommand", commandWidgetClass, pdialog->main_form, XtNfromVert, first_present, XtNfromHoriz, pdialog->show_units_command, NULL)); pdialog->cityopt_command= I_L(XtVaCreateManagedWidget("cityoptionscommand", commandWidgetClass, pdialog->main_form, XtNfromVert, first_present, XtNfromHoriz, pdialog->cma_command, NULL)); XtRealizeWidget(pdialog->shell); XtQueryGeometry (pdialog->sub_form, NULL, &geom); widthTotal=geom.width; if (widthTotal>0) { XtQueryGeometry (first_citizen, NULL, &geom); widthCitizen=geom.width; borderCitizen=geom.border_width; XtVaGetValues(first_citizen, XtNinternalWidth, &internalCitizen, XtNhorizDistance, &spaceCitizen, NULL); XtQueryGeometry (first_support, NULL, &geom); widthUnit=geom.width; borderUnit=geom.border_width; XtVaGetValues(first_support, XtNinternalWidth, &internalUnit, XtNhorizDistance, &spaceUnit, NULL); XtQueryGeometry (pdialog->support_unit_next_command, NULL, &geom); widthNext=geom.width; borderNext=geom.border_width; XtVaGetValues(pdialog->support_unit_next_command, XtNinternalWidth, &internalNext, XtNhorizDistance, &spaceNext, NULL); XtQueryGeometry (pdialog->support_unit_prev_command, NULL, &geom); widthPrev=geom.width; borderPrev=geom.border_width; XtVaGetValues(pdialog->support_unit_prev_command, XtNinternalWidth, &internalPrev, XtNhorizDistance, &spacePrev, NULL); #if LAYOUT_DEBUG >= 3 printf ( "T: w: %d\n" "C: wbis: %d %d %d %d\n" "U: wbis: %d %d %d %d\n" "N: wbis: %d %d %d %d\n" "P: wbis: %d %d %d %d\n" , widthTotal, widthCitizen, borderCitizen, internalCitizen, spaceCitizen, widthUnit, borderUnit, internalUnit, spaceUnit, widthNext, borderNext, internalNext, spaceNext, widthPrev, borderPrev, internalPrev, spacePrev ); #endif itemWidth=widthCitizen+2*borderCitizen+2*internalCitizen+spaceCitizen; if (itemWidth>0) { pdialog->num_citizens_shown=widthTotal/itemWidth; if (pdialog->num_citizens_shown<MIN_NUM_CITIZENS) pdialog->num_citizens_shown=MIN_NUM_CITIZENS; else if (pdialog->num_citizens_shown>MAX_NUM_CITIZENS) pdialog->num_citizens_shown=MAX_NUM_CITIZENS; } else { pdialog->num_citizens_shown=MIN_NUM_CITIZENS; } #if LAYOUT_DEBUG >= 2 printf ( "C: wT iW nC: %d %d %d\n" , widthTotal, itemWidth, pdialog->num_citizens_shown ); #endif if (widthNext<widthPrev) widthNext=widthPrev; if (borderNext<borderPrev) borderNext=borderPrev; if (internalNext<internalPrev) internalNext=internalPrev; if (spaceNext<spacePrev) spaceNext=spacePrev; widthTotal-=(widthNext+2*borderNext+2*internalNext+spaceNext); itemWidth=widthUnit+2*borderUnit+2*internalUnit+spaceUnit; if (itemWidth>0) { pdialog->num_units_shown=widthTotal/itemWidth; if (pdialog->num_units_shown<MIN_NUM_UNITS) pdialog->num_units_shown=MIN_NUM_UNITS; else if (pdialog->num_units_shown>MAX_NUM_UNITS) pdialog->num_units_shown=MAX_NUM_UNITS; } else { pdialog->num_units_shown=MIN_NUM_UNITS; } #if LAYOUT_DEBUG >= 2 printf ( "U: wT iW nU: %d %d %d\n" , widthTotal, itemWidth, pdialog->num_units_shown ); #endif } else { pdialog->num_citizens_shown=DEFAULT_NUM_CITIZENS; pdialog->num_units_shown=DEFAULT_NUM_UNITS; if (tileset_tile_height(tileset)<45) { pdialog->num_citizens_shown-=5; pdialog->num_units_shown+=3; } } #if LAYOUT_DEBUG >= 1 printf ( "nC nU: %d %d\n" , pdialog->num_citizens_shown, pdialog->num_units_shown ); #endif pdialog->citizen_labels= fc_malloc(pdialog->num_citizens_shown * sizeof(Widget)); pdialog->support_unit_pixcomms= fc_malloc(pdialog->num_units_shown * sizeof(Widget)); pdialog->present_unit_pixcomms= fc_malloc(pdialog->num_units_shown * sizeof(Widget)); pdialog->citizen_labels[0]=first_citizen; for(i=1; i<pdialog->num_citizens_shown; i++) pdialog->citizen_labels[i]= XtVaCreateManagedWidget("citizenlabels", commandWidgetClass, pdialog->main_form, XtNfromVert, pdialog->cityname_label, XtNfromHoriz, (XtArgVal)pdialog->citizen_labels[i-1], XtNbitmap, get_citizen_pixmap(c, 0, pcity), NULL); pdialog->support_unit_pixcomms[0]=first_support; for(i=1; i<pdialog->num_units_shown; i++) { pdialog->support_unit_pixcomms[i]= XtVaCreateManagedWidget("supportunitcanvas", pixcommWidgetClass, pdialog->main_form, XtNfromVert, pdialog->support_unit_label, XtNfromHoriz, (XtArgVal)pdialog->support_unit_pixcomms[i-1], XtNwidth, tileset_full_tile_width(tileset), XtNheight, 3 * tileset_tile_height(tileset) / 2, NULL); } relative=pdialog->support_unit_pixcomms[pdialog->num_units_shown-1]; XtVaSetValues(pdialog->support_unit_next_command, XtNfromVert, pdialog->support_unit_label, XtNfromHoriz, (XtArgVal)relative, NULL); XtVaSetValues(pdialog->support_unit_prev_command, XtNfromVert, pdialog->support_unit_next_command, XtNfromHoriz, (XtArgVal)relative, NULL); pdialog->present_unit_pixcomms[0]=first_present; for(i=1; i<pdialog->num_units_shown; i++) { pdialog->present_unit_pixcomms[i]= XtVaCreateManagedWidget("presentunitcanvas", pixcommWidgetClass, pdialog->main_form, XtNfromVert, pdialog->present_unit_label, XtNfromHoriz, (XtArgVal)pdialog->support_unit_pixcomms[i-1], XtNwidth, tileset_full_tile_width(tileset), XtNheight, tileset_full_tile_height(tileset), NULL); } relative=pdialog->present_unit_pixcomms[pdialog->num_units_shown-1]; XtVaSetValues(pdialog->present_unit_next_command, XtNfromVert, pdialog->present_unit_label, XtNfromHoriz, (XtArgVal)relative, NULL); XtVaSetValues(pdialog->present_unit_prev_command, XtNfromVert, pdialog->present_unit_next_command, XtNfromHoriz, (XtArgVal)relative, NULL); /* FIXME: this ignores the mask. */ XtVaSetValues(pdialog->shell, XtNiconPixmap, get_icon_sprite(tileset, ICON_CITYDLG), NULL); XtAddCallback(pdialog->sell_command, XtNcallback, sell_callback, (XtPointer)pdialog); XtAddCallback(pdialog->buy_command, XtNcallback, buy_callback, (XtPointer)pdialog); XtAddCallback(pdialog->change_command, XtNcallback, change_callback, (XtPointer)pdialog); XtAddCallback(pdialog->worklist_command, XtNcallback, worklist_callback, (XtPointer)pdialog); XtAddCallback(pdialog->close_command, XtNcallback, close_callback, (XtPointer)pdialog); XtAddCallback(pdialog->rename_command, XtNcallback, rename_callback, (XtPointer)pdialog); XtAddCallback(pdialog->trade_command, XtNcallback, trade_callback, (XtPointer)pdialog); XtAddCallback(pdialog->activate_command, XtNcallback, activate_callback, (XtPointer)pdialog); XtAddCallback(pdialog->show_units_command, XtNcallback, show_units_callback, (XtPointer)pdialog); XtAddCallback(pdialog->support_unit_next_command, XtNcallback, units_next_prev_callback, (XtPointer)pdialog); XtAddCallback(pdialog->support_unit_prev_command, XtNcallback, units_next_prev_callback, (XtPointer)pdialog); XtAddCallback(pdialog->present_unit_next_command, XtNcallback, units_next_prev_callback, (XtPointer)pdialog); XtAddCallback(pdialog->present_unit_prev_command, XtNcallback, units_next_prev_callback, (XtPointer)pdialog); XtAddCallback(pdialog->cityopt_command, XtNcallback, cityopt_callback, (XtPointer)pdialog); XtAddCallback(pdialog->cma_command, XtNcallback, cma_callback, (XtPointer)pdialog); dialog_list_prepend(dialog_list, pdialog); for(i=0; i<B_LAST+1; i++) pdialog->improvlist_names_ptrs[i]=0; XtRealizeWidget(pdialog->shell); real_city_dialog_refresh(pdialog->pcity); /* if(make_modal) XtSetSensitive(toplevel, FALSE); pdialog->is_modal=make_modal; */ XSetWMProtocols(display, XtWindow(pdialog->shell), &wm_delete_window, 1); XtOverrideTranslations(pdialog->shell, XtParseTranslationTable ("<Message>WM_PROTOCOLS: msg-close-city()")); XtSetKeyboardFocus(pdialog->shell, pdialog->close_command); return pdialog; } /**************************************************************** ... *****************************************************************/ void activate_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog = (struct city_dialog *)client_data; activate_all_units(pdialog->pcity->tile); } /**************************************************************** ... *****************************************************************/ void show_units_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog = (struct city_dialog *)client_data; struct tile *ptile = pdialog->pcity->tile; if( unit_list_size(ptile->units) ) unit_select_dialog_popup(ptile); } /**************************************************************** ... *****************************************************************/ void units_next_prev_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog = (struct city_dialog *)client_data; if (w==pdialog->support_unit_next_command) { (pdialog->support_unit_base)++; city_dialog_update_supported_units(pdialog, 0); } else if (w==pdialog->support_unit_prev_command) { (pdialog->support_unit_base)--; city_dialog_update_supported_units(pdialog, 0); } else if (w==pdialog->present_unit_next_command) { (pdialog->present_unit_base)++; city_dialog_update_present_units(pdialog, 0); } else if (w==pdialog->present_unit_prev_command) { (pdialog->present_unit_base)--; city_dialog_update_present_units(pdialog, 0); } } #ifdef UNUSED /**************************************************************** ... *****************************************************************/ static void present_units_ok_callback(Widget w, XtPointer client_data, XtPointer call_data) { destroy_message_dialog(w); } #endif /**************************************************************** ... *****************************************************************/ static void present_units_activate_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); if (NULL != punit) { struct city *pcity = tile_city(unit_tile(punit)); unit_focus_set(punit); if (NULL != pcity) { struct city_dialog *pdialog = get_city_dialog(pcity); if (NULL != pdialog) { city_dialog_update_present_units(pdialog, 0); } } } destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ static void supported_units_activate_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); if (NULL != punit) { struct city *pcity = tile_city(unit_tile(punit)); unit_focus_set(punit); if (NULL != pcity) { struct city_dialog *pdialog = get_city_dialog(pcity); if (NULL != pdialog) { city_dialog_update_supported_units(pdialog, 0); } } } destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ static void present_units_activate_close_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); destroy_message_dialog(w); if (NULL != punit) { struct city *pcity = tile_city(unit_tile(punit)); unit_focus_set(punit); if (NULL != pcity) { struct city_dialog *pdialog = get_city_dialog(pcity); if (NULL != pdialog) { close_city_dialog(pdialog); } } } } /**************************************************************** ... *****************************************************************/ static void supported_units_activate_close_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); destroy_message_dialog(w); if (NULL != punit) { struct city *pcity = player_city_by_number(client_player(), punit->homecity); unit_focus_set(punit); if (NULL != pcity) { struct city_dialog *pdialog = get_city_dialog(pcity); if (NULL != pdialog) { close_city_dialog(pdialog); } } } } /**************************************************************** ... *****************************************************************/ static void present_units_sentry_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); if (NULL != punit) { request_unit_sentry(punit); } destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ static void present_units_fortify_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); if (NULL != punit) { request_unit_fortify(punit); } destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ static void present_units_homecity_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); if (NULL != punit) { request_unit_change_homecity(punit); } destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ static void present_units_cancel_callback(Widget w, XtPointer client_data, XtPointer call_data) { destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ void present_units_callback(Widget w, XtPointer client_data, XtPointer call_data) { Widget wd; struct city_dialog *pdialog; struct city *pcity; XEvent *e = (XEvent*)call_data; struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); if ((NULL != punit || (can_conn_edit(&client.conn) && NULL == client.conn.playing && (punit = game_unit_by_number((size_t) client_data)))) && (pcity = tile_city(unit_tile(punit))) && (pdialog = get_city_dialog(pcity))) { if(e->type==ButtonRelease && e->xbutton.button==Button2) { unit_focus_set(punit); close_city_dialog(pdialog); return; } if(e->type==ButtonRelease && e->xbutton.button==Button3) { unit_focus_set(punit); return; } wd=popup_message_dialog(pdialog->shell, "presentunitsdialog", unit_description(punit), present_units_activate_callback, punit->id, 1, present_units_activate_close_callback, punit->id, 1, present_units_sentry_callback, punit->id, 1, present_units_fortify_callback, punit->id, 1, disband_callback, punit->id, 1, present_units_homecity_callback, punit->id, 1, upgrade_callback, punit->id, 1, present_units_cancel_callback, 0, 0, NULL); if (punit->activity == ACTIVITY_SENTRY || !can_unit_do_activity(punit, ACTIVITY_SENTRY)) { XtSetSensitive(XtNameToWidget(wd, "*button2"), FALSE); } if (punit->activity == ACTIVITY_FORTIFYING || !can_unit_do_activity(punit, ACTIVITY_FORTIFYING)) { XtSetSensitive(XtNameToWidget(wd, "*button3"), FALSE); } if (unit_has_type_flag(punit, UTYF_UNDISBANDABLE)) { XtSetSensitive(XtNameToWidget(wd, "*button4"), FALSE); } if (punit->homecity == pcity->id) { XtSetSensitive(XtNameToWidget(wd, "*button5"), FALSE); } if (NULL == client.conn.playing || (NULL == can_upgrade_unittype(client.conn.playing, unit_type(punit)))) { XtSetSensitive(XtNameToWidget(wd, "*button6"), FALSE); } } } /**************************************************************** ... *****************************************************************/ static void rename_city_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog = client_data; if (pdialog) { city_rename(pdialog->pcity, input_dialog_get_input(w)); } input_dialog_destroy(w); } /**************************************************************** ... *****************************************************************/ void rename_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog; pdialog=(struct city_dialog *)client_data; input_dialog_create(pdialog->shell, "shellrenamecity", _("What should we rename the city to?"), city_name(pdialog->pcity), rename_city_callback, (XtPointer)pdialog, rename_city_callback, (XtPointer)0); } /**************************************************************** ... *****************************************************************/ static void trade_message_dialog_callback(Widget w, XtPointer client_data, XtPointer call_data) { destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ void trade_callback(Widget w, XtPointer client_data, XtPointer call_data) { int i; int x=0,total=0; char buf[512], *bptr=buf; int nleft = sizeof(buf); struct city_dialog *pdialog; pdialog=(struct city_dialog *)client_data; fc_snprintf(buf, sizeof(buf), _("These trade routes have been established with %s:\n"), city_name(pdialog->pcity)); bptr = end_of_strn(bptr, &nleft); for (i = 0; i < MAX_TRADE_ROUTES; i++) if(pdialog->pcity->trade[i]) { struct city *pcity; x=1; total+=pdialog->pcity->trade_value[i]; if ((pcity = game_city_by_number(pdialog->pcity->trade[i]))) { fc_snprintf(bptr, nleft, _("%32s: %2d Trade/Year\n"), city_name(pcity), pdialog->pcity->trade_value[i]); bptr = end_of_strn(bptr, &nleft); } else { fc_snprintf(bptr, nleft, _("%32s: %2d Trade/Year\n"), _("Unknown"), pdialog->pcity->trade_value[i]); bptr = end_of_strn(bptr, &nleft); } } if (!x) { fc_strlcpy(bptr, _("No trade routes exist.\n"), nleft); } else { fc_snprintf(bptr, nleft, _("\nTotal trade %d Trade/Year\n"), total); } popup_message_dialog(pdialog->shell, "citytradedialog", buf, trade_message_dialog_callback, 0, 0, NULL); } /**************************************************************** ... *****************************************************************/ void city_dialog_update_pollution(struct city_dialog *pdialog) { char buf[512]; get_contents_of_pollution(pdialog, buf, sizeof(buf)); xaw_set_label(pdialog->pollution_label, buf); } /**************************************************************** ... *****************************************************************/ void city_dialog_update_storage(struct city_dialog *pdialog) { char buf[512]; get_contents_of_storage(pdialog, buf, sizeof(buf)); xaw_set_label(pdialog->storage_label, buf); } /**************************************************************** ... *****************************************************************/ void city_dialog_update_building(struct city_dialog *pdialog) { char buf[32]; struct city *pcity=pdialog->pcity; XtSetSensitive(pdialog->buy_command, city_can_buy(pcity)); /* FIXME: Should not pass NULL as improvement * to test_player_sell_building_now(). It skips many tests. */ XtSetSensitive(pdialog->sell_command, test_player_sell_building_now(client.conn.playing, pcity, NULL) == TR_SUCCESS); xaw_set_label(pdialog->building_label, city_production_name_translation(pcity)); get_contents_of_progress(pdialog, buf, sizeof(buf)); xaw_set_label(pdialog->progress_label, buf); get_contents_of_worklist(pdialog, buf, sizeof(buf)); xaw_set_label(pdialog->worklist_label, buf); } /**************************************************************** ... *****************************************************************/ void city_dialog_update_production(struct city_dialog *pdialog) { char buf[512]; get_contents_of_production(pdialog, buf, sizeof(buf)); xaw_set_label(pdialog->production_label, buf); } /**************************************************************** ... *****************************************************************/ void city_dialog_update_output(struct city_dialog *pdialog) { char buf[512]; get_contents_of_output(pdialog, buf, sizeof(buf)); xaw_set_label(pdialog->output_label, buf); } /**************************************************************************** Handle the callback when a citizen sprite widget is clicked. ****************************************************************************/ static void citizen_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog = client_data; int i; /* HACK: figure out which figure was clicked. */ for (i = 0; i < city_size_get(pdialog->pcity); i++) { if (pdialog->citizen_labels[i] == w) { break; } } fc_assert(i < city_size_get(pdialog->pcity)); city_rotate_specialist(pdialog->pcity, i); } /**************************************************************** ... *****************************************************************/ void city_dialog_update_citizens(struct city_dialog *pdialog) { enum citizen_category citizens[MAX_CITY_SIZE]; int i; struct city *pcity=pdialog->pcity; int num_citizens = get_city_citizen_types(pcity, FEELING_FINAL, citizens); for (i = 0; i < num_citizens && i < pdialog->num_citizens_shown; i++) { xaw_set_bitmap(pdialog->citizen_labels[i], get_citizen_pixmap(citizens[i], i, pcity)); /* HACK: set sensitivity/callbacks on the widget */ XtRemoveAllCallbacks(pdialog->citizen_labels[i], XtNcallback); XtAddCallback(pdialog->citizen_labels[i], XtNcallback, citizen_callback, (XtPointer)pdialog); XtSetSensitive(pdialog->citizen_labels[i], TRUE); } if (i >= pdialog->num_citizens_shown && i < num_citizens) { i = pdialog->num_citizens_shown - 1; /* FIXME: what about the mask? */ xaw_set_bitmap(pdialog->citizen_labels[i], get_arrow_sprite(tileset, ARROW_RIGHT)->pixmap); XtSetSensitive(pdialog->citizen_labels[i], FALSE); XtRemoveAllCallbacks(pdialog->citizen_labels[i], XtNcallback); return; } for(; i<pdialog->num_citizens_shown; i++) { xaw_set_bitmap(pdialog->citizen_labels[i], None); XtSetSensitive(pdialog->citizen_labels[i], FALSE); XtRemoveAllCallbacks(pdialog->citizen_labels[i], XtNcallback); } } /**************************************************************** ... *****************************************************************/ static void support_units_callback(Widget w, XtPointer client_data, XtPointer call_data) { Widget wd; XEvent *e = (XEvent*)call_data; struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); if (NULL != punit) { struct city *pcity = game_city_by_number(punit->homecity); if (NULL != pcity) { struct city_dialog *pdialog = get_city_dialog(pcity); if ( NULL != pdialog) { if(e->type==ButtonRelease && e->xbutton.button==Button2) { unit_focus_set(punit); close_city_dialog(pdialog); return; } if(e->type==ButtonRelease && e->xbutton.button==Button3) { unit_focus_set(punit); return; } wd = popup_message_dialog(pdialog->shell, "supportunitsdialog", unit_description(punit), supported_units_activate_callback, punit->id, 1, supported_units_activate_close_callback, punit->id, 1, disband_callback, punit->id, 1, present_units_cancel_callback, 0, 0, NULL); if (unit_has_type_flag(punit, UTYF_UNDISBANDABLE)) { XtSetSensitive(XtNameToWidget(wd, "*button3"), FALSE); } } } } } /**************************************************************** ... *****************************************************************/ static int units_scroll_maintenance(int nunits, int nshow, int *base, Widget next, Widget prev) { int adj_base=FALSE; int nextra; nextra=nunits-nshow; if (nextra<0) nextra=0; if (*base>nextra) { *base=nextra; adj_base=TRUE; } if (*base<0) { *base=0; adj_base=TRUE; } if (nextra<=0) { XtUnmapWidget(next); XtUnmapWidget(prev); } else { XtMapWidget(next); XtMapWidget(prev); XtSetSensitive(next, *base<nextra); XtSetSensitive(prev, *base>0); } return (adj_base); } /**************************************************************** ... *****************************************************************/ void city_dialog_update_supported_units(struct city_dialog *pdialog, int unitid) { struct unit_list *plist; int i, j, adj_base; Widget pixcomm; int free_unhappy = get_city_bonus(pdialog->pcity, EFT_MAKE_CONTENT_MIL); if (NULL != client.conn.playing && city_owner(pdialog->pcity) != client.conn.playing) { plist = pdialog->pcity->client.info_units_supported; } else { plist = pdialog->pcity->units_supported; } adj_base = units_scroll_maintenance(unit_list_size(plist), pdialog->num_units_shown, &(pdialog->support_unit_base), pdialog->support_unit_next_command, pdialog->support_unit_prev_command); i = 0; /* number of displayed units */ j = 0; /* index into list */ unit_list_iterate(plist, punit) { struct canvas store; int happy_cost = city_unit_unhappiness(punit, &free_unhappy); if (j++ < pdialog->support_unit_base) { continue; } if (i >= pdialog->num_units_shown) { break; } pixcomm=pdialog->support_unit_pixcomms[i]; store.pixmap = XawPixcommPixmap(pixcomm); if(!adj_base && unitid && punit->id!=unitid) continue; XawPixcommClear(pixcomm); /* STG */ put_unit(punit, &store, 1.0, 0, 0); put_unit_pixmap_city_overlays(punit, XawPixcommPixmap(pixcomm), punit->upkeep, happy_cost); xaw_expose_now(pixcomm); XtRemoveAllCallbacks(pixcomm, XtNcallback); XtAddCallback(pixcomm, XtNcallback, support_units_callback, INT_TO_XTPOINTER(punit->id)); XtSetSensitive(pixcomm, TRUE); i++; } unit_list_iterate_end; /* Disable any empty slots */ for(; i<pdialog->num_units_shown; i++) { XawPixcommClear(pdialog->support_unit_pixcomms[i]); XtSetSensitive(pdialog->support_unit_pixcomms[i], FALSE); } } /**************************************************************** ... *****************************************************************/ void city_dialog_update_present_units(struct city_dialog *pdialog, int unitid) { struct unit_list *plist; int i, j, adj_base; Widget pixcomm; if (NULL != client.conn.playing && city_owner(pdialog->pcity) != client.conn.playing) { plist = pdialog->pcity->client.info_units_present; } else { plist = pdialog->pcity->tile->units; } adj_base = units_scroll_maintenance(unit_list_size(plist), pdialog->num_units_shown, &(pdialog->present_unit_base), pdialog->present_unit_next_command, pdialog->present_unit_prev_command); i = 0; /* number of displayed units */ j = 0; /* index into list */ unit_list_iterate(plist, punit) { struct canvas store; if (j++ < pdialog->present_unit_base) { continue; } if (i >= pdialog->num_units_shown) { break; } pixcomm=pdialog->present_unit_pixcomms[i]; store.pixmap = XawPixcommPixmap(pixcomm); if(!adj_base && unitid && punit->id!=unitid) continue; XawPixcommClear(pixcomm); /* STG */ put_unit(punit, &store, 1.0, 0, 0); xaw_expose_now(pixcomm); XtRemoveAllCallbacks(pixcomm, XtNcallback); XtAddCallback(pixcomm, XtNcallback, present_units_callback, INT_TO_XTPOINTER(punit->id)); XtSetSensitive(pixcomm, TRUE); i++; } unit_list_iterate_end; for(; i<pdialog->num_units_shown; i++) { XawPixcommClear(pdialog->present_unit_pixcomms[i]); XtSetSensitive(pdialog->present_unit_pixcomms[i], FALSE); } } /**************************************************************** ... *****************************************************************/ void city_dialog_update_title(struct city_dialog *pdialog) { char buf[512]; String now; fc_snprintf(buf, sizeof(buf), _("%s - %s citizens Governor: %s"), city_name(pdialog->pcity), population_to_text(city_population(pdialog->pcity)), cmafec_get_short_descr_of_city(pdialog->pcity)); XtVaGetValues(pdialog->cityname_label, XtNlabel, &now, NULL); if(strcmp(now, buf) != 0) { XtVaSetValues(pdialog->cityname_label, XtNlabel, (XtArgVal)buf, NULL); xaw_horiz_center(pdialog->cityname_label); XtVaSetValues(pdialog->shell, XtNtitle, (XtArgVal)city_name(pdialog->pcity), NULL); } } /**************************************************************** ... *****************************************************************/ void city_dialog_update_improvement_list(struct city_dialog *pdialog) { int n = 0, flag = 0; city_built_iterate(pdialog->pcity, pimprove) { if (!pdialog->improvlist_names_ptrs[n] || strcmp(pdialog->improvlist_names_ptrs[n], city_improvement_name_translation(pdialog->pcity, pimprove)) != 0) flag = 1; sz_strlcpy(pdialog->improvlist_names[n], city_improvement_name_translation(pdialog->pcity, pimprove)); pdialog->improvlist_names_ptrs[n] = pdialog->improvlist_names[n]; n++; } city_built_iterate_end; if(pdialog->improvlist_names_ptrs[n]!=0) { pdialog->improvlist_names_ptrs[n]=0; flag=1; } if(flag || n==0) { XawListChange(pdialog->improvement_list, pdialog->improvlist_names_ptrs, n, 0, False); /* force refresh of viewport so the scrollbar is added. * Buggy sun athena requires this */ XtVaSetValues(pdialog->improvement_viewport, XtNforceBars, False, NULL); XtVaSetValues(pdialog->improvement_viewport, XtNforceBars, True, NULL); } } /************************************************************************** ... **************************************************************************/ void citydlg_btn_select_citymap(Widget w, XEvent *event) { XButtonEvent *ev=&event->xbutton; struct city *pcity = NULL; dialog_list_iterate(dialog_list, pdialog) { if (pdialog->map_canvas == w) { pcity = pdialog->pcity; break; } } dialog_list_iterate_end; if (pcity) { if (!cma_is_city_under_agent(pcity, NULL)) { int xtile, ytile; if (canvas_to_city_pos(&xtile, &ytile, city_map_radius_sq_get(pcity), ev->x, ev->y)) { city_toggle_worker(pcity, xtile, ytile); } } } } /**************************************************************** ... *****************************************************************/ static void buy_callback_yes(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog = client_data; city_buy_production(pdialog->pcity); destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ static void buy_callback_no(Widget w, XtPointer client_data, XtPointer call_data) { destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ void buy_callback(Widget w, XtPointer client_data, XtPointer call_data) { char tbuf[512], buf[512]; struct city_dialog *pdialog = (struct city_dialog *)client_data;; const char *name = city_production_name_translation(pdialog->pcity); int value = city_production_buy_gold_cost(pdialog->pcity); if (!can_client_issue_orders()) { return; } fc_snprintf(tbuf, ARRAY_SIZE(tbuf), PL_("Treasury contains %d gold.", "Treasury contains %d gold.", client_player()->economic.gold), client_player()->economic.gold); if (value <= client_player()->economic.gold) { fc_snprintf(buf, sizeof(buf), /* TRANS: Last %s is pre-pluralised "Treasury contains %d gold." */ PL_("Buy %s for %d gold?\n%s", "Buy %s for %d gold?\n%s", value), name, value, tbuf); popup_message_dialog(pdialog->shell, "buydialog", buf, buy_callback_yes, pdialog, 0, buy_callback_no, 0, 0, NULL); } else { fc_snprintf(buf, sizeof(buf), /* TRANS: Last %s is pre-pluralised "Treasury contains %d gold." */ PL_("%s costs %d gold.\n%s", "%s costs %d gold.\n%s", value), name, value, tbuf); popup_message_dialog(pdialog->shell, "buynodialog", buf, buy_callback_no, 0, 0, NULL); } } /**************************************************************** ... *****************************************************************/ void unitupgrade_callback_yes(Widget w, XtPointer client_data, XtPointer call_data) { struct unit *punit = player_unit_by_number(client_player(), (size_t)client_data); /* Is it right place for breaking? -ev */ if (!can_client_issue_orders()) { return; } if (NULL != punit) { request_unit_upgrade(punit); } destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ void unitupgrade_callback_no(Widget w, XtPointer client_data, XtPointer call_data) { destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ void upgrade_callback(Widget w, XtPointer client_data, XtPointer call_data) { char buf[512]; struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); if (!punit) { return; } if (UU_OK == unit_upgrade_info(punit, buf, sizeof(buf))) { popup_message_dialog(toplevel, "upgradedialog", buf, unitupgrade_callback_yes, INT_TO_XTPOINTER(punit->id), 0, unitupgrade_callback_no, 0, 0, NULL); } else { popup_message_dialog(toplevel, "upgradenodialog", buf, unitupgrade_callback_no, 0, 0, NULL); } destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ void disband_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct unit *punit = player_unit_by_number(client_player(), (size_t) client_data); struct unit_list *punits; if (!punit) { return; } punits = unit_list_new(); unit_list_append(punits, punit); popup_disband_dialog(punits); unit_list_destroy(punits); destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ static void change_to_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog; XawListReturnStruct *ret; pdialog=(struct city_dialog *)client_data; ret=XawListShowCurrent(pdialog->change_list); if (ret->list_index != XAW_LIST_NONE) { struct universal target = universal_by_number((ret->list_index >= pdialog->change_list_num_improvements) ? VUT_UTYPE : VUT_IMPROVEMENT, pdialog->change_list_ids[ret->list_index]); city_change_production(pdialog->pcity, target); } XtDestroyWidget(XtParent(XtParent(w))); XtSetSensitive(pdialog->shell, TRUE); } /**************************************************************** ... *****************************************************************/ static void change_no_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog; pdialog=(struct city_dialog *)client_data; XtDestroyWidget(XtParent(XtParent(w))); XtSetSensitive(pdialog->shell, TRUE); } /**************************************************************** ... *****************************************************************/ static void change_help_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog; XawListReturnStruct *ret; pdialog=(struct city_dialog *)client_data; ret=XawListShowCurrent(pdialog->change_list); if(ret->list_index!=XAW_LIST_NONE) { int idx = pdialog->change_list_ids[ret->list_index]; bool is_unit = (ret->list_index >= pdialog->change_list_num_improvements); if (is_unit) { popup_help_dialog_typed(utype_name_translation(utype_by_number(idx)), HELP_UNIT); } else if (is_great_wonder(improvement_by_number(idx))) { popup_help_dialog_typed(improvement_name_translation(improvement_by_number(idx)), HELP_WONDER); } else { popup_help_dialog_typed(improvement_name_translation(improvement_by_number(idx)), HELP_IMPROVEMENT); } } else popup_help_dialog_string(HELP_IMPROVEMENTS_ITEM); } /**************************************************************** ... *****************************************************************/ void change_callback(Widget w, XtPointer client_data, XtPointer call_data) { static char *dummy_change_list[]={ "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 888 turns", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3", "4", "5", 0 }; Widget cshell, cform, clabel, cview, button_change, button_cancel, button_help; Position x, y; Dimension width, height; struct city_dialog *pdialog; struct universal production; int n; pdialog=(struct city_dialog *)client_data; I_T(cshell=XtCreatePopupShell("changedialog", transientShellWidgetClass, pdialog->shell, NULL, 0)); cform=XtVaCreateManagedWidget("dform", formWidgetClass, cshell, NULL); I_L(clabel=XtVaCreateManagedWidget("dlabel", labelWidgetClass, cform, NULL)); cview=XtVaCreateManagedWidget("dview", viewportWidgetClass, cform, XtNfromVert, clabel, NULL); pdialog->change_list=XtVaCreateManagedWidget("dlist", listWidgetClass, cview, XtNforceColumns, 1, XtNdefaultColumns,1, XtNlist, (XtArgVal)dummy_change_list, XtNverticalList, False, NULL); button_change = I_L(XtVaCreateManagedWidget("buttonchange", commandWidgetClass, cform, XtNfromVert, cview, NULL)); button_cancel = I_L(XtVaCreateManagedWidget("buttoncancel", commandWidgetClass, cform, XtNfromVert, cview, XtNfromHoriz, button_change, NULL)); button_help = I_L(XtVaCreateManagedWidget("buttonhelp", commandWidgetClass, cform, XtNfromVert, cview, XtNfromHoriz, button_cancel, NULL)); XtAddCallback(button_change, XtNcallback, change_to_callback, (XtPointer)pdialog); XtAddCallback(button_cancel, XtNcallback, change_no_callback, (XtPointer)pdialog); XtAddCallback(button_help, XtNcallback, change_help_callback, (XtPointer)pdialog); XtVaGetValues(pdialog->shell, XtNwidth, &width, XtNheight, &height, NULL); XtTranslateCoords(pdialog->shell, (Position) width/6, (Position) height/10, &x, &y); XtVaSetValues(cshell, XtNx, x, XtNy, y, NULL); XtPopup(cshell, XtGrabNone); XtSetSensitive(pdialog->shell, FALSE); n = 0; improvement_iterate(pimprove) { if(can_city_build_improvement_now(pdialog->pcity, pimprove)) { production.kind = VUT_IMPROVEMENT; production.value.building = pimprove; get_city_dialog_production_full(pdialog->change_list_names[n], sizeof(pdialog->change_list_names[n]), production, pdialog->pcity); pdialog->change_list_names_ptrs[n]=pdialog->change_list_names[n]; pdialog->change_list_ids[n++] = improvement_number(pimprove); } } improvement_iterate_end; pdialog->change_list_num_improvements=n; unit_type_iterate(punittype) { if (can_city_build_unit_now(pdialog->pcity, punittype)) { production.kind = VUT_UTYPE; production.value.utype = punittype; get_city_dialog_production_full(pdialog->change_list_names[n], sizeof(pdialog->change_list_names[n]), production, pdialog->pcity); pdialog->change_list_names_ptrs[n]=pdialog->change_list_names[n]; pdialog->change_list_ids[n++] = utype_number(punittype); } } unit_type_iterate_end; pdialog->change_list_names_ptrs[n]=0; XawListChange(pdialog->change_list, pdialog->change_list_names_ptrs, 0, 0, False); /* force refresh of viewport so the scrollbar is added. * Buggy sun athena requires this */ XtVaSetValues(cview, XtNforceBars, True, NULL); } /**************************************************************** Display the city's worklist. *****************************************************************/ void worklist_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog; pdialog = (struct city_dialog *)client_data; if (pdialog->worklist_shell) { XtPopup(pdialog->worklist_shell, XtGrabNone); } else { pdialog->worklist_shell = popup_worklist(pdialog->pcity, NULL, pdialog->shell, (void *) pdialog, commit_city_worklist, cancel_city_worklist); } } /**************************************************************** Commit the changes to the worklist for the city. *****************************************************************/ void commit_city_worklist(struct worklist *pwl, void *data) { struct city_dialog *pdialog = data; city_worklist_commit(pdialog->pcity, pwl); } void cancel_city_worklist(void *data) { struct city_dialog *pdialog = (struct city_dialog *)data; pdialog->worklist_shell = NULL; } /**************************************************************** ... *****************************************************************/ static void sell_callback_yes(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog = client_data; city_sell_improvement(pdialog->pcity, pdialog->sell_id); destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ static void sell_callback_no(Widget w, XtPointer client_data, XtPointer call_data) { destroy_message_dialog(w); } /**************************************************************** ... *****************************************************************/ void sell_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog; XawListReturnStruct *ret; pdialog=(struct city_dialog *)client_data; ret=XawListShowCurrent(pdialog->improvement_list); if(ret->list_index!=XAW_LIST_NONE) { int n = 0; city_built_iterate(pdialog->pcity, pimprove) { if (n == ret->list_index) { char buf[512]; int price; if (!can_city_sell_building(pdialog->pcity, pimprove)) { return; } pdialog->sell_id = improvement_number(pimprove); price = impr_sell_gold(pimprove); fc_snprintf(buf, sizeof(buf), PL_("Sell %s for %d gold?", "Sell %s for %d gold?", price), city_improvement_name_translation(pdialog->pcity, pimprove), price); popup_message_dialog(pdialog->shell, "selldialog", buf, sell_callback_yes, pdialog, 0, sell_callback_no, pdialog, 0, NULL); return; } n++; } city_built_iterate_end; } } /**************************************************************** ... *****************************************************************/ void close_city_dialog(struct city_dialog *pdialog) { if (pdialog->worklist_shell) XtDestroyWidget(pdialog->worklist_shell); XtDestroyWidget(pdialog->shell); dialog_list_remove(dialog_list, pdialog); free(pdialog->citizen_labels); free(pdialog->support_unit_pixcomms); free(pdialog->present_unit_pixcomms); /* if(pdialog->is_modal) XtSetSensitive(toplevel, TRUE); */ free(pdialog); popdown_cma_dialog(); } /**************************************************************** ... *****************************************************************/ void citydlg_key_close(Widget w) { citydlg_msg_close(XtParent(XtParent(w))); } /**************************************************************** ... *****************************************************************/ void citydlg_msg_close(Widget w) { dialog_list_iterate(dialog_list, pdialog) { if (pdialog->shell == w) { close_city_dialog(pdialog); return; } } dialog_list_iterate_end; } /**************************************************************** ... *****************************************************************/ void close_callback(Widget w, XtPointer client_data, XtPointer call_data) { close_city_dialog((struct city_dialog *)client_data); } /**************************************************************** City Options dialog: (current only auto-attack options) Note, there can only be one such dialog at a time, because I'm lazy. That could be fixed, similar to way you can have multiple city dialogs. triggle = tri_toggle (three way toggle button) *****************************************************************/ #define NUM_CITYOPT_TOGGLES 5 Widget create_cityopt_dialog(const char *cityname); void cityopt_ok_command_callback(Widget w, XtPointer client_data, XtPointer call_data); void cityopt_cancel_command_callback(Widget w, XtPointer client_data, XtPointer call_data); void cityopt_newcit_triggle_callback(Widget w, XtPointer client_data, XtPointer call_data); char *newcitizen_labels[] = { N_("Workers"), N_("Scientists"), N_("Taxmen") }; static Widget cityopt_shell = 0; static Widget cityopt_triggle; static Widget cityopt_toggles[NUM_CITYOPT_TOGGLES]; static int cityopt_city_id = 0; static int newcitizen_index; /**************************************************************** ... *****************************************************************/ void cityopt_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog = (struct city_dialog *)client_data; struct city *pcity = pdialog->pcity; int i; if(cityopt_shell) { XtDestroyWidget(cityopt_shell); } cityopt_shell=create_cityopt_dialog(city_name(pcity)); /* Doing this here makes the "No"'s centered consistently */ for(i=0; i<NUM_CITYOPT_TOGGLES; i++) { bool state = is_city_option_set(pcity, i); XtVaSetValues(cityopt_toggles[i], XtNstate, state, XtNlabel, state?_("Yes"):_("No"), NULL); } if (is_city_option_set(pcity, CITYO_NEW_EINSTEIN)) { newcitizen_index = 1; } else if (is_city_option_set(pcity, CITYO_NEW_TAXMAN)) { newcitizen_index = 2; } else { newcitizen_index = 0; } XtVaSetValues(cityopt_triggle, XtNstate, 1, XtNlabel, _(newcitizen_labels[newcitizen_index]), NULL); cityopt_city_id = pcity->id; xaw_set_relative_position(pdialog->shell, cityopt_shell, 15, 15); XtPopup(cityopt_shell, XtGrabNone); } /************************************************************************** ... **************************************************************************/ Widget create_cityopt_dialog(const char *cityname) { Widget shell, form, label, ok, cancel; int i; shell = I_T(XtCreatePopupShell("cityoptpopup", transientShellWidgetClass, toplevel, NULL, 0)); form = XtVaCreateManagedWidget("cityoptform", formWidgetClass, shell, NULL); label = XtVaCreateManagedWidget("cityoptlabel", labelWidgetClass, form, XtNlabel, cityname, NULL); I_L(XtVaCreateManagedWidget("cityoptnewcitlabel", labelWidgetClass, form, NULL)); cityopt_triggle = XtVaCreateManagedWidget("cityoptnewcittriggle", toggleWidgetClass, form, NULL); /* NOTE: the ordering here is deliberately out of order; want toggles[] to be in enum city_options order, but want display in different order. --dwp - disband and workers options at top - helicopters (special case air) at bottom */ I_L(XtVaCreateManagedWidget("cityoptdisbandlabel", labelWidgetClass, form, NULL)); cityopt_toggles[4] = XtVaCreateManagedWidget("cityoptdisbandtoggle", toggleWidgetClass, form, NULL); I_L(XtVaCreateManagedWidget("cityoptvlandlabel", labelWidgetClass, form, NULL)); cityopt_toggles[0] = XtVaCreateManagedWidget("cityoptvlandtoggle", toggleWidgetClass, form, NULL); I_L(XtVaCreateManagedWidget("cityoptvsealabel", labelWidgetClass, form, NULL)); cityopt_toggles[1] = XtVaCreateManagedWidget("cityoptvseatoggle", toggleWidgetClass, form, NULL); I_L(XtVaCreateManagedWidget("cityoptvairlabel", labelWidgetClass, form, NULL)); cityopt_toggles[3] = XtVaCreateManagedWidget("cityoptvairtoggle", toggleWidgetClass, form, NULL); I_L(XtVaCreateManagedWidget("cityoptvhelilabel", labelWidgetClass, form, NULL)); cityopt_toggles[2] = XtVaCreateManagedWidget("cityoptvhelitoggle", toggleWidgetClass, form, NULL); ok = I_L(XtVaCreateManagedWidget("cityoptokcommand", commandWidgetClass, form, NULL)); cancel = I_L(XtVaCreateManagedWidget("cityoptcancelcommand", commandWidgetClass, form, NULL)); XtAddCallback(ok, XtNcallback, cityopt_ok_command_callback, (XtPointer)shell); XtAddCallback(cancel, XtNcallback, cityopt_cancel_command_callback, (XtPointer)shell); for(i=0; i<NUM_CITYOPT_TOGGLES; i++) { XtAddCallback(cityopt_toggles[i], XtNcallback, toggle_callback, NULL); } XtAddCallback(cityopt_triggle, XtNcallback, cityopt_newcit_triggle_callback, NULL); XtRealizeWidget(shell); xaw_horiz_center(label); return shell; } /************************************************************************** ... **************************************************************************/ void cityopt_cancel_command_callback(Widget w, XtPointer client_data, XtPointer call_data) { XtDestroyWidget(cityopt_shell); cityopt_shell = 0; } /************************************************************************** ... **************************************************************************/ void cityopt_ok_command_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city *pcity = game_city_by_number(cityopt_city_id); if (pcity) { /* int i; */ bv_city_options new_options; Boolean b; fc_assert(CITYO_LAST == 3); BV_CLR_ALL(new_options); /* for(i=0; i<NUM_CITYOPT_TOGGLES; i++) { XtVaGetValues(cityopt_toggles[i], XtNstate, &b, NULL); if (b) new_options |= (1<<i); } */ XtVaGetValues(cityopt_toggles[4], XtNstate, &b, NULL); if (b) { BV_SET(new_options, CITYO_DISBAND); } if (newcitizen_index == 1) { BV_SET(new_options, CITYO_NEW_EINSTEIN); } else if (newcitizen_index == 2) { BV_SET(new_options, CITYO_NEW_TAXMAN); } dsend_packet_city_options_req(&client.conn, cityopt_city_id,new_options); } XtDestroyWidget(cityopt_shell); cityopt_shell = 0; } /************************************************************************** Changes the label of the toggle widget to between newcitizen_labels and increments (mod 3) newcitizen_index. **************************************************************************/ void cityopt_newcit_triggle_callback(Widget w, XtPointer client_data, XtPointer call_data) { newcitizen_index++; if (newcitizen_index>=3) { newcitizen_index = 0; } XtVaSetValues(cityopt_triggle, XtNstate, 1, XtNlabel, _(newcitizen_labels[newcitizen_index]), NULL); } /************************************************************************** ... **************************************************************************/ void popdown_cityopt_dialog(void) { if(cityopt_shell) { XtDestroyWidget(cityopt_shell); cityopt_shell = 0; } } /**************************************************************** The user clicked on the "CMA..." button in the citydialog. *****************************************************************/ void cma_callback(Widget w, XtPointer client_data, XtPointer call_data) { struct city_dialog *pdialog = (struct city_dialog *)client_data; popdown_cma_dialog(); show_cma_dialog(pdialog->pcity, pdialog->shell); }
valisc/freeciv
client/gui-xaw/citydlg.c
C
gpl-2.0
80,107
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wikibase.DataModel { public class IndexedList<K, V> : IEnumerable { private Dictionary<K, V> dictionary; private Func<V, K> indexProvider; public int Count { get { return dictionary.Count; } } public V this[K key] { get { return dictionary[key]; } } public IndexedList(Func<V, K> indexProvider, List<V> values = null) { if (indexProvider == null) { throw new ArgumentNullException("The index provider must not be null"); } this.dictionary = values == null ? new Dictionary<K, V>() : values.ToDictionary<V, K>(indexProvider); this.indexProvider = indexProvider; } public void Add(V value) { dictionary.Add(indexProvider(value), value); } public void Set(V value) { dictionary[indexProvider(value)] = value; } public bool ContainsKey(K key) { return dictionary.ContainsKey(key); } public bool Remove(K key) { return dictionary.Remove(key); } public IEnumerator GetEnumerator() { return dictionary.Values.GetEnumerator(); } } }
Benestar/wikibase.net
Wikibase.Net/DataModel/IndexedList.cs
C#
gpl-2.0
1,483
stej-garage-control =================== Arduino powered garage door controller. ### Website [The Garage Control Project](http://stejsoftware.github.io/GarageControlFirmware/) ### Depends This project is dependent on a few other Arduino libraries: * [My ArduinoLibrary](https://github.com/stejsoftware/ArduinoLibrary) * [DHT](https://github.com/adafruit/DHT-sensor-library) * [Adafruit_LEDBackpack](https://github.com/adafruit/Adafruit-LED-Backpack-Library) * [Adafruit_GFX](https://github.com/adafruit/Adafruit-GFX-Library) * [CmdMessenger](https://github.com/thijse/Arduino-CmdMessenger)
stejsoftware/stej-garage-control
README.md
Markdown
gpl-2.0
595
<?php /** * JBZoo App is universal Joomla CCK, application for YooTheme Zoo component * @package jbzoo * @version 2.x Pro * @author JBZoo App http://jbzoo.com * @copyright Copyright (C) JBZoo.com, All rights reserved. * @license http://jbzoo.com/license-pro.php JBZoo Licence * @coder Denis Smetannikov <denis@jbzoo.com> */ // no direct access defined('_JEXEC') or die('Restricted access'); /** * Class Element */ abstract class JBCartElement { const DEFAULT_GROUP = '_default'; /** * @var String */ public $identifier; /** * @var App */ public $app; /** * @var AppData */ public $config; /** * @var String */ protected $_group; /** * @var JBCartOrder */ protected $_order; /** * @var String */ protected $_type; /** * @var Element callbacks */ protected $_callbacks = array(); /** * @var JBCartElementHelper */ protected $_jbcartelement = null; /** * @var SimpleXMLElement */ protected $_xmlData = null; /** * @var JSONData */ protected $_metaData = null; /** * @var string */ protected $_namespace = JBCart::ELEMENT_TYPE_DEFAULT; /** * @var JSONData */ protected $_data = array(); /** * @var JBMoneyHelper */ protected $_jbmoney = array(); /** * Constructor * @param App $app * @param string $type * @param string $group */ public function __construct($app, $type, $group) { // set app $this->app = $app; $this->config = $this->app->data->create(); $this->_group = strtolower(trim($group)); $this->_type = strtolower(trim($type)); $this->_jbcartelement = $this->app->jbcartelement; $this->_data = $this->app->data->create($this->_data); } /** * Load custom languages */ protected function _loadLangs() { JFactory::getLanguage()->load('elem_' . $this->getElementType(), $this->getPath(), null, true); } /** * Set new config data * @param $config */ public function setConfig($config) { if (is_array($config)) { $config = $this->app->data->create($config); } $this->config = $config; } /** * Gets the elements type * @return string */ public function getElementType() { return strtolower($this->_type); } /** * Gets the elements type * @return string */ public function getElementGroup() { return strtolower($this->_group); } /** * Set data through data array. * @param array $data * @return $this */ public function bindData($data = array()) { if (!empty($data)) { foreach ($data as $key => $value) { $this->set($key, $value); } } return $this; } /** * Gets the elements data * @param $key * @param null $default * @return mixed */ public function get($key, $default = null) { $result = $this->_data->get($key, $default); if ($result === null) { $result = $default; } return $result; } /** * Sets the elements data. * @param $key * @param $value * @return $this */ public function set($key, $value) { $this->_data->set($key, $value); return $this; } /** * Gets data array * @return array */ public function data() { return $this->_data; } /** * Get element layout path and use override if exists * @param null|string $layout * @return string */ public function getLayout($layout = null) { // init vars $type = $this->getElementType(); $group = $this->getElementGroup(); // set default if (empty($layout)) { $layout = $type . '.php'; } else if (strpos($layout, '.php') === false) { $layout .= '.php'; } // own layout $layoutPath = $this->app->path->path("cart-elements:{$group}/{$type}/tmpl/{$layout}"); // parent option if (empty($layoutPath)) { $layoutPath = $this->app->path->path("cart-elements:{$group}/option/tmpl/{$layout}"); } // parent group if (empty($layoutPath)) { $layoutPath = $this->app->path->path("cart-elements:core/{$group}/tmpl/{$layout}"); } // global if (empty($layoutPath)) { $layoutPath = $this->app->path->path("cart-elements:core/element/tmpl/{$layout}"); } return $layoutPath; } /** * Get related order object * @return JBCartOrder */ public function getOrder() { return $this->_order; } /** * Get related type object * @return String */ public function getType() { return $this->_type; } /** * Get element group * @return bool */ public function getGroup() { return $this->getMetadata('group'); } /** * Set related item object * @param JBCartOrder $order */ public function setOrder(JBCartOrder $order) { $this->_order = $order; } /** * Set related type object * @param array $params * @return bool */ public function hasValue($params = array()) { $value = $this->get('value', $this->config->get('default')); return !empty($value); } /** * Renders the element * @param array $params * @return mixed|string */ public function render($params = array()) { $paramLayout = $params->get('layout') ? $params->get('layout') . '.php' : null; if ($layout = $this->getLayout($paramLayout)) { return $this->renderLayout($layout, array( 'params' => $params, 'value' => $this->get('value'), 'order' => $this->getOrder(), )); } return null; } /** * @param string $layout * @param array $vars * @return null|string */ protected function _partial($layout, $vars = array()) { $vars['order'] = $this->getOrder(); if ($layout = $this->getLayout($layout . '.php')) { return self::renderLayout($layout, $vars); } return null; } /** * Renders the element using template layout file * @param string $__layout layouts template file * @param array $__args layouts template file args * @return string */ protected function renderLayout($__layout, $__args = array()) { // init vars if (is_array($__args)) { foreach ($__args as $__var => $__value) { $$__var = $__value; } } // render layout $__html = ''; ob_start(); include($__layout); $__html = ob_get_contents(); ob_end_clean(); return $__html; } /** * Load elements css/js assets * @return $this */ public function loadAssets() { $group = $this->getElementGroup(); $type = $this->getElementType(); $jbassets = $this->app->jbassets; $jbassets->js('cart-elements:' . $group . '/' . $type . '/assets/js/' . $type . '.js'); $jbassets->css('cart-elements:' . $group . '/' . $type . '/assets/css/' . $type . '.css'); $jbassets->less('cart-elements:' . $group . '/' . $type . '/assets/less/' . $type . '.less'); return $this; } /** * Load elements css/js config assets * @return $this */ public function loadConfigAssets() { $this->app->path->register($this->app->path->path('helpers:fields'), 'fields'); return $this; } /** * Register a callback function * @param $method */ public function registerCallback($method) { if (!in_array(strtolower($method), $this->_callbacks)) { $this->_callbacks[] = strtolower($method); } } /** * Execute elements callback function * @param $method * @param array $args */ public function callback($method, $args = array()) { // try to call a elements class method if (in_array(strtolower($method), $this->_callbacks) && method_exists($this, $method)) { // call method $res = call_user_func_array(array($this, $method), $args); // output if method returns a string if (is_string($res)) { echo $res; } } } /** * Get parameter form object to render input form * @return AppParameterForm */ public function getConfigForm() { // get form /** @var AppParameterForm $form */ $form = $this->app->parameterform->create(); $params = array(); $class = new ReflectionClass($this); while ($class !== false) { $xmlPath = preg_replace('#\.php$#i', '.xml', $class->getFileName()); if (file_exists($xmlPath)) { $params[] = $xmlPath; } $class = $class->getParentClass(); } $params = array_reverse($params); // trigger configparams event $event = $this->app->event->create($this, 'cart-element:configparams')->setReturnValue($params); $params = $this->app->event->dispatcher->notify($event)->getReturnValue(); // skip if there are no config files $params = array_filter($params); if (empty($params)) { return null; } // add config xml files foreach ($params as $xml) { $form->addXML($xml); } // set values $form->setValues($this->config); // add reference to element $form->element = $this; // trigger configform event $this->app->jbevent->fire($this, 'cart-element:configform', compact('form')); $fieldsPath = JPath::clean($this->getPath() . '/fields'); if (is_dir($fieldsPath)) { $form->addElementPath($fieldsPath); } return $form; } /** * Get elements xml meta data * @param null $key * @return bool */ public function getMetaData($key = null) { if (!isset($this->_metaData)) { $data = array(); $xml = $this->loadXML(); if (!$xml) { return false; } $data['type'] = $xml->attributes()->type ? (string)$xml->attributes()->type : 'Unknown'; $data['group'] = $xml->attributes()->group ? (string)$xml->attributes()->group : 'Unknown'; $data['hidden'] = $xml->attributes()->hidden ? (string)$xml->attributes()->hidden : 'false'; $data['core'] = $xml->attributes()->core ? (string)$xml->attributes()->core : 'false'; $data['system-tmpl'] = $xml->attributes()->{'system-tmpl'} ? (string)$xml->attributes()->{'system-tmpl'} : 'false'; $data['trusted'] = $xml->attributes()->trusted ? (string)$xml->attributes()->trusted : 'false'; $data['orderable'] = $xml->attributes()->orderable ? (string)$xml->attributes()->orderable : 'false'; $data['name'] = JText::_((string)$xml->name); $data['creationdate'] = $xml->creationDate ? (string)$xml->creationDate : 'Unknown'; $data['author'] = $xml->author ? (string)$xml->author : 'Unknown'; $data['copyright'] = (string)$xml->copyright; $data['authorEmail'] = (string)$xml->authorEmail; $data['authorUrl'] = (string)$xml->authorUrl; $data['version'] = (string)$xml->version; $data['description'] = JText::_((string)$xml->description); $this->_metaData = $this->app->data->create($data); } return $key == null ? $this->_metaData : $this->_metaData->get($key); } /** * Retrieve Element XML file info * @return SimpleXMLElement */ public function loadXML() { if (!isset($this->_xmlData)) { $type = $this->getElementType(); $group = $this->getElementGroup(); $this->_xmlData = simplexml_load_file($this->app->path->path("cart-elements:$group/$type/$type.xml")); } return $this->_xmlData; } /** * Gets the controle name for given name * @param $name * @param bool $array * @return string */ public function getControlName($name, $array = false) { return $this->_namespace . '[' . $this->identifier . '][' . $name . ']' . ($array ? '[]' : ''); } /** * Check if element is accessible with users access rights * @param null $user * @return mixed */ public function canAccess($user = null) { return $this->app->user->canAccess($user, $this->config->get('access', $this->app->joomla->getDefaultAccess())); } /** * Get path to element's base directory * @return mixed */ public function getPath() { return $this->app->path->path("cart-elements:" . $this->getElementGroup() . '/' . $this->getElementType()); } /** * Check if element is system * @return bool */ public function isSystemTmpl() { $systemTmpl = strtolower($this->getMetaData('system-tmpl')); if ($systemTmpl == 'true') { return true; } return false; } /** * Check if element is core * @return bool */ public function isCore() { $core = strtolower($this->getMetaData('core')); if ($core == 'true') { return true; } return false; } /** * Check if element is core * @return bool */ public function isHidden() { $hidden = strtolower($this->getMetaData('hidden')); if ($hidden == 'true' || $hidden == '1') { return true; } return false; } /** * Renders the element in submission * @param array $params * @return string|void */ public function renderSubmission($params = array()) { if ($layout = $this->getLayout('submission.php')) { return self::renderLayout($layout, array( 'params' => $params, 'value' => $this->get('value'), 'order' => $this->getOrder(), )); } return null; } /** * Validates the submitted element * @param $value * @param $params * @return array */ public function validateSubmission($value, $params) { $params = $this->app->data->create($params); $value = $this->app->data->create($value); return array( 'value' => $this->app->validator ->create('textfilter', array( 'required' => (int)$params->get('required'), 'trim' => true, )) ->clean($value->get('value')), ); } /** * @return string */ public function getName() { $name = $this->config->get('name'); if (empty($name)) { $retult = $this->getMetaData('name'); } else { $retult = JText::_($name); } $retult = JString::trim($retult); return $retult; } /** * @return JSONData */ public function getOrderData() { return $this->app->data->create(array( 'data' => $this->data(), 'config' => (array)$this->config, )); } /** * @param null $default * @return mixed */ public function getDescription($default = null) { return JText::_($this->config->get('description', $default)); } /** * @param bool $uniq * @return string */ public function htmlId($uniq = false) { $id = 'jbcart-' . $this->identifier; if ($uniq) { return $this->app->jbstring->getId($id); } return $id; } /** * @param string $methodName * @param array $params * @return mixed */ public function getAjaxUrl($methodName = 'ajax', array $params = array()) { $urlParams = array( 'order_id' => $this->getOrder()->id, 'group' => $this->getElementGroup(), 'element' => $this->identifier, ); return $this->app->jbrouter->elementOrder($methodName, $urlParams, $params); } /** * @param $attrs * @return mixed */ protected function _attrs($attrs) { return $this->app->jbhtml->buildAttrs($attrs); } /** * @param string $positon */ public function saveConfig($positon = JBCart::DEFAULT_POSITION) { $config = JBModelConfig::model(); $list = $config->getGroup('cart.' . $this->getElementGroup()); $list[$positon][$this->identifier] = (array)$this->config; $config->setGroup('cart.' . $this->getElementGroup(), $list); } } /** * Class JBCartElementException */ class JBCartElementException extends AppException { }
alexmixaylov/real
media/zoo/applications/jbuniversal/cart-elements/core/element/element.php
PHP
gpl-2.0
18,323
#include "hge-object-page.hpp" hge::ui::ObjectPage::ObjectPage(QWidget *parent) : QWidget(parent) { }
Hossein-Noroozpour/HGE-Builder
hge-object-page.cpp
C++
gpl-2.0
103
<?php use mvc\interfaces\controllerActionInterface; use mvc\controller\controllerClass; use mvc\config\configClass as config; use mvc\request\requestClass as request; use mvc\routing\routingClass as routing; use mvc\session\sessionClass as session; use mvc\i18n\i18nClass as i18n; use hook\log\logHookClass as log; /** * Description of ejemploClass * * @author Mariana Lopez, Andres Felipe Alvarez */ class deleteSelectActionClass extends controllerClass implements controllerActionInterface { public function execute() { try { if (request::getInstance()->isMethod('POST')) { $idsToDelete = request::getInstance()->getPost('chk'); foreach ($idsToDelete as $id) { $ids = array( usuarioTableClass::ID => $id ); usuarioTableClass::delete($ids, true); } session::getInstance()->setSuccess(i18n::__(20003, null, 'default')); log::register('EliminacionSeleccionado', usuarioTableClass::getNameTable(), null, session::getInstance()->getUserId()); routing::getInstance()->redirect('usuario', 'index'); } else { routing::getInstance()->redirect('usuario', 'index'); } } catch (PDOException $exc) { session::getInstance()->setFlash('exc', $exc); routing::getInstance()->forward('shfSecurity', 'exception'); } } }
marianandres/CultExcelEnterprise1
controller/usuario/deleteSelectActionClass.php
PHP
gpl-2.0
1,500
<?php $section = get_heckscher_section(); ?> <div class="heckscherdropdown dropdown-<?php echo $section; ?>"> <?php if ( $section == 'guidelines') : ?> <span class="more">More Guidelines</span> <?php elseif ( $section == 'projects') : ?> <span class="more">More Projects</span> <?php else : ?> <span class="more">More</span> <?php endif; ?> <div class="ddwrapper"> <ul><?php echo wp_list_pages(array( 'echo' => 0, 'title_li' => __(''), 'depth' => '1', 'link_before' => '<span>', 'link_after' => '</span>', 'child_of' => $post->post_parent, 'exclude' => $post->ID )); ?></ul> </div> </div>
everythingtype/heckscher
parts/sibling-dropdown.php
PHP
gpl-2.0
627
WRITE8_HANDLER( stv_SMPC_w ); READ8_HANDLER( stv_SMPC_r ); WRITE8_HANDLER( saturn_SMPC_w ); READ8_HANDLER( saturn_SMPC_r );
Luke-Nukem/mame-144-vector_mod
src/mame/machine/smpc.h
C
gpl-2.0
128
#ifndef IMC_H #define IMC_H #define ENTRE(x,a,b) ((a)<=(x) && (x)<=(b)) #define INTRAPESO 18.50 #define NORMAL 24.99 #define SOBREPESO 25 #define OBESO 30 #define INFRA "infrapeso" #define NOM "normal" #define SOBRE "sobrepeso" #define OBE "obeso" float IMC(float peso, float altura); #endif
liobouchan/P31ESCOM
4/imc.h
C
gpl-2.0
401
import re from geopy import exc from geopy.compat import urlencode from geopy.geocoders.base import DEFAULT_SENTINEL, Geocoder from geopy.location import Location from geopy.util import logger __all__ = ("What3Words", ) class What3Words(Geocoder): """What3Words geocoder. Documentation at: https://docs.what3words.com/api/v2/ .. versionadded:: 1.5.0 .. versionchanged:: 1.15.0 API has been updated to v2. """ multiple_word_re = re.compile( r"[^\W\d\_]+\.{1,1}[^\W\d\_]+\.{1,1}[^\W\d\_]+$", re.U ) geocode_path = '/v2/forward' reverse_path = '/v2/reverse' def __init__( self, api_key, format_string=None, scheme='https', timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, ): """ :param str api_key: Key provided by What3Words (https://accounts.what3words.com/register). :param str format_string: See :attr:`geopy.geocoders.options.default_format_string`. :param str scheme: Must be ``https``. .. deprecated:: 1.15.0 API v2 requires https. Don't use this parameter, it's going to be removed in geopy 2.0. Scheme other than ``https`` would result in a :class:`geopy.exc.ConfigurationError` being thrown. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. .. versionadded:: 1.12.0 :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. .. versionadded:: 1.14.0 """ super(What3Words, self).__init__( format_string=format_string, # The `scheme` argument is present for the legacy reasons only. # If a custom value has been passed, it should be validated. # Otherwise use `https` instead of the `options.default_scheme`. scheme=(scheme or 'https'), timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, ) if self.scheme != "https": raise exc.ConfigurationError("What3Words now requires `https`.") self.api_key = api_key domain = 'api.what3words.com' self.geocode_api = '%s://%s%s' % (self.scheme, domain, self.geocode_path) self.reverse_api = '%s://%s%s' % (self.scheme, domain, self.reverse_path) def _check_query(self, query): """ Check query validity with regex """ if not self.multiple_word_re.match(query): return False else: return True def geocode(self, query, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be thrown. :param str query: The 3-word address you wish to geocode. :param str lang: two character language codes as supported by the API (https://docs.what3words.com/api/v2/#lang). :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. .. versionchanged:: 1.14.0 ``exactly_one=False`` now returns a list of a single location. This option wasn't respected before. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ if not self._check_query(query): raise exc.GeocoderQueryError( "Search string must be 'word.word.word'" ) params = { 'addr': self.format_string % query, 'lang': lang.lower(), 'key': self.api_key, } url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) return self._parse_json( self._call_geocoder(url, timeout=timeout), exactly_one=exactly_one ) def _parse_json(self, resources, exactly_one=True): """ Parse type, words, latitude, and longitude and language from a JSON response. """ code = resources['status'].get('code') if code: # https://docs.what3words.com/api/v2/#errors exc_msg = "Error returned by What3Words: %s" % resources['status']['message'] if code == 401: raise exc.GeocoderAuthenticationFailure(exc_msg) raise exc.GeocoderQueryError(exc_msg) def parse_resource(resource): """ Parse record. """ if 'geometry' in resource: words = resource['words'] position = resource['geometry'] latitude, longitude = position['lat'], position['lng'] if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(words, (latitude, longitude), resource) else: raise exc.GeocoderParseError('Error parsing result.') location = parse_resource(resources) if exactly_one: return location else: return [location] def reverse(self, query, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return a `3 words` address by location point. Each point on surface has a `3 words` address, so there's always a non-empty response. :param query: The coordinates for which you wish to obtain the 3 word address. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str lang: two character language codes as supported by the API (https://docs.what3words.com/api/v2/#lang). :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. .. versionchanged:: 1.14.0 ``exactly_one=False`` now returns a list of a single location. This option wasn't respected before. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ lang = lang.lower() params = { 'coords': self._coerce_point_to_string(query), 'lang': lang.lower(), 'key': self.api_key, } url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) return self._parse_reverse_json( self._call_geocoder(url, timeout=timeout), exactly_one=exactly_one ) def _parse_reverse_json(self, resources, exactly_one=True): """ Parses a location from a single-result reverse API call. """ return self._parse_json(resources, exactly_one)
phborba/dsgtoolsop
auxiliar/geopy/geocoders/what3words.py
Python
gpl-2.0
8,452
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <meta http-equiv="Content-Style-Type" content="text/css"> <meta name="categories" content="project"> <meta name="product" content="Canvas"> <link rel="stylesheet" href="../support/help.css" charset="ISO-8859-1" type="text/css"> <title>Project Menu</title> </head> <script type="text/javascript"> function setTitle() { top.document.title = document.title + " - " + parent.parent.WINDOW_TITLE; } </script> <body onload="setTitle();"> <table bgcolor="#dcdcdc" border="0" cellspacing="0" width="100%"> <tr><td> <p><img src="../support/schrodinger_logo.gif" align="left" alt="" border="0" hspace="5" vspace="5" /></p> </td></tr> <tr><td> <h1 class="title"><span class="canvas">Project Menu</span></h1> </td></tr> </table> <p>The <span class="GUI">Project</span> menu gives you access to information about the Canvas project. </p> <ul> <li><p><span class="GUI">Project View</span>&mdash;This option displays or hides the <span class="GUI">Project View</span> panel. This panel displays a tree view of the project, which provides access to all the objects created in the project, such as views, jobs run, and so on. By default, it is docked into the main window. You can undock it and redock it by clicking the docking button. <img src="../images/common/docking_button.gif" /> </p> </li> <li><p><span class="GUI">Messages View</span>&mdash;This option displays or hides the <span class="GUI">Messages View</span> panel. This panel displays log and error messages from various operations that are done on the project. By default, it is docked into the main window. You can undock it and redock it by clicking the docking button. <img src="../images/common/docking_button.gif" /> </p> </li> </ul> <hr /> <table width="100%"> <td><p class="small"><a href="../support/legal_notice.html" target="LegalNoticeWindow">Legal Notice</a></p></td> <tr><td> <table align="right"> <tr><td><p class="small"> File: project/menu.html<br /> Last updated: 26 Oct 2009 </p></td></tr> </table> </td></tr> </table> </body> </html>
platinhom/ManualHom
Schrodinger/Schrodinger_2012_docs/canvas/help/project/menu.html
HTML
gpl-2.0
2,144
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.autoplot.pngwalk; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.util.logging.Level; import java.util.logging.Logger; import org.das2.util.LoggerManager; /** * first from http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html * resize taken from http://www.componenthouse.com/article-20 * @author jbf */ public class ImageResize { public static final Logger logger= LoggerManager.getLogger("autoplot.pngwalk"); /** * convenient typical use. * @param img image to resize. * @param thumbSize corner-to-corner size, preserving aspect ratio. * @return buffered image that is thumbSize across. */ public static BufferedImage getScaledInstance( BufferedImage img, int thumbSize ) { int w0= img.getWidth(); int h0= img.getHeight(); int thumbH, thumbW; double aspect = 1. * w0 / h0; thumbH = (int) (Math.sqrt(Math.pow(thumbSize, 2) / (aspect * aspect + 1.))); thumbW = (int) (thumbH * aspect); return getScaledInstance( img, thumbW, thumbH, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true ); } /** * Convenience method that returns a scaled instance of the * provided {@code BufferedImage}. * * @param img the original image to be scaled * @param targetWidth the desired width of the scaled instance, * in pixels * @param targetHeight the desired height of the scaled instance, * in pixels * @param hint one of the rendering hints that corresponds to * {@code RenderingHints.KEY_INTERPOLATION} (e.g. * {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR}, * {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR}, * {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC}) * @param higherQuality if true, this method will use a multi-step * scaling technique that provides higher quality than the usual * one-step technique (only useful in downscaling cases, where * {@code targetWidth} or {@code targetHeight} is * smaller than the original dimensions, and generally only when * the {@code BILINEAR} hint is specified) * @return a scaled version of the original {@code BufferedImage} */ public static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight, Object hint, boolean higherQuality) { int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB; BufferedImage ret = (BufferedImage)img; int w, h; if (higherQuality) { // Use multi-step technique: start with original size, then // scale down in multiple passes with drawImage() // until the target size is reached w = img.getWidth(); h = img.getHeight(); } else { // Use one-step technique: scale directly from original // size to target size with a single drawImage() call w = targetWidth; h = targetHeight; } int count= 0; do { if (higherQuality && w > targetWidth) { w /= 2; if (w < targetWidth) { w = targetWidth; } } if (higherQuality && h > targetHeight) { h /= 2; if (h < targetHeight) { h = targetHeight; } } BufferedImage tmp = new BufferedImage(w, h, type); Graphics2D g2 = tmp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint ); g2.drawImage(ret, 0, 0, w, h, null); g2.dispose(); ret = tmp; count++; // I noticed a case where it hung in this loop. } while ( count<50 && ( w != targetWidth || h != targetHeight) ); if ( count==50 ) { logger.log( Level.WARNING, "ran out of iterations in imageResize" ); } return ret; } }
autoplot/app
Autoplot/src/org/autoplot/pngwalk/ImageResize.java
Java
gpl-2.0
4,487
/* * Copyright 2004 Timo Hirvonen * * 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 _SEARCH_MODE_H #define _SEARCH_MODE_H #include "search.h" #include "uchar.h" extern char *search_str; extern enum search_direction search_direction; /* //WORDS or ??WORDS search mode */ extern int search_restricted; extern void search_mode_ch(uchar ch); extern void search_mode_key(int key); extern void search_mode_init(void); extern void search_mode_exit(void); void search_text(const char *text, int restricted, int beginning); #endif
cojocar/cmus-dbus
search_mode.h
C
gpl-2.0
1,215
<?php // // +----------------------------------------------------------------------+ // | PHP Version 5 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2004 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 3.0 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available through the world-wide-web at the following url: | // | http://www.php.net/license/3_0.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Authors: Stig Bakken <ssb@php.net> | // | Tomas V.V.Cox <cox@idecnet.com> | // | | // +----------------------------------------------------------------------+ // // $Id: peclcmd.php,v 1.1 2005/02/21 05:30:56 cellog Exp $ /** * @nodep Gtk */ if ('/home/renato/tmp/usr/share/php' != '@'.'include_path'.'@') { ini_set('include_path', '/home/renato/tmp/usr/share/php'); $raw = false; } else { // this is a raw, uninstalled pear, either a cvs checkout, or php distro $raw = true; } define('PEAR_RUNTYPE', 'pecl'); require_once 'pearcmd.php'; /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: nil * mode: php * End: */ // vim600:syn=php ?>
telabotanica/tapirlink
lib/pear/peclcmd.php
PHP
gpl-2.0
1,830
#!/bin/bash . `dirname $0`/functions.sh rm -f reloc3 reloc3lib*.so reloc3.log rm -f prelink.cache $CC -shared -O2 -fpic -o reloc3lib1.so $srcdir/reloc3lib1.c $CC -shared -O2 -fpic -o reloc3lib2.so $srcdir/reloc1lib2.c reloc3lib1.so BINS="reloc3" LIBS="reloc3lib1.so reloc3lib2.so" $CCLINK -o reloc3 $srcdir/reloc3.c -Wl,--rpath-link,. reloc3lib2.so strip -g $BINS $LIBS savelibs echo $PRELINK ${PRELINK_OPTS--vm} ./reloc3 > reloc3.log $PRELINK ${PRELINK_OPTS--vm} ./reloc3 >> reloc3.log 2>&1 || exit 1 grep -q ^`echo $PRELINK | sed 's/ .*$/: /'` reloc3.log && exit 2 LD_LIBRARY_PATH=. ./reloc3 >> reloc3.log || exit 3 readelf -a ./reloc3 >> reloc3.log 2>&1 || exit 4 # So that it is not prelinked again chmod -x ./reloc3 comparelibs >> reloc3.log 2>&1 || exit 5
ystk/debian-prelink
testsuite/reloc3.sh
Shell
gpl-2.0
762
/* created by click/linuxmodule/fixincludes.pl on Tue Nov 25 22:39:42 2014 */ /* from /lib/modules/2.6.27.5-117.fc10.i686/build/include/config/ip/nf/filter.h */
songxingshen/myclick
include/click-linuxmodule/include0/config/ip/nf/filter.h
C
gpl-2.0
161
/* * Copyright (C) 2010-2022 Fabio Cavallo (aka FHorse) * * 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 <string.h> #include "mappers.h" #include "info.h" #include "mem_map.h" #include "save_slot.h" INLINE static void ks7031_init_prg(void); INLINE static void ks7031_update(void); struct _ks7031 { BYTE reg[4]; } ks7031; struct _ks7031tmp { BYTE *prg_6000; BYTE *prg_6800; BYTE *prg_7000; BYTE *prg_7800; BYTE *prg_8000; BYTE *prg_8800; BYTE *prg_9000; BYTE *prg_9800; BYTE *prg_A000; BYTE *prg_A800; BYTE *prg_B000; BYTE *prg_B800; BYTE *prg_C000; BYTE *prg_C800; BYTE *prg_D000; BYTE *prg_D800; BYTE *prg_E000; BYTE *prg_E800; BYTE *prg_F000; BYTE *prg_F800; } ks7031tmp; void map_init_KS7031(void) { EXTCL_CPU_WR_MEM(KS7031); EXTCL_CPU_RD_MEM(KS7031); EXTCL_SAVE_MAPPER(KS7031); mapper.internal_struct[0] = (BYTE *)&ks7031; mapper.internal_struct_size[0] = sizeof(ks7031); memset(&ks7031, 0x00, sizeof(ks7031)); info.mapper.extend_rd = TRUE; ks7031_init_prg(); ks7031_update(); mirroring_V(); } void extcl_cpu_wr_mem_KS7031(WORD address, BYTE value) { ks7031.reg[(address & 0x1800) >> 11] = value; ks7031_update(); } BYTE extcl_cpu_rd_mem_KS7031(WORD address, BYTE openbus, UNUSED(BYTE before)) { switch (address & 0xF800) { case 0x6000: return (ks7031tmp.prg_6000[address & 0x07FF]); case 0x6800: return (ks7031tmp.prg_6800[address & 0x07FF]); case 0x7000: return (ks7031tmp.prg_7000[address & 0x07FF]); case 0x7800: return (ks7031tmp.prg_7800[address & 0x07FF]); case 0x8000: return (ks7031tmp.prg_8000[address & 0x07FF]); case 0x8800: return (ks7031tmp.prg_8800[address & 0x07FF]); case 0x9000: return (ks7031tmp.prg_9000[address & 0x07FF]); case 0x9800: return (ks7031tmp.prg_9800[address & 0x07FF]); case 0xA000: return (ks7031tmp.prg_A000[address & 0x07FF]); case 0xA800: return (ks7031tmp.prg_A800[address & 0x07FF]); case 0xB000: return (ks7031tmp.prg_B000[address & 0x07FF]); case 0xB800: return (ks7031tmp.prg_B800[address & 0x07FF]); case 0xC000: return (ks7031tmp.prg_C000[address & 0x07FF]); case 0xC800: return (ks7031tmp.prg_C800[address & 0x07FF]); case 0xD000: return (ks7031tmp.prg_D000[address & 0x07FF]); case 0xD800: return (ks7031tmp.prg_D800[address & 0x07FF]); case 0xE000: return (ks7031tmp.prg_E000[address & 0x07FF]); case 0xE800: return (ks7031tmp.prg_E800[address & 0x07FF]); case 0xF000: return (ks7031tmp.prg_F000[address & 0x07FF]); case 0xF800: return (ks7031tmp.prg_F800[address & 0x07FF]); } return (openbus); } BYTE extcl_save_mapper_KS7031(BYTE mode, BYTE slot, FILE *fp) { save_slot_ele(mode, slot, ks7031.reg); if (mode == SAVE_SLOT_READ) { ks7031_init_prg(); ks7031_update(); } return (EXIT_OK); } INLINE static void ks7031_init_prg(void) { BYTE value; // 0x8000 value = 15; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_8000 = prg_chip_byte_pnt(0, value << 11); // 0x8800 value = 14; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_8800 = prg_chip_byte_pnt(0, value << 11); // 0x9000 value = 13; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_9000 = prg_chip_byte_pnt(0, value << 11); // 0x9800 value = 12; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_9800 = prg_chip_byte_pnt(0, value << 11); // 0xA000 value = 11; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_A000 = prg_chip_byte_pnt(0, value << 11); // 0xA800 value = 10; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_A800 = prg_chip_byte_pnt(0, value << 11); // 0xB000 value = 9; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_B000 = prg_chip_byte_pnt(0, value << 11); // 0xB800 value = 8; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_B800 = prg_chip_byte_pnt(0, value << 11); // 0xC000 value = 7; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_C000 = prg_chip_byte_pnt(0, value << 11); // 0xC800 value = 6; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_C800 = prg_chip_byte_pnt(0, value << 11); // 0xD000 value = 5; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_D000 = prg_chip_byte_pnt(0, value << 11); // 0xD800 value = 4; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_D800 = prg_chip_byte_pnt(0, value << 11); // 0xE000 value = 3; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_E000 = prg_chip_byte_pnt(0, value << 11); // 0xE800 value = 2; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_E800 = prg_chip_byte_pnt(0, value << 11); // 0xF000 value = 1; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_F000 = prg_chip_byte_pnt(0, value << 11); // 0xF800 value = 0; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_F800 = prg_chip_byte_pnt(0, value << 11); } INLINE static void ks7031_update(void) { WORD value; // 0x6000 value = ks7031.reg[0]; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_6000 = prg_chip_byte_pnt(0, value << 11); // 0x6800 value = ks7031.reg[1]; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_6800 = prg_chip_byte_pnt(0, value << 11); // 0x7000 value = ks7031.reg[2]; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_7000 = prg_chip_byte_pnt(0, value << 11); // 0x7800 value = ks7031.reg[3]; control_bank(info.prg.rom[0].max.banks_2k) ks7031tmp.prg_7800 = prg_chip_byte_pnt(0, value << 11); }
punesemu/puNES
src/core/mappers/mapper_KS7031.c
C
gpl-2.0
6,148
using Server.Items; namespace Server.Mobiles { [CorpseName( "a lava serpent corpse" )] [TypeAlias( "Server.Mobiles.Lavaserpant" )] public class LavaSerpent : BaseCreature { [Constructable] public LavaSerpent() : base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 ) { Name = "a lava serpent"; Body = 90; BaseSoundID = 219; SetStr( 386, 415 ); SetDex( 56, 80 ); SetInt( 66, 85 ); SetHits( 232, 249 ); SetMana( 0 ); SetDamage( 10, 22 ); SetDamageType( ResistanceType.Physical, 20 ); SetDamageType( ResistanceType.Fire, 80 ); SetResistance( ResistanceType.Physical, 35, 45 ); SetResistance( ResistanceType.Fire, 70, 80 ); SetResistance( ResistanceType.Poison, 30, 40 ); SetResistance( ResistanceType.Energy, 10, 20 ); SetSkill( SkillName.MagicResist, 25.3, 70.0 ); SetSkill( SkillName.Tactics, 65.1, 70.0 ); SetSkill( SkillName.Wrestling, 60.1, 80.0 ); Fame = 4500; Karma = -4500; VirtualArmor = 40; PackItem( new SulfurousAsh( 3 ) ); PackItem( new Bone() ); // TODO: body parts, armour } public override void GenerateLoot() { AddLoot( LootPack.Average ); } public override bool DeathAdderCharmable{ get{ return true; } } public override bool HasBreath{ get{ return true; } } // fire breath enabled public override int Meat{ get{ return 4; } } public override int Hides{ get{ return 15; } } public override HideType HideType{ get{ return HideType.Spined; } } public LavaSerpent(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int) 0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); if ( BaseSoundID == -1 ) BaseSoundID = 219; } } }
felladrin/last-wish
Scripts/Mobiles/Animals/Reptiles/LavaSerpent.cs
C#
gpl-2.0
1,925
/* * Copyright 2002-2005, Instant802 Networks, Inc. * Copyright 2005-2006, Devicescape Software, Inc. * Copyright 2006-2007 Jiri Benc <jbenc@suse.cz> * Copyright 2007 Johannes Berg <johannes@sipsolutions.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. * * * Transmit and frame generation functions. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/skbuff.h> #include <linux/etherdevice.h> #include <linux/bitmap.h> #include <linux/rcupdate.h> #include <linux/export.h> #include <net/net_namespace.h> #include <net/ieee80211_radiotap.h> #include <net/cfg80211.h> #include <net/mac80211.h> #include <asm/unaligned.h> #include "ieee80211_i.h" #include "driver-ops.h" #include "led.h" #include "mesh.h" #include "wep.h" #include "wpa.h" #include "wme.h" #include "rate.h" /* misc utils */ static __le16 ieee80211_duration(struct ieee80211_tx_data *tx, struct sk_buff *skb, int group_addr, int next_frag_len) { int rate, mrate, erp, dur, i, shift = 0; struct ieee80211_rate *txrate; struct ieee80211_local *local = tx->local; struct ieee80211_supported_band *sband; struct ieee80211_hdr *hdr; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_chanctx_conf *chanctx_conf; u32 rate_flags = 0; rcu_read_lock(); chanctx_conf = rcu_dereference(tx->sdata->vif.chanctx_conf); if (chanctx_conf) { shift = ieee80211_chandef_get_shift(&chanctx_conf->def); rate_flags = ieee80211_chandef_rate_flags(&chanctx_conf->def); } rcu_read_unlock(); /* assume HW handles this */ if (tx->rate.flags & IEEE80211_TX_RC_MCS) return 0; /* uh huh? */ if (WARN_ON_ONCE(tx->rate.idx < 0)) return 0; sband = local->hw.wiphy->bands[info->band]; txrate = &sband->bitrates[tx->rate.idx]; erp = txrate->flags & IEEE80211_RATE_ERP_G; /* * data and mgmt (except PS Poll): * - during CFP: 32768 * - during contention period: * if addr1 is group address: 0 * if more fragments = 0 and addr1 is individual address: time to * transmit one ACK plus SIFS * if more fragments = 1 and addr1 is individual address: time to * transmit next fragment plus 2 x ACK plus 3 x SIFS * * IEEE 802.11, 9.6: * - control response frame (CTS or ACK) shall be transmitted using the * same rate as the immediately previous frame in the frame exchange * sequence, if this rate belongs to the PHY mandatory rates, or else * at the highest possible rate belonging to the PHY rates in the * BSSBasicRateSet */ hdr = (struct ieee80211_hdr *)skb->data; if (ieee80211_is_ctl(hdr->frame_control)) { /* TODO: These control frames are not currently sent by * mac80211, but should they be implemented, this function * needs to be updated to support duration field calculation. * * RTS: time needed to transmit pending data/mgmt frame plus * one CTS frame plus one ACK frame plus 3 x SIFS * CTS: duration of immediately previous RTS minus time * required to transmit CTS and its SIFS * ACK: 0 if immediately previous directed data/mgmt had * more=0, with more=1 duration in ACK frame is duration * from previous frame minus time needed to transmit ACK * and its SIFS * PS Poll: BIT(15) | BIT(14) | aid */ return 0; } /* data/mgmt */ if (0 /* FIX: data/mgmt during CFP */) return cpu_to_le16(32768); if (group_addr) /* Group address as the destination - no ACK */ return 0; /* Individual destination address: * IEEE 802.11, Ch. 9.6 (after IEEE 802.11g changes) * CTS and ACK frames shall be transmitted using the highest rate in * basic rate set that is less than or equal to the rate of the * immediately previous frame and that is using the same modulation * (CCK or OFDM). If no basic rate set matches with these requirements, * the highest mandatory rate of the PHY that is less than or equal to * the rate of the previous frame is used. * Mandatory rates for IEEE 802.11g PHY: 1, 2, 5.5, 11, 6, 12, 24 Mbps */ rate = -1; /* use lowest available if everything fails */ mrate = sband->bitrates[0].bitrate; for (i = 0; i < sband->n_bitrates; i++) { struct ieee80211_rate *r = &sband->bitrates[i]; if (r->bitrate > txrate->bitrate) break; if ((rate_flags & r->flags) != rate_flags) continue; if (tx->sdata->vif.bss_conf.basic_rates & BIT(i)) rate = DIV_ROUND_UP(r->bitrate, 1 << shift); switch (sband->band) { case IEEE80211_BAND_2GHZ: { u32 flag; if (tx->sdata->flags & IEEE80211_SDATA_OPERATING_GMODE) flag = IEEE80211_RATE_MANDATORY_G; else flag = IEEE80211_RATE_MANDATORY_B; if (r->flags & flag) mrate = r->bitrate; break; } case IEEE80211_BAND_5GHZ: if (r->flags & IEEE80211_RATE_MANDATORY_A) mrate = r->bitrate; break; case IEEE80211_BAND_60GHZ: /* TODO, for now fall through */ case IEEE80211_NUM_BANDS: WARN_ON(1); break; } } if (rate == -1) { /* No matching basic rate found; use highest suitable mandatory * PHY rate */ rate = DIV_ROUND_UP(mrate, 1 << shift); } /* Don't calculate ACKs for QoS Frames with NoAck Policy set */ if (ieee80211_is_data_qos(hdr->frame_control) && *(ieee80211_get_qos_ctl(hdr)) & IEEE80211_QOS_CTL_ACK_POLICY_NOACK) dur = 0; else /* Time needed to transmit ACK * (10 bytes + 4-byte FCS = 112 bits) plus SIFS; rounded up * to closest integer */ dur = ieee80211_frame_duration(sband->band, 10, rate, erp, tx->sdata->vif.bss_conf.use_short_preamble, shift); if (next_frag_len) { /* Frame is fragmented: duration increases with time needed to * transmit next fragment plus ACK and 2 x SIFS. */ dur *= 2; /* ACK + SIFS */ /* next fragment */ dur += ieee80211_frame_duration(sband->band, next_frag_len, txrate->bitrate, erp, tx->sdata->vif.bss_conf.use_short_preamble, shift); } return cpu_to_le16(dur); } /* tx handlers */ static ieee80211_tx_result debug_noinline ieee80211_tx_h_dynamic_ps(struct ieee80211_tx_data *tx) { struct ieee80211_local *local = tx->local; struct ieee80211_if_managed *ifmgd; /* driver doesn't support power save */ if (!(local->hw.flags & IEEE80211_HW_SUPPORTS_PS)) return TX_CONTINUE; /* hardware does dynamic power save */ if (local->hw.flags & IEEE80211_HW_SUPPORTS_DYNAMIC_PS) return TX_CONTINUE; /* dynamic power save disabled */ if (local->hw.conf.dynamic_ps_timeout <= 0) return TX_CONTINUE; /* we are scanning, don't enable power save */ if (local->scanning) return TX_CONTINUE; if (!local->ps_sdata) return TX_CONTINUE; /* No point if we're going to suspend */ if (local->quiescing) return TX_CONTINUE; /* dynamic ps is supported only in managed mode */ if (tx->sdata->vif.type != NL80211_IFTYPE_STATION) return TX_CONTINUE; ifmgd = &tx->sdata->u.mgd; /* * Don't wakeup from power save if u-apsd is enabled, voip ac has * u-apsd enabled and the frame is in voip class. This effectively * means that even if all access categories have u-apsd enabled, in * practise u-apsd is only used with the voip ac. This is a * workaround for the case when received voip class packets do not * have correct qos tag for some reason, due the network or the * peer application. * * Note: ifmgd->uapsd_queues access is racy here. If the value is * changed via debugfs, user needs to reassociate manually to have * everything in sync. */ if ((ifmgd->flags & IEEE80211_STA_UAPSD_ENABLED) && (ifmgd->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VO) && skb_get_queue_mapping(tx->skb) == IEEE80211_AC_VO) return TX_CONTINUE; if (local->hw.conf.flags & IEEE80211_CONF_PS) { ieee80211_stop_queues_by_reason(&local->hw, IEEE80211_MAX_QUEUE_MAP, IEEE80211_QUEUE_STOP_REASON_PS); ifmgd->flags &= ~IEEE80211_STA_NULLFUNC_ACKED; ieee80211_queue_work(&local->hw, &local->dynamic_ps_disable_work); } /* Don't restart the timer if we're not disassociated */ if (!ifmgd->associated) return TX_CONTINUE; mod_timer(&local->dynamic_ps_timer, jiffies + msecs_to_jiffies(local->hw.conf.dynamic_ps_timeout)); return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_check_assoc(struct ieee80211_tx_data *tx) { struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); bool assoc = false; if (unlikely(info->flags & IEEE80211_TX_CTL_INJECTED)) return TX_CONTINUE; if (unlikely(test_bit(SCAN_SW_SCANNING, &tx->local->scanning)) && test_bit(SDATA_STATE_OFFCHANNEL, &tx->sdata->state) && !ieee80211_is_probe_req(hdr->frame_control) && !ieee80211_is_nullfunc(hdr->frame_control)) /* * When software scanning only nullfunc frames (to notify * the sleep state to the AP) and probe requests (for the * active scan) are allowed, all other frames should not be * sent and we should not get here, but if we do * nonetheless, drop them to avoid sending them * off-channel. See the link below and * ieee80211_start_scan() for more. * * http://article.gmane.org/gmane.linux.kernel.wireless.general/30089 */ return TX_DROP; if (tx->sdata->vif.type == NL80211_IFTYPE_WDS) return TX_CONTINUE; if (tx->sdata->vif.type == NL80211_IFTYPE_MESH_POINT) return TX_CONTINUE; if (tx->flags & IEEE80211_TX_PS_BUFFERED) return TX_CONTINUE; if (tx->sta) assoc = test_sta_flag(tx->sta, WLAN_STA_ASSOC); if (likely(tx->flags & IEEE80211_TX_UNICAST)) { if (unlikely(!assoc && ieee80211_is_data(hdr->frame_control))) { #ifdef CPTCFG_MAC80211_VERBOSE_DEBUG sdata_info(tx->sdata, "dropped data frame to not associated station %pM\n", hdr->addr1); #endif I802_DEBUG_INC(tx->local->tx_handlers_drop_not_assoc); return TX_DROP; } } else if (unlikely(tx->sdata->vif.type == NL80211_IFTYPE_AP && ieee80211_is_data(hdr->frame_control) && !atomic_read(&tx->sdata->u.ap.num_mcast_sta))) { /* * No associated STAs - no need to send multicast * frames. */ return TX_DROP; } return TX_CONTINUE; } /* This function is called whenever the AP is about to exceed the maximum limit * of buffered frames for power saving STAs. This situation should not really * happen often during normal operation, so dropping the oldest buffered packet * from each queue should be OK to make some room for new frames. */ static void purge_old_ps_buffers(struct ieee80211_local *local) { int total = 0, purged = 0; struct sk_buff *skb; struct ieee80211_sub_if_data *sdata; struct sta_info *sta; list_for_each_entry_rcu(sdata, &local->interfaces, list) { struct ps_data *ps; if (sdata->vif.type == NL80211_IFTYPE_AP) ps = &sdata->u.ap.ps; else if (ieee80211_vif_is_mesh(&sdata->vif)) ps = &sdata->u.mesh.ps; else continue; skb = skb_dequeue(&ps->bc_buf); if (skb) { purged++; dev_kfree_skb(skb); } total += skb_queue_len(&ps->bc_buf); } /* * Drop one frame from each station from the lowest-priority * AC that has frames at all. */ list_for_each_entry_rcu(sta, &local->sta_list, list) { int ac; for (ac = IEEE80211_AC_BK; ac >= IEEE80211_AC_VO; ac--) { skb = skb_dequeue(&sta->ps_tx_buf[ac]); total += skb_queue_len(&sta->ps_tx_buf[ac]); if (skb) { purged++; ieee80211_free_txskb(&local->hw, skb); break; } } } local->total_ps_buffered = total; ps_dbg_hw(&local->hw, "PS buffers full - purged %d frames\n", purged); } static ieee80211_tx_result ieee80211_tx_h_multicast_ps_buf(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; struct ps_data *ps; /* * broadcast/multicast frame * * If any of the associated/peer stations is in power save mode, * the frame is buffered to be sent after DTIM beacon frame. * This is done either by the hardware or us. */ /* powersaving STAs currently only in AP/VLAN/mesh mode */ if (tx->sdata->vif.type == NL80211_IFTYPE_AP || tx->sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { if (!tx->sdata->bss) return TX_CONTINUE; ps = &tx->sdata->bss->ps; } else if (ieee80211_vif_is_mesh(&tx->sdata->vif)) { ps = &tx->sdata->u.mesh.ps; } else { return TX_CONTINUE; } /* no buffering for ordered frames */ if (ieee80211_has_order(hdr->frame_control)) return TX_CONTINUE; if (tx->local->hw.flags & IEEE80211_HW_QUEUE_CONTROL) info->hw_queue = tx->sdata->vif.cab_queue; /* no stations in PS mode */ if (!atomic_read(&ps->num_sta_ps)) return TX_CONTINUE; info->flags |= IEEE80211_TX_CTL_SEND_AFTER_DTIM; /* device releases frame after DTIM beacon */ if (!(tx->local->hw.flags & IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING)) return TX_CONTINUE; /* buffered in mac80211 */ if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER) purge_old_ps_buffers(tx->local); if (skb_queue_len(&ps->bc_buf) >= AP_MAX_BC_BUFFER) { ps_dbg(tx->sdata, "BC TX buffer full - dropping the oldest frame\n"); dev_kfree_skb(skb_dequeue(&ps->bc_buf)); } else tx->local->total_ps_buffered++; skb_queue_tail(&ps->bc_buf, tx->skb); return TX_QUEUED; } static int ieee80211_use_mfp(__le16 fc, struct sta_info *sta, struct sk_buff *skb) { if (!ieee80211_is_mgmt(fc)) return 0; if (sta == NULL || !test_sta_flag(sta, WLAN_STA_MFP)) return 0; if (!ieee80211_is_robust_mgmt_frame((struct ieee80211_hdr *) skb->data)) return 0; return 1; } static ieee80211_tx_result ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx) { struct sta_info *sta = tx->sta; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_local *local = tx->local; if (unlikely(!sta)) return TX_CONTINUE; if (unlikely((test_sta_flag(sta, WLAN_STA_PS_STA) || test_sta_flag(sta, WLAN_STA_PS_DRIVER)) && !(info->flags & IEEE80211_TX_CTL_NO_PS_BUFFER))) { int ac = skb_get_queue_mapping(tx->skb); ps_dbg(sta->sdata, "STA %pM aid %d: PS buffer for AC %d\n", sta->sta.addr, sta->sta.aid, ac); if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER) purge_old_ps_buffers(tx->local); if (skb_queue_len(&sta->ps_tx_buf[ac]) >= STA_MAX_TX_BUFFER) { struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf[ac]); ps_dbg(tx->sdata, "STA %pM TX buffer for AC %d full - dropping oldest frame\n", sta->sta.addr, ac); ieee80211_free_txskb(&local->hw, old); } else tx->local->total_ps_buffered++; info->control.jiffies = jiffies; info->control.vif = &tx->sdata->vif; info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING; skb_queue_tail(&sta->ps_tx_buf[ac], tx->skb); if (!timer_pending(&local->sta_cleanup)) mod_timer(&local->sta_cleanup, round_jiffies(jiffies + STA_INFO_CLEANUP_INTERVAL)); /* * We queued up some frames, so the TIM bit might * need to be set, recalculate it. */ sta_info_recalc_tim(sta); return TX_QUEUED; } else if (unlikely(test_sta_flag(sta, WLAN_STA_PS_STA))) { ps_dbg(tx->sdata, "STA %pM in PS mode, but polling/in SP -> send frame\n", sta->sta.addr); } return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_ps_buf(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; if (unlikely(tx->flags & IEEE80211_TX_PS_BUFFERED)) return TX_CONTINUE; /* only deauth, disassoc and action are bufferable MMPDUs */ if (ieee80211_is_mgmt(hdr->frame_control) && !ieee80211_is_deauth(hdr->frame_control) && !ieee80211_is_disassoc(hdr->frame_control) && !ieee80211_is_action(hdr->frame_control)) { if (tx->flags & IEEE80211_TX_UNICAST) info->flags |= IEEE80211_TX_CTL_NO_PS_BUFFER; return TX_CONTINUE; } if (tx->flags & IEEE80211_TX_UNICAST) return ieee80211_tx_h_unicast_ps_buf(tx); else return ieee80211_tx_h_multicast_ps_buf(tx); } static ieee80211_tx_result debug_noinline ieee80211_tx_h_check_control_port_protocol(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); if (unlikely(tx->sdata->control_port_protocol == tx->skb->protocol)) { if (tx->sdata->control_port_no_encrypt) info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; info->control.flags |= IEEE80211_TX_CTRL_PORT_CTRL_PROTO; } return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_select_key(struct ieee80211_tx_data *tx) { struct ieee80211_key *key; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; if (unlikely(info->flags & IEEE80211_TX_INTFL_DONT_ENCRYPT)) tx->key = NULL; else if (tx->sta && (key = rcu_dereference(tx->sta->ptk))) tx->key = key; else if (ieee80211_is_mgmt(hdr->frame_control) && is_multicast_ether_addr(hdr->addr1) && ieee80211_is_robust_mgmt_frame(hdr) && (key = rcu_dereference(tx->sdata->default_mgmt_key))) tx->key = key; else if (is_multicast_ether_addr(hdr->addr1) && (key = rcu_dereference(tx->sdata->default_multicast_key))) tx->key = key; else if (!is_multicast_ether_addr(hdr->addr1) && (key = rcu_dereference(tx->sdata->default_unicast_key))) tx->key = key; else if (info->flags & IEEE80211_TX_CTL_INJECTED) tx->key = NULL; else if (!tx->sdata->drop_unencrypted) tx->key = NULL; else if (tx->skb->protocol == tx->sdata->control_port_protocol) tx->key = NULL; else if (ieee80211_is_robust_mgmt_frame(hdr) && !(ieee80211_is_action(hdr->frame_control) && tx->sta && test_sta_flag(tx->sta, WLAN_STA_MFP))) tx->key = NULL; else if (ieee80211_is_mgmt(hdr->frame_control) && !ieee80211_is_robust_mgmt_frame(hdr)) tx->key = NULL; else { I802_DEBUG_INC(tx->local->tx_handlers_drop_unencrypted); return TX_DROP; } if (tx->key) { bool skip_hw = false; tx->key->tx_rx_count++; /* TODO: add threshold stuff again */ switch (tx->key->conf.cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: case WLAN_CIPHER_SUITE_TKIP: if (!ieee80211_is_data_present(hdr->frame_control)) tx->key = NULL; break; case WLAN_CIPHER_SUITE_CCMP: if (!ieee80211_is_data_present(hdr->frame_control) && !ieee80211_use_mfp(hdr->frame_control, tx->sta, tx->skb)) tx->key = NULL; else skip_hw = (tx->key->conf.flags & IEEE80211_KEY_FLAG_SW_MGMT_TX) && ieee80211_is_mgmt(hdr->frame_control); break; case WLAN_CIPHER_SUITE_AES_CMAC: if (!ieee80211_is_mgmt(hdr->frame_control)) tx->key = NULL; break; } if (unlikely(tx->key && tx->key->flags & KEY_FLAG_TAINTED && !ieee80211_is_deauth(hdr->frame_control))) return TX_DROP; if (!skip_hw && tx->key && tx->key->flags & KEY_FLAG_UPLOADED_TO_HARDWARE) info->control.hw_key = &tx->key->conf; } return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_rate_ctrl(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (void *)tx->skb->data; struct ieee80211_supported_band *sband; u32 len; struct ieee80211_tx_rate_control txrc; struct ieee80211_sta_rates *ratetbl = NULL; bool assoc = false; memset(&txrc, 0, sizeof(txrc)); sband = tx->local->hw.wiphy->bands[info->band]; len = min_t(u32, tx->skb->len + FCS_LEN, tx->local->hw.wiphy->frag_threshold); /* set up the tx rate control struct we give the RC algo */ txrc.hw = &tx->local->hw; txrc.sband = sband; txrc.bss_conf = &tx->sdata->vif.bss_conf; txrc.skb = tx->skb; txrc.reported_rate.idx = -1; txrc.rate_idx_mask = tx->sdata->rc_rateidx_mask[info->band]; if (txrc.rate_idx_mask == (1 << sband->n_bitrates) - 1) txrc.max_rate_idx = -1; else txrc.max_rate_idx = fls(txrc.rate_idx_mask) - 1; if (tx->sdata->rc_has_mcs_mask[info->band]) txrc.rate_idx_mcs_mask = tx->sdata->rc_rateidx_mcs_mask[info->band]; txrc.bss = (tx->sdata->vif.type == NL80211_IFTYPE_AP || tx->sdata->vif.type == NL80211_IFTYPE_MESH_POINT || tx->sdata->vif.type == NL80211_IFTYPE_ADHOC); /* set up RTS protection if desired */ if (len > tx->local->hw.wiphy->rts_threshold) { txrc.rts = true; } info->control.use_rts = txrc.rts; info->control.use_cts_prot = tx->sdata->vif.bss_conf.use_cts_prot; /* * Use short preamble if the BSS can handle it, but not for * management frames unless we know the receiver can handle * that -- the management frame might be to a station that * just wants a probe response. */ if (tx->sdata->vif.bss_conf.use_short_preamble && (ieee80211_is_data(hdr->frame_control) || (tx->sta && test_sta_flag(tx->sta, WLAN_STA_SHORT_PREAMBLE)))) txrc.short_preamble = true; info->control.short_preamble = txrc.short_preamble; if (tx->sta) assoc = test_sta_flag(tx->sta, WLAN_STA_ASSOC); /* * Lets not bother rate control if we're associated and cannot * talk to the sta. This should not happen. */ if (WARN(test_bit(SCAN_SW_SCANNING, &tx->local->scanning) && assoc && !rate_usable_index_exists(sband, &tx->sta->sta), "%s: Dropped data frame as no usable bitrate found while " "scanning and associated. Target station: " "%pM on %d GHz band\n", tx->sdata->name, hdr->addr1, info->band ? 5 : 2)) return TX_DROP; /* * If we're associated with the sta at this point we know we can at * least send the frame at the lowest bit rate. */ rate_control_get_rate(tx->sdata, tx->sta, &txrc); if (tx->sta && !info->control.skip_table) ratetbl = rcu_dereference(tx->sta->sta.rates); if (unlikely(info->control.rates[0].idx < 0)) { if (ratetbl) { struct ieee80211_tx_rate rate = { .idx = ratetbl->rate[0].idx, .flags = ratetbl->rate[0].flags, .count = ratetbl->rate[0].count }; if (ratetbl->rate[0].idx < 0) return TX_DROP; tx->rate = rate; } else { return TX_DROP; } } else { tx->rate = info->control.rates[0]; } if (txrc.reported_rate.idx < 0) { txrc.reported_rate = tx->rate; if (tx->sta && ieee80211_is_data(hdr->frame_control)) tx->sta->last_tx_rate = txrc.reported_rate; } else if (tx->sta) tx->sta->last_tx_rate = txrc.reported_rate; if (ratetbl) return TX_CONTINUE; if (unlikely(!info->control.rates[0].count)) info->control.rates[0].count = 1; if (WARN_ON_ONCE((info->control.rates[0].count > 1) && (info->flags & IEEE80211_TX_CTL_NO_ACK))) info->control.rates[0].count = 1; return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_sequence(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; u16 *seq; u8 *qc; int tid; /* * Packet injection may want to control the sequence * number, if we have no matching interface then we * neither assign one ourselves nor ask the driver to. */ if (unlikely(info->control.vif->type == NL80211_IFTYPE_MONITOR)) return TX_CONTINUE; if (unlikely(ieee80211_is_ctl(hdr->frame_control))) return TX_CONTINUE; if (ieee80211_hdrlen(hdr->frame_control) < 24) return TX_CONTINUE; if (ieee80211_is_qos_nullfunc(hdr->frame_control)) return TX_CONTINUE; /* * Anything but QoS data that has a sequence number field * (is long enough) gets a sequence number from the global * counter. QoS data frames with a multicast destination * also use the global counter (802.11-2012 9.3.2.10). */ if (!ieee80211_is_data_qos(hdr->frame_control) || is_multicast_ether_addr(hdr->addr1)) { /* driver should assign sequence number */ info->flags |= IEEE80211_TX_CTL_ASSIGN_SEQ; /* for pure STA mode without beacons, we can do it */ hdr->seq_ctrl = cpu_to_le16(tx->sdata->sequence_number); tx->sdata->sequence_number += 0x10; return TX_CONTINUE; } /* * This should be true for injected/management frames only, for * management frames we have set the IEEE80211_TX_CTL_ASSIGN_SEQ * above since they are not QoS-data frames. */ if (!tx->sta) return TX_CONTINUE; /* include per-STA, per-TID sequence counter */ qc = ieee80211_get_qos_ctl(hdr); tid = *qc & IEEE80211_QOS_CTL_TID_MASK; seq = &tx->sta->tid_seq[tid]; hdr->seq_ctrl = cpu_to_le16(*seq); /* Increase the sequence number. */ *seq = (*seq + 0x10) & IEEE80211_SCTL_SEQ; return TX_CONTINUE; } static int ieee80211_fragment(struct ieee80211_tx_data *tx, struct sk_buff *skb, int hdrlen, int frag_threshold) { struct ieee80211_local *local = tx->local; struct ieee80211_tx_info *info; struct sk_buff *tmp; int per_fragm = frag_threshold - hdrlen - FCS_LEN; int pos = hdrlen + per_fragm; int rem = skb->len - hdrlen - per_fragm; if (WARN_ON(rem < 0)) return -EINVAL; /* first fragment was already added to queue by caller */ while (rem) { int fraglen = per_fragm; if (fraglen > rem) fraglen = rem; rem -= fraglen; tmp = dev_alloc_skb(local->tx_headroom + frag_threshold + IEEE80211_ENCRYPT_HEADROOM + IEEE80211_ENCRYPT_TAILROOM); if (!tmp) return -ENOMEM; __skb_queue_tail(&tx->skbs, tmp); skb_reserve(tmp, local->tx_headroom + IEEE80211_ENCRYPT_HEADROOM); /* copy control information */ memcpy(tmp->cb, skb->cb, sizeof(tmp->cb)); info = IEEE80211_SKB_CB(tmp); info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT | IEEE80211_TX_CTL_FIRST_FRAGMENT); if (rem) info->flags |= IEEE80211_TX_CTL_MORE_FRAMES; skb_copy_queue_mapping(tmp, skb); tmp->priority = skb->priority; tmp->dev = skb->dev; /* copy header and data */ memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen); memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen); pos += fraglen; } /* adjust first fragment's length */ skb->len = hdrlen + per_fragm; return 0; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_fragment(struct ieee80211_tx_data *tx) { struct sk_buff *skb = tx->skb; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_hdr *hdr = (void *)skb->data; int frag_threshold = tx->local->hw.wiphy->frag_threshold; int hdrlen; int fragnum; /* no matter what happens, tx->skb moves to tx->skbs */ __skb_queue_tail(&tx->skbs, skb); tx->skb = NULL; if (info->flags & IEEE80211_TX_CTL_DONTFRAG) return TX_CONTINUE; if (tx->local->ops->set_frag_threshold) return TX_CONTINUE; /* * Warn when submitting a fragmented A-MPDU frame and drop it. * This scenario is handled in ieee80211_tx_prepare but extra * caution taken here as fragmented ampdu may cause Tx stop. */ if (WARN_ON(info->flags & IEEE80211_TX_CTL_AMPDU)) return TX_DROP; hdrlen = ieee80211_hdrlen(hdr->frame_control); /* internal error, why isn't DONTFRAG set? */ if (WARN_ON(skb->len + FCS_LEN <= frag_threshold)) return TX_DROP; /* * Now fragment the frame. This will allocate all the fragments and * chain them (using skb as the first fragment) to skb->next. * During transmission, we will remove the successfully transmitted * fragments from this list. When the low-level driver rejects one * of the fragments then we will simply pretend to accept the skb * but store it away as pending. */ if (ieee80211_fragment(tx, skb, hdrlen, frag_threshold)) return TX_DROP; /* update duration/seq/flags of fragments */ fragnum = 0; skb_queue_walk(&tx->skbs, skb) { const __le16 morefrags = cpu_to_le16(IEEE80211_FCTL_MOREFRAGS); hdr = (void *)skb->data; info = IEEE80211_SKB_CB(skb); if (!skb_queue_is_last(&tx->skbs, skb)) { hdr->frame_control |= morefrags; /* * No multi-rate retries for fragmented frames, that * would completely throw off the NAV at other STAs. */ info->control.rates[1].idx = -1; info->control.rates[2].idx = -1; info->control.rates[3].idx = -1; BUILD_BUG_ON(IEEE80211_TX_MAX_RATES != 4); info->flags &= ~IEEE80211_TX_CTL_RATE_CTRL_PROBE; } else { hdr->frame_control &= ~morefrags; } hdr->seq_ctrl |= cpu_to_le16(fragnum & IEEE80211_SCTL_FRAG); fragnum++; } return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_stats(struct ieee80211_tx_data *tx) { struct sk_buff *skb; int ac = -1; if (!tx->sta) return TX_CONTINUE; skb_queue_walk(&tx->skbs, skb) { ac = skb_get_queue_mapping(skb); tx->sta->tx_fragments++; tx->sta->tx_bytes[ac] += skb->len; } if (ac >= 0) tx->sta->tx_packets[ac]++; return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_encrypt(struct ieee80211_tx_data *tx) { if (!tx->key) return TX_CONTINUE; switch (tx->key->conf.cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: return ieee80211_crypto_wep_encrypt(tx); case WLAN_CIPHER_SUITE_TKIP: return ieee80211_crypto_tkip_encrypt(tx); case WLAN_CIPHER_SUITE_CCMP: return ieee80211_crypto_ccmp_encrypt(tx); case WLAN_CIPHER_SUITE_AES_CMAC: return ieee80211_crypto_aes_cmac_encrypt(tx); default: return ieee80211_crypto_hw_encrypt(tx); } return TX_DROP; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_calculate_duration(struct ieee80211_tx_data *tx) { struct sk_buff *skb; struct ieee80211_hdr *hdr; int next_len; bool group_addr; skb_queue_walk(&tx->skbs, skb) { hdr = (void *) skb->data; if (unlikely(ieee80211_is_pspoll(hdr->frame_control))) break; /* must not overwrite AID */ if (!skb_queue_is_last(&tx->skbs, skb)) { struct sk_buff *next = skb_queue_next(&tx->skbs, skb); next_len = next->len; } else next_len = 0; group_addr = is_multicast_ether_addr(hdr->addr1); hdr->duration_id = ieee80211_duration(tx, skb, group_addr, next_len); } return TX_CONTINUE; } /* actual transmit path */ static bool ieee80211_tx_prep_agg(struct ieee80211_tx_data *tx, struct sk_buff *skb, struct ieee80211_tx_info *info, struct tid_ampdu_tx *tid_tx, int tid) { bool queued = false; bool reset_agg_timer = false; struct sk_buff *purge_skb = NULL; if (test_bit(HT_AGG_STATE_OPERATIONAL, &tid_tx->state)) { info->flags |= IEEE80211_TX_CTL_AMPDU; reset_agg_timer = true; } else if (test_bit(HT_AGG_STATE_WANT_START, &tid_tx->state)) { /* * nothing -- this aggregation session is being started * but that might still fail with the driver */ } else { spin_lock(&tx->sta->lock); /* * Need to re-check now, because we may get here * * 1) in the window during which the setup is actually * already done, but not marked yet because not all * packets are spliced over to the driver pending * queue yet -- if this happened we acquire the lock * either before or after the splice happens, but * need to recheck which of these cases happened. * * 2) during session teardown, if the OPERATIONAL bit * was cleared due to the teardown but the pointer * hasn't been assigned NULL yet (or we loaded it * before it was assigned) -- in this case it may * now be NULL which means we should just let the * packet pass through because splicing the frames * back is already done. */ tid_tx = rcu_dereference_protected_tid_tx(tx->sta, tid); if (!tid_tx) { /* do nothing, let packet pass through */ } else if (test_bit(HT_AGG_STATE_OPERATIONAL, &tid_tx->state)) { info->flags |= IEEE80211_TX_CTL_AMPDU; reset_agg_timer = true; } else { queued = true; info->control.vif = &tx->sdata->vif; info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING; __skb_queue_tail(&tid_tx->pending, skb); if (skb_queue_len(&tid_tx->pending) > STA_MAX_TX_BUFFER) purge_skb = __skb_dequeue(&tid_tx->pending); } spin_unlock(&tx->sta->lock); if (purge_skb) ieee80211_free_txskb(&tx->local->hw, purge_skb); } /* reset session timer */ if (reset_agg_timer && tid_tx->timeout) tid_tx->last_tx = jiffies; return queued; } /* * initialises @tx */ static ieee80211_tx_result ieee80211_tx_prepare(struct ieee80211_sub_if_data *sdata, struct ieee80211_tx_data *tx, struct sk_buff *skb) { struct ieee80211_local *local = sdata->local; struct ieee80211_hdr *hdr; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); int tid; u8 *qc; memset(tx, 0, sizeof(*tx)); tx->skb = skb; tx->local = local; tx->sdata = sdata; __skb_queue_head_init(&tx->skbs); /* * If this flag is set to true anywhere, and we get here, * we are doing the needed processing, so remove the flag * now. */ info->flags &= ~IEEE80211_TX_INTFL_NEED_TXPROCESSING; hdr = (struct ieee80211_hdr *) skb->data; if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { tx->sta = rcu_dereference(sdata->u.vlan.sta); if (!tx->sta && sdata->dev->ieee80211_ptr->use_4addr) return TX_DROP; } else if (info->flags & (IEEE80211_TX_CTL_INJECTED | IEEE80211_TX_INTFL_NL80211_FRAME_TX) || tx->sdata->control_port_protocol == tx->skb->protocol) { tx->sta = sta_info_get_bss(sdata, hdr->addr1); } if (!tx->sta) tx->sta = sta_info_get(sdata, hdr->addr1); if (tx->sta && ieee80211_is_data_qos(hdr->frame_control) && !ieee80211_is_qos_nullfunc(hdr->frame_control) && (local->hw.flags & IEEE80211_HW_AMPDU_AGGREGATION) && !(local->hw.flags & IEEE80211_HW_TX_AMPDU_SETUP_IN_HW)) { struct tid_ampdu_tx *tid_tx; qc = ieee80211_get_qos_ctl(hdr); tid = *qc & IEEE80211_QOS_CTL_TID_MASK; tid_tx = rcu_dereference(tx->sta->ampdu_mlme.tid_tx[tid]); if (tid_tx) { bool queued; queued = ieee80211_tx_prep_agg(tx, skb, info, tid_tx, tid); if (unlikely(queued)) return TX_QUEUED; } } if (is_multicast_ether_addr(hdr->addr1)) { tx->flags &= ~IEEE80211_TX_UNICAST; info->flags |= IEEE80211_TX_CTL_NO_ACK; } else tx->flags |= IEEE80211_TX_UNICAST; if (!(info->flags & IEEE80211_TX_CTL_DONTFRAG)) { if (!(tx->flags & IEEE80211_TX_UNICAST) || skb->len + FCS_LEN <= local->hw.wiphy->frag_threshold || info->flags & IEEE80211_TX_CTL_AMPDU) info->flags |= IEEE80211_TX_CTL_DONTFRAG; } if (!tx->sta) info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT; else if (test_and_clear_sta_flag(tx->sta, WLAN_STA_CLEAR_PS_FILT)) info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT; info->flags |= IEEE80211_TX_CTL_FIRST_FRAGMENT; return TX_CONTINUE; } static bool ieee80211_tx_frags(struct ieee80211_local *local, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct sk_buff_head *skbs, bool txpending) { struct ieee80211_tx_control control; struct sk_buff *skb, *tmp; unsigned long flags; skb_queue_walk_safe(skbs, skb, tmp) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); int q = info->hw_queue; #ifdef CPTCFG_MAC80211_VERBOSE_DEBUG if (WARN_ON_ONCE(q >= local->hw.queues)) { __skb_unlink(skb, skbs); ieee80211_free_txskb(&local->hw, skb); continue; } #endif spin_lock_irqsave(&local->queue_stop_reason_lock, flags); if (local->queue_stop_reasons[q] || (!txpending && !skb_queue_empty(&local->pending[q]))) { if (unlikely(info->flags & IEEE80211_TX_INTFL_OFFCHAN_TX_OK)) { if (local->queue_stop_reasons[q] & ~BIT(IEEE80211_QUEUE_STOP_REASON_OFFCHANNEL)) { /* * Drop off-channel frames if queues * are stopped for any reason other * than off-channel operation. Never * queue them. */ spin_unlock_irqrestore( &local->queue_stop_reason_lock, flags); ieee80211_purge_tx_queue(&local->hw, skbs); return true; } } else { /* * Since queue is stopped, queue up frames for * later transmission from the tx-pending * tasklet when the queue is woken again. */ if (txpending) skb_queue_splice_init(skbs, &local->pending[q]); else skb_queue_splice_tail_init(skbs, &local->pending[q]); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); return false; } } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); info->control.vif = vif; control.sta = sta; __skb_unlink(skb, skbs); drv_tx(local, &control, skb); } return true; } /* * Returns false if the frame couldn't be transmitted but was queued instead. */ static bool __ieee80211_tx(struct ieee80211_local *local, struct sk_buff_head *skbs, int led_len, struct sta_info *sta, bool txpending) { struct ieee80211_tx_info *info; struct ieee80211_sub_if_data *sdata; struct ieee80211_vif *vif; struct ieee80211_sta *pubsta; struct sk_buff *skb; bool result = true; __le16 fc; if (WARN_ON(skb_queue_empty(skbs))) return true; skb = skb_peek(skbs); fc = ((struct ieee80211_hdr *)skb->data)->frame_control; info = IEEE80211_SKB_CB(skb); sdata = vif_to_sdata(info->control.vif); if (sta && !sta->uploaded) sta = NULL; if (sta) pubsta = &sta->sta; else pubsta = NULL; switch (sdata->vif.type) { case NL80211_IFTYPE_MONITOR: if (sdata->u.mntr_flags & MONITOR_FLAG_ACTIVE) { vif = &sdata->vif; break; } sdata = rcu_dereference(local->monitor_sdata); if (sdata) { vif = &sdata->vif; info->hw_queue = vif->hw_queue[skb_get_queue_mapping(skb)]; } else if (local->hw.flags & IEEE80211_HW_QUEUE_CONTROL) { dev_kfree_skb(skb); return true; } else vif = NULL; break; case NL80211_IFTYPE_AP_VLAN: sdata = container_of(sdata->bss, struct ieee80211_sub_if_data, u.ap); /* fall through */ default: vif = &sdata->vif; break; } result = ieee80211_tx_frags(local, vif, pubsta, skbs, txpending); ieee80211_tpt_led_trig_tx(local, fc, led_len); WARN_ON_ONCE(!skb_queue_empty(skbs)); return result; } /* * Invoke TX handlers, return 0 on success and non-zero if the * frame was dropped or queued. */ static int invoke_tx_handlers(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); ieee80211_tx_result res = TX_DROP; #define CALL_TXH(txh) \ do { \ res = txh(tx); \ if (res != TX_CONTINUE) \ goto txh_done; \ } while (0) CALL_TXH(ieee80211_tx_h_dynamic_ps); CALL_TXH(ieee80211_tx_h_check_assoc); CALL_TXH(ieee80211_tx_h_ps_buf); CALL_TXH(ieee80211_tx_h_check_control_port_protocol); CALL_TXH(ieee80211_tx_h_select_key); if (!(tx->local->hw.flags & IEEE80211_HW_HAS_RATE_CONTROL)) CALL_TXH(ieee80211_tx_h_rate_ctrl); if (unlikely(info->flags & IEEE80211_TX_INTFL_RETRANSMISSION)) { __skb_queue_tail(&tx->skbs, tx->skb); tx->skb = NULL; goto txh_done; } CALL_TXH(ieee80211_tx_h_michael_mic_add); CALL_TXH(ieee80211_tx_h_sequence); CALL_TXH(ieee80211_tx_h_fragment); /* handlers after fragment must be aware of tx info fragmentation! */ CALL_TXH(ieee80211_tx_h_stats); CALL_TXH(ieee80211_tx_h_encrypt); if (!(tx->local->hw.flags & IEEE80211_HW_HAS_RATE_CONTROL)) CALL_TXH(ieee80211_tx_h_calculate_duration); #undef CALL_TXH txh_done: if (unlikely(res == TX_DROP)) { I802_DEBUG_INC(tx->local->tx_handlers_drop); if (tx->skb) ieee80211_free_txskb(&tx->local->hw, tx->skb); else ieee80211_purge_tx_queue(&tx->local->hw, &tx->skbs); return -1; } else if (unlikely(res == TX_QUEUED)) { I802_DEBUG_INC(tx->local->tx_handlers_queued); return -1; } return 0; } bool ieee80211_tx_prepare_skb(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct sk_buff *skb, int band, struct ieee80211_sta **sta) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_tx_data tx; if (ieee80211_tx_prepare(sdata, &tx, skb) == TX_DROP) return false; info->band = band; info->control.vif = vif; info->hw_queue = vif->hw_queue[skb_get_queue_mapping(skb)]; if (invoke_tx_handlers(&tx)) return false; if (sta) { if (tx.sta) *sta = &tx.sta->sta; else *sta = NULL; } return true; } EXPORT_SYMBOL(ieee80211_tx_prepare_skb); /* * Returns false if the frame couldn't be transmitted but was queued instead. */ static bool ieee80211_tx(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, bool txpending, enum ieee80211_band band) { struct ieee80211_local *local = sdata->local; struct ieee80211_tx_data tx; ieee80211_tx_result res_prepare; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); bool result = true; int led_len; if (unlikely(skb->len < 10)) { dev_kfree_skb(skb); return true; } /* initialises tx */ led_len = skb->len; res_prepare = ieee80211_tx_prepare(sdata, &tx, skb); if (unlikely(res_prepare == TX_DROP)) { ieee80211_free_txskb(&local->hw, skb); return true; } else if (unlikely(res_prepare == TX_QUEUED)) { return true; } info->band = band; /* set up hw_queue value early */ if (!(info->flags & IEEE80211_TX_CTL_TX_OFFCHAN) || !(local->hw.flags & IEEE80211_HW_QUEUE_CONTROL)) info->hw_queue = sdata->vif.hw_queue[skb_get_queue_mapping(skb)]; if (!invoke_tx_handlers(&tx)) result = __ieee80211_tx(local, &tx.skbs, led_len, tx.sta, txpending); return result; } /* device xmit handlers */ static int ieee80211_skb_resize(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, int head_need, bool may_encrypt) { struct ieee80211_local *local = sdata->local; int tail_need = 0; if (may_encrypt && sdata->crypto_tx_tailroom_needed_cnt) { tail_need = IEEE80211_ENCRYPT_TAILROOM; tail_need -= skb_tailroom(skb); tail_need = max_t(int, tail_need, 0); } if (skb_cloned(skb)) I802_DEBUG_INC(local->tx_expand_skb_head_cloned); else if (head_need || tail_need) I802_DEBUG_INC(local->tx_expand_skb_head); else return 0; if (pskb_expand_head(skb, head_need, tail_need, GFP_ATOMIC)) { wiphy_debug(local->hw.wiphy, "failed to reallocate TX buffer\n"); return -ENOMEM; } return 0; } void ieee80211_xmit(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, enum ieee80211_band band) { struct ieee80211_local *local = sdata->local; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; int headroom; bool may_encrypt; may_encrypt = !(info->flags & IEEE80211_TX_INTFL_DONT_ENCRYPT); headroom = local->tx_headroom; if (may_encrypt) headroom += IEEE80211_ENCRYPT_HEADROOM; headroom -= skb_headroom(skb); headroom = max_t(int, 0, headroom); if (ieee80211_skb_resize(sdata, skb, headroom, may_encrypt)) { ieee80211_free_txskb(&local->hw, skb); return; } hdr = (struct ieee80211_hdr *) skb->data; info->control.vif = &sdata->vif; if (ieee80211_vif_is_mesh(&sdata->vif)) { if (ieee80211_is_data(hdr->frame_control) && is_unicast_ether_addr(hdr->addr1)) { if (mesh_nexthop_resolve(sdata, skb)) return; /* skb queued: don't free */ } else { ieee80211_mps_set_frame_flags(sdata, NULL, hdr); } } #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,27)) /* Older kernels do not have the select_queue callback */ skb_set_queue_mapping(skb, ieee80211_select_queue(sdata, skb)); #endif ieee80211_set_qos_hdr(sdata, skb); ieee80211_tx(sdata, skb, false, band); } static bool ieee80211_parse_tx_radiotap(struct sk_buff *skb) { struct ieee80211_radiotap_iterator iterator; struct ieee80211_radiotap_header *rthdr = (struct ieee80211_radiotap_header *) skb->data; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); int ret = ieee80211_radiotap_iterator_init(&iterator, rthdr, skb->len, NULL); u16 txflags; info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT | IEEE80211_TX_CTL_DONTFRAG; /* * for every radiotap entry that is present * (ieee80211_radiotap_iterator_next returns -ENOENT when no more * entries present, or -EINVAL on error) */ while (!ret) { ret = ieee80211_radiotap_iterator_next(&iterator); if (ret) continue; /* see if this argument is something we can use */ switch (iterator.this_arg_index) { /* * You must take care when dereferencing iterator.this_arg * for multibyte types... the pointer is not aligned. Use * get_unaligned((type *)iterator.this_arg) to dereference * iterator.this_arg for type "type" safely on all arches. */ case IEEE80211_RADIOTAP_FLAGS: if (*iterator.this_arg & IEEE80211_RADIOTAP_F_FCS) { /* * this indicates that the skb we have been * handed has the 32-bit FCS CRC at the end... * we should react to that by snipping it off * because it will be recomputed and added * on transmission */ if (skb->len < (iterator._max_length + FCS_LEN)) return false; skb_trim(skb, skb->len - FCS_LEN); } if (*iterator.this_arg & IEEE80211_RADIOTAP_F_WEP) info->flags &= ~IEEE80211_TX_INTFL_DONT_ENCRYPT; if (*iterator.this_arg & IEEE80211_RADIOTAP_F_FRAG) info->flags &= ~IEEE80211_TX_CTL_DONTFRAG; break; case IEEE80211_RADIOTAP_TX_FLAGS: txflags = get_unaligned_le16(iterator.this_arg); if (txflags & IEEE80211_RADIOTAP_F_TX_NOACK) info->flags |= IEEE80211_TX_CTL_NO_ACK; break; /* * Please update the file * Documentation/networking/mac80211-injection.txt * when parsing new fields here. */ default: break; } } if (ret != -ENOENT) /* ie, if we didn't simply run out of fields */ return false; /* * remove the radiotap header * iterator->_max_length was sanity-checked against * skb->len by iterator init */ skb_pull(skb, iterator._max_length); return true; } netdev_tx_t ieee80211_monitor_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct ieee80211_local *local = wdev_priv(dev->ieee80211_ptr); struct ieee80211_chanctx_conf *chanctx_conf; struct ieee80211_channel *chan; struct ieee80211_radiotap_header *prthdr = (struct ieee80211_radiotap_header *)skb->data; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_hdr *hdr; struct ieee80211_sub_if_data *tmp_sdata, *sdata; u16 len_rthdr; int hdrlen; /* check for not even having the fixed radiotap header part */ if (unlikely(skb->len < sizeof(struct ieee80211_radiotap_header))) goto fail; /* too short to be possibly valid */ /* is it a header version we can trust to find length from? */ if (unlikely(prthdr->it_version)) goto fail; /* only version 0 is supported */ /* then there must be a radiotap header with a length we can use */ len_rthdr = ieee80211_get_radiotap_len(skb->data); /* does the skb contain enough to deliver on the alleged length? */ if (unlikely(skb->len < len_rthdr)) goto fail; /* skb too short for claimed rt header extent */ /* * fix up the pointers accounting for the radiotap * header still being in there. We are being given * a precooked IEEE80211 header so no need for * normal processing */ skb_set_mac_header(skb, len_rthdr); /* * these are just fixed to the end of the rt area since we * don't have any better information and at this point, nobody cares */ skb_set_network_header(skb, len_rthdr); skb_set_transport_header(skb, len_rthdr); if (skb->len < len_rthdr + 2) goto fail; hdr = (struct ieee80211_hdr *)(skb->data + len_rthdr); hdrlen = ieee80211_hdrlen(hdr->frame_control); if (skb->len < len_rthdr + hdrlen) goto fail; /* * Initialize skb->protocol if the injected frame is a data frame * carrying a rfc1042 header */ if (ieee80211_is_data(hdr->frame_control) && skb->len >= len_rthdr + hdrlen + sizeof(rfc1042_header) + 2) { u8 *payload = (u8 *)hdr + hdrlen; if (ether_addr_equal(payload, rfc1042_header)) skb->protocol = cpu_to_be16((payload[6] << 8) | payload[7]); } memset(info, 0, sizeof(*info)); info->flags = IEEE80211_TX_CTL_REQ_TX_STATUS | IEEE80211_TX_CTL_INJECTED; /* process and remove the injection radiotap header */ if (!ieee80211_parse_tx_radiotap(skb)) goto fail; rcu_read_lock(); /* * We process outgoing injected frames that have a local address * we handle as though they are non-injected frames. * This code here isn't entirely correct, the local MAC address * isn't always enough to find the interface to use; for proper * VLAN/WDS support we will need a different mechanism (which * likely isn't going to be monitor interfaces). */ sdata = IEEE80211_DEV_TO_SUB_IF(dev); list_for_each_entry_rcu(tmp_sdata, &local->interfaces, list) { if (!ieee80211_sdata_running(tmp_sdata)) continue; if (tmp_sdata->vif.type == NL80211_IFTYPE_MONITOR || tmp_sdata->vif.type == NL80211_IFTYPE_AP_VLAN || tmp_sdata->vif.type == NL80211_IFTYPE_WDS) continue; if (ether_addr_equal(tmp_sdata->vif.addr, hdr->addr2)) { sdata = tmp_sdata; break; } } chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) { tmp_sdata = rcu_dereference(local->monitor_sdata); if (tmp_sdata) chanctx_conf = rcu_dereference(tmp_sdata->vif.chanctx_conf); } if (chanctx_conf) chan = chanctx_conf->def.chan; else if (!local->use_chanctx) chan = local->_oper_chandef.chan; else goto fail_rcu; /* * Frame injection is not allowed if beaconing is not allowed * or if we need radar detection. Beaconing is usually not allowed when * the mode or operation (Adhoc, AP, Mesh) does not support DFS. * Passive scan is also used in world regulatory domains where * your country is not known and as such it should be treated as * NO TX unless the channel is explicitly allowed in which case * your current regulatory domain would not have the passive scan * flag. * * Since AP mode uses monitor interfaces to inject/TX management * frames we can make AP mode the exception to this rule once it * supports radar detection as its implementation can deal with * radar detection by itself. We can do that later by adding a * monitor flag interfaces used for AP support. */ if ((chan->flags & (IEEE80211_CHAN_NO_IBSS | IEEE80211_CHAN_RADAR | IEEE80211_CHAN_PASSIVE_SCAN))) goto fail_rcu; ieee80211_xmit(sdata, skb, chan->band); rcu_read_unlock(); return NETDEV_TX_OK; fail_rcu: rcu_read_unlock(); fail: dev_kfree_skb(skb); return NETDEV_TX_OK; /* meaning, we dealt with the skb */ } /** * ieee80211_subif_start_xmit - netif start_xmit function for Ethernet-type * subinterfaces (wlan#, WDS, and VLAN interfaces) * @skb: packet to be sent * @dev: incoming interface * * Returns: 0 on success (and frees skb in this case) or 1 on failure (skb will * not be freed, and caller is responsible for either retrying later or freeing * skb). * * This function takes in an Ethernet header and encapsulates it with suitable * IEEE 802.11 header based on which interface the packet is coming in. The * encapsulated packet will then be passed to master interface, wlan#.11, for * transmission (through low-level driver). */ netdev_tx_t ieee80211_subif_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev); struct ieee80211_local *local = sdata->local; struct ieee80211_tx_info *info; int head_need; u16 ethertype, hdrlen, meshhdrlen = 0; __le16 fc; struct ieee80211_hdr hdr; struct ieee80211s_hdr mesh_hdr __maybe_unused; struct mesh_path __maybe_unused *mppath = NULL, *mpath = NULL; const u8 *encaps_data; int encaps_len, skip_header_bytes; int nh_pos, h_pos; struct sta_info *sta = NULL; bool wme_sta = false, authorized = false, tdls_auth = false; bool tdls_direct = false; bool multicast; u32 info_flags = 0; u16 info_id = 0; struct ieee80211_chanctx_conf *chanctx_conf; struct ieee80211_sub_if_data *ap_sdata; enum ieee80211_band band; if (unlikely(skb->len < ETH_HLEN)) goto fail; /* convert Ethernet header to proper 802.11 header (based on * operation mode) */ ethertype = (skb->data[12] << 8) | skb->data[13]; fc = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_DATA); rcu_read_lock(); switch (sdata->vif.type) { case NL80211_IFTYPE_AP_VLAN: sta = rcu_dereference(sdata->u.vlan.sta); if (sta) { fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS); /* RA TA DA SA */ memcpy(hdr.addr1, sta->sta.addr, ETH_ALEN); memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); memcpy(hdr.addr3, skb->data, ETH_ALEN); memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN); hdrlen = 30; authorized = test_sta_flag(sta, WLAN_STA_AUTHORIZED); wme_sta = test_sta_flag(sta, WLAN_STA_WME); } ap_sdata = container_of(sdata->bss, struct ieee80211_sub_if_data, u.ap); chanctx_conf = rcu_dereference(ap_sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; band = chanctx_conf->def.chan->band; if (sta) break; /* fall through */ case NL80211_IFTYPE_AP: if (sdata->vif.type == NL80211_IFTYPE_AP) chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS); /* DA BSSID SA */ memcpy(hdr.addr1, skb->data, ETH_ALEN); memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); memcpy(hdr.addr3, skb->data + ETH_ALEN, ETH_ALEN); hdrlen = 24; band = chanctx_conf->def.chan->band; break; case NL80211_IFTYPE_WDS: fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS); /* RA TA DA SA */ memcpy(hdr.addr1, sdata->u.wds.remote_addr, ETH_ALEN); memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); memcpy(hdr.addr3, skb->data, ETH_ALEN); memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN); hdrlen = 30; /* * This is the exception! WDS style interfaces are prohibited * when channel contexts are in used so this must be valid */ band = local->hw.conf.chandef.chan->band; break; #ifdef CPTCFG_MAC80211_MESH case NL80211_IFTYPE_MESH_POINT: if (!is_multicast_ether_addr(skb->data)) { struct sta_info *next_hop; bool mpp_lookup = true; mpath = mesh_path_lookup(sdata, skb->data); if (mpath) { mpp_lookup = false; next_hop = rcu_dereference(mpath->next_hop); if (!next_hop || !(mpath->flags & (MESH_PATH_ACTIVE | MESH_PATH_RESOLVING))) mpp_lookup = true; } if (mpp_lookup) mppath = mpp_path_lookup(sdata, skb->data); if (mppath && mpath) mesh_path_del(mpath->sdata, mpath->dst); } /* * Use address extension if it is a packet from * another interface or if we know the destination * is being proxied by a portal (i.e. portal address * differs from proxied address) */ if (ether_addr_equal(sdata->vif.addr, skb->data + ETH_ALEN) && !(mppath && !ether_addr_equal(mppath->mpp, skb->data))) { hdrlen = ieee80211_fill_mesh_addresses(&hdr, &fc, skb->data, skb->data + ETH_ALEN); meshhdrlen = ieee80211_new_mesh_header(sdata, &mesh_hdr, NULL, NULL); } else { /* DS -> MBSS (802.11-2012 13.11.3.3). * For unicast with unknown forwarding information, * destination might be in the MBSS or if that fails * forwarded to another mesh gate. In either case * resolution will be handled in ieee80211_xmit(), so * leave the original DA. This also works for mcast */ const u8 *mesh_da = skb->data; if (mppath) mesh_da = mppath->mpp; else if (mpath) mesh_da = mpath->dst; hdrlen = ieee80211_fill_mesh_addresses(&hdr, &fc, mesh_da, sdata->vif.addr); if (is_multicast_ether_addr(mesh_da)) /* DA TA mSA AE:SA */ meshhdrlen = ieee80211_new_mesh_header( sdata, &mesh_hdr, skb->data + ETH_ALEN, NULL); else /* RA TA mDA mSA AE:DA SA */ meshhdrlen = ieee80211_new_mesh_header( sdata, &mesh_hdr, skb->data, skb->data + ETH_ALEN); } chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; band = chanctx_conf->def.chan->band; break; #endif case NL80211_IFTYPE_STATION: if (sdata->wdev.wiphy->flags & WIPHY_FLAG_SUPPORTS_TDLS) { bool tdls_peer = false; sta = sta_info_get(sdata, skb->data); if (sta) { authorized = test_sta_flag(sta, WLAN_STA_AUTHORIZED); wme_sta = test_sta_flag(sta, WLAN_STA_WME); tdls_peer = test_sta_flag(sta, WLAN_STA_TDLS_PEER); tdls_auth = test_sta_flag(sta, WLAN_STA_TDLS_PEER_AUTH); } /* * If the TDLS link is enabled, send everything * directly. Otherwise, allow TDLS setup frames * to be transmitted indirectly. */ tdls_direct = tdls_peer && (tdls_auth || !(ethertype == ETH_P_TDLS && skb->len > 14 && skb->data[14] == WLAN_TDLS_SNAP_RFTYPE)); } if (tdls_direct) { /* link during setup - throw out frames to peer */ if (!tdls_auth) goto fail_rcu; /* DA SA BSSID */ memcpy(hdr.addr1, skb->data, ETH_ALEN); memcpy(hdr.addr2, skb->data + ETH_ALEN, ETH_ALEN); memcpy(hdr.addr3, sdata->u.mgd.bssid, ETH_ALEN); hdrlen = 24; } else if (sdata->u.mgd.use_4addr && cpu_to_be16(ethertype) != sdata->control_port_protocol) { fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS); /* RA TA DA SA */ memcpy(hdr.addr1, sdata->u.mgd.bssid, ETH_ALEN); memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); memcpy(hdr.addr3, skb->data, ETH_ALEN); memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN); hdrlen = 30; } else { fc |= cpu_to_le16(IEEE80211_FCTL_TODS); /* BSSID SA DA */ memcpy(hdr.addr1, sdata->u.mgd.bssid, ETH_ALEN); memcpy(hdr.addr2, skb->data + ETH_ALEN, ETH_ALEN); memcpy(hdr.addr3, skb->data, ETH_ALEN); hdrlen = 24; } chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; band = chanctx_conf->def.chan->band; break; case NL80211_IFTYPE_ADHOC: /* DA SA BSSID */ memcpy(hdr.addr1, skb->data, ETH_ALEN); memcpy(hdr.addr2, skb->data + ETH_ALEN, ETH_ALEN); memcpy(hdr.addr3, sdata->u.ibss.bssid, ETH_ALEN); hdrlen = 24; chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; band = chanctx_conf->def.chan->band; break; default: goto fail_rcu; } /* * There's no need to try to look up the destination * if it is a multicast address (which can only happen * in AP mode) */ multicast = is_multicast_ether_addr(hdr.addr1); if (!multicast) { sta = sta_info_get(sdata, hdr.addr1); if (sta) { authorized = test_sta_flag(sta, WLAN_STA_AUTHORIZED); wme_sta = test_sta_flag(sta, WLAN_STA_WME); } } /* For mesh, the use of the QoS header is mandatory */ if (ieee80211_vif_is_mesh(&sdata->vif)) wme_sta = true; /* receiver and we are QoS enabled, use a QoS type frame */ if (wme_sta && local->hw.queues >= IEEE80211_NUM_ACS) { fc |= cpu_to_le16(IEEE80211_STYPE_QOS_DATA); hdrlen += 2; } /* * Drop unicast frames to unauthorised stations unless they are * EAPOL frames from the local station. */ if (unlikely(!ieee80211_vif_is_mesh(&sdata->vif) && !multicast && !authorized && (cpu_to_be16(ethertype) != sdata->control_port_protocol || !ether_addr_equal(sdata->vif.addr, skb->data + ETH_ALEN)))) { #ifdef CPTCFG_MAC80211_VERBOSE_DEBUG net_info_ratelimited("%s: dropped frame to %pM (unauthorized port)\n", dev->name, hdr.addr1); #endif I802_DEBUG_INC(local->tx_handlers_drop_unauth_port); goto fail_rcu; } #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,3,0)) if (unlikely(!multicast && skb->sk && skb_shinfo(skb)->tx_flags & SKBTX_WIFI_STATUS)) { struct sk_buff *orig_skb = skb; skb = skb_clone(skb, GFP_ATOMIC); if (skb) { unsigned long flags; int id; spin_lock_irqsave(&local->ack_status_lock, flags); id = idr_alloc(&local->ack_status_frames, orig_skb, 1, 0x10000, GFP_ATOMIC); spin_unlock_irqrestore(&local->ack_status_lock, flags); if (id >= 0) { info_id = id; info_flags |= IEEE80211_TX_CTL_REQ_TX_STATUS; } else if (skb_shared(skb)) { kfree_skb(orig_skb); } else { kfree_skb(skb); skb = orig_skb; } } else { /* couldn't clone -- lose tx status ... */ skb = orig_skb; } } #endif /* * If the skb is shared we need to obtain our own copy. */ if (skb_shared(skb)) { struct sk_buff *tmp_skb = skb; /* can't happen -- skb is a clone if info_id != 0 */ WARN_ON(info_id); skb = skb_clone(skb, GFP_ATOMIC); kfree_skb(tmp_skb); if (!skb) goto fail_rcu; } hdr.frame_control = fc; hdr.duration_id = 0; hdr.seq_ctrl = 0; skip_header_bytes = ETH_HLEN; if (ethertype == ETH_P_AARP || ethertype == ETH_P_IPX) { encaps_data = bridge_tunnel_header; encaps_len = sizeof(bridge_tunnel_header); skip_header_bytes -= 2; } else if (ethertype >= ETH_P_802_3_MIN) { encaps_data = rfc1042_header; encaps_len = sizeof(rfc1042_header); skip_header_bytes -= 2; } else { encaps_data = NULL; encaps_len = 0; } nh_pos = skb_network_header(skb) - skb->data; h_pos = skb_transport_header(skb) - skb->data; skb_pull(skb, skip_header_bytes); nh_pos -= skip_header_bytes; h_pos -= skip_header_bytes; head_need = hdrlen + encaps_len + meshhdrlen - skb_headroom(skb); /* * So we need to modify the skb header and hence need a copy of * that. The head_need variable above doesn't, so far, include * the needed header space that we don't need right away. If we * can, then we don't reallocate right now but only after the * frame arrives at the master device (if it does...) * * If we cannot, however, then we will reallocate to include all * the ever needed space. Also, if we need to reallocate it anyway, * make it big enough for everything we may ever need. */ if (head_need > 0 || skb_cloned(skb)) { head_need += IEEE80211_ENCRYPT_HEADROOM; head_need += local->tx_headroom; head_need = max_t(int, 0, head_need); if (ieee80211_skb_resize(sdata, skb, head_need, true)) { ieee80211_free_txskb(&local->hw, skb); skb = NULL; goto fail_rcu; } } if (encaps_data) { memcpy(skb_push(skb, encaps_len), encaps_data, encaps_len); nh_pos += encaps_len; h_pos += encaps_len; } #ifdef CPTCFG_MAC80211_MESH if (meshhdrlen > 0) { memcpy(skb_push(skb, meshhdrlen), &mesh_hdr, meshhdrlen); nh_pos += meshhdrlen; h_pos += meshhdrlen; } #endif if (ieee80211_is_data_qos(fc)) { __le16 *qos_control; qos_control = (__le16*) skb_push(skb, 2); memcpy(skb_push(skb, hdrlen - 2), &hdr, hdrlen - 2); /* * Maybe we could actually set some fields here, for now just * initialise to zero to indicate no special operation. */ *qos_control = 0; } else memcpy(skb_push(skb, hdrlen), &hdr, hdrlen); nh_pos += hdrlen; h_pos += hdrlen; dev->stats.tx_packets++; dev->stats.tx_bytes += skb->len; /* Update skb pointers to various headers since this modified frame * is going to go through Linux networking code that may potentially * need things like pointer to IP header. */ skb_set_mac_header(skb, 0); skb_set_network_header(skb, nh_pos); skb_set_transport_header(skb, h_pos); info = IEEE80211_SKB_CB(skb); memset(info, 0, sizeof(*info)); dev->trans_start = jiffies; info->flags = info_flags; info->ack_frame_id = info_id; ieee80211_xmit(sdata, skb, band); rcu_read_unlock(); return NETDEV_TX_OK; fail_rcu: rcu_read_unlock(); fail: dev_kfree_skb(skb); return NETDEV_TX_OK; } /* * ieee80211_clear_tx_pending may not be called in a context where * it is possible that it packets could come in again. */ void ieee80211_clear_tx_pending(struct ieee80211_local *local) { struct sk_buff *skb; int i; for (i = 0; i < local->hw.queues; i++) { while ((skb = skb_dequeue(&local->pending[i])) != NULL) ieee80211_free_txskb(&local->hw, skb); } } /* * Returns false if the frame couldn't be transmitted but was queued instead, * which in this case means re-queued -- take as an indication to stop sending * more pending frames. */ static bool ieee80211_tx_pending_skb(struct ieee80211_local *local, struct sk_buff *skb) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_sub_if_data *sdata; struct sta_info *sta; struct ieee80211_hdr *hdr; bool result; struct ieee80211_chanctx_conf *chanctx_conf; sdata = vif_to_sdata(info->control.vif); if (info->flags & IEEE80211_TX_INTFL_NEED_TXPROCESSING) { chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (unlikely(!chanctx_conf)) { dev_kfree_skb(skb); return true; } result = ieee80211_tx(sdata, skb, true, chanctx_conf->def.chan->band); } else { struct sk_buff_head skbs; __skb_queue_head_init(&skbs); __skb_queue_tail(&skbs, skb); hdr = (struct ieee80211_hdr *)skb->data; sta = sta_info_get(sdata, hdr->addr1); result = __ieee80211_tx(local, &skbs, skb->len, sta, true); } return result; } /* * Transmit all pending packets. Called from tasklet. */ void ieee80211_tx_pending(unsigned long data) { struct ieee80211_local *local = (struct ieee80211_local *)data; unsigned long flags; int i; bool txok; rcu_read_lock(); spin_lock_irqsave(&local->queue_stop_reason_lock, flags); for (i = 0; i < local->hw.queues; i++) { /* * If queue is stopped by something other than due to pending * frames, or we have no pending frames, proceed to next queue. */ if (local->queue_stop_reasons[i] || skb_queue_empty(&local->pending[i])) continue; while (!skb_queue_empty(&local->pending[i])) { struct sk_buff *skb = __skb_dequeue(&local->pending[i]); struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); if (WARN_ON(!info->control.vif)) { ieee80211_free_txskb(&local->hw, skb); continue; } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); txok = ieee80211_tx_pending_skb(local, skb); spin_lock_irqsave(&local->queue_stop_reason_lock, flags); if (!txok) break; } if (skb_queue_empty(&local->pending[i])) ieee80211_propagate_queue_wake(local, i); } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); rcu_read_unlock(); } /* functions for drivers to get certain frames */ static void __ieee80211_beacon_add_tim(struct ieee80211_sub_if_data *sdata, struct ps_data *ps, struct sk_buff *skb) { u8 *pos, *tim; int aid0 = 0; int i, have_bits = 0, n1, n2; /* Generate bitmap for TIM only if there are any STAs in power save * mode. */ if (atomic_read(&ps->num_sta_ps) > 0) /* in the hope that this is faster than * checking byte-for-byte */ have_bits = !bitmap_empty((unsigned long*)ps->tim, IEEE80211_MAX_AID+1); if (ps->dtim_count == 0) ps->dtim_count = sdata->vif.bss_conf.dtim_period - 1; else ps->dtim_count--; tim = pos = (u8 *) skb_put(skb, 6); *pos++ = WLAN_EID_TIM; *pos++ = 4; *pos++ = ps->dtim_count; *pos++ = sdata->vif.bss_conf.dtim_period; if (ps->dtim_count == 0 && !skb_queue_empty(&ps->bc_buf)) aid0 = 1; ps->dtim_bc_mc = aid0 == 1; if (have_bits) { /* Find largest even number N1 so that bits numbered 1 through * (N1 x 8) - 1 in the bitmap are 0 and number N2 so that bits * (N2 + 1) x 8 through 2007 are 0. */ n1 = 0; for (i = 0; i < IEEE80211_MAX_TIM_LEN; i++) { if (ps->tim[i]) { n1 = i & 0xfe; break; } } n2 = n1; for (i = IEEE80211_MAX_TIM_LEN - 1; i >= n1; i--) { if (ps->tim[i]) { n2 = i; break; } } /* Bitmap control */ *pos++ = n1 | aid0; /* Part Virt Bitmap */ skb_put(skb, n2 - n1); memcpy(pos, ps->tim + n1, n2 - n1 + 1); tim[1] = n2 - n1 + 4; } else { *pos++ = aid0; /* Bitmap control */ *pos++ = 0; /* Part Virt Bitmap */ } } static int ieee80211_beacon_add_tim(struct ieee80211_sub_if_data *sdata, struct ps_data *ps, struct sk_buff *skb) { struct ieee80211_local *local = sdata->local; /* * Not very nice, but we want to allow the driver to call * ieee80211_beacon_get() as a response to the set_tim() * callback. That, however, is already invoked under the * sta_lock to guarantee consistent and race-free update * of the tim bitmap in mac80211 and the driver. */ if (local->tim_in_locked_section) { __ieee80211_beacon_add_tim(sdata, ps, skb); } else { spin_lock_bh(&local->tim_lock); __ieee80211_beacon_add_tim(sdata, ps, skb); spin_unlock_bh(&local->tim_lock); } return 0; } void ieee80211_csa_finish(struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); ieee80211_queue_work(&sdata->local->hw, &sdata->csa_finalize_work); } EXPORT_SYMBOL(ieee80211_csa_finish); static void ieee80211_update_csa(struct ieee80211_sub_if_data *sdata, struct beacon_data *beacon) { struct probe_resp *resp; int counter_offset_beacon = sdata->csa_counter_offset_beacon; int counter_offset_presp = sdata->csa_counter_offset_presp; u8 *beacon_data; size_t beacon_data_len; switch (sdata->vif.type) { case NL80211_IFTYPE_AP: beacon_data = beacon->tail; beacon_data_len = beacon->tail_len; break; case NL80211_IFTYPE_ADHOC: beacon_data = beacon->head; beacon_data_len = beacon->head_len; break; case NL80211_IFTYPE_MESH_POINT: beacon_data = beacon->head; beacon_data_len = beacon->head_len; break; default: return; } if (WARN_ON(counter_offset_beacon >= beacon_data_len)) return; /* warn if the driver did not check for/react to csa completeness */ if (WARN_ON(beacon_data[counter_offset_beacon] == 0)) return; beacon_data[counter_offset_beacon]--; if (sdata->vif.type == NL80211_IFTYPE_AP && counter_offset_presp) { rcu_read_lock(); resp = rcu_dereference(sdata->u.ap.probe_resp); /* if nl80211 accepted the offset, this should not happen. */ if (WARN_ON(!resp)) { rcu_read_unlock(); return; } resp->data[counter_offset_presp]--; rcu_read_unlock(); } } bool ieee80211_csa_is_complete(struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct beacon_data *beacon = NULL; u8 *beacon_data; size_t beacon_data_len; int counter_beacon = sdata->csa_counter_offset_beacon; int ret = false; if (!ieee80211_sdata_running(sdata)) return false; rcu_read_lock(); if (vif->type == NL80211_IFTYPE_AP) { struct ieee80211_if_ap *ap = &sdata->u.ap; beacon = rcu_dereference(ap->beacon); if (WARN_ON(!beacon || !beacon->tail)) goto out; beacon_data = beacon->tail; beacon_data_len = beacon->tail_len; } else if (vif->type == NL80211_IFTYPE_ADHOC) { struct ieee80211_if_ibss *ifibss = &sdata->u.ibss; beacon = rcu_dereference(ifibss->presp); if (!beacon) goto out; beacon_data = beacon->head; beacon_data_len = beacon->head_len; } else if (vif->type == NL80211_IFTYPE_MESH_POINT) { struct ieee80211_if_mesh *ifmsh = &sdata->u.mesh; beacon = rcu_dereference(ifmsh->beacon); if (!beacon) goto out; beacon_data = beacon->head; beacon_data_len = beacon->head_len; } else { WARN_ON(1); goto out; } if (WARN_ON(counter_beacon > beacon_data_len)) goto out; if (beacon_data[counter_beacon] == 0) ret = true; out: rcu_read_unlock(); return ret; } EXPORT_SYMBOL(ieee80211_csa_is_complete); struct sk_buff *ieee80211_beacon_get_tim(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u16 *tim_offset, u16 *tim_length) { struct ieee80211_local *local = hw_to_local(hw); struct sk_buff *skb = NULL; struct ieee80211_tx_info *info; struct ieee80211_sub_if_data *sdata = NULL; enum ieee80211_band band; struct ieee80211_tx_rate_control txrc; struct ieee80211_chanctx_conf *chanctx_conf; rcu_read_lock(); sdata = vif_to_sdata(vif); chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!ieee80211_sdata_running(sdata) || !chanctx_conf) goto out; if (tim_offset) *tim_offset = 0; if (tim_length) *tim_length = 0; if (sdata->vif.type == NL80211_IFTYPE_AP) { struct ieee80211_if_ap *ap = &sdata->u.ap; struct beacon_data *beacon = rcu_dereference(ap->beacon); if (beacon) { if (sdata->vif.csa_active) ieee80211_update_csa(sdata, beacon); /* * headroom, head length, * tail length and maximum TIM length */ skb = dev_alloc_skb(local->tx_headroom + beacon->head_len + beacon->tail_len + 256); if (!skb) goto out; skb_reserve(skb, local->tx_headroom); memcpy(skb_put(skb, beacon->head_len), beacon->head, beacon->head_len); ieee80211_beacon_add_tim(sdata, &ap->ps, skb); if (tim_offset) *tim_offset = beacon->head_len; if (tim_length) *tim_length = skb->len - beacon->head_len; if (beacon->tail) memcpy(skb_put(skb, beacon->tail_len), beacon->tail, beacon->tail_len); } else goto out; } else if (sdata->vif.type == NL80211_IFTYPE_ADHOC) { struct ieee80211_if_ibss *ifibss = &sdata->u.ibss; struct ieee80211_hdr *hdr; struct beacon_data *presp = rcu_dereference(ifibss->presp); if (!presp) goto out; if (sdata->vif.csa_active) ieee80211_update_csa(sdata, presp); skb = dev_alloc_skb(local->tx_headroom + presp->head_len); if (!skb) goto out; skb_reserve(skb, local->tx_headroom); memcpy(skb_put(skb, presp->head_len), presp->head, presp->head_len); hdr = (struct ieee80211_hdr *) skb->data; hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_BEACON); } else if (ieee80211_vif_is_mesh(&sdata->vif)) { struct ieee80211_if_mesh *ifmsh = &sdata->u.mesh; struct beacon_data *bcn = rcu_dereference(ifmsh->beacon); if (!bcn) goto out; if (sdata->vif.csa_active) ieee80211_update_csa(sdata, bcn); if (ifmsh->sync_ops) ifmsh->sync_ops->adjust_tbtt( sdata); skb = dev_alloc_skb(local->tx_headroom + bcn->head_len + 256 + /* TIM IE */ bcn->tail_len); if (!skb) goto out; skb_reserve(skb, local->tx_headroom); memcpy(skb_put(skb, bcn->head_len), bcn->head, bcn->head_len); ieee80211_beacon_add_tim(sdata, &ifmsh->ps, skb); memcpy(skb_put(skb, bcn->tail_len), bcn->tail, bcn->tail_len); } else { WARN_ON(1); goto out; } band = chanctx_conf->def.chan->band; info = IEEE80211_SKB_CB(skb); info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; info->flags |= IEEE80211_TX_CTL_NO_ACK; info->band = band; memset(&txrc, 0, sizeof(txrc)); txrc.hw = hw; txrc.sband = local->hw.wiphy->bands[band]; txrc.bss_conf = &sdata->vif.bss_conf; txrc.skb = skb; txrc.reported_rate.idx = -1; txrc.rate_idx_mask = sdata->rc_rateidx_mask[band]; if (txrc.rate_idx_mask == (1 << txrc.sband->n_bitrates) - 1) txrc.max_rate_idx = -1; else txrc.max_rate_idx = fls(txrc.rate_idx_mask) - 1; txrc.bss = true; rate_control_get_rate(sdata, NULL, &txrc); info->control.vif = vif; info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT | IEEE80211_TX_CTL_ASSIGN_SEQ | IEEE80211_TX_CTL_FIRST_FRAGMENT; out: rcu_read_unlock(); return skb; } EXPORT_SYMBOL(ieee80211_beacon_get_tim); struct sk_buff *ieee80211_proberesp_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct ieee80211_if_ap *ap = NULL; struct sk_buff *skb = NULL; struct probe_resp *presp = NULL; struct ieee80211_hdr *hdr; struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); if (sdata->vif.type != NL80211_IFTYPE_AP) return NULL; rcu_read_lock(); ap = &sdata->u.ap; presp = rcu_dereference(ap->probe_resp); if (!presp) goto out; skb = dev_alloc_skb(presp->len); if (!skb) goto out; memcpy(skb_put(skb, presp->len), presp->data, presp->len); hdr = (struct ieee80211_hdr *) skb->data; memset(hdr->addr1, 0, sizeof(hdr->addr1)); out: rcu_read_unlock(); return skb; } EXPORT_SYMBOL(ieee80211_proberesp_get); struct sk_buff *ieee80211_pspoll_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata; struct ieee80211_if_managed *ifmgd; struct ieee80211_pspoll *pspoll; struct ieee80211_local *local; struct sk_buff *skb; if (WARN_ON(vif->type != NL80211_IFTYPE_STATION)) return NULL; sdata = vif_to_sdata(vif); ifmgd = &sdata->u.mgd; local = sdata->local; skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*pspoll)); if (!skb) return NULL; skb_reserve(skb, local->hw.extra_tx_headroom); pspoll = (struct ieee80211_pspoll *) skb_put(skb, sizeof(*pspoll)); memset(pspoll, 0, sizeof(*pspoll)); pspoll->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_PSPOLL); pspoll->aid = cpu_to_le16(ifmgd->aid); /* aid in PS-Poll has its two MSBs each set to 1 */ pspoll->aid |= cpu_to_le16(1 << 15 | 1 << 14); memcpy(pspoll->bssid, ifmgd->bssid, ETH_ALEN); memcpy(pspoll->ta, vif->addr, ETH_ALEN); return skb; } EXPORT_SYMBOL(ieee80211_pspoll_get); struct sk_buff *ieee80211_nullfunc_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct ieee80211_hdr_3addr *nullfunc; struct ieee80211_sub_if_data *sdata; struct ieee80211_if_managed *ifmgd; struct ieee80211_local *local; struct sk_buff *skb; if (WARN_ON(vif->type != NL80211_IFTYPE_STATION)) return NULL; sdata = vif_to_sdata(vif); ifmgd = &sdata->u.mgd; local = sdata->local; skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*nullfunc)); if (!skb) return NULL; skb_reserve(skb, local->hw.extra_tx_headroom); nullfunc = (struct ieee80211_hdr_3addr *) skb_put(skb, sizeof(*nullfunc)); memset(nullfunc, 0, sizeof(*nullfunc)); nullfunc->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS); memcpy(nullfunc->addr1, ifmgd->bssid, ETH_ALEN); memcpy(nullfunc->addr2, vif->addr, ETH_ALEN); memcpy(nullfunc->addr3, ifmgd->bssid, ETH_ALEN); return skb; } EXPORT_SYMBOL(ieee80211_nullfunc_get); struct sk_buff *ieee80211_probereq_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const u8 *ssid, size_t ssid_len, size_t tailroom) { struct ieee80211_sub_if_data *sdata; struct ieee80211_local *local; struct ieee80211_hdr_3addr *hdr; struct sk_buff *skb; size_t ie_ssid_len; u8 *pos; sdata = vif_to_sdata(vif); local = sdata->local; ie_ssid_len = 2 + ssid_len; skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*hdr) + ie_ssid_len + tailroom); if (!skb) return NULL; skb_reserve(skb, local->hw.extra_tx_headroom); hdr = (struct ieee80211_hdr_3addr *) skb_put(skb, sizeof(*hdr)); memset(hdr, 0, sizeof(*hdr)); hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_PROBE_REQ); eth_broadcast_addr(hdr->addr1); memcpy(hdr->addr2, vif->addr, ETH_ALEN); eth_broadcast_addr(hdr->addr3); pos = skb_put(skb, ie_ssid_len); *pos++ = WLAN_EID_SSID; *pos++ = ssid_len; if (ssid_len) memcpy(pos, ssid, ssid_len); pos += ssid_len; return skb; } EXPORT_SYMBOL(ieee80211_probereq_get); void ieee80211_rts_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const void *frame, size_t frame_len, const struct ieee80211_tx_info *frame_txctl, struct ieee80211_rts *rts) { const struct ieee80211_hdr *hdr = frame; rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_RTS); rts->duration = ieee80211_rts_duration(hw, vif, frame_len, frame_txctl); memcpy(rts->ra, hdr->addr1, sizeof(rts->ra)); memcpy(rts->ta, hdr->addr2, sizeof(rts->ta)); } EXPORT_SYMBOL(ieee80211_rts_get); void ieee80211_ctstoself_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const void *frame, size_t frame_len, const struct ieee80211_tx_info *frame_txctl, struct ieee80211_cts *cts) { const struct ieee80211_hdr *hdr = frame; cts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_CTS); cts->duration = ieee80211_ctstoself_duration(hw, vif, frame_len, frame_txctl); memcpy(cts->ra, hdr->addr1, sizeof(cts->ra)); } EXPORT_SYMBOL(ieee80211_ctstoself_get); struct sk_buff * ieee80211_get_buffered_bc(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct ieee80211_local *local = hw_to_local(hw); struct sk_buff *skb = NULL; struct ieee80211_tx_data tx; struct ieee80211_sub_if_data *sdata; struct ps_data *ps; struct ieee80211_tx_info *info; struct ieee80211_chanctx_conf *chanctx_conf; sdata = vif_to_sdata(vif); rcu_read_lock(); chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto out; if (sdata->vif.type == NL80211_IFTYPE_AP) { struct beacon_data *beacon = rcu_dereference(sdata->u.ap.beacon); if (!beacon || !beacon->head) goto out; ps = &sdata->u.ap.ps; } else if (ieee80211_vif_is_mesh(&sdata->vif)) { ps = &sdata->u.mesh.ps; } else { goto out; } if (ps->dtim_count != 0 || !ps->dtim_bc_mc) goto out; /* send buffered bc/mc only after DTIM beacon */ while (1) { skb = skb_dequeue(&ps->bc_buf); if (!skb) goto out; local->total_ps_buffered--; if (!skb_queue_empty(&ps->bc_buf) && skb->len >= 2) { struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; /* more buffered multicast/broadcast frames ==> set * MoreData flag in IEEE 802.11 header to inform PS * STAs */ hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_MOREDATA); } if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) sdata = IEEE80211_DEV_TO_SUB_IF(skb->dev); if (!ieee80211_tx_prepare(sdata, &tx, skb)) break; dev_kfree_skb_any(skb); } info = IEEE80211_SKB_CB(skb); tx.flags |= IEEE80211_TX_PS_BUFFERED; info->band = chanctx_conf->def.chan->band; if (invoke_tx_handlers(&tx)) skb = NULL; out: rcu_read_unlock(); return skb; } EXPORT_SYMBOL(ieee80211_get_buffered_bc); void __ieee80211_tx_skb_tid_band(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, int tid, enum ieee80211_band band) { int ac = ieee802_1d_to_ac[tid & 7]; skb_set_mac_header(skb, 0); skb_set_network_header(skb, 0); skb_set_transport_header(skb, 0); skb_set_queue_mapping(skb, ac); skb->priority = tid; skb->dev = sdata->dev; /* * The other path calling ieee80211_xmit is from the tasklet, * and while we can handle concurrent transmissions locking * requirements are that we do not come into tx with bhs on. */ local_bh_disable(); ieee80211_xmit(sdata, skb, band); local_bh_enable(); }
LairdCP/laird-linux-backports
net/mac80211/tx.c
C
gpl-2.0
82,070
/* $Id: piggyback.c,v 1.1.1.1 2004/06/19 05:03:57 ashieh Exp $ Simple utility to make a single-image install kernel with initial ramdisk for Sparc tftpbooting without need to set up nfs. Copyright (C) 1996 Jakub Jelinek (jj@sunsite.mff.cuni.cz) Pete Zaitcev <zaitcev@yahoo.com> endian fixes for cross-compiles, 2000. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <dirent.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> /* * Note: run this on an a.out kernel (use elftoaout for it), * as PROM looks for a.out image only. */ unsigned short ld2(char *p) { return (p[0] << 8) | p[1]; } unsigned int ld4(char *p) { return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; } void st4(char *p, unsigned int x) { p[0] = x >> 24; p[1] = x >> 16; p[2] = x >> 8; p[3] = x; } void usage(void) { /* fs_img.gz is an image of initial ramdisk. */ fprintf(stderr, "Usage: piggyback vmlinux.aout System.map fs_img.gz\n"); fprintf(stderr, "\tKernel image will be modified in place.\n"); exit(1); } void die(char *str) { perror (str); exit(1); } int main(int argc,char **argv) { static char aout_magic[] = { 0x01, 0x03, 0x01, 0x07 }; unsigned char buffer[1024], *q, *r; unsigned int i, j, k, start, end, offset; FILE *map; struct stat s; int image, tail; if (argc != 4) usage(); start = end = 0; if (stat (argv[3], &s) < 0) die (argv[3]); map = fopen (argv[2], "r"); if (!map) die(argv[2]); while (fgets (buffer, 1024, map)) { if (!strcmp (buffer + 8, " T start\n") || !strcmp (buffer + 16, " T start\n")) start = strtoul (buffer, NULL, 16); else if (!strcmp (buffer + 8, " A end\n") || !strcmp (buffer + 16, " A end\n")) end = strtoul (buffer, NULL, 16); } fclose (map); if (!start || !end) { fprintf (stderr, "Could not determine start and end from System.map\n"); exit(1); } if ((image = open(argv[1],O_RDWR)) < 0) die(argv[1]); if (read(image,buffer,512) != 512) die(argv[1]); if (memcmp (buffer, "\177ELF", 4) == 0) { q = buffer + ld4(buffer + 28); i = ld4(q + 4) + ld4(buffer + 24) - ld4(q + 8); if (lseek(image,i,0) < 0) die("lseek"); if (read(image,buffer,512) != 512) die(argv[1]); j = 0; } else if (memcmp(buffer, aout_magic, 4) == 0) { i = j = 32; } else { fprintf (stderr, "Not ELF nor a.out. Don't blame me.\n"); exit(1); } k = i; i += (ld2(buffer + j + 2)<<2) - 512; if (lseek(image,i,0) < 0) die("lseek"); if (read(image,buffer,1024) != 1024) die(argv[1]); for (q = buffer, r = q + 512; q < r; q += 4) { if (*q == 'H' && q[1] == 'd' && q[2] == 'r' && q[3] == 'S') break; } if (q == r) { fprintf (stderr, "Couldn't find headers signature in the kernel.\n"); exit(1); } offset = i + (q - buffer) + 10; if (lseek(image, offset, 0) < 0) die ("lseek"); st4(buffer, 0); st4(buffer + 4, 0x01000000); st4(buffer + 8, (end + 32 + 4095) & ~4095); st4(buffer + 12, s.st_size); if (write(image,buffer+2,14) != 14) die (argv[1]); if (lseek(image, k - start + ((end + 32 + 4095) & ~4095), 0) < 0) die ("lseek"); if ((tail = open(argv[3],O_RDONLY)) < 0) die(argv[3]); while ((i = read (tail,buffer,1024)) > 0) if (write(image,buffer,i) != i) die (argv[1]); if (close(image) < 0) die("close"); if (close(tail) < 0) die("close"); return 0; }
romanalexander/Trickles
arch/sparc/boot/piggyback.c
C
gpl-2.0
4,050
package gov.noaa.pmel.eps2; import java.awt.*; /** * <code>EPSConstants</code> * Various symbolic constants used by EPS * * @author oz * @version 1.0 */ public interface EPSConstants { public static int MISSINGVALUE = -99; public static char COLON_DELIMITER = ':'; public static char TAB_DELIMITER = '\t'; public static char COMMA_DELIMITER = ','; public static String SCOLON_DELIMITER = ":"; public static String STAB_DELIMITER = "\t"; public static String SCOMMA_DELIMITER = ","; public static String SHYPHEN_DELIMITER = "-"; public static String SSPACE_DELIMITER = " "; public static String SPERIOD_DELIMITER = "."; public static String SSLASH_DELIMITER = "/"; public static String SBACKSLASH_DELIMITER = "\\"; public static String SEQUAL_DELIMITER = "="; /** * 8 bit integer */ public static int EPBYTE = 0; /** * Sring data */ public static int EPCHAR = 1; /** * 16 bit integer */ public static int EPSHORT = 2; /** * 32 bit integer */ public static int EPINT = 3; /** * 32 bit floating point */ public static int EPREAL = 4; /** * 64 bit floating point */ public static int EPDOUBLE = 5; public static int MAX_NC_DIMS = 100; public static int EPNONEAXIS = -1; public static int EPSPACE = 0; public static int EPTIME = 1; public static int EPXAXIS = 2; public static int EPYAXIS = 3; public static int EPZAXIS = 4; public static int EPTAXIS = 5; public static int EPINTT = 6; public static int EPREALT = 7; public static int EPTDUMMY = 8; public static int EPXDUMMY = 9; public static int EPYDUMMY = 10; public static int EPZDUMMY = 11; public static int CANONICALTIME = 12; public static int PROFILEPTRS = 1; public static int TSPTRS = 2; public static int SIMPLEPTRS = 3; public static int POASECTION = 4; public static int WOCESECTION = 5; public static int SD2SECTION = 6; public static int SD3SECTION = 7; public static int SSSECTION = 8; public static int XMLPTRS = 9; public static int ARGOPTRS = 10; public static int GTSPPPTRS = 11; /** * Sort criteria<br> */ public static int X_ASC = 1; public static int X_DSC = 2; public static int Y_ASC = 3; public static int Y_DSC = 4; public static int Z_ASC = 5; public static int Z_DSC = 6; public static int T_ASC = 7; public static int T_DSC = 8; public static boolean NC_NOWRITE = true; public static boolean NC_WRITE = false; public static int NC_UNSPECIFIED = 0;/* private */ public static int NC_BYTE = 1; public static int NC_CHAR = 2; public static int NC_SHORT = 3; public static int NC_LONG = 4; public static int NC_FLOAT = 5; public static int NC_DOUBLE = 6; public static int NC_BITFIELD = 7; public static int NC_STRING = 8; public static int NC_IARRAY = 9; public static int NC_DIMENSION = 10; public static int NC_VARIABLE = 11; public static int NC_ATTRIBUTE = 12; public static long GREGORIAN = (15+31*(10+12*1582)); public static long JULGREG = 299161; /** * "CRUISE" CTD attribute<br> * Cruise number */ public static String EPCRUISE = "CRUISE"; /** * "CAST" CTD attribute<br> * cast number */ public static String EPCAST = "CAST"; /** * "INST_TYPE" required EPIC attribute * instrument type */ public static String EPINSTTYPE = "INST_TYPE"; /** * "CREATION_DATE" * file creation date */ public static String EPCRDATE = "CREATION_DATE"; /** * "BOTTLE" CTD attribute<br> * Bottle data flag (=1 if bottle) */ public static String EPBOTTLE = "BOTTLE"; /** * */ public static String EPCASTNUM = "CAST_NUMBER"; /** * "DATA_TYPE" required EPIC attribute<br> * legal values include "CTD", "TIME", "TRACK", * and "GRID" */ public static String EPDATATYPE = "DATA_TYPE"; /** * "DATA_SUBTYPE" required EPIC attribute */ public static String EPSUBTYPE = "DATA_SUBTYPE"; /** * "EXPERIMENT" Time Series attribute<br> * experiment name * legal values include "CTD" and "BOTTLE" */ public static String EPEXPERIMENT = "EXPERIMENT"; /** * "PROJECT" Time Series attribute <br> * Project name */ public static String EPPROJECT = "PROJECT"; /** * "MOORING" Time Series attribute<br> * Mooring identification */ public static String EPMOORING = "MOORING"; /** * "DELTA_T" Time Series attribute<br> * series delta-t description */ public static String EPDELTAT = "DELTA_T"; /** * "COMPOSITE" Time Series attribute<br> */ public static String EPCOMPOSITE = "COMPOSITE"; /** * "POS_CONST" Time Series attribute<br> * consistent position flag (=1 not consistent) */ public static String EPPOSCONST = "POS_CONST"; /** * "DEPTH_CONST" Time Series attribute<br> * consistent depth flag (=1 not consistent) */ public static String EPDEPTHCONST = "DEPTH_CONST"; /** * "DATA_ORIGIN" required EPIC attribute */ public static String EPDATAORIGIN = "DATA_ORIGIN"; /** * "DESCRIPT" Time Series attribute<br> * text description field */ public static String EPDESCRIPT = "DESCRIPT"; /** * "DATA_CMNT" Time Series attribute<br> * data comment */ public static String EPDATACMNT = "DATA_CMNT"; /** * "COORD_SYSTEM" required EPIC attribute<br> * value of "GEOGRAPHICAL" for classic EPIC data */ public static String EPCOORDSYS = "COORD_SYSTEM"; /** * "WATER_MASS" CTD and Time Series attribute <br> * Water Mass flag <br> * <p align="left">The WATER MASS attribute is used * by EPIC contouring programs to decide the default * contouring level. Refering to following table for valid * Water Mass flags:</p> * <table border="1"> *<tr> * <td>FLAG</td> * <td>Default contouring level used for water mass at region</td> *</tr> *<tr> * <td> * <div align="center">"B"</div> * </td> * <td> * <div align="center">Bering Sea</div> * </td> *</tr> *<tr> * <td> * <div align="center">"G"</div> * </td> * <td> * <div align="center">Gulf of Alaska</div> * </td> *</tr> *<tr> * <td> * <div align="center">"S" </div> * </td> * <td> * <div align="center">Shelikof </div> * </td> *</tr> *<tr> * <td> * <div align="center">"V"</div> * </td> * <td> * <div align="center">Vents </div> * </td> *</tr> *<tr> * <td> * <div align="center">"P"</div> * </td> * <td> * <div align="center">Puget Sound</div> * </td> *</tr> *<tr> * <td> * <div align="center">"E"</div> * </td> * <td> * <div align="center">Equatorial</div> * </td> *</tr> *<tr> * <td> * <div align="center">" " </div> * </td> * <td> * <div align="center">Equatorial</div> * </td> *</tr> * </table> * */ public static String EPWATERMASS = "WATER_MASS"; /** * "DRIFTER" Time Series attribute<br> * drifter flag (=1 if drifter) */ public static String EPDRIFTER = "DRIFTER"; /** * "WEATHER" CTD attribute<br> * Weather code (0-9) */ public static String EPWEATHER = "WEATHER"; /** * "SEA_STATE" CTD attribute<br> * Sea state code (0-9) */ public static String EPSEASTATE = "SEA_STATE"; /** * "BAROMETER" CTD attribute<br> * Atmospheric pressure in millibars */ public static String EPBAROMETER = "BAROMETER"; /** * "WIND_DIR" CTD attribute<br> * Wind direction in degrees from north */ public static String EPWINDDIR = "WIND_DIR"; /** * "WIND_SPEED" CTD attribute<br> * Wind speed in knots */ public static String EPWINDSPEED = "WIND_SPEED"; /** * "VISIBILITY" CTD attribute<br> * Visibility code (0-9) */ public static String EPVISIBILITY = "VISIBILITY"; /** * "CLOUD_TYPE" CTD attribute<br> * Cloud type code (0-9, X) */ public static String EPCLOUDTYPE = "CLOUD_TYPE"; /** * "CLOUD_AMOUNT" CTD attribute<br> * Cloud amount code (0-9) */ public static String EPCLOUDAMOUNT = "CLOUD_AMOUNT"; /** * "AIR_TEMP" CTD attribute<br> * Dry air temperature */ public static String EPAIRTEMP = "AIR_TEMP"; /** * "WET_BULB" CTD attribute<br> * Web bulb temperature */ public static String EPWETBULB = "WET_BULB"; /** * "WATER_DEPTH" CTD and Time Series attribute<br> * Water depth to nearest meter */ public static String EPWATERDEPTH = "WATER_DEPTH"; /** * "VAR_DESC" Time Series attribute<br> * text field describing variables */ public static String EPVARDESC = "VAR_DESC"; /** * "FILL_FLAG" Time Series attribute<br> * data fill flag (=1 if data has fill values) */ public static String EPFILLFLAG = "FILL_FLAG"; /** * "VAR_FILL" Time Series attribute<br> * character string */ public static String EPVARFILL = "VAR_FILL"; /** * "PROG_CMNT1" latest program comment */ public static String EPPROGCMNT1 = "PROG_CMNT1"; /** * "PROG_CMNT2" next program comment */ public static String EPPROGCMNT2 = "PROG_CMNT2"; /** * "PROG_CMNT3" next program comment */ public static String EPPROGCMNT3 = "PROG_CMNT3"; /** * "PROG_CMNT4" oldest program comment */ public static String EPPROGCMNT4 = "PROG_CMNT4"; /** * "LAT_PC" optional Time Series attribute<br> * piece measurement latitude */ public static String EPLATPC = "LAT_PC"; /** * "LONG_PC" optional Time Series attribute<br> * piece measurement longitude */ public static String EPLONGPC = "LONG_PC"; /** * "START_PC" optional Time Series attribute<br> * piece start time and date */ public static String EPSTARTPC = "START_PC"; /** * "END_PC" optional Time Series attribute<br> * piece stop time and date */ public static String EPENDPC = "END_PC"; /** * "INST_DEPTH_PC" optional Time Series attribute<br> * piece measurement depth (m) */ public static String EPINSTDEPTHPC = "INST_DEPTH_PC"; /** * "INDENT_PC" optional Time Series attribute<br> * piece identification */ public static String EPIDENTPC = "IDENT_PC"; /** * "IMAGE" card image from classic EPIC data file */ public static String EPIMAGE = "IMAGE"; /** * Evenly spaced data values in the axis */ public static String EPEVEN = "EVEN"; /** * Unevenly spaced data values in the axis */ public static String EPUNEVEN = "UNEVEN"; /** * Evenly spaced data values in the axis */ public static String EPEVEN_INT = "EVENI"; /** * Evenly spaced data values in the axis */ public static String EPEVEN_REAL = "EVENR"; /** * Unevenly spaced data values in the axis */ public static String EPUNEVEN_INT = "UNEVENI"; /** * Unevenly spaced data values in the axis */ public static String EPUNEVEN_REAL = "UNEVENR"; /** * File open for read only */ public static int EPREAD = 0; /** * File open for create */ public static int EPCREATE = 1; /** * File open for edit (append or overwrite) */ public static int EPEDIT = 2; /** * Synonyms for the x axis */ public static String[] xname = {"x", "longitude", null}; /** * Synonyms for the y axis */ public static String[] yname = {"y", "latitude", null}; /** * Synonyms for the z axis */ public static String[] zname = {"z", "depth", "elevation", null}; /** * Synonyms for the y axis units */ public static String[] yunit = {"degree_north", "degrees_north", "degreeN", "degrees_N", "degreesN", null}; /** * Synonyms for the x axis units */ public static String[] xunit = {"degree_east", "degrees_east", "degree_E", "degreeE", "degrees_E", "degreesE", null}; /** * Synonyms for the z axis units */ public static String[] zunit = {"z", "depth", "elevation", "dbar", "mbar", "Pa", null}; /** * Conversions for time in various units to seconds */ public static TimeToSecond[] time_units = { new TimeToSecond("year", 3.1536e+7, false), new TimeToSecond("yr" , 3.1536e+7, false), new TimeToSecond("a" , 3.1536e+7, true), new TimeToSecond("day", 8.64e+04, false), new TimeToSecond("d", 8.64e+04, true), new TimeToSecond("hour", 3.6e+03, false), new TimeToSecond("hr", 3.6e+03, false), new TimeToSecond("h", 3.6e+03, true), new TimeToSecond("minute", 60, false), new TimeToSecond("min", 60, false), new TimeToSecond("second", 1, false), new TimeToSecond("sec", 1, false), new TimeToSecond("s", 1, true), new TimeToSecond("msec", 1e-3, false), new TimeToSecond("msecs", 1e-3, false), new TimeToSecond("millisecond", 1e-3, false), new TimeToSecond("millisec", 1e-3, false), new TimeToSecond("millis", 1e-3, true), new TimeToSecond("shake", 1e-8, false), new TimeToSecond("sidereal_day",8.616409e4, false), new TimeToSecond("sidereal_minute",5.983617e1,false), new TimeToSecond("sidereal_second",0.9972696, false), new TimeToSecond("sidereal_year",3.155815e7, false), new TimeToSecond("tropical_year",3.155693e7, false), new TimeToSecond("eon", 3.1536e+16, false), new TimeToSecond("fortnight", 1.2096e+06, false), new TimeToSecond("0", 0, false) }; static String[] LongMonths = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static String[] LongWeekDays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static int[] max_day = {31,28,31,30,31,30,31,31,30,31,30,31}; static String[] dummyName = {"tdummy", "zdummy", "ydummy", "xdummy"}; public static int PTRFILEFORMAT = 0; public static int JOAFORMAT = 1; public static int POAFORMAT = 2; public static int SSFORMAT = 3; public static int SD2FORMAT = 4; public static int SD3FORMAT = 5; public static int WOCEHYDFORMAT = 6; public static int WOCECTDFORMAT = 7; public static int NETCDFFORMAT = 8; public static int ZIPSECTIONFILEFORMAT = 9; public static int NETCDFXBTFORMAT = 10; public static int DODSNETCDFFORMAT = 11; public static int JOPIFORMAT = 12; public static int XMLPTRFILEFORMAT = 13; public static int GZIPTARSECTIONFILEFORMAT = 14; public static int GZIPFILEFORMAT = 15; public static int ARGOINVENTORYFORMAT = 16; public static int GTSPPINVENTORYFORMAT = 17; public static int ARGONODCNETCDFFORMAT = 18; public static int XYZFORMAT = 19; public static int TEXTFORMAT = 20; public static int NQDBFORMAT = 21; public static int WODCSVFORMAT = 22; public static int ARGOGDACNETCDFFORMAT = 23; public static int UNKNOWNFORMAT = 99; public static int MATCHES = 0; public static int STARTSWITH = 1; public static int CONTAINS = 2; public static int ALL_OBS = 1; }
OceanAtlas/JOA
gov/noaa/pmel/eps2/EPSConstants.java
Java
gpl-2.0
15,827
<!doctype html> <html> <head> <title>graph-item demo</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes"> <script src="../../webcomponentsjs/webcomponents-lite.js"></script> <link rel="import" href="../external-elements.html"> <link rel="import" href="../../iron-demo-helpers/demo-pages-shared-styles.html"> <link rel="import" href="../../iron-demo-helpers/demo-snippet.html"> <link rel="import" href="../tree-browser-view.html"> <style is="custom-style" include="demo-pages-shared-styles"> .vertical-section-container { max-width: 80%; } </style> </head> <body> <div class="vertical-section-container centered"> <demo-snippet> <template> <tree-browser-view nx-config='{"env": "dev", "termAccession": "TS-0079"}'></tree-browser-view> </template> </demo-snippet> <demo-snippet> <template> <tree-browser-view nx-config='{"env": "dev", "termAccession": "6.3.2.-"}'></tree-browser-view> </template> </demo-snippet> </div> </body> </html>
calipho-sib/nextprot-elements
demo/tree-browser-view-demo.html
HTML
gpl-2.0
1,163
/* * linux/drivers/video/m532xfb.c -- Coldfire MCF5329 frame buffer driver * * Copyright (c) 2006, emlix, Thomas Brinker <tb@emlix.com> * Yaroslav Vinogradov yaroslav.vinogradov@freescale.com * Copyright Freescale Semiconductor, Inc 2006 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Modified for Coldfire M5329 frame buffer by yaroslav.vinogradov@freescale.com * Modified to new api Jan 2001 by James Simmons (jsimmons@transvirtual.com) * Created 28 Dec 1997 by Geert Uytterhoeven * * Copyright (c) 2007, 2008 Arcturus Networks Inc. * by David Wu <www.ArcturusNetworks.com> * Dec. 2008, David Wu Added support for WG320240A LCD * June 2007, David Wu Added support for Focus FS453 video card */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/tty.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/fb.h> #include <linux/init.h> #include <asm/coldfire.h> #include <asm/mcfsim.h> #ifdef CONFIG_FB_FS453_TVOUT #include <linux/i2c.h> #include <asm/uaccess.h> #include <linux/video_encoder.h> /* * FIXME: VGA mode is not defined by video_encoder.h * while FS453 supports VGA output. */ #ifndef VIDEO_ENCODER_VGA #define VIDEO_ENCODER_VGA 32 #endif #define MODE_PAL "TV-PAL" #define MODE_NTSC "TV-NTSC" #define MODE_VGA "TV-VGA" extern int fs453_ioctl(unsigned int cmd, void *arg); #endif #if defined (CONFIG_FB_FS453_TVOUT) || defined (CONFIG_WG320240A) static int m532xfb_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg); #endif #define FB_HWAIT1 0 #define FB_HWIDTH 1 #define FB_HWAIT2 2 #define FB_VWAIT1 3 #define FB_VWIDTH 4 #define FB_VWAIT2 5 #if defined (CONFIG_FB_FS453_TVOUT) static u32 fb_wait_params[][6] = { /* the settings below are for VGA mode: LCD -> Focus 453 -> VGA */ /* HWAIT1, HWIDTH, HWAIT2, VWAIT1, VWIDTH, VWAIT2 */ {96, 63, 42, 11, 2, 32}, /* 640x480 */ {110, 59, 85, 42, 3, 24}, /* 800x600 */ {138, 63, 108, 137, 10, 138}, /* 320x240 */ {144, 63, 102, 157, 10, 158}, /* 320x200 */ {85, 10, 75, 32, 10, 10}, /* 240x320 */ {10, 16, 56, 5, 3, 23}, /* 640x480_HIGH 72Hz 36.5kHz */ {138, 63, 108, 53, 10, 117}, /* 320x240_HIGH 75Hz 31.5kHz */ {144, 63, 102, 73, 10, 137}, /* 320x200_HIGH 75Hz 31.5kHz */ }; #elif defined (CONFIG_WG320240A) static u32 fb_wait_params[][6] = { {6, 19, 154, 0, 4, 0}, /* 320x240@60 non-color mode */ }; #else static u32 fb_wait_params[][6] = { /* HWAIT1, HWIDTH, HWAIT2, VWAIT1, VWIDTH, VWAIT2 */ /* 640x480 */ {48, 14, 102, 32, 1, 35}, /* 800x600 */ {110, 59, 85, 42, 3, 24}, /* 240x320 */ {85, 10, 75, 32, 10, 10} }; #endif #if defined(CONFIG_LCD_640x480_HIGH) #define CONFIG_LCD_640x480 #endif #if defined(CONFIG_LCD_320x240_HIGH) #define CONFIG_LCD_320x240 #endif #if defined(CONFIG_LCD_320x200_HIGH) #define CONFIG_LCD_320x200 #endif #if defined(CONFIG_LCD_640x480) #if defined(CONFIG_LCD_640x480_HIGH) #define MODE_OPTION "640x480@72" #define FB_WAIT_PARAMS(p) (fb_wait_params[5][(p)]) #else #define MODE_OPTION "640x480@60" #define FB_WAIT_PARAMS(p) (fb_wait_params[0][(p)]) #endif #ifdef CONFIG_FB_FS453_TVOUT #define MODE_BPP 16 #else #define MODE_BPP 32 #endif #define MODE_WIDTH 640 #define MODE_HEIGHT 480 #define MODE_VPW (MODE_WIDTH >> (MODE_BPP == 16 ? 1 : 0)) #ifdef CONFIG_FB_FS453_TVOUT #define PIX_CLK_DIV 2 #define LCDC_LDCR_VALUE (MCF_LCDC_LDCR_TM(14) | MCF_LCDC_LDCR_HM(4)) #else #define PIX_CLK_DIV 12 #define LCDC_LDCR_VALUE (MCF_LCDC_LDCR_TM(8) | MCF_LCDC_LDCR_HM(4)) #endif #elif defined(CONFIG_LCD_800x600) #define MODE_OPTION "800x600@60" #define MODE_BPP 32 /* Default is 32 bits, 16 bits mode is also aviable */ #define MODE_WIDTH 800 #define MODE_HEIGHT 600 #define MODE_VPW (MODE_WIDTH >> (MODE_BPP == 16 ? 1 : 0)) #define FB_WAIT_PARAMS(p) (fb_wait_params[1][(p)]) #ifdef CONFIG_FB_FS453_TVOUT #define PIX_CLK_DIV 2 #else #define PIX_CLK_DIV 3 #endif #define LCDC_LDCR_VALUE (MCF_LCDC_LDCR_TM(8) | MCF_LCDC_LDCR_HM(4)) #elif defined(CONFIG_LCD_240x320) #define MODE_OPTION "240x320@60" #define MODE_BPP 32 #define MODE_WIDTH 240 #define MODE_HEIGHT 320 #define MODE_VPW (MODE_WIDTH >> (MODE_BPP == 16 ? 1 : 0)) #ifdef CONFIG_FB_FS453_TVOUT #define FB_WAIT_PARAMS(p) (fb_wait_params[4][(p)]) #define PIX_CLK_DIV 3 #else #define FB_WAIT_PARAMS(p) (fb_wait_params[2][(p)]) #define PIX_CLK_DIV 12 #endif #define LCDC_LDCR_VALUE (MCF_LCDC_LDCR_TM(4) | MCF_LCDC_LDCR_HM(8) | MCF_LCDC_LDCR_BURST) #elif defined(CONFIG_LCD_320x240) #if defined(CONFIG_LCD_320x240_HIGH) #define MODE_OPTION "320x240@75" #define FB_WAIT_PARAMS(p) (fb_wait_params[6][(p)]) #else #define MODE_OPTION "320x240@60" #ifdef CONFIG_WG320240A #define FB_WAIT_PARAMS(p) (fb_wait_params[0][(p)]) #else #define FB_WAIT_PARAMS(p) (fb_wait_params[2][(p)]) #endif #endif #ifdef CONFIG_WG320240A #define MODE_BPP 1 #define MODE_VPW (MODE_WIDTH >> 5) #define PIX_CLK_DIV 10 #else #define MODE_BPP 16 /* less memory usage: half of 32 bits mode */ #define MODE_VPW (MODE_WIDTH >> (MODE_BPP == 16 ? 1 : 0)) #define PIX_CLK_DIV 3 #endif #define MODE_WIDTH 320 #define MODE_HEIGHT 240 #define LCDC_LDCR_VALUE (MCF_LCDC_LDCR_TM(14) | MCF_LCDC_LDCR_HM(4)) #elif defined(CONFIG_LCD_320x200) #if defined(CONFIG_LCD_320x200_HIGH) #define MODE_OPTION "320x200@75" #define FB_WAIT_PARAMS(p) (fb_wait_params[7][(p)]) #else #define MODE_OPTION "320x200@60" #define FB_WAIT_PARAMS(p) (fb_wait_params[3][(p)]) #endif #define MODE_BPP 16 /* less memory usage: half of 32 bits mode */ #define MODE_WIDTH 320 #define MODE_HEIGHT 200 #define MODE_VPW (MODE_WIDTH >> (MODE_BPP == 16 ? 1 : 0)) #define PIX_CLK_DIV 3 #define LCDC_LDCR_VALUE (MCF_LCDC_LDCR_TM(14) | MCF_LCDC_LDCR_HM(4)) #else #error "LCD display resolution is not specified!" #endif #ifdef CONFIG_VT extern int soft_cursor(struct fb_info* info, struct fb_cursor* cursor); #endif /* * This structure defines the hardware state of the graphics card. Normally * you place this in a header file in linux/include/video. This file usually * also includes register information. That allows other driver subsystems * and userland applications the ability to use the same header file to * avoid duplicate work and easy porting of software. */ struct m532x_par { char mode_option[40]; /* ... */ unsigned dump; }; /* * Here we define the default structs fb_fix_screeninfo and fb_var_screeninfo * if we don't use modedb. If we do use modedb see xxxfb_init how to use it * to get a fb_var_screeninfo. Otherwise define a default var as well. */ static struct fb_fix_screeninfo m532xfb_fix = { .id = "M532x FB", .type = FB_TYPE_PACKED_PIXELS, #ifdef CONFIG_WG320240A .visual = FB_VISUAL_PSEUDOCOLOR, #else .visual = FB_VISUAL_TRUECOLOR, #endif .xpanstep = 0, .ypanstep = 0, .ywrapstep = 0, .accel = FB_ACCEL_NONE, }; /* * Modern graphical hardware not only supports pipelines but some * also support multiple monitors where each display can have its * its own unique data. In this case each display could be * represented by a separate framebuffer device thus a separate * struct fb_info. Now the struct xxx_par represents the graphics * hardware state thus only one exist per card. In this case the * struct xxx_par for each graphics card would be shared between * every struct fb_info that represents a framebuffer on that card. * This allows when one display changes it video resolution (info->var) * the other displays know instantly. Each display can always be * aware of the entire hardware state that affects it because they share * the same xxx_par struct. The other side of the coin is multiple * graphics cards that pass data around until it is finally displayed * on one monitor. Such examples are the voodoo 1 cards and high end * NUMA graphics servers. For this case we have a bunch of pars, each * one that represents a graphics state, that belong to one struct * fb_info. Their you would want to have *par point to a array of device * states and have each struct fb_ops function deal with all those * states. I hope this covers every possible hardware design. If not * feel free to send your ideas at jsimmons@users.sf.net */ /* * If your driver supports multiple boards or it supports multiple * framebuffers, you should make these arrays, or allocate them * dynamically (using kmalloc()). */ static struct fb_info info; /* * Each one represents the state of the hardware. Most hardware have * just one hardware state. These here represent the default state(s). */ #define DUMP_OPTIONS 0x0 /* nothing */ /*#define DUMP_OPTIONS 0xffffffff *//* everything */ static struct m532x_par current_par = { .mode_option = MODE_OPTION, .dump = DUMP_OPTIONS, }; static u32 pseudo_palette[256]; int m532xfb_init(void); int m532xfb_setup(char*); /* ----- DUMP start ----- */ void m532xfb_dump_var(struct fb_info *info) { printk("*** FB var: ***\n"); printk("resolution: %d x %d\n", info->var.xres, info->var.yres); printk("virtual: %d x %d\n", info->var.xres_virtual, info->var.yres_virtual); printk("offsets: %d x %d\n", info->var.xoffset, info->var.yoffset); printk("bpp: %d\n", info->var.bits_per_pixel); printk("grey: %d\n", info->var.grayscale); printk("red: off: %d len %d msb %d\n", info->var.red.offset, info->var.red.length, info->var.red.msb_right); printk("green: off: %d len %d msb %d\n", info->var.green.offset, info->var.green.length, info->var.green.msb_right); printk("blue: off: %d len %d msb %d\n", info->var.blue.offset, info->var.blue.length, info->var.blue.msb_right); printk("transp:off: %d len %d msb %d\n", info->var.transp.offset, info->var.transp.length, info->var.transp.msb_right); printk("pixelformat:%d\n", info->var.nonstd); printk("activate: %d\n", info->var.activate); printk("dimension: %d x %d\n", info->var.height, info->var.width); printk("pixclock: %lu\n", PICOS2KHZ(info->var.pixclock)); printk("margins: %d - %d - %d - %d\n", info->var.left_margin, info->var.right_margin, info->var.upper_margin, info->var.lower_margin); printk("synclen: %d - %d\n", info->var.hsync_len, info->var.vsync_len); printk("sync: %d\n", info->var.sync); printk("vmode: %d\n", info->var.vmode); printk("rotate: %d\n\n", info->var.rotate); } void m532xfb_dump_fix(struct fb_info *info) { printk("*** FB fix: ***\n"); printk("id %s\n", info->fix.id); printk("smem_start 0x%08lx\n", info->fix.smem_start); printk("smem_len %d\n", info->fix.smem_len); printk("type: %d\n", info->fix.type); printk("type_aux: %d\n", info->fix.type_aux); printk("visual: %d\n", info->fix.visual); printk("xpanstep %d\n", info->fix.xpanstep); printk("ypanstep %d\n", info->fix.ypanstep); printk("ywrapstep %d\n", info->fix.ywrapstep); printk("line_length %d\n", info->fix.line_length); printk("accel %d\n\n", info->fix.accel); } void m532xfb_dump_par(struct fb_info *info) { struct m532x_par *par = (struct m532x_par *) info->par; printk("*** FB par: ***\n"); printk("dump: %d\n\n", par->dump); } void m532xfb_dump_colors(void) { } void m532xfb_dump_info(struct fb_info *info) { int dump = ((struct m532x_par *) info->par)->dump; if (!dump) return; printk("-------------------------------------------------------------------\n"); printk("*** FB info DUMP ***\n"); printk("node: %d\n", info->node); printk("flags: %d\n\n", info->flags); printk("screenbase: 0x%p\n", info->screen_base); printk("screen_size: 0x%08lx\n", info->screen_size); printk("state: %d\n\n", info->state); if (dump & 0x02) m532xfb_dump_fix(info); if (dump & 0x04) m532xfb_dump_var(info); if (dump & 0x08) m532xfb_dump_par(info); if (dump & 0x10) m532xfb_dump_colors(); printk("*** LCD-Registers ***\n"); printk("MCF_LCDC_SSAR 0x%08lx\n",MCF_LCDC_LSSAR); printk("MCF_GPIO_PAR_LCDDATA 0x%08x\n",MCF_GPIO_PAR_LCDDATA); printk("MCF_GPIO_PAR_LCDCTL 0x%08x\n",MCF_GPIO_PAR_LCDCTL); printk("MCF_SCM_BCR 0x%08lx\n",MCF_SCM_BCR); printk("MCF_LCDC_SR 0x%08lx\n",MCF_LCDC_LSR); printk("MCF_LCDC_VPWR 0x%08lx\n",MCF_LCDC_LVPWR); printk("MCF_LCDC_CPR 0x%08lx\n",MCF_LCDC_LCPR); printk("MCF_LCDC_CWHBR 0x%08lx\n",MCF_LCDC_LCWHBR); printk("MCF_LCDC_CCMR 0x%08lx\n",MCF_LCDC_LCCMR); printk("MCF_LCDC_PCR 0x%08lx\n",MCF_LCDC_LPCR); printk("MCF_LCDC_HCR 0x%08lx\n",MCF_LCDC_LHCR); printk("MCF_LCDC_VCR 0x%08lx\n",MCF_LCDC_LVCR); printk("MCF_LCDC_POR 0x%08lx\n",MCF_LCDC_LPOR); printk("MCF_LCDC_SCR 0x%08lx\n",MCF_LCDC_LSCR); printk("MCF_LCDC_PCCR 0x%08lx\n",MCF_LCDC_LPCCR); printk("MCF_LCDC_DCR 0x%08lx\n",MCF_LCDC_LDCR); printk("MCF_LCDC_RMCR 0x%08lx\n",MCF_LCDC_LRMCR); printk("MCF_LCDC_ICR 0x%08lx\n",MCF_LCDC_LICR); printk("MCF_LCDC_IER 0x%08lx\n",MCF_LCDC_LIER); printk("MCF_LCDC_ISR 0x%08lx\n",MCF_LCDC_LISR); printk("MCF_LCDC_GWSAR 0x%08lx\n",MCF_LCDC_LGWSAR); printk("MCF_LCDC_GWSR 0x%08lx\n",MCF_LCDC_LGWSR); printk("MCF_LCDC_GWVPWR 0x%08lx\n",MCF_LCDC_LGWVPWR); printk("MCF_LCDC_GWPOR 0x%08lx\n",MCF_LCDC_LGWPOR); printk("MCF_LCDC_GWPR 0x%08lx\n",MCF_LCDC_LGWPR); printk("MCF_LCDC_GWCR 0x%08lx\n",MCF_LCDC_LGWCR); printk("MCF_LCDC_GWDCR 0x%08lx\n",MCF_LCDC_LGWDCR); printk("MCF_LCDC_GWLUT_BASE 0x%08lx\n",MCF_LCDC_GWLUT_BASE); printk("0xFC00_4100(XBS_PRS1) 0x%08lx\n", MCF_REG32(0xFC004100)); printk("0xFC00_4110(XBS_CRS1) 0x%08lx\n", MCF_REG32(0xFC004110)); printk("-------------------------------------------------------------------\n"); } /* ----- DUMP end ----- */ /** * xxxfb_setcolreg - Optional function. Sets a color register. * @regno: Which register in the CLUT we are programming * @red: The red value which can be up to 16 bits wide * @green: The green value which can be up to 16 bits wide * @blue: The blue value which can be up to 16 bits wide. * @transp: If supported, the alpha value which can be up to 16 bits wide. * @info: frame buffer info structure * * Set a single color register. The values supplied have a 16 bit * magnitude which needs to be scaled in this function for the hardware. * Things to take into consideration are how many color registers, if * any, are supported with the current color visual. With truecolor mode * no color palettes are supported. Here a pseudo palette is created * which we store the value in pseudo_palette in struct fb_info. For * pseudocolor mode we have a limited color palette. To deal with this * we can program what color is displayed for a particular pixel value. * DirectColor is similar in that we can program each color field. If * we have a static colormap we don't need to implement this function. * * Returns negative errno on error, or zero on success. */ static int m532xfb_setcolreg(unsigned regno, unsigned red, unsigned green, unsigned blue, unsigned transp, const struct fb_info *info) { if (regno >= 256) /* no. of hw registers */ return -EINVAL; /* * Program hardware... do anything you want with transp */ /* grayscale works only partially under directcolor */ if (info->var.grayscale) { /* grayscale = 0.30*R + 0.59*G + 0.11*B */ red = green = blue = (red * 77 + green * 151 + blue * 28) >> 8; } /* Directcolor: * var->{color}.offset contains start of bitfield * var->{color}.length contains length of bitfield * {hardwarespecific} contains width of DAC * cmap[X] is programmed to (X << red.offset) | (X << green.offset) | (X << blue.offset) * RAMDAC[X] is programmed to (red, green, blue) * * Pseudocolor: * uses offset = 0 && length = DAC register width. * var->{color}.offset is 0 * var->{color}.length contains widht of DAC * cmap is not used * DAC[X] is programmed to (red, green, blue) * Truecolor: * does not use RAMDAC (usually has 3 of them). * var->{color}.offset contains start of bitfield * var->{color}.length contains length of bitfield * cmap is programmed to (red << red.offset) | (green << green.offset) | * (blue << blue.offset) | (transp << transp.offset) * RAMDAC does not exist */ #define CNVT_TOHW(val,width) ((((val)<<(width))+0x7FFF-(val))>>16) switch (info->fix.visual) { case FB_VISUAL_TRUECOLOR: case FB_VISUAL_PSEUDOCOLOR: red = CNVT_TOHW(red, info->var.red.length); green = CNVT_TOHW(green, info->var.green.length); blue = CNVT_TOHW(blue, info->var.blue.length); transp = CNVT_TOHW(transp, info->var.transp.length); break; case FB_VISUAL_DIRECTCOLOR: /* example here assumes 8 bit DAC. Might be different * for your hardware */ red = CNVT_TOHW(red, 8); green = CNVT_TOHW(green, 8); blue = CNVT_TOHW(blue, 8); /* hey, there is bug in transp handling... */ transp = CNVT_TOHW(transp, 8); break; } #undef CNVT_TOHW /* Truecolor has hardware independent palette */ if (info->fix.visual == FB_VISUAL_TRUECOLOR) { u32 v; if (regno >= 16) return -EINVAL; v = (red << info->var.red.offset) | (green << info->var.green.offset) | (blue << info->var.blue.offset) | (transp << info->var.transp.offset); switch (info->var.bits_per_pixel) { case 8: /* Yes some hand held devices have this. */ ((u8*)(info->pseudo_palette))[regno] = v; break; case 16: ((u16*)(info->pseudo_palette))[regno] = v; break; case 24: case 32: ((u32*)(info->pseudo_palette))[regno] = v; break; } return 0; } /* ... */ printk("do something with color palette!\n"); return 0; } /* ------------------------------------------------------------------------- */ /* We implement our own mmap to set MAY_SHARE and add the correct size */ static int m532xfb_mmap(struct fb_info *info, struct vm_area_struct *vma) { vma->vm_flags |= VM_MAYSHARE| VM_SHARED; vma->vm_start = info->fix.smem_start; vma->vm_end = info->fix.smem_start + info->fix.smem_len; return 0; } #if defined(CONFIG_UC53281EVM) || defined(CONFIG_UC532X) || !defined(CONFIG_VT) int m532xfb_cursor(struct fb_info *info, struct fb_cursor *cursor) { /* don't want any cursor; we use mouse*/ return 0; } #endif /* * Frame buffer operations */ static struct fb_ops m532xfb_ops = { .owner = THIS_MODULE, .fb_fillrect = cfb_fillrect, /* Needed !!! */ .fb_copyarea = cfb_copyarea, /* Needed !!! */ .fb_imageblit = cfb_imageblit, /* Needed !!! */ #if defined(CONFIG_UC53281EVM)|| defined(CONFIG_UC532X) || !defined(CONFIG_VT) .fb_cursor = m532xfb_cursor, /* Needed !!! */ #else .fb_cursor = soft_cursor, /* Needed !!! */ #endif .fb_mmap = m532xfb_mmap, #if defined (CONFIG_FB_FS453_TVOUT) || defined (CONFIG_WG320240A) .fb_ioctl = m532xfb_ioctl, #endif }; #ifdef CONFIG_WG320240A /* defined it here just for compatibility of user application */ static int m532xfb_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg) { return 0; } #endif #ifdef CONFIG_FB_FS453_TVOUT extern int fs453_ioctl(unsigned int cmd, void *arg); extern void fs453_dump(void); static int m532xfb_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg) { switch (cmd) { case ENCODER_GET_CAPABILITIES:{ int ret; struct video_encoder_capability cap; ret = fs453_ioctl(cmd, &cap); if (ret) return ret; if (copy_to_user((void *)arg, &cap, sizeof(cap))) return -EFAULT; break; } case ENCODER_SET_NORM:{ unsigned long mode; if (copy_from_user(&mode, (void *)arg, sizeof(mode))) return -EFAULT; return fs453_ioctl(cmd, &mode); } case ENCODER_SET_INPUT: case ENCODER_SET_OUTPUT: case ENCODER_ENABLE_OUTPUT:{ unsigned long varg; if (copy_from_user(&varg, (void *)arg, sizeof(varg))) return -EFAULT; return fs453_ioctl(cmd, &varg); } case ENCODER_SET_REG: { /*struct set_reg * tmp_val = (struct set_reg *)arg;*/ /*dev_dbg("reg=[0x%04x] val=[0x%x] size=[%d]\n", ((struct set_reg *)arg)->reg, ((struct set_reg *)arg)->val, ((struct set_reg *)arg)->size); */ return fs453_ioctl(cmd, (void *)arg); } break; case DECODER_DUMP: m532xfb_dump_info(info); fs453_dump(); break; default: dev_dbg(info->device, "Unknown ioctl command (0x%08X)\n", cmd); return -EINVAL; } return 0; } #endif /* * Initialization */ int __init m532xfb_init(void) { int cmap_len=256, retval; char* mode_option=NULL; /* * For kernel boot options (in 'video=xxxfb:<options>' format) */ #ifndef MODULE char *option = NULL; if (fb_get_options("m532xfb", &option)) { printk("No fb on command line specified\n"); return -ENODEV; } m532xfb_setup(option); #endif printk("Initing M532x Framebuffer\n"); info.fbops = &m532xfb_ops; info.fix = m532xfb_fix; info.pseudo_palette = pseudo_palette; /* * Set up flags to indicate what sort of acceleration your * driver can provide (pan/wrap/copyarea/etc.) and whether it * is a module -- see FBINFO_* in include/linux/fb.h */ info.flags = FBINFO_DEFAULT + FBINFO_HWACCEL_DISABLED; info.par = &current_par; /* * This should give a reasonable default video mode. The following is * done when we can set a video mode. */ if (!mode_option) mode_option = MODE_OPTION; retval = fb_find_mode(&info.var, &info, mode_option, NULL, 0, NULL, MODE_BPP); if (!retval || retval == 4) return -EINVAL; info.screen_size = (info.var.xres * info.var.yres * info.var.bits_per_pixel) / 8; info.var.xres_virtual = info.var.xres; info.var.yres_virtual = info.var.yres; info.var.pixclock = KHZ2PICOS(MCF_BUSCLK/1000/(PIX_CLK_DIV + 1)); info.var.hsync_len = FB_WAIT_PARAMS(FB_HWIDTH) + 1; info.var.vsync_len = FB_WAIT_PARAMS(FB_VWIDTH); info.var.left_margin = FB_WAIT_PARAMS(FB_HWAIT2) + 3; info.var.right_margin = FB_WAIT_PARAMS(FB_HWAIT1) + 1; info.var.upper_margin = FB_WAIT_PARAMS(FB_VWAIT2); info.var.lower_margin = FB_WAIT_PARAMS(FB_VWAIT1); #if MODE_BPP == 32 info.var.red.offset = 18; info.var.red.length = 6; info.var.red.msb_right = 0; info.var.green.offset = 10; info.var.green.length = 6; info.var.green.msb_right = 0; info.var.blue.offset = 2; info.var.blue.length = 6; info.var.blue.msb_right = 0; info.var.transp.offset = 0; info.var.transp.length = 0; info.var.transp.msb_right = 0; #else #if MODE_BPP == 1 info.var.red.offset = 0; info.var.red.length = 8; info.var.green.offset = 0; info.var.green.length = 8; info.var.blue.offset = 0; info.var.blue.length = 8; info.var.transp.offset = 0; info.var.transp.length = 0; info.var.transp.msb_right = 0; info.var.vmode = FB_VMODE_NONINTERLACED; #else info.var.red.offset = 11; info.var.red.length = 5; info.var.green.offset = 5; info.var.green.length = 6; info.var.blue.offset = 0; info.var.blue.length = 5; #endif #endif /* * Here we set the screen_base to the virtual memory address * for the framebuffer. Usually we obtain the resource address * from the bus layer and then translate it to virtual memory * space via ioremap. Consult ioport.h. */ info.screen_base = (unsigned char *)__get_free_pages(GFP_KERNEL, get_order(info.screen_size)); if (!info.screen_base) { printk("Unable to allocate %d PAGEs(%ld Bytes) fb memory\n",get_order(info.screen_size),info.screen_size); return -ENOMEM; } info.fix.smem_start = virt_to_phys((void *)info.screen_base); info.fix.smem_len = info.screen_size; info.fix.line_length = info.var.xres * info.var.bits_per_pixel / 8; /* * Set page reserved so that mmap will work. This is necessary * since we'll be remapping normal memory. */ { unsigned char * page; for (page = info.screen_base; (unsigned long)page < (PAGE_ALIGN((unsigned long)info.screen_base + info.screen_size)); page += PAGE_SIZE) { SetPageReserved(virt_to_page(page)); } } memset((void *)info.screen_base, 0, info.screen_size); /* set gpios */ MCF_GPIO_PAR_LCDDATA = 0xff; /* switch all to display */ #ifdef CONFIG_WG320240A MCF_GPIO_PAR_LCDCTL = 0x0ff; #else MCF_GPIO_PAR_LCDCTL = 0x1ff; #endif /* burst mode */ MCF_SCM_BCR = 0x3ff; MCF_LCDC_LSSAR = (unsigned int)info.screen_base; MCF_LCDC_LSR = MCF_LCDC_LSR_XMAX(MODE_WIDTH/16) | MCF_LCDC_LSR_YMAX(MODE_HEIGHT); MCF_LCDC_LVPWR = MCF_LCDC_LVPWR_VPW(MODE_VPW); /* Setup contrast register */ #ifdef CONFIG_WG320240A MCF_LCDC_LPCCR = 0x00000588; #else MCF_LCDC_LPCCR = 0x00000510; #endif #if defined(CONFIG_LCD_640x480) MCF_LCDC_LPCR = MCF_LCDC_LPCR_TFT | MCF_LCDC_LPCR_COLOR #if MODE_BPP == 32 | MCF_LCDC_LPCR_BPIX_18bpp #else | MCF_LCDC_LPCR_BPIX_16bpp #endif | MCF_LCDC_LPCR_FLM | MCF_LCDC_LPCR_LPPOL #ifndef CONFIG_FB_FS453_TVOUT | MCF_LCDC_LPCR_OEPOL #endif | MCF_LCDC_LPCR_CLKPOL | MCF_LCDC_LPCR_SCLKSEL | MCF_LCDC_LPCR_ACDSEL | MCF_LCDC_LPCR_ENDSEL | MCF_LCDC_LPCR_PCD(PIX_CLK_DIV); #elif defined(CONFIG_LCD_800x600) MCF_LCDC_LPCR = MCF_LCDC_LPCR_MODE_TFT #if MODE_BPP == 32 | MCF_LCDC_LPCR_BPIX_18bpp #else | MCF_LCDC_LPCR_BPIX_16bpp #endif | MCF_LCDC_LPCR_FLM | MCF_LCDC_LPCR_LPPOL | MCF_LCDC_LPCR_CLKPOL #ifndef CONFIG_FB_FS453_TVOUT | MCF_LCDC_LPCR_OEPOL #endif | MCF_LCDC_LPCR_ACDSEL | MCF_LCDC_LPCR_SCLKSEL | MCF_LCDC_LPCR_ENDSEL | MCF_LCDC_LPCR_PCD(PIX_CLK_DIV); #elif defined(CONFIG_LCD_240x320) || defined(CONFIG_LCD_320x240) || defined(CONFIG_LCD_320x200) #ifdef CONFIG_WG320240A MCF_LCDC_LPCR = MCF_LCDC_LPCR_MODE_MONOCGROME | MCF_LCDC_LPCR_PBSIZ_4 | MCF_LCDC_LPCR_BPIX_1bpp | MCF_LCDC_LPCR_OEPOL | MCF_LCDC_LPCR_SCLKIDLE | MCF_LCDC_LPCR_ENDSEL | MCF_LCDC_LPCR_SWAP_SEL | MCF_LCDC_LPCR_PCD(PIX_CLK_DIV); /*0x201e000a;*/ #else MCF_LCDC_LPCR = MCF_LCDC_LPCR_TFT | MCF_LCDC_LPCR_COLOR #if MODE_BPP == 32 | MCF_LCDC_LPCR_BPIX_18bpp #else | MCF_LCDC_LPCR_BPIX_16bpp #endif | MCF_LCDC_LPCR_FLM | MCF_LCDC_LPCR_LPPOL #ifndef CONFIG_FB_FS453_TVOUT | MCF_LCDC_LPCR_OEPOL #endif | MCF_LCDC_LPCR_CLKPOL | MCF_LCDC_LPCR_SCLKSEL | MCF_LCDC_LPCR_ACDSEL | MCF_LCDC_LPCR_ENDSEL | MCF_LCDC_LPCR_PCD(PIX_CLK_DIV); #endif #endif MCF_LCDC_LHCR = MCF_LCDC_LHCR_H_WIDTH(FB_WAIT_PARAMS(FB_HWIDTH)) | MCF_LCDC_LHCR_H_WAIT_1(FB_WAIT_PARAMS(FB_HWAIT1)) | MCF_LCDC_LHCR_H_WAIT_2(FB_WAIT_PARAMS(FB_HWAIT2)); MCF_LCDC_LVCR = MCF_LCDC_LVCR_V_WIDTH(FB_WAIT_PARAMS(FB_VWIDTH)) | MCF_LCDC_LVCR_V_WAIT_1(FB_WAIT_PARAMS(FB_VWAIT1)) | MCF_LCDC_LVCR_V_WAIT_2(FB_WAIT_PARAMS(FB_VWAIT2)); MCF_LCDC_LPOR = MCF_LCDC_LPOR_POS(0); MCF_LCDC_LDCR = LCDC_LDCR_VALUE; /* connect ldc controller to clock */ MCF_CCM_MISCCR |= MCF_CCM_MISCCR_LCD_CHEN; /* This has to been done !!! */ fb_alloc_cmap(&info.cmap, cmap_len, 0); /* * The following is done in the case of having hardware with a static * mode. If we are setting the mode ourselves we don't call this. */ if (register_framebuffer(&info) < 0) return -EINVAL; printk(KERN_INFO "fb%d: %s frame buffer device @0x%p\n", info.node, info.fix.id, info.screen_base); #if defined(CONFIG_UC53281EVM) || defined(CONFIG_UC532X) /* donot show cursor */ MCF_LCDC_LCPR = 0x0; MCF_LCDC_LCWHBR = 0x0; MCF_REG32(0xFC004100) = 0x65400321; /* WMQ: set LCD priority in XBS_PRS1 to be the highest */ /* should call fs453_setup() but fs453 driver is not initiated yet, using ioctl from user space instead */ /*fs453_setup(); */ #endif m532xfb_dump_info(&info); return 0; } /* * Cleanup */ static void __exit m532xfb_cleanup(void) { /* * If your driver supports multiple boards, you should unregister and * clean up all instances. */ unregister_framebuffer(&info); fb_dealloc_cmap(&info.cmap); /* ... */ } /* * Setup */ /* * Only necessary if your driver takes special options, * otherwise we fall back on the generic fb_setup(). */ int __init m532xfb_setup(char *options) { /* Parse user speficied options (`video=xxxfb:') */ return 0; } /* ------------------------------------------------------------------------- */ /* * Modularization */ module_init(m532xfb_init); module_exit(m532xfb_cleanup); MODULE_AUTHOR ("David Wu <www.ArcturusNetworks.com>, Thomas Brinker <tb@emlix.com>"); MODULE_DESCRIPTION("MCF532x Framebuffer"); MODULE_LICENSE("GPL");
robacklin/uclinux-linux
drivers/video/m532xfb.c
C
gpl-2.0
29,749
<?php if(have_posts()) : ?> <div class="imagethumbs"><?php ioya_the_images( $posts, apply_filters( 'ioya_image_count', 8 ), apply_filters( 'ioya_image_size', array(44, 44) ) ); ?></div> <?php while (have_posts()) : the_post(); ?> <div class="post"> <small><?php the_date(); ?></small> <h3><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3> <?php the_excerpt(); ?> </div> <?php endwhile; ?> <?php else : ?> <div class="post"> <p><?php _e('Sorry, we didn\'t find any posts for this month.', 'ioya'); ?></p> </div> <?php endif; ?>
jarednova/Passport
wp-content/plugins/in-over-your-archives/ioya_month.php
PHP
gpl-2.0
643
<?php /** * Core Design Web Gallery plugin for Joomla! 2.5 * @author Daniel Rataj, <info@greatjoomla.com> * @package Joomla * @subpackage Content * @category Plugin * @version 2.5.x.2.0.5 * @copyright Copyright (C) 2007 - 2012 Great Joomla!, http://www.greatjoomla.com * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL 3 * * This file is part of Great Joomla! extension. * This extension 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 extension 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/>. */ $path = ''; if (isset($_GET['path'])) $path = (string )$_GET['path']; if (extension_loaded('zlib') && !ini_get('zlib.output_compression')) @ob_start('ob_gzhandler'); header("Content-type: application/x-javascript"); header('Cache-Control: must-revalidate'); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT'); echo "var GB_ROOT_DIR = '$path'"; ?>
fatwayne/heart-bridge-joomla
plugins/content/cdwebgallery/engine/greybox/app/application.js.php
PHP
gpl-2.0
1,422
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CRAN - Package devRate</title> <link rel="stylesheet" type="text/css" href="../../CRAN_web.css" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="citation_title" content="Quantify Relationship Between Developmental Rate and Temperature in Ectotherms [R package devRate version 0.1.1]" /> <meta name="citation_author1" content="Francois Rebaudo" /> <meta name="citation_author2" content="Quentin Struelens" /> <meta name="citation_publication_date.Published" content="2017-01-23" /> <meta name="citation_public_url" content="https://CRAN.R-project.org/package=devRate" /> <meta name="DC.identifier" content="https://CRAN.R-project.org/package=devRate" /> <meta name="DC.publisher" content="Comprehensive R Archive Network (CRAN)" /> <style type="text/css"> table td { vertical-align: top; } </style> </head> <body> <h2>devRate: Quantify Relationship Between Developmental Rate and Temperature in Ectotherms</h2> <p>A set of functions to ease quantifying the relationship between developmental rate and temperature. The package comprises a set of models and estimated parameters borrowed from a literature review in ectotherms.</p> <table summary="Package devRate summary"> <tr> <td>Version:</td> <td>0.1.1</td> </tr> <tr> <td>Suggests:</td> <td><a href="../knitr/index.html">knitr</a>, <a href="../rmarkdown/index.html">rmarkdown</a>, <a href="../testthat/index.html">testthat</a></td> </tr> <tr> <td>Published:</td> <td>2017-01-23</td> </tr> <tr> <td>Author:</td> <td>Francois Rebaudo [aut, cre], Quentin Struelens [aut]</td> </tr> <tr> <td>Maintainer:</td> <td>Francois Rebaudo &#x3c;&#x66;&#x72;&#x61;&#x6e;&#x63;&#x6f;&#x69;&#x73;&#x2e;&#x72;&#x65;&#x62;&#x61;&#x75;&#x64;&#x6f;&#x20;&#x61;&#x74;&#x20;&#x69;&#x72;&#x64;&#x2e;&#x66;&#x72;&#x3e;</td> </tr> <tr> <td>License:</td> <td><a href="../../licenses/GPL-2">GPL-2</a></td> </tr> <tr> <td>NeedsCompilation:</td> <td>no</td> </tr> <tr> <td>Materials:</td> <td><a href="README.html">README</a> <a href="news.html">NEWS</a> </td> </tr> <tr> <td>CRAN&nbsp;checks:</td> <td><a href="../../checks/check_results_devRate.html">devRate results</a></td> </tr> </table> <h4>Downloads:</h4> <table summary="Package devRate downloads"> <tr> <td> Reference&nbsp;manual: </td> <td> <a href="devRate.pdf"> devRate.pdf </a> </td> </tr> <tr> <td>Vignettes:</td> <td> <a href="vignettes/example_tropical.html">main</a><br/> </td> </tr> <tr> <td> Package&nbsp;source: </td> <td> <a href="../../../src/contrib/devRate_0.1.1.tar.gz"> devRate_0.1.1.tar.gz </a> </td> </tr> <tr> <td> Windows&nbsp;binaries: </td> <td> r-devel: <a href="../../../bin/windows/contrib/3.5/devRate_0.1.1.zip">devRate_0.1.1.zip</a>, r-release: <a href="../../../bin/windows/contrib/3.4/devRate_0.1.1.zip">devRate_0.1.1.zip</a>, r-oldrel: <a href="../../../bin/windows/contrib/3.3/devRate_0.1.1.zip">devRate_0.1.1.zip</a> </td> </tr> <tr> <td> OS&nbsp;X&nbsp;El&nbsp;Capitan&nbsp;binaries: </td> <td> r-release: <a href="../../../bin/macosx/el-capitan/contrib/3.4/devRate_0.1.1.tgz">devRate_0.1.1.tgz</a> </td> </tr> <tr> <td> OS&nbsp;X&nbsp;Mavericks&nbsp;binaries: </td> <td> r-oldrel: <a href="../../../bin/macosx/mavericks/contrib/3.3/devRate_0.1.1.tgz">devRate_0.1.1.tgz</a> </td> </tr> <tr> <td> Old&nbsp;sources: </td> <td> <a href="../../../src/contrib/Archive/devRate"> devRate archive </a> </td> </tr> </table> <h4>Linking:</h4> <p>Please use the canonical form <a href="https://CRAN.R-project.org/package=devRate"><samp>https://CRAN.R-project.org/package=devRate</samp></a> to link to this page.</p> </body> </html>
esander91/NamespacePollution
Code/GetMetaDataFromCRAN/raw_html/devRate.html
HTML
gpl-2.0
3,756
/* $Id: PDMAsyncCompletion.cpp $ */ /** @file * PDM Async I/O - Transport data asynchronous in R3 using EMT. */ /* * Copyright (C) 2006-2011 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /******************************************************************************* * Header Files * *******************************************************************************/ #define LOG_GROUP LOG_GROUP_PDM_ASYNC_COMPLETION #include "PDMInternal.h" #include <VBox/vmm/pdm.h> #include <VBox/vmm/mm.h> #ifdef VBOX_WITH_REM # include <VBox/vmm/rem.h> #endif #include <VBox/vmm/vm.h> #include <VBox/vmm/uvm.h> #include <VBox/err.h> #include <VBox/log.h> #include <iprt/asm.h> #include <iprt/assert.h> #include <iprt/thread.h> #include <iprt/mem.h> #include <iprt/critsect.h> #include <iprt/tcp.h> #include <iprt/path.h> #include <iprt/string.h> #include <VBox/vmm/pdmasynccompletion.h> #include "PDMAsyncCompletionInternal.h" /******************************************************************************* * Structures and Typedefs * *******************************************************************************/ /** * Async I/O type. */ typedef enum PDMASYNCCOMPLETIONTEMPLATETYPE { /** Device . */ PDMASYNCCOMPLETIONTEMPLATETYPE_DEV = 1, /** Driver consumer. */ PDMASYNCCOMPLETIONTEMPLATETYPE_DRV, /** Internal consumer. */ PDMASYNCCOMPLETIONTEMPLATETYPE_INTERNAL, /** Usb consumer. */ PDMASYNCCOMPLETIONTEMPLATETYPE_USB } PDMASYNCTEMPLATETYPE; /** * PDM Async I/O template. */ typedef struct PDMASYNCCOMPLETIONTEMPLATE { /** Pointer to the next template in the list. */ R3PTRTYPE(PPDMASYNCCOMPLETIONTEMPLATE) pNext; /** Pointer to the previous template in the list. */ R3PTRTYPE(PPDMASYNCCOMPLETIONTEMPLATE) pPrev; /** Type specific data. */ union { /** PDMASYNCCOMPLETIONTEMPLATETYPE_DEV */ struct { /** Pointer to consumer function. */ R3PTRTYPE(PFNPDMASYNCCOMPLETEDEV) pfnCompleted; /** Pointer to the device instance owning the template. */ R3PTRTYPE(PPDMDEVINS) pDevIns; } Dev; /** PDMASYNCCOMPLETIONTEMPLATETYPE_DRV */ struct { /** Pointer to consumer function. */ R3PTRTYPE(PFNPDMASYNCCOMPLETEDRV) pfnCompleted; /** Pointer to the driver instance owning the template. */ R3PTRTYPE(PPDMDRVINS) pDrvIns; /** User argument given during template creation. * This is only here to make things much easier * for DrVVD. */ void *pvTemplateUser; } Drv; /** PDMASYNCCOMPLETIONTEMPLATETYPE_INTERNAL */ struct { /** Pointer to consumer function. */ R3PTRTYPE(PFNPDMASYNCCOMPLETEINT) pfnCompleted; /** Pointer to user data. */ R3PTRTYPE(void *) pvUser; } Int; /** PDMASYNCCOMPLETIONTEMPLATETYPE_USB */ struct { /** Pointer to consumer function. */ R3PTRTYPE(PFNPDMASYNCCOMPLETEUSB) pfnCompleted; /** Pointer to the usb instance owning the template. */ R3PTRTYPE(PPDMUSBINS) pUsbIns; } Usb; } u; /** Template type. */ PDMASYNCCOMPLETIONTEMPLATETYPE enmType; /** Pointer to the VM. */ R3PTRTYPE(PVM) pVM; /** Use count of the template. */ volatile uint32_t cUsed; } PDMASYNCCOMPLETIONTEMPLATE; /** * Bandwidth control manager instance data */ typedef struct PDMACBWMGR { /** Pointer to the next manager in the list. */ struct PDMACBWMGR *pNext; /** Pointer to the shared UVM structure. */ PPDMASYNCCOMPLETIONEPCLASS pEpClass; /** Identifier of the manager. */ char *pszId; /** Maximum number of bytes the endpoints are allowed to transfer (Max is 4GB/s currently) */ volatile uint32_t cbTransferPerSecMax; /** Number of bytes we start with */ volatile uint32_t cbTransferPerSecStart; /** Step after each update */ volatile uint32_t cbTransferPerSecStep; /** Number of bytes we are allowed to transfer till the next update. * Reset by the refresh timer. */ volatile uint32_t cbTransferAllowed; /** Timestamp of the last update */ volatile uint64_t tsUpdatedLast; /** Reference counter - How many endpoints are associated with this manager. */ volatile uint32_t cRefs; } PDMACBWMGR; /** Pointer to a bandwidth control manager pointer. */ typedef PPDMACBWMGR *PPPDMACBWMGR; /******************************************************************************* * Internal Functions * *******************************************************************************/ static void pdmR3AsyncCompletionPutTask(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, PPDMASYNCCOMPLETIONTASK pTask); /** * Internal worker for the creation apis * * @returns VBox status. * @param pVM Pointer to the VM. * @param ppTemplate Where to store the template handle. */ static int pdmR3AsyncCompletionTemplateCreate(PVM pVM, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate, PDMASYNCCOMPLETIONTEMPLATETYPE enmType) { PUVM pUVM = pVM->pUVM; AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER); PPDMASYNCCOMPLETIONTEMPLATE pTemplate; int rc = MMR3HeapAllocZEx(pVM, MM_TAG_PDM_ASYNC_COMPLETION, sizeof(PDMASYNCCOMPLETIONTEMPLATE), (void **)&pTemplate); if (RT_FAILURE(rc)) return rc; /* * Initialize fields. */ pTemplate->pVM = pVM; pTemplate->cUsed = 0; pTemplate->enmType = enmType; /* * Add template to the global VM template list. */ RTCritSectEnter(&pUVM->pdm.s.ListCritSect); pTemplate->pNext = pUVM->pdm.s.pAsyncCompletionTemplates; if (pUVM->pdm.s.pAsyncCompletionTemplates) pUVM->pdm.s.pAsyncCompletionTemplates->pPrev = pTemplate; pUVM->pdm.s.pAsyncCompletionTemplates = pTemplate; RTCritSectLeave(&pUVM->pdm.s.ListCritSect); *ppTemplate = pTemplate; return VINF_SUCCESS; } /** * Creates a async completion template for a device instance. * * The template is used when creating new completion tasks. * * @returns VBox status code. * @param pVM Pointer to the VM. * @param pDevIns The device instance. * @param ppTemplate Where to store the template pointer on success. * @param pfnCompleted The completion callback routine. * @param pszDesc Description. */ VMMR3DECL(int) PDMR3AsyncCompletionTemplateCreateDevice(PVM pVM, PPDMDEVINS pDevIns, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate, PFNPDMASYNCCOMPLETEDEV pfnCompleted, const char *pszDesc) { LogFlow(("%s: pDevIns=%p ppTemplate=%p pfnCompleted=%p pszDesc=%s\n", __FUNCTION__, pDevIns, ppTemplate, pfnCompleted, pszDesc)); /* * Validate input. */ VM_ASSERT_EMT(pVM); AssertPtrReturn(pfnCompleted, VERR_INVALID_POINTER); AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER); /* * Create the template. */ PPDMASYNCCOMPLETIONTEMPLATE pTemplate; int rc = pdmR3AsyncCompletionTemplateCreate(pVM, &pTemplate, PDMASYNCCOMPLETIONTEMPLATETYPE_DEV); if (RT_SUCCESS(rc)) { pTemplate->u.Dev.pDevIns = pDevIns; pTemplate->u.Dev.pfnCompleted = pfnCompleted; *ppTemplate = pTemplate; Log(("PDM: Created device template %p: pfnCompleted=%p pDevIns=%p\n", pTemplate, pfnCompleted, pDevIns)); } return rc; } /** * Creates a async completion template for a driver instance. * * The template is used when creating new completion tasks. * * @returns VBox status code. * @param pVM Pointer to the VM. * @param pDrvIns The driver instance. * @param ppTemplate Where to store the template pointer on success. * @param pfnCompleted The completion callback routine. * @param pvTemplateUser Template user argument * @param pszDesc Description. */ VMMR3DECL(int) PDMR3AsyncCompletionTemplateCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate, PFNPDMASYNCCOMPLETEDRV pfnCompleted, void *pvTemplateUser, const char *pszDesc) { LogFlow(("%s: pDrvIns=%p ppTemplate=%p pfnCompleted=%p pszDesc=%s\n", __FUNCTION__, pDrvIns, ppTemplate, pfnCompleted, pszDesc)); /* * Validate input. */ AssertPtrReturn(pfnCompleted, VERR_INVALID_POINTER); AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER); /* * Create the template. */ PPDMASYNCCOMPLETIONTEMPLATE pTemplate; int rc = pdmR3AsyncCompletionTemplateCreate(pVM, &pTemplate, PDMASYNCCOMPLETIONTEMPLATETYPE_DRV); if (RT_SUCCESS(rc)) { pTemplate->u.Drv.pDrvIns = pDrvIns; pTemplate->u.Drv.pfnCompleted = pfnCompleted; pTemplate->u.Drv.pvTemplateUser = pvTemplateUser; *ppTemplate = pTemplate; Log(("PDM: Created driver template %p: pfnCompleted=%p pDrvIns=%p\n", pTemplate, pfnCompleted, pDrvIns)); } return rc; } /** * Creates a async completion template for a USB device instance. * * The template is used when creating new completion tasks. * * @returns VBox status code. * @param pVM Pointer to the VM. * @param pUsbIns The USB device instance. * @param ppTemplate Where to store the template pointer on success. * @param pfnCompleted The completion callback routine. * @param pszDesc Description. */ VMMR3DECL(int) PDMR3AsyncCompletionTemplateCreateUsb(PVM pVM, PPDMUSBINS pUsbIns, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate, PFNPDMASYNCCOMPLETEUSB pfnCompleted, const char *pszDesc) { LogFlow(("%s: pUsbIns=%p ppTemplate=%p pfnCompleted=%p pszDesc=%s\n", __FUNCTION__, pUsbIns, ppTemplate, pfnCompleted, pszDesc)); /* * Validate input. */ VM_ASSERT_EMT(pVM); AssertPtrReturn(pfnCompleted, VERR_INVALID_POINTER); AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER); /* * Create the template. */ PPDMASYNCCOMPLETIONTEMPLATE pTemplate; int rc = pdmR3AsyncCompletionTemplateCreate(pVM, &pTemplate, PDMASYNCCOMPLETIONTEMPLATETYPE_USB); if (RT_SUCCESS(rc)) { pTemplate->u.Usb.pUsbIns = pUsbIns; pTemplate->u.Usb.pfnCompleted = pfnCompleted; *ppTemplate = pTemplate; Log(("PDM: Created usb template %p: pfnCompleted=%p pDevIns=%p\n", pTemplate, pfnCompleted, pUsbIns)); } return rc; } /** * Creates a async completion template for internally by the VMM. * * The template is used when creating new completion tasks. * * @returns VBox status code. * @param pVM Pointer to the VM. * @param ppTemplate Where to store the template pointer on success. * @param pfnCompleted The completion callback routine. * @param pvUser2 The 2nd user argument for the callback. * @param pszDesc Description. */ VMMR3DECL(int) PDMR3AsyncCompletionTemplateCreateInternal(PVM pVM, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate, PFNPDMASYNCCOMPLETEINT pfnCompleted, void *pvUser2, const char *pszDesc) { LogFlow(("%s: ppTemplate=%p pfnCompleted=%p pvUser2=%p pszDesc=%s\n", __FUNCTION__, ppTemplate, pfnCompleted, pvUser2, pszDesc)); /* * Validate input. */ VM_ASSERT_EMT(pVM); AssertPtrReturn(pfnCompleted, VERR_INVALID_POINTER); AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER); /* * Create the template. */ PPDMASYNCCOMPLETIONTEMPLATE pTemplate; int rc = pdmR3AsyncCompletionTemplateCreate(pVM, &pTemplate, PDMASYNCCOMPLETIONTEMPLATETYPE_INTERNAL); if (RT_SUCCESS(rc)) { pTemplate->u.Int.pvUser = pvUser2; pTemplate->u.Int.pfnCompleted = pfnCompleted; *ppTemplate = pTemplate; Log(("PDM: Created internal template %p: pfnCompleted=%p pvUser2=%p\n", pTemplate, pfnCompleted, pvUser2)); } return rc; } /** * Destroys the specified async completion template. * * @returns VBox status codes: * @retval VINF_SUCCESS on success. * @retval VERR_PDM_ASYNC_TEMPLATE_BUSY if the template is still in use. * * @param pTemplate The template in question. */ VMMR3DECL(int) PDMR3AsyncCompletionTemplateDestroy(PPDMASYNCCOMPLETIONTEMPLATE pTemplate) { LogFlow(("%s: pTemplate=%p\n", __FUNCTION__, pTemplate)); if (!pTemplate) { AssertMsgFailed(("pTemplate is NULL!\n")); return VERR_INVALID_PARAMETER; } /* * Check if the template is still used. */ if (pTemplate->cUsed > 0) { AssertMsgFailed(("Template is still in use\n")); return VERR_PDM_ASYNC_TEMPLATE_BUSY; } /* * Unlink the template from the list. */ PUVM pUVM = pTemplate->pVM->pUVM; RTCritSectEnter(&pUVM->pdm.s.ListCritSect); PPDMASYNCCOMPLETIONTEMPLATE pPrev = pTemplate->pPrev; PPDMASYNCCOMPLETIONTEMPLATE pNext = pTemplate->pNext; if (pPrev) pPrev->pNext = pNext; else pUVM->pdm.s.pAsyncCompletionTemplates = pNext; if (pNext) pNext->pPrev = pPrev; RTCritSectLeave(&pUVM->pdm.s.ListCritSect); /* * Free the template. */ MMR3HeapFree(pTemplate); return VINF_SUCCESS; } /** * Destroys all the specified async completion templates for the given device instance. * * @returns VBox status codes: * @retval VINF_SUCCESS on success. * @retval VERR_PDM_ASYNC_TEMPLATE_BUSY if one or more of the templates are still in use. * * @param pVM Pointer to the VM. * @param pDevIns The device instance. */ VMMR3DECL(int) PDMR3AsyncCompletionTemplateDestroyDevice(PVM pVM, PPDMDEVINS pDevIns) { LogFlow(("%s: pDevIns=%p\n", __FUNCTION__, pDevIns)); /* * Validate input. */ if (!pDevIns) return VERR_INVALID_PARAMETER; VM_ASSERT_EMT(pVM); /* * Unlink it. */ PUVM pUVM = pVM->pUVM; RTCritSectEnter(&pUVM->pdm.s.ListCritSect); PPDMASYNCCOMPLETIONTEMPLATE pTemplate = pUVM->pdm.s.pAsyncCompletionTemplates; while (pTemplate) { if ( pTemplate->enmType == PDMASYNCCOMPLETIONTEMPLATETYPE_DEV && pTemplate->u.Dev.pDevIns == pDevIns) { PPDMASYNCCOMPLETIONTEMPLATE pTemplateDestroy = pTemplate; pTemplate = pTemplate->pNext; int rc = PDMR3AsyncCompletionTemplateDestroy(pTemplateDestroy); if (RT_FAILURE(rc)) { RTCritSectLeave(&pUVM->pdm.s.ListCritSect); return rc; } } else pTemplate = pTemplate->pNext; } RTCritSectLeave(&pUVM->pdm.s.ListCritSect); return VINF_SUCCESS; } /** * Destroys all the specified async completion templates for the given driver instance. * * @returns VBox status codes: * @retval VINF_SUCCESS on success. * @retval VERR_PDM_ASYNC_TEMPLATE_BUSY if one or more of the templates are still in use. * * @param pVM Pointer to the VM. * @param pDrvIns The driver instance. */ VMMR3DECL(int) PDMR3AsyncCompletionTemplateDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns) { LogFlow(("%s: pDevIns=%p\n", __FUNCTION__, pDrvIns)); /* * Validate input. */ if (!pDrvIns) return VERR_INVALID_PARAMETER; VM_ASSERT_EMT(pVM); /* * Unlink it. */ PUVM pUVM = pVM->pUVM; RTCritSectEnter(&pUVM->pdm.s.ListCritSect); PPDMASYNCCOMPLETIONTEMPLATE pTemplate = pUVM->pdm.s.pAsyncCompletionTemplates; while (pTemplate) { if ( pTemplate->enmType == PDMASYNCCOMPLETIONTEMPLATETYPE_DRV && pTemplate->u.Drv.pDrvIns == pDrvIns) { PPDMASYNCCOMPLETIONTEMPLATE pTemplateDestroy = pTemplate; pTemplate = pTemplate->pNext; int rc = PDMR3AsyncCompletionTemplateDestroy(pTemplateDestroy); if (RT_FAILURE(rc)) { RTCritSectLeave(&pUVM->pdm.s.ListCritSect); return rc; } } else pTemplate = pTemplate->pNext; } RTCritSectLeave(&pUVM->pdm.s.ListCritSect); return VINF_SUCCESS; } /** * Destroys all the specified async completion templates for the given USB device instance. * * @returns VBox status codes: * @retval VINF_SUCCESS on success. * @retval VERR_PDM_ASYNC_TEMPLATE_BUSY if one or more of the templates are still in use. * * @param pVM Pointer to the VM. * @param pUsbIns The USB device instance. */ VMMR3DECL(int) PDMR3AsyncCompletionTemplateDestroyUsb(PVM pVM, PPDMUSBINS pUsbIns) { LogFlow(("%s: pUsbIns=%p\n", __FUNCTION__, pUsbIns)); /* * Validate input. */ if (!pUsbIns) return VERR_INVALID_PARAMETER; VM_ASSERT_EMT(pVM); /* * Unlink it. */ PUVM pUVM = pVM->pUVM; RTCritSectEnter(&pUVM->pdm.s.ListCritSect); PPDMASYNCCOMPLETIONTEMPLATE pTemplate = pUVM->pdm.s.pAsyncCompletionTemplates; while (pTemplate) { if ( pTemplate->enmType == PDMASYNCCOMPLETIONTEMPLATETYPE_USB && pTemplate->u.Usb.pUsbIns == pUsbIns) { PPDMASYNCCOMPLETIONTEMPLATE pTemplateDestroy = pTemplate; pTemplate = pTemplate->pNext; int rc = PDMR3AsyncCompletionTemplateDestroy(pTemplateDestroy); if (RT_FAILURE(rc)) { RTCritSectLeave(&pUVM->pdm.s.ListCritSect); return rc; } } else pTemplate = pTemplate->pNext; } RTCritSectLeave(&pUVM->pdm.s.ListCritSect); return VINF_SUCCESS; } static PPDMACBWMGR pdmacBwMgrFindById(PPDMASYNCCOMPLETIONEPCLASS pEpClass, const char *pcszId) { PPDMACBWMGR pBwMgr = NULL; if (RT_VALID_PTR(pcszId)) { int rc = RTCritSectEnter(&pEpClass->CritSect); AssertRC(rc); pBwMgr = pEpClass->pBwMgrsHead; while ( pBwMgr && RTStrCmp(pBwMgr->pszId, pcszId)) pBwMgr = pBwMgr->pNext; rc = RTCritSectLeave(&pEpClass->CritSect); AssertRC(rc); } return pBwMgr; } static void pdmacBwMgrLink(PPDMACBWMGR pBwMgr) { PPDMASYNCCOMPLETIONEPCLASS pEpClass = pBwMgr->pEpClass; int rc = RTCritSectEnter(&pEpClass->CritSect); AssertRC(rc); pBwMgr->pNext = pEpClass->pBwMgrsHead; pEpClass->pBwMgrsHead = pBwMgr; rc = RTCritSectLeave(&pEpClass->CritSect); AssertRC(rc); } #ifdef SOME_UNUSED_FUNCTION static void pdmacBwMgrUnlink(PPDMACBWMGR pBwMgr) { PPDMASYNCCOMPLETIONEPCLASS pEpClass = pBwMgr->pEpClass; int rc = RTCritSectEnter(&pEpClass->CritSect); AssertRC(rc); if (pBwMgr == pEpClass->pBwMgrsHead) pEpClass->pBwMgrsHead = pBwMgr->pNext; else { PPDMACBWMGR pPrev = pEpClass->pBwMgrsHead; while ( pPrev && pPrev->pNext != pBwMgr) pPrev = pPrev->pNext; AssertPtr(pPrev); pPrev->pNext = pBwMgr->pNext; } rc = RTCritSectLeave(&pEpClass->CritSect); AssertRC(rc); } #endif /* SOME_UNUSED_FUNCTION */ static int pdmacAsyncCompletionBwMgrCreate(PPDMASYNCCOMPLETIONEPCLASS pEpClass, const char *pcszBwMgr, uint32_t cbTransferPerSecMax, uint32_t cbTransferPerSecStart, uint32_t cbTransferPerSecStep) { LogFlowFunc(("pEpClass=%#p pcszBwMgr=%#p{%s} cbTransferPerSecMax=%u cbTransferPerSecStart=%u cbTransferPerSecStep=%u\n", pEpClass, pcszBwMgr, cbTransferPerSecMax, cbTransferPerSecStart, cbTransferPerSecStep)); AssertPtrReturn(pEpClass, VERR_INVALID_POINTER); AssertPtrReturn(pcszBwMgr, VERR_INVALID_POINTER); AssertReturn(*pcszBwMgr != '\0', VERR_INVALID_PARAMETER); int rc; PPDMACBWMGR pBwMgr = pdmacBwMgrFindById(pEpClass, pcszBwMgr); if (!pBwMgr) { rc = MMR3HeapAllocZEx(pEpClass->pVM, MM_TAG_PDM_ASYNC_COMPLETION, sizeof(PDMACBWMGR), (void **)&pBwMgr); if (RT_SUCCESS(rc)) { pBwMgr->pszId = RTStrDup(pcszBwMgr); if (pBwMgr->pszId) { pBwMgr->pEpClass = pEpClass; pBwMgr->cRefs = 0; /* Init I/O flow control. */ pBwMgr->cbTransferPerSecMax = cbTransferPerSecMax; pBwMgr->cbTransferPerSecStart = cbTransferPerSecStart; pBwMgr->cbTransferPerSecStep = cbTransferPerSecStep; pBwMgr->cbTransferAllowed = pBwMgr->cbTransferPerSecStart; pBwMgr->tsUpdatedLast = RTTimeSystemNanoTS(); pdmacBwMgrLink(pBwMgr); rc = VINF_SUCCESS; } else { rc = VERR_NO_MEMORY; MMR3HeapFree(pBwMgr); } } } else rc = VERR_ALREADY_EXISTS; LogFlowFunc(("returns rc=%Rrc\n", rc)); return rc; } DECLINLINE(void) pdmacBwMgrRef(PPDMACBWMGR pBwMgr) { ASMAtomicIncU32(&pBwMgr->cRefs); } DECLINLINE(void) pdmacBwMgrUnref(PPDMACBWMGR pBwMgr) { Assert(pBwMgr->cRefs > 0); ASMAtomicDecU32(&pBwMgr->cRefs); } bool pdmacEpIsTransferAllowed(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, uint32_t cbTransfer, RTMSINTERVAL *pmsWhenNext) { bool fAllowed = true; PPDMACBWMGR pBwMgr = ASMAtomicReadPtrT(&pEndpoint->pBwMgr, PPDMACBWMGR); LogFlowFunc(("pEndpoint=%p pBwMgr=%p cbTransfer=%u\n", pEndpoint, pBwMgr, cbTransfer)); if (pBwMgr) { uint32_t cbOld = ASMAtomicSubU32(&pBwMgr->cbTransferAllowed, cbTransfer); if (RT_LIKELY(cbOld >= cbTransfer)) fAllowed = true; else { fAllowed = false; /* We are out of resources Check if we can update again. */ uint64_t tsNow = RTTimeSystemNanoTS(); uint64_t tsUpdatedLast = ASMAtomicUoReadU64(&pBwMgr->tsUpdatedLast); if (tsNow - tsUpdatedLast >= (1000*1000*1000)) { if (ASMAtomicCmpXchgU64(&pBwMgr->tsUpdatedLast, tsNow, tsUpdatedLast)) { if (pBwMgr->cbTransferPerSecStart < pBwMgr->cbTransferPerSecMax) { pBwMgr->cbTransferPerSecStart = RT_MIN(pBwMgr->cbTransferPerSecMax, pBwMgr->cbTransferPerSecStart + pBwMgr->cbTransferPerSecStep); LogFlow(("AIOMgr: Increasing maximum bandwidth to %u bytes/sec\n", pBwMgr->cbTransferPerSecStart)); } /* Update */ ASMAtomicWriteU32(&pBwMgr->cbTransferAllowed, pBwMgr->cbTransferPerSecStart - cbTransfer); fAllowed = true; LogFlow(("AIOMgr: Refreshed bandwidth\n")); } } else { ASMAtomicAddU32(&pBwMgr->cbTransferAllowed, cbTransfer); *pmsWhenNext = ((1000*1000*1000) - (tsNow - tsUpdatedLast)) / (1000*1000); } } } LogFlowFunc(("fAllowed=%RTbool\n", fAllowed)); return fAllowed; } void pdmR3AsyncCompletionCompleteTask(PPDMASYNCCOMPLETIONTASK pTask, int rc, bool fCallCompletionHandler) { LogFlow(("%s: pTask=%#p fCallCompletionHandler=%RTbool\n", __FUNCTION__, pTask, fCallCompletionHandler)); if (fCallCompletionHandler) { PPDMASYNCCOMPLETIONTEMPLATE pTemplate = pTask->pEndpoint->pTemplate; switch (pTemplate->enmType) { case PDMASYNCCOMPLETIONTEMPLATETYPE_DEV: pTemplate->u.Dev.pfnCompleted(pTemplate->u.Dev.pDevIns, pTask->pvUser, rc); break; case PDMASYNCCOMPLETIONTEMPLATETYPE_DRV: pTemplate->u.Drv.pfnCompleted(pTemplate->u.Drv.pDrvIns, pTemplate->u.Drv.pvTemplateUser, pTask->pvUser, rc); break; case PDMASYNCCOMPLETIONTEMPLATETYPE_USB: pTemplate->u.Usb.pfnCompleted(pTemplate->u.Usb.pUsbIns, pTask->pvUser, rc); break; case PDMASYNCCOMPLETIONTEMPLATETYPE_INTERNAL: pTemplate->u.Int.pfnCompleted(pTemplate->pVM, pTask->pvUser, pTemplate->u.Int.pvUser, rc); break; default: AssertMsgFailed(("Unknown template type!\n")); } } pdmR3AsyncCompletionPutTask(pTask->pEndpoint, pTask); } /** * Worker initializing a endpoint class. * * @returns VBox status code. * @param pVM Pointer to the shared VM instance data. * @param pEpClass Pointer to the endpoint class structure. * @param pCfgHandle Pointer to the CFGM tree. */ int pdmR3AsyncCompletionEpClassInit(PVM pVM, PCPDMASYNCCOMPLETIONEPCLASSOPS pEpClassOps, PCFGMNODE pCfgHandle) { /* Validate input. */ AssertPtrReturn(pEpClassOps, VERR_INVALID_POINTER); AssertReturn(pEpClassOps->u32Version == PDMAC_EPCLASS_OPS_VERSION, VERR_VERSION_MISMATCH); AssertReturn(pEpClassOps->u32VersionEnd == PDMAC_EPCLASS_OPS_VERSION, VERR_VERSION_MISMATCH); LogFlowFunc((": pVM=%p pEpClassOps=%p{%s}\n", pVM, pEpClassOps, pEpClassOps->pcszName)); /* Allocate global class data. */ PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = NULL; int rc = MMR3HeapAllocZEx(pVM, MM_TAG_PDM_ASYNC_COMPLETION, pEpClassOps->cbEndpointClassGlobal, (void **)&pEndpointClass); if (RT_SUCCESS(rc)) { /* Initialize common data. */ pEndpointClass->pVM = pVM; pEndpointClass->pEndpointOps = pEpClassOps; rc = RTCritSectInit(&pEndpointClass->CritSect); if (RT_SUCCESS(rc)) { PCFGMNODE pCfgNodeClass = CFGMR3GetChild(pCfgHandle, pEpClassOps->pcszName); /* Create task cache */ rc = RTMemCacheCreate(&pEndpointClass->hMemCacheTasks, pEpClassOps->cbTask, 0, UINT32_MAX, NULL, NULL, NULL, 0); if (RT_SUCCESS(rc)) { /* Call the specific endpoint class initializer. */ rc = pEpClassOps->pfnInitialize(pEndpointClass, pCfgNodeClass); if (RT_SUCCESS(rc)) { /* Create all bandwidth groups for resource control. */ PCFGMNODE pCfgBwGrp = CFGMR3GetChild(pCfgNodeClass, "BwGroups"); if (pCfgBwGrp) { for (PCFGMNODE pCur = CFGMR3GetFirstChild(pCfgBwGrp); pCur; pCur = CFGMR3GetNextChild(pCur)) { uint32_t cbMax, cbStart, cbStep; size_t cchName = CFGMR3GetNameLen(pCur) + 1; char *pszBwGrpId = (char *)RTMemAllocZ(cchName); if (!pszBwGrpId) { rc = VERR_NO_MEMORY; break; } rc = CFGMR3GetName(pCur, pszBwGrpId, cchName); AssertRC(rc); if (RT_SUCCESS(rc)) rc = CFGMR3QueryU32(pCur, "Max", &cbMax); if (RT_SUCCESS(rc)) rc = CFGMR3QueryU32Def(pCur, "Start", &cbStart, cbMax); if (RT_SUCCESS(rc)) rc = CFGMR3QueryU32Def(pCur, "Step", &cbStep, 0); if (RT_SUCCESS(rc)) rc = pdmacAsyncCompletionBwMgrCreate(pEndpointClass, pszBwGrpId, cbMax, cbStart, cbStep); RTMemFree(pszBwGrpId); if (RT_FAILURE(rc)) break; } } if (RT_SUCCESS(rc)) { PUVM pUVM = pVM->pUVM; AssertMsg(!pUVM->pdm.s.apAsyncCompletionEndpointClass[pEpClassOps->enmClassType], ("Endpoint class was already initialized\n")); pUVM->pdm.s.apAsyncCompletionEndpointClass[pEpClassOps->enmClassType] = pEndpointClass; LogFlowFunc((": Initialized endpoint class \"%s\" rc=%Rrc\n", pEpClassOps->pcszName, rc)); return VINF_SUCCESS; } } RTMemCacheDestroy(pEndpointClass->hMemCacheTasks); } RTCritSectDelete(&pEndpointClass->CritSect); } MMR3HeapFree(pEndpointClass); } LogFlowFunc((": Failed to initialize endpoint class rc=%Rrc\n", rc)); return rc; } /** * Worker terminating all endpoint classes. * * @returns nothing * @param pEndpointClass Pointer to the endpoint class to terminate. * * @remarks This method ensures that any still open endpoint is closed. */ static void pdmR3AsyncCompletionEpClassTerminate(PPDMASYNCCOMPLETIONEPCLASS pEndpointClass) { PVM pVM = pEndpointClass->pVM; /* Close all still open endpoints. */ while (pEndpointClass->pEndpointsHead) PDMR3AsyncCompletionEpClose(pEndpointClass->pEndpointsHead); /* Destroy the bandwidth managers. */ PPDMACBWMGR pBwMgr = pEndpointClass->pBwMgrsHead; while (pBwMgr) { PPDMACBWMGR pFree = pBwMgr; pBwMgr = pBwMgr->pNext; MMR3HeapFree(pFree); } /* Call the termination callback of the class. */ pEndpointClass->pEndpointOps->pfnTerminate(pEndpointClass); RTMemCacheDestroy(pEndpointClass->hMemCacheTasks); RTCritSectDelete(&pEndpointClass->CritSect); /* Free the memory of the class finally and clear the entry in the class array. */ pVM->pUVM->pdm.s.apAsyncCompletionEndpointClass[pEndpointClass->pEndpointOps->enmClassType] = NULL; MMR3HeapFree(pEndpointClass); } /** * Initialize the async completion manager. * * @returns VBox status code * @param pVM Pointer to the VM. */ int pdmR3AsyncCompletionInit(PVM pVM) { LogFlowFunc((": pVM=%p\n", pVM)); VM_ASSERT_EMT(pVM); PCFGMNODE pCfgRoot = CFGMR3GetRoot(pVM); PCFGMNODE pCfgAsyncCompletion = CFGMR3GetChild(CFGMR3GetChild(pCfgRoot, "PDM"), "AsyncCompletion"); int rc = pdmR3AsyncCompletionEpClassInit(pVM, &g_PDMAsyncCompletionEndpointClassFile, pCfgAsyncCompletion); LogFlowFunc((": pVM=%p rc=%Rrc\n", pVM, rc)); return rc; } /** * Terminates the async completion manager. * * @returns VBox status code * @param pVM Pointer to the VM. */ int pdmR3AsyncCompletionTerm(PVM pVM) { LogFlowFunc((": pVM=%p\n", pVM)); PUVM pUVM = pVM->pUVM; for (size_t i = 0; i < RT_ELEMENTS(pUVM->pdm.s.apAsyncCompletionEndpointClass); i++) if (pUVM->pdm.s.apAsyncCompletionEndpointClass[i]) pdmR3AsyncCompletionEpClassTerminate(pUVM->pdm.s.apAsyncCompletionEndpointClass[i]); return VINF_SUCCESS; } /** * Resume worker for the async completion manager. * * @returns nothing. * @param pVM Pointer to the VM. */ void pdmR3AsyncCompletionResume(PVM pVM) { LogFlowFunc((": pVM=%p\n", pVM)); PUVM pUVM = pVM->pUVM; /* Log the bandwidth groups and all assigned endpoints. */ for (size_t i = 0; i < RT_ELEMENTS(pUVM->pdm.s.apAsyncCompletionEndpointClass); i++) if (pUVM->pdm.s.apAsyncCompletionEndpointClass[i]) { PPDMASYNCCOMPLETIONEPCLASS pEpClass = pUVM->pdm.s.apAsyncCompletionEndpointClass[i]; PPDMACBWMGR pBwMgr = pEpClass->pBwMgrsHead; PPDMASYNCCOMPLETIONENDPOINT pEp; if (pBwMgr) LogRel(("AIOMgr: Bandwidth groups for class '%s'\n", i == PDMASYNCCOMPLETIONEPCLASSTYPE_FILE ? "File" : "<Unknown>")); while (pBwMgr) { LogRel(("AIOMgr: Id: %s\n", pBwMgr->pszId)); LogRel(("AIOMgr: Max: %u B/s\n", pBwMgr->cbTransferPerSecMax)); LogRel(("AIOMgr: Start: %u B/s\n", pBwMgr->cbTransferPerSecStart)); LogRel(("AIOMgr: Step: %u B/s\n", pBwMgr->cbTransferPerSecStep)); LogRel(("AIOMgr: Endpoints:\n")); pEp = pEpClass->pEndpointsHead; while (pEp) { if (pEp->pBwMgr == pBwMgr) LogRel(("AIOMgr: %s\n", pEp->pszUri)); pEp = pEp->pNext; } pBwMgr = pBwMgr->pNext; } /* Print all endpoints without assigned bandwidth groups. */ pEp = pEpClass->pEndpointsHead; if (pEp) LogRel(("AIOMgr: Endpoints without assigned bandwidth groups:\n")); while (pEp) { if (!pEp->pBwMgr) LogRel(("AIOMgr: %s\n", pEp->pszUri)); pEp = pEp->pNext; } } } /** * Tries to get a free task from the endpoint or class cache * allocating the task if it fails. * * @returns Pointer to a new and initialized task or NULL * @param pEndpoint The endpoint the task is for. * @param pvUser Opaque user data for the task. */ static PPDMASYNCCOMPLETIONTASK pdmR3AsyncCompletionGetTask(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, void *pvUser) { PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = pEndpoint->pEpClass; PPDMASYNCCOMPLETIONTASK pTask = (PPDMASYNCCOMPLETIONTASK)RTMemCacheAlloc(pEndpointClass->hMemCacheTasks); if (RT_LIKELY(pTask)) { /* Initialize common parts. */ pTask->pvUser = pvUser; pTask->pEndpoint = pEndpoint; /* Clear list pointers for safety. */ pTask->pPrev = NULL; pTask->pNext = NULL; pTask->tsNsStart = RTTimeNanoTS(); #ifdef VBOX_WITH_STATISTICS STAM_COUNTER_INC(&pEndpoint->StatIoOpsStarted); #endif } return pTask; } /** * Puts a task in one of the caches. * * @returns nothing. * @param pEndpoint The endpoint the task belongs to. * @param pTask The task to cache. */ static void pdmR3AsyncCompletionPutTask(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, PPDMASYNCCOMPLETIONTASK pTask) { PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = pEndpoint->pEpClass; uint64_t cNsRun = RTTimeNanoTS() - pTask->tsNsStart; if (RT_UNLIKELY(cNsRun >= RT_NS_10SEC)) LogRel(("AsyncCompletion: Task %#p completed after %llu seconds\n", pTask, cNsRun / RT_NS_1SEC)); #ifdef VBOX_WITH_STATISTICS PSTAMCOUNTER pStatCounter; if (cNsRun < RT_NS_1US) pStatCounter = &pEndpoint->StatTaskRunTimesNs[cNsRun / (RT_NS_1US / 10)]; else if (cNsRun < RT_NS_1MS) pStatCounter = &pEndpoint->StatTaskRunTimesUs[cNsRun / (RT_NS_1MS / 10)]; else if (cNsRun < RT_NS_1SEC) pStatCounter = &pEndpoint->StatTaskRunTimesMs[cNsRun / (RT_NS_1SEC / 10)]; else if (cNsRun < RT_NS_1SEC_64*100) pStatCounter = &pEndpoint->StatTaskRunTimesSec[cNsRun / (RT_NS_1SEC_64*100 / 10)]; else pStatCounter = &pEndpoint->StatTaskRunOver100Sec; STAM_COUNTER_INC(pStatCounter); STAM_COUNTER_INC(&pEndpoint->StatIoOpsCompleted); pEndpoint->cIoOpsCompleted++; uint64_t tsMsCur = RTTimeMilliTS(); uint64_t tsInterval = tsMsCur - pEndpoint->tsIntervalStartMs; if (tsInterval >= 1000) { pEndpoint->StatIoOpsPerSec.c = pEndpoint->cIoOpsCompleted / (tsInterval / 1000); pEndpoint->tsIntervalStartMs = tsMsCur; pEndpoint->cIoOpsCompleted = 0; } #endif /* VBOX_WITH_STATISTICS */ RTMemCacheFree(pEndpointClass->hMemCacheTasks, pTask); } static PPDMASYNCCOMPLETIONENDPOINT pdmR3AsyncCompletionFindEndpointWithUri(PPDMASYNCCOMPLETIONEPCLASS pEndpointClass, const char *pszUri) { PPDMASYNCCOMPLETIONENDPOINT pEndpoint = pEndpointClass->pEndpointsHead; while (pEndpoint) { if (!RTStrCmp(pEndpoint->pszUri, pszUri)) return pEndpoint; pEndpoint = pEndpoint->pNext; } return NULL; } VMMR3DECL(int) PDMR3AsyncCompletionEpCreateForFile(PPPDMASYNCCOMPLETIONENDPOINT ppEndpoint, const char *pszFilename, uint32_t fFlags, PPDMASYNCCOMPLETIONTEMPLATE pTemplate) { LogFlowFunc((": ppEndpoint=%p pszFilename=%p{%s} fFlags=%u pTemplate=%p\n", ppEndpoint, pszFilename, pszFilename, fFlags, pTemplate)); /* Sanity checks. */ AssertPtrReturn(ppEndpoint, VERR_INVALID_POINTER); AssertPtrReturn(pszFilename, VERR_INVALID_POINTER); AssertPtrReturn(pTemplate, VERR_INVALID_POINTER); /* Check that the flags are valid. */ AssertReturn(((~(PDMACEP_FILE_FLAGS_READ_ONLY | PDMACEP_FILE_FLAGS_DONT_LOCK | PDMACEP_FILE_FLAGS_HOST_CACHE_ENABLED) & fFlags) == 0), VERR_INVALID_PARAMETER); PVM pVM = pTemplate->pVM; PUVM pUVM = pVM->pUVM; PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = pUVM->pdm.s.apAsyncCompletionEndpointClass[PDMASYNCCOMPLETIONEPCLASSTYPE_FILE]; PPDMASYNCCOMPLETIONENDPOINT pEndpoint = NULL; AssertMsg(pEndpointClass, ("File endpoint class was not initialized\n")); /* Search for a already opened endpoint for this file. */ pEndpoint = pdmR3AsyncCompletionFindEndpointWithUri(pEndpointClass, pszFilename); if (pEndpoint) { /* Endpoint found. */ pEndpoint->cUsers++; *ppEndpoint = pEndpoint; return VINF_SUCCESS; } /* Create an endpoint. */ int rc = MMR3HeapAllocZEx(pVM, MM_TAG_PDM_ASYNC_COMPLETION, pEndpointClass->pEndpointOps->cbEndpoint, (void **)&pEndpoint); if (RT_SUCCESS(rc)) { /* Initialize common parts. */ pEndpoint->pNext = NULL; pEndpoint->pPrev = NULL; pEndpoint->pEpClass = pEndpointClass; pEndpoint->pTemplate = pTemplate; pEndpoint->pszUri = RTStrDup(pszFilename); pEndpoint->cUsers = 1; pEndpoint->pBwMgr = NULL; if ( pEndpoint->pszUri && RT_SUCCESS(rc)) { /* Call the initializer for the endpoint. */ rc = pEndpointClass->pEndpointOps->pfnEpInitialize(pEndpoint, pszFilename, fFlags); if (RT_SUCCESS(rc)) { /* Link it into the list of endpoints. */ rc = RTCritSectEnter(&pEndpointClass->CritSect); AssertMsg(RT_SUCCESS(rc), ("Failed to enter critical section rc=%Rrc\n", rc)); pEndpoint->pNext = pEndpointClass->pEndpointsHead; if (pEndpointClass->pEndpointsHead) pEndpointClass->pEndpointsHead->pPrev = pEndpoint; pEndpointClass->pEndpointsHead = pEndpoint; pEndpointClass->cEndpoints++; rc = RTCritSectLeave(&pEndpointClass->CritSect); AssertMsg(RT_SUCCESS(rc), ("Failed to enter critical section rc=%Rrc\n", rc)); /* Reference the template. */ ASMAtomicIncU32(&pTemplate->cUsed); #ifdef VBOX_WITH_STATISTICS /* Init the statistics part */ for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesNs); i++) { rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunTimesNs[i], STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES, "Nanosecond resolution runtime statistics", "/PDM/AsyncCompletion/File/%s/TaskRun1Ns-%u-%u", RTPathFilename(pEndpoint->pszUri), i*100, i*100+100-1); if (RT_FAILURE(rc)) break; } if (RT_SUCCESS(rc)) { for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesUs); i++) { rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunTimesUs[i], STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES, "Microsecond resolution runtime statistics", "/PDM/AsyncCompletion/File/%s/TaskRun2MicroSec-%u-%u", RTPathFilename(pEndpoint->pszUri), i*100, i*100+100-1); if (RT_FAILURE(rc)) break; } } if (RT_SUCCESS(rc)) { for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesMs); i++) { rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunTimesMs[i], STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES, "Milliseconds resolution runtime statistics", "/PDM/AsyncCompletion/File/%s/TaskRun3Ms-%u-%u", RTPathFilename(pEndpoint->pszUri), i*100, i*100+100-1); if (RT_FAILURE(rc)) break; } } if (RT_SUCCESS(rc)) { for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesMs); i++) { rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunTimesSec[i], STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES, "Second resolution runtime statistics", "/PDM/AsyncCompletion/File/%s/TaskRun4Sec-%u-%u", RTPathFilename(pEndpoint->pszUri), i*10, i*10+10-1); if (RT_FAILURE(rc)) break; } } if (RT_SUCCESS(rc)) { rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunOver100Sec, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES, "Tasks which ran more than 100sec", "/PDM/AsyncCompletion/File/%s/TaskRunSecGreater100Sec", RTPathFilename(pEndpoint->pszUri)); } if (RT_SUCCESS(rc)) { rc = STAMR3RegisterF(pVM, &pEndpoint->StatIoOpsPerSec, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Processed I/O operations per second", "/PDM/AsyncCompletion/File/%s/IoOpsPerSec", RTPathFilename(pEndpoint->pszUri)); } if (RT_SUCCESS(rc)) { rc = STAMR3RegisterF(pVM, &pEndpoint->StatIoOpsStarted, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Started I/O operations for this endpoint", "/PDM/AsyncCompletion/File/%s/IoOpsStarted", RTPathFilename(pEndpoint->pszUri)); } if (RT_SUCCESS(rc)) { rc = STAMR3RegisterF(pVM, &pEndpoint->StatIoOpsCompleted, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Completed I/O operations for this endpoint", "/PDM/AsyncCompletion/File/%s/IoOpsCompleted", RTPathFilename(pEndpoint->pszUri)); } /** @todo why bother maintaing rc when it's just ignored / logged and not returned? */ pEndpoint->tsIntervalStartMs = RTTimeMilliTS(); #endif *ppEndpoint = pEndpoint; LogFlowFunc((": Created endpoint for %s: rc=%Rrc\n", pszFilename, rc)); return VINF_SUCCESS; } RTStrFree(pEndpoint->pszUri); } MMR3HeapFree(pEndpoint); } LogFlowFunc((": Creation of endpoint for %s failed: rc=%Rrc\n", pszFilename, rc)); return rc; } VMMR3DECL(void) PDMR3AsyncCompletionEpClose(PPDMASYNCCOMPLETIONENDPOINT pEndpoint) { LogFlowFunc((": pEndpoint=%p\n", pEndpoint)); /* Sanity checks. */ AssertReturnVoid(VALID_PTR(pEndpoint)); pEndpoint->cUsers--; /* If the last user closed the endpoint we will free it. */ if (!pEndpoint->cUsers) { PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = pEndpoint->pEpClass; pEndpointClass->pEndpointOps->pfnEpClose(pEndpoint); /* Drop reference from the template. */ ASMAtomicDecU32(&pEndpoint->pTemplate->cUsed); /* Unlink the endpoint from the list. */ int rc = RTCritSectEnter(&pEndpointClass->CritSect); AssertMsg(RT_SUCCESS(rc), ("Failed to enter critical section rc=%Rrc\n", rc)); PPDMASYNCCOMPLETIONENDPOINT pEndpointNext = pEndpoint->pNext; PPDMASYNCCOMPLETIONENDPOINT pEndpointPrev = pEndpoint->pPrev; if (pEndpointPrev) pEndpointPrev->pNext = pEndpointNext; else pEndpointClass->pEndpointsHead = pEndpointNext; if (pEndpointNext) pEndpointNext->pPrev = pEndpointPrev; pEndpointClass->cEndpoints--; rc = RTCritSectLeave(&pEndpointClass->CritSect); AssertMsg(RT_SUCCESS(rc), ("Failed to enter critical section rc=%Rrc\n", rc)); #ifdef VBOX_WITH_STATISTICS /* Deregister the statistics part */ PVM pVM = pEndpointClass->pVM; for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesNs); i++) STAMR3Deregister(pVM, &pEndpoint->StatTaskRunTimesNs[i]); for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesUs); i++) STAMR3Deregister(pVM, &pEndpoint->StatTaskRunTimesUs[i]); for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesMs); i++) STAMR3Deregister(pVM, &pEndpoint->StatTaskRunTimesMs[i]); for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesMs); i++) STAMR3Deregister(pVM, &pEndpoint->StatTaskRunTimesSec[i]); STAMR3Deregister(pVM, &pEndpoint->StatTaskRunOver100Sec); STAMR3Deregister(pVM, &pEndpoint->StatIoOpsPerSec); STAMR3Deregister(pVM, &pEndpoint->StatIoOpsStarted); STAMR3Deregister(pVM, &pEndpoint->StatIoOpsCompleted); #endif RTStrFree(pEndpoint->pszUri); MMR3HeapFree(pEndpoint); } } VMMR3DECL(int) PDMR3AsyncCompletionEpRead(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, RTFOFF off, PCRTSGSEG paSegments, unsigned cSegments, size_t cbRead, void *pvUser, PPPDMASYNCCOMPLETIONTASK ppTask) { AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER); AssertPtrReturn(paSegments, VERR_INVALID_POINTER); AssertPtrReturn(ppTask, VERR_INVALID_POINTER); AssertReturn(cSegments > 0, VERR_INVALID_PARAMETER); AssertReturn(cbRead > 0, VERR_INVALID_PARAMETER); AssertReturn(off >= 0, VERR_INVALID_PARAMETER); PPDMASYNCCOMPLETIONTASK pTask; pTask = pdmR3AsyncCompletionGetTask(pEndpoint, pvUser); if (!pTask) return VERR_NO_MEMORY; int rc = pEndpoint->pEpClass->pEndpointOps->pfnEpRead(pTask, pEndpoint, off, paSegments, cSegments, cbRead); if (RT_SUCCESS(rc)) *ppTask = pTask; else pdmR3AsyncCompletionPutTask(pEndpoint, pTask); return rc; } VMMR3DECL(int) PDMR3AsyncCompletionEpWrite(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, RTFOFF off, PCRTSGSEG paSegments, unsigned cSegments, size_t cbWrite, void *pvUser, PPPDMASYNCCOMPLETIONTASK ppTask) { AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER); AssertPtrReturn(paSegments, VERR_INVALID_POINTER); AssertPtrReturn(ppTask, VERR_INVALID_POINTER); AssertReturn(cSegments > 0, VERR_INVALID_PARAMETER); AssertReturn(cbWrite > 0, VERR_INVALID_PARAMETER); AssertReturn(off >= 0, VERR_INVALID_PARAMETER); PPDMASYNCCOMPLETIONTASK pTask; pTask = pdmR3AsyncCompletionGetTask(pEndpoint, pvUser); if (!pTask) return VERR_NO_MEMORY; int rc = pEndpoint->pEpClass->pEndpointOps->pfnEpWrite(pTask, pEndpoint, off, paSegments, cSegments, cbWrite); if (RT_SUCCESS(rc)) { *ppTask = pTask; } else pdmR3AsyncCompletionPutTask(pEndpoint, pTask); return rc; } VMMR3DECL(int) PDMR3AsyncCompletionEpFlush(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, void *pvUser, PPPDMASYNCCOMPLETIONTASK ppTask) { AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER); AssertPtrReturn(ppTask, VERR_INVALID_POINTER); PPDMASYNCCOMPLETIONTASK pTask; pTask = pdmR3AsyncCompletionGetTask(pEndpoint, pvUser); if (!pTask) return VERR_NO_MEMORY; int rc = pEndpoint->pEpClass->pEndpointOps->pfnEpFlush(pTask, pEndpoint); if (RT_SUCCESS(rc)) *ppTask = pTask; else pdmR3AsyncCompletionPutTask(pEndpoint, pTask); return rc; } VMMR3DECL(int) PDMR3AsyncCompletionEpGetSize(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, uint64_t *pcbSize) { AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER); AssertPtrReturn(pcbSize, VERR_INVALID_POINTER); if (pEndpoint->pEpClass->pEndpointOps->pfnEpGetSize) return pEndpoint->pEpClass->pEndpointOps->pfnEpGetSize(pEndpoint, pcbSize); return VERR_NOT_SUPPORTED; } VMMR3DECL(int) PDMR3AsyncCompletionEpSetSize(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, uint64_t cbSize) { AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER); if (pEndpoint->pEpClass->pEndpointOps->pfnEpSetSize) return pEndpoint->pEpClass->pEndpointOps->pfnEpSetSize(pEndpoint, cbSize); return VERR_NOT_SUPPORTED; } VMMR3DECL(int) PDMR3AsyncCompletionEpSetBwMgr(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, const char *pcszBwMgr) { AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER); PPDMACBWMGR pBwMgrOld = NULL; PPDMACBWMGR pBwMgrNew = NULL; int rc = VINF_SUCCESS; if (pcszBwMgr) { pBwMgrNew = pdmacBwMgrFindById(pEndpoint->pEpClass, pcszBwMgr); if (pBwMgrNew) pdmacBwMgrRef(pBwMgrNew); else rc = VERR_NOT_FOUND; } if (RT_SUCCESS(rc)) { pBwMgrOld = ASMAtomicXchgPtrT(&pEndpoint->pBwMgr, pBwMgrNew, PPDMACBWMGR); if (pBwMgrOld) pdmacBwMgrUnref(pBwMgrOld); } return rc; } VMMR3DECL(int) PDMR3AsyncCompletionTaskCancel(PPDMASYNCCOMPLETIONTASK pTask) { NOREF(pTask); return VERR_NOT_IMPLEMENTED; } VMMR3DECL(int) PDMR3AsyncCompletionBwMgrSetMaxForFile(PVM pVM, const char *pcszBwMgr, uint32_t cbMaxNew) { AssertPtrReturn(pVM, VERR_INVALID_POINTER); AssertPtrReturn(pcszBwMgr, VERR_INVALID_POINTER); int rc = VINF_SUCCESS; PPDMASYNCCOMPLETIONEPCLASS pEpClass = pVM->pUVM->pdm.s.apAsyncCompletionEndpointClass[PDMASYNCCOMPLETIONEPCLASSTYPE_FILE]; PPDMACBWMGR pBwMgr = pdmacBwMgrFindById(pEpClass, pcszBwMgr); if (pBwMgr) { /* * Set the new value for the start and max value to let the manager pick up * the new limit immediately. */ ASMAtomicWriteU32(&pBwMgr->cbTransferPerSecMax, cbMaxNew); ASMAtomicWriteU32(&pBwMgr->cbTransferPerSecStart, cbMaxNew); } else rc = VERR_NOT_FOUND; return rc; }
VirtualMonitor/VirtualMonitor
src/VBox/VMM/VMMR3/PDMAsyncCompletion.cpp
C++
gpl-2.0
54,355
<div class="col-sm-9 col-sm-offset-3 content-right-column"> <div class="row"> <div class="col-sm-10"> <!--<h2 class="title">Chronology</h2>--> <table> <tbody> <tr> <td class="c2" align="right" valign="top" width="100"> <b>1757</b> </td> <td>Born in London (28 November) to James Blake, a hosier, and his wife Catherine Wright Armitage Blake. Lives with family at 28 Broad Street.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1767</b> </td> <td>Enrolled in Henry Pars's drawing school.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1772</b> </td> <td>Apprenticed to James Basire, engraver to the Society of Antiquaries and the Royal Society. Begins to live with Basire at 31 Great Queen Street, London.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1779</b> </td> <td>Apprenticeship ends.<br> Becomes journeyman copy engraver.<br> Admitted as student to Royal Academy of Art's Schools of Design.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1780</b> </td> <td>Gordon Riots in London (June), in which Blake may have participated.<br> Arrested on suspicion of spying during sketching trip on the River Medway.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1782</b> </td> <td>Marries Catherine Boucher (18 August). Moves to 23 Green Street, London.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1783</b> </td> <td>Publishes <i>Poetical Sketches</i>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1784</b> </td> <td>Moves to 27 Broad Street, London. Sets up printing and publishing partnership with James Parker at 27 Broad Street.<br> Begins writing <a target="_blank" href="http://www.blakearchive.org/work/bb74"><i>An Island in the Moon</i></a> (c. 1784-85).</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1785</b> </td> <td>Moves to 28 Poland Street, London.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1787</b> </td> <td>Younger brother Robert dies (February).</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>c. 1788</b> </td> <td>Invents relief etching.<br> Publishes <a target="_blank" href="http://www.blakearchive.org/work/aro"><i>All Religions are One</i></a> and <a target="_blank" href="http://www.blakearchive.org/work/nnr"><i>There is No Natural Religion</i></a>, first illuminated books.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1789</b> </td> <td>Publishes <a target="_blank" href="http://www.blakearchive.org/work/s-inn"><i>Songs of Innocence</i></a> and begins <a target="_blank" href="http://www.blakearchive.org/work/thel"><i>The Book of Thel</i></a> (1789-90).<br> Writes <a target="_blank" href="http://www.blakearchive.org/work/bb203"><i>Tiriel</i></a> (c. 1789).<br> Attends organizational meeting of the New Jerusalem (Swedenborgian) Church (April).</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1790</b> </td> <td>Prints <a target="_blank" href="http://www.blakearchive.org/work/mhh"><i>The Marriage of Heaven and Hell</i></a>.<br> Moves to 13 Hercules Buildings, Lambeth.<br></td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1791</b> </td> <td>Writes at least one part of several proposed parts of <i>The French Revolution</i>.<br> Composes and engraves six original designs for Mary Wollstonecraft's <a target="_blank" href="http://www.blakearchive.org/work/bb514"><i>Original Stories from Real Life</i></a>.<br> Begins to engrave seventeen illustrations for John Gabriel Stedman’s <i>Narrative, of a Five Years’ Expedition, Against the Revolted Negroes of Surinam</i>, published in 1796. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1793</b> </td> <td>Publishes <a target="_blank" href="http://www.blakearchive.org/work/vda"><i>Visions of the Daughters of Albion</i></a>, <a target="_blank" href="http://www.blakearchive.org/work/america"><i>America a Prophecy</i></a>, and <a target="_blank" href="http://www.blakearchive.org/work/gates-child"><i>For Children: The Gates of Paradise</i></a>.<br> Engraves <a target="_blank" href="http://www.blakearchive.org/copy/bb85.a?descId=bb85.a.spb.01"><i>Albion rose</i></a>.<br> Prints the Prospectus advertising engravings and illuminated books. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1794</b> </td> <td>Publishes <a target="_blank" href="http://www.blakearchive.org/work/europe"><i>Europe: a Prophecy</i></a>, <a target="_blank" href="http://www.blakearchive.org/work/songsie"><i>Songs of Experience</i></a>, and <a target="_blank" href="http://www.blakearchive.org/work/urizen"><i>The [First] Book of Urizen</i></a>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1795</b> </td> <td>Publishes <a target="_blank" href="http://www.blakearchive.org/work/ahania"><i>The Book of Ahania</i></a>, <a target="_blank" href="http://www.blakearchive.org/work/b-los"><i>The Book of Los</i></a>, and <a target="_blank" href="http://www.blakearchive.org/work/s-los"><i>The Song of Los</i></a>.<br> Produces <a target="_blank" href="http://www.blakearchive.org/work/cpd">twelve large color-printed drawings</a>.<br> Begins work on <a target="_blank" href="http://www.blakearchive.org/work/but330">537 water color illustrations to Edward Young's <i>Night Thoughts</i></a>.<br> Engraves <a target="_blank" href="http://www.blakearchive.org/copy/bb85.a?descId=bb85.a.spb.01] "><i>Albion rose</i></a>. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>c. 1796</b> </td> <td>Begins writing <a target="_blank" href="http://www.blakearchive.org/work/bb209"><i>Vala, or The Four Zoas</i></a>.<br> Produces the <a target="_blank" href="http://www.blakearchive.org/work/bb136"><i>Small Book of Designs</i></a> and the <a target="_blank" href="http://www.blakearchive.org/work/bb85"><i>Large Book of Designs</i></a>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1797</b> </td> <td>Begins work on <a target="_blank" href="http://www.blakearchive.org/work/but335">116 water color illustrations to the poems of Thomas Gray</a> for John Flaxman.<br> Young's <i>Night Thoughts</i> published with <a target="_blank" href="http://www.blakearchive.org/work/but515">43 plates engraved by Blake</a> after his own designs.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>c. 1799</b> </td> <td>Begins <a target="_blank" href="http://www.blakearchive.org/work/biblicaltemperas">fifty biblical temperas</a> for Thomas Butts. </tr> <tr> <td class="c2" align="right" valign="top"><b>1800</b> </td> <td>Moves to Felpham, Sussex, to work for patron William Hayley.<br> Begins <a target="_blank" href="http://www.blakearchive.org/work/biblicalwc">biblical water colors</a> for Thomas Butts.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1801</b> </td> <td>Produces eight water color illustrations of Milton's <a target="_blank" href="http://www.blakearchive.org/work/but527"><i>Comus</i></a> for the Rev. Joseph Thomas. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1803</b> </td> <td>Indicted on charges of sedition (October) as a result of a quarrel with a soldier, John Scolfield, whom he had evicted from his garden (August).<br> Returns to London and moves to 17 South Molton Street.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1804</b> </td> <td>Acquitted of sedition charges (January).<br> Begins work on <a target="_blank" href="http://www.blakearchive.org/work/milton"><i>Milton a Poem</i></a> and <a target="_blank" href="http://www.blakearchive.org/work/jerusalem"><i>Jerusalem The Emanation of the Giant Albion</i></a>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1805</b> </td> <td>Begins illustrations for Blair's <a target="_blank" href="http://www.blakearchive.org/work/bb435"><i>The Grave</i></a>, to be published by Robert Cromek.<br> Produces <a target="_blank" href="http://www.blakearchive.org/work/but551">nineteen water color illustrations of the <i>Book of Job</i></a> for Thomas Butts (c. 1805-6).</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1807</b> </td> <td>Produces <a target="_blank" href="http://www.blakearchive.org/work/but529">twelve water color illustrations of Milton's <i>Paradise Lost</i></a> for the Rev. Joseph Thomas.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>c. 1807</b> </td> <td><a target="_blank" href="http://www.blakearchive.org/work/bb126">Produces the Pickering Manuscript</a>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1808</b> </td> <td>Produces <a target="_blank" href="http://www.blakearchive.org/work/but536">twelve water color illustrations of Milton's <i>Paradise Lost</i></a> for Thomas Butts.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>c. 1808</b> </td> <td>Annotates the first eight of Reynolds <i>Discourses</i>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1809</b> </td> <td>Exhibits sixteen paintings at 28 Broad Street, accompanied by a <a target="_blank" href="http://www.blakearchive.org/work/bb32"><i>Descriptive Catalogue</i></a> defending his theory and practice.<br> Produces <a target="_blank" href="http://www.blakearchive.org/work/but538">six water color illustrations of Milton’s <i>On the Morning of Christ’s Nativity</i></a> for the Rev. Joseph Thomas. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>c. 1810-11</b> </td> <td>Drafts the <i>Public Address</i>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>c. 1811</b> </td> <td>Prints first copies of <a target="_blank" href="http://www.blakearchive.org/work/milton"><i>Milton a Poem</i></a>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1815</b> </td> <td>Produces <a target="_blank" href="http://www.blakearchive.org/work/but528">eight water color illustrations of Milton's <i>Comus</i></a> for Thomas Butts.<br> Produces <a target="_blank" href="http://www.blakearchive.org/work/but538">six water color illustrations of Milton’s <i>On the Morning of Christ’s Nativity</i></a> for Thomas Butts. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>c. 1816-1820</b> </td> <td>Produces <a target="_blank" href="http://www.blakearchive.org/work/but543">twelve water color illustrations of Milton’s <i>L’Allegro</i> and <i>Il Penseroso</i></a> for Thomas Butts.<br> Produces <a target="_blank" href="http://www.blakearchive.org/work/but544">twelve water color illustrations of Milton’s <i>Paradise Regained</i></a>, possibly for Thomas Butts but sold to John Linnell. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1818</b> </td> <td>Meets John Linnell.<br> Begins sketching "Visionary Heads" for John Varley.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>c. 1820</b> </td> <td>Publishes <a target="_blank" href="http://www.blakearchive.org/work/gates-sexes"><i>For the Sexes: The Gates of Paradise</i></a>.<br> Prints first copies of <a target="_blank" href="http://www.blakearchive.org/work/jerusalem"><i>Jerusalem The Emanation of the Giant Albion</i></a>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1821</b> </td> <td><a target="_blank" href="http://www.blakearchive.org/work/but504">Virgil's <i>Pastorals</i></a>, edited by Robert John Thornton, published with wood engravings by Blake.<br> Produces <a target="_blank" href="http://www.blakearchive.org/work/but537">twenty-one water color illustrations of the <i>Book of Job</i></a> for John Linnell.<br> Moves to 3 Fountain Court, London. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1822</b> </td> <td>Publishes <a target="_blank" href="http://www.blakearchive.org/work/abel"><i>The Ghost of Abel</i></a> and <a target="_blank" href="http://www.blakearchive.org/work/homer"><i>On Homers Poetry [and] On Virgil</i></a> (c. 1822).<br> Produces <a target="_blank" href="http://www.blakearchive.org/work/but537">three water color illustrations of Milton's <i>Paradise Lost</i></a> for John Linnell. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1824</b> </td> <td>Begins illustrations to Dante's <a target="_blank" href="http://www.blakearchive.org/work/but812"><i>Divine Comedy</i></a> and Bunyan's <i>Pilgrim's Progress</i>.</td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1826</b> </td> <td>Publishes <a target="_blank" href="http://www.blakearchive.org/work/bb421">a title page and twenty-one engraved <i>Illustrations of the Book of Job</i></a>.<br> Produces <a target="_blank" href="http://www.blakearchive.org/work/laocoon"><i>Laoco&ouml;n</i></a> (c. 1826).<br> Begins <a target="_blank" href="http://www.blakearchive.org/work/but828">Genesis Manuscript</a>.<br> Begins to engrave <a target="_blank" href="http://www.blakearchive.org/work/but812">seven illustrations from the “Inferno” of his <i>Divine Comedy</i></a> designs. </td> </tr> <tr> <td class="c2" align="right" valign="top"><b>1827</b> </td> <td>Dies 12 August in his rooms at 3 Fountain Court.</td> </tr> </tbody> </table> </div> </div> </div>
blakearchive/archive
blakearchive/static/html/chronology.html
HTML
gpl-2.0
14,718
namespace :project_state do resources :summary, only: [:index] resources :users, only: [:show] resource :user, only: [:show] resources :state, only: [:show] resources :project_state_reports, only: [:index, :show, :update] resources :bank_holidays, only: [:index] get 'configure', action: :edit post 'configure', action: :edit end
crukci-bioinformatics/process_tracker_plugin
config/routes.rb
Ruby
gpl-2.0
347
/*============================================================================*/ /*! \file reader_xtc.hpp * \author Tiago LOBATO GIMENES (tlgimenes@gmail.com) * \date 2015-03-30 18:49 * * \brief .xtc file reader * * This file contains the implementation of a class for reading .xtc files * with a trajectory list * */ /*============================================================================*/ /////////////////////////////////////////////////////////////////////////////// #ifndef READER_XTC_HPP #define READER_XTC_HPP /////////////////////////////////////////////////////////////////////////////// #include <vector> #include <string> #include <sstream> #include <fstream> #include <boost/filesystem.hpp> #include "error.hpp" #include "xdrfile/xdrfile.h" #include "xdrfile/xdrfile_xtc.h" /////////////////////////////////////////////////////////////////////////////// /*! \brief Maximun file name lenght */ #define MAX_FILE_NAME_LENGTH 128 /////////////////////////////////////////////////////////////////////////////// namespace bfs = boost::filesystem; /////////////////////////////////////////////////////////////////////////////// /*! \brief Class for reading trajlist and .xtc files */ class reader_xtc { public: /*! \brief Reads all trajectories specified in the trajlist file. * * A trajlist file can contains the relative paths to the .xtc files or name of * files that contains relative paths to the .xtc files. The absolute * path is always done in the following way : path = home/trajlist * */ static inline void read_list(const std::string& home, const std::string& trajlist, std::vector<float>& data, int& n_atoms); protected: /*! \brief Reads a trajectory file. * * It can be *.xtc or any other file defined in _supported_ext vector * and appends the new trajectories in the data vector * */ static inline void read_trajfile(const std::string& trajfile, std::vector<float>& data, int& n_atoms, int& n_samples); /*! \brief finds *.xtc files from trajlist * * Given a trajlist path, this function will recursively try to find * the (*.xtc) files and insert it on the framefile_list. The complete * path for the file must be given by home/trajlist * */ static inline void get_framefile_list(std::vector<std::string>& framefile_list, const std::string& home, const std::string& trajlist); /*! \brief Checks if the extension of file "file_name" is supported or not * by this class * * \return true if file extension is supported, false otherwise * */ static inline bool is_ext_supported(const std::string& file_name); private: static std::vector<std::string> _supported_ext; /*! list of supported extensions */ }; /////////////////////////////////////////////////////////////////////////////// std::vector<std::string> reader_xtc::_supported_ext = {".xtc"}; /////////////////////////////////////////////////////////////////////////////// inline void reader_xtc::read_list(const std::string& home, const std::string& trajlist_path, std::vector<float>& data, int& n_atoms) { std::vector<std::string> trajlist; int n_samples = 0; // Checks if file exists if(!bfs::is_regular_file(home+trajlist_path)) FATAL_ERROR(home+trajlist_path+": File not found :("); reader_xtc::get_framefile_list(trajlist, home, trajlist_path); data.clear(); // clears data // Number of atoms in the first file is number of atoms in all the files if(trajlist.size() <= 0) FATAL_ERROR("File list empty :("); read_xtc_natoms((char*)trajlist[0].c_str(), &n_atoms); // Foreach file in trajlist for(std::string trajfile : trajlist) { DBG_MESSAGE("Reading file: " + trajfile + " ... "); // Debug Message reader_xtc::read_trajfile(trajfile, data, n_atoms, n_samples); DBG_MESSAGE(std::to_string(n_samples) + " frames found\n"); // Debug Message } } /////////////////////////////////////////////////////////////////////////////// inline bool reader_xtc::is_ext_supported(const std::string& str) { for(std::string l : reader_xtc::_supported_ext) { if(!str.compare(str.size()-4, 4, l)) return true; } return false; } /////////////////////////////////////////////////////////////////////////////// inline void reader_xtc::get_framefile_list(std::vector<std::string>& trajlist, const std::string& home, const std::string& trajlinks_path) { std::stringstream trajlinks; std::string sub_traj; // Recursion base, when file is a complete path if(reader_xtc::is_ext_supported(trajlinks_path)) trajlist.push_back(home + trajlinks_path); // when file is a link to a file else { // Gets contents of the file trajlinks << std::ifstream(home + trajlinks_path, std::ios_base::in).rdbuf(); trajlinks >> sub_traj; while(trajlinks && !trajlinks.eof() && sub_traj.size() > 0) // Foreach link in the file { if(bfs::is_regular_file(home+sub_traj)) // if file is openable and is a link to other files reader_xtc::get_framefile_list(trajlist, home, sub_traj); else if(bfs::is_regular_file(home+sub_traj+".xtc")) // if file without xtc extension trajlist.push_back(home+sub_traj+".xtc"); else // default file name trajlist.push_back(home+sub_traj+"/frame0.xtc"); trajlinks >> sub_traj; // gets new file/link } } } /////////////////////////////////////////////////////////////////////////////// inline void reader_xtc::read_trajfile(const std::string& trajfile, std::vector<float> &data, int& n_atoms, int& n_samples) { int step; float time, prec; matrix box; rvec* tmp = new rvec[n_atoms]; n_samples = 0; // Opens trajfile XDRFILE *xdr_file = xdrfile_open(trajfile.c_str(), "r"); // opens file // Reads each frame while (exdrOK == read_xtc(xdr_file, n_atoms, &step, &time, box, tmp, &prec)) { for(int i=0; i < n_atoms; i++) { data.push_back(tmp[i][0]); data.push_back(tmp[i][1]); data.push_back(tmp[i][2]); } n_samples++; } // Closes trajfile xdrfile_close(xdr_file); // Deletes allocated memory delete []tmp; } /////////////////////////////////////////////////////////////////////////////// #endif /* !READER_XTC_HPP */ ///////////////////////////////////////////////////////////////////////////////
tlgimenes/CUDADClusterer
utils/reader_xtc.hpp
C++
gpl-2.0
6,763
/* * PROJECT: ReactOS Kernel * LICENSE: GPL - See COPYING in the top level directory * FILE: ntoskrnl/ob/oblink.c * PURPOSE: Implements symbolic links * PROGRAMMERS: Alex Ionescu (alex@relsoft.net) * David Welch (welch@mcmail.com) */ /* INCLUDES *****************************************************************/ #include <ntoskrnl.h> #define NDEBUG #include <debug.h> /* GLOBALS ******************************************************************/ POBJECT_TYPE ObSymbolicLinkType = NULL; /* PRIVATE FUNCTIONS *********************************************************/ VOID NTAPI ObpDeleteSymbolicLinkName(IN POBJECT_SYMBOLIC_LINK SymbolicLink) { POBJECT_HEADER ObjectHeader; POBJECT_HEADER_NAME_INFO ObjectNameInfo; /* FIXME: Need to support Device maps */ /* Get header data */ ObjectHeader = OBJECT_TO_OBJECT_HEADER(SymbolicLink); ObjectNameInfo = ObpReferenceNameInfo(ObjectHeader); /* Check if we are not actually in a directory with a device map */ if (!(ObjectNameInfo) || !(ObjectNameInfo->Directory) /*|| !(ObjectNameInfo->Directory->DeviceMap)*/) { ObpDereferenceNameInfo(ObjectNameInfo); return; } /* Check if it's a DOS drive letter, and remove the entry from drive map if needed */ if (SymbolicLink->DosDeviceDriveIndex != 0 && ObjectNameInfo->Name.Length == 2 * sizeof(WCHAR) && ObjectNameInfo->Name.Buffer[1] == L':' && ( (ObjectNameInfo->Name.Buffer[0] >= L'A' && ObjectNameInfo->Name.Buffer[0] <= L'Z') || (ObjectNameInfo->Name.Buffer[0] >= L'a' && ObjectNameInfo->Name.Buffer[0] <= L'z') )) { /* Remove the drive entry */ KeAcquireGuardedMutex(&ObpDeviceMapLock); ObSystemDeviceMap->DriveType[SymbolicLink->DosDeviceDriveIndex-1] = DOSDEVICE_DRIVE_UNKNOWN; ObSystemDeviceMap->DriveMap &= ~(1 << (SymbolicLink->DosDeviceDriveIndex-1)); KeReleaseGuardedMutex(&ObpDeviceMapLock); /* Reset the drive index, valid drive index starts from 1 */ SymbolicLink->DosDeviceDriveIndex = 0; } ObpDereferenceNameInfo(ObjectNameInfo); } NTSTATUS NTAPI ObpParseSymbolicLinkToIoDeviceObject(IN POBJECT_DIRECTORY SymbolicLinkDirectory, IN OUT POBJECT_DIRECTORY *Directory, IN OUT PUNICODE_STRING TargetPath, IN OUT POBP_LOOKUP_CONTEXT Context, OUT PVOID *Object) { UNICODE_STRING Name; BOOLEAN ManualUnlock; if (! TargetPath || ! Object || ! Context || ! Directory || ! SymbolicLinkDirectory) { return STATUS_INVALID_PARAMETER; } /* FIXME: Need to support Device maps */ /* Try walking the target path and open each part of the path */ while (TargetPath->Length) { /* Strip '\' if present at the beginning of the target path */ if (TargetPath->Length >= sizeof(OBJ_NAME_PATH_SEPARATOR)&& TargetPath->Buffer[0] == OBJ_NAME_PATH_SEPARATOR) { TargetPath->Buffer++; TargetPath->Length -= sizeof(OBJ_NAME_PATH_SEPARATOR); } /* Remember the current component of the target path */ Name = *TargetPath; /* Move forward to the next component of the target path */ while (TargetPath->Length >= sizeof(OBJ_NAME_PATH_SEPARATOR)) { if (TargetPath->Buffer[0] != OBJ_NAME_PATH_SEPARATOR) { TargetPath->Buffer++; TargetPath->Length -= sizeof(OBJ_NAME_PATH_SEPARATOR); } else break; } Name.Length -= TargetPath->Length; /* Finished processing the entire path, stop */ if (! Name.Length) break; /* * Make sure a deadlock does not occur as an exclusive lock on a pushlock * would have already taken one in ObpLookupObjectName() on the parent * directory where the symlink is being created [ObInsertObject()]. * Prevent recursive locking by faking lock state in the lookup context * when the current directory is same as the parent directory where * the symlink is being created. If the lock state is not faked, * ObpLookupEntryDirectory() will try to get a recursive lock on the * pushlock and hang. For e.g. this happens when a substed drive is pointed to * another substed drive. */ if (*Directory == SymbolicLinkDirectory && ! Context->DirectoryLocked) { /* Fake lock state so that ObpLookupEntryDirectory() doesn't attempt a lock */ ManualUnlock = TRUE; Context->DirectoryLocked = TRUE; } else ManualUnlock = FALSE; *Object = ObpLookupEntryDirectory(*Directory, &Name, 0, FALSE, Context); /* Locking was faked, undo it now */ if (*Directory == SymbolicLinkDirectory && ManualUnlock) Context->DirectoryLocked = FALSE; /* Lookup failed, stop */ if (! *Object) break; if (OBJECT_TO_OBJECT_HEADER(*Object)->Type == ObDirectoryType) { /* Make this current directory, and continue search */ *Directory = (POBJECT_DIRECTORY)*Object; } else if (OBJECT_TO_OBJECT_HEADER(*Object)->Type == ObSymbolicLinkType && (((POBJECT_SYMBOLIC_LINK)*Object)->DosDeviceDriveIndex == 0)) { /* Symlink points to another initialized symlink, ask caller to reparse */ *Directory = ObpRootDirectoryObject; TargetPath = &((POBJECT_SYMBOLIC_LINK)*Object)->LinkTarget; return STATUS_REPARSE_OBJECT; } else { /* Neither directory or symlink, stop */ break; } } /* Return a valid object, only if object type is IoDeviceObject */ if (*Object && OBJECT_TO_OBJECT_HEADER(*Object)->Type != IoDeviceObjectType) { *Object = NULL; } return STATUS_SUCCESS; } VOID NTAPI ObpCreateSymbolicLinkName(IN POBJECT_SYMBOLIC_LINK SymbolicLink) { POBJECT_HEADER ObjectHeader; POBJECT_HEADER_NAME_INFO ObjectNameInfo; PVOID Object = NULL; POBJECT_DIRECTORY Directory; UNICODE_STRING TargetPath; NTSTATUS Status; ULONG DriveType = DOSDEVICE_DRIVE_CALCULATE; ULONG ReparseCnt; const ULONG MaxReparseAttempts = 20; OBP_LOOKUP_CONTEXT Context; /* FIXME: Need to support Device maps */ /* Get header data */ ObjectHeader = OBJECT_TO_OBJECT_HEADER(SymbolicLink); ObjectNameInfo = ObpReferenceNameInfo(ObjectHeader); /* Check if we are not actually in a directory with a device map */ if (!(ObjectNameInfo) || !(ObjectNameInfo->Directory) /*|| !(ObjectNameInfo->Directory->DeviceMap)*/) { ObpDereferenceNameInfo(ObjectNameInfo); return; } /* Check if it's a DOS drive letter, and set the drive index accordingly */ if (ObjectNameInfo->Name.Length == 2 * sizeof(WCHAR) && ObjectNameInfo->Name.Buffer[1] == L':' && ( (ObjectNameInfo->Name.Buffer[0] >= L'A' && ObjectNameInfo->Name.Buffer[0] <= L'Z') || (ObjectNameInfo->Name.Buffer[0] >= L'a' && ObjectNameInfo->Name.Buffer[0] <= L'z') )) { SymbolicLink->DosDeviceDriveIndex = RtlUpcaseUnicodeChar(ObjectNameInfo->Name.Buffer[0]) - L'A'; /* The Drive index start from 1 */ SymbolicLink->DosDeviceDriveIndex++; /* Initialize lookup context */ ObpInitializeLookupContext(&Context); /* Start the search from the root */ Directory = ObpRootDirectoryObject; TargetPath = SymbolicLink->LinkTarget; /* * Locate the IoDeviceObject if any this symbolic link points to. * To prevent endless reparsing, setting an upper limit on the * number of reparses. */ Status = STATUS_REPARSE_OBJECT; ReparseCnt = 0; while (Status == STATUS_REPARSE_OBJECT && ReparseCnt < MaxReparseAttempts) { Status = ObpParseSymbolicLinkToIoDeviceObject(ObjectNameInfo->Directory, &Directory, &TargetPath, &Context, &Object); if (Status == STATUS_REPARSE_OBJECT) ReparseCnt++; } /* Cleanup lookup context */ ObpReleaseLookupContext(&Context); /* Error, or max resparse attemtps exceeded */ if (! NT_SUCCESS(Status) || ReparseCnt >= MaxReparseAttempts) { /* Cleanup */ ObpDereferenceNameInfo(ObjectNameInfo); return; } if (Object) { /* Calculate the drive type */ switch(((PDEVICE_OBJECT)Object)->DeviceType) { case FILE_DEVICE_VIRTUAL_DISK: DriveType = DOSDEVICE_DRIVE_RAMDISK; break; case FILE_DEVICE_CD_ROM: case FILE_DEVICE_CD_ROM_FILE_SYSTEM: DriveType = DOSDEVICE_DRIVE_CDROM; break; case FILE_DEVICE_DISK: case FILE_DEVICE_DISK_FILE_SYSTEM: case FILE_DEVICE_FILE_SYSTEM: if (((PDEVICE_OBJECT)Object)->Characteristics & FILE_REMOVABLE_MEDIA) DriveType = DOSDEVICE_DRIVE_REMOVABLE; else DriveType = DOSDEVICE_DRIVE_FIXED; break; case FILE_DEVICE_NETWORK: case FILE_DEVICE_NETWORK_FILE_SYSTEM: DriveType = DOSDEVICE_DRIVE_REMOTE; break; default: DPRINT1("Device Type %lu for %wZ is not known or unhandled\n", ((PDEVICE_OBJECT)Object)->DeviceType, &SymbolicLink->LinkTarget); DriveType = DOSDEVICE_DRIVE_UNKNOWN; } } /* Add a new drive entry */ KeAcquireGuardedMutex(&ObpDeviceMapLock); ObSystemDeviceMap->DriveType[SymbolicLink->DosDeviceDriveIndex-1] = (UCHAR)DriveType; ObSystemDeviceMap->DriveMap |= 1 << (SymbolicLink->DosDeviceDriveIndex-1); KeReleaseGuardedMutex(&ObpDeviceMapLock); } /* Cleanup */ ObpDereferenceNameInfo(ObjectNameInfo); } /*++ * @name ObpDeleteSymbolicLink * * The ObpDeleteSymbolicLink routine <FILLMEIN> * * @param ObjectBody * <FILLMEIN> * * @return None. * * @remarks None. * *--*/ VOID NTAPI ObpDeleteSymbolicLink(PVOID ObjectBody) { POBJECT_SYMBOLIC_LINK SymlinkObject = (POBJECT_SYMBOLIC_LINK)ObjectBody; /* Make sure that the symbolic link has a name */ if (SymlinkObject->LinkTarget.Buffer) { /* Free the name */ ExFreePool(SymlinkObject->LinkTarget.Buffer); SymlinkObject->LinkTarget.Buffer = NULL; } } /*++ * @name ObpParseSymbolicLink * * The ObpParseSymbolicLink routine <FILLMEIN> * * @param Object * <FILLMEIN> * * @param NextObject * <FILLMEIN> * * @param FullPath * <FILLMEIN> * * @param RemainingPath * <FILLMEIN> * * @param Attributes * <FILLMEIN> * * @return STATUS_SUCCESS or appropriate error value. * * @remarks None. * *--*/ NTSTATUS NTAPI ObpParseSymbolicLink(IN PVOID ParsedObject, IN PVOID ObjectType, IN OUT PACCESS_STATE AccessState, IN KPROCESSOR_MODE AccessMode, IN ULONG Attributes, IN OUT PUNICODE_STRING FullPath, IN OUT PUNICODE_STRING RemainingName, IN OUT PVOID Context OPTIONAL, IN PSECURITY_QUALITY_OF_SERVICE SecurityQos OPTIONAL, OUT PVOID *NextObject) { POBJECT_SYMBOLIC_LINK SymlinkObject = (POBJECT_SYMBOLIC_LINK)ParsedObject; PUNICODE_STRING TargetPath; PWSTR NewTargetPath; ULONG LengthUsed, MaximumLength, TempLength; NTSTATUS Status; PAGED_CODE(); /* Assume failure */ *NextObject = NULL; /* Check if we're out of name to parse */ if (!RemainingName->Length) { /* Check if we got an object type */ if (ObjectType) { /* Reference the object only */ Status = ObReferenceObjectByPointer(ParsedObject, 0, ObjectType, AccessMode); if (NT_SUCCESS(Status)) { /* Return it */ *NextObject = ParsedObject; } if ((NT_SUCCESS(Status)) || (Status != STATUS_OBJECT_TYPE_MISMATCH)) { /* Fail */ return Status; } } } else if (RemainingName->Buffer[0] != OBJ_NAME_PATH_SEPARATOR) { /* Symbolic links must start with a backslash */ return STATUS_OBJECT_TYPE_MISMATCH; } /* Check if this symlink is bound to a specific object */ if (SymlinkObject->LinkTargetObject) { UNIMPLEMENTED; } /* Set the target path and length */ TargetPath = &SymlinkObject->LinkTarget; TempLength = TargetPath->Length; /* * Strip off the extra trailing '\', if we don't do this we will end up * adding a extra '\' between TargetPath and RemainingName * causing caller's like ObpLookupObjectName() to fail. */ if (TempLength && RemainingName->Length) { /* The target and remaining names aren't empty, so check for slashes */ if ((TargetPath->Buffer[TempLength / sizeof(WCHAR) - 1] == OBJ_NAME_PATH_SEPARATOR) && (RemainingName->Buffer[0] == OBJ_NAME_PATH_SEPARATOR)) { /* Reduce the length by one to cut off the extra '\' */ TempLength -= sizeof(OBJ_NAME_PATH_SEPARATOR); } } /* Calculate the new length */ LengthUsed = TempLength + RemainingName->Length; /* Check if it's not too much */ if (LengthUsed > 0xFFF0) return STATUS_NAME_TOO_LONG; /* Optimization: check if the new name is shorter */ if (FullPath->MaximumLength <= LengthUsed) { /* It's not, allocate a new one */ MaximumLength = LengthUsed + sizeof(WCHAR); NewTargetPath = ExAllocatePoolWithTag(NonPagedPool, MaximumLength, OB_NAME_TAG); if (!NewTargetPath) return STATUS_INSUFFICIENT_RESOURCES; } else { /* It is! Reuse the name... */ MaximumLength = FullPath->MaximumLength; NewTargetPath = FullPath->Buffer; } /* Make sure we have a length */ if (RemainingName->Length) { /* Copy the new path */ RtlMoveMemory((PVOID)((ULONG_PTR)NewTargetPath + TempLength), RemainingName->Buffer, RemainingName->Length); } /* Copy the target path and null-terminate it */ RtlCopyMemory(NewTargetPath, TargetPath->Buffer, TempLength); NewTargetPath[LengthUsed / sizeof(WCHAR)] = UNICODE_NULL; /* If the optimization didn't work, free the old buffer */ if (NewTargetPath != FullPath->Buffer) ExFreePool(FullPath->Buffer); /* Update the path values */ FullPath->Length = (USHORT)LengthUsed; FullPath->MaximumLength = (USHORT)MaximumLength; FullPath->Buffer = NewTargetPath; /* Tell the parse routine to start reparsing */ return STATUS_REPARSE; } /* PUBLIC FUNCTIONS **********************************************************/ /*++ * @name NtCreateSymbolicLinkObject * @implemented NT4 * * The NtCreateSymbolicLinkObject opens or creates a symbolic link object. * * @param LinkHandle * Variable which receives the symlink handle. * * @param DesiredAccess * Desired access to the symlink. * * @param ObjectAttributes * Structure describing the symlink. * * @param LinkTarget * Unicode string defining the symlink's target * * @return STATUS_SUCCESS or appropriate error value. * * @remarks None. * *--*/ NTSTATUS NTAPI NtCreateSymbolicLinkObject(OUT PHANDLE LinkHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PUNICODE_STRING LinkTarget) { HANDLE hLink; POBJECT_SYMBOLIC_LINK SymbolicLink; UNICODE_STRING CapturedLinkTarget; KPROCESSOR_MODE PreviousMode = ExGetPreviousMode(); NTSTATUS Status; PAGED_CODE(); /* Check if we need to probe parameters */ if (PreviousMode != KernelMode) { _SEH2_TRY { /* Probe the target */ CapturedLinkTarget = ProbeForReadUnicodeString(LinkTarget); ProbeForRead(CapturedLinkTarget.Buffer, CapturedLinkTarget.MaximumLength, sizeof(WCHAR)); /* Probe the return handle */ ProbeForWriteHandle(LinkHandle); } _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { /* Return the exception code */ _SEH2_YIELD(return _SEH2_GetExceptionCode()); } _SEH2_END; } else { /* No need to capture */ CapturedLinkTarget = *LinkTarget; } /* Check if the maximum length is odd */ if (CapturedLinkTarget.MaximumLength % sizeof(WCHAR)) { /* Round it down */ CapturedLinkTarget.MaximumLength = (USHORT)ALIGN_DOWN(CapturedLinkTarget.MaximumLength, WCHAR); } /* Fail if the length is odd, or if the maximum is smaller or 0 */ if ((CapturedLinkTarget.Length % sizeof(WCHAR)) || (CapturedLinkTarget.MaximumLength < CapturedLinkTarget.Length) || !(CapturedLinkTarget.MaximumLength)) { /* This message is displayed on the debugger in Windows */ DbgPrint("OB: Invalid symbolic link target - %wZ\n", &CapturedLinkTarget); return STATUS_INVALID_PARAMETER; } /* Create the object */ Status = ObCreateObject(PreviousMode, ObSymbolicLinkType, ObjectAttributes, PreviousMode, NULL, sizeof(OBJECT_SYMBOLIC_LINK), 0, 0, (PVOID*)&SymbolicLink); if (NT_SUCCESS(Status)) { /* Success! Fill in the creation time immediately */ KeQuerySystemTime(&SymbolicLink->CreationTime); /* Setup the target name */ SymbolicLink->LinkTarget.Length = CapturedLinkTarget.Length; SymbolicLink->LinkTarget.MaximumLength = CapturedLinkTarget.Length + sizeof(WCHAR); SymbolicLink->LinkTarget.Buffer = ExAllocatePoolWithTag(PagedPool, CapturedLinkTarget.MaximumLength, TAG_SYMLINK_TARGET); if (!SymbolicLink->LinkTarget.Buffer) { /* Dereference the symbolic link object and fail */ ObDereferenceObject(SymbolicLink); return STATUS_NO_MEMORY; } /* Copy it */ RtlCopyMemory(SymbolicLink->LinkTarget.Buffer, CapturedLinkTarget.Buffer, CapturedLinkTarget.MaximumLength); /* Initialize the remaining name, dos drive index and target object */ SymbolicLink->LinkTargetObject = NULL; SymbolicLink->DosDeviceDriveIndex = 0; RtlInitUnicodeString(&SymbolicLink->LinkTargetRemaining, NULL); /* Insert it into the object tree */ Status = ObInsertObject(SymbolicLink, NULL, DesiredAccess, 0, NULL, &hLink); if (NT_SUCCESS(Status)) { _SEH2_TRY { /* Return the handle to caller */ *LinkHandle = hLink; } _SEH2_EXCEPT(ExSystemExceptionFilter()) { /* Get exception code */ Status = _SEH2_GetExceptionCode(); } _SEH2_END; } } /* Return status to caller */ return Status; } /*++ * @name NtOpenSymbolicLinkObject * @implemented NT4 * * The NtOpenSymbolicLinkObject opens a symbolic link object. * * @param LinkHandle * Variable which receives the symlink handle. * * @param DesiredAccess * Desired access to the symlink. * * @param ObjectAttributes * Structure describing the symlink. * * @return STATUS_SUCCESS or appropriate error value. * * @remarks None. * *--*/ NTSTATUS NTAPI NtOpenSymbolicLinkObject(OUT PHANDLE LinkHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes) { HANDLE hLink; KPROCESSOR_MODE PreviousMode = ExGetPreviousMode(); NTSTATUS Status; PAGED_CODE(); /* Check if we need to probe parameters */ if (PreviousMode != KernelMode) { _SEH2_TRY { /* Probe the return handle */ ProbeForWriteHandle(LinkHandle); } _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { /* Return the exception code */ _SEH2_YIELD(return _SEH2_GetExceptionCode()); } _SEH2_END; } /* Open the object */ Status = ObOpenObjectByName(ObjectAttributes, ObSymbolicLinkType, PreviousMode, NULL, DesiredAccess, NULL, &hLink); if (NT_SUCCESS(Status)) { _SEH2_TRY { /* Return the handle to caller */ *LinkHandle = hLink; } _SEH2_EXCEPT(ExSystemExceptionFilter()) { /* Get exception code */ Status = _SEH2_GetExceptionCode(); } _SEH2_END; } /* Return status to caller */ return Status; } /*++ * @name NtQuerySymbolicLinkObject * @implemented NT4 * * The NtQuerySymbolicLinkObject queries a symbolic link object. * * @param LinkHandle * Symlink handle to query * * @param LinkTarget * Unicode string defining the symlink's target * * @param ResultLength * Caller supplied storage for the number of bytes written (or NULL). * * @return STATUS_SUCCESS or appropriate error value. * * @remarks None. * *--*/ NTSTATUS NTAPI NtQuerySymbolicLinkObject(IN HANDLE LinkHandle, OUT PUNICODE_STRING LinkTarget, OUT PULONG ResultLength OPTIONAL) { UNICODE_STRING SafeLinkTarget = { 0, 0, NULL }; POBJECT_SYMBOLIC_LINK SymlinkObject; KPROCESSOR_MODE PreviousMode = ExGetPreviousMode(); NTSTATUS Status; ULONG LengthUsed; PAGED_CODE(); if (PreviousMode != KernelMode) { _SEH2_TRY { /* Probe the unicode string for read and write */ ProbeForWriteUnicodeString(LinkTarget); /* Probe the unicode string's buffer for write */ SafeLinkTarget = *LinkTarget; ProbeForWrite(SafeLinkTarget.Buffer, SafeLinkTarget.MaximumLength, sizeof(WCHAR)); /* Probe the return length */ if (ResultLength) ProbeForWriteUlong(ResultLength); } _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) { /* Return the exception code */ _SEH2_YIELD(return _SEH2_GetExceptionCode()); } _SEH2_END; } else { /* No need to probe */ SafeLinkTarget = *LinkTarget; } /* Reference the object */ Status = ObReferenceObjectByHandle(LinkHandle, SYMBOLIC_LINK_QUERY, ObSymbolicLinkType, PreviousMode, (PVOID *)&SymlinkObject, NULL); if (NT_SUCCESS(Status)) { /* Lock the object */ ObpAcquireObjectLock(OBJECT_TO_OBJECT_HEADER(SymlinkObject)); /* * So here's the thing: If you specify a return length, then the * implementation will use the maximum length. If you don't, then * it will use the length. */ LengthUsed = ResultLength ? SymlinkObject->LinkTarget.MaximumLength : SymlinkObject->LinkTarget.Length; /* Enter SEH so we can safely copy */ _SEH2_TRY { /* Make sure our buffer will fit */ if (LengthUsed <= SafeLinkTarget.MaximumLength) { /* Copy the buffer */ RtlCopyMemory(SafeLinkTarget.Buffer, SymlinkObject->LinkTarget.Buffer, LengthUsed); /* Copy the new length */ LinkTarget->Length = SymlinkObject->LinkTarget.Length; } else { /* Otherwise set the failure status */ Status = STATUS_BUFFER_TOO_SMALL; } /* In both cases, check if the required length was requested */ if (ResultLength) { /* Then return it */ *ResultLength = SymlinkObject->LinkTarget.MaximumLength; } } _SEH2_EXCEPT(ExSystemExceptionFilter()) { /* Get the error code */ Status = _SEH2_GetExceptionCode(); } _SEH2_END; /* Unlock and dereference the object */ ObpReleaseObjectLock(OBJECT_TO_OBJECT_HEADER(SymlinkObject)); ObDereferenceObject(SymlinkObject); } /* Return query status */ return Status; } /* EOF */
rickerliang/reactos-mirror2
ntoskrnl/ob/oblink.c
C
gpl-2.0
26,797
/* * Copyright 2009 TauNova (http://taunova.com). All rights reserved. * * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package com.taunova.ui.light.component; import java.awt.Graphics; /** * Description * * @version 1.0, 12/07/09 * @author Renat Gilmanov * @author Viktor Zakalyuzhnyy */ public class LightLabel extends AbstractTextComponent { public LightLabel(String text) { super(text); } @Override public void paint(Graphics g) { g.setColor(background); g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height); g.setColor(textColor); g.drawString(text, bounds.x+10, bounds.y+15); } }
RenatGilmanov/tau-ui
src/java/com/taunova/ui/light/component/LightLabel.java
Java
gpl-2.0
791
<?php namespace Drupal\Tests\conditional_fields\FunctionalJavascript; use Drupal\language\Entity\ContentLanguageSettings; use Drupal\Tests\conditional_fields\FunctionalJavascript\TestCases\ConditionalFieldValueInterface; /** * Test Conditional Fields Language Select Plugin. * * @group conditional_fields */ class ConditionalFieldLanguageSelectTest extends ConditionalFieldTestBase implements ConditionalFieldValueInterface { /** * Modules to enable. * * @var array */ public static $modules = [ 'conditional_fields', 'language', 'node', 'options', ]; /** * {@inheritdoc} */ protected $screenshotPath = 'sites/simpletest/conditional_fields/language_select/'; /** * The field name used in the test. * * @var string */ protected $fieldName = 'langcode'; /** * Jquery selector of field in a document. * * @var string */ protected $fieldSelector; /** * The field to use in this test. * * @var \Drupal\field\Entity\FieldConfig */ protected $field; /** * The default language code. * * @var string */ protected $defaultLanguage; /** * An array with Not specified and Not applicable language codes. * * @var array */ protected $langcodes = ['und', 'zxx']; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->fieldSelector = "[name=\"{$this->fieldName}[0][value]\"]"; // Get the default language which will trigger the dependency. $this->defaultLanguage = \Drupal::languageManager()->getCurrentLanguage()->getId(); // Enable language selector on node creation page. ContentLanguageSettings::loadByEntityTypeBundle('node', 'article') ->setLanguageAlterable(TRUE) ->setDefaultLangcode($this->defaultLanguage) ->save(); } /** * {@inheritdoc} */ public function testVisibleValueWidget() { $this->baseTestSteps(); // Visit a ConditionalFields configuration page for Content bundles. $this->createCondition('body', $this->fieldName, 'visible', 'value'); $this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png'); // Set up conditions. $data = [ 'condition' => 'value', 'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_WIDGET, $this->fieldName . '[0][value]' => $this->defaultLanguage, 'grouping' => 'AND', 'state' => 'visible', 'effect' => 'show', ]; $this->submitForm( $data, 'Save settings'); $this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png'); // Check if that configuration is saved. $this->drupalGet('admin/structure/types/manage/article/conditionals'); $this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png'); $this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value'); // Visit Article Add form to check that conditions are applied. $this->drupalGet('node/add/article'); // Check that the field Body is visible. $this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png'); $this->waitUntilVisible('.field--name-body', 50, '01. Article Body field is not visible'); // Change a select value set that should not show the body. $this->changeField($this->fieldSelector, $this->langcodes[0]); $this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png'); $this->waitUntilHidden('.field--name-body', 50, '02. Article Body field is visible'); // Change a select value set to show the body. $this->changeField($this->fieldSelector, $this->defaultLanguage); $this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png'); $this->waitUntilVisible('.field--name-body', 50, '03. Article Body field is not visible'); // Change a select value set to hide the body again. $this->changeField($this->fieldSelector, $this->langcodes[1]); $this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png'); $this->waitUntilHidden('.field--name-body', 50, '04. Article Body field is visible'); } /** * {@inheritdoc} */ public function testVisibleValueRegExp() { $this->baseTestSteps(); // Visit a ConditionalFields configuration page for Content bundles. $this->createCondition('body', $this->fieldName, 'visible', 'value'); $this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png'); // Set up conditions. $data = [ 'condition' => 'value', 'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_REGEX, "regex" => '^'. $this->langcodes[0] . '$', 'grouping' => 'AND', 'state' => 'visible', 'effect' => 'show', ]; $this->submitForm( $data, 'Save settings'); $this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png'); // Check if that configuration is saved. $this->drupalGet('admin/structure/types/manage/article/conditionals'); $this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png'); $this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value'); // Visit Article Add form to check that conditions are applied. $this->drupalGet('node/add/article'); // Check that the field Body is visible. $this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png'); $this->waitUntilHidden('.field--name-body', 50, '01. Article Body field is visible'); // Change a select value set that should not show the body. $this->changeField($this->fieldSelector, $this->langcodes[0]); $this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png'); $this->waitUntilVisible('.field--name-body', 50, '02. Article Body field is not visible'); // Change a select value set to show the body. $this->changeField($this->fieldSelector, $this->defaultLanguage); $this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png'); $this->waitUntilHidden('.field--name-body', 50, '03. Article Body field is visible'); // Change a select value set to hide the body again. $this->changeField($this->fieldSelector, $this->langcodes[1]); $this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png'); $this->waitUntilHidden('.field--name-body', 50, '04. Article Body field is visible'); } /** * {@inheritdoc} */ public function testVisibleValueAnd() { $this->baseTestSteps(); // Visit a ConditionalFields configuration page for Content bundles. $this->createCondition('body', $this->fieldName, 'visible', 'value'); $this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png'); // Set up conditions. $data = [ 'condition' => 'value', 'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_AND, "values" => implode( "\r\n", $this->langcodes ), 'grouping' => 'AND', 'state' => 'visible', 'effect' => 'show', ]; $this->submitForm( $data, 'Save settings'); $this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png'); // Check if that configuration is saved. $this->drupalGet('admin/structure/types/manage/article/conditionals'); $this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png'); $this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value'); // Visit Article Add form to check that conditions are applied. $this->drupalGet('node/add/article'); // Check that the field Body is visible. $this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png'); $this->waitUntilHidden('.field--name-body', 50, '01. Article Body field is visible'); // Change a select value set that should not show the body. $this->changeField($this->fieldSelector, $this->langcodes[0]); $this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png'); $this->waitUntilHidden('.field--name-body', 50, '02. Article Body field is visible'); // Change a select value set to show the body. $this->changeField($this->fieldSelector, $this->defaultLanguage); $this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png'); $this->waitUntilHidden('.field--name-body', 50, '03. Article Body field is visible'); // Change a select value set to hide the body again. $this->changeField($this->fieldSelector, $this->langcodes[1]); $this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png'); $this->waitUntilHidden('.field--name-body', 50, '04. Article Body field is visible'); } /** * {@inheritdoc} */ public function testVisibleValueOr() { $this->baseTestSteps(); // Visit a ConditionalFields configuration page for Content bundles. $this->createCondition('body', $this->fieldName, 'visible', 'value'); $this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png'); // Set up conditions. $data = [ 'condition' => 'value', 'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_OR, "values" => implode( "\r\n", $this->langcodes ), 'grouping' => 'AND', 'state' => 'visible', 'effect' => 'show', ]; $this->submitForm( $data, 'Save settings'); $this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png'); // Check if that configuration is saved. $this->drupalGet('admin/structure/types/manage/article/conditionals'); $this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png'); $this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value'); // Visit Article Add form to check that conditions are applied. $this->drupalGet('node/add/article'); // Check that the field Body is visible. $this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png'); $this->waitUntilHidden('.field--name-body', 50, '01. Article Body field is visible'); // Change a select value set that should not show the body. $this->changeField($this->fieldSelector, $this->langcodes[0]); $this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png'); $this->waitUntilVisible('.field--name-body', 50, '02. Article Body field is not visible'); // Change a select value set to show the body. $this->changeField($this->fieldSelector, $this->defaultLanguage); $this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png'); $this->waitUntilHidden('.field--name-body', 50, '03. Article Body field is visible'); // Change a select value set to hide the body again. $this->changeField($this->fieldSelector, $this->langcodes[1]); $this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png'); $this->waitUntilVisible('.field--name-body', 50, '04. Article Body field is not visible'); } /** * {@inheritdoc} */ public function testVisibleValueNot() { $this->baseTestSteps(); // Visit a ConditionalFields configuration page for Content bundles. $this->createCondition('body', $this->fieldName, 'visible', 'value'); $this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png'); // Set up conditions. $data = [ 'condition' => 'value', 'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_NOT, "values" => implode( "\r\n", $this->langcodes ), 'grouping' => 'AND', 'state' => 'visible', 'effect' => 'show', ]; $this->submitForm( $data, 'Save settings'); $this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png'); // Check if that configuration is saved. $this->drupalGet('admin/structure/types/manage/article/conditionals'); $this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png'); $this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value'); // Visit Article Add form to check that conditions are applied. $this->drupalGet('node/add/article'); // Check that the field Body is visible. $this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png'); $this->waitUntilVisible('.field--name-body', 50, '01. Article Body field is not visible'); // Change a select value set that should not show the body. $this->changeField($this->fieldSelector, $this->langcodes[0]); $this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png'); $this->waitUntilHidden('.field--name-body', 50, '02. Article Body field is visible'); // Change a select value set to show the body. $this->changeField($this->fieldSelector, $this->defaultLanguage); $this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png'); $this->waitUntilVisible('.field--name-body', 50, '03. Article Body field is not visible'); // Change a select value set to hide the body again. $this->changeField($this->fieldSelector, $this->langcodes[1]); $this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png'); $this->waitUntilHidden('.field--name-body', 50, '04. Article Body field is visible'); } /** * {@inheritdoc} */ public function testVisibleValueXor() { $this->baseTestSteps(); // Visit a ConditionalFields configuration page for Content bundles. $this->createCondition('body', $this->fieldName, 'visible', 'value'); $this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png'); // Set up conditions. $data = [ 'condition' => 'value', 'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_XOR, "values" => implode( "\r\n", $this->langcodes ), 'grouping' => 'AND', 'state' => 'visible', 'effect' => 'show', ]; $this->submitForm( $data, 'Save settings'); $this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png'); // Check if that configuration is saved. $this->drupalGet('admin/structure/types/manage/article/conditionals'); $this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png'); $this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value'); // Visit Article Add form to check that conditions are applied. $this->drupalGet('node/add/article'); // Check that the field Body is visible. $this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png'); $this->waitUntilHidden('.field--name-body', 50, '01. Article Body field is visible'); // Change a select value set that should not show the body. $this->changeField($this->fieldSelector, $this->langcodes[0]); $this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png'); $this->waitUntilVisible('.field--name-body', 50, '02. Article Body field is not visible'); // Change a select value set to show the body. $this->changeField($this->fieldSelector, $this->defaultLanguage); $this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png'); $this->waitUntilHidden('.field--name-body', 50, '03. Article Body field is visible'); // Change a select value set to hide the body again. $this->changeField($this->fieldSelector, $this->langcodes[1]); $this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png'); $this->waitUntilVisible('.field--name-body', 50, '04. Article Body field is not visible'); } }
enslyon/ensl
modules/conditional_fields/tests/src/FunctionalJavascript/ConditionalFieldLanguageSelectTest.php
PHP
gpl-2.0
17,212
/* * device.h - generic, centralized driver model * * Copyright (c) 2001-2003 Patrick Mochel <mochel@osdl.org> * Copyright (c) 2004-2009 Greg Kroah-Hartman <gregkh@suse.de> * Copyright (c) 2008-2009 Novell Inc. * * This file is released under the GPLv2 * * See Documentation/driver-model/ for more information. */ #ifndef _DEVICE_H_ #define _DEVICE_H_ #include <linux/ioport.h> #include <linux/kobject.h> #include <linux/klist.h> #include <linux/list.h> #include <linux/lockdep.h> #include <linux/compiler.h> #include <linux/types.h> #include <linux/module.h> #include <linux/pm.h> #include <linux/atomic.h> #include <asm/device.h> struct device; struct device_private; struct device_driver; struct driver_private; struct class; struct subsys_private; struct bus_type; struct device_node; struct iommu_ops; struct bus_attribute { struct attribute attr; ssize_t (*show)(struct bus_type *bus, char *buf); ssize_t (*store)(struct bus_type *bus, const char *buf, size_t count); }; #define BUS_ATTR(_name, _mode, _show, _store) \ struct bus_attribute bus_attr_##_name = __ATTR(_name, _mode, _show, _store) extern int __must_check bus_create_file(struct bus_type *, struct bus_attribute *); extern void bus_remove_file(struct bus_type *, struct bus_attribute *); /** * struct bus_type - The bus type of the device * * @name: The name of the bus. * @dev_name: Used for subsystems to enumerate devices like ("foo%u", dev->id). * @dev_root: Default device to use as the parent. * @bus_attrs: Default attributes of the bus. * @dev_attrs: Default attributes of the devices on the bus. * @drv_attrs: Default attributes of the device drivers on the bus. * @match: Called, perhaps multiple times, whenever a new device or driver * is added for this bus. It should return a nonzero value if the * given device can be handled by the given driver. * @uevent: Called when a device is added, removed, or a few other things * that generate uevents to add the environment variables. * @probe: Called when a new device or driver add to this bus, and callback * the specific driver's probe to initial the matched device. * @remove: Called when a device removed from this bus. * @shutdown: Called at shut-down time to quiesce the device. * @suspend: Called when a device on this bus wants to go to sleep mode. * @resume: Called to bring a device on this bus out of sleep mode. * @pm: Power management operations of this bus, callback the specific * device driver's pm-ops. * @p: The private data of the driver core, only the driver core can * touch this. * * A bus is a channel between the processor and one or more devices. For the * purposes of the device model, all devices are connected via a bus, even if * it is an internal, virtual, "platform" bus. Buses can plug into each other. * A USB controller is usually a PCI device, for example. The device model * represents the actual connections between buses and the devices they control. * A bus is represented by the bus_type structure. It contains the name, the * default attributes, the bus' methods, PM operations, and the driver core's * private data. */ struct bus_type { const char *name; const char *dev_name; struct device *dev_root; struct bus_attribute *bus_attrs; struct device_attribute *dev_attrs; struct driver_attribute *drv_attrs; int (*match)(struct device *dev, struct device_driver *drv); int (*uevent)(struct device *dev, struct kobj_uevent_env *env); int (*probe)(struct device *dev); int (*remove)(struct device *dev); void (*shutdown)(struct device *dev); int (*suspend)(struct device *dev, pm_message_t state); int (*resume)(struct device *dev); const struct dev_pm_ops *pm; struct iommu_ops *iommu_ops; struct subsys_private *p; }; /* This is a #define to keep the compiler from merging different * instances of the __key variable */ #define bus_register(subsys) \ ({ \ static struct lock_class_key __key; \ __bus_register(subsys, &__key); \ }) extern int __must_check __bus_register(struct bus_type *bus, struct lock_class_key *key); extern void bus_unregister(struct bus_type *bus); extern int __must_check bus_rescan_devices(struct bus_type *bus); /* iterator helpers for buses */ struct subsys_dev_iter { struct klist_iter ki; const struct device_type *type; }; void subsys_dev_iter_init(struct subsys_dev_iter *iter, struct bus_type *subsys, struct device *start, const struct device_type *type); struct device *subsys_dev_iter_next(struct subsys_dev_iter *iter); void subsys_dev_iter_exit(struct subsys_dev_iter *iter); int bus_for_each_dev(struct bus_type *bus, struct device *start, void *data, int (*fn)(struct device *dev, void *data)); struct device *bus_find_device(struct bus_type *bus, struct device *start, void *data, int (*match)(struct device *dev, void *data)); struct device *bus_find_device_by_name(struct bus_type *bus, struct device *start, const char *name); struct device *subsys_find_device_by_id(struct bus_type *bus, unsigned int id, struct device *hint); int bus_for_each_drv(struct bus_type *bus, struct device_driver *start, void *data, int (*fn)(struct device_driver *, void *)); void bus_sort_breadthfirst(struct bus_type *bus, int (*compare)(const struct device *a, const struct device *b)); /* * Bus notifiers: Get notified of addition/removal of devices * and binding/unbinding of drivers to devices. * In the long run, it should be a replacement for the platform * notify hooks. */ struct notifier_block; extern int bus_register_notifier(struct bus_type *bus, struct notifier_block *nb); extern int bus_unregister_notifier(struct bus_type *bus, struct notifier_block *nb); /* All 4 notifers below get called with the target struct device * * as an argument. Note that those functions are likely to be called * with the device lock held in the core, so be careful. */ #define BUS_NOTIFY_ADD_DEVICE 0x00000001 /* device added */ #define BUS_NOTIFY_DEL_DEVICE 0x00000002 /* device removed */ #define BUS_NOTIFY_BIND_DRIVER 0x00000003 /* driver about to be bound */ #define BUS_NOTIFY_BOUND_DRIVER 0x00000004 /* driver bound to device */ #define BUS_NOTIFY_UNBIND_DRIVER 0x00000005 /* driver about to be unbound */ #define BUS_NOTIFY_UNBOUND_DRIVER 0x00000006 /* driver is unbound from the device */ extern struct kset *bus_get_kset(struct bus_type *bus); extern struct klist *bus_get_device_klist(struct bus_type *bus); /** * struct device_driver - The basic device driver structure * @name: Name of the device driver. * @bus: The bus which the device of this driver belongs to. * @owner: The module owner. * @mod_name: Used for built-in modules. * @suppress_bind_attrs: Disables bind/unbind via sysfs. * @of_match_table: The open firmware table. * @probe: Called to query the existence of a specific device, * whether this driver can work with it, and bind the driver * to a specific device. * @remove: Called when the device is removed from the system to * unbind a device from this driver. * @shutdown: Called at shut-down time to quiesce the device. * @suspend: Called to put the device to sleep mode. Usually to a * low power state. * @resume: Called to bring a device from sleep mode. * @groups: Default attributes that get created by the driver core * automatically. * @pm: Power management operations of the device which matched * this driver. * @p: Driver core's private data, no one other than the driver * core can touch this. * * The device driver-model tracks all of the drivers known to the system. * The main reason for this tracking is to enable the driver core to match * up drivers with new devices. Once drivers are known objects within the * system, however, a number of other things become possible. Device drivers * can export information and configuration variables that are independent * of any specific device. */ struct device_driver { const char *name; struct bus_type *bus; struct module *owner; const char *mod_name; /* used for built-in modules */ bool suppress_bind_attrs; /* disables bind/unbind via sysfs */ const struct of_device_id *of_match_table; int (*probe) (struct device *dev); int (*remove) (struct device *dev); void (*shutdown) (struct device *dev); int (*suspend) (struct device *dev, pm_message_t state); int (*resume) (struct device *dev); const struct attribute_group **groups; const struct dev_pm_ops *pm; struct driver_private *p; }; extern int __must_check driver_register(struct device_driver *drv); extern void driver_unregister(struct device_driver *drv); extern struct device_driver *get_driver(struct device_driver *drv); extern void put_driver(struct device_driver *drv); extern struct device_driver *driver_find(const char *name, struct bus_type *bus); extern int driver_probe_done(void); extern void wait_for_device_probe(void); /* sysfs interface for exporting driver attributes */ struct driver_attribute { struct attribute attr; ssize_t (*show)(struct device_driver *driver, char *buf); ssize_t (*store)(struct device_driver *driver, const char *buf, size_t count); }; #define DRIVER_ATTR(_name, _mode, _show, _store) \ struct driver_attribute driver_attr_##_name = \ __ATTR(_name, _mode, _show, _store) extern int __must_check driver_create_file(struct device_driver *driver, const struct driver_attribute *attr); extern void driver_remove_file(struct device_driver *driver, const struct driver_attribute *attr); extern int __must_check driver_add_kobj(struct device_driver *drv, struct kobject *kobj, const char *fmt, ...); extern int __must_check driver_for_each_device(struct device_driver *drv, struct device *start, void *data, int (*fn)(struct device *dev, void *)); struct device *driver_find_device(struct device_driver *drv, struct device *start, void *data, int (*match)(struct device *dev, void *data)); /** * struct subsys_interface - interfaces to device functions * @name name of the device function * @subsystem subsytem of the devices to attach to * @node the list of functions registered at the subsystem * @add device hookup to device function handler * @remove device hookup to device function handler * * Simple interfaces attached to a subsystem. Multiple interfaces can * attach to a subsystem and its devices. Unlike drivers, they do not * exclusively claim or control devices. Interfaces usually represent * a specific functionality of a subsystem/class of devices. */ struct subsys_interface { const char *name; struct bus_type *subsys; struct list_head node; int (*add_dev)(struct device *dev, struct subsys_interface *sif); int (*remove_dev)(struct device *dev, struct subsys_interface *sif); }; int subsys_interface_register(struct subsys_interface *sif); void subsys_interface_unregister(struct subsys_interface *sif); int subsys_system_register(struct bus_type *subsys, const struct attribute_group **groups); /** * struct class - device classes * @name: Name of the class. * @owner: The module owner. * @class_attrs: Default attributes of this class. * @dev_attrs: Default attributes of the devices belong to the class. * @dev_bin_attrs: Default binary attributes of the devices belong to the class. * @dev_kobj: The kobject that represents this class and links it into the hierarchy. * @dev_uevent: Called when a device is added, removed from this class, or a * few other things that generate uevents to add the environment * variables. * @devnode: Callback to provide the devtmpfs. * @class_release: Called to release this class. * @dev_release: Called to release the device. * @suspend: Used to put the device to sleep mode, usually to a low power * state. * @resume: Used to bring the device from the sleep mode. * @ns_type: Callbacks so sysfs can detemine namespaces. * @namespace: Namespace of the device belongs to this class. * @pm: The default device power management operations of this class. * @p: The private data of the driver core, no one other than the * driver core can touch this. * * A class is a higher-level view of a device that abstracts out low-level * implementation details. Drivers may see a SCSI disk or an ATA disk, but, * at the class level, they are all simply disks. Classes allow user space * to work with devices based on what they do, rather than how they are * connected or how they work. */ struct class { const char *name; struct module *owner; struct class_attribute *class_attrs; struct device_attribute *dev_attrs; struct bin_attribute *dev_bin_attrs; struct kobject *dev_kobj; int (*dev_uevent)(struct device *dev, struct kobj_uevent_env *env); char *(*devnode)(struct device *dev, mode_t *mode); void (*class_release)(struct class *class); void (*dev_release)(struct device *dev); int (*suspend)(struct device *dev, pm_message_t state); int (*resume)(struct device *dev); const struct kobj_ns_type_operations *ns_type; const void *(*namespace)(struct device *dev); const struct dev_pm_ops *pm; struct subsys_private *p; }; struct class_dev_iter { struct klist_iter ki; const struct device_type *type; }; extern struct kobject *sysfs_dev_block_kobj; extern struct kobject *sysfs_dev_char_kobj; extern int __must_check __class_register(struct class *class, struct lock_class_key *key); extern void class_unregister(struct class *class); /* This is a #define to keep the compiler from merging different * instances of the __key variable */ #define class_register(class) \ ({ \ static struct lock_class_key __key; \ __class_register(class, &__key); \ }) struct class_compat; struct class_compat *class_compat_register(const char *name); void class_compat_unregister(struct class_compat *cls); int class_compat_create_link(struct class_compat *cls, struct device *dev, struct device *device_link); void class_compat_remove_link(struct class_compat *cls, struct device *dev, struct device *device_link); extern void class_dev_iter_init(struct class_dev_iter *iter, struct class *class, struct device *start, const struct device_type *type); extern struct device *class_dev_iter_next(struct class_dev_iter *iter); extern void class_dev_iter_exit(struct class_dev_iter *iter); extern int class_for_each_device(struct class *class, struct device *start, void *data, int (*fn)(struct device *dev, void *data)); extern struct device *class_find_device(struct class *class, struct device *start, void *data, int (*match)(struct device *, void *)); struct class_attribute { struct attribute attr; ssize_t (*show)(struct class *class, struct class_attribute *attr, char *buf); ssize_t (*store)(struct class *class, struct class_attribute *attr, const char *buf, size_t count); }; #define CLASS_ATTR(_name, _mode, _show, _store) \ struct class_attribute class_attr_##_name = __ATTR(_name, _mode, _show, _store) extern int __must_check class_create_file(struct class *class, const struct class_attribute *attr); extern void class_remove_file(struct class *class, const struct class_attribute *attr); /* Simple class attribute that is just a static string */ struct class_attribute_string { struct class_attribute attr; char *str; }; /* Currently read-only only */ #define _CLASS_ATTR_STRING(_name, _mode, _str) \ { __ATTR(_name, _mode, show_class_attr_string, NULL), _str } #define CLASS_ATTR_STRING(_name, _mode, _str) \ struct class_attribute_string class_attr_##_name = \ _CLASS_ATTR_STRING(_name, _mode, _str) extern ssize_t show_class_attr_string(struct class *class, struct class_attribute *attr, char *buf); struct class_interface { struct list_head node; struct class *class; int (*add_dev) (struct device *, struct class_interface *); void (*remove_dev) (struct device *, struct class_interface *); }; extern int __must_check class_interface_register(struct class_interface *); extern void class_interface_unregister(struct class_interface *); extern struct class * __must_check __class_create(struct module *owner, const char *name, struct lock_class_key *key); extern void class_destroy(struct class *cls); /* This is a #define to keep the compiler from merging different * instances of the __key variable */ #define class_create(owner, name) \ ({ \ static struct lock_class_key __key; \ __class_create(owner, name, &__key); \ }) /* * The type of device, "struct device" is embedded in. A class * or bus can contain devices of different types * like "partitions" and "disks", "mouse" and "event". * This identifies the device type and carries type-specific * information, equivalent to the kobj_type of a kobject. * If "name" is specified, the uevent will contain it in * the DEVTYPE variable. */ struct device_type { const char *name; const struct attribute_group **groups; int (*uevent)(struct device *dev, struct kobj_uevent_env *env); char *(*devnode)(struct device *dev, mode_t *mode); void (*release)(struct device *dev); const struct dev_pm_ops *pm; }; /* interface for exporting device attributes */ struct device_attribute { struct attribute attr; ssize_t (*show)(struct device *dev, struct device_attribute *attr, char *buf); ssize_t (*store)(struct device *dev, struct device_attribute *attr, const char *buf, size_t count); }; struct dev_ext_attribute { struct device_attribute attr; void *var; }; ssize_t device_show_ulong(struct device *dev, struct device_attribute *attr, char *buf); ssize_t device_store_ulong(struct device *dev, struct device_attribute *attr, const char *buf, size_t count); ssize_t device_show_int(struct device *dev, struct device_attribute *attr, char *buf); ssize_t device_store_int(struct device *dev, struct device_attribute *attr, const char *buf, size_t count); #define DEVICE_ATTR(_name, _mode, _show, _store) \ struct device_attribute dev_attr_##_name = __ATTR(_name, _mode, _show, _store) #define DEVICE_ULONG_ATTR(_name, _mode, _var) \ struct dev_ext_attribute dev_attr_##_name = \ { __ATTR(_name, _mode, device_show_ulong, device_store_ulong), &(_var) } #define DEVICE_INT_ATTR(_name, _mode, _var) \ struct dev_ext_attribute dev_attr_##_name = \ { __ATTR(_name, _mode, device_show_ulong, device_store_ulong), &(_var) } extern int device_create_file(struct device *device, const struct device_attribute *entry); extern void device_remove_file(struct device *dev, const struct device_attribute *attr); extern int __must_check device_create_bin_file(struct device *dev, const struct bin_attribute *attr); extern void device_remove_bin_file(struct device *dev, const struct bin_attribute *attr); extern int device_schedule_callback_owner(struct device *dev, void (*func)(struct device *dev), struct module *owner); /* This is a macro to avoid include problems with THIS_MODULE */ #define device_schedule_callback(dev, func) \ device_schedule_callback_owner(dev, func, THIS_MODULE) /* device resource management */ typedef void (*dr_release_t)(struct device *dev, void *res); typedef int (*dr_match_t)(struct device *dev, void *res, void *match_data); #ifdef CONFIG_DEBUG_DEVRES extern void *__devres_alloc(dr_release_t release, size_t size, gfp_t gfp, const char *name); #define devres_alloc(release, size, gfp) \ __devres_alloc(release, size, gfp, #release) #else extern void *devres_alloc(dr_release_t release, size_t size, gfp_t gfp); #endif extern void devres_free(void *res); extern void devres_add(struct device *dev, void *res); extern void *devres_find(struct device *dev, dr_release_t release, dr_match_t match, void *match_data); extern void *devres_get(struct device *dev, void *new_res, dr_match_t match, void *match_data); extern void *devres_remove(struct device *dev, dr_release_t release, dr_match_t match, void *match_data); extern int devres_destroy(struct device *dev, dr_release_t release, dr_match_t match, void *match_data); /* devres group */ extern void * __must_check devres_open_group(struct device *dev, void *id, gfp_t gfp); extern void devres_close_group(struct device *dev, void *id); extern void devres_remove_group(struct device *dev, void *id); extern int devres_release_group(struct device *dev, void *id); /* managed kzalloc/kfree for device drivers, no kmalloc, always use kzalloc */ extern void *devm_kzalloc(struct device *dev, size_t size, gfp_t gfp); extern void devm_kfree(struct device *dev, void *p); void __iomem *devm_request_and_ioremap(struct device *dev, struct resource *res); struct device_dma_parameters { /* * a low level driver may set these to teach IOMMU code about * sg limitations. */ unsigned int max_segment_size; unsigned long segment_boundary_mask; }; /** * struct device - The basic device structure * @parent: The device's "parent" device, the device to which it is attached. * In most cases, a parent device is some sort of bus or host * controller. If parent is NULL, the device, is a top-level device, * which is not usually what you want. * @p: Holds the private data of the driver core portions of the device. * See the comment of the struct device_private for detail. * @kobj: A top-level, abstract class from which other classes are derived. * @init_name: Initial name of the device. * @type: The type of device. * This identifies the device type and carries type-specific * information. * @mutex: Mutex to synchronize calls to its driver. * @bus: Type of bus device is on. * @driver: Which driver has allocated this * @platform_data: Platform data specific to the device. * Example: For devices on custom boards, as typical of embedded * and SOC based hardware, Linux often uses platform_data to point * to board-specific structures describing devices and how they * are wired. That can include what ports are available, chip * variants, which GPIO pins act in what additional roles, and so * on. This shrinks the "Board Support Packages" (BSPs) and * minimizes board-specific #ifdefs in drivers. * @power: For device power management. * See Documentation/power/devices.txt for details. * @pm_domain: Provide callbacks that are executed during system suspend, * hibernation, system resume and during runtime PM transitions * along with subsystem-level and driver-level callbacks. * @numa_node: NUMA node this device is close to. * @dma_mask: Dma mask (if dma'ble device). * @coherent_dma_mask: Like dma_mask, but for alloc_coherent mapping as not all * hardware supports 64-bit addresses for consistent allocations * such descriptors. * @dma_parms: A low level driver may set these to teach IOMMU code about * segment limitations. * @dma_pools: Dma pools (if dma'ble device). * @dma_mem: Internal for coherent mem override. * @archdata: For arch-specific additions. * @of_node: Associated device tree node. * @devt: For creating the sysfs "dev". * @devres_lock: Spinlock to protect the resource of the device. * @devres_head: The resources list of the device. * @knode_class: The node used to add the device to the class list. * @class: The class of the device. * @groups: Optional attribute groups. * @release: Callback to free the device after all references have * gone away. This should be set by the allocator of the * device (i.e. the bus driver that discovered the device). * * At the lowest level, every device in a Linux system is represented by an * instance of struct device. The device structure contains the information * that the device model core needs to model the system. Most subsystems, * however, track additional information about the devices they host. As a * result, it is rare for devices to be represented by bare device structures; * instead, that structure, like kobject structures, is usually embedded within * a higher-level representation of the device. */ struct device { struct device *parent; struct device_private *p; struct kobject kobj; const char *init_name; /* initial name of the device */ const struct device_type *type; struct mutex mutex; /* mutex to synchronize calls to * its driver. */ struct bus_type *bus; /* type of bus device is on */ struct device_driver *driver; /* which driver has allocated this device */ void *platform_data; /* Platform specific data, device core doesn't touch it */ struct dev_pm_info power; struct dev_pm_domain *pm_domain; #ifdef CONFIG_NUMA int numa_node; /* NUMA node this device is close to */ #endif u64 *dma_mask; /* dma mask (if dma'able device) */ u64 coherent_dma_mask;/* Like dma_mask, but for alloc_coherent mappings as not all hardware supports 64 bit addresses for consistent allocations such descriptors. */ struct device_dma_parameters *dma_parms; struct list_head dma_pools; /* dma pools (if dma'ble) */ struct dma_coherent_mem *dma_mem; /* internal for coherent mem override */ /* arch specific additions */ struct dev_archdata archdata; struct device_node *of_node; /* associated device tree node */ dev_t devt; /* dev_t, creates the sysfs "dev" */ u32 id; /* device instance */ spinlock_t devres_lock; struct list_head devres_head; struct klist_node knode_class; struct class *class; const struct attribute_group **groups; /* optional groups */ void (*release)(struct device *dev); }; /* Get the wakeup routines, which depend on struct device */ #include <linux/pm_wakeup.h> static inline const char *dev_name(const struct device *dev) { /* Use the init name until the kobject becomes available */ if (dev->init_name) return dev->init_name; return kobject_name(&dev->kobj); } extern int dev_set_name(struct device *dev, const char *name, ...) __attribute__((format(printf, 2, 3))); #ifdef CONFIG_NUMA static inline int dev_to_node(struct device *dev) { return dev->numa_node; } static inline void set_dev_node(struct device *dev, int node) { dev->numa_node = node; } #else static inline int dev_to_node(struct device *dev) { return -1; } static inline void set_dev_node(struct device *dev, int node) { } #endif static inline struct pm_subsys_data *dev_to_psd(struct device *dev) { return dev ? dev->power.subsys_data : NULL; } static inline unsigned int dev_get_uevent_suppress(const struct device *dev) { return dev->kobj.uevent_suppress; } static inline void dev_set_uevent_suppress(struct device *dev, int val) { dev->kobj.uevent_suppress = val; } static inline int device_is_registered(struct device *dev) { return dev->kobj.state_in_sysfs; } static inline void device_enable_async_suspend(struct device *dev) { if (!dev->power.is_prepared) dev->power.async_suspend = true; } static inline void device_disable_async_suspend(struct device *dev) { if (!dev->power.is_prepared) dev->power.async_suspend = false; } static inline bool device_async_suspend_enabled(struct device *dev) { return !!dev->power.async_suspend; } static inline void pm_suspend_ignore_children(struct device *dev, bool enable) { dev->power.ignore_children = enable; } static inline void device_lock(struct device *dev) { mutex_lock(&dev->mutex); } static inline int device_trylock(struct device *dev) { return mutex_trylock(&dev->mutex); } static inline void device_unlock(struct device *dev) { mutex_unlock(&dev->mutex); } void driver_init(void); /* * High level routines for use by the bus drivers */ extern int __must_check device_register(struct device *dev); extern void device_unregister(struct device *dev); extern void device_initialize(struct device *dev); extern int __must_check device_add(struct device *dev); extern void device_del(struct device *dev); extern int device_for_each_child(struct device *dev, void *data, int (*fn)(struct device *dev, void *data)); extern struct device *device_find_child(struct device *dev, void *data, int (*match)(struct device *dev, void *data)); extern int device_rename(struct device *dev, const char *new_name); extern int device_move(struct device *dev, struct device *new_parent, enum dpm_order dpm_order); extern const char *device_get_devnode(struct device *dev, mode_t *mode, const char **tmp); extern void *dev_get_drvdata(const struct device *dev); extern int dev_set_drvdata(struct device *dev, void *data); /* * Root device objects for grouping under /sys/devices */ extern struct device *__root_device_register(const char *name, struct module *owner); static inline struct device *root_device_register(const char *name) { return __root_device_register(name, THIS_MODULE); } extern void root_device_unregister(struct device *root); static inline void *dev_get_platdata(const struct device *dev) { return dev->platform_data; } /* * Manual binding of a device to driver. See drivers/base/bus.c * for information on use. */ extern int __must_check device_bind_driver(struct device *dev); extern void device_release_driver(struct device *dev); extern int __must_check device_attach(struct device *dev); extern int __must_check driver_attach(struct device_driver *drv); extern int __must_check device_reprobe(struct device *dev); /* * Easy functions for dynamically creating devices on the fly */ extern struct device *device_create_vargs(struct class *cls, struct device *parent, dev_t devt, void *drvdata, const char *fmt, va_list vargs); extern struct device *device_create(struct class *cls, struct device *parent, dev_t devt, void *drvdata, const char *fmt, ...) __attribute__((format(printf, 5, 6))); extern void device_destroy(struct class *cls, dev_t devt); /* * Platform "fixup" functions - allow the platform to have their say * about devices and actions that the general device layer doesn't * know about. */ /* Notify platform of device discovery */ extern int (*platform_notify)(struct device *dev); extern int (*platform_notify_remove)(struct device *dev); /* * get_device - atomically increment the reference count for the device. * */ extern struct device *get_device(struct device *dev); extern void put_device(struct device *dev); extern void wait_for_device_probe(void); #ifdef CONFIG_DEVTMPFS extern int devtmpfs_create_node(struct device *dev); extern int devtmpfs_delete_node(struct device *dev); extern int devtmpfs_mount(const char *mntdir); #else static inline int devtmpfs_create_node(struct device *dev) { return 0; } static inline int devtmpfs_delete_node(struct device *dev) { return 0; } static inline int devtmpfs_mount(const char *mountpoint) { return 0; } #endif /* drivers/base/power/shutdown.c */ extern void device_shutdown(void); /* debugging and troubleshooting/diagnostic helpers. */ extern const char *dev_driver_string(const struct device *dev); #ifdef CONFIG_PRINTK extern int dev_printk(const char *level, const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 3, 4))); extern int dev_emerg(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); extern int dev_alert(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); extern int dev_crit(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); extern int dev_err(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); extern int dev_warn(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); extern int dev_notice(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); extern int _dev_info(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); #else static inline int dev_printk(const char *level, const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 3, 4))); static inline int dev_printk(const char *level, const struct device *dev, const char *fmt, ...) { return 0; } static inline int dev_emerg(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); static inline int dev_emerg(const struct device *dev, const char *fmt, ...) { return 0; } static inline int dev_crit(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); static inline int dev_crit(const struct device *dev, const char *fmt, ...) { return 0; } static inline int dev_alert(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); static inline int dev_alert(const struct device *dev, const char *fmt, ...) { return 0; } static inline int dev_err(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); static inline int dev_err(const struct device *dev, const char *fmt, ...) { return 0; } static inline int dev_warn(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); static inline int dev_warn(const struct device *dev, const char *fmt, ...) { return 0; } static inline int dev_notice(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); static inline int dev_notice(const struct device *dev, const char *fmt, ...) { return 0; } static inline int _dev_info(const struct device *dev, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); static inline int _dev_info(const struct device *dev, const char *fmt, ...) { return 0; } #endif /* * Stupid hackaround for existing uses of non-printk uses dev_info * * Note that the definition of dev_info below is actually _dev_info * and a macro is used to avoid redefining dev_info */ #define dev_info(dev, fmt, arg...) _dev_info(dev, fmt, ##arg) #if defined(DEBUG) #define dev_dbg(dev, format, arg...) \ dev_printk(KERN_DEBUG, dev, format, ##arg) #elif defined(CONFIG_DYNAMIC_DEBUG) #define dev_dbg(dev, format, ...) \ do { \ dynamic_dev_dbg(dev, format, ##__VA_ARGS__); \ } while (0) #else #define dev_dbg(dev, format, arg...) \ ({ \ if (0) \ dev_printk(KERN_DEBUG, dev, format, ##arg); \ 0; \ }) #endif #ifdef VERBOSE_DEBUG #define dev_vdbg dev_dbg #else #define dev_vdbg(dev, format, arg...) \ ({ \ if (0) \ dev_printk(KERN_DEBUG, dev, format, ##arg); \ 0; \ }) #endif /* * dev_WARN*() acts like dev_printk(), but with the key difference * of using a WARN/WARN_ON to get the message out, including the * file/line information and a backtrace. */ #define dev_WARN(dev, format, arg...) \ WARN(1, "Device: %s\n" format, dev_driver_string(dev), ## arg); #define dev_WARN_ONCE(dev, condition, format, arg...) \ WARN_ONCE(condition, "Device %s\n" format, \ dev_driver_string(dev), ## arg) /* Create alias, so I can be autoloaded. */ #define MODULE_ALIAS_CHARDEV(major,minor) \ MODULE_ALIAS("char-major-" __stringify(major) "-" __stringify(minor)) #define MODULE_ALIAS_CHARDEV_MAJOR(major) \ MODULE_ALIAS("char-major-" __stringify(major) "-*") #ifdef CONFIG_SYSFS_DEPRECATED extern long sysfs_deprecated; #else #define sysfs_deprecated 0 #endif /** * module_driver() - Helper macro for drivers that don't do anything * special in module init/exit. This eliminates a lot of boilerplate. * Each module may only use this macro once, and calling it replaces * module_init() and module_exit(). * * Use this macro to construct bus specific macros for registering * drivers, and do not use it on its own. */ #define module_driver(__driver, __register, __unregister) \ static int __init __driver##_init(void) \ { \ return __register(&(__driver)); \ } \ module_init(__driver##_init); \ static void __exit __driver##_exit(void) \ { \ __unregister(&(__driver)); \ } \ module_exit(__driver##_exit); #endif /* _DEVICE_H_ */
ktoonsez/SiyahD
include/linux/device.h
C
gpl-2.0
36,133
/* vi: set sw=4 ts=4: */ /* * pivot_root.c - Change root file system. Bagsed on util-linux 2.10s * * busyboxed by Evin Robertson * pivot_root syscall stubbed by Erik Andersen, so it will compile * regardless of the kernel being used. * * Licengsed under GPLv2, see file LICENSE in this source tree. */ //usage:#define pivot_root_trivial_usage //usage: "NEW_ROOT PUT_OLD" //usage:#define pivot_root_full_usage "\n\n" //usage: "Move the current root file system to PUT_OLD and make NEW_ROOT\n" //usage: "the new root file system" #include "libbb.h" extern int pivot_root(const char * new_root,const char * put_old); int pivot_root_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; int pivot_root_main(int argc, char **argv) { if (argc != 3) bb_show_usage(); if (pivot_root(argv[1], argv[2]) < 0) { /* prints "pivot_root: <strerror text>" */ bb_perror_nomsg_and_die(); } return EXIT_SUCCESS; }
ThinkIntegrate/busybox
util-linux/pivot_root.c
C
gpl-2.0
941
/* Copyright (C) 2008 - 2016 by Mark de Wever <koraq@xs4all.nl> Part of the Battle for Wesnoth Project http://www.wesnoth.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. See the COPYING file for more details. */ #ifndef GUI_WIDGETS_TEXT_BOX_HPP_INCLUDED #define GUI_WIDGETS_TEXT_BOX_HPP_INCLUDED #include "gui/widgets/text.hpp" namespace gui2 { // ------------ WIDGET -----------{ /** * Class for text input history. * * The history of text items can be stored in the preferences. This class * handles that. Every item needs an id by which the history is loaded and * saved. */ class ttext_history { public: /** * Gets history that matches id. * * @param id The id of the history to look for. * @param enabled The enabled state of the history. * * @returns The history object. */ static ttext_history get_history(const std::string& id, const bool enabled); ttext_history() : history_(0), pos_(0), enabled_(false) { } /** * Push string into the history. * * If the string is empty or the same as the last item in the history this * function is a nop. * * @param text The text to push in the history. */ void push(const std::string& text); /** * One step up in the history. * * Pushes text to the history if at the end. * * @param text The text to push in the history. * * @returns The current value of the history. */ std::string up(const std::string& text = ""); /** * One step down in the history. * * Pushes text to the history if at the end. * * @param text The text to push in the history. * * @returns The current value of the history. */ std::string down(const std::string& text = ""); /** * Gets the current history value. * * @returns If enabled return the current history * position, otherwise an empty string is * returned. */ std::string get_value() const; /***** ***** ***** setters / getters for members ***** ****** *****/ void set_enabled(bool enabled = true) { enabled_ = enabled; } bool get_enabled() const { return enabled_; } private: ttext_history(std::vector<std::string>* history, const bool enabled) : history_(history), pos_(history->size()), enabled_(enabled) { } /** The items in the history. */ std::vector<std::string>* history_; /** The current position in the history. */ unsigned pos_; /** Is the history enabled. */ bool enabled_; }; /** Class for a single line text area. */ class ttext_box : public ttext_ { public: ttext_box(); /** Saves the text in the widget to the history. */ void save_to_history() { history_.push(get_value()); } /***** ***** ***** setters / getters for members ***** ****** *****/ void set_history(const std::string& id) { history_ = ttext_history::get_history(id, true); } void set_max_input_length(const size_t length) { max_input_length_ = length; } void clear() { set_value(""); } protected: /***** ***** ***** ***** layout functions ***** ***** ***** *****/ /** See @ref twidget::place. */ virtual void place(const tpoint& origin, const tpoint& size) override; /***** ***** ***** ***** Inherited ***** ***** ***** *****/ /** See @ref tcontrol::update_canvas. */ virtual void update_canvas() override; /** Inherited from ttext_. */ void goto_end_of_line(const bool select = false) override { goto_end_of_data(select); } /** Inherited from ttext_. */ void goto_start_of_line(const bool select = false) override { goto_start_of_data(select); } /** Inherited from ttext_. */ void delete_char(const bool before_cursor) override; /** Inherited from ttext_. */ void delete_selection() override; void handle_mouse_selection(tpoint mouse, const bool start_selection); private: /** The history text for this widget. */ ttext_history history_; /** The maximum length of the text input. */ size_t max_input_length_; /** * The x offset in the widget where the text starts. * * This value is needed to translate a location in the widget to a location * in the text. */ unsigned text_x_offset_; /** * The y offset in the widget where the text starts. * * Needed to determine whether a click is on the text. */ unsigned text_y_offset_; /** * The height of the text itself. * * Needed to determine whether a click is on the text. */ unsigned text_height_; /** Updates text_x_offset_ and text_y_offset_. */ void update_offsets(); /** Is the mouse in dragging mode, this affects selection in mouse move */ bool dragging_; /** * Inherited from ttext_. * * Unmodified Unhandled. * Control Ignored. * Shift Ignored. * Alt Ignored. */ void handle_key_up_arrow(SDL_Keymod /*modifier*/, bool& /*handled*/) override { } /** * Inherited from ttext_. * * Unmodified Unhandled. * Control Ignored. * Shift Ignored. * Alt Ignored. */ void handle_key_down_arrow(SDL_Keymod /*modifier*/, bool& /*handled*/) override { } /** * Goes one item up in the history. * * @returns True if there's a history, false otherwise. */ bool history_up(); /** * Goes one item down in the history. * * @returns True if there's a history, false otherwise. */ bool history_down(); /** Inherited from ttext_. */ void handle_key_default(bool& handled, SDL_Keycode key, SDL_Keymod modifier, const utf8::string& unicode) override; /** Inherited from ttext_. */ void handle_key_clear_line(SDL_Keymod modifier, bool& handled) override; /** See @ref tcontrol::get_control_type. */ virtual const std::string& get_control_type() const override; /** Inherited from tcontrol. */ void load_config_extra() override; /***** ***** ***** signal handlers ***** ****** *****/ void signal_handler_mouse_motion(const event::tevent event, bool& handled, const tpoint& coordinate); void signal_handler_left_button_down(const event::tevent event, bool& handled); void signal_handler_left_button_up(const event::tevent event, bool& handled); void signal_handler_left_button_double_click(const event::tevent event, bool& handled); }; // }---------- DEFINITION ---------{ struct ttext_box_definition : public tcontrol_definition { explicit ttext_box_definition(const config& cfg); struct tresolution : public tresolution_definition_ { explicit tresolution(const config& cfg); tformula<unsigned> text_x_offset; tformula<unsigned> text_y_offset; }; }; // }---------- BUILDER -----------{ namespace implementation { struct tbuilder_text_box : public tbuilder_control { public: explicit tbuilder_text_box(const config& cfg); using tbuilder_control::build; twidget* build() const; std::string history; size_t max_input_length; }; } // namespace implementation // }------------ END -------------- } // namespace gui2 #endif
aquileia/wesnoth
src/gui/widgets/text_box.hpp
C++
gpl-2.0
7,540
<?php include('includes/session.inc'); $Title = _('Tax Status Maintenance'); include('includes/header.inc'); include('includes/SQL_CommonFunctions.inc'); if (isset($_GET['TaxStatusID'])) { $TaxStatusID = strtoupper($_GET['TaxStatusID']); } elseif (isset($_POST['TaxStatusID'])) { $TaxStatusID = strtoupper($_POST['TaxStatusID']); } else { unset($TaxStatusID); } //initialise no input errors assumed initially before we test $InputError = 0; /* actions to take once the user has clicked the submit button ie the page has called itself with some user input */ //first off validate inputs sensible if ($InputError != 1 and (isset($_POST['update']) or isset($_POST['insert']))) { if (isset($_POST['update'])) { $SQL = "UPDATE prltaxstatus SET taxstatusdescription='" . $_POST['TaxStatusDescription'] . "', personalexemption='" . $_POST['PersonalExemption'] . "', additionalexemption='" . $_POST['AdditionalExemption'] . "', totalexemption='" . $_POST['TotalExemption'] . "' WHERE taxstatusid = '" . $TaxStatusID . "'"; $ErrMsg = _('The tax status could not be updated because'); $DbgMsg = _('The SQL that was used to update the tax status but failed was'); $Result = DB_query($SQL, $ErrMsg, $DbgMsg); prnMsg(_('The tax status master record for') . ' ' . $TaxStatusID . ' ' . _('has been updated'), 'success'); } elseif (isset($_POST['insert'])) { //its a new tax status $SQL = "INSERT INTO prltaxstatus (taxstatusid, taxstatusdescription, personalexemption, additionalexemption, totalexemption ) VALUES ('" . $_POST['TaxStatusID'] . "', '" . $_POST['TaxStatusDescription'] . "', '" . $_POST['PersonalExemption'] . "', '" . $_POST['AdditionalExemption'] . "', '" . $_POST['TotalExemption'] . "' )"; $ErrMsg = _('The tax status') . ' ' . $_POST['TaxStatusDescription'] . ' ' . _('could not be added because'); $DbgMsg = _('The SQL that was used to insert the tax status but failed was'); $Result = DB_query($SQL, $ErrMsg, $DbgMsg); prnMsg(_('A new tax status for') . ' ' . $_POST['TaxStatusDescription'] . ' ' . _('has been added to the database'), 'success'); } unset($TaxStatusID); unset($_POST['TaxStatusDescription']); unset($_POST['PersonalExemption']); unset($_POST['AdditionalExemption']); unset($_POST['TotalExemption']); } elseif ($InputError > 0) { prnMsg(_('Validation failed') . _('no updates or deletes took place'), 'warn'); } if (isset($_POST['delete']) AND $_POST['delete'] != '') { //the link to delete a selected record was clicked instead of the submit button $CancelDelete = 0; // PREVENT DELETES IF DEPENDENT RECORDS IN 'SuppTrans' , PurchOrders, SupplierContacts if ($CancelDelete == 0) { $SQL = "DELETE FROM prltaxstatus WHERE taxstatusid='$TaxStatusID'"; $Result = DB_query($SQL); prnMsg(_('Tax status record for') . ' ' . $TaxStatusID . ' ' . _('has been deleted'), 'success'); unset($TaxStatusID); unset($_SESSION['TaxStatusID']); } //end if Delete tax status } //end of (isset($_POST['submit'])) //SupplierID exists - either passed when calling the form or from the form itself echo '<form method="post" class="noPrint" action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '">'; echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />'; echo '<p class="page_title_text noPrint" > <img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/money_add.png" title="' . $Title . '" alt="" />' . ' ' . $Title . ' </p>'; $SQL = "SELECT taxstatusid, taxstatusdescription, personalexemption, additionalexemption, totalexemption FROM prltaxstatus"; $Result = DB_query($SQL); if (DB_num_rows($Result)) { echo '<table class="selection"> <tr> <th>' . _('Status ID') . '<th> <th>' . _('Description') . '<th> <th>' . _('Personal Excemption') . '<th> <th>' . _('Additional Excemption') . '<th> <th>' . _('Total Excemption') . '<th> </tr>'; while ($MyRow = DB_fetch_array($Result)) { echo '<tr> <td>' . $MyRow['taxstatusid'] . '<td> <td>' . $MyRow['taxstatusdescription'] . '<td> <td class="number">' . locale_number_format($MyRow['personalexemption'], $_SESSION['CompanyRecord']['decimalplaces']) . '<td> <td class="number">' . locale_number_format($MyRow['additionalexemption'], $_SESSION['CompanyRecord']['decimalplaces']) . '<td> <td class="number">' . locale_number_format($MyRow['totalexemption'], $_SESSION['CompanyRecord']['decimalplaces']) . '<td> <td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?TaxStatusID=' . $MyRow['taxstatusid'] . '">' . _('Edit') . '</a></td> </tr>'; } echo '</table>'; } if (isset($TaxStatusID)) { $SQL = "SELECT taxstatusid, taxstatusdescription, personalexemption, additionalexemption, totalexemption FROM prltaxstatus WHERE taxstatusid = '" . $TaxStatusID . "'"; $Result = DB_query($SQL); $MyRow = DB_fetch_array($Result); $_POST['TaxStatusDescription'] = $MyRow['taxstatusdescription']; $_POST['PersonalExemption'] = $MyRow['personalexemption']; $_POST['AdditionalExemption'] = $MyRow['additionalexemption']; $_POST['TotalExemption'] = $MyRow['totalexemption']; echo '<table class="selection">'; echo '<input type="hidden" name="TaxStatusID" value="' . $TaxStatusID . '" />'; echo '<tr> <td>' . _('Tax Status ID') . ':</td> <td>' . $TaxStatusID . '</td> </tr>'; } else { // its a new status being added echo '<table class="selection">'; echo '<tr> <td>' . _('Tax Status ID') . ':</td> <td><input type="text" name="TaxStatusID" value="" size="12" maxlength="10" /></td> </tr>'; $_POST['TaxStatusDescription'] = ''; $_POST['PersonalExemption'] = 0; $_POST['AdditionalExemption'] = 0; $_POST['TotalExemption'] = 0; } echo '<tr> <td>' . _('Tax Status Description') . ':</td> <td><input type="text" name="TaxStatusDescription" value="' . $_POST['TaxStatusDescription'] . '" size="42" maxlength="40" //></td> </tr>'; echo '<tr> <td>' . _('Personal Exemption') . ':</td> <td><input type="text" class="number" name="PersonalExemption" value="' . $_POST['PersonalExemption'] . '" size="13" maxlength="12" /></td> </tr>'; echo '<tr> <td>' . _('Additional Exemption') . ':</td> <td><input type="text" class="number" name="AdditionalExemption" size="13" maxlength="12" value="' . $_POST['AdditionalExemption'] . '" /></td> </tr>'; echo '<tr> <td>' . _('Total Exemption') . ':</td> <td><input type="text" class="number" name="TotalExemption" size="13" maxlength="12" value="' . $_POST['TotalExemption'] . '" /></td> </tr>'; if (!isset($TaxStatusID)) { echo '</table> <div class="centre"> <input type="submit" name="insert" value="' . _('Add These New Tax Status Details') . '" /> </div> </form>'; } else { echo '</table> <div class="centre"> <input type="submit" name="update" value="' . _('Update Tax Status') . '" /> </div>'; echo '<div class="centre"> <input type="Submit" name="delete" value="' . _('Delete Employee') . '" onclick="return confirm("' . _('Are you sure you wish to delete this tax status?') . '");" /> </div> </form>'; } include('includes/footer.inc'); ?>
fahadhatib/KwaMoja
prlTaxStatus.php
PHP
gpl-2.0
7,520
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.3.1"/> <title>Taobao Cpp/Qt SDK: TaoApiCpp/request/TopatsResultGetRequest.h Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Taobao Cpp/Qt SDK </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_5ced2c06884fa9bf5c2da90298abd959.html">TaoApiCpp</a></li><li class="navelem"><a class="el" href="dir_1128517a525300e3048e72552ab6f4a6.html">request</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">TopatsResultGetRequest.h</div> </div> </div><!--header--> <div class="contents"> <a href="TopatsResultGetRequest_8h.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<span class="preprocessor">#ifndef TOPATSRESULTGETREQUEST_H</span></div> <div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;<span class="preprocessor"></span><span class="preprocessor">#define TOPATSRESULTGETREQUEST_H</span></div> <div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160;<span class="preprocessor"></span></div> <div class="line"><a name="l00004"></a><span class="lineno"> 4</span>&#160;<span class="preprocessor">#include &lt;<a class="code" href="TaoRequest_8h.html">TaoApiCpp/TaoRequest.h</a>&gt;</span></div> <div class="line"><a name="l00005"></a><span class="lineno"> 5</span>&#160;<span class="preprocessor">#include &lt;<a class="code" href="TaoParser_8h.html">TaoApiCpp/TaoParser.h</a>&gt;</span></div> <div class="line"><a name="l00006"></a><span class="lineno"> 6</span>&#160;<span class="preprocessor">#include &lt;<a class="code" href="TopatsResultGetResponse_8h.html">TaoApiCpp/response/TopatsResultGetResponse.h</a>&gt;</span></div> <div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160;</div> <div class="line"><a name="l00018"></a><span class="lineno"><a class="code" href="classTopatsResultGetRequest.html"> 18</a></span>&#160;<span class="keyword">class </span><a class="code" href="classTopatsResultGetRequest.html">TopatsResultGetRequest</a> : <span class="keyword">public</span> <a class="code" href="classTaoRequest.html" title="Api请求基类。">TaoRequest</a></div> <div class="line"><a name="l00019"></a><span class="lineno"> 19</span>&#160;{</div> <div class="line"><a name="l00020"></a><span class="lineno"> 20</span>&#160; <span class="keyword">public</span>:</div> <div class="line"><a name="l00021"></a><span class="lineno"> 21</span>&#160; <span class="keyword">virtual</span> QString <a class="code" href="classTopatsResultGetRequest.html#a6e5ea6c056ec82555e2d1cdb6867c536">getApiMethodName</a>() <span class="keyword">const</span>;</div> <div class="line"><a name="l00022"></a><span class="lineno"> 22</span>&#160;</div> <div class="line"><a name="l00023"></a><span class="lineno"> 23</span>&#160; qlonglong <a class="code" href="classTopatsResultGetRequest.html#a2c02b23e453c760c2f1061fda611c612">getTaskId</a>() <span class="keyword">const</span></div> <div class="line"><a name="l00024"></a><span class="lineno"> 24</span>&#160;; <span class="keywordtype">void</span> <a class="code" href="classTopatsResultGetRequest.html#a9670dfdf8ac9e75b82112106e8d538fe">setTaskId</a> (qlonglong <a class="code" href="classTopatsResultGetRequest.html#ad0d7d39c764d37f192904af50f5c17bb" title="任务id号,创建任务时返回的task_id">taskId</a>);</div> <div class="line"><a name="l00025"></a><span class="lineno"> 25</span>&#160;</div> <div class="line"><a name="l00026"></a><span class="lineno"> 26</span>&#160;</div> <div class="line"><a name="l00027"></a><span class="lineno"> 27</span>&#160; <span class="keyword">virtual</span> <a class="code" href="classTopatsResultGetResponse.html" title="TOP RESPONSE API: 获取异步任务结果。 异步API使用方法,请查看:异步API使用说明 1. 只能获取AppKey自身创建的异步任务结果 2. 如果任务状态为done,则返回任务结果(如taobao.topats.trades.fullinfo.get)或下载地址(如taobao.topats.trades.sold.get) 3. 任务结果下载地址只能使用一次,需要重复下载可重新调用此接口获取下载地址 4. 任务结果中的check_code字段为待下载文件的md5 sum,可通过此校验码验证文件下载的完整性">TopatsResultGetResponse</a> *<a class="code" href="classTopatsResultGetRequest.html#ac00a8e69ee6dbda745f64baf89cd2604" title="发送请求,返回Reponse派生类。">getResponseClass</a>(<span class="keyword">const</span> QString &amp;<a class="code" href="classTaoRequest.html#a9956848123bf21777fb605b4585a7c98">session</a> = <span class="stringliteral">&quot;&quot;</span>,</div> <div class="line"><a name="l00028"></a><span class="lineno"> 28</span>&#160; <span class="keyword">const</span> QString &amp;<a class="code" href="classTaoRequest.html#a7dcc6b71d454184a32a3f1c0adbc4a64">accessToken</a> = <span class="stringliteral">&quot;&quot;</span>); </div> <div class="line"><a name="l00029"></a><span class="lineno"> 29</span>&#160;</div> <div class="line"><a name="l00030"></a><span class="lineno"> 30</span>&#160; <span class="keyword">private</span>:</div> <div class="line"><a name="l00034"></a><span class="lineno"><a class="code" href="classTopatsResultGetRequest.html#ad0d7d39c764d37f192904af50f5c17bb"> 34</a></span>&#160; qlonglong <a class="code" href="classTopatsResultGetRequest.html#ad0d7d39c764d37f192904af50f5c17bb" title="任务id号,创建任务时返回的task_id">taskId</a>;</div> <div class="line"><a name="l00035"></a><span class="lineno"> 35</span>&#160;</div> <div class="line"><a name="l00036"></a><span class="lineno"> 36</span>&#160;};</div> <div class="line"><a name="l00037"></a><span class="lineno"> 37</span>&#160;</div> <div class="line"><a name="l00038"></a><span class="lineno"> 38</span>&#160;<span class="preprocessor">#endif </span><span class="comment">/* TOPATSRESULTGETREQUEST_H */</span><span class="preprocessor"></span></div> </div><!-- fragment --></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Sun Apr 14 2013 16:25:36 for Taobao Cpp/Qt SDK by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.3.1 </small></address> </body> </html>
sd44/TaobaoCppQtSDK
doc/TopatsResultGetRequest_8h_source.html
HTML
gpl-2.0
10,334
package ModelLayer; import java.util.ArrayList; /** * Write a description of class Product here. * * @author (Jacob Pedersen & Ronnie Knudsen) * @version (04-12-2014) dd-mm-yyyy */ public class Product { // instance variables private ArrayList<ProductItem> items; private int id; private String barcode; private String productName; private String description; private double minimumPrice; //Absolute minimum price, that the product may be sold for. private double salesPrice; //Actual price the product should be sold for. private double supplierPrice; //The price the product costed to buy from the supplier private double discountPrice; //if there's a discount, the sales price will be defined here while the discount lasts. When not null, this will be the given sales price. private int quantity; //The ammount of items private String location; //location the products items is located in the warehouse. /** * Constructor for objects of class Product * * @param id the products unique id. * @param barcode the products barcode. * @param productName The products name. * @param description product description. * @param minimumPrice minimum price that the product may be sold for. * @param salesPrice Actual price the product should be sold for. * @param supplierPrice The price the product costed to buy from the supplier. * @param discountPrice if there's a discount, the sales price will be defined here while the discount lasts. When not 0, this will be the given sales price. */ public Product(int id, String barcode, String productName, String description, double minimumPrice, double salesPrice, double supplierPrice) { items = new ArrayList<ProductItem>(); this.id = id; this.barcode = barcode; this.productName = productName; this.description = description; this.minimumPrice = minimumPrice; this.salesPrice = salesPrice; this.supplierPrice = supplierPrice; this.quantity = 0; this.location = "Undefined"; } /** * Adds an item to the container with availbale items for this product. * * @param productItem A parameter */ public void addItem(ProductItem productItem) { items.add(productItem); quantity++; } /** * If an item is avalible, the first on the list is returned. * * @return is an item of the given itemtype. */ public ProductItem getItem() { if(items.size() > 0) { return items.get(0); } return null; } /** * Returns the item with the given SerialNumber if it exists. * * @param SerialNumber The items serialnumber. * @Return The item with the given serialnumber if it exists. Else it returns null. */ public ProductItem getItemBySerial(String serialNumber) { //Find item with given serialNumber. return null; } /** * returns true if remove is available. * * @true if remove is available, else false */ public boolean removeItem() { if(getAvailable() == true) { items.remove(0); quantity--; return true; } return false; } /** * @return true if there's items available for the product and false if not. */ public boolean getAvailable() { if(quantity > 0) { return true; } return false; } /** * Get the products id. * @return Get the products id. */ public int getId() { return id; } /** * Get the products barcode. * @return The products Barcode. */ public String getBarcode() { return barcode; } /** * Get the products name. * @return The products name. */ public String getProductName() { return productName; } /** * Get the products description. * @return The products description. */ public String getDescription() { return description; } /** * Get the products minimum price. * @return The products minimum price. */ public double getMinimumPrice() { return minimumPrice; } /** * Get the products sales price. * @return The products sales price. */ public double getSalesPrice() { return salesPrice; } /** * Get the products discount price. * @return The products discount price. */ public double getDiscountPrice() { return discountPrice; } /** * Get the products supplier price. * @return The products supplier price. */ public double getSupplierPrice() { return supplierPrice; } /** * Get the products quantity of available items. * @return The products quantity. */ public int getQuantity() { return quantity; } /** * Get the products location in the warehouse. * @return The products location in the warehouse. */ public String getLocation() { return location; } /** * @param barcode the barcode to set */ public void setBarcode(String barcode) { this.barcode = barcode; } /** * @param productName the productName to set */ public void setProductName(String productName) { this.productName = productName; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @param minimumPrice the minimumPrice to set */ public void setMinimumPrice(double minimumPrice) { this.minimumPrice = minimumPrice; } /** * @param salesPrice the salesPrice to set */ public void setSalesPrice(double salesPrice) { this.salesPrice = salesPrice; } /** * @param supplierPrice the supplierPrice to set */ public void setSupplierPrice(double supplierPrice) { this.supplierPrice = supplierPrice; } /** * @param discountPrice the discountPrice to set */ public void setDiscountPrice(double discountPrice) { this.discountPrice = discountPrice; } /** * @param quantity the quantity to set */ public void setQuantity(int quantity) { this.quantity = quantity; } /** * @param location the location to set */ public void setLocation(String location) { this.location = location; } }
dmab0914-Gruppe-2/Vestbjerg-Byggecenter
src/ModelLayer/Product.java
Java
gpl-2.0
6,578
#include <iostream> #include "assembler.h" using namespace std; // Simple constructor. Assembler::Assembler(istream &in, ostream &out) { currentAddress = 0; for (int i = 0; i < MAXLABEL; i++) labelTable[i] = 0; insource = &in; outsource = &out; } // Default destructor. Assembler::~Assembler() { } // The first pass of the assmebler. This just builds the labelTable. // Don't translate just yet. void Assembler::firstPass() { // Start at address 0 (not 1 as I had previously thought) currentAddress = 0; string nextop; (*insource) >> nextop; // Loop until we find the ENDPROG operation. for (;;) { // Record the current address in the label table. if (nextop == "DEFADDR") { int index; (*insource) >> index; labelTable[index] = currentAddress; (*insource) >> nextop; } // Record the associated value in the label table. else if (nextop == "DEFARG") { int index, value; (*insource) >> index >> value; labelTable[index] = value; (*insource) >> nextop; } // Stop when we find ENDPROG. else if (nextop == "ENDPROG") return; else if (nextop == "ARROW" || nextop == "ASSIGN" || nextop == "BAR" || nextop == "CONSTANT" || nextop == "FI" || nextop == "READ" || nextop == "WRITE") { // Skip one machine words. (*insource) >> nextop; (*insource) >> nextop; currentAddress += 2; } else if (nextop == "CALL" || nextop == "INDEX" || nextop == "PROC" || nextop == "PROG" || nextop == "VARIABLE") { // Skip two machine words. (*insource) >> nextop; (*insource) >> nextop; (*insource) >> nextop; currentAddress += 3; } else { // just get the next machine word. (*insource) >> nextop; currentAddress++; } } } // The second pass of the assembler. Here we actually translate operations // to their opcodes. void Assembler::secondPass() { string nextop; (*insource) >> nextop; // Loop until ENDPROG. for (;;) { if (nextop == "ADD") { (*outsource) << 0 << endl;; currentAddress++; } else if (nextop == "AND") { (*outsource) << 1 << endl;; currentAddress++; } else if (nextop == "ARROW") { (*outsource) << 2 << endl;; int temp; (*insource) >> temp; // Output the absolute jump address. (*outsource) << labelTable[temp] << endl; currentAddress += 2; } else if (nextop == "ASSIGN") { (*outsource) << 3 << endl; int temp; (*insource) >> temp; (*outsource) << temp << endl; currentAddress += 2; } else if (nextop == "BAR") { (*outsource) << 4 << endl; int temp; (*insource) >> temp; (*outsource) << labelTable[temp] << endl; currentAddress += 2; } else if (nextop == "CALL") { (*outsource) << 5 << endl; int temp; (*insource) >> temp; (*outsource) << temp << endl; (*insource) >> temp; (*outsource) << labelTable[temp] << endl; currentAddress += 3; } else if (nextop == "CONSTANT") { (*outsource) << 6 << endl; int temp; (*insource) >> temp; (*outsource) << temp << endl; currentAddress += 2; } else if (nextop == "DIVIDE") { (*outsource) << 7 << endl; currentAddress++; } else if (nextop == "ENDPROC") { (*outsource) << 8 << endl; currentAddress++; } else if (nextop == "ENDPROG") { (*outsource) << 9 << endl; break; } else if (nextop == "EQUAL") { (*outsource) << 10 << endl; currentAddress++; } else if (nextop == "FI") { (*outsource) << 11 << endl; int temp; (*insource) >> temp; (*outsource) << temp << endl; currentAddress += 2; } else if (nextop == "GREATER") { (*outsource) << 12 << endl; currentAddress++; } else if (nextop == "INDEX") { (*outsource) << 13 << endl; int temp; (*insource) >> temp; (*outsource) << temp << endl; (*insource) >> temp; (*outsource) << temp << endl; currentAddress += 3; } else if (nextop == "LESS") { (*outsource) << 14 << endl; currentAddress++; } else if (nextop == "MINUS") { (*outsource) << 15 << endl; currentAddress++; } else if (nextop == "MODULO") { (*outsource) << 16 << endl; currentAddress++; } else if (nextop == "MULTIPLY") { (*outsource) << 17 << endl; currentAddress++; } else if (nextop == "NOT") { (*outsource) << 18 << endl; currentAddress++; } else if (nextop == "OR") { (*outsource) << 19 << endl; currentAddress++; } else if (nextop == "PROC") { (*outsource) << 20 << endl; int temp; (*insource) >> temp; (*outsource) << labelTable[temp] << endl; (*insource) >> temp; (*outsource) << labelTable[temp] << endl; currentAddress += 3; } else if (nextop == "PROG") { (*outsource) << 21 << endl; int temp; (*insource) >> temp; (*outsource) << labelTable[temp] << endl; (*insource) >> temp; (*outsource) << labelTable[temp] << endl; currentAddress += 3; } else if (nextop == "READ") { (*outsource) << 22 << endl; int temp; (*insource) >> temp; (*outsource) << temp << endl; currentAddress += 2; } else if (nextop == "SUBTRACT") { (*outsource) << 23 << endl; currentAddress++; } else if (nextop == "VALUE") { (*outsource) << 24 << endl; currentAddress++; } else if (nextop == "VARIABLE") { (*outsource) << 25 << endl; int temp; (*insource) >> temp; (*outsource) << temp << endl; (*insource) >> temp; (*outsource) << temp << endl; currentAddress += 3; } else if (nextop == "WRITE") { (*outsource) << 26 << endl; int temp; (*insource) >> temp; (*outsource) << temp << endl; currentAddress += 2; } else if (nextop == "DEFADDR") { int temp; (*insource) >> temp; } else if (nextop == "DEFARG") { int temp1, temp2; (*insource) >> temp1 >> temp2; } else { // We should never see this message. cerr << "Assembler encountered an unknown operator: `" << nextop << "'. Bailing...\n"; exit(2); } (*insource) >> nextop; } }
versionzero/plc
src/assembler.cc
C++
gpl-2.0
6,134
/* * Copyright 2001 MontaVista Software Inc. * Author: Jun Sun, jsun@mvista.com or jsun@junsun.net * Copyright (c) 2003, 2004 Maciej W. Rozycki * * Common time service routines for MIPS machines. See * Documentation/mips/time.README. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/types.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/param.h> #include <linux/time.h> #include <linux/timex.h> #include <linux/smp.h> #include <linux/kernel_stat.h> #include <linux/spinlock.h> #include <linux/interrupt.h> #include <linux/module.h> #include <asm/bootinfo.h> #include <asm/cache.h> #include <asm/compiler.h> #include <asm/cpu.h> #include <asm/cpu-features.h> #include <asm/div64.h> #include <asm/sections.h> #include <asm/time.h> /* * The integer part of the number of usecs per jiffy is taken from tick, * but the fractional part is not recorded, so we calculate it using the * initial value of HZ. This aids systems where tick isn't really an * integer (e.g. for HZ = 128). */ #define USECS_PER_JIFFY TICK_SIZE #define USECS_PER_JIFFY_FRAC ((unsigned long)(u32)((1000000ULL << 32) / HZ)) #define TICK_SIZE (tick_nsec / 1000) /* * forward reference */ DEFINE_SPINLOCK(rtc_lock); /* * By default we provide the null RTC ops */ static unsigned long null_rtc_get_time(void) { return mktime(2013, 10, 29, 0, 0, 0); /* Oct-29-2013 */ } static int null_rtc_set_time(unsigned long sec) { return 0; } unsigned long (*rtc_mips_get_time)(void) = null_rtc_get_time; int (*rtc_mips_set_time)(unsigned long) = null_rtc_set_time; int (*rtc_mips_set_mmss)(unsigned long); /* how many counter cycles in a jiffy */ static unsigned long cycles_per_jiffy __read_mostly; /* expirelo is the count value for next CPU timer interrupt */ static unsigned int expirelo; /* * Null timer ack for systems not needing one (e.g. i8254). */ static void null_timer_ack(void) { /* nothing */ } /* * Null high precision timer functions for systems lacking one. */ static cycle_t null_hpt_read(void) { return 0; } /* * Timer ack for an R4k-compatible timer of a known frequency. */ static void c0_timer_ack(void) { unsigned int count; /* Ack this timer interrupt and set the next one. */ expirelo += cycles_per_jiffy; write_c0_compare(expirelo); /* Check to see if we have missed any timer interrupts. */ while (((count = read_c0_count()) - expirelo) < 0x7fffffff) { /* missed_timer_count++; */ expirelo = count + cycles_per_jiffy; write_c0_compare(expirelo); } } /* * High precision timer functions for a R4k-compatible timer. */ static cycle_t c0_hpt_read(void) { return read_c0_count(); } /* For use both as a high precision timer and an interrupt source. */ static void __init c0_hpt_timer_init(void) { expirelo = read_c0_count() + cycles_per_jiffy; write_c0_compare(expirelo); } int (*mips_timer_state)(void); void (*mips_timer_ack)(void); /* last time when xtime and rtc are sync'ed up */ static long last_rtc_update; /* * local_timer_interrupt() does profiling and process accounting * on a per-CPU basis. * * In UP mode, it is invoked from the (global) timer_interrupt. * * In SMP mode, it might invoked by per-CPU timer interrupt, or * a broadcasted inter-processor interrupt which itself is triggered * by the global timer interrupt. */ void local_timer_interrupt(int irq, void *dev_id) { profile_tick(CPU_PROFILING); update_process_times(user_mode(get_irq_regs())); } /* * High-level timer interrupt service routines. This function * is set as irqaction->handler and is invoked through do_IRQ. */ irqreturn_t timer_interrupt(int irq, void *dev_id) { write_seqlock(&xtime_lock); mips_timer_ack(); /* * call the generic timer interrupt handling */ do_timer(1); /* * If we have an externally synchronized Linux clock, then update * CMOS clock accordingly every ~11 minutes. rtc_mips_set_time() has to be * called as close as possible to 500 ms before the new second starts. */ if (ntp_synced() && xtime.tv_sec > last_rtc_update + 660 && (xtime.tv_nsec / 1000) >= 500000 - ((unsigned) TICK_SIZE) / 2 && (xtime.tv_nsec / 1000) <= 500000 + ((unsigned) TICK_SIZE) / 2) { if (rtc_mips_set_mmss(xtime.tv_sec) == 0) { last_rtc_update = xtime.tv_sec; } else { /* do it again in 60 s */ last_rtc_update = xtime.tv_sec - 600; } } write_sequnlock(&xtime_lock); /* * In UP mode, we call local_timer_interrupt() to do profiling * and process accouting. * * In SMP mode, local_timer_interrupt() is invoked by appropriate * low-level local timer interrupt handler. */ local_timer_interrupt(irq, dev_id); return IRQ_HANDLED; } int null_perf_irq(void) { return 0; } int (*perf_irq)(void) = null_perf_irq; EXPORT_SYMBOL(null_perf_irq); EXPORT_SYMBOL(perf_irq); /* * Timer interrupt */ int cp0_compare_irq; /* * Performance counter IRQ or -1 if shared with timer */ int cp0_perfcount_irq; EXPORT_SYMBOL_GPL(cp0_perfcount_irq); /* * Possibly handle a performance counter interrupt. * Return true if the timer interrupt should not be checked */ static inline int handle_perf_irq (int r2) { /* * The performance counter overflow interrupt may be shared with the * timer interrupt (cp0_perfcount_irq < 0). If it is and a * performance counter has overflowed (perf_irq() == IRQ_HANDLED) * and we can't reliably determine if a counter interrupt has also * happened (!r2) then don't check for a timer interrupt. */ return (cp0_perfcount_irq < 0) && perf_irq() == IRQ_HANDLED && !r2; } asmlinkage void ll_timer_interrupt(int irq) { int r2 = cpu_has_mips_r2; irq_enter(); kstat_this_cpu.irqs[irq]++; if (handle_perf_irq(r2)) goto out; if (r2 && ((read_c0_cause() & (1 << 30)) == 0)) goto out; timer_interrupt(irq, NULL); out: irq_exit(); } asmlinkage void ll_local_timer_interrupt(int irq) { irq_enter(); if (smp_processor_id() != 0) kstat_this_cpu.irqs[irq]++; /* we keep interrupt disabled all the time */ local_timer_interrupt(irq, NULL); irq_exit(); } /* * time_init() - it does the following things. * * 1) board_time_init() - * a) (optional) set up RTC routines, * b) (optional) calibrate and set the mips_hpt_frequency * (only needed if you intended to use cpu counter as timer interrupt * source) * 2) setup xtime based on rtc_mips_get_time(). * 3) calculate a couple of cached variables for later usage * 4) plat_timer_setup() - * a) (optional) over-write any choices made above by time_init(). * b) machine specific code should setup the timer irqaction. * c) enable the timer interrupt */ void (*board_time_init)(void); unsigned int mips_hpt_frequency; #ifdef CONFIG_MIPS_TC3262 unsigned int mips_hpt_frequency_true; unsigned long loops_per_jiffy_true = 0; extern unsigned long loops_per_jiffy; unsigned long udelay_val_true[NR_CPUS]; #endif static struct irqaction timer_irqaction = { .handler = timer_interrupt, .flags = IRQF_DISABLED | IRQF_PERCPU, .name = "timer", }; static unsigned int __init calibrate_hpt(void) { cycle_t frequency, hpt_start, hpt_end, hpt_count, hz; const int loops = HZ / 10; int log_2_loops = 0; int i; /* * We want to calibrate for 0.1s, but to avoid a 64-bit * division we round the number of loops up to the nearest * power of 2. */ while (loops > 1 << log_2_loops) log_2_loops++; i = 1 << log_2_loops; /* * Wait for a rising edge of the timer interrupt. */ while (mips_timer_state()); while (!mips_timer_state()); /* * Now see how many high precision timer ticks happen * during the calculated number of periods between timer * interrupts. */ hpt_start = clocksource_mips.read(); do { while (mips_timer_state()); while (!mips_timer_state()); } while (--i); hpt_end = clocksource_mips.read(); hpt_count = (hpt_end - hpt_start) & clocksource_mips.mask; hz = HZ; frequency = hpt_count * hz; return frequency >> log_2_loops; } struct clocksource clocksource_mips = { .name = "MIPS", .mask = CLOCKSOURCE_MASK(32), .flags = CLOCK_SOURCE_IS_CONTINUOUS, }; static void __init init_mips_clocksource(void) { u64 temp; u32 shift; if (!mips_hpt_frequency || clocksource_mips.read == null_hpt_read) return; /* Calclate a somewhat reasonable rating value */ clocksource_mips.rating = 200 + mips_hpt_frequency / 10000000; /* Find a shift value */ for (shift = 32; shift > 0; shift--) { temp = (u64) NSEC_PER_SEC << shift; do_div(temp, mips_hpt_frequency); if ((temp >> 32) == 0) break; } clocksource_mips.shift = shift; clocksource_mips.mult = (u32)temp; clocksource_register(&clocksource_mips); } void __init time_init(void) { if (board_time_init) board_time_init(); if (!rtc_mips_set_mmss) rtc_mips_set_mmss = rtc_mips_set_time; xtime.tv_sec = rtc_mips_get_time(); xtime.tv_nsec = 0; set_normalized_timespec(&wall_to_monotonic, -xtime.tv_sec, -xtime.tv_nsec); /* Choose appropriate high precision timer routines. */ if (!cpu_has_counter && !clocksource_mips.read) /* No high precision timer -- sorry. */ clocksource_mips.read = null_hpt_read; else if (!mips_hpt_frequency && !mips_timer_state) { /* A high precision timer of unknown frequency. */ if (!clocksource_mips.read) /* No external high precision timer -- use R4k. */ clocksource_mips.read = c0_hpt_read; } else { /* We know counter frequency. Or we can get it. */ if (!clocksource_mips.read) { /* No external high precision timer -- use R4k. */ clocksource_mips.read = c0_hpt_read; if (!mips_timer_state) { /* No external timer interrupt -- use R4k. */ mips_timer_ack = c0_timer_ack; /* Calculate cache parameters. */ cycles_per_jiffy = (mips_hpt_frequency + HZ / 2) / HZ; /* * This sets up the high precision * timer for the first interrupt. */ c0_hpt_timer_init(); } } if (!mips_hpt_frequency) mips_hpt_frequency = calibrate_hpt(); #ifdef CONFIG_MIPS_TC3262 mips_hpt_frequency_true = mips_hpt_frequency; #endif /* Report the high precision timer rate for a reference. */ printk("Using %u.%03u MHz high precision timer.\n", ((mips_hpt_frequency + 500) / 1000) / 1000, ((mips_hpt_frequency + 500) / 1000) % 1000); } if (!mips_timer_ack) /* No timer interrupt ack (e.g. i8254). */ mips_timer_ack = null_timer_ack; /* * Call board specific timer interrupt setup. * * this pointer must be setup in machine setup routine. * * Even if a machine chooses to use a low-level timer interrupt, * it still needs to setup the timer_irqaction. * In that case, it might be better to set timer_irqaction.handler * to be NULL function so that we are sure the high-level code * is not invoked accidentally. */ plat_timer_setup(&timer_irqaction); init_mips_clocksource(); } #define FEBRUARY 2 #define STARTOFTIME 1970 #define SECDAY 86400L #define SECYR (SECDAY * 365) #define leapyear(y) ((!((y) % 4) && ((y) % 100)) || !((y) % 400)) #define days_in_year(y) (leapyear(y) ? 366 : 365) #define days_in_month(m) (month_days[(m) - 1]) static int month_days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; void to_tm(unsigned long tim, struct rtc_time *tm) { long hms, day, gday; int i; gday = day = tim / SECDAY; hms = tim % SECDAY; /* Hours, minutes, seconds are easy */ tm->tm_hour = hms / 3600; tm->tm_min = (hms % 3600) / 60; tm->tm_sec = (hms % 3600) % 60; /* Number of years in days */ for (i = STARTOFTIME; day >= days_in_year(i); i++) day -= days_in_year(i); tm->tm_year = i; /* Number of months in days left */ if (leapyear(tm->tm_year)) days_in_month(FEBRUARY) = 29; for (i = 1; day >= days_in_month(i); i++) day -= days_in_month(i); days_in_month(FEBRUARY) = 28; tm->tm_mon = i - 1; /* tm_mon starts from 0 to 11 */ /* Days are what is left over (+1) from all that. */ tm->tm_mday = day + 1; /* * Determine the day of week */ tm->tm_wday = (gday + 4) % 7; /* 1970/1/1 was Thursday */ } //#define DBG #ifdef CONFIG_MIPS_TC3262 int reset_time_value(int time_shift){ u64 temp; u32 shift; int i; unsigned int cpu; #ifdef DBG printk("cycles_per_jiffy %x\n",cycles_per_jiffy); printk("true mips_hpt_frequency %x shift %d\n",mips_hpt_frequency_true,time_shift); #endif if(loops_per_jiffy_true == 0){ //save correct value if(loops_per_jiffy == (1<<12)){ printk("init not over\n"); return -1; }else{ loops_per_jiffy_true = loops_per_jiffy; for(i=0;i<NR_CPUS;i++){ udelay_val_true[i] = cpu_data[i].udelay_val; } } } #ifdef DBG printk("true loops_per_jiffie %x loops_per_jiffie %x\n", loops_per_jiffy_true, loops_per_jiffy); #endif local_irq_disable(); mips_hpt_frequency = (mips_hpt_frequency_true>>(time_shift)); #ifdef DBG printk("After mips_hpt_frequency %x \n",mips_hpt_frequency); #endif /* Calculate cache parameters. */ cycles_per_jiffy = (mips_hpt_frequency + HZ / 2) / HZ; #ifdef DBG printk("cycles_per_jiffy %x\n",cycles_per_jiffy); #endif /* Calclate a somewhat reasonable rating value */ clocksource_mips.rating = 200 + mips_hpt_frequency / 10000000; /* Find a shift value */ for (shift = 32; shift > 0; shift--) { temp = (u64) NSEC_PER_SEC << shift; do_div(temp, mips_hpt_frequency); if ((temp >> 32) == 0) break; } clocksource_mips.shift = shift; clocksource_mips.mult = (u32)temp; //about date clocksource_calculate_interval(&clocksource_mips, NTP_INTERVAL_LENGTH); clocksource_change_rating(&clocksource_mips, clocksource_mips.rating); #ifdef DBG printk("clocksource_mips.rate %x shift %x mult %x cycle_interval %x\n",clocksource_mips.rating,clocksource_mips.shift,clocksource_mips.mult,clocksource_mips.cycle_interval); #endif //about delay for(i=0;i<NR_CPUS;i++){ cpu_data[i].udelay_val = (udelay_val_true[i] >> (time_shift)); } loops_per_jiffy = loops_per_jiffy_true >> (time_shift) ; local_irq_enable(); return 0; } EXPORT_SYMBOL(reset_time_value); #endif EXPORT_SYMBOL(rtc_lock); EXPORT_SYMBOL(to_tm); EXPORT_SYMBOL(rtc_mips_set_time); EXPORT_SYMBOL(rtc_mips_get_time);
ndmsystems/linux-2.6.22-tc
arch/mips/kernel/time.c
C
gpl-2.0
14,358
#!/bin/sh proj=$1 if [ "$proj" == "" ]; then echo oracc-project-runtime.sh: must give project on command line exit 1 fi if [ -w $ORACC_HOME/$proj/00any ]; then destdir=$ORACC_HOME/$proj/00any else destdir=$ORACC/00any fi if [ ! -w $destdir ]; then echo oracc-project-runtime.sh: cannot write to $destdir. Stop exit 1 fi fproj=`/bin/echo -n $proj | tr / -` echo :$fproj: cd $ORACC tar --exclude www/$proj/estindex -Jcf $destdir/$fproj-runtime.tar.xz \ agg/projects/images/$proj.png \ bld/$proj/[PQX][0-9][0-9][0-9] \ pub/$proj \ xml/$proj \ www/$proj
oracc/oracc
misc/admin/oracc-project-runtime.sh
Shell
gpl-2.0
594
<?php /** * @package Joomla.Platform * @subpackage Database * * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * MySQLi import driver. * * @since 11.1 */ class JDatabaseImporterMysqli extends JDatabaseImporter { /** * Checks if all data and options are in order prior to exporting. * * @return JDatabaseImporterMysqli Method supports chaining. * * @since 11.1 * @throws Exception if an error is encountered. */ public function check() { // Check if the db connector has been set. if (!($this->db instanceof JDatabaseDriverMysqli)) { throw new Exception('JPLATFORM_ERROR_DATABASE_CONNECTOR_WRONG_TYPE'); } // Check if the tables have been specified. if (empty($this->from)) { throw new Exception('JPLATFORM_ERROR_NO_TABLES_SPECIFIED'); } return $this; } /** * Get the SQL syntax to add a table. * * @param SimpleXMLElement $table The table information. * * @return string * * @since 11.1 * @throws RuntimeException */ protected function xmlToCreate(SimpleXMLElement $table) { $existingTables = $this->db->getTableList(); $tableName = (string) $table['name']; if (in_array($tableName, $existingTables)) { throw new RuntimeException('The table you are trying to create already exists'); } $createTableStatement = 'CREATE TABLE ' . $this->db->quoteName($tableName) . ' ('; foreach ($table->xpath('field') as $field) { $createTableStatement .= $this->getColumnSQL($field) . ', '; } $newLookup = $this->getKeyLookup($table->xpath('key')); // Loop through each key in the new structure. foreach ($newLookup as $key) { $createTableStatement .= $this->getKeySQL($key) . ', '; } // Remove the comma after the last key $createTableStatement = rtrim($createTableStatement, ', '); $createTableStatement .= ')'; return $createTableStatement; } /** * Get the SQL syntax to add a column. * * @param string $table The table name. * @param SimpleXMLElement $field The XML field definition. * * @return string * * @since 11.1 */ protected function getAddColumnSql($table, SimpleXMLElement $field) { return 'ALTER TABLE ' . $this->db->quoteName($table) . ' ADD COLUMN ' . $this->getColumnSql($field); } /** * Get the SQL syntax to add a key. * * @param string $table The table name. * @param array $keys An array of the fields pertaining to this key. * * @return string * * @since 11.1 */ protected function getAddKeySql($table, $keys) { return 'ALTER TABLE ' . $this->db->quoteName($table) . ' ADD ' . $this->getKeySql($keys); } /** * Get alters for table if there is a difference. * * @param SimpleXMLElement $structure The XML structure pf the table. * * @return array * * @since 11.1 */ protected function getAlterTableSql(SimpleXMLElement $structure) { $table = $this->getRealTableName($structure['name']); $oldFields = $this->db->getTableColumns($table); $oldKeys = $this->db->getTableKeys($table); $alters = array(); // Get the fields and keys from the XML that we are aiming for. $newFields = $structure->xpath('field'); $newKeys = $structure->xpath('key'); // Loop through each field in the new structure. foreach ($newFields as $field) { $fName = (string) $field['Field']; if (isset($oldFields[$fName])) { // The field exists, check it's the same. $column = $oldFields[$fName]; // Test whether there is a change. $change = ((string) $field['Type'] != $column->Type) || ((string) $field['Null'] != $column->Null) || ((string) $field['Default'] != $column->Default) || ((string) $field['Extra'] != $column->Extra); if ($change) { $alters[] = $this->getChangeColumnSql($table, $field); } // Unset this field so that what we have left are fields that need to be removed. unset($oldFields[$fName]); } else { // The field is new. $alters[] = $this->getAddColumnSql($table, $field); } } // Any columns left are orphans foreach ($oldFields as $name => $column) { // Delete the column. $alters[] = $this->getDropColumnSql($table, $name); } // Get the lookups for the old and new keys. $oldLookup = $this->getKeyLookup($oldKeys); $newLookup = $this->getKeyLookup($newKeys); // Loop through each key in the new structure. foreach ($newLookup as $name => $keys) { // Check if there are keys on this field in the existing table. if (isset($oldLookup[$name])) { $same = true; $newCount = count($newLookup[$name]); $oldCount = count($oldLookup[$name]); // There is a key on this field in the old and new tables. Are they the same? if ($newCount == $oldCount) { // Need to loop through each key and do a fine grained check. for ($i = 0; $i < $newCount; $i++) { $same = (((string) $newLookup[$name][$i]['Non_unique'] == $oldLookup[$name][$i]->Non_unique) && ((string) $newLookup[$name][$i]['Column_name'] == $oldLookup[$name][$i]->Column_name) && ((string) $newLookup[$name][$i]['Seq_in_index'] == $oldLookup[$name][$i]->Seq_in_index) && ((string) $newLookup[$name][$i]['Collation'] == $oldLookup[$name][$i]->Collation) && ((string) $newLookup[$name][$i]['Index_type'] == $oldLookup[$name][$i]->Index_type)); /* Debug. echo '<pre>'; echo '<br>Non_unique: '. ((string) $newLookup[$name][$i]['Non_unique'] == $oldLookup[$name][$i]->Non_unique ? 'Pass' : 'Fail').' '. (string) $newLookup[$name][$i]['Non_unique'].' vs '.$oldLookup[$name][$i]->Non_unique; echo '<br>Column_name: '. ((string) $newLookup[$name][$i]['Column_name'] == $oldLookup[$name][$i]->Column_name ? 'Pass' : 'Fail').' '. (string) $newLookup[$name][$i]['Column_name'].' vs '.$oldLookup[$name][$i]->Column_name; echo '<br>Seq_in_index: '. ((string) $newLookup[$name][$i]['Seq_in_index'] == $oldLookup[$name][$i]->Seq_in_index ? 'Pass' : 'Fail').' '. (string) $newLookup[$name][$i]['Seq_in_index'].' vs '.$oldLookup[$name][$i]->Seq_in_index; echo '<br>Collation: '. ((string) $newLookup[$name][$i]['Collation'] == $oldLookup[$name][$i]->Collation ? 'Pass' : 'Fail').' '. (string) $newLookup[$name][$i]['Collation'].' vs '.$oldLookup[$name][$i]->Collation; echo '<br>Index_type: '. ((string) $newLookup[$name][$i]['Index_type'] == $oldLookup[$name][$i]->Index_type ? 'Pass' : 'Fail').' '. (string) $newLookup[$name][$i]['Index_type'].' vs '.$oldLookup[$name][$i]->Index_type; echo '<br>Same = '.($same ? 'true' : 'false'); echo '</pre>'; */ if (!$same) { // Break out of the loop. No need to check further. break; } } } else { // Count is different, just drop and add. $same = false; } if (!$same) { $alters[] = $this->getDropKeySql($table, $name); $alters[] = $this->getAddKeySql($table, $keys); } // Unset this field so that what we have left are fields that need to be removed. unset($oldLookup[$name]); } else { // This is a new key. $alters[] = $this->getAddKeySql($table, $keys); } } // Any keys left are orphans. foreach ($oldLookup as $name => $keys) { if (strtoupper($name) == 'PRIMARY') { $alters[] = $this->getDropPrimaryKeySql($table); } else { $alters[] = $this->getDropKeySql($table, $name); } } return $alters; } /** * Get the syntax to alter a column. * * @param string $table The name of the database table to alter. * @param SimpleXMLElement $field The XML definition for the field. * * @return string * * @since 11.1 */ protected function getChangeColumnSql($table, SimpleXMLElement $field) { return 'ALTER TABLE ' . $this->db->quoteName($table) . ' CHANGE COLUMN ' . $this->db->quoteName((string) $field['Field']) . ' ' . $this->getColumnSql($field); } /** * Get the SQL syntax for a single column that would be included in a table create or alter statement. * * @param SimpleXMLElement $field The XML field definition. * * @return string * * @since 11.1 */ protected function getColumnSql(SimpleXMLElement $field) { // TODO Incorporate into parent class and use $this. $blobs = array('text', 'smalltext', 'mediumtext', 'largetext'); $fName = (string) $field['Field']; $fType = (string) $field['Type']; $fNull = (string) $field['Null']; $fDefault = isset($field['Default']) ? (string) $field['Default'] : null; $fExtra = (string) $field['Extra']; $query = $this->db->quoteName($fName) . ' ' . $fType; if ($fNull == 'NO') { if (in_array($fType, $blobs) || $fDefault === null) { $query .= ' NOT NULL'; } else { // TODO Don't quote numeric values. $query .= ' NOT NULL DEFAULT ' . $this->db->quote($fDefault); } } else { if ($fDefault === null) { $query .= ' DEFAULT NULL'; } else { // TODO Don't quote numeric values. $query .= ' DEFAULT ' . $this->db->quote($fDefault); } } if ($fExtra) { $query .= ' ' . strtoupper($fExtra); } return $query; } /** * Get the SQL syntax to drop a key. * * @param string $table The table name. * @param string $name The name of the key to drop. * * @return string * * @since 11.1 */ protected function getDropKeySql($table, $name) { return 'ALTER TABLE ' . $this->db->quoteName($table) . ' DROP KEY ' . $this->db->quoteName($name); } /** * Get the SQL syntax to drop a key. * * @param string $table The table name. * * @return string * * @since 11.1 */ protected function getDropPrimaryKeySql($table) { return 'ALTER TABLE ' . $this->db->quoteName($table) . ' DROP PRIMARY KEY'; } /** * Get the details list of keys for a table. * * @param array $keys An array of objects that comprise the keys for the table. * * @return array The lookup array. array({key name} => array(object, ...)) * * @since 11.1 * @throws Exception */ protected function getKeyLookup($keys) { // First pass, create a lookup of the keys. $lookup = array(); foreach ($keys as $key) { if ($key instanceof SimpleXMLElement) { $kName = (string) $key['Key_name']; } else { $kName = $key->Key_name; } if (empty($lookup[$kName])) { $lookup[$kName] = array(); } $lookup[$kName][] = $key; } return $lookup; } /** * Get the SQL syntax for a key. * * @param array $columns An array of SimpleXMLElement objects comprising the key. * * @return string * * @since 11.1 */ protected function getKeySql($columns) { // TODO Error checking on array and element types. $kNonUnique = (string) $columns[0]['Non_unique']; $kName = (string) $columns[0]['Key_name']; $kColumn = (string) $columns[0]['Column_name']; $prefix = ''; if ($kName == 'PRIMARY') { $prefix = 'PRIMARY '; } elseif ($kNonUnique == 0) { $prefix = 'UNIQUE '; } $nColumns = count($columns); $kColumns = array(); if ($nColumns == 1) { $kColumns[] = $this->db->quoteName($kColumn); } else { foreach ($columns as $column) { $kColumns[] = (string) $column['Column_name']; } } $query = $prefix . 'KEY ' . ($kName != 'PRIMARY' ? $this->db->quoteName($kName) : '') . ' (' . implode(',', $kColumns) . ')'; return $query; } }
ylahav/joomla-cms
libraries/joomla/database/importer/mysqli.php
PHP
gpl-2.0
11,690
// cmdline_extract_cache_subset.cc // // Copyright (C) 2008-2010 Daniel Burrows // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // Local includes: #include "cmdline_extract_cache_subset.h" #include "cmdline_util.h" #include "terminal.h" #include "text_progress.h" #include <aptitude.h> #include <generic/apt/apt.h> #include <generic/apt/dump_packages.h> #include <generic/apt/matching/match.h> #include <generic/apt/matching/parse.h> #include <generic/apt/matching/pattern.h> #include <generic/util/util.h> // System includes: #include <apt-pkg/error.h> #include <apt-pkg/progress.h> #include <stdio.h> #include <memory> using aptitude::cmdline::create_terminal; using aptitude::cmdline::make_text_progress; using aptitude::cmdline::terminal_io; namespace aptitude { namespace cmdline { int extract_cache_subset(int argc, char *argv[]) { if(argc < 2) { fprintf(stderr, _("extract-cache-entries: at least one argument is required (the directory\nto which to write files).\n")); return -1; } const std::shared_ptr<terminal_io> term = create_terminal(); std::string out_dir = argv[1]; std::shared_ptr<OpProgress> progress = make_text_progress(false, term, term, term); apt_init(progress.get(), true); if(_error->PendingError()) { _error->DumpErrors(); return -1; } bool ok = true; std::set<pkgCache::PkgIterator> packages; if(argc == 2) { for(pkgCache::PkgIterator pIt = (*apt_cache_file)->PkgBegin(); !pIt.end(); ++pIt) packages.insert(pIt); } else { for(int i = 2; i < argc; ++i) { std::string arg(argv[i]); if(!aptitude::matching::is_pattern(arg)) { pkgCache::PkgIterator pIt = (*apt_cache_file)->FindPkg(arg); if(pIt.end()) { std::cerr << ssprintf(_("No such package \"%s\""), arg.c_str()) << std::endl; ok = false; } else packages.insert(pIt); } else { using namespace aptitude::matching; using cwidget::util::ref_ptr; ref_ptr<pattern> p = parse(arg); if(p.valid()) { _error->DumpErrors(); } else { std::vector<std::pair<pkgCache::PkgIterator, ref_ptr<structural_match> > > matches; ref_ptr<search_cache> search_info(search_cache::create()); search(p, search_info, matches, *apt_cache_file, *apt_package_records); for(std::vector<std::pair<pkgCache::PkgIterator, ref_ptr<structural_match> > >::const_iterator it = matches.begin(); it != matches.end(); ++it) packages.insert(it->first); } } } } if(!ok) return 2; if(packages.size() == 0) { printf(_("No packages were selected by the given search pattern; nothing to do.\n")); return 0; } aptitude::apt::make_truncated_state_copy(out_dir, packages); bool copy_ok = !_error->PendingError(); _error->DumpErrors(); return copy_ok ? 0 : 1; } } }
iamduyu/aptitude
src/cmdline/cmdline_extract_cache_subset.cc
C++
gpl-2.0
3,749
/* * File: main.c * Purpose: Core game initialisation for UNIX (and other) machines * * Copyright (c) 1997 Ben Harrison, and others * * This work is free software; you can redistribute it and/or modify it * under the terms of either: * * a) the GNU General Public License as published by the Free Software * Foundation, version 2, or * * b) the "Angband licence": * This software may be copied and distributed for educational, research, * and not for profit purposes provided that this copyright and statement * are included in all such copies. Other copyrights may also apply. */ #include "angband.h" /* * Some machines have a "main()" function in their "main-xxx.c" file, * all the others use this file for their "main()" function. */ #if defined(WIN32_CONSOLE_MODE) \ || (!defined(WINDOWS) && !defined(RISCOS)) \ || defined(USE_SDL) #include "main.h" /* * List of the available modules in the order they are tried. */ static const struct module modules[] = { #ifdef USE_SDL { "sdl", help_sdl, init_sdl }, #endif /* USE_SDL */ #ifdef USE_GCU { "gcu", help_gcu, init_gcu }, #endif /* USE_GCU */ }; #ifdef USE_SOUND /* * List of sound modules in the order they should be tried. */ static const struct module sound_modules[] = { #ifdef SOUND_SDL { "sdl", "SDL_mixer sound module", init_sound_sdl }, #endif /* SOUND_SDL */ { "dummy", "Dummy module", NULL }, }; #endif /* * A hook for "quit()". * * Close down, then fall back into "quit()". */ static void quit_hook(cptr s) { int j; /* Unused parameter */ (void)s; /* Scan windows */ for (j = ANGBAND_TERM_MAX - 1; j >= 0; j--) { /* Unused */ if (!angband_term[j]) continue; /* Nuke it */ term_nuke(angband_term[j]); } } /* * SDL needs a look-in */ #ifdef USE_SDL # include "SDL.h" #endif /* * Initialize and verify the file paths, and the score file. * * Use the ANGBAND_PATH environment var if possible, else use * DEFAULT_PATH, and in either case, branch off appropriately. * * First, we'll look for the ANGBAND_PATH environment variable, * and then look for the files in there. If that doesn't work, * we'll try the DEFAULT_PATH constants. So be sure that one of * these two things works... * * We must ensure that the path ends with "PATH_SEP" if needed, * since the "init_file_paths()" function will simply append the * relevant "sub-directory names" to the given path. * * Make sure that the path doesn't overflow the buffer. We have * to leave enough space for the path separator, directory, and * filenames. */ static void init_stuff(void) { char configpath[512]; char libpath[512]; char datapath[512]; /* Use the angband_path, or a default */ my_strcpy(configpath, DEFAULT_CONFIG_PATH, sizeof(configpath)); my_strcpy(libpath, DEFAULT_LIB_PATH, sizeof(libpath)); my_strcpy(datapath, DEFAULT_DATA_PATH, sizeof(datapath)); /* Make sure they're terminated */ configpath[511] = '\0'; libpath[511] = '\0'; datapath[511] = '\0'; /* Hack -- Add a path separator (only if needed) */ if (!suffix(configpath, PATH_SEP)) my_strcat(configpath, PATH_SEP, sizeof(configpath)); if (!suffix(libpath, PATH_SEP)) my_strcat(libpath, PATH_SEP, sizeof(libpath)); if (!suffix(datapath, PATH_SEP)) my_strcat(datapath, PATH_SEP, sizeof(datapath)); /* Initialize */ init_file_paths(configpath, libpath, datapath); } /* * Handle a "-d<what>=<path>" option * * The "<what>" can be any string starting with the same letter as the * name of a subdirectory of the "lib" folder (i.e. "i" or "info"). * * The "<path>" can be any legal path for the given system, and should * not end in any special path separator (i.e. "/tmp" or "~/.ang-info"). */ static void change_path(cptr info) { if (!info || !info[0]) quit_fmt("Try '-d<path>'.", info); string_free(ANGBAND_DIR_USER); ANGBAND_DIR_USER = string_make(info); } #ifdef SET_UID /* * Find a default user name from the system. */ static void user_name(char *buf, size_t len, int id) { struct passwd *pw = getpwuid(id); /* Default to PLAYER */ if (!pw) { my_strcpy(buf, "PLAYER", len); return; } /* Capitalise and copy */ strnfmt(buf, len, "%^s", pw->pw_name); } #endif /* SET_UID */ static bool new_game; /* * Pass the appropriate "Initialisation screen" command to the game, * getting user input if needed. */ static errr get_init_cmd(void) { /* Wait for response */ pause_line(Term->hgt - 1); if (new_game) cmd_insert(CMD_NEWGAME); else /* This might be modified to supply the filename in future. */ cmd_insert(CMD_LOADFILE); /* Everything's OK. */ return 0; } /* Command dispatcher for curses, etc builds */ static errr default_get_cmd(cmd_context context, bool wait) { if (context == CMD_INIT) return get_init_cmd(); else return textui_get_cmd(context, wait); } /* * Simple "main" function for multiple platforms. * * Note the special "--" option which terminates the processing of * standard options. All non-standard options (if any) are passed * directly to the "init_xxx()" function. */ int main(int argc, char *argv[]) { int i; bool done = FALSE; const char *mstr = NULL; bool args = TRUE; game_mode = 0; /* Save the "program name" XXX XXX XXX */ argv0 = argv[0]; #ifdef SET_UID /* Default permissions on files */ (void)umask(022); #endif /* SET_UID */ /* Get the file paths */ init_stuff(); #ifdef SET_UID /* Get the user id */ player_uid = getuid(); /* Save the effective GID for later recall */ player_egid = getegid(); #endif /* SET_UID */ /* Drop permissions */ safe_setuid_drop(); #ifdef SET_UID /* Get the "user name" as a default player name */ user_name(op_ptr->full_name, sizeof(op_ptr->full_name), player_uid); /* Create any missing directories */ create_needed_dirs(); #endif /* SET_UID */ /* Process the command line arguments */ for (i = 1; args && (i < argc); i++) { cptr arg = argv[i]; /* Require proper options */ if (*arg++ != '-') goto usage; /* Analyze option */ switch (*arg++) { case 'N': case 'n': { new_game = TRUE; break; } case 'W': case 'w': { arg_wizard = TRUE; break; } case 'R': case 'r': { arg_rebalance = TRUE; break; } case 'G': case 'g': { /* Default graphics tile */ arg_graphics = GRAPHICS_ADAM_BOLT; break; } case 'u': case 'U': { if (!*arg) goto usage; /* Get the savefile name */ my_strcpy(op_ptr->full_name, arg, sizeof(op_ptr->full_name)); continue; } case 'm': case 'M': { if (!*arg) goto usage; mstr = arg; continue; } case 's': case 'S': { if (!*arg) goto usage; switch (*arg) { case 'm': case 'M': { game_mode = GAME_NPPMORIA; break; } case 'a': case 'A': { game_mode = GAME_NPPANGBAND; break; } } continue; } case 'd': case 'D': { change_path(arg); continue; } case '-': { argv[i] = argv[0]; argc = argc - i; argv = argv + i; args = FALSE; break; } default: usage: { /* Dump usage information */ puts("Usage: angband [options] [-- subopts]"); puts(" -n Start a new character"); puts(" -L Load a new-format save file"); puts(" -s<typ> Use a particular game style: ang or mor"); puts(" -w Resurrect dead character (marks savefile)"); puts(" -r Rebalance monsters if monster.raw is absent"); puts(" -g Request graphics mode"); puts(" -u<who> Use your <who> savefile"); puts(" -d<path> Store pref files and screendumps in <path>"); puts(" -m<sys> Use module <sys>, where <sys> can be:"); /* Print the name and help for each available module */ for (i = 0; i < (int)N_ELEMENTS(modules); i++) { printf(" %s %s\n", modules[i].name, modules[i].help); } /* Actually abort the process */ quit(NULL); } } if (*arg) goto usage; } /* Hack -- Forget standard args */ if (args) { argc = 1; argv[1] = NULL; } /* Try the modules in the order specified by modules[] */ for (i = 0; i < (int)N_ELEMENTS(modules); i++) { /* User requested a specific module? */ if (!mstr || (streq(mstr, modules[i].name))) { if (0 == modules[i].init(argc, argv)) { ANGBAND_SYS = modules[i].name; done = TRUE; break; } } } /* Make sure we have a display! */ if (!done) quit("Unable to prepare any 'display module'!"); /* Process the player name */ process_player_name(TRUE); /* Install "quit" hook */ quit_aux = quit_hook; #ifdef USE_SOUND /* Try the modules in the order specified by sound_modules[] */ for (i = 0; i < (int)N_ELEMENTS(sound_modules) - 1; i++) { if (0 == sound_modules[i].init(argc, argv)) break; } #endif /* Catch nasty signals */ signals_init(); /* Set up the command hook */ cmd_get_hook = default_get_cmd; /* Set up the display handlers and things. */ init_display(); /* Play the game */ play_game(); /* Free resources */ cleanup_angband(); /* Quit */ quit(NULL); /* Exit */ return (0); } #endif /* !defined(MACINTOSH) && !defined(WINDOWS) && !defined(RISCOS) */
nppangband/NPPAngband
src/main.c
C
gpl-2.0
9,339
class CreateMaterials < ActiveRecord::Migration def change create_table :materials do |t| t.string :name t.decimal :price_per_m2 t.timestamps null: false end end end
ProjNaRok1516/ruby-www
db/migrate/20160105130157_create_materials.rb
Ruby
gpl-2.0
197
/** * @file qq.c * * purple * * Purple is the legal property of its developers, whose names are too numerous * to list here. Please refer to the COPYRIGHT file distributed with this * source distribution. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA */ #include "internal.h" #include "accountopt.h" #include "debug.h" #include "notify.h" #include "prefs.h" #include "prpl.h" #include "privacy.h" #include "request.h" #include "roomlist.h" #include "server.h" #include "util.h" #include "buddy_info.h" #include "buddy_memo.h" #include "buddy_opt.h" #include "buddy_list.h" #include "char_conv.h" #include "group.h" #include "group_im.h" #include "group_info.h" #include "group_join.h" #include "group_opt.h" #include "group_internal.h" #include "qq_define.h" #include "im.h" #include "qq_process.h" #include "qq_base.h" #include "packet_parse.h" #include "qq.h" #include "qq_network.h" #include "send_file.h" #include "utils.h" #include "version.h" #define OPENQ_VERSION "0.3.2-p20" static GList *server_list_build(gchar select) { GList *list = NULL; if ( select == 'T' || select == 'A') { list = g_list_append(list, "tcpconn.tencent.com:8000"); list = g_list_append(list, "tcpconn2.tencent.com:8000"); list = g_list_append(list, "tcpconn3.tencent.com:8000"); list = g_list_append(list, "tcpconn4.tencent.com:8000"); list = g_list_append(list, "tcpconn5.tencent.com:8000"); list = g_list_append(list, "tcpconn6.tencent.com:8000"); } if ( select == 'U' || select == 'A') { list = g_list_append(list, "sz.tencent.com:8000"); list = g_list_append(list, "sz2.tencent.com:8000"); list = g_list_append(list, "sz3.tencent.com:8000"); list = g_list_append(list, "sz4.tencent.com:8000"); list = g_list_append(list, "sz5.tencent.com:8000"); list = g_list_append(list, "sz6.tencent.com:8000"); list = g_list_append(list, "sz7.tencent.com:8000"); list = g_list_append(list, "sz8.tencent.com:8000"); list = g_list_append(list, "sz9.tencent.com:8000"); } return list; } static void server_list_create(PurpleAccount *account) { PurpleConnection *gc; qq_data *qd; PurpleProxyInfo *gpi; const gchar *custom_server; gc = purple_account_get_connection(account); g_return_if_fail(gc != NULL && gc->proto_data != NULL); qd = gc->proto_data; gpi = purple_proxy_get_setup(account); qd->use_tcp = purple_account_get_bool(account, "use_tcp", TRUE); custom_server = purple_account_get_string(account, "server", NULL); if (custom_server != NULL) { purple_debug_info("QQ", "Select server '%s'\n", custom_server); if (*custom_server != '\0' && g_ascii_strcasecmp(custom_server, "auto") != 0) { qd->servers = g_list_append(qd->servers, g_strdup(custom_server)); return; } } if (qd->use_tcp) { qd->servers = server_list_build('T'); return; } qd->servers = server_list_build('U'); } static void server_list_remove_all(qq_data *qd) { g_return_if_fail(qd != NULL); purple_debug_info("QQ", "free server list\n"); g_list_free(qd->servers); qd->curr_server = NULL; } static void qq_login(PurpleAccount *account) { PurpleConnection *gc; qq_data *qd; PurplePresence *presence; const gchar *version_str; g_return_if_fail(account != NULL); gc = purple_account_get_connection(account); g_return_if_fail(gc != NULL); gc->flags |= PURPLE_CONNECTION_HTML | PURPLE_CONNECTION_NO_BGCOLOR | PURPLE_CONNECTION_AUTO_RESP; qd = g_new0(qq_data, 1); memset(qd, 0, sizeof(qq_data)); qd->gc = gc; gc->proto_data = qd; presence = purple_account_get_presence(account); if(purple_presence_is_status_primitive_active(presence, PURPLE_STATUS_INVISIBLE)) { qd->login_mode = QQ_LOGIN_MODE_HIDDEN; } else if(purple_presence_is_status_primitive_active(presence, PURPLE_STATUS_AWAY) || purple_presence_is_status_primitive_active(presence, PURPLE_STATUS_EXTENDED_AWAY)) { qd->login_mode = QQ_LOGIN_MODE_AWAY; } else { qd->login_mode = QQ_LOGIN_MODE_NORMAL; } server_list_create(account); purple_debug_info("QQ", "Server list has %d\n", g_list_length(qd->servers)); version_str = purple_account_get_string(account, "client_version", NULL); qd->client_tag = QQ_CLIENT_0D55; /* set default as QQ2005 */ qd->client_version = 2005; if (version_str != NULL && strlen(version_str) != 0) { if (strcmp(version_str, "qq2007") == 0) { qd->client_tag = QQ_CLIENT_111D; qd->client_version = 2007; } else if (strcmp(version_str, "qq2008") == 0) { qd->client_tag = QQ_CLIENT_115B; qd->client_version = 2008; } } qd->is_show_notice = purple_account_get_bool(account, "show_notice", TRUE); qd->is_show_news = purple_account_get_bool(account, "show_news", TRUE); qd->is_show_chat = purple_account_get_bool(account, "show_chat", TRUE); qd->resend_times = purple_prefs_get_int("/plugins/prpl/qq/resend_times"); if (qd->resend_times <= 1) qd->itv_config.resend = 4; qd->itv_config.resend = purple_prefs_get_int("/plugins/prpl/qq/resend_interval"); if (qd->itv_config.resend <= 0) qd->itv_config.resend = 3; purple_debug_info("QQ", "Resend interval %d, retries %d\n", qd->itv_config.resend, qd->resend_times); qd->itv_config.keep_alive = purple_account_get_int(account, "keep_alive_interval", 60); if (qd->itv_config.keep_alive < 30) qd->itv_config.keep_alive = 30; qd->itv_config.keep_alive /= qd->itv_config.resend; qd->itv_count.keep_alive = qd->itv_config.keep_alive; qd->itv_config.update = purple_account_get_int(account, "update_interval", 300); if (qd->itv_config.update > 0) { if (qd->itv_config.update < qd->itv_config.keep_alive) { qd->itv_config.update = qd->itv_config.keep_alive; } qd->itv_config.update /= qd->itv_config.resend; qd->itv_count.update = qd->itv_config.update; } else { qd->itv_config.update = 0; } qd->connect_watcher = purple_timeout_add_seconds(0, qq_connect_later, gc); } /* clean up the given QQ connection and free all resources */ static void qq_close(PurpleConnection *gc) { qq_data *qd; g_return_if_fail(gc != NULL && gc->proto_data); qd = gc->proto_data; if (qd->check_watcher > 0) { purple_timeout_remove(qd->check_watcher); qd->check_watcher = 0; } if (qd->connect_watcher > 0) { purple_timeout_remove(qd->connect_watcher); qd->connect_watcher = 0; } qq_disconnect(gc); if (qd->redirect) g_free(qd->redirect); if (qd->ld.token) g_free(qd->ld.token); if (qd->ld.token_ex) g_free(qd->ld.token_ex); if (qd->captcha.token) g_free(qd->captcha.token); if (qd->captcha.data) g_free(qd->captcha.data); server_list_remove_all(qd); g_free(qd); gc->proto_data = NULL; } /* returns the icon name for a buddy or protocol */ static const gchar *qq_list_icon(PurpleAccount *a, PurpleBuddy *b) { return "qq"; } /* a short status text beside buddy icon*/ static gchar *qq_status_text(PurpleBuddy *b) { qq_buddy_data *bd; GString *status; bd = purple_buddy_get_protocol_data(b); if (bd == NULL) return NULL; status = g_string_new(""); switch(bd->status) { case QQ_BUDDY_OFFLINE: g_string_append(status, _("Offline")); break; case QQ_BUDDY_ONLINE_NORMAL: g_string_append(status, _("Online")); break; /* TODO What does this status mean? Labelling it as offline... */ case QQ_BUDDY_CHANGE_TO_OFFLINE: g_string_append(status, _("Offline")); break; case QQ_BUDDY_ONLINE_AWAY: g_string_append(status, _("Away")); break; case QQ_BUDDY_ONLINE_INVISIBLE: g_string_append(status, _("Invisible")); break; case QQ_BUDDY_ONLINE_BUSY: g_string_append(status, _("Busy")); break; default: g_string_printf(status, _("Unknown-%d"), bd->status); } return g_string_free(status, FALSE); } /* a floating text when mouse is on the icon, show connection status here */ static void qq_tooltip_text(PurpleBuddy *b, PurpleNotifyUserInfo *user_info, gboolean full) { qq_buddy_data *bd; gchar *tmp; GString *str; g_return_if_fail(b != NULL); bd = purple_buddy_get_protocol_data(b); if (bd == NULL) return; /* if (PURPLE_BUDDY_IS_ONLINE(b) && bd != NULL) */ if (bd->ip.s_addr != 0) { str = g_string_new(NULL); g_string_printf(str, "%s:%d", inet_ntoa(bd->ip), bd->port); if (bd->comm_flag & QQ_COMM_FLAG_TCP_MODE) { g_string_append(str, " TCP"); } else { g_string_append(str, " UDP"); } g_string_free(str, TRUE); } tmp = g_strdup_printf("%d", bd->age); purple_notify_user_info_add_pair(user_info, _("Age"), tmp); g_free(tmp); switch (bd->gender) { case QQ_BUDDY_GENDER_GG: purple_notify_user_info_add_pair(user_info, _("Gender"), _("Male")); break; case QQ_BUDDY_GENDER_MM: purple_notify_user_info_add_pair(user_info, _("Gender"), _("Female")); break; case QQ_BUDDY_GENDER_UNKNOWN: purple_notify_user_info_add_pair(user_info, _("Gender"), _("Unknown")); break; default: tmp = g_strdup_printf("Error (%d)", bd->gender); purple_notify_user_info_add_pair(user_info, _("Gender"), tmp); g_free(tmp); } if (bd->level) { tmp = g_strdup_printf("%d", bd->level); purple_notify_user_info_add_pair(user_info, _("Level"), tmp); g_free(tmp); } str = g_string_new(NULL); if (bd->comm_flag & QQ_COMM_FLAG_QQ_MEMBER) { g_string_append( str, _("Member") ); } if (bd->comm_flag & QQ_COMM_FLAG_QQ_VIP) { g_string_append( str, _(" VIP") ); } if (bd->comm_flag & QQ_COMM_FLAG_TCP_MODE) { g_string_append( str, _(" TCP") ); } if (bd->comm_flag & QQ_COMM_FLAG_MOBILE) { g_string_append( str, _(" FromMobile") ); } if (bd->comm_flag & QQ_COMM_FLAG_BIND_MOBILE) { g_string_append( str, _(" BindMobile") ); } if (bd->comm_flag & QQ_COMM_FLAG_VIDEO) { g_string_append( str, _(" Video") ); } if (bd->ext_flag & QQ_EXT_FLAG_ZONE) { g_string_append( str, _(" Zone") ); } purple_notify_user_info_add_pair(user_info, _("Flag"), str->str); g_string_free(str, TRUE); #ifdef DEBUG tmp = g_strdup_printf( "%s (%04X)", qq_get_ver_desc(bd->client_tag), bd->client_tag ); purple_notify_user_info_add_pair(user_info, _("Ver"), tmp); g_free(tmp); tmp = g_strdup_printf( "Ext 0x%X, Comm 0x%X", bd->ext_flag, bd->comm_flag ); purple_notify_user_info_add_pair(user_info, _("Flag"), tmp); g_free(tmp); #endif } /* we can show tiny icons on the four corners of buddy icon, */ static const char *qq_list_emblem(PurpleBuddy *b) { PurpleAccount *account; PurpleConnection *gc; qq_data *qd; qq_buddy_data *buddy; if (!b || !(account = purple_buddy_get_account(b)) || !(gc = purple_account_get_connection(account)) || !(qd = purple_connection_get_protocol_data(gc))) return NULL; buddy = purple_buddy_get_protocol_data(b); if (!buddy) { return "not-authorized"; } if (buddy->comm_flag & QQ_COMM_FLAG_MOBILE) return "mobile"; if (buddy->comm_flag & QQ_COMM_FLAG_VIDEO) return "video"; if (buddy->comm_flag & QQ_COMM_FLAG_QQ_MEMBER) return "qq_member"; return NULL; } /* QQ away status (used to initiate QQ away packet) */ static GList *qq_status_types(PurpleAccount *ga) { PurpleStatusType *status; GList *types = NULL; status = purple_status_type_new_full(PURPLE_STATUS_AVAILABLE, "available", _("Available"), TRUE, TRUE, FALSE); types = g_list_append(types, status); status = purple_status_type_new_full(PURPLE_STATUS_AWAY, "away", _("Away"), TRUE, TRUE, FALSE); types = g_list_append(types, status); status = purple_status_type_new_full(PURPLE_STATUS_INVISIBLE, "invisible", _("Invisible"), TRUE, TRUE, FALSE); types = g_list_append(types, status); status = purple_status_type_new_full(PURPLE_STATUS_UNAVAILABLE, "busy", _("Busy"), TRUE, TRUE, FALSE); types = g_list_append(types, status); status = purple_status_type_new_full(PURPLE_STATUS_OFFLINE, "offline", _("Offline"), TRUE, TRUE, FALSE); types = g_list_append(types, status); status = purple_status_type_new_full(PURPLE_STATUS_MOBILE, "mobile", NULL, FALSE, FALSE, TRUE); types = g_list_append(types, status); return types; } /* initiate QQ away with proper change_status packet */ static void qq_change_status(PurpleAccount *account, PurpleStatus *status) { PurpleConnection *gc = purple_account_get_connection(account); qq_request_change_status(gc, 0); } /* send packet to get who's detailed information */ static void qq_show_buddy_info(PurpleConnection *gc, const gchar *who) { guint32 uid; qq_data *qd; qd = gc->proto_data; uid = purple_name_to_uid(who); if (uid <= 0) { purple_debug_error("QQ", "Not valid QQid: %s\n", who); purple_notify_error(gc, NULL, _("Invalid name"), NULL); return; } if (qd->client_version >= 2007) { qq_request_get_level_2007(gc, uid); } else { qq_request_get_level(gc, uid); } qq_request_buddy_info(gc, uid, 0, QQ_BUDDY_INFO_DISPLAY); } static void action_update_all_rooms(PurplePluginAction *action) { PurpleConnection *gc = (PurpleConnection *) action->context; qq_data *qd; g_return_if_fail(NULL != gc && NULL != gc->proto_data); qd = (qq_data *) gc->proto_data; if ( !qd->is_login ) { return; } qq_update_all_rooms(gc, 0, 0); } static void action_change_icon(PurplePluginAction *action) { PurpleConnection *gc = (PurpleConnection *) action->context; qq_data *qd; gchar *icon_name; gchar *icon_path; g_return_if_fail(NULL != gc && NULL != gc->proto_data); qd = (qq_data *) gc->proto_data; if ( !qd->is_login ) { return; } icon_name = qq_get_icon_name(qd->my_icon); icon_path = qq_get_icon_path(icon_name); g_free(icon_name); purple_debug_info("QQ", "Change prev icon %s to...\n", icon_path); purple_request_file(action, _("Select icon..."), icon_path, FALSE, G_CALLBACK(qq_change_icon_cb), NULL, purple_connection_get_account(gc), NULL, NULL, gc); g_free(icon_path); } static void action_modify_info_base(PurplePluginAction *action) { PurpleConnection *gc = (PurpleConnection *) action->context; qq_data *qd; g_return_if_fail(NULL != gc && NULL != gc->proto_data); qd = (qq_data *) gc->proto_data; qq_request_buddy_info(gc, qd->uid, 0, QQ_BUDDY_INFO_MODIFY_BASE); } static void action_modify_info_ext(PurplePluginAction *action) { PurpleConnection *gc = (PurpleConnection *) action->context; qq_data *qd; g_return_if_fail(NULL != gc && NULL != gc->proto_data); qd = (qq_data *) gc->proto_data; qq_request_buddy_info(gc, qd->uid, 0, QQ_BUDDY_INFO_MODIFY_EXT); } static void action_modify_info_addr(PurplePluginAction *action) { PurpleConnection *gc = (PurpleConnection *) action->context; qq_data *qd; g_return_if_fail(NULL != gc && NULL != gc->proto_data); qd = (qq_data *) gc->proto_data; qq_request_buddy_info(gc, qd->uid, 0, QQ_BUDDY_INFO_MODIFY_ADDR); } static void action_modify_info_contact(PurplePluginAction *action) { PurpleConnection *gc = (PurpleConnection *) action->context; qq_data *qd; g_return_if_fail(NULL != gc && NULL != gc->proto_data); qd = (qq_data *) gc->proto_data; qq_request_buddy_info(gc, qd->uid, 0, QQ_BUDDY_INFO_MODIFY_CONTACT); } static void action_change_password(PurplePluginAction *action) { PurpleConnection *gc = (PurpleConnection *) action->context; g_return_if_fail(NULL != gc && NULL != gc->proto_data); purple_notify_uri(NULL, "https://password.qq.com"); } /* show a brief summary of what we get from login packet */ static void action_show_account_info(PurplePluginAction *action) { PurpleConnection *gc = (PurpleConnection *) action->context; qq_data *qd; GString *info; struct tm *tm_local; int index; g_return_if_fail(NULL != gc && NULL != gc->proto_data); qd = (qq_data *) gc->proto_data; info = g_string_new("<html><body>"); tm_local = localtime(&qd->login_time); g_string_append_printf(info, _("<b>Login time</b>: %d-%d-%d, %d:%d:%d<br>\n"), (1900 +tm_local->tm_year), (1 + tm_local->tm_mon), tm_local->tm_mday, tm_local->tm_hour, tm_local->tm_min, tm_local->tm_sec); g_string_append_printf(info, _("<b>Total Online Buddies</b>: %d<br>\n"), qd->online_total); tm_local = localtime(&qd->online_last_update); g_string_append_printf(info, _("<b>Last Refresh</b>: %d-%d-%d, %d:%d:%d<br>\n"), (1900 +tm_local->tm_year), (1 + tm_local->tm_mon), tm_local->tm_mday, tm_local->tm_hour, tm_local->tm_min, tm_local->tm_sec); g_string_append(info, "<hr>"); g_string_append_printf(info, _("<b>Server</b>: %s<br>\n"), qd->curr_server); g_string_append_printf(info, _("<b>Client Tag</b>: %s<br>\n"), qq_get_ver_desc(qd->client_tag)); g_string_append_printf(info, _("<b>Connection Mode</b>: %s<br>\n"), qd->use_tcp ? "TCP" : "UDP"); g_string_append_printf(info, _("<b>My Internet IP</b>: %s:%d<br>\n"), inet_ntoa(qd->my_ip), qd->my_port); g_string_append(info, "<hr>"); g_string_append(info, "<i>Network Status</i><br>\n"); g_string_append_printf(info, _("<b>Sent</b>: %lu<br>\n"), qd->net_stat.sent); g_string_append_printf(info, _("<b>Resend</b>: %lu<br>\n"), qd->net_stat.resend); g_string_append_printf(info, _("<b>Lost</b>: %lu<br>\n"), qd->net_stat.lost); g_string_append_printf(info, _("<b>Received</b>: %lu<br>\n"), qd->net_stat.rcved); g_string_append_printf(info, _("<b>Received Duplicate</b>: %lu<br>\n"), qd->net_stat.rcved_dup); g_string_append(info, "<hr>"); g_string_append(info, "<i>Last Login Information</i><br>\n"); for (index = 0; index < sizeof(qd->last_login_time) / sizeof(time_t); index++) { tm_local = localtime(&qd->last_login_time[index]); g_string_append_printf(info, _("<b>Time</b>: %d-%d-%d, %d:%d:%d<br>\n"), (1900 +tm_local->tm_year), (1 + tm_local->tm_mon), tm_local->tm_mday, tm_local->tm_hour, tm_local->tm_min, tm_local->tm_sec); } if (qd->last_login_ip.s_addr != 0) { g_string_append_printf(info, _("<b>IP</b>: %s<br>\n"), inet_ntoa(qd->last_login_ip)); } g_string_append(info, "</body></html>"); purple_notify_formatted(gc, NULL, _("Login Information"), NULL, info->str, NULL, NULL); g_string_free(info, TRUE); } static void action_about_openq(PurplePluginAction *action) { PurpleConnection *gc = (PurpleConnection *) action->context; qq_data *qd; GString *info; gchar *title; g_return_if_fail(NULL != gc && NULL != gc->proto_data); qd = (qq_data *) gc->proto_data; info = g_string_new("<html><body>"); g_string_append(info, _("<p><b>Original Author</b>:<br>\n")); g_string_append(info, "puzzlebird<br>\n"); g_string_append(info, "<br>\n"); g_string_append(info, _("<p><b>Code Contributors</b>:<br>\n")); g_string_append(info, "gfhuang(poppyer) : patches for libpurple 2.0.0beta2, maintainer<br>\n"); g_string_append(info, "Yuan Qingyun : patches for libpurple 1.5.0, maintainer<br>\n"); g_string_append(info, "henryouly : file transfer, udp sock5 proxy and qq_show, maintainer<br>\n"); g_string_append(info, "hzhr : maintainer<br>\n"); g_string_append(info, "joymarquis : maintainer<br>\n"); g_string_append(info, "arfankai : fixed bugs in char_conv.c<br>\n"); g_string_append(info, "rakescar : provided filter for HTML tag<br>\n"); g_string_append(info, "yyw : improved performance on PPC linux<br>\n"); g_string_append(info, "lvxiang : provided ip to location original code<br>\n"); g_string_append(info, "markhuetsch : OpenQ merge into libpurple, maintainer 2006-2007<br>\n"); g_string_append(info, "ccpaging : maintainer since 2007<br>\n"); g_string_append(info, "icesky : maintainer since 2007<br>\n"); g_string_append(info, "csyfek : faces, maintainer since 2007<br>\n"); g_string_append(info, "<br>\n"); g_string_append(info, _("<p><b>Lovely Patch Writers</b>:<br>\n")); g_string_append(info, "gnap : message displaying, documentation<br>\n"); g_string_append(info, "manphiz : qun processing<br>\n"); g_string_append(info, "moo : qun processing<br>\n"); g_string_append(info, "Coly Li : qun processing<br>\n"); g_string_append(info, "Emil Alexiev : captcha verification on login based on LumaQQ for MAC (2007), login, add buddy, remove buddy, message exchange and logout<br>\n"); g_string_append(info, "Chengming Wang : buddy memo<br>\n"); g_string_append(info, "lonicerae : chat room window bugfix, server list bugfix, buddy memo<br>\n"); g_string_append(info, "<br>\n"); g_string_append(info, _("<p><b>Acknowledgement</b>:<br>\n")); g_string_append(info, "Shufeng Tan : http://sf.net/projects/perl-oicq<br>\n"); g_string_append(info, "Jeff Ye : http://www.sinomac.com<br>\n"); g_string_append(info, "Hu Zheng : http://forlinux.yeah.net<br>\n"); g_string_append(info, "yunfan : http://www.myswear.net<br>\n"); g_string_append(info, "OpenQ Team : http://openq.linuxsir.org<br>\n"); g_string_append(info, "LumaQQ Team : http://lumaqq.linuxsir.org<br>\n"); g_string_append(info, "Pidgin Team : http://www.pidgin.im<br>\n"); g_string_append(info, "Huang Guan : http://home.xxsyzx.com<br>\n"); g_string_append(info, "OpenQ Google Group : http://groups.google.com/group/openq<br>\n"); g_string_append(info, "<br>\n"); g_string_append(info, _("<p><b>Scrupulous Testers</b>:<br>\n")); g_string_append(info, "yegle<br>\n"); g_string_append(info, "cnzhangbx<br>\n"); g_string_append(info, "casparant<br>\n"); g_string_append(info, "wd<br>\n"); g_string_append(info, "x6719620<br>\n"); g_string_append(info, "netelk<br>\n"); g_string_append(info, _("and more, please let me know... thank you!))")); g_string_append(info, "<br>\n<br>\n"); g_string_append(info, _("<p><i>And, all the boys in the backroom...</i><br>\n")); g_string_append(info, _("<i>Feel free to join us!</i> :)")); g_string_append(info, "</body></html>"); title = g_strdup_printf(_("About OpenQ %s"), OPENQ_VERSION); purple_notify_formatted(gc, title, title, NULL, info->str, NULL, NULL); g_free(title); g_string_free(info, TRUE); } /* static void _qq_menu_search_or_add_permanent_group(PurplePluginAction *action) { purple_roomlist_show_with_account(NULL); } */ /* static void _qq_menu_create_permanent_group(PurplePluginAction * action) { PurpleConnection *gc = (PurpleConnection *) action->context; purple_request_input(gc, _("Create QQ Qun"), _("Input Qun name here"), _("Only QQ members can create permanent Qun"), "OpenQ", FALSE, FALSE, NULL, _("Create"), G_CALLBACK(qq_create_room), _("Cancel"), NULL, gc); } */ static void action_chat_quit(PurpleBlistNode * node) { PurpleChat *chat = (PurpleChat *)node; PurpleAccount *account = purple_chat_get_account(chat); PurpleConnection *gc = purple_account_get_connection(account); GHashTable *components = purple_chat_get_components(chat); gchar *num_str; guint32 room_id; g_return_if_fail(PURPLE_BLIST_NODE_IS_CHAT(node)); g_return_if_fail(components != NULL); num_str = g_hash_table_lookup(components, QQ_ROOM_KEY_INTERNAL_ID); room_id = strtoul(num_str, NULL, 10); g_return_if_fail(room_id != 0); qq_room_quit(gc, room_id); } static void action_chat_get_info(PurpleBlistNode * node) { PurpleChat *chat = (PurpleChat *)node; PurpleAccount *account = purple_chat_get_account(chat); PurpleConnection *gc = purple_account_get_connection(account); GHashTable *components = purple_chat_get_components(chat); gchar *num_str; guint32 room_id; g_return_if_fail(PURPLE_BLIST_NODE_IS_CHAT(node)); g_return_if_fail(components != NULL); num_str = g_hash_table_lookup(components, QQ_ROOM_KEY_INTERNAL_ID); room_id = strtoul(num_str, NULL, 10); g_return_if_fail(room_id != 0); qq_send_room_cmd_mess(gc, QQ_ROOM_CMD_GET_INFO, room_id, NULL, 0, 0, QQ_ROOM_INFO_DISPLAY); } #if 0 /* TODO: re-enable this */ static void _qq_menu_send_file(PurpleBlistNode * node, gpointer ignored) { PurpleBuddy *buddy; PurpleConnection *gc; qq_buddy_data *bd; g_return_if_fail (PURPLE_BLIST_NODE_IS_BUDDY (node)); buddy = (PurpleBuddy *) node; bd = (qq_buddy_data *) buddy->proto_data; /* if (is_online (bd->status)) { */ gc = purple_account_get_connection (buddy->account); g_return_if_fail (gc != NULL && gc->proto_data != NULL); qq_send_file(gc, buddy->name, NULL); /* } */ } #endif /* protocol related menus */ static GList *qq_actions(PurplePlugin *plugin, gpointer context) { GList *m; PurplePluginAction *act; m = NULL; act = purple_plugin_action_new(_("Change Icon"), action_change_icon); m = g_list_append(m, act); act = purple_plugin_action_new(_("Modify Information"), action_modify_info_base); m = g_list_append(m, act); act = purple_plugin_action_new(_("Modify Extended Information"), action_modify_info_ext); m = g_list_append(m, act); act = purple_plugin_action_new(_("Modify Address"), action_modify_info_addr); m = g_list_append(m, act); act = purple_plugin_action_new(_("Modify Contact"), action_modify_info_contact); m = g_list_append(m, act); act = purple_plugin_action_new(_("Change Password"), action_change_password); m = g_list_append(m, act); act = purple_plugin_action_new(_("Account Information"), action_show_account_info); m = g_list_append(m, act); act = purple_plugin_action_new(_("Update all QQ Quns"), action_update_all_rooms); m = g_list_append(m, act); act = purple_plugin_action_new(_("About OpenQ"), action_about_openq); m = g_list_append(m, act); /* act = purple_plugin_action_new(_("Qun: Search a permanent Qun"), _qq_menu_search_or_add_permanent_group); m = g_list_append(m, act); act = purple_plugin_action_new(_("Qun: Create a permanent Qun"), _qq_menu_create_permanent_group); m = g_list_append(m, act); */ return m; } static void qq_add_buddy_from_menu_cb(PurpleBlistNode *node, gpointer data) { PurpleBuddy *buddy; PurpleConnection *gc; g_return_if_fail(PURPLE_BLIST_NODE_IS_BUDDY(node)); buddy = (PurpleBuddy *) node; gc = purple_account_get_connection(purple_buddy_get_account(buddy)); qq_add_buddy(gc, buddy, NULL); } static void qq_modify_buddy_memo_from_menu_cb(PurpleBlistNode *node, gpointer data) { PurpleBuddy *buddy; qq_buddy_data *bd; PurpleConnection *gc; guint32 bd_uid; g_return_if_fail(PURPLE_BLIST_NODE_IS_BUDDY(node)); buddy = (PurpleBuddy *)node; g_return_if_fail(NULL != buddy); gc = purple_account_get_connection(purple_buddy_get_account(buddy)); g_return_if_fail(NULL != gc); bd = (qq_buddy_data *)purple_buddy_get_protocol_data(buddy); g_return_if_fail(NULL != bd); bd_uid = bd->uid; /* param: gc, uid, update_class, action * here, update_class is set to bd_uid. because some memo packages returned * without uid, which will make us confused */ qq_request_buddy_memo(gc, bd_uid, bd_uid, QQ_BUDDY_MEMO_MODIFY); } static GList *qq_buddy_menu(PurpleBuddy *buddy) { GList *m = NULL; PurpleMenuAction *act; qq_buddy_data *bd = purple_buddy_get_protocol_data(buddy); if (bd == NULL) { act = purple_menu_action_new(_("Add Buddy"), PURPLE_CALLBACK(qq_add_buddy_from_menu_cb), NULL, NULL); m = g_list_append(m, act); return m; } act = purple_menu_action_new(_("Modify Buddy Memo"), PURPLE_CALLBACK(qq_modify_buddy_memo_from_menu_cb), NULL, NULL); m = g_list_append(m, act); /* TODO : not working, temp commented out by gfhuang */ #if 0 if (bd && is_online(bd->status)) { act = purple_menu_action_new(_("Send File"), PURPLE_CALLBACK(_qq_menu_send_file), NULL, NULL); /* add NULL by gfhuang */ m = g_list_append(m, act); } #endif return m; } /* chat-related (QQ Qun) menu shown up with right-click */ static GList *qq_chat_menu(PurpleBlistNode *node) { GList *m; PurpleMenuAction *act; m = NULL; act = purple_menu_action_new(_("Get Info"), PURPLE_CALLBACK(action_chat_get_info), NULL, NULL); m = g_list_append(m, act); act = purple_menu_action_new(_("Quit Qun"), PURPLE_CALLBACK(action_chat_quit), NULL, NULL); m = g_list_append(m, act); return m; } /* buddy-related menu shown up with right-click */ static GList *qq_blist_node_menu(PurpleBlistNode * node) { if(PURPLE_BLIST_NODE_IS_CHAT(node)) return qq_chat_menu(node); if(PURPLE_BLIST_NODE_IS_BUDDY(node)) return qq_buddy_menu((PurpleBuddy *) node); return NULL; } /* convert name displayed in a chat channel to original QQ UID */ static gchar *chat_name_to_purple_name(const gchar *const name) { const char *start; const char *end; gchar *ret; g_return_val_if_fail(name != NULL, NULL); /* Sample: (1234567)*/ start = strchr(name, '('); g_return_val_if_fail(start != NULL, NULL); end = strchr(start, ')'); g_return_val_if_fail(end != NULL && (end - start) > 1, NULL); ret = g_strndup(start + 1, end - start - 1); return ret; } /* convert chat nickname to uid to get this buddy info */ /* who is the nickname of buddy in QQ chat-room (Qun) */ static void qq_get_chat_buddy_info(PurpleConnection *gc, gint channel, const gchar *who) { qq_data *qd; gchar *uid_str; guint32 uid; purple_debug_info("QQ", "Get chat buddy info of %s\n", who); g_return_if_fail(who != NULL); uid_str = chat_name_to_purple_name(who); if (uid_str == NULL) { return; } qd = gc->proto_data; uid = purple_name_to_uid(uid_str); g_free(uid_str); if (uid <= 0) { purple_debug_error("QQ", "Not valid chat name: %s\n", who); purple_notify_error(gc, NULL, _("Invalid name"), NULL); return; } if (qd->client_version < 2007) { qq_request_get_level(gc, uid); } qq_request_buddy_info(gc, uid, 0, QQ_BUDDY_INFO_DISPLAY); } /* convert chat nickname to uid to invite individual IM to buddy */ /* who is the nickname of buddy in QQ chat-room (Qun) */ static gchar *qq_get_chat_buddy_real_name(PurpleConnection *gc, gint channel, const gchar *who) { g_return_val_if_fail(who != NULL, NULL); return chat_name_to_purple_name(who); } static PurplePluginProtocolInfo prpl_info = { OPT_PROTO_CHAT_TOPIC | OPT_PROTO_USE_POINTSIZE, NULL, /* user_splits */ NULL, /* protocol_options */ {"png", 96, 96, 96, 96, 0, PURPLE_ICON_SCALE_SEND}, /* icon_spec */ qq_list_icon, /* list_icon */ qq_list_emblem, /* list_emblems */ qq_status_text, /* status_text */ qq_tooltip_text, /* tooltip_text */ qq_status_types, /* away_states */ qq_blist_node_menu, /* blist_node_menu */ qq_chat_info, /* chat_info */ qq_chat_info_defaults, /* chat_info_defaults */ qq_login, /* open */ qq_close, /* close */ qq_send_im, /* send_im */ NULL, /* set_info */ NULL, /* send_typing */ qq_show_buddy_info, /* get_info */ qq_change_status, /* change status */ NULL, /* set_idle */ NULL, /* change_passwd */ qq_add_buddy, /* add_buddy */ NULL, /* add_buddies */ qq_remove_buddy, /* remove_buddy */ NULL, /* remove_buddies */ NULL, /* add_permit */ NULL, /* add_deny */ NULL, /* rem_permit */ NULL, /* rem_deny */ NULL, /* set_permit_deny */ qq_group_join, /* join_chat */ NULL, /* reject chat invite */ NULL, /* get_chat_name */ NULL, /* chat_invite */ NULL, /* chat_leave */ NULL, /* chat_whisper */ qq_chat_send, /* chat_send */ NULL, /* keepalive */ NULL, /* register_user */ qq_get_chat_buddy_info, /* get_cb_info */ NULL, /* get_cb_away */ NULL, /* alias_buddy */ NULL, /* change buddy's group */ NULL, /* rename_group */ NULL, /* buddy_free */ NULL, /* convo_closed */ NULL, /* normalize */ qq_set_custom_icon, NULL, /* remove_group */ qq_get_chat_buddy_real_name, /* get_cb_real_name */ NULL, /* set_chat_topic */ NULL, /* find_blist_chat */ qq_roomlist_get_list, /* roomlist_get_list */ qq_roomlist_cancel, /* roomlist_cancel */ NULL, /* roomlist_expand_category */ NULL, /* can_receive_file */ NULL, /* qq_send_file send_file */ NULL, /* new xfer */ NULL, /* offline_message */ NULL, /* PurpleWhiteboardPrplOps */ NULL, /* send_raw */ NULL, /* roomlist_room_serialize */ NULL, /* unregister_user */ NULL, /* send_attention */ NULL, /* get attention_types */ sizeof(PurplePluginProtocolInfo), /* struct_size */ NULL, /* get_account_text_table */ NULL, /* initiate_media */ NULL /* can_do_media */ }; static PurplePluginInfo info = { PURPLE_PLUGIN_MAGIC, PURPLE_MAJOR_VERSION, PURPLE_MINOR_VERSION, PURPLE_PLUGIN_PROTOCOL, /**< type */ NULL, /**< ui_requirement */ 0, /**< flags */ NULL, /**< dependencies */ PURPLE_PRIORITY_DEFAULT, /**< priority */ "prpl-qq", /**< id */ "QQ", /**< name */ DISPLAY_VERSION, /**< version */ /** summary */ N_("QQ Protocol Plugin"), /** description */ N_("QQ Protocol Plugin"), NULL, /**< author */ PURPLE_WEBSITE, /**< homepage */ NULL, /**< load */ NULL, /**< unload */ NULL, /**< destroy */ NULL, /**< ui_info */ &prpl_info, /**< extra_info */ NULL, /**< prefs_info */ qq_actions, /* padding */ NULL, NULL, NULL, NULL }; static void init_plugin(PurplePlugin *plugin) { PurpleAccountOption *option; PurpleKeyValuePair *kvp; GList *server_list = NULL; GList *server_kv_list = NULL; GList *it; /* #ifdef DEBUG */ GList *version_kv_list = NULL; /* #endif */ server_list = server_list_build('A'); purple_prefs_remove("/plugins/prpl/qq/serverlist"); server_kv_list = NULL; kvp = g_new0(PurpleKeyValuePair, 1); kvp->key = g_strdup(_("Auto")); kvp->value = g_strdup("auto"); server_kv_list = g_list_append(server_kv_list, kvp); it = server_list; while(it) { if (it->data != NULL && strlen(it->data) > 0) { kvp = g_new0(PurpleKeyValuePair, 1); kvp->key = g_strdup(it->data); kvp->value = g_strdup(it->data); server_kv_list = g_list_append(server_kv_list, kvp); } it = it->next; } g_list_free(server_list); option = purple_account_option_list_new(_("Select Server"), "server", server_kv_list); prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option); kvp = g_new0(PurpleKeyValuePair, 1); kvp->key = g_strdup(_("QQ2005")); kvp->value = g_strdup("qq2005"); version_kv_list = g_list_append(version_kv_list, kvp); kvp = g_new0(PurpleKeyValuePair, 1); kvp->key = g_strdup(_("QQ2007")); kvp->value = g_strdup("qq2007"); version_kv_list = g_list_append(version_kv_list, kvp); kvp = g_new0(PurpleKeyValuePair, 1); kvp->key = g_strdup(_("QQ2008")); kvp->value = g_strdup("qq2008"); version_kv_list = g_list_append(version_kv_list, kvp); option = purple_account_option_list_new(_("Client Version"), "client_version", version_kv_list); prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option); option = purple_account_option_bool_new(_("Connect by TCP"), "use_tcp", TRUE); prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option); option = purple_account_option_bool_new(_("Show server notice"), "show_notice", TRUE); prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option); option = purple_account_option_bool_new(_("Show server news"), "show_news", TRUE); prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option); option = purple_account_option_bool_new(_("Show chat room when msg comes"), "show_chat", TRUE); prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option); option = purple_account_option_int_new(_("Keep alive interval (seconds)"), "keep_alive_interval", 60); prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option); option = purple_account_option_int_new(_("Update interval (seconds)"), "update_interval", 300); prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option); purple_prefs_add_none("/plugins/prpl/qq"); purple_prefs_add_bool("/plugins/prpl/qq/show_status_by_icon", TRUE); purple_prefs_add_bool("/plugins/prpl/qq/show_fake_video", FALSE); purple_prefs_add_bool("/plugins/prpl/qq/auto_get_authorize_info", TRUE); purple_prefs_add_int("/plugins/prpl/qq/resend_interval", 3); purple_prefs_add_int("/plugins/prpl/qq/resend_times", 10); } PURPLE_INIT_PLUGIN(qq, init_plugin, info);
tdrhq/pidgin-clone
libpurple/protocols/qq/qq.c
C
gpl-2.0
36,344
// Aseprite // Copyright (C) 2001-2016 David Capello // // 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. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "app/util/freetype_utils.h" #include "base/unique_ptr.h" #include "doc/blend_funcs.h" #include "doc/blend_internals.h" #include "doc/color.h" #include "doc/image.h" #include "doc/primitives.h" #include "ft/face.h" #include "ft/lib.h" #include <stdexcept> namespace app { doc::Image* render_text(const std::string& fontfile, int fontsize, const std::string& text, doc::color_t color, bool antialias) { base::UniquePtr<doc::Image> image(nullptr); ft::Lib ft; ft::Face face(ft.open(fontfile)); if (face.isValid()) { // Set font size face.setSize(fontsize); face.setAntialias(antialias); // Calculate text size gfx::Rect bounds = face.calcTextBounds(text); // Render the image and copy it to the clipboard if (!bounds.isEmpty()) { image.reset(doc::Image::create(doc::IMAGE_RGB, bounds.w, bounds.h)); doc::clear_image(image, 0); face.forEachGlyph( text, [&bounds, &image, color, antialias](const ft::Glyph& glyph) { int t, yimg = - bounds.y + int(glyph.y); for (int v=0; v<int(glyph.bitmap->rows); ++v, ++yimg) { const uint8_t* p = glyph.bitmap->buffer + v*glyph.bitmap->pitch; int ximg = - bounds.x + int(glyph.x); int bit = 0; for (int u=0; u<int(glyph.bitmap->width); ++u, ++ximg) { int alpha; if (antialias) { alpha = *(p++); } else { alpha = ((*p) & (1 << (7 - (bit++))) ? 255: 0); if (bit == 8) { bit = 0; ++p; } } int output_alpha = MUL_UN8(doc::rgba_geta(color), alpha, t); if (output_alpha) { doc::color_t output_color = doc::rgba(doc::rgba_getr(color), doc::rgba_getg(color), doc::rgba_getb(color), output_alpha); doc::put_pixel( image, ximg, yimg, doc::rgba_blender_normal( doc::get_pixel(image, ximg, yimg), output_color)); } } } }); } else { throw std::runtime_error("There is no text"); } } else { throw std::runtime_error("Error loading font face"); } return (image ? image.release(): nullptr); } } // namespace app
tony/aseprite
src/app/util/freetype_utils.cpp
C++
gpl-2.0
2,836
/******************************************************************************** * * * GNORASI - The Knowlegde-Based Remote Sensing Engine * * * * Language: C++ * * * * Copyright (c) ALTEC SA - All rights reserved. * * Copyright (c) ALTEC SA - All rights reserved. * * Copyright (c) ALTEC SA - All rights reserved. * * * * This file is part of the GNORASI software package. GNORASI 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. * * * * GNORASI 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 * * in the file "LICENSE.txt" along with this program. * * If not, see <http://www.gnu.org/licenses/>. * * * ********************************************************************************/ #include "otbgeodesicactivecontourlevelsetimagefilterprocessor.h" #include "voreen/core/voreenapplication.h" namespace voreen { const std::string OTBGeodesicActiveContourLevelSetImageFilterProcessor::loggerCat_("voreen.OTBGeodesicActiveContourLevelSetImageFilterProcessor"); OTBGeodesicActiveContourLevelSetImageFilterProcessor::OTBGeodesicActiveContourLevelSetImageFilterProcessor() :OTBImageFilterProcessor(), seedX_("seedX", "Seed Point X: ", 0, 0, 2000), seedY_("seedY", "Seed Point Y: ", 0, 0, 2000), initialDistance_("initialDistance", "Initial Distance: ", 5.0f, 0.0f, 1000.0f), sigma_("sigma", "Sigma: ", 1.0f, 0.0f, 100.0f), sigmoidAlpha_("sigmoidAlpha", "Sigmoid Alpha:", 5.f, -100.0f, 255.0f), sigmoidBeta_("sigmoidBeta", "Sigmoid Beta:", 10.0f, -100.0f, 255.0f), propagationScaling_("propagationScaling", "Propagation Scaling: ", 10.0, 0.0f, 100.0f), inPort_(Port::INPORT, "OTBImage.Inport",0), outPort_(Port::OUTPORT, "OTBImage.Outport",0), testOutPort1_(Port::OUTPORT, "OTBImage.Smoothing",0), testOutPort2_(Port::OUTPORT, "OTBImage.GradientMagnitude",0), testOutPort3_(Port::OUTPORT, "OTBImage.Sigmoid",0), testOutPort4_(Port::OUTPORT, "OTBImage.FastMarching",0) { addProperty(enableSwitch_); addProperty(seedX_); addProperty(seedY_); addProperty(initialDistance_); addProperty(sigma_); addProperty(sigmoidAlpha_); addProperty(sigmoidBeta_); addProperty(propagationScaling_); addPort(inPort_); addPort(testOutPort1_); addPort(testOutPort2_); addPort(testOutPort3_); addPort(testOutPort4_); addPort(outPort_); smoothing = SmoothingFilterType::New(); gradientMagnitude = GradientFilterType::New(); sigmoid = SigmoidFilterType::New(); fastMarching = FastMarchingFilterType::New(); seeds = NodeContainer::New(); geodesicActiveContour = GeodesicActiveContourFilterType::New(); thresholder = ThresholdingFilterType::New(); portToCharCaster = PortToCharCastingFilterType::New(); charToInternalCaster = CharToInternalCastingFilterType::New(); charToPortCaster = CharToPortCastingFilterType::New(); internToPortCaster1 = InternalToPortCastingFilterType::New(); } Processor* OTBGeodesicActiveContourLevelSetImageFilterProcessor::create() const { return new OTBGeodesicActiveContourLevelSetImageFilterProcessor(); } OTBGeodesicActiveContourLevelSetImageFilterProcessor::~OTBGeodesicActiveContourLevelSetImageFilterProcessor() { } void OTBGeodesicActiveContourLevelSetImageFilterProcessor::initialize() throw (tgt::Exception) { Processor::initialize(); } void OTBGeodesicActiveContourLevelSetImageFilterProcessor::deinitialize() throw (tgt::Exception) { Processor::deinitialize(); } std::string OTBGeodesicActiveContourLevelSetImageFilterProcessor::getProcessorInfo() const { return "Geodesic Active Contour Level Set Image Filter Processor"; } void OTBGeodesicActiveContourLevelSetImageFilterProcessor::process() { //LINFO("Geodesic Active Contour Level SetImage Filter Enabled!"); //check bypass switch if (!enableSwitch_.get()) { bypass(&inPort_, &outPort_); return; } try { //Curvature Anisotropic Diffusion smoothing->SetInput(inPort_.getData()); smoothing->SetTimeStep(0.125); smoothing->SetNumberOfIterations(5); smoothing->SetConductanceParameter(9.0); //testOutport1.Smoothing testOutPort1_.setData(smoothing->GetOutput()); //Gradient Magnitude gradientMagnitude->SetInput(smoothing->GetOutput()); double sigma = sigma_.get(); gradientMagnitude->SetSigma(sigma); //testOutport2.GradientMagnitude testOutPort2_.setData(gradientMagnitude->GetOutput()); //Sigmoid portToCharCaster->SetInput(gradientMagnitude->GetOutput()); sigmoid->SetInput(portToCharCaster->GetOutput()); sigmoid->SetOutputMinimum(0); sigmoid->SetOutputMaximum(255); double alpha = sigmoidAlpha_.get(); double beta = sigmoidBeta_.get(); sigmoid->SetAlpha(alpha); sigmoid->SetBeta(beta); sigmoid->Update(); charToInternalCaster->SetInput(sigmoid->GetOutput()); //testOutport3.Sigmoid charToPortCaster->SetInput(sigmoid->GetOutput()); testOutPort3_.setData(charToPortCaster->GetOutput()); //Geodesic Active Contour geodesicActiveContour->SetFeatureImage(charToInternalCaster->GetOutput()); double propagationScaling = propagationScaling_.get(); geodesicActiveContour->SetPropagationScaling(propagationScaling); geodesicActiveContour->SetCurvatureScaling(1.0); geodesicActiveContour->SetAdvectionScaling(1.0); geodesicActiveContour->SetMaximumRMSError(0.02); geodesicActiveContour->SetNumberOfIterations(800); //Fast Marching seedPosition[0] = seedX_.get(); seedPosition[1] = seedY_.get(); double initialDistance = initialDistance_.get(); NodeType node; double seedValue = -initialDistance; node.SetValue(seedValue); node.SetIndex(seedPosition); seeds->Initialize(); seeds->InsertElement(0,node); fastMarching->SetTrialPoints(seeds); fastMarching->SetSpeedConstant(1.0); fastMarching->SetOutputSize(inPort_.getData()->GetBufferedRegion().GetSize()); fastMarching->Update(); //testOutport3.FastMarching testOutPort4_.setData(fastMarching->GetOutput()); //Fast Matching -> Geodesic Active Contour geodesicActiveContour->SetInput(fastMarching->GetOutput()); geodesicActiveContour->Update(); //Thresholder internToPortCaster1->SetInput(geodesicActiveContour->GetOutput()); thresholder->SetInput(internToPortCaster1->GetOutput()); thresholder->SetLowerThreshold(-1000.0); thresholder->SetUpperThreshold(0.0); thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); thresholder->Update(); //outPort outPort_.setData(thresholder->GetOutput()); LINFO("Geodesic Active Contour Level SetImage Filter Connected!"); } catch (int e) { LERROR("Error in Geodesic Active Contour Level SetImage Filter!"); return; } } } // namespace
gnorasi/gnorasi
Gnorasi/modules/otb/processors/Segmentation/otbgeodesicactivecontourlevelsetimagefilterprocessor.cpp
C++
gpl-2.0
8,476
<?php /** * @file * Contains \Drupal\Console\Utils\Create\UserData. */ namespace Drupal\Console\Utils\Create; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Entity\EntityFieldManagerInterface; use Drupal\Core\Datetime\DateFormatterInterface; /** * Class Users * * @package Drupal\Console\Utils\Create */ class UserData extends Base { /** * Create and returns an array of new Users. * * @param $roles * @param $limit * @param $password * @param $timeRange * * @return array */ public function create( $roles, $limit, $password, $timeRange ) { $siteRoles = $this->drupalApi->getRoles(); $users = []; for ($i=0; $i<$limit; $i++) { $username = $this->getRandom()->word(mt_rand(6, 12)); $user = $this->entityTypeManager->getStorage('user')->create( [ 'name' => $username, 'mail' => $username . '@example.com', 'pass' => $password?:$this->getRandom()->word(mt_rand(8, 16)), 'status' => mt_rand(0, 1), 'roles' => $roles[array_rand($roles)], 'created' => REQUEST_TIME - mt_rand(0, $timeRange), ] ); try { $user->save(); $userRoles = []; foreach ($user->getRoles() as $userRole) { $userRoles[] = $siteRoles[$userRole]; } $users['success'][] = [ 'user-id' => $user->id(), 'username' => $user->getUsername(), 'roles' => implode(', ', $userRoles), 'created' => $this->dateFormatter->format( $user->getCreatedTime(), 'custom', 'Y-m-d h:i:s' ) ]; } catch (\Exception $error) { $users['error'][] = [ 'vid' => $user->id(), 'name' => $user->get('name'), 'error' => $error->getMessage() ]; } } return $users; } }
cburschka/drupal-console
src/Utils/Create/UserData.php
PHP
gpl-2.0
2,268
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>closeable_view</title> <link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../index.html" title="Chapter&#160;1.&#160;Geometry 1.0"> <link rel="up" href="../views.html" title="Views"> <link rel="prev" href="segment_view.html" title="segment_view"> <link rel="next" href="reversible_view.html" title="reversible_view"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="segment_view.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../views.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="reversible_view.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="geometry.reference.views.closeable_view"></a><a class="link" href="closeable_view.html" title="closeable_view">closeable_view</a> </h4></div></div></div> <p> <a class="indexterm" name="id963268"></a> View on a range, either closing it or leaving it as it is. </p> <a name="geometry.reference.views.closeable_view.description"></a><h6> <a name="geometry.reference.views.closeable_view.description-heading"></a> <a class="link" href="closeable_view.html#geometry.reference.views.closeable_view.description">Description</a> </h6> <p> The closeable_view is used internally by the library to handle all rings, either closed or open, the same way. The default method is closed, all algorithms process rings as if they are closed. Therefore, if they are opened, a view is created which closes them. The closeable_view might be used by library users, but its main purpose is internally. </p> <a name="geometry.reference.views.closeable_view.synopsis"></a><h6> <a name="geometry.reference.views.closeable_view.synopsis-heading"></a> <a class="link" href="closeable_view.html#geometry.reference.views.closeable_view.synopsis">Synopsis</a> </h6> <p> </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> <span class="identifier">Range</span><span class="special">,</span> <span class="identifier">closure_selector</span> <span class="identifier">Close</span><span class="special">&gt;</span> <span class="keyword">struct</span> <span class="identifier">closeable_view</span> <span class="special">{</span> <span class="comment">// ...</span> <span class="special">};</span> </pre> <p> </p> <a name="geometry.reference.views.closeable_view.template_parameter_s_"></a><h6> <a name="geometry.reference.views.closeable_view.template_parameter_s_-heading"></a> <a class="link" href="closeable_view.html#geometry.reference.views.closeable_view.template_parameter_s_">Template parameter(s)</a> </h6> <div class="informaltable"><table class="table"> <colgroup> <col> <col> </colgroup> <thead><tr> <th> <p> Parameter </p> </th> <th> <p> Description </p> </th> </tr></thead> <tbody> <tr> <td> <p> typename Range </p> </td> <td> <p> Original range </p> </td> </tr> <tr> <td> <p> closure_selector Close </p> </td> <td> <p> Specifies if it the range is closed, if so, nothing will happen. If it is open, it will iterate the first point after the last point. </p> </td> </tr> </tbody> </table></div> <a name="geometry.reference.views.closeable_view.header"></a><h6> <a name="geometry.reference.views.closeable_view.header-heading"></a> <a class="link" href="closeable_view.html#geometry.reference.views.closeable_view.header">Header</a> </h6> <p> <code class="computeroutput"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">geometry</span><span class="special">/</span><span class="identifier">views</span><span class="special">/</span><span class="identifier">closeable_view</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span></code> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2011 Barend Gehrels, Bruno Lalande, Mateusz Loskot<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="segment_view.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../views.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="reversible_view.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
geodynamics/gale
boost/libs/geometry/doc/html/geometry/reference/views/closeable_view.html
HTML
gpl-2.0
6,631
package com.code.taskmanager; import java.util.List; import com.code.taskmanager.bean.AppInfo; import com.code.taskmanager.db.dao.WhiteListDao; import com.code.taskmanager.utils.ApplicationUtils; import android.app.Activity; import android.app.ActivityManager; import android.content.SharedPreferences; import android.os.Bundle; import android.text.format.Formatter; import android.widget.Toast; public class ClearActivity extends Activity { private boolean openWhiteList; private List<AppInfo> runningApplication; private ActivityManager activityManager; private WhiteListDao whiteListDao; private int count = 0; private long mem = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE); activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); whiteListDao = new WhiteListDao(this); openWhiteList = sp.getBoolean("OpenWhiteList", false); runningApplication = ApplicationUtils.getRunningApplication(this); clear(); finish(); } private void clear() { if (openWhiteList) { for (AppInfo info : runningApplication) { if (!whiteListDao.find(info.packagename)) { activityManager.killBackgroundProcesses(info.packagename); mem += info.mem; count++; } } } else { for (AppInfo info : runningApplication) { activityManager.killBackgroundProcesses(info.packagename); mem += info.mem; count++; } } Toast.makeText( this, "Çå³ýÁË" + count + "¸öÈÎÎñ" + ",¹²ÊÍ·ÅÁË" + Formatter.formatFileSize(this, mem) + "µÄÄÚ´æ", Toast.LENGTH_SHORT).show(); } @Override protected void onDestroy() { super.onDestroy(); whiteListDao.close(); } }
silvernoo/KillTask
src/com/code/taskmanager/ClearActivity.java
Java
gpl-2.0
1,759