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
/* ENCRYP-- ENCRYPT PASSWORD */ /*COPYRIGHT 1980, INFOCOM COMPUTERS AND COMMUNICATIONS, CAMBRIDGE MA. 02142*/ /* ALL RIGHTS RESERVED, COMMERCIAL USAGE STRICTLY PROHIBITED */ /* WRITTEN BY R. M. SUPNIK */ #include <stdio.h> #include "funcs.h" #include "vars.h" void encryp_(const char *inw, char *outw) { /* Initialized data */ const char *keyw = "ECORMS"; integer i, j, uinw[6], usum; char ukeyw[1*6]; integer uinws, ukeyws; /* Parameter adjustments */ --outw; --inw; /* Function Body */ uinws = 0; /* !UNBIASED INW SUM. */ ukeyws = 0; /* !UNBIASED KEYW SUM. */ j = 1; /* !POINTER IN KEYWORD. */ for (i = 1; i <= 6; ++i) { /* !UNBIAS, COMPUTE SUMS. */ ukeyw[i - 1] = (keyw[i - 1] - 64); if (inw[j] <= '@') { j = 1; } uinw[i - 1] = inw[j] - 64; ukeyws += ukeyw[i - 1]; uinws += uinw[i - 1]; ++j; /* L100: */ } usum = uinws % 8 + (ukeyws % 8 << 3); /* !COMPUTE MASK. */ for (i = 1; i <= 6; ++i) { j = (uinw[i - 1] ^ ukeyw[i - 1] ^ usum) & 31; usum = (usum + 1) % 32; if (j > 26) { j %= 26; } outw[i] = (max(1,j) + 64); /* L200: */ } } /* encryp_ */ /* CPGOTO-- MOVE TO NEXT STATE IN PUZZLE ROOM */ /* DECLARATIONS */ void cpgoto_(integer st) { /* System generated locals */ integer i__1, i__2; /* Local variables */ integer i; rooms_1.rflag[rindex_1.cpuzz - 1] &= ~ RSEEN; i__1 = objcts_1.olnt; for (i = 1; i <= i__1; ++i) { /* !RELOCATE OBJECTS. */ if (objcts_1.oroom[i - 1] == rindex_1.cpuzz && (objcts_1.oflag2[i - 1] & (ACTRBT + VILLBT)) == 0) { i__2 = findex_1.cphere * hyper_1.hfactr; newsta_(i, 0, i__2, 0, 0); } if (objcts_1.oroom[i - 1] == st * hyper_1.hfactr) { newsta_(i, 0, rindex_1.cpuzz, 0, 0); } /* L100: */ } findex_1.cphere = st; } /* cpgoto_ */ /* CPINFO-- DESCRIBE PUZZLE ROOM */ /* DECLARATIONS */ void cpinfo_(integer rmk, integer st) { /* Initialized data */ static const integer dgmoft[8] = { -9,-8,-7,-1,1,7,8,9 }; const char *pict = "SSS M"; /* Local variables */ integer i, j, k, l; char dgm[1*8]; rspeak_(rmk); for (i = 1; i <= 8; ++i) { j = dgmoft[i - 1]; dgm[i - 1] = pict[puzzle_1.cpvec[st + j - 1] + 3]; /* !GET PICTURE ELEMENT. */ if (abs(j) == 1 || abs(j) == 8) { goto L100; } k = 8; if (j < 0) { k = -8; } /* !GET ORTHO DIR. */ l = j - k; if (puzzle_1.cpvec[st + k - 1] != 0 && puzzle_1.cpvec[st + l - 1] != 0) { dgm[i - 1] = '?'; } L100: ; } more_output(NULL); printf(" |%c%c %c%c %c%c|\n", dgm[0], dgm[0], dgm[1], dgm[1], dgm[2], dgm[2]); more_output(NULL); printf(" West |%c%c .. %c%c| East\n", dgm[3], dgm[3], dgm[4], dgm[4]); more_output(NULL); printf(" |%c%c %c%c %c%c|\n", dgm[5], dgm[5], dgm[6], dgm[6], dgm[7], dgm[7]); if (st == 10) { rspeak_(870); } /* !AT HOLE? */ if (st == 37) { rspeak_(871); } /* !AT NICHE? */ i = 872; /* !DOOR OPEN? */ if (findex_1.cpoutf) { i = 873; } if (st == 52) { rspeak_(i); } /* !AT DOOR? */ if (puzzle_1.cpvec[st] == -2) { rspeak_(874); } /* !EAST LADDER? */ if (puzzle_1.cpvec[st - 2] == -3) { rspeak_(875); } /* !WEST LADDER? */ } /* cpinfo_ */
svagionitis/zork.inv
zork.src/dso7.c
C
gpl-2.0
3,354
/* * Copyright (C) 2010, Samsung Electronics Co. Ltd. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/input.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/earlysuspend.h> #include <linux/slab.h> #include <linux/gpio.h> #include <linux/i2c/mxt768e.h> #include <asm/unaligned.h> #include <linux/firmware.h> #include <linux/string.h> #include "mXT768e__APP_V2_0_AA.h" #define OBJECT_TABLE_START_ADDRESS 7 #define OBJECT_TABLE_ELEMENT_SIZE 6 #define CMD_RESET_OFFSET 0 #define CMD_BACKUP_OFFSET 1 #define CMD_CALIBRATE_OFFSET 2 #define CMD_REPORTATLL_OFFSET 3 #define CMD_DEBUG_CTRL_OFFSET 4 #define CMD_DIAGNOSTIC_OFFSET 5 #define DETECT_MSG_MASK 0x80 #define PRESS_MSG_MASK 0x40 #define RELEASE_MSG_MASK 0x20 #define MOVE_MSG_MASK 0x10 #define SUPPRESS_MSG_MASK 0x02 /* Version */ #define MXT224_VER_20 20 #define MXT224_VER_21 21 #define MXT224_VER_22 22 /* Slave addresses */ #define MXT_APP_LOW 0x4a #define MXT_APP_HIGH 0x4b #define MXT_BOOT_LOW 0x24 #define MXT_BOOT_HIGH 0x25 #define MXT768E_APP_LOW 0x4c #define MXT768E_APP_HIGH 0x4d #define MXT768E_BOOT_LOW 0x26 #define MXT768E_BOOT_HIGH 0x27 /* FIRMWARE NAME */ #define MXT224_ECHO_FW_NAME "mXT224E.fw" #define MXT224_FW_NAME "mXT224.fw" #define MXT768E_FW_NAME "mXT768e.fw" #define MXT_FWRESET_TIME 175 /* msec */ #define MXT_RESET_TIME 300 /* msec */ #define MXT_BOOT_VALUE 0xa5 #define MXT_BACKUP_VALUE 0x55 /* Bootloader mode status */ #define MXT_WAITING_BOOTLOAD_CMD 0xc0 /* valid 7 6 bit only */ #define MXT_WAITING_FRAME_DATA 0x80 /* valid 7 6 bit only */ #define MXT_FRAME_CRC_CHECK 0x02 #define MXT_FRAME_CRC_FAIL 0x03 #define MXT_FRAME_CRC_PASS 0x04 #define MXT_APP_CRC_FAIL 0x40 /* valid 7 8 bit only */ #define MXT_BOOT_STATUS_MASK 0x3f /* Command to unlock bootloader */ #define MXT_UNLOCK_CMD_MSB 0xaa #define MXT_UNLOCK_CMD_LSB 0xdc #define ID_BLOCK_SIZE 7 /*#define DRIVER_FILTER*/ #define MXT_STATE_INACTIVE -1 #define MXT_STATE_RELEASE 0 #define MXT_STATE_PRESS 1 #define MXT_STATE_MOVE 2 #define MAX_USING_FINGER_NUM 10 /* touch booster */ #define TOUCH_BOOSTER 0 #define TOUCH_BOOSTER_TIME 3000 #if TOUCH_BOOSTER #include <mach/cpufreq.h> #endif /* use sumsize in T57 register */ #define USE_SUMSIZE 1 #if USE_SUMSIZE #define MAX_SUMSIZE 40 #define MAX_SINGLE_SUMSIZE 100 #endif /* Add for debugging */ /*####################*/ /*#define FOR_DEBUGGING_TEST*/ /*#define FOR_DEBUGGING_TEST_DOWNLOADFW_BIN*/ /*#define ITDEV //hmink*/ /*#define SHOW_COORDINATE*/ /*####################*/ #ifdef ITDEV static int driver_paused;//itdev static int debug_enabled;//itdev #endif struct object_t { u8 object_type; u16 i2c_address; u8 size; u8 instances; u8 num_report_ids; } __packed; struct finger_info { s16 x; s16 y; s16 z; u16 w; s8 state; int16_t component; u16 mcount; /*add for debug*/ }; typedef struct { u8 object_type; /*!< Object type. */ u8 instance; /*!< Instance number. */ } report_id_map_t; u8 max_report_id; report_id_map_t *rid_map; static bool rid_map_alloc; struct mxt_data { struct i2c_client *client; struct input_dev *input_dev; struct early_suspend early_suspend; u8 family_id; u32 finger_mask; int gpio_read_done; struct object_t *objects; u8 objects_len; u8 tsp_version; u8 tsp_build; u8 tsp_variant; const u8 *power_cfg; u8 finger_type; u16 msg_proc; u16 cmd_proc; u16 msg_object_size; u32 x_dropbits:2; u32 y_dropbits:2; u8 chrgtime_batt; u8 chrgtime_charging; u8 atchcalst; u8 atchcalsthr; u8 tchthr_batt; u8 tchthr_charging; u8 calcfg_batt_e; u8 calcfg_charging_e; u8 atchcalsthr_e; u8 atchfrccalthr_e; u8 atchfrccalratio_e; u8 idlesyncsperx_batt; u8 idlesyncsperx_charging; u8 actvsyncsperx_batt; u8 actvsyncsperx_charging; u8 idleacqint_batt; u8 idleacqint_charging; u8 actacqint_batt; u8 actacqint_charging; u8 xloclip_batt; u8 xloclip_charging; u8 xhiclip_batt; u8 xhiclip_charging; u8 yloclip_batt; u8 yloclip_charging; u8 yhiclip_batt; u8 yhiclip_charging; u8 xedgectrl_batt; u8 xedgectrl_charging; u8 xedgedist_batt; u8 xedgedist_charging; u8 yedgectrl_batt; u8 yedgectrl_charging; u8 yedgedist_batt; u8 yedgedist_charging; u8 tchhyst_batt; u8 tchhyst_charging; const u8 *t48_config_batt_e; const u8 *t48_config_chrg_e; struct delayed_work config_dwork; struct delayed_work overflow_dwork; struct delayed_work check_median_error_dwork; struct delayed_work check_abnormal_palm_dwork; #if TOUCH_BOOSTER struct delayed_work dvfs_dwork; #endif void (*power_on)(void); void (*power_off)(void); void (*register_cb)(void *); void (*read_ta_status)(void *); int num_fingers; #ifdef ITDEV u16 last_read_addr; u16 msg_proc_addr; #endif struct finger_info fingers[]; }; struct mxt_data *copy_data; extern struct class *sec_class; int touch_is_pressed; EXPORT_SYMBOL(touch_is_pressed); static int mxt_enabled; static bool g_debug_switch; static u8 threshold; static int firm_status_data; static bool deepsleep; void Mxt_force_released(void); static void mxt_ta_probe(int ta_status); static void report_input_data(struct mxt_data *data); /* add for protection code +*/ static bool overflow_detected; static bool first_touch_detected; static bool palm_detected_check; static int config_dwork_flag; static int treat_median_error_status; static int tchcount_aft_median_error; static int count_abnormal_palm; static int count_overflow_detect; #define CNTLMTTCH_AFT_MEDIAN_ERROR 5 #define LIMIT_ABNORMAL_PALM 2 #define LIMIT_OVERFLOW_CNT 2 #define TIME_FOR_RECALIBRATION 3 /*3 sec */ #define TIME_FOR_RECONFIG 10 /*10 sec*/ #define TIME_FOR_RECONFIG_ON_REPET 7 /*7 sec */ #define TIME_FOR_RECONFIG_ON_BOOT 30 /*30 sec*/ #define TIME_FOR_CHECK_MEDIAN_ERROR 2 /*2 sec*/ #define TIME_FOR_CHK_ABNMAL_PALM 900 /*900 msec*/ #define TIME_FOR_RECAL_ABNMAL_PALM 5 /*5 sec*/ #define CAL_FROM_BOOTUP 0 #define CAL_FROM_RESUME 1 #define CAL_BEF_WORK_CALLED 2 #define CAL_REP_WORK_CALLED 3 #define CAL_AFT_WORK_CALLED 4 /* add for protection code -*/ #if TOUCH_BOOSTER static bool tsp_press_status; static bool touch_cpu_lock_status; static int cpu_lv = -1; #endif static int tsp_reboot_count = 0; static int read_mem(struct mxt_data *data, u16 reg, u8 len, u8 *buf) { int ret; u16 le_reg = cpu_to_le16(reg); struct i2c_msg msg[2] = { { .addr = data->client->addr, .flags = 0, .len = 2, .buf = (u8 *)&le_reg, }, { .addr = data->client->addr, .flags = I2C_M_RD, .len = len, .buf = buf, }, }; ret = i2c_transfer(data->client->adapter, msg, 2); if (ret < 0){ printk(KERN_ERR"[TSP]i2c failed ret = %d\n",ret); return ret; } return ret == 2 ? 0 : -EIO; } static int write_mem(struct mxt_data *data, u16 reg, u8 len, const u8 *buf) { int ret; u8 tmp[len + 2]; put_unaligned_le16(cpu_to_le16(reg), tmp); memcpy(tmp + 2, buf, len); ret = i2c_master_send(data->client, tmp, sizeof(tmp)); if (ret < 0) return ret; /* if (reg==(data->cmd_proc + CMD_CALIBRATE_OFFSET)) printk(KERN_ERR"[TSP] write calibrate_command ret is %d, size is %d\n",ret,sizeof(tmp)); */ return ret == sizeof(tmp) ? 0 : -EIO; } static int __devinit mxt_reset(struct mxt_data *data) { u8 buf = 1u; return write_mem(data, data->cmd_proc + CMD_RESET_OFFSET, 1, &buf); } static int __devinit mxt_backup(struct mxt_data *data) { u8 buf = 0x55u; return write_mem(data, data->cmd_proc + CMD_BACKUP_OFFSET, 1, &buf); } static int get_object_info(struct mxt_data *data, u8 object_type, u16 *size, u16 *address) { int i; for (i = 0; i < data->objects_len; i++) { if (data->objects[i].object_type == object_type) { *size = data->objects[i].size + 1; *address = data->objects[i].i2c_address; return 0; } } return -ENODEV; } static int write_config(struct mxt_data *data, u8 type, const u8 *cfg) { int ret; u16 address = 0; u16 size = 0; ret = get_object_info(data, type, &size, &address); if(size ==0 && address == 0) return 0; else return write_mem(data, address, size, cfg); } static int check_instance(struct mxt_data *data, u8 object_type) { int i; for (i = 0; i < data->objects_len; i++) { if (data->objects[i].object_type == object_type) { return (data->objects[i].instances); } } return 0; } static int init_write_config(struct mxt_data *data, u8 type, const u8 *cfg) { int ret; u16 address = 0; u16 size = 0; u8 *temp; ret = get_object_info(data, type, &size, &address); if((size == 0) || (address == 0)) return 0; ret = write_mem(data, address, size, cfg); if (check_instance(data, type)) { printk("[TSP] exist instance1 object (%d)\n", type); temp = kmalloc(size * sizeof(u8), GFP_KERNEL); memset(temp, 0, size); ret |= write_mem(data, address+size, size, temp); kfree(temp); } return ret; } static int change_config(struct mxt_data *data, u16 reg, u8 offeset, u8 change_value) { u8 value = 0; value = change_value; return write_mem(data, reg+offeset, 1, &value); } static u32 __devinit crc24(u32 crc, u8 byte1, u8 byte2) { static const u32 crcpoly = 0x80001B; u32 res; u16 data_word; data_word = (((u16)byte2) << 8) | byte1; res = (crc << 1) ^ (u32)data_word; if (res & 0x1000000) res ^= crcpoly; return res; } static int __devinit calculate_infoblock_crc(struct mxt_data *data, u32 *crc_pointer) { u32 crc = 0; u8 mem[7 + data->objects_len * 6]; int status; int i; status = read_mem(data, 0, sizeof(mem), mem); if (status) return status; for (i = 0; i < sizeof(mem) - 1; i += 2) crc = crc24(crc, mem[i], mem[i + 1]); *crc_pointer = crc24(crc, mem[i], 0) & 0x00FFFFFF; return 0; } uint8_t calibrate_chip_e(void) { u8 cal_data = 1; int ret = 0; /* send calibration command to the chip */ ret = write_mem(copy_data, copy_data->cmd_proc + CMD_CALIBRATE_OFFSET, 1, &cal_data); /* set flag for calibration lockup recovery if cal command was successful */ if (!ret) { printk(KERN_DEBUG "[TSP] calibration success!!!\n"); } return ret; } static unsigned int mxt_time_point; static unsigned int mxt_time_diff; static unsigned int mxt_timer_state; static unsigned int good_check_flag; static u8 cal_check_flag; uint8_t calibrate_chip(void) { u8 cal_data = 1; int ret = 0; u8 atchcalst_tmp, atchcalsthr_tmp; u16 obj_address = 0; u16 size = 1; int ret1 = 0; /* printk(KERN_ERR"[TSP]ret is %d,ret1 is %d\n",ret,ret1); */ if (cal_check_flag == 0) { ret = get_object_info(copy_data, GEN_ACQUISITIONCONFIG_T8, &size, &obj_address); size = 1; /* change calibration suspend settings to zero until calibration confirmed good */ /* store normal settings */ /* read_mem(copy_data, obj_address+6, (u8)size, &atchcalst); */ /* read_mem(copy_data, obj_address+7, (u8)size, &atchcalsthr); */ /* resume calibration must be performed with zero settings */ atchcalst_tmp = 0; atchcalsthr_tmp = 0; ret = write_mem(copy_data, obj_address+6, size, &atchcalst_tmp); ret1 = write_mem(copy_data, obj_address+7, size, &atchcalsthr_tmp); /* Write temporary acquisition config to chip. */ /* if (write_acquisition_config(acquisition_config) != CFG_WRITE_OK) { "Acquisition config write failed!\n" printk("\n[TSP][ERROR] line : %d\n", __LINE__); ret = WRITE_MEM_FAILED; calling function should retry calibration call }*/ /* restore settings to the local structure so that when we confirm the * cal is good we can correct them in the chip * this must be done before returning */ /* printk(KERN_ERR"[TSP] acquition restore! atchcalst=%d, atchcalsthr=%d\n", atchcalst, atchcalsthr ); write_mem(copy_data, obj_address+6, size, &atchcalst); write_mem(copy_data, obj_address+7, size, &atchcalsthr); */ } /* send calibration command to the chip */ if (!ret && !ret1 /*&& !Doing_calibration_falg*/) { /* change calibration suspend settings to zero until calibration confirmed good */ ret = write_mem(copy_data, copy_data->cmd_proc + CMD_CALIBRATE_OFFSET, 1, &cal_data); /* msleep(5); */ /*read_mem(copy_data, copy_data->cmd_proc+2, (u8)size, &value); printk(KERN_ERR"[TSP] calibration data is %d\n",value);*/ /* set flag for calibration lockup recovery if cal command was successful */ if (!ret) { /* set flag to show we must still confirm if calibration was good or bad */ cal_check_flag = 1u; /* Doing_calibration_falg = 1; */ printk(KERN_ERR "[TSP] calibration success!!!\n"); } } return ret; } static void treat_force_reset(struct mxt_data *data) { u8 i; u8 count = 0; int error = 0; printk(KERN_DEBUG "[TSP] %s execute !!\n", __func__); /* release touch */ for (i = 0; i < data->num_fingers; i++) { if (data->fingers[i].state == MXT_STATE_INACTIVE) continue; data->fingers[i].z = 0; data->fingers[i].state = MXT_STATE_RELEASE; count++; } if (count) report_input_data(data); /* reset the touch IC. */ error = mxt_reset(data); if (error < 0) printk(KERN_ERR"[TSP]mxt_reset fail!!!\n"); else msleep(MXT_RESET_TIME); } static void mxt_set_normal_config(struct mxt_data *data) { u16 size; u16 obj_address = 0; int error = 0; bool ta_status = 0; printk(KERN_DEBUG "[TSP] %s execute !!\n", __func__); get_object_info(data, GEN_POWERCONFIG_T7, &size, &obj_address); /* 1 :ACTVACQINT*/ error = change_config(data, obj_address, 1, 255); /* 2 :ACTV2IDLETO*/ error |= change_config(data, obj_address, 2, 25); get_object_info(data, GEN_ACQUISITIONCONFIG_T8, &size, &obj_address); /* 8:ATCHFRCCALTHR*/ error |= change_config(data, obj_address, 8, 50); /* 9:ATCHFRCCALRATIO*/ error |= change_config(data, obj_address, 9, 0); get_object_info(data, TOUCH_MULTITOUCHSCREEN_T9, &size, &obj_address); /* 31:TCHHYST */ error |= change_config(data, obj_address, 31, 15); get_object_info(data, PROCI_TOUCHSUPPRESSION_T42, &size, &obj_address); /* 0:CTRL */ error |= change_config(data, obj_address, 0, 3); get_object_info(data, SPT_CTECONFIG_T46, &size, &obj_address); data->read_ta_status(&ta_status); if (ta_status) { /* 2:IDLESYNCSPERX */ error |= change_config(data, obj_address, 2, data->idlesyncsperx_charging); /* 3:ACTVSYNCSPERX */ error |= change_config(data, obj_address, 3, data->actvsyncsperx_charging); } else { /* 2:IDLESYNCSPERX */ error |= change_config(data, obj_address, 2, data->idlesyncsperx_batt); /* 3:ACTVSYNCSPERX */ error |= change_config(data, obj_address, 3, data->actvsyncsperx_batt); } get_object_info(data, PROCG_NOISESUPPRESSION_T48, &size, &obj_address); /* 52:TCHHYST[0] */ error |= change_config(data, obj_address, 52, 15); get_object_info(data, SPT_GENERICDATA_T57, &size, &obj_address); /* 0:SUMSIZE */ error |= change_config(data, obj_address, 0, 131); if (error < 0) printk(KERN_ERR "[TSP] ta_probe write config Error!!\n"); } static void mxt_set_recovery_config(struct mxt_data *data) { u16 size; u16 obj_address = 0; int error = 0; printk(KERN_DEBUG "[TSP] %s execute !!\n", __func__); get_object_info(data, GEN_POWERCONFIG_T7, &size, &obj_address); /* 1 :ACTVACQINT*/ error = change_config(data, obj_address, 1, 16); /* 2 :ACTV2IDLETO*/ error |= change_config(data, obj_address, 2, 7); get_object_info(data, GEN_ACQUISITIONCONFIG_T8, &size, &obj_address); /* 8:ATCHFRCCALTHR*/ error |= change_config(data, obj_address, 8, 8); /* 9:ATCHFRCCALRATIO*/ error |= change_config(data, obj_address, 9, 136); get_object_info(data, TOUCH_MULTITOUCHSCREEN_T9, &size, &obj_address); /* 31:TCHHYST */ error |= change_config(data, obj_address, 31, 0); get_object_info(data, PROCI_TOUCHSUPPRESSION_T42, &size, &obj_address); /* 0:CTRL */ error |= change_config(data, obj_address, 0, 51); get_object_info(data, SPT_CTECONFIG_T46, &size, &obj_address); /* 2:IDLESYNCSPERX */ error |= change_config(data, obj_address, 2, 34); /* 3:ACTVSYNCSPERX */ error |= change_config(data, obj_address, 3, 34); get_object_info(data, PROCG_NOISESUPPRESSION_T48, &size, &obj_address); /* 52:TCHHYST[0] */ error |= change_config(data, obj_address, 52, 5); get_object_info(data, SPT_GENERICDATA_T57, &size, &obj_address); /* 0:SUMSIZE */ error |= change_config(data, obj_address, 0, 0); if (error < 0) printk(KERN_ERR "[TSP] %s write config Error!!\n" , __func__); count_overflow_detect = 0; } static void treat_error_status_e(void) { bool ta_status = 0; u16 size; u16 obj_address = 0; int error = 0; struct mxt_data *data = copy_data; data->read_ta_status(&ta_status); tchcount_aft_median_error = 0; cancel_delayed_work(&data->check_median_error_dwork); schedule_delayed_work(&data->check_median_error_dwork , HZ*TIME_FOR_CHECK_MEDIAN_ERROR); if (treat_median_error_status) { printk(KERN_ERR "[TSP] Error status already treated\n"); return; } else treat_median_error_status = 1; if (ta_status) { printk(KERN_ERR "[TSP] Error status TA is[%d]\n", ta_status); get_object_info(data, GEN_POWERCONFIG_T7, &size, &obj_address); /* 1:ACTVACQINT */ error = change_config(data, obj_address, 1, 255); get_object_info(data, GEN_ACQUISITIONCONFIG_T8, &size, &obj_address); /* 0:CHRGTIME */ error |= change_config(data, obj_address, 0, 64); /* 8:ATCHFRCCALTHR*/ error |= change_config(data, obj_address, 8, 50); /* 9:ATCHFRCCALRATIO*/ error |= change_config(data, obj_address, 9, 0); get_object_info(data, PROCI_TOUCHSUPPRESSION_T42, &size, &obj_address); /* 0:CTRL */ error |= change_config(data, obj_address, 0, 3); get_object_info(data, SPT_CTECONFIG_T46, &size, &obj_address); /* 2:IDLESYNCSPERX */ error |= change_config(data, obj_address, 2, 48); /* 3:ACTVSYNCSPERX */ error |= change_config(data, obj_address, 3, 48); get_object_info(data, PROCG_NOISESUPPRESSION_T48, &size, &obj_address); /* 2:CALCFG */ error |= change_config(data, obj_address, 2, 114); /* 3:BASEFREQ */ error |= change_config(data, obj_address, 3, 15); /* 8:MFFREQ[0] */ error |= change_config(data, obj_address, 8, 3); /* 9:MFFREQ[1] */ error |= change_config(data, obj_address, 9, 5); /* 10:NLGAIN*/ error |= change_config(data, obj_address, 10, 96); /* 11:NLTHR*/ error |= change_config(data, obj_address, 11, 30); /* 17:GCMAXADCSPERX */ error |= change_config(data, obj_address, 17, 100); /* 34:BLEN[0] */ error |= change_config(data, obj_address, 34, 80); /* 35:TCHTHR[0] */ error |= change_config(data, obj_address, 35, 40); /* 36:TCHDI[0] */ error |= change_config(data, obj_address, 36, 2); /* 39:MOVFILTER[0] */ error |= change_config(data, obj_address, 39, 65); /* 41:MRGHYST[0] */ error |= change_config(data, obj_address, 41, 40); /* 42:MRGTHR[0] */ error |= change_config(data, obj_address, 42, 50); /* 43:XLOCLIP[0] */ error |= change_config(data, obj_address, 43, 5); /* 44:XHICLIP[0] */ error |= change_config(data, obj_address, 44, 5); /* 51:JUMPLIMIT[0] */ error |= change_config(data, obj_address, 51, 25); /* 52:TCHHYST[0] */ error |= change_config(data, obj_address, 52, 15); if (error < 0) printk(KERN_ERR "[TSP] failed to write error status\n"); } else { printk(KERN_ERR "[TSP] Error status TA is[%d]\n", ta_status); get_object_info(data, GEN_POWERCONFIG_T7, &size, &obj_address); /* 1:ACTVACQINT */ error = change_config(data, obj_address, 1, 255); get_object_info(data, GEN_ACQUISITIONCONFIG_T8, &size, &obj_address); /* 0:CHRGTIME */ error |= change_config(data, obj_address, 0, 64); /* 8:ATCHFRCCALTHR*/ error |= change_config(data, obj_address, 8, 50); /* 9:ATCHFRCCALRATIO*/ error |= change_config(data, obj_address, 9, 0); get_object_info(data, TOUCH_MULTITOUCHSCREEN_T9, &size, &obj_address); /* 31:TCHHYST */ error |= change_config(data, obj_address, 31, 15); get_object_info(data, PROCI_TOUCHSUPPRESSION_T42, &size, &obj_address); /* 0:CTRL */ error |= change_config(data, obj_address, 0, 3); get_object_info(data, SPT_CTECONFIG_T46, &size, &obj_address); /* 2:IDLESYNCSPERX */ error |= change_config(data, obj_address, 2, 48); /* 3:ACTVSYNCSPERX */ error |= change_config(data, obj_address, 3, 48); get_object_info(data, PROCG_NOISESUPPRESSION_T48, &size, &obj_address); /* 2:CALCFG */ error |= change_config(data, obj_address, 2, 242); /* 3:BASEFREQ */ error |= change_config(data, obj_address, 3, 15); /* 8:MFFREQ[0] */ error |= change_config(data, obj_address, 8, 3); /* 9:MFFREQ[1] */ error |= change_config(data, obj_address, 9, 5); /* 10:NLGAIN*/ error |= change_config(data, obj_address, 10, 112); /* 11:NLTHR*/ error |= change_config(data, obj_address, 11, 25); /* 17:GCMAXADCSPERX */ error |= change_config(data, obj_address, 17, 100); /* 34:BLEN[0] */ error |= change_config(data, obj_address, 34, 112); /* 35:TCHTHR[0] */ error |= change_config(data, obj_address, 35, 40); /* 41:MRGHYST[0] */ error |= change_config(data, obj_address, 41, 40); /* 42:MRGTHR[0] */ error |= change_config(data, obj_address, 42, 50); /* 51:JUMPLIMIT[0] */ error |= change_config(data, obj_address, 51, 25); /* 52:TCHHYST[0] */ error |= change_config(data, obj_address, 52, 15); if (error < 0) printk(KERN_ERR "[TSP] failed to write error status\n"); } } /* this function is called in irq routine */ static void treat_calibration_state(struct mxt_data *data) { first_touch_detected = 0; overflow_detected = 0; palm_detected_check = 0; count_abnormal_palm = 0; cancel_delayed_work(&data->overflow_dwork); cancel_delayed_work(&data->check_abnormal_palm_dwork); if (config_dwork_flag == CAL_FROM_RESUME) { config_dwork_flag = CAL_BEF_WORK_CALLED; } else if (config_dwork_flag == CAL_BEF_WORK_CALLED) { cancel_delayed_work(&data->config_dwork); schedule_delayed_work(&data->config_dwork , HZ*TIME_FOR_RECONFIG); } else if (config_dwork_flag == CAL_REP_WORK_CALLED) { cancel_delayed_work(&data->config_dwork); schedule_delayed_work(&data->config_dwork , HZ*TIME_FOR_RECONFIG_ON_REPET); } else if (config_dwork_flag == CAL_AFT_WORK_CALLED) { mxt_set_recovery_config(data); config_dwork_flag = CAL_BEF_WORK_CALLED; schedule_delayed_work(&data->config_dwork , HZ*TIME_FOR_RECONFIG); } } /* mxt224E reconfigration */ static void mxt_reconfigration_normal(struct work_struct *work) { struct mxt_data *data = container_of(work, struct mxt_data, config_dwork.work); if (mxt_enabled) { disable_irq(data->client->irq); if (first_touch_detected && !overflow_detected) { mxt_set_normal_config(data); config_dwork_flag = CAL_AFT_WORK_CALLED; } else { cancel_delayed_work(&data->config_dwork); schedule_delayed_work(&data->config_dwork , HZ*TIME_FOR_RECONFIG_ON_REPET); config_dwork_flag = CAL_REP_WORK_CALLED; } enable_irq(data->client->irq); } return; } static void mxt_calbration_by_overflowed(struct work_struct *work) { struct mxt_data *data = container_of(work, struct mxt_data, overflow_dwork.work); u8 id; int error = 0; u8 count = 0; bool ta_status = 0; if (mxt_enabled) { disable_irq(data->client->irq); printk(KERN_DEBUG "[TSP] %s execute [%s][%d]\n", __func__ , (overflow_detected == 1) ? "T" : "F", count_overflow_detect); if (overflow_detected) { for (id = 0 ; id < MAX_USING_FINGER_NUM ; ++id) { if (data->fingers[id].state == MXT_STATE_INACTIVE) continue; if (data->fingers[id].mcount > 10) { overflow_detected = 0; enable_irq(data->client->irq); return; } } if (!first_touch_detected) count_overflow_detect++; if (count_overflow_detect >= LIMIT_OVERFLOW_CNT) { count_overflow_detect = 0; treat_force_reset(data); enable_irq(data->client->irq); if (data->read_ta_status) { data->read_ta_status(&ta_status); printk(KERN_DEBUG "[TSP] ta_status is %d\n", ta_status); mxt_ta_probe(ta_status); } } else { calibrate_chip_e(); enable_irq(data->client->irq); } } } } static void mxt_check_medianfilter_error(struct work_struct *work) { printk(KERN_DEBUG "[TSP] %s [%d]\n", __func__, tchcount_aft_median_error); if (tchcount_aft_median_error >= CNTLMTTCH_AFT_MEDIAN_ERROR) { calibrate_chip_e(); } tchcount_aft_median_error = 0; } static void mxt_check_abnormal_palm(struct work_struct *work) { struct mxt_data *data = container_of(work, struct mxt_data, check_abnormal_palm_dwork.work); if (mxt_enabled) { disable_irq(data->client->irq); if (palm_detected_check) { if (count_abnormal_palm >= LIMIT_ABNORMAL_PALM) { count_abnormal_palm = 0; calibrate_chip_e(); } else { /* to check palm is keep going or not */ schedule_delayed_work( &data->check_abnormal_palm_dwork, HZ*TIME_FOR_RECAL_ABNMAL_PALM); } } else { if (count_abnormal_palm == 1) { printk(KERN_DEBUG "[TSP] calibration for palm\n"); calibrate_chip_e(); } } palm_detected_check = 0; enable_irq(data->client->irq); } } #if TOUCH_BOOSTER static void mxt_set_dvfs_off(struct work_struct *work) { struct mxt_data *data = container_of(work, struct mxt_data, dvfs_dwork.work); if (mxt_enabled) { disable_irq(data->client->irq); if (touch_cpu_lock_status && !tsp_press_status){ s5pv310_cpufreq_lock_free(DVFS_LOCK_ID_TSP); touch_cpu_lock_status = 0; } enable_irq(data->client->irq); } } static void mxt_set_dvfs_on(struct mxt_data *data) { cancel_delayed_work(&data->dvfs_dwork); if (cpu_lv < 0) cpu_lv = s5pv310_cpufreq_round_idx(CPUFREQ_500MHZ); s5pv310_cpufreq_lock(DVFS_LOCK_ID_TSP, cpu_lv); touch_cpu_lock_status = 1; } #endif static int check_abs_time(void) { if (!mxt_time_point) return 0; mxt_time_diff = jiffies_to_msecs(jiffies) - mxt_time_point; if (mxt_time_diff > 0) return 1; else return 0; } void check_chip_calibration(void) { u8 data_buffer[100] = { 0 }; u8 try_ctr = 0; u8 data_byte = 0xF3; /* dianostic command to get touch flags */ u8 tch_ch = 0, atch_ch = 0; /* u8 atchcalst, atchcalsthr; */ u8 check_mask; u8 i, j = 0; u8 x_line_limit; int ret; u16 size; u16 object_address = 0; /* we have had the first touchscreen or face suppression message * after a calibration - check the sensor state and try to confirm if * cal was good or bad */ /* get touch flags from the chip using the diagnostic object */ /* write command to command processor to get touch flags - 0xF3 Command required to do this */ /* write_mem(command_processor_address + DIAGNOSTIC_OFFSET, 1, &data_byte); */ write_mem(copy_data, copy_data->cmd_proc + CMD_DIAGNOSTIC_OFFSET, 1, &data_byte); /* get the address of the diagnostic object so we can get the data we need */ /* diag_address = get_object_address(DEBUG_DIAGNOSTIC_T37,0); */ ret = get_object_info(copy_data, DEBUG_DIAGNOSTIC_T37, &size, &object_address); msleep(10); /* read touch flags from the diagnostic object - clear buffer so the while loop can run first time */ memset(data_buffer , 0xFF, sizeof(data_buffer)); /* wait for diagnostic object to update */ while (!((data_buffer[0] == 0xF3) && (data_buffer[1] == 0x00))) { /* wait for data to be valid */ if (try_ctr > 10) { /* Failed! */ printk(KERN_ERR"[TSP] Diagnostic Data did not update!!\n"); mxt_timer_state = 0; break; } mdelay(2); try_ctr++; /* timeout counter */ /* read_mem(diag_address, 2,data_buffer); */ read_mem(copy_data, object_address, 2, data_buffer); } /* data is ready - read the detection flags */ /* read_mem(diag_address, 82,data_buffer); */ read_mem(copy_data, object_address, 82, data_buffer); /* data array is 20 x 16 bits for each set of flags, 2 byte header, 40 bytes for touch flags 40 bytes for antitouch flags*/ /* count up the channels/bits if we recived the data properly */ if ((data_buffer[0] == 0xF3) && (data_buffer[1] == 0x00)) { /* mode 0 : 16 x line, mode 1 : 17 etc etc upto mode 4.*/ /* x_line_limit = 16 + cte_config.mode; */ x_line_limit = 16 + 3; if (x_line_limit > 20) { /* hard limit at 20 so we don't over-index the array */ x_line_limit = 20; } /* double the limit as the array is in bytes not words */ x_line_limit = x_line_limit << 1; /* count the channels and print the flags to the log */ for (i = 0; i < x_line_limit; i += 2) { /* check X lines - data is in words so increment 2 at a time */ /* print the flags to the log - only really needed for debugging */ /* count how many bits set for this row */ for (j = 0; j < 8; j++) { /* create a bit mask to check against */ check_mask = 1 << j; /* check detect flags */ if (data_buffer[2+i] & check_mask) tch_ch++; if (data_buffer[3+i] & check_mask) tch_ch++; /* check anti-detect flags */ if (data_buffer[42+i] & check_mask) atch_ch++; if (data_buffer[43+i] & check_mask) atch_ch++; } } printk(KERN_ERR"[TSP] t: %d, a: %d\n", tch_ch, atch_ch); /* send page up command so we can detect when data updates next time, * page byte will sit at 1 until we next send F3 command */ data_byte = 0x01; /* write_mem(command_processor_address + DIAGNOSTIC_OFFSET, 1, &data_byte); */ write_mem(copy_data, copy_data->cmd_proc + CMD_DIAGNOSTIC_OFFSET, 1, &data_byte); /* process counters and decide if we must re-calibrate or if cal was good */ if ((tch_ch > 0) && (atch_ch == 0)) { /* jwlee change. */ /* cal was good - don't need to check any more */ if (!check_abs_time()) mxt_time_diff = 501; if (mxt_timer_state == 1) { if (mxt_time_diff > 500) { printk(KERN_ERR"[TSP] calibration was good\n"); cal_check_flag = 0; good_check_flag = 0; mxt_timer_state = 0; mxt_time_point = jiffies_to_msecs(jiffies); ret = get_object_info(copy_data, GEN_ACQUISITIONCONFIG_T8, &size, &object_address); /* change calibration suspend settings to zero until calibration confirmed good */ /* store normal settings */ size = 1; write_mem(copy_data, object_address+6, size, &copy_data->atchcalst); write_mem(copy_data, object_address+7, size, &copy_data->atchcalsthr); /* dprintk("[TSP] reset acq atchcalst=%d, atchcalsthr=%d\n", acquisition_config.atchcalst, acquisition_config.atchcalsthr ); */ /* Write normal acquisition config back to the chip. if (write_acquisition_config(acquisition_config) != CFG_WRITE_OK) { "Acquisition config write failed!\n" printk(KERN_DEBUG "\n[TSP][ERROR] line : %d\n", __LINE__); MUST be fixed } */ } else { cal_check_flag = 1; } } else { mxt_timer_state = 1; mxt_time_point = jiffies_to_msecs(jiffies); cal_check_flag = 1; } } else if (atch_ch >= 5) { /* cal was bad - must recalibrate and check afterwards */ printk(KERN_ERR"[TSP] calibration was bad\n"); calibrate_chip(); mxt_timer_state = 0; mxt_time_point = jiffies_to_msecs(jiffies); } else { /* we cannot confirm if good or bad - we must wait for next touch message to confirm */ printk(KERN_ERR"[TSP] calibration was not decided yet\n"); cal_check_flag = 1u; mxt_timer_state = 0; mxt_time_point = jiffies_to_msecs(jiffies); } } } static void mxt_ta_probe(int ta_status) { u16 obj_address = 0; u16 size; u8 value; int error; struct mxt_data *data = copy_data; if (!mxt_enabled) { printk(KERN_ERR"mxt_enabled is 0\n"); return; } if (data->family_id == 0xA1) { /* MXT-768E */ if (treat_median_error_status) { treat_median_error_status = 0; tchcount_aft_median_error = 0; } if (ta_status) { get_object_info(data, GEN_POWERCONFIG_T7, &size, &obj_address); /* 0:IDLEACQINT */ error = change_config(data, obj_address, 0, data->idleacqint_charging); #if 0 /*it was setted in mxt_set_normal_config*/ /* 1:ACTVACQINT */ error |= change_config(data, obj_address, 1, data->actacqint_charging); #endif get_object_info(data, GEN_ACQUISITIONCONFIG_T8, &size, &obj_address); /* 0:CHRGTIME */ error |= change_config(data, obj_address, 0, data->chrgtime_charging); get_object_info(data, TOUCH_MULTITOUCHSCREEN_T9, &size, &obj_address); error |= change_config(data, obj_address, 22, data->xloclip_charging); error |= change_config(data, obj_address, 23, data->xhiclip_charging); error |= change_config(data, obj_address, 24, data->yloclip_charging); error |= change_config(data, obj_address, 25, data->yhiclip_charging); error |= change_config(data, obj_address, 26, data->xedgectrl_charging); error |= change_config(data, obj_address, 27, data->xedgedist_charging); error |= change_config(data, obj_address, 28, data->yedgectrl_charging); error |= change_config(data, obj_address, 29, data->yedgedist_charging); error |= write_config(data, data->t48_config_chrg_e[0], data->t48_config_chrg_e + 1); #if 0 /*it was setted in mxt_set_normal_config*/ get_object_info(data, SPT_CTECONFIG_T46, &size, &obj_address); /* 2:IDLESYNCSPERX */ error |= change_config(data, obj_address, 2, data->idlesyncsperx_charging); /* 3:ACTVSYNCSPERX */ error |= change_config(data, obj_address, 3, data->actvsyncsperx_charging); #endif threshold = data->tchthr_charging; if (error < 0) printk(KERN_ERR "[TSP] ta_probe write config Error!!\n"); } else { get_object_info(data, GEN_POWERCONFIG_T7, &size, &obj_address); /* 0:IDLEACQINT */ error = change_config(data, obj_address, 0, data->idleacqint_batt); #if 0 /*it was setted in mxt_set_normal_config*/ /* 1:ACTVACQINT */ error |= change_config(data, obj_address, 1, data->actacqint_batt); #endif get_object_info(data, GEN_ACQUISITIONCONFIG_T8, &size, &obj_address); /* 0:CHRGTIME */ error |= change_config(data, obj_address, 0, data->chrgtime_batt); get_object_info(data, TOUCH_MULTITOUCHSCREEN_T9, &size, &obj_address); error |= change_config(data, obj_address, 7, data->tchthr_batt); error |= change_config(data, obj_address, 22, data->xloclip_batt); error |= change_config(data, obj_address, 23, data->xhiclip_batt); error |= change_config(data, obj_address, 24, data->yloclip_batt); error |= change_config(data, obj_address, 25, data->yhiclip_batt); error |= change_config(data, obj_address, 26, data->xedgectrl_batt); error |= change_config(data, obj_address, 27, data->xedgedist_batt); error |= change_config(data, obj_address, 28, data->yedgectrl_batt); error |= change_config(data, obj_address, 29, data->yedgedist_batt); error |= change_config(data, obj_address, 31, data->tchhyst_batt); error |= write_config(data, data->t48_config_batt_e[0], data->t48_config_batt_e + 1); #if 0 /*it was setted in mxt_set_normal_config*/ get_object_info(data, SPT_CTECONFIG_T46, &size, &obj_address); /* 2:IDLESYNCSPERX */ error |= change_config(data, obj_address, 2, data->idlesyncsperx_batt); /* 3:ACTVSYNCSPERX */ error |= change_config(data, obj_address, 3, data->actvsyncsperx_batt); #endif threshold = data->tchthr_batt; if (error < 0) printk(KERN_ERR "[TSP] ta_probe write config Error!!\n"); } } else if (data->family_id == 0x81) { /* : MXT-224E */ get_object_info(data, PROCG_NOISESUPPRESSION_T48, &size, &obj_address); if (ta_status) { error = write_config(data, data->t48_config_chrg_e[0], data->t48_config_chrg_e + 1); value = data->calcfg_charging_e | 0x20; threshold = data->tchthr_charging; } else { error = write_config(data, data->t48_config_batt_e[0], data->t48_config_batt_e + 1); value = data->calcfg_batt_e | 0x20; threshold = data->tchthr_batt; } error |= write_mem(data, obj_address+2, 1, &value); if (error < 0) printk(KERN_ERR "[TSP] mxt TA/USB mxt_noise_suppression_config Error!!\n"); } else if (data->family_id == 0x80) { /* : MXT-224 */ if (ta_status) { threshold = data->tchthr_charging; } else { threshold = data->tchthr_batt; } get_object_info(data, TOUCH_MULTITOUCHSCREEN_T9, &size, &obj_address); write_mem(data, obj_address+7, 1, &threshold); } printk("[TSP] threshold : %d\n", threshold); }; #if defined(DRIVER_FILTER) static void equalize_coordinate(bool detect, u8 id, u16 *px, u16 *py) { static int tcount[MAX_USING_FINGER_NUM] = { 0, }; static u16 pre_x[MAX_USING_FINGER_NUM][4] = {{0}, }; static u16 pre_y[MAX_USING_FINGER_NUM][4] = {{0}, }; int coff[4] = {0,}; int distance = 0; if (detect) { tcount[id] = 0; } pre_x[id][tcount[id]%4] = *px; pre_y[id][tcount[id]%4] = *py; if (tcount[id] > 3) { { distance = abs(pre_x[id][(tcount[id]-1)%4] - *px) + abs(pre_y[id][(tcount[id]-1)%4] - *py); coff[0] = (u8)(2 + distance/5); if (coff[0] < 8) { coff[0] = max(2, coff[0]); coff[1] = min((8 - coff[0]), (coff[0]>>1)+1); coff[2] = min((8 - coff[0] - coff[1]), (coff[1]>>1)+1); coff[3] = 8 - coff[0] - coff[1] - coff[2]; /* printk(KERN_DEBUG "[TSP] %d, %d, %d, %d", coff[0], coff[1], coff[2], coff[3]); */ *px = (u16)((*px*(coff[0]) + pre_x[id][(tcount[id]-1)%4]*(coff[1]) + pre_x[id][(tcount[id]-2)%4]*(coff[2]) + pre_x[id][(tcount[id]-3)%4]*(coff[3]))/8); *py = (u16)((*py*(coff[0]) + pre_y[id][(tcount[id]-1)%4]*(coff[1]) + pre_y[id][(tcount[id]-2)%4]*(coff[2]) + pre_y[id][(tcount[id]-3)%4]*(coff[3]))/8); } else { *px = (u16)((*px*4 + pre_x[id][(tcount[id]-1)%4])/5); *py = (u16)((*py*4 + pre_y[id][(tcount[id]-1)%4])/5); } } } tcount[id]++; } #endif /* DRIVER_FILTER */ uint8_t reportid_to_type(struct mxt_data *data, u8 report_id, u8 *instance) { report_id_map_t *report_id_map; report_id_map = rid_map; if (report_id <= max_report_id) { *instance = report_id_map[report_id].instance; return (report_id_map[report_id].object_type); } else return 0; } static int __devinit mxt_init_touch_driver(struct mxt_data *data) { struct object_t *object_table; u32 read_crc = 0; u32 calc_crc; u16 crc_address; u16 dummy; int i, j; u8 id[ID_BLOCK_SIZE]; int ret; u8 type_count = 0; u8 tmp; u16 size, obj_address; u8 value; int current_report_id, start_report_id; ret = read_mem(data, 0, sizeof(id), id); if (ret) return ret; dev_info(&data->client->dev, "family = %#02x, variant = %#02x, version " "= %#02x, build = %d\n", id[0], id[1], id[2], id[3]); printk(KERN_ERR" family = %#02x, variant = %#02x, version " "= %#02x, build = %d\n", id[0], id[1], id[2], id[3]); dev_dbg(&data->client->dev, "matrix X size = %d\n", id[4]); dev_dbg(&data->client->dev, "matrix Y size = %d\n", id[5]); data->family_id = id[0]; data->tsp_variant = id[1]; data->tsp_version = id[2]; data->tsp_build = id[3]; data->objects_len = id[6]; object_table = kmalloc(data->objects_len * sizeof(*object_table), GFP_KERNEL); if (!object_table) return -ENOMEM; ret = read_mem(data, OBJECT_TABLE_START_ADDRESS, data->objects_len * sizeof(*object_table), (u8 *)object_table); if (ret) goto err; max_report_id = 0; for (i = 0; i < data->objects_len; i++) { object_table[i].i2c_address = le16_to_cpu(object_table[i].i2c_address); max_report_id += object_table[i].num_report_ids * (object_table[i].instances + 1); tmp = 0; if (object_table[i].num_report_ids) { tmp = type_count + 1; type_count += object_table[i].num_report_ids * (object_table[i].instances + 1); } switch (object_table[i].object_type) { case TOUCH_MULTITOUCHSCREEN_T9: data->finger_type = tmp; dev_dbg(&data->client->dev, "Finger type = %d\n", data->finger_type); break; case GEN_MESSAGEPROCESSOR_T5: #ifdef ITDEV data->msg_proc_addr = object_table[i].i2c_address; #endif data->msg_object_size = object_table[i].size + 1; dev_dbg(&data->client->dev, "Message object size = " "%d\n", data->msg_object_size); break; } } if (rid_map_alloc) { rid_map_alloc = false; kfree(rid_map); } rid_map = kmalloc((sizeof(report_id_map_t) * max_report_id + 1), GFP_KERNEL); if (!rid_map) { kfree(object_table); return -ENOMEM; } rid_map_alloc = true; rid_map[0].instance = 0; rid_map[0].object_type = 0; current_report_id = 1; for (i = 0; i < data->objects_len; i++) { if (object_table[i].num_report_ids != 0) { for (j = 0; j <= object_table[i].instances; j++) { for (start_report_id = current_report_id; current_report_id < (start_report_id + object_table[i].num_report_ids); current_report_id++) { rid_map[current_report_id].instance = j; rid_map[current_report_id].object_type = object_table[i].object_type; } } } } data->objects = object_table; /* Verify CRC */ crc_address = OBJECT_TABLE_START_ADDRESS + data->objects_len * OBJECT_TABLE_ELEMENT_SIZE; #ifdef __BIG_ENDIAN #error The following code will likely break on a big endian machine #endif ret = read_mem(data, crc_address, 3, (u8 *)&read_crc); if (ret) goto err; read_crc = le32_to_cpu(read_crc); ret = calculate_infoblock_crc(data, &calc_crc); if (ret) goto err; if (read_crc != calc_crc) { dev_err(&data->client->dev, "CRC error\n"); ret = -EFAULT; goto err; } ret = get_object_info(data, GEN_MESSAGEPROCESSOR_T5, &dummy, &data->msg_proc); if (ret) goto err; ret = get_object_info(data, GEN_COMMANDPROCESSOR_T6, &dummy, &data->cmd_proc); if (ret) goto err; return 0; err: kfree(object_table); return ret; } static void report_input_data(struct mxt_data *data) { int i; int count = 0; int report_count = 0; int press_count = 0; int move_count = 0; for (i = 0; i < data->num_fingers; i++) { if (data->fingers[i].state == MXT_STATE_INACTIVE) continue; input_report_abs(data->input_dev, ABS_MT_POSITION_X, data->fingers[i].x); input_report_abs(data->input_dev, ABS_MT_POSITION_Y, data->fingers[i].y); input_report_abs(data->input_dev, ABS_MT_TOUCH_MAJOR, data->fingers[i].z); input_report_abs(data->input_dev, ABS_MT_WIDTH_MAJOR, data->fingers[i].w); input_report_abs(data->input_dev, ABS_MT_TRACKING_ID, i); #ifdef _SUPPORT_SHAPE_TOUCH_ input_report_abs(data->input_dev, ABS_MT_COMPONENT, data->fingers[i].component); /* printk(KERN_ERR"the component data is %d\n",data->fingers[i].component); */ #endif input_mt_sync(data->input_dev); report_count++; #ifdef SHOW_COORDINATE if (data->fingers[i].state == MXT_STATE_PRESS || data->fingers[i].state == MXT_STATE_RELEASE) { printk(KERN_DEBUG "[TSP] id[%d],x=%d,y=%d,z=%d,w=%d,mc=%d\n", i , data->fingers[i].x, data->fingers[i].y , data->fingers[i].z, data->fingers[i].w , data->fingers[i].mcount); } #else if (data->fingers[i].state == MXT_STATE_PRESS) printk(KERN_DEBUG "[TSP] P: id[%d],w=%d\n" , i, data->fingers[i].w); else if (data->fingers[i].state == MXT_STATE_RELEASE) printk(KERN_DEBUG "[TSP] R: id[%d],mc=%d\n" , i, data->fingers[i].mcount); #endif if (treat_median_error_status) { if (data->fingers[i].state == MXT_STATE_RELEASE || data->fingers[i].state == MXT_STATE_PRESS) { tchcount_aft_median_error++; if (tchcount_aft_median_error > 100) tchcount_aft_median_error = 0; } } else tchcount_aft_median_error = 0; if (data->fingers[i].state == MXT_STATE_RELEASE) { data->fingers[i].state = MXT_STATE_INACTIVE; data->fingers[i].mcount = 0; } else { data->fingers[i].state = MXT_STATE_MOVE; count++; } } if (report_count > 0) { #ifdef ITDEV if (!driver_paused) #endif input_sync(data->input_dev); } if (count) touch_is_pressed = 1; else touch_is_pressed = 0; #if TOUCH_BOOSTER if (count == 0) { if (touch_cpu_lock_status) { cancel_delayed_work(&data->dvfs_dwork); schedule_delayed_work(&data->dvfs_dwork, msecs_to_jiffies(TOUCH_BOOSTER_TIME)); } tsp_press_status = 0; } else tsp_press_status = 1; #endif data->finger_mask = 0; } static irqreturn_t mxt_irq_thread(int irq, void *ptr) { struct mxt_data *data = ptr; int id; u8 msg[data->msg_object_size]; u8 touch_message_flag = 0; u16 obj_address = 0; u16 size; u8 value; int error; u8 object_type, instance; #if USE_SUMSIZE uint16_t sum_size = 0; #endif do { touch_message_flag = 0; if (read_mem(data, data->msg_proc, sizeof(msg), msg)) { #if TOUCH_BOOSTER if (touch_cpu_lock_status) { s5pv310_cpufreq_lock_free(DVFS_LOCK_ID_TSP); touch_cpu_lock_status = 0; } #endif return IRQ_HANDLED; } #ifdef ITDEV//itdev if (debug_enabled) print_hex_dump(KERN_DEBUG, "MXT MSG:", DUMP_PREFIX_NONE, 16, 1, msg, sizeof(msg), false); #endif object_type = reportid_to_type(data, msg[0] , &instance); if (object_type == GEN_COMMANDPROCESSOR_T6) { if (msg[1] == 0x00) /* normal mode */ { printk("[TSP] normal mode\n"); } if ((msg[1]&0x04) == 0x04) /* I2C checksum error */ { printk("[TSP] I2C checksum error\n"); } if ((msg[1]&0x08) == 0x08) /* config error */ { printk("[TSP] config error\n"); } if ((msg[1]&0x10) == 0x10) /* calibration */ { printk(KERN_DEBUG "[TSP] calibration is" " on going !!\n"); treat_calibration_state(data); } if ((msg[1]&0x20) == 0x20) /* signal error */ { printk("[TSP] signal error\n"); } if ((msg[1]&0x40) == 0x40) /* overflow */ { printk("[TSP] overflow detected\n"); overflow_detected = 1; cancel_delayed_work(&data->overflow_dwork); schedule_delayed_work(&data->overflow_dwork , HZ*TIME_FOR_RECALIBRATION); } if ((msg[1]&0x80) == 0x80) /* reset */ { printk("[TSP] reset is ongoing\n"); } } if (object_type == PROCI_TOUCHSUPPRESSION_T42) { get_object_info(data, GEN_ACQUISITIONCONFIG_T8, &size, &obj_address); if ((msg[1] & 0x01) == 0x00) { /* Palm release */ printk(KERN_DEBUG "[TSP] palm touch released\n"); if (palm_detected_check) count_abnormal_palm++; else count_abnormal_palm = 0; touch_is_pressed = 0; } else if ((msg[1] & 0x01) == 0x01) { /* Palm Press */ printk(KERN_DEBUG "[TSP] palm touch detected\n"); if (!palm_detected_check) { count_abnormal_palm = 1; palm_detected_check = 1; cancel_delayed_work( &data->check_abnormal_palm_dwork); schedule_delayed_work( &data->check_abnormal_palm_dwork, msecs_to_jiffies( TIME_FOR_CHK_ABNMAL_PALM)); } else count_abnormal_palm++; touch_is_pressed = 1; touch_message_flag = 1; } } if (object_type == PROCG_NOISESUPPRESSION_T48) { /* printk(KERN_ERR "[TSP] T48 [STATUS]:%#02x" "[ADCSPERX]:%#02x[FRQ]:%#02x" "[STATE]:%#02x[NLEVEL]:%#02x\n" , msg[1], msg[2], msg[3], msg[4], msg[5]);*/ if (msg[4] == 5) { /* Median filter error */ printk(KERN_ERR "[TSP] Median filter error\n"); if ((data->family_id == 0xA1) && ((data->tsp_version == 0x13) || (data->tsp_version == 0x20))) { if (data->read_ta_status) treat_error_status_e(); } else { get_object_info(data, PROCG_NOISESUPPRESSION_T48, &size, &obj_address); value = data->calcfg_batt_e; error = write_mem(data, obj_address+2, 1, &value); msleep(5); value |= 0x20; error |= write_mem(data, obj_address+2, 1, &value); if(error) printk(KERN_ERR "[TSP] failed to reenable CHRGON\n"); } } } #if USE_SUMSIZE if (object_type == SPT_GENERICDATA_T57) { sum_size = msg[1]; sum_size += (msg[2]<<8); } #endif if (object_type == TOUCH_MULTITOUCHSCREEN_T9) { id = msg[0] - data->finger_type; if (data->family_id == 0x80) { /* : MXT-224 */ if ( (data->fingers[id].state >= MXT_STATE_PRESS) && msg[1] & PRESS_MSG_MASK ) { printk("[TSP] calibrate on ghost touch\n"); calibrate_chip(); } } /* If not a touch event, then keep going */ if (id < 0 || id >= data->num_fingers){ continue; } if (data->finger_mask & (1U << id)) report_input_data(data); if (msg[1] & RELEASE_MSG_MASK) { data->fingers[id].z = 0; data->fingers[id].w = msg[5]; data->finger_mask |= 1U << id; data->fingers[id].state = MXT_STATE_RELEASE; } else if ((msg[1] & DETECT_MSG_MASK) && (msg[1] & (PRESS_MSG_MASK | MOVE_MSG_MASK))) { #if TOUCH_BOOSTER if (!touch_cpu_lock_status) mxt_set_dvfs_on(data); #endif touch_message_flag = 1; data->fingers[id].z = msg[6]; data->fingers[id].w = msg[5]; // data->fingers[id].x = (((msg[2] << 4) | (msg[4] >> 4)) >> data->x_dropbits) * 1280/1024 ; // data->fingers[id].y = (((msg[3] << 4) | (msg[4] & 0xF)) >> data->y_dropbits) * 800/1024 ; data->fingers[id].x = (((msg[2] << 4) | (msg[4] >> 4)) >> data->x_dropbits); data->fingers[id].y = (((msg[3] << 4) | (msg[4] & 0xF)) >> data->y_dropbits); data->finger_mask |= 1U << id; if (msg[1] & PRESS_MSG_MASK) { #if defined(DRIVER_FILTER) equalize_coordinate(1, id, &data->fingers[id].x, &data->fingers[id].y); #endif data->fingers[id].state = MXT_STATE_PRESS; data->fingers[id].mcount = 0; if (!first_touch_detected) { first_touch_detected = 1; count_overflow_detect = 0; } } else if (msg[1] & MOVE_MSG_MASK) { #if defined(DRIVER_FILTER) equalize_coordinate(0, id, &data->fingers[id].x, &data->fingers[id].y); #endif data->fingers[id].mcount += 1; } #ifdef _SUPPORT_SHAPE_TOUCH_ data->fingers[id].component= msg[7]; #endif } else if ((msg[1] & SUPPRESS_MSG_MASK) && (data->fingers[id].state != MXT_STATE_INACTIVE)) { data->fingers[id].z = 0; data->fingers[id].w = msg[5]; data->fingers[id].state = MXT_STATE_RELEASE; data->finger_mask |= 1U << id; } else { dev_dbg(&data->client->dev, "Unknown state %#02x %#02x\n", msg[0], msg[1]); continue; } } } while (!gpio_get_value(data->gpio_read_done)); if (data->finger_mask) { #if USE_SUMSIZE if (sum_size > 0) { /* case of normal configuration */ u8 num_finger = 0; u8 i; uint16_t t9_sum_size = 0; for (i = 0; i < data->num_fingers; i++) { if (data->fingers[i].state == MXT_STATE_INACTIVE || data->fingers[i].state == MXT_STATE_RELEASE) continue; t9_sum_size += data->fingers[i].w; num_finger++; } if ((num_finger == 1) && ((sum_size-t9_sum_size) >= MAX_SUMSIZE)) { printk(KERN_DEBUG "[TSP] recalibrate for max sumsize[%d]" "t9_sum_size[%d]\n" , sum_size, t9_sum_size); calibrate_chip_e(); } else { report_input_data(data); } t9_sum_size = 0; sum_size = 0; } else { /* case of recovery configuration */ report_input_data(data); } #else report_input_data(data); #endif } if (data->family_id == 0x80) { /* : MXT-224 */ if (touch_message_flag && (cal_check_flag)) { check_chip_calibration(); } } return IRQ_HANDLED; } static void mxt_deepsleep(struct mxt_data *data) { u8 power_cfg[3] = {0, }; write_config(data, GEN_POWERCONFIG_T7, power_cfg); deepsleep = 1; } static void mxt_wakeup(struct mxt_data *data) { write_config(data, GEN_POWERCONFIG_T7, data->power_cfg); } static int mxt_internal_suspend(struct mxt_data *data) { int i; int count = 0; if (data->family_id == 0xA1) { /* : MXT-768E */ cancel_delayed_work(&data->config_dwork); cancel_delayed_work(&data->overflow_dwork); cancel_delayed_work(&data->check_median_error_dwork); cancel_delayed_work(&data->check_abnormal_palm_dwork); } else if (data->family_id == 0x81) { /* : MXT-224E */ cancel_delayed_work(&data->config_dwork); } for (i = 0; i < data->num_fingers; i++) { if (data->fingers[i].state == MXT_STATE_INACTIVE) continue; data->fingers[i].z = 0; data->fingers[i].state = MXT_STATE_RELEASE; count++; } if (count) report_input_data(data); #if TOUCH_BOOSTER cancel_delayed_work(&data->dvfs_dwork); tsp_press_status = 0; if (touch_cpu_lock_status) { s5pv310_cpufreq_lock_free(DVFS_LOCK_ID_TSP); touch_cpu_lock_status = 0; } #endif /*if (!deepsleep) data->power_off();*/ data->power_off(); return 0; } static int mxt_internal_resume(struct mxt_data *data) { /*if (!deepsleep) data->power_on(); else mxt_wakeup(data);*/ data->power_on(); return 0; } #ifdef CONFIG_HAS_EARLYSUSPEND #define mxt_suspend NULL #define mxt_resume NULL static void mxt_early_suspend(struct early_suspend *h) { struct mxt_data *data = container_of(h, struct mxt_data, early_suspend); if (mxt_enabled == 1) { printk(KERN_DEBUG"[TSP] %s\n", __func__); mxt_enabled = 0; touch_is_pressed = 0; disable_irq(data->client->irq); mxt_internal_suspend(data); } else printk(KERN_ERR"[TSP] %s. but touch already off\n", __func__); } static void mxt_late_resume(struct early_suspend *h) { bool ta_status = 0; struct mxt_data *data = container_of(h, struct mxt_data, early_suspend); if (mxt_enabled == 0) { printk(KERN_DEBUG"[TSP] %s\n", __func__); mxt_internal_resume(data); /*if (!deepsleep) enable_irq(data->client->irq);*/ mxt_enabled = 1; if (data->read_ta_status) { data->read_ta_status(&ta_status); printk("[TSP] ta_status is %d\n", ta_status); /*if (!(deepsleep && ta_status)) mxt_ta_probe(ta_status);*/ mxt_ta_probe(ta_status); } if (data->family_id == 0xA1) {/* : MXT-768E */ config_dwork_flag = CAL_FROM_RESUME; overflow_detected = 0; first_touch_detected = 0; treat_median_error_status = 0; tchcount_aft_median_error = 0; palm_detected_check = 0; count_overflow_detect = 0; calibrate_chip_e(); } else if (data->family_id == 0x81) { /* : MXT-224E */ calibrate_chip_e(); schedule_delayed_work(&data->config_dwork, HZ*5); } else calibrate_chip(); enable_irq(data->client->irq); /*if(deepsleep) deepsleep = 0;*/ } else printk(KERN_ERR"[TSP] %s. but touch already on\n", __func__); } #else static int mxt_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct mxt_data *data = i2c_get_clientdata(client); mxt_enabled = 0; touch_is_pressed = 0; #if TOUCH_BOOSTER tsp_press_status = 0; #endif return mxt_internal_suspend(data); } static int mxt_resume(struct device *dev) { int ret = 0; bool ta_status = 0; struct i2c_client *client = to_i2c_client(dev); struct mxt_data *data = i2c_get_clientdata(client); ret = mxt_internal_resume(data); mxt_enabled = 1; if (data->read_ta_status) { data->read_ta_status(&ta_status); printk("[TSP] ta_status is %d\n", ta_status); mxt_ta_probe(ta_status); } return ret; } #endif void Mxt_force_released(void) { struct mxt_data *data = copy_data; int i; if (!mxt_enabled) { printk(KERN_ERR"[TSP] mxt_enabled is 0\n"); return; } for (i = 0; i < data->num_fingers; i++) { if (data->fingers[i].state == MXT_STATE_INACTIVE) continue; data->fingers[i].z = 0; data->fingers[i].state = MXT_STATE_RELEASE; } report_input_data(data); if (data->family_id == 0xA1) { /* : MXT-768E */ calibrate_chip_e(); } else if (data->family_id == 0x81) { /* : MXT-224E */ calibrate_chip_e(); } else calibrate_chip(); }; EXPORT_SYMBOL(Mxt_force_released); static ssize_t mxt_debug_setting(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { g_debug_switch = !g_debug_switch; return 0; } static ssize_t mxt_object_setting(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct mxt_data *data = dev_get_drvdata(dev); unsigned int object_type; unsigned int object_register; unsigned int register_value; u8 value; u8 val; int ret; u16 address; u16 size; sscanf(buf, "%u%u%u", &object_type, &object_register, &register_value); printk(KERN_ERR "[TSP] object type T%d", object_type); printk(KERN_ERR "[TSP] object register ->Byte%d\n", object_register); printk(KERN_ERR "[TSP] register value %d\n", register_value); ret = get_object_info(data, (u8)object_type, &size, &address); if (ret) { printk(KERN_ERR "[TSP] fail to get object_info\n"); return count; } size = 1; value = (u8)register_value; write_mem(data, address+(u16)object_register, size, &value); read_mem(data, address+(u16)object_register, (u8)size, &val); printk(KERN_ERR "[TSP] T%d Byte%d is %d\n", object_type, object_register, val); return count; } static ssize_t mxt_object_show(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct mxt_data *data = dev_get_drvdata(dev); unsigned int object_type; u8 val; int ret; u16 address; u16 size; u16 i; sscanf(buf, "%u", &object_type); printk("[TSP] object type T%d\n", object_type); ret = get_object_info(data, (u8)object_type, &size, &address); if (ret) { printk(KERN_ERR "[TSP] fail to get object_info\n"); return count; } for (i = 0; i < size; i++) { read_mem(data, address+i, 1, &val); printk("[TSP] Byte %u --> %u\n", i, val); } return count; } struct device *sec_touchscreen; static u8 firmware_latest[] = {0x16, 0x20}; /* mxt224 : 0x16, mxt224E : 0x10 */ static u8 build_latest[] = {0xAB, 0xAA}; struct device *mxt_noise_test; /* top_left, top_right, center, bottom_left, bottom_right */ unsigned int test_node[5] = {642, 98, 367, 668, 124}; uint16_t qt_refrence_node[768] = { 0 }; uint16_t qt_delta_node[768] = { 0 }; void diagnostic_chip(u8 mode) { int error; u16 t6_address = 0; u16 size_one; int ret; u8 value; u16 t37_address = 0; ret = get_object_info(copy_data, GEN_COMMANDPROCESSOR_T6, &size_one, &t6_address); size_one = 1; error = write_mem(copy_data, t6_address+5, (u8)size_one, &mode); /* qt602240_write_object(p_qt602240_data, QT602240_GEN_COMMAND, */ /* QT602240_COMMAND_DIAGNOSTIC, mode); */ if (error < 0) { printk(KERN_ERR "[TSP] error %s: write_object\n", __func__); } else { get_object_info(copy_data, DEBUG_DIAGNOSTIC_T37, &size_one, &t37_address); size_one = 1; /* printk(KERN_ERR"diagnostic_chip setting success\n"); */ read_mem(copy_data, t37_address, (u8)size_one, &value); /* printk(KERN_ERR"dianostic_chip mode is %d\n",value); */ } } uint8_t read_uint16_t(struct mxt_data *data, uint16_t address, uint16_t *buf ) { uint8_t status; uint8_t temp[2]; status = read_mem(data, address, 2, temp); *buf= ((uint16_t)temp[1]<<8)+ (uint16_t)temp[0]; return (status); } void read_dbg_data(uint8_t dbg_mode , uint16_t node, uint16_t *dbg_data) { u8 read_page, read_point; uint8_t mode,page; u16 size; u16 diagnostic_addr = 0; if (!mxt_enabled) { printk(KERN_ERR "[TSP ]read_dbg_data. mxt_enabled is 0\n"); return; } get_object_info(copy_data, DEBUG_DIAGNOSTIC_T37, &size, &diagnostic_addr); read_page = node / 64; node %= 64; read_point = (node * 2) + 2; /* Page Num Clear */ diagnostic_chip(MXT_CTE_MODE); msleep(10); do { if(read_mem(copy_data, diagnostic_addr, 1, &mode)) { printk(KERN_INFO "[TSP] READ_MEM_FAILED \n"); return; } } while(mode != MXT_CTE_MODE); diagnostic_chip(dbg_mode); msleep(10); do { if(read_mem(copy_data, diagnostic_addr, 1, &mode)) { printk(KERN_INFO "[TSP] READ_MEM_FAILED \n"); return; } } while(mode != dbg_mode); for(page = 1; page <= read_page;page++) { diagnostic_chip(MXT_PAGE_UP); msleep(10); do { if(read_mem(copy_data, diagnostic_addr + 1, 1, &mode)) { printk(KERN_INFO "[TSP] READ_MEM_FAILED \n"); return; } } while(mode != page); } if(read_uint16_t(copy_data, diagnostic_addr + read_point, dbg_data)) { printk(KERN_INFO "[TSP] READ_MEM_FAILED \n"); return; } } #define MIN_VALUE 19744 #define MAX_VALUE 28884 #define MIN_VALUE_TA_ERROR_MODE 19125 #define T48_CALCFG_CHRGON 0x20 /* caution : should check the sensor level this value is depend on tsp tunning state */ #define SENSOR_GAIN_TAERROR 5 int read_all_data(uint16_t dbg_mode) { u8 read_page, read_point; u16 max_value = MIN_VALUE, min_value = MAX_VALUE; u16 ref_max_value = MAX_VALUE; u16 ref_min_value = MIN_VALUE; u16 object_address = 0; u8 data_buffer[2] = { 0 }; u8 node = 0; int state = 0; int num = 0; int ret; u16 size; u8 val = 0; u8 sensor_gain = 0; bool ta_status = 0; if (copy_data->read_ta_status) { copy_data->read_ta_status(&ta_status); printk(KERN_INFO "[TSP] ta_status is %d\n", ta_status); } /* check the CHRG_ON bit is set or not */ /* when CHRG_ON is setted dual x is on so skip read last line*/ get_object_info(copy_data, PROCG_NOISESUPPRESSION_T48, &size, &object_address); ret = read_mem(copy_data, object_address+2 , 1, &val); if (ret < 0) printk(KERN_ERR " TSP read fail : %s", __func__); printk(KERN_INFO "[TSP] %s CALCFG[%#02x]\n", __func__, val); val = val & T48_CALCFG_CHRGON; /* read sensor gain to check reference value */ if (val == T48_CALCFG_CHRGON) { ret = read_mem(copy_data, object_address+34 , 1, &sensor_gain); if (ret < 0) printk(KERN_ERR " TSP read fail : %s", __func__); sensor_gain = (sensor_gain&0xF0)>>4; printk(KERN_INFO "[TSP] %s BLEN[%d]\n", __func__, sensor_gain); if (sensor_gain == SENSOR_GAIN_TAERROR) ref_min_value = MIN_VALUE_TA_ERROR_MODE; } /* Page Num Clear */ diagnostic_chip(MXT_CTE_MODE); msleep(30);/* msleep(20); */ diagnostic_chip(dbg_mode); msleep(30);/* msleep(20); */ ret = get_object_info(copy_data, DEBUG_DIAGNOSTIC_T37, &size, &object_address); msleep(50); /* msleep(20); */ /* 768/64 */ for (read_page = 0 ; read_page < 12; read_page++) { for (node = 0; node < 64; node++) { read_point = (node * 2) + 2; read_mem(copy_data, object_address+(u16)read_point, 2, data_buffer); qt_refrence_node[num] = ((uint16_t)data_buffer[1]<<8)+ (uint16_t)data_buffer[0]; /* last X line has 1/2 reference during TA mode So do not check min/max value */ if ((val != T48_CALCFG_CHRGON) || (val == T48_CALCFG_CHRGON && (num < 736))) { if ((qt_refrence_node[num] < ref_min_value) || (qt_refrence_node[num] > ref_max_value)) { if (sensor_gain == SENSOR_GAIN_TAERROR) state = 2; else state = 1; printk(KERN_ERR"[TSP] Mxt768E qt_refrence_node[%3d] = %5d\n", num, qt_refrence_node[num]); } if (data_buffer[0] != 0) { if (qt_refrence_node[num] > max_value) max_value = qt_refrence_node[num]; if (qt_refrence_node[num] < min_value) min_value = qt_refrence_node[num]; } } num++; /* all node => 24 * 32 = 768 => (12page * 64) */ /* if ((read_page == 11) && (node == 64)) break; */ if (qt_refrence_node[num-1] == 0) printk(KERN_ERR"[TSP]qt_refrence_node[%d] = 0\n", num); if (num == 768) break; } diagnostic_chip(MXT_PAGE_UP); msleep(35); if (num == 768) break; } if ((max_value - min_value) > 4500) { printk(KERN_ERR "[TSP] diff = %d, max_value = %d, min_value = %d\n", (max_value - min_value), max_value, min_value); state = 1; } return state; } int read_all_delta_data(uint16_t dbg_mode) { u8 read_page, read_point; u16 object_address = 0; u8 data_buffer[2] = { 0 }; u8 node = 0; int state = 0; int num = 0; int ret; u16 size; /* Page Num Clear */ diagnostic_chip(MXT_CTE_MODE); msleep(30);/* msleep(20); */ diagnostic_chip(dbg_mode); msleep(30);/* msleep(20); */ ret = get_object_info(copy_data, DEBUG_DIAGNOSTIC_T37, &size, &object_address); /*jerry no need to leave it */ #if 0 for (i = 0; i < 5; i++) { if (data_buffer[0] == dbg_mode) break; msleep(20); } #else msleep(50); /* msleep(20); */ #endif /* 768/64 */ for (read_page = 0 ; read_page < 12; read_page++) { for (node = 0; node < 64; node++) { read_point = (node * 2) + 2; read_mem(copy_data, object_address+(u16)read_point, 2, data_buffer); qt_delta_node[num] = ((uint16_t)data_buffer[1]<<8)+ (uint16_t)data_buffer[0]; num++; /* all node => 24 * 32 = 768 => (12page * 64) */ /*if ((read_page == 11) && (node == 64)) break;*/ } diagnostic_chip(MXT_PAGE_UP); msleep(35); } return state; } int find_channel(uint16_t dbg_mode) { u8 read_page, read_point; u16 object_address = 0; u8 data_buffer[2] = { 0 }; u8 node = 0; int state = 0; int num = 0; int ret; u16 size; u16 delta_val = 0; u16 max_val = 0; /* Page Num Clear */ diagnostic_chip(MXT_CTE_MODE); msleep(30);/* msleep(20); */ diagnostic_chip(dbg_mode); msleep(30);/* msleep(20); */ ret = get_object_info(copy_data, DEBUG_DIAGNOSTIC_T37, &size, &object_address); /*jerry no need to leave it */ #if 0 for (i = 0; i < 5; i++) { if (data_buffer[0] == dbg_mode) break; msleep(20); } #else msleep(50); /* msleep(20); */ #endif /* 768/64 */ for (read_page = 0 ; read_page < 12; read_page++) { for (node = 0; node < 64; node++) { read_point = (node * 2) + 2; read_mem(copy_data, object_address+(u16)read_point, 2, data_buffer); delta_val = ((uint16_t)data_buffer[1]<<8)+ (uint16_t)data_buffer[0]; if (delta_val > 32767) delta_val = 65535 - delta_val; if (delta_val > max_val) { max_val = delta_val; state = (read_point - 2)/2 + (read_page * 64); } num++; /* all node => 24 * 32 = 768 => (12page * 64) */ /*if ((read_page == 11) && (node == 64)) break;*/ } diagnostic_chip(MXT_PAGE_UP); msleep(35); } return state; } static ssize_t find_channel_show(struct device *dev, struct device_attribute *attr, char *buf) { int status = 0; //struct mxt_data *mxt = dev_get_drvdata(dev); status = find_channel(MXT_DELTA_MODE); return sprintf(buf, "%u\n", status); } static int mxt_check_bootloader(struct i2c_client *client, unsigned int state) { u8 val; u8 temp; recheck: if (i2c_master_recv(client, &val, 1) != 1) { dev_err(&client->dev, "%s: i2c recv failed\n", __func__); return -EIO; } if (val & 0x20) { if (i2c_master_recv(client, &temp, 1) != 1) { dev_err(&client->dev, "%s: i2c recv failed\n", __func__); return -EIO; } if (i2c_master_recv(client, &temp, 1) != 1) { dev_err(&client->dev, "%s: i2c recv failed\n", __func__); return -EIO; } val &= ~0x20; } if ((val & 0xF0)== MXT_APP_CRC_FAIL) { printk("[TOUCH] MXT_APP_CRC_FAIL\n"); if (i2c_master_recv(client, &val, 1) != 1) { dev_err(&client->dev, "%s: i2c recv failed\n", __func__); return -EIO; } if(val & 0x20) { if (i2c_master_recv(client, &temp, 1) != 1) { dev_err(&client->dev, "%s: i2c recv failed\n", __func__); return -EIO; } if (i2c_master_recv(client, &temp, 1) != 1) { dev_err(&client->dev, "%s: i2c recv failed\n", __func__); return -EIO; } val &= ~0x20; } } switch (state) { case MXT_WAITING_BOOTLOAD_CMD: case MXT_WAITING_FRAME_DATA: val &= ~MXT_BOOT_STATUS_MASK; break; case MXT_FRAME_CRC_PASS: if (val == MXT_FRAME_CRC_CHECK) goto recheck; break; default: return -EINVAL; } if (val != state) { dev_err(&client->dev, "Unvalid bootloader mode state\n"); printk(KERN_ERR "[TSP] Unvalid bootloader mode state\n"); return -EINVAL; } return 0; } static int mxt_unlock_bootloader(struct i2c_client *client) { u8 buf[2]; buf[0] = MXT_UNLOCK_CMD_LSB; buf[1] = MXT_UNLOCK_CMD_MSB; if (i2c_master_send(client, buf, 2) != 2) { dev_err(&client->dev, "%s: i2c send failed\n", __func__); return -EIO; } return 0; } static int mxt_fw_write(struct i2c_client *client, const u8 *data, unsigned int frame_size) { if (i2c_master_send(client, data, frame_size) != frame_size) { dev_err(&client->dev, "%s: i2c send failed\n", __func__); return -EIO; } return 0; } static int mxt_load_fw(struct device *dev, const char *fn) { struct mxt_data *data = copy_data; struct i2c_client *client = copy_data->client; /*const */struct firmware *fw = NULL; unsigned int frame_size; unsigned int pos = 0; int ret; u16 obj_address=0; u16 size_one; u8 value; unsigned int object_register; int check_frame_crc_error = 0; int check_wating_frame_data_error = 0; printk("[TSP] mxt_load_fw start!!!\n"); /*ret = request_firmware(&fw, fn, &client->dev); if (ret) { dev_err(dev, "Unable to open firmware %s\n", fn); printk(KERN_ERR "[TSP] Unable to open firmware %s\n", fn); return ret; } */ fw = kmalloc(sizeof(struct firmware), GFP_KERNEL); if(!fw) { printk("[TSP] mxt_load_fw kmalloc Failed !!!\n"); return -ENOMEM; } fw->size = ARRAY_SIZE(mXT768e__APP_V2_0_AA); fw->data = mXT768e__APP_V2_0_AA; /* Change to the bootloader mode */ /* mxt_write_object(data, MXT_GEN_COMMAND, MXT_COMMAND_RESET, MXT_BOOT_VALUE); */ object_register = 0; value = (u8)MXT_BOOT_VALUE; ret = get_object_info(data, GEN_COMMANDPROCESSOR_T6, &size_one, &obj_address); if (ret) { printk(KERN_ERR"[TSP] fail to get object_info\n"); /*release_firmware(fw); */ kfree(fw); fw = NULL; return ret; } size_one = 1; write_mem(data, obj_address+(u16)object_register, (u8)size_one, &value); msleep(MXT_RESET_TIME); /* Change to slave address of bootloader */ if (data->family_id == 0xA1) { /* : MXT-768E */ if (client->addr == MXT768E_APP_LOW) client->addr = MXT768E_BOOT_LOW; else client->addr = MXT768E_BOOT_HIGH; } else { if (client->addr == MXT_APP_LOW) client->addr = MXT_BOOT_LOW; else client->addr = MXT_BOOT_HIGH; } ret = mxt_check_bootloader(client, MXT_WAITING_BOOTLOAD_CMD); if (ret) goto out; /* Unlock bootloader */ mxt_unlock_bootloader(client); while (pos < fw->size) { ret = mxt_check_bootloader(client, MXT_WAITING_FRAME_DATA); if (ret) { check_wating_frame_data_error++; if (check_wating_frame_data_error > 10) { printk(KERN_ERR"[TSP] firm update fail. wating_frame_data err\n"); goto out; } else { printk("[TSP]check_wating_frame_data_error = %d, retry\n", check_wating_frame_data_error); continue; } } frame_size = ((*(fw->data + pos) << 8) | *(fw->data + pos + 1)); /* We should add 2 at frame size as the the firmware data is not * included the CRC bytes. */ frame_size += 2; /* Write one frame to device */ /* mxt_fw_write(client, fw->data + pos, frame_size); */ mxt_fw_write(client, fw->data + pos, frame_size); ret = mxt_check_bootloader(client, MXT_FRAME_CRC_PASS); if (ret) { check_frame_crc_error++; if (check_frame_crc_error > 10) { printk(KERN_ERR"[TSP] firm update fail. frame_crc err\n"); goto out; } else { printk("[TSP]check_frame_crc_error = %d, retry\n", check_frame_crc_error); continue; } } pos += frame_size; dev_dbg(dev, "Updated %d bytes / %zd bytes\n", pos, fw->size); printk("[TSP] Updated %d bytes / %zd bytes\n", pos, fw->size); msleep(1); } out: kfree(fw); fw = NULL; /*release_firmware(fw);*/ /* Change to slave address of application */ if (data->family_id == 0xA1) { /* : MXT-768E */ if (client->addr == MXT768E_BOOT_LOW) client->addr = MXT768E_APP_LOW; else client->addr = MXT768E_APP_HIGH; } else { if (client->addr == MXT_BOOT_LOW) client->addr = MXT_APP_LOW; else client->addr = MXT_APP_HIGH; } return ret; } static int mxt_load_fw_bootmode(struct device *dev, const char *fn) { struct mxt_data *data = copy_data; struct i2c_client *client = copy_data->client; /*const */struct firmware *fw = NULL; unsigned int frame_size; unsigned int pos = 0; int ret; u16 obj_address=0; u16 size_one; u8 value; unsigned int object_register; int check_frame_crc_error = 0; int check_wating_frame_data_error = 0; printk("[TSP] mxt_load_fw start!!!\n"); /*ret = request_firmware(&fw, fn, &client->dev); if (ret) { dev_err(dev, "Unable to open firmware %s\n", fn); printk(KERN_ERR "[TSP] Unable to open firmware %s\n", fn); return ret; } */ fw = kmalloc(sizeof(struct firmware), GFP_KERNEL); if(!fw) { printk("[TSP] mxt_load_fw_bootmode kmalloc Failed !!!\n"); return -ENOMEM; } fw->size = ARRAY_SIZE(mXT768e__APP_V2_0_AA); fw->data = mXT768e__APP_V2_0_AA; /* Unlock bootloader */ mxt_unlock_bootloader(client); while (pos < fw->size) { ret = mxt_check_bootloader(client, MXT_WAITING_FRAME_DATA); if (ret) { check_wating_frame_data_error++; if (check_wating_frame_data_error > 10) { printk(KERN_ERR"[TSP] firm update fail. wating_frame_data err\n"); goto out; } else { printk("[TSP]check_wating_frame_data_error = %d, retry\n", check_wating_frame_data_error); continue; } } frame_size = ((*(fw->data + pos) << 8) | *(fw->data + pos + 1)); /* We should add 2 at frame size as the the firmware data is not * included the CRC bytes. */ frame_size += 2; /* Write one frame to device */ /* mxt_fw_write(client, fw->data + pos, frame_size); */ mxt_fw_write(client, fw->data + pos, frame_size); ret = mxt_check_bootloader(client, MXT_FRAME_CRC_PASS); if (ret) { check_frame_crc_error++; if (check_frame_crc_error > 10) { printk(KERN_ERR"[TSP] firm update fail. frame_crc err\n"); goto out; } else { printk("[TSP]check_frame_crc_error = %d, retry\n", check_frame_crc_error); continue; } } pos += frame_size; dev_dbg(dev, "Updated %d bytes / %zd bytes\n", pos, fw->size); printk("[TSP] Updated %d bytes / %zd bytes\n", pos, fw->size); msleep(1); } out: kfree(fw); fw = NULL; /*release_firmware(fw);*/ /* Change to slave address of application */ if (data->family_id == 0xA1) { /* : MXT-768E */ if (client->addr == MXT768E_BOOT_LOW) client->addr = MXT768E_APP_LOW; else client->addr = MXT768E_APP_HIGH; } else { if (client->addr == MXT_BOOT_LOW) client->addr = MXT_APP_LOW; else client->addr = MXT_APP_HIGH; } return ret; } static ssize_t set_refer0_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = copy_data; uint16_t mxt_reference=0; read_dbg_data(MXT_REFERENCE_MODE, test_node[0],&mxt_reference); return sprintf(buf, "%u\n", mxt_reference); } static ssize_t set_refer1_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = copy_data; uint16_t mxt_reference=0; read_dbg_data(MXT_REFERENCE_MODE, test_node[1], &mxt_reference); return sprintf(buf, "%u\n", mxt_reference); } static ssize_t set_refer2_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = copy_data; uint16_t mxt_reference=0; read_dbg_data(MXT_REFERENCE_MODE, test_node[2], &mxt_reference); return sprintf(buf, "%u\n", mxt_reference); } static ssize_t set_refer3_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = copy_data; uint16_t mxt_reference=0; read_dbg_data(MXT_REFERENCE_MODE, test_node[3], &mxt_reference); return sprintf(buf, "%u\n", mxt_reference); } static ssize_t set_refer4_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { uint16_t mxt_reference=0; read_dbg_data(MXT_REFERENCE_MODE, test_node[4], &mxt_reference); return sprintf(buf, "%u\n", mxt_reference); } static ssize_t set_delta0_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { uint16_t mxt_delta=0; read_dbg_data(MXT_DELTA_MODE, test_node[0], &mxt_delta); if (mxt_delta < 32767) return sprintf(buf, "%u\n", mxt_delta); else mxt_delta = 65535 - mxt_delta; if(mxt_delta) return sprintf(buf, "-%u\n", mxt_delta); else return sprintf(buf, "%u\n", mxt_delta); } static ssize_t set_delta1_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { uint16_t mxt_delta=0; read_dbg_data(MXT_DELTA_MODE, test_node[1], &mxt_delta); if (mxt_delta < 32767) return sprintf(buf, "%u\n", mxt_delta); else mxt_delta = 65535 - mxt_delta; if(mxt_delta) return sprintf(buf, "-%u\n", mxt_delta); else return sprintf(buf, "%u\n", mxt_delta); } static ssize_t set_delta2_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { uint16_t mxt_delta=0; read_dbg_data(MXT_DELTA_MODE, test_node[2], &mxt_delta); if (mxt_delta < 32767) return sprintf(buf, "%u\n", mxt_delta); else mxt_delta = 65535 - mxt_delta; if(mxt_delta) return sprintf(buf, "-%u\n", mxt_delta); else return sprintf(buf, "%u\n", mxt_delta); } static ssize_t set_delta3_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { uint16_t mxt_delta=0; read_dbg_data(MXT_DELTA_MODE, test_node[3], &mxt_delta); if (mxt_delta < 32767) return sprintf(buf, "%u\n", mxt_delta); else mxt_delta = 65535 - mxt_delta; if(mxt_delta) return sprintf(buf, "-%u\n", mxt_delta); else return sprintf(buf, "%u\n", mxt_delta); } static ssize_t set_delta4_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { uint16_t mxt_delta=0; read_dbg_data(MXT_DELTA_MODE, test_node[4], &mxt_delta); if (mxt_delta < 32767) return sprintf(buf, "%u\n", mxt_delta); else mxt_delta = 65535 - mxt_delta; if(mxt_delta) return sprintf(buf, "-%u\n", mxt_delta); else return sprintf(buf, "%u\n", mxt_delta); } static ssize_t set_threshold_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", threshold); } static ssize_t set_all_refer_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { int status = 0; status = read_all_data(MXT_REFERENCE_MODE); return sprintf(buf, "%u\n", status); } static int index_reference; static int atoi(char *str) { int result = 0; int count = 0; if( str == NULL ) return -1; while( str[count] != NULL && str[count] >= '0' && str[count] <= '9' ) { result = result * 10 + str[count] - '0'; ++count; } return result; } ssize_t disp_all_refdata_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", qt_refrence_node[index_reference]); } ssize_t disp_all_refdata_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { index_reference = atoi(buf); return size; } static ssize_t set_all_delta_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { int status = 0; status = read_all_delta_data(MXT_DELTA_MODE); return sprintf(buf, "%u\n", status); } static int index_delta; ssize_t disp_all_deltadata_show(struct device *dev, struct device_attribute *attr, char *buf) { if (qt_delta_node[index_delta] < 32767) return sprintf(buf, "%u\n", qt_delta_node[index_delta]); else qt_delta_node[index_delta] = 65535 - qt_delta_node[index_delta]; return sprintf(buf, "-%u\n", qt_delta_node[index_delta]); } ssize_t disp_all_deltadata_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { index_delta = atoi(buf); return size; } static ssize_t set_firm_version_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = copy_data; u8 id[ID_BLOCK_SIZE]; u8 value; int ret; u8 i; if (mxt_enabled == 1) { disable_irq(data->client->irq); for (i = 0; i < 4; i++) { ret = read_mem(copy_data, 0, sizeof(id), id); if (!ret) break; } enable_irq(data->client->irq); if (ret < 0) { printk(KERN_ERR " TSP read fail : %s", __func__); value = 0; return sprintf(buf, "%d\n", value); } else { printk(KERN_DEBUG "%s : %#02x\n", __func__, id[2]); return sprintf(buf, "%#02x\n", id[2]); } } else { printk(KERN_ERR " TSP power off : %s", __func__); value = 0; return sprintf(buf, "%d\n", value); } } static ssize_t set_module_off_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = copy_data; int count; if (mxt_enabled == 1) { mxt_enabled = 0; touch_is_pressed = 0; #if TOUCH_BOOSTER tsp_press_status = 0; #endif disable_irq(data->client->irq); mxt_internal_suspend(data); } count = sprintf(buf, "tspoff\n"); return count; } static ssize_t set_module_on_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = copy_data; int count; bool ta_status = 0; if (mxt_enabled == 0) { mxt_internal_resume(data); enable_irq(data->client->irq); mxt_enabled = 1; if (data->read_ta_status) { data->read_ta_status(&ta_status); printk("[TSP] ta_status is %d\n", ta_status); mxt_ta_probe(ta_status); } calibrate_chip(); } count = sprintf(buf, "tspon\n"); return count; } #ifdef FOR_DEBUGGING_TEST_DOWNLOADFW_BIN // add_for_bin_download #include <linux/uaccess.h> #define MXT768E_FW_BIN_NAME "/sdcard/mxt768e.bin" static int mxt_download(const u8 *pBianry, const u32 unLength) { struct mxt_data *data = copy_data; struct i2c_client *client = copy_data->client; unsigned int frame_size; unsigned int pos = 0; int ret; u16 obj_address=0; u16 size_one; u8 value; unsigned int object_register; int check_frame_crc_error = 0; int check_wating_frame_data_error = 0; pr_info("[TSP] mxt_download start!!!\n"); /* Change to the bootloader mode */ /* mxt_write_object(data, MXT_GEN_COMMAND, MXT_COMMAND_RESET, MXT_BOOT_VALUE); */ object_register = 0; value = (u8)MXT_BOOT_VALUE; ret = get_object_info(data, GEN_COMMANDPROCESSOR_T6, &size_one, &obj_address); if (ret) { pr_err("TSP] fail to get object_info\n"); return ret; } size_one = 1; pr_info("[TSP] 3\n"); write_mem(data, obj_address+(u16)object_register, (u8)size_one, &value); msleep(MXT_RESET_TIME); /* Change to slave address of bootloader */ if (data->family_id == 0xA1) { /* : MXT-768E */ if (client->addr == MXT768E_APP_LOW) client->addr = MXT768E_BOOT_LOW; else client->addr = MXT768E_BOOT_HIGH; } else { if (client->addr == MXT_APP_LOW) client->addr = MXT_BOOT_LOW; else client->addr = MXT_BOOT_HIGH; } ret = mxt_check_bootloader(client, MXT_WAITING_BOOTLOAD_CMD); if (ret) goto out; /* Unlock bootloader */ mxt_unlock_bootloader(client); while (pos < unLength) { ret = mxt_check_bootloader(client, MXT_WAITING_FRAME_DATA); if (ret) { check_wating_frame_data_error++; if (check_wating_frame_data_error > 10) { printk(KERN_ERR"[TSP] firm update fail. wating_frame_data err\n"); goto out; } else { printk("[TSP]check_wating_frame_data_error = %d, retry\n", check_wating_frame_data_error); continue; } } frame_size = ((*(pBianry + pos) << 8) | *(pBianry + pos + 1)); /* We should add 2 at frame size as the the firmware data is not * included the CRC bytes. */ frame_size += 2; /* Write one frame to device */ /* mxt_fw_write(client, fw->data + pos, frame_size); */ mxt_fw_write(client, pBianry + pos, frame_size); ret = mxt_check_bootloader(client, MXT_FRAME_CRC_PASS); if (ret) { check_frame_crc_error++; if (check_frame_crc_error > 10) { pr_err("[TSP] firm update fail. frame_crc err\n"); goto out; } else { pr_info("[TSP]check_frame_crc_error = %d, retry\n", check_frame_crc_error); continue; } } pos += frame_size; pr_info("[TSP] Updated %d bytes / %zd bytes\n", pos, unLength); msleep(1); } out: /* Change to slave address of application */ if (data->family_id == 0xA1) { /* : MXT-768E */ if (client->addr == MXT768E_BOOT_LOW) client->addr = MXT768E_APP_LOW; else client->addr = MXT768E_APP_HIGH; } else { if (client->addr == MXT_BOOT_LOW) client->addr = MXT_APP_LOW; else client->addr = MXT_APP_HIGH; } return ret; } int mxt_binfile_download(void) { int nRet = 0; int retry_cnt = 0; long fw1_size = 0; unsigned char *fw_data1; struct file *filp; loff_t pos; int ret = 0; mm_segment_t oldfs; spinlock_t lock; oldfs = get_fs(); set_fs(get_ds()); filp = filp_open(MXT768E_FW_BIN_NAME, O_RDONLY, 0); if (IS_ERR(filp)) { pr_err("file open error:%d\n", (s32)filp); return -1; } fw1_size = filp->f_path.dentry->d_inode->i_size; pr_info("Size of the file : %ld(bytes)\n", fw1_size); fw_data1 = kmalloc(fw1_size, GFP_KERNEL); memset(fw_data1, 0, fw1_size); pos = 0; memset(fw_data1, 0, fw1_size); ret = vfs_read(filp, (char __user *)fw_data1, fw1_size, &pos); if(ret != fw1_size) { pr_err("Failed to read file %s (ret = %d)\n", MXT768E_FW_BIN_NAME, ret); kfree(fw_data1); filp_close(filp, current->files); return -1; } filp_close(filp, current->files); set_fs(oldfs); for (retry_cnt = 0; retry_cnt < 3; retry_cnt++) { pr_info("[TSP] ADB - MASTER CHIP Firmware update! try : %d",retry_cnt+1); nRet = mxt_download( (const u8*) fw_data1, (const u32)fw1_size); if (nRet) continue; break; } kfree(fw_data1); return nRet; } #endif static ssize_t set_mxt_firm_update_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct mxt_data *data = dev_get_drvdata(dev); int error = 0; printk("[TSP] set_mxt_update_show start!!\n"); if (*buf != 'S' && *buf != 'F') { printk(KERN_ERR"Invalid values\n"); dev_err(dev, "Invalid values\n"); return -EINVAL; } disable_irq(data->client->irq); firm_status_data = 1; #ifdef FOR_DEBUGGING_TEST_DOWNLOADFW_BIN // add_for_bin_download error = mxt_binfile_download(); #else if (data->family_id == 0xA1) { /* : MXT-768E */ if (*buf != 'F' && data->tsp_version >= firmware_latest[1] && data->tsp_build >= build_latest[1]) { printk(KERN_ERR"[TSP] mxt768E has latest firmware\n"); firm_status_data =2; enable_irq(data->client->irq); return size; } printk("[TSP] mxt768E_fm_update\n"); error = mxt_load_fw(dev, MXT768E_FW_NAME); } else if (data->family_id == 0x80) { /* : MXT-224 */ if (*buf != 'F' && data->tsp_version >= firmware_latest[0] && data->tsp_build >= build_latest[0]) { printk(KERN_ERR"[TSP] mxt224 has latest firmware\n"); firm_status_data =2; enable_irq(data->client->irq); return size; } printk("[TSP] mxt224_fm_update\n"); error = mxt_load_fw(dev, MXT224_FW_NAME); } else if (data->family_id == 0x81) { /* tsp_family_id - 0x81 : MXT-224E */ if (*buf != 'F' && data->tsp_version >= firmware_latest[1] && data->tsp_build >= build_latest[1]) { printk(KERN_ERR"[TSP] mxt224E has latest firmware\n"); firm_status_data =2; enable_irq(data->client->irq); return size; } printk("[TSP] mxt224E_fm_update\n"); error = mxt_load_fw(dev, MXT224_ECHO_FW_NAME); } #endif if (error) { dev_err(dev, "The firmware update failed(%d)\n", error); firm_status_data =3; printk(KERN_ERR"[TSP]The firmware update failed(%d)\n", error); return error; } else { dev_dbg(dev, "The firmware update succeeded\n"); firm_status_data =2; printk("[TSP] The firmware update succeeded\n"); /* Wait for reset */ msleep(MXT_RESET_TIME); mxt_init_touch_driver(data); /* mxt224_initialize(data); */ } enable_irq(data->client->irq); error = mxt_backup(data); if (error) { printk(KERN_ERR"[TSP]mxt_backup fail!!!\n"); return error; } /* reset the touch IC. */ error = mxt_reset(data); if (error) { printk(KERN_ERR"[TSP]mxt_reset fail!!!\n"); return error; } msleep(MXT_RESET_TIME); return size; } static ssize_t set_mxt_firm_status_show(struct device *dev, struct device_attribute *attr, char *buf) { int count; printk("Enter firmware_status_show by Factory command \n"); if (firm_status_data == 1) { count = sprintf(buf, "DOWNLOADING\n"); } else if (firm_status_data == 2) { count = sprintf(buf, "PASS\n"); } else if (firm_status_data == 3) { count = sprintf(buf, "FAIL\n"); } else count = sprintf(buf, "PASS\n"); return count; } static ssize_t key_threshold_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", threshold); } static ssize_t key_threshold_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { /*TO DO IT*/ unsigned int object_register=7; u8 value; u8 val; int ret; u16 address = 0; u16 size_one; int num; if (sscanf(buf, "%d", &num) == 1) { threshold = num; printk("threshold value %d\n",threshold); ret = get_object_info(copy_data, TOUCH_MULTITOUCHSCREEN_T9, &size_one, &address); size_one = 1; value = (u8)threshold; write_mem(copy_data, address+(u16)object_register, size_one, &value); read_mem(copy_data, address+(u16)object_register, (u8)size_one, &val); printk(KERN_ERR"T9 Byte%d is %d\n", object_register, val); } return size; } static ssize_t set_mxt_firm_version_show(struct device *dev, struct device_attribute *attr, char *buf) { u8 fw_latest_version = 0; struct mxt_data *data = dev_get_drvdata(dev); if (data->family_id == 0xA1) fw_latest_version = firmware_latest[1]; else if (data->family_id == 0x80) fw_latest_version = firmware_latest[0]; else if (data->family_id == 0x81) fw_latest_version = firmware_latest[1]; pr_info("Atmel Last firmware version is %d\n", fw_latest_version); return sprintf(buf, "%#02x\n", fw_latest_version); } static ssize_t set_mxt_firm_version_read_show(struct device *dev, struct device_attribute *attr, char *buf) { struct mxt_data *data = dev_get_drvdata(dev); printk("[TSP] tsp_build = 0x%x\n", data->tsp_build); return sprintf(buf, "%#02x\n", data->tsp_version); } static ssize_t mxt_touchtype_show(struct device *dev, struct device_attribute *attr, char *buf) { char temp[15]; sprintf(temp, "ATMEL,MXT768E\n"); strcat(buf, temp); return strlen(buf); } static ssize_t x_line_show(struct device *dev, struct device_attribute *attr, char *buf) { u8 data = 24; return sprintf(buf, "%d\n", data); } static ssize_t y_line_show(struct device *dev, struct device_attribute *attr, char *buf) { u8 data = 32; return sprintf(buf, "%d\n", data); } #ifdef ITDEV //itdev /* Functions for mem_access interface */ struct bin_attribute mem_access_attr; static int mxt_read_block(struct i2c_client *client, u16 addr, u16 length, u8 *value) { struct i2c_adapter *adapter = client->adapter; struct i2c_msg msg[2]; __le16 le_addr; struct mxt_data *mxt; mxt = i2c_get_clientdata(client); if (mxt != NULL) { if ((mxt->last_read_addr == addr) && (addr == mxt->msg_proc_addr)) { if (i2c_master_recv(client, value, length) == length) { #ifdef ITDEV if (debug_enabled)//itdev print_hex_dump(KERN_DEBUG, "MXT RX:", DUMP_PREFIX_NONE, 16, 1, value, length, false);//itdev #endif return 0; } else return -EIO; } else { mxt->last_read_addr = addr; } } le_addr = cpu_to_le16(addr); msg[0].addr = client->addr; msg[0].flags = 0x00; msg[0].len = 2; msg[0].buf = (u8 *) &le_addr; msg[1].addr = client->addr; msg[1].flags = I2C_M_RD; msg[1].len = length; msg[1].buf = (u8 *) value; if (i2c_transfer(adapter, msg, 2) == 2) { #ifdef ITDEV if (debug_enabled) {//itdev print_hex_dump(KERN_DEBUG, "MXT TX:", DUMP_PREFIX_NONE, 16, 1, msg[0].buf, msg[0].len, false);//itdev print_hex_dump(KERN_DEBUG, "MXT RX:", DUMP_PREFIX_NONE, 16, 1, msg[1].buf, msg[1].len, false);//itdev } #endif return 0; } else return -EIO; } /* Writes a block of bytes (max 256) to given address in mXT chip. */ int mxt_write_block(struct i2c_client *client, u16 addr, u16 length, u8 *value) { int i; struct { __le16 le_addr; u8 data[256]; } i2c_block_transfer; struct mxt_data *mxt; if (length > 256) return -EINVAL; mxt = i2c_get_clientdata(client); if (mxt != NULL) mxt->last_read_addr = -1; for (i = 0; i < length; i++) i2c_block_transfer.data[i] = *value++; i2c_block_transfer.le_addr = cpu_to_le16(addr); i = i2c_master_send(client, (u8 *) &i2c_block_transfer, length + 2); if (i == (length + 2)) { #ifdef ITDEV if (debug_enabled)//itdev print_hex_dump(KERN_DEBUG, "MXT TX:", DUMP_PREFIX_NONE, 16, 1, &i2c_block_transfer, length+2, false);//itdev #endif return length; } else return -EIO; } static ssize_t mem_access_read(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { int ret = 0; struct i2c_client *client; pr_info("mem_access_read p=%p off=%lli c=%zi\n", buf, off, count); if (off >= 32768) return -EIO; if (off + count > 32768) count = 32768 - off; if (count > 256) count = 256; if (count > 0) { client = to_i2c_client(container_of(kobj, struct device, kobj)); ret = mxt_read_block(client, off, count, buf); } return ret >= 0 ? count : ret; } static ssize_t mem_access_write(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buf, loff_t off, size_t count) { int ret = 0; struct i2c_client *client; pr_info("mem_access_write p=%p off=%lli c=%zi\n", buf, off, count); if (off >= 32768) return -EIO; if (off + count > 32768) count = 32768 - off; if (count > 256) count = 256; if (count > 0) { client = to_i2c_client(container_of(kobj, struct device, kobj)); ret = mxt_write_block(client, off, count, buf); } return ret >= 0 ? count : 0; } static ssize_t pause_show(struct device *dev, struct device_attribute *attr, char *buf) { int count = 0; count += sprintf(buf + count, "%d", driver_paused); count += sprintf(buf + count, "\n"); return count; } static ssize_t pause_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int i; if (sscanf(buf, "%u", &i) == 1 && i < 2) { driver_paused = i; printk("%s\n", i ? "paused" : "unpaused"); } else { printk("pause_driver write error\n"); } return count; } static ssize_t debug_enable_show(struct device *dev, struct device_attribute *attr, char *buf) { int count = 0; count += sprintf(buf + count, "%d", debug_enabled); count += sprintf(buf + count, "\n"); return count; } static ssize_t debug_enable_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int i; if (sscanf(buf, "%u", &i) == 1 && i < 2) { debug_enabled = i; printk("%s\n", i ? "debug enabled" : "debug disabled"); } else { printk("debug_enabled write error\n"); } return count; } static ssize_t command_calibrate_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client; struct mxt_data *mxt; int ret; #if 0 client = to_i2c_client(dev); mxt = i2c_get_clientdata(client); ret = mxt_write_byte(client, MXT_BASE_ADDR(MXT_GEN_COMMANDPROCESSOR_T6) + MXT_ADR_T6_CALIBRATE, 0x1); #else ret = calibrate_chip_e(); #endif return (ret < 0) ? ret : count; } static ssize_t command_reset_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client; struct mxt_data *mxt; int ret; client = to_i2c_client(dev); mxt = i2c_get_clientdata(client); #if 0 ret = reset_chip(mxt, RESET_TO_NORMAL); #else ret = mxt_reset(mxt); #endif return (ret < 0) ? ret : count; } static ssize_t command_backup_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct i2c_client *client; struct mxt_data *mxt; int ret; client = to_i2c_client(dev); mxt = i2c_get_clientdata(client); #if 0 ret = backup_to_nv(mxt); #else ret = mxt_backup(mxt); #endif return (ret < 0) ? ret : count; } #endif //itdev static DEVICE_ATTR(set_refer0, S_IRUGO, set_refer0_mode_show, NULL); static DEVICE_ATTR(set_delta0, S_IRUGO, set_delta0_mode_show, NULL); static DEVICE_ATTR(set_refer1, S_IRUGO, set_refer1_mode_show, NULL); static DEVICE_ATTR(set_delta1, S_IRUGO, set_delta1_mode_show, NULL); static DEVICE_ATTR(set_refer2, S_IRUGO, set_refer2_mode_show, NULL); static DEVICE_ATTR(set_delta2, S_IRUGO, set_delta2_mode_show, NULL); static DEVICE_ATTR(set_refer3, S_IRUGO, set_refer3_mode_show, NULL); static DEVICE_ATTR(set_delta3, S_IRUGO, set_delta3_mode_show, NULL); static DEVICE_ATTR(set_refer4, S_IRUGO, set_refer4_mode_show, NULL); static DEVICE_ATTR(set_delta4, S_IRUGO, set_delta4_mode_show, NULL); static DEVICE_ATTR(set_all_refer, S_IRUGO, set_all_refer_mode_show, NULL); static DEVICE_ATTR(disp_all_refdata, S_IRUGO | S_IWUSR | S_IWGRP, disp_all_refdata_show, disp_all_refdata_store); static DEVICE_ATTR(set_all_delta, S_IRUGO, set_all_delta_mode_show, NULL); static DEVICE_ATTR(disp_all_deltadata, S_IRUGO | S_IWUSR | S_IWGRP, disp_all_deltadata_show, disp_all_deltadata_store); static DEVICE_ATTR(set_firm_version, S_IRUGO | S_IWUSR | S_IWGRP, set_firm_version_show, NULL); static DEVICE_ATTR(set_module_off, S_IRUGO | S_IWUSR | S_IWGRP, set_module_off_show, NULL); static DEVICE_ATTR(set_module_on, S_IRUGO | S_IWUSR | S_IWGRP, set_module_on_show, NULL); static DEVICE_ATTR(mxt_touchtype, S_IRUGO | S_IWUSR | S_IWGRP, mxt_touchtype_show, NULL); static DEVICE_ATTR(set_threshold, S_IRUGO, set_threshold_mode_show, NULL); static DEVICE_ATTR(tsp_firm_update, S_IWUSR | S_IWGRP, NULL, set_mxt_firm_update_store); /* firmware update */ static DEVICE_ATTR(tsp_firm_update_status, S_IRUGO, set_mxt_firm_status_show, NULL); /* firmware update status return */ static DEVICE_ATTR(tsp_threshold, S_IRUGO | S_IWUSR | S_IWGRP, key_threshold_show, key_threshold_store); /* touch threshold return, store */ static DEVICE_ATTR(tsp_firm_version_phone, S_IRUGO, set_mxt_firm_version_show, NULL);/* PHONE*/ /* firmware version resturn in phone driver version */ static DEVICE_ATTR(tsp_firm_version_panel, S_IRUGO, set_mxt_firm_version_read_show, NULL);/*PART*/ /* firmware version resturn in TSP panel version */ static DEVICE_ATTR(object_show, S_IWUSR | S_IWGRP, NULL, mxt_object_show); static DEVICE_ATTR(object_write, S_IWUSR | S_IWGRP, NULL, mxt_object_setting); static DEVICE_ATTR(dbg_switch, S_IWUSR | S_IWGRP, NULL, mxt_debug_setting); static DEVICE_ATTR(find_delta_channel, S_IRUGO, find_channel_show, NULL); static DEVICE_ATTR(x_line, S_IRUGO, x_line_show, NULL); static DEVICE_ATTR(y_line, S_IRUGO, y_line_show, NULL); #ifdef ITDEV /* Sysfs files for libmaxtouch interface */ static DEVICE_ATTR(pause_driver, 0666, pause_show, pause_store);//itdev static DEVICE_ATTR(debug_enable, 0666, debug_enable_show, debug_enable_store);//itdev static DEVICE_ATTR(command_calibrate, 0666, NULL, command_calibrate_store);//itdev static DEVICE_ATTR(command_reset, 0666, NULL, command_reset_store);//itdev static DEVICE_ATTR(command_backup, 0666, NULL, command_backup_store);//itdev static struct attribute *libmaxtouch_attributes[] = { &dev_attr_pause_driver.attr,//itdev &dev_attr_debug_enable.attr,//itdev &dev_attr_command_calibrate.attr,//itdev &dev_attr_command_reset.attr,//itdev &dev_attr_command_backup.attr,//itdev NULL, }; static struct attribute_group libmaxtouch_attr_group = { .attrs = libmaxtouch_attributes, }; #endif static struct attribute *mxt_attrs[] = { &dev_attr_object_show.attr, &dev_attr_object_write.attr, &dev_attr_dbg_switch.attr, NULL }; static const struct attribute_group mxt_attr_group = { .attrs = mxt_attrs, }; static int __devinit mxt_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct mxt_platform_data *pdata = client->dev.platform_data; struct mxt_data *data; struct input_dev *input_dev; int ret; int i; bool ta_status = 0; u8 **tsp_config; tsp_reinit:; touch_is_pressed = 0; #if TOUCH_BOOSTER tsp_press_status = 0; #endif if (!pdata) { dev_err(&client->dev, "missing platform data\n"); return -ENODEV; } if (pdata->max_finger_touches <= 0) return -EINVAL; data = kzalloc(sizeof(*data) + pdata->max_finger_touches * sizeof(*data->fingers), GFP_KERNEL); if (!data) return -ENOMEM; data->num_fingers = pdata->max_finger_touches; data->power_on = pdata->power_on; data->power_off = pdata->power_off; data->register_cb = pdata->register_cb; data->read_ta_status = pdata->read_ta_status; data->client = client; i2c_set_clientdata(client, data); input_dev = input_allocate_device(); if (!input_dev) { ret = -ENOMEM; dev_err(&client->dev, "input device allocation failed\n"); goto err_alloc_dev; } data->input_dev = input_dev; input_set_drvdata(input_dev, data); input_dev->name = "sec_touchscreen"; set_bit(EV_ABS, input_dev->evbit); input_set_abs_params(input_dev, ABS_MT_POSITION_X, pdata->min_x, pdata->max_x, 0, 0); input_set_abs_params(input_dev, ABS_MT_POSITION_Y, pdata->min_y, pdata->max_y, 0, 0); input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR, pdata->min_z, pdata->max_z, 0, 0); input_set_abs_params(input_dev, ABS_MT_WIDTH_MAJOR, pdata->min_w, pdata->max_w, 0, 0); input_set_abs_params(input_dev, ABS_MT_TRACKING_ID, 0, data->num_fingers - 1, 0, 0); #ifdef _SUPPORT_SHAPE_TOUCH_ input_set_abs_params(input_dev, ABS_MT_COMPONENT, 0, 255, 0, 0); #endif ret = input_register_device(input_dev); if (ret) { input_free_device(input_dev); goto err_reg_dev; } data->gpio_read_done = pdata->gpio_read_done; data->power_on(); copy_data = data; if (client->addr == MXT768E_APP_LOW) client->addr = MXT768E_BOOT_LOW; else client->addr = MXT768E_BOOT_HIGH; ret = mxt_check_bootloader(client, MXT_WAITING_BOOTLOAD_CMD); if (ret >= 0) { printk("[TSP] boot mode. firm update excute\n"); mxt_load_fw_bootmode(NULL, MXT768E_FW_NAME); msleep(MXT_RESET_TIME); } else { if (client->addr == MXT768E_BOOT_LOW) client->addr = MXT768E_APP_LOW; else client->addr = MXT768E_APP_HIGH; } ret = mxt_init_touch_driver(data); data->register_cb(mxt_ta_probe); if (ret) { dev_err(&client->dev, "chip initialization failed\n"); goto err_init_drv; } if (data->family_id == 0xA1) { /* tsp_family_id - 0xA1 : MXT-768E */ tsp_config = (u8 **)pdata->config_e; data->t48_config_batt_e = pdata->t48_config_batt_e; data->t48_config_chrg_e = pdata->t48_config_chrg_e; data->tchthr_batt = pdata->tchthr_batt_e; data->tchthr_charging = pdata->tchthr_charging_e; data->calcfg_batt_e = pdata->calcfg_batt_e; data->calcfg_charging_e = pdata->calcfg_charging_e; data->atchcalsthr_e = pdata->atchcalsthr_e; data->atchfrccalthr_e = pdata->atchfrccalthr_e; data->atchfrccalratio_e = pdata->atchfrccalratio_e; data->chrgtime_batt = pdata->chrgtime_batt; data->chrgtime_charging = pdata->chrgtime_charging; data->idlesyncsperx_batt = pdata->idlesyncsperx_batt; data->idlesyncsperx_charging = pdata->idlesyncsperx_charging; data->actvsyncsperx_batt = pdata->actvsyncsperx_batt; data->actvsyncsperx_charging = pdata->actvsyncsperx_charging; data->idleacqint_batt = pdata->idleacqint_batt; data->idleacqint_charging = pdata->idleacqint_charging; data->actacqint_batt = pdata->actacqint_batt; data->actacqint_charging = pdata->actacqint_charging; data->xloclip_batt = pdata->xloclip_batt; data->xloclip_charging = pdata->xloclip_charging; data->xhiclip_batt = pdata->xhiclip_batt; data->xhiclip_charging = pdata->xhiclip_charging; data->yloclip_batt = pdata->yloclip_batt; data->yloclip_charging = pdata->yloclip_charging; data->yhiclip_batt = pdata->yhiclip_batt; data->yhiclip_charging = pdata->yhiclip_charging; data->xedgectrl_batt = pdata->xedgectrl_batt; data->xedgectrl_charging = pdata->xedgectrl_charging; data->xedgedist_batt = pdata->xedgedist_batt; data->xedgedist_charging = pdata->xedgedist_charging; data->yedgectrl_batt = pdata->yedgectrl_batt; data->yedgectrl_charging = pdata->yedgectrl_charging; data->yedgedist_batt = pdata->yedgedist_batt; data->yedgedist_charging = pdata->yedgedist_charging; data->tchhyst_batt = pdata->tchhyst_batt; data->tchhyst_charging = pdata->tchhyst_charging; printk("[TSP] TSP chip is MXT768-E\n"); #if !defined(FOR_DEBUGGING_TEST_DOWNLOADFW_BIN)// add_for_bin_download if ((data->tsp_version < firmware_latest[1] || (data->tsp_version == firmware_latest[1] && data->tsp_build != build_latest[1])) && (data->tsp_variant != 0)) { printk(KERN_INFO "[TSP] mxt768E force firmware update\n"); if (mxt_load_fw(NULL, MXT768E_FW_NAME)) goto err_config; else { msleep(MXT_RESET_TIME); mxt_init_touch_driver(data); } } #endif INIT_DELAYED_WORK(&data->config_dwork, mxt_reconfigration_normal); INIT_DELAYED_WORK(&data->overflow_dwork, mxt_calbration_by_overflowed); INIT_DELAYED_WORK(&data->check_median_error_dwork, mxt_check_medianfilter_error); INIT_DELAYED_WORK(&data->check_abnormal_palm_dwork, mxt_check_abnormal_palm); #if TOUCH_BOOSTER INIT_DELAYED_WORK(&data->dvfs_dwork, mxt_set_dvfs_off); #endif } else if (data->family_id == 0x80) { /* : MXT-224 */ tsp_config = (u8 **)pdata->config; data->atchcalst = pdata->atchcalst; data->atchcalsthr = pdata->atchcalsthr; data->tchthr_batt = pdata->tchthr_batt; data->tchthr_charging = pdata->tchthr_charging; printk("[TSP] TSP chip is MXT224\n"); } else if (data->family_id == 0x81) { /* tsp_family_id - 0x81 : MXT-224E */ tsp_config = (u8 **)pdata->config_e; data->t48_config_batt_e = pdata->t48_config_batt_e; data->t48_config_chrg_e = pdata->t48_config_chrg_e; data->tchthr_batt = pdata->tchthr_batt_e; data->tchthr_charging = pdata->tchthr_charging_e; data->calcfg_batt_e = pdata->calcfg_batt_e; data->calcfg_charging_e = pdata->calcfg_charging_e; data->atchfrccalthr_e = pdata->atchfrccalthr_e; data->atchfrccalratio_e = pdata->atchfrccalratio_e; printk("[TSP] TSP chip is MXT224-E\n"); if (!(data->tsp_version >= firmware_latest[1] && data->tsp_build >= build_latest[1])) { printk("[TSP] mxt224E force firmware update\n"); if (mxt_load_fw(NULL, MXT224_ECHO_FW_NAME)) goto err_config; else { msleep(MXT_FWRESET_TIME); mxt_init_touch_driver(data); } } INIT_DELAYED_WORK(&data->config_dwork, mxt_reconfigration_normal); } else { printk(KERN_ERR"ERROR : There is no valid TSP ID\n"); goto err_config; } for (i = 0; tsp_config[i][0] != RESERVED_T255; i++) { ret = init_write_config(data, tsp_config[i][0], tsp_config[i] + 1); if (ret) goto err_config; if (tsp_config[i][0] == GEN_POWERCONFIG_T7) data->power_cfg = tsp_config[i] + 1; if (tsp_config[i][0] == TOUCH_MULTITOUCHSCREEN_T9) { /* Are x and y inverted? */ if (tsp_config[i][10] & 0x1) { data->x_dropbits = (!(tsp_config[i][22] & 0xC)) << 1; data->y_dropbits = (!(tsp_config[i][20] & 0xC)) << 1; } else { data->x_dropbits = (!(tsp_config[i][20] & 0xC)) << 1; data->y_dropbits = (!(tsp_config[i][22] & 0xC)) << 1; } } } ret = mxt_backup(data); if (ret) goto err_backup; /* reset the touch IC. */ ret = mxt_reset(data); if (ret) goto err_reset; msleep(MXT_RESET_TIME); if (data->family_id == 0xA1) { /* : MXT-768E */ calibrate_chip_e(); } else if (data->family_id == 0x81) { /* : MXT-224E */ calibrate_chip_e(); } else calibrate_chip(); for (i = 0; i < data->num_fingers; i++) { data->fingers[i].state = MXT_STATE_INACTIVE; } ret = request_threaded_irq(client->irq, NULL, mxt_irq_thread, IRQF_TRIGGER_LOW | IRQF_ONESHOT, "mxt_ts", data); if (ret < 0) goto err_irq; ret = sysfs_create_group(&client->dev.kobj, &mxt_attr_group); if (ret) printk(KERN_ERR"[TSP] sysfs_create_group()is falled\n"); #ifdef ITDEV //itdev ret = sysfs_create_group(&client->dev.kobj, &libmaxtouch_attr_group); if (ret) { pr_err("Failed to create libmaxtouch sysfs group\n"); goto err_irq; } sysfs_bin_attr_init(&mem_access_attr); mem_access_attr.attr.name = "mem_access"; mem_access_attr.attr.mode = S_IRUGO | S_IWUGO; mem_access_attr.read = mem_access_read; mem_access_attr.write = mem_access_write; mem_access_attr.size = 65535; if (sysfs_create_bin_file(&client->dev.kobj, &mem_access_attr) < 0) { pr_err("Failed to create device file(%s)!\n", mem_access_attr.attr.name); goto err_irq; } #endif sec_touchscreen = device_create(sec_class, NULL, 0, NULL, "sec_touchscreen"); dev_set_drvdata(sec_touchscreen, data); if (IS_ERR(sec_touchscreen)) printk(KERN_ERR "[TSP] Failed to create device(sec_touchscreen)!\n"); if (device_create_file(sec_touchscreen, &dev_attr_tsp_firm_update) < 0) printk(KERN_ERR "[TSP] Failed to create device file(%s)!\n", dev_attr_tsp_firm_update.attr.name); if (device_create_file(sec_touchscreen, &dev_attr_tsp_firm_update_status) < 0) printk(KERN_ERR "[TSP] Failed to create device file(%s)!\n", dev_attr_tsp_firm_update_status.attr.name); if (device_create_file(sec_touchscreen, &dev_attr_tsp_threshold) < 0) printk(KERN_ERR "[TSP] Failed to create device file(%s)!\n", dev_attr_tsp_threshold.attr.name); if (device_create_file(sec_touchscreen, &dev_attr_tsp_firm_version_phone) < 0) printk(KERN_ERR "[TSP] Failed to create device file(%s)!\n", dev_attr_tsp_firm_version_phone.attr.name); if (device_create_file(sec_touchscreen, &dev_attr_tsp_firm_version_panel) < 0) printk(KERN_ERR "[TSP] Failed to create device file(%s)!\n", dev_attr_tsp_firm_version_panel.attr.name); if (device_create_file(sec_touchscreen, &dev_attr_mxt_touchtype) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_mxt_touchtype.attr.name); mxt_noise_test = device_create(sec_class, NULL, 0, NULL, "tsp_noise_test"); if (IS_ERR(mxt_noise_test)) printk(KERN_ERR "Failed to create device(mxt_noise_test)!\n"); if (device_create_file(mxt_noise_test, &dev_attr_set_refer0) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_refer0.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_delta0) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_delta0.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_refer1) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_refer1.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_delta1) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_delta1.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_refer2) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_refer2.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_delta2) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_delta2.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_refer3) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_refer3.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_delta3) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_delta3.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_refer4) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_refer4.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_delta4) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_delta4.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_all_refer) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_all_refer.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_disp_all_refdata)< 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_disp_all_refdata.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_all_delta) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_all_delta.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_disp_all_deltadata)< 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_disp_all_deltadata.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_threshold) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_threshold.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_firm_version) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_firm_version.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_module_off) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_module_off.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_set_module_on) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_set_module_on.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_x_line) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_x_line.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_y_line) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_y_line.attr.name); if (device_create_file(mxt_noise_test, &dev_attr_find_delta_channel) < 0) printk(KERN_ERR "Failed to create device file(%s)!\n", dev_attr_find_delta_channel.attr.name); #ifdef CONFIG_HAS_EARLYSUSPEND data->early_suspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN + 1; data->early_suspend.suspend = mxt_early_suspend; data->early_suspend.resume = mxt_late_resume; register_early_suspend(&data->early_suspend); #endif if (data->family_id == 0xA1) { /* : MXT-768E */ schedule_delayed_work(&data->config_dwork , HZ*TIME_FOR_RECONFIG_ON_BOOT); } else if (data->family_id == 0x81) { /* : MXT-224E */ schedule_delayed_work(&data->config_dwork, HZ*5); } mxt_enabled = 1; if (data->read_ta_status) { data->read_ta_status(&ta_status); printk("[TSP] ta_status is %d\n", ta_status); mxt_ta_probe(ta_status); } return 0; err_irq: err_reset: err_backup: err_config: kfree(data->objects); err_init_drv: gpio_free(data->gpio_read_done); /* err_gpio_req: data->power_off(); input_unregister_device(input_dev); */ err_reg_dev: err_alloc_dev: data->power_off(); kfree(data); if( tsp_reboot_count < 3 ) { if(input_dev) input_unregister_device(input_dev); tsp_reboot_count++; mdelay(20); printk(KERN_ERR "[TSP] retry probe %d\n",tsp_reboot_count); goto tsp_reinit; } return ret; } static int __devexit mxt_remove(struct i2c_client *client) { struct mxt_data *data = i2c_get_clientdata(client); #ifdef CONFIG_HAS_EARLYSUSPEND unregister_early_suspend(&data->early_suspend); #endif free_irq(client->irq, data); kfree(data->objects); gpio_free(data->gpio_read_done); data->power_off(); input_unregister_device(data->input_dev); kfree(data); return 0; } static struct i2c_device_id mxt_idtable[] = { {MXT_DEV_NAME, 0}, {}, }; MODULE_DEVICE_TABLE(i2c, mxt_idtable); static const struct dev_pm_ops mxt_pm_ops = { .suspend = mxt_suspend, .resume = mxt_resume, }; static struct i2c_driver mxt_i2c_driver = { .id_table = mxt_idtable, .probe = mxt_probe, .remove = __devexit_p(mxt_remove), .driver = { .owner = THIS_MODULE, .name = MXT_DEV_NAME, .pm = &mxt_pm_ops, }, }; static int __init mxt_init(void) { return i2c_add_driver(&mxt_i2c_driver); } static void __exit mxt_exit(void) { i2c_del_driver(&mxt_i2c_driver); } module_init(mxt_init); module_exit(mxt_exit); MODULE_DESCRIPTION("Atmel MaXTouch 224E driver"); MODULE_AUTHOR("Heetae Ahn <heetae82.ahn@samsung.com>"); MODULE_LICENSE("GPL");
glitschi/kernel_P7320
drivers/input/touchscreen/mxt768e.c
C
gpl-2.0
115,352
<?php /* ----------------------------------------------------------------------------------------- $Id: xtc_get_uprid.inc.php 899 2005-04-29 02:40:57Z hhgag $ XT-Commerce - community made shopping http://www.xt-commerce.com Copyright (c) 2003 XT-Commerce ----------------------------------------------------------------------------------------- based on: (c) 2000-2001 The Exchange Project (earlier name of osCommerce) (c) 2002-2003 osCommerce(general.php,v 1.225 2003/05/29); www.oscommerce.com (c) 2003 nextcommerce (xtc_get_uprid.inc.php,v 1.3 2003/08/13); www.nextcommerce.org Released under the GNU General Public License ---------------------------------------------------------------------------------------*/ // Return a product ID with attributes function xtc_get_uprid($prid, $params) { global $scModules; if (is_numeric($prid)) { $uprid = $prid; if (is_array($params) && (sizeof($params) > 0)) { $attributes_check = true; $attributes_ids = ''; reset($params); while (list($option, $value) = each($params)) { //new module support list($option, $value) = (class_exists('shoppingCartModules') ? $scModules->get_uprid(array($option, $value)) : array($option, $value)); if (is_numeric($option) && is_numeric($value)) { $attributes_ids .= '{' . (int)$option . '}' . (int)$value; } else { $attributes_check = false; break; } } if ($attributes_check == true) { $uprid .= $attributes_ids; } } } else { $uprid = xtc_get_prid($prid); if (is_numeric($uprid)) { if (strpos($prid, '{') !== false) { $attributes_check = true; $attributes_ids = ''; $attributes = explode('{', substr($prid, strpos($prid, '{')+1)); for ($i=0, $n=sizeof($attributes); $i<$n; $i++) { $pair = explode('}', $attributes[$i]); if (is_numeric($pair[0]) && is_numeric($pair[1])) { $attributes_ids .= '{' . (int)$pair[0] . '}' . (int)$pair[1]; } else { $attributes_check = false; break; } } if ($attributes_check == true) { $uprid .= $attributes_ids; } } } else { return false; } } return $uprid; } ?>
dsiekiera/modified-bs4
inc/xtc_get_uprid.inc.php
PHP
gpl-2.0
2,442
/* * ZAL - The abstraction layer for Zimbra. * Copyright (C) 2016 ZeXtras S.r.l. * * This file is part of ZAL. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, version 2 of * the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZAL. If not, see <http://www.gnu.org/licenses/>. */ package org.openzal.zal; import com.zimbra.cs.account.accesscontrol.generated.RightConsts; public class RightConstants { public static String RT_sendAs = RightConsts.RT_sendAs; public static String RT_domainAdminCosRights = RightConsts.RT_domainAdminCosRights; public static String RT_loginAs = RightConsts.RT_loginAs; public static String RT_domainAdminRights = RightConsts.RT_domainAdminRights; public static String RT_adminLoginAs = RightConsts.RT_adminLoginAs; public static String RT_domainAdminConsoleAccountsFeaturesTabRights = RightConsts.RT_domainAdminConsoleAccountsFeaturesTabRights; public static String RT_listZimlet = RightConsts.RT_listZimlet; public static String RT_getZimlet = RightConsts.RT_getZimlet; public static String RT_domainAdminZimletRights = RightConsts.RT_domainAdminZimletRights; public static String RT_setAdminSavedSearch = RightConsts.RT_setAdminSavedSearch; public static String RT_viewAdminSavedSearch = RightConsts.RT_viewAdminSavedSearch; public static String RT_domainAdminConsoleDLSharesTabRights = RightConsts.RT_domainAdminConsoleDLSharesTabRights; public static String RT_getAccountInfo = RightConsts.RT_getAccountInfo; public static String RT_configureQuota = RightConsts.RT_configureQuota; public static String RT_sendOnBehalfOf = RightConsts.RT_sendOnBehalfOf; public static String RT_sendOnBehalfOfDistList = RightConsts.RT_sendOnBehalfOfDistList; public static String RT_sendAsDistList = RightConsts.RT_sendAsDistList; public static String RT_addGroupAlias = RightConsts.RT_addGroupAlias; public static String RT_addGroupMember = RightConsts.RT_addGroupMember; public static String RT_createGroup = RightConsts.RT_createGroup; public static String RT_deleteGroup = RightConsts.RT_deleteGroup; public static String RT_getGroup = RightConsts.RT_getGroup; public static String RT_listGroup = RightConsts.RT_listGroup; public static String RT_modifyGroup = RightConsts.RT_modifyGroup; public static String RT_removeGroupAlias = RightConsts.RT_removeGroupAlias; public static String RT_removeGroupMember = RightConsts.RT_removeGroupMember; public static String RT_renameGroup = RightConsts.RT_renameGroup; }
ZeXtras/OpenZAL
src/java/org/openzal/zal/RightConstants.java
Java
gpl-2.0
2,924
/* vi: set sw=4 ts=4: */ /* * Busybox main internal header file * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Based in part on code from sash, Copyright (c) 1999 by David I. Bell * Permission has been granted to redistribute this code under the GPL. * */ #ifndef __LIBCONFIG_H__ #define __LIBCONFIG_H__ 1 #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <termios.h> #include <stdint.h> #include <netdb.h> #include <features.h> #include "bb_config.h" #ifdef CONFIG_SELINUX #include <selinux/selinux.h> #endif #include "pwd_.h" #include "grp_.h" #ifdef CONFIG_FEATURE_SHADOWPASSWDS #include "shadow_.h" #endif #ifdef CONFIG_FEATURE_SHA1_PASSWORDS # include "sha1.h" #endif /* Convenience macros to test the version of gcc. */ #if defined __GNUC__ && defined __GNUC_MINOR__ # define __GNUC_PREREQ(maj, min) \ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) #else # define __GNUC_PREREQ(maj, min) 0 #endif /* __restrict is known in EGCS 1.2 and above. */ #if !__GNUC_PREREQ (2,92) # define __restrict /* Ignore */ #endif #define attribute_noreturn __attribute__ ((__noreturn__)) /* Some useful definitions */ #define FALSE ((int) 0) #define TRUE ((int) 1) #define SKIP ((int) 2) /* for mtab.c */ #define MTAB_GETMOUNTPT '1' #define MTAB_GETDEVICE '2' #define BUF_SIZE 8192 #define EXPAND_ALLOC 1024 /* Macros for min/max. */ #ifndef MIN #define MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef MAX #define MAX(a,b) (((a)>(b))?(a):(b)) #endif extern void bb_show_usage(void) __attribute__ ((noreturn)); extern void bb_error_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))); extern void bb_error_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))); extern void bb_perror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))); extern void bb_perror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))); extern void bb_vherror_msg(const char *s, va_list p); extern void bb_herror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))); extern void bb_herror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))); extern void bb_perror_nomsg_and_die(void) __attribute__ ((noreturn)); extern void bb_perror_nomsg(void); /* These two are used internally -- you shouldn't need to use them */ extern void bb_verror_msg(const char *s, va_list p) __attribute__ ((format (printf, 1, 0))); extern void bb_vperror_msg(const char *s, va_list p) __attribute__ ((format (printf, 1, 0))); extern int bb_echo(int argc, char** argv); extern const char *bb_mode_string(int mode); extern int is_directory(const char *name, int followLinks, struct stat *statBuf); extern int remove_file(const char *path, int flags); extern int copy_file(const char *source, const char *dest, int flags); extern ssize_t safe_read(int fd, void *buf, size_t count); extern ssize_t bb_full_read(int fd, void *buf, size_t len); extern ssize_t safe_write(int fd, const void *buf, size_t count); extern ssize_t bb_full_write(int fd, const void *buf, size_t len); extern int recursive_action(const char *fileName, int recurse, int followLinks, int depthFirst, int (*fileAction) (const char *fileName, struct stat* statbuf, void* userData), int (*dirAction) (const char *fileName, struct stat* statbuf, void* userData), void* userData); extern int bb_parse_mode( const char* s, mode_t* theMode); extern long bb_xgetlarg(const char *arg, int base, long lower, long upper); extern unsigned long bb_baud_to_value(speed_t speed); extern speed_t bb_value_to_baud(unsigned long value); extern int get_kernel_revision(void); extern int get_console_fd(void); extern struct mntent *find_mount_point(const char *name, const char *table); extern void erase_mtab(const char * name); extern long *find_pid_by_name( const char* pidName); extern long *pidlist_reverse(long *pidList); extern char *find_block_device(char *path); extern char *bb_get_line_from_file(FILE *file); extern char *bb_get_chomped_line_from_file(FILE *file); extern char *bb_get_chunk_from_file(FILE *file); extern int bb_copyfd_size(int fd1, int fd2, const off_t size); extern int bb_copyfd_eof(int fd1, int fd2); extern void bb_xprint_and_close_file(FILE *file); extern int bb_xprint_file_by_name(const char *filename); extern char bb_process_escape_sequence(const char **ptr); extern char *bb_get_last_path_component(char *path); extern FILE *bb_wfopen(const char *path, const char *mode); extern FILE *bb_wfopen_input(const char *filename); extern FILE *bb_xfopen(const char *path, const char *mode); extern int bb_fclose_nonstdin(FILE *f); extern void bb_fflush_stdout_and_exit(int retval) __attribute__ ((noreturn)); #define BB_GETOPT_ERROR 0x80000000UL extern const char *bb_opt_complementally; extern const struct option *bb_applet_long_options; extern unsigned long bb_getopt_ulflags(int argc, char **argv, const char *applet_opts, ...); extern int bb_vfprintf(FILE * __restrict stream, const char * __restrict format, va_list arg) __attribute__ ((format (printf, 2, 0))); extern int bb_vprintf(const char * __restrict format, va_list arg) __attribute__ ((format (printf, 1, 0))); extern int bb_fprintf(FILE * __restrict stream, const char * __restrict format, ...) __attribute__ ((format (printf, 2, 3))); extern int bb_printf(const char * __restrict format, ...) __attribute__ ((format (printf, 1, 2))); //#warning rename to xferror_filename? extern void bb_xferror(FILE *fp, const char *fn); extern void bb_xferror_stdout(void); extern void bb_xfflush_stdout(void); extern void bb_warn_ignoring_args(int n); extern void chomp(char *s); extern void trim(char *s); extern const char *bb_skip_whitespace(const char *); extern struct BB_applet *find_applet_by_name(const char *name); void run_applet_by_name(const char *name, int argc, char **argv); /* dmalloc will redefine these to it's own implementation. It is safe * to have the prototypes here unconditionally. */ extern void *xmalloc(size_t size); extern void *xrealloc(void *old, size_t size); extern void *xcalloc(size_t nmemb, size_t size); extern char *bb_xstrdup (const char *s); extern char *bb_xstrndup (const char *s, int n); extern char *safe_strncpy(char *dst, const char *src, size_t size); extern int safe_strtoi(char *arg, int* value); extern int safe_strtod(char *arg, double* value); extern int safe_strtol(char *arg, long* value); extern int safe_strtoul(char *arg, unsigned long* value); struct suffix_mult { const char *suffix; unsigned int mult; }; extern unsigned long bb_xgetularg_bnd_sfx(const char *arg, int base, unsigned long lower, unsigned long upper, const struct suffix_mult *suffixes); extern unsigned long bb_xgetularg_bnd(const char *arg, int base, unsigned long lower, unsigned long upper); extern unsigned long bb_xgetularg10_bnd(const char *arg, unsigned long lower, unsigned long upper); extern unsigned long bb_xgetularg10(const char *arg); extern long bb_xgetlarg_bnd_sfx(const char *arg, int base, long lower, long upper, const struct suffix_mult *suffixes); extern long bb_xgetlarg10_sfx(const char *arg, const struct suffix_mult *suffixes); //#warning pitchable now? extern unsigned long bb_xparse_number(const char *numstr, const struct suffix_mult *suffixes); /* These parse entries in /etc/passwd and /etc/group. This is desirable * for BusyBox since we want to avoid using the glibc NSS stuff, which * increases target size and is often not needed on embedded systems. */ extern long bb_xgetpwnam(const char *name); extern long bb_xgetgrnam(const char *name); extern char * bb_getug(char *buffer, char *idname, long id, int bufsize, char prefix); extern char * bb_getpwuid(char *name, long uid, int bufsize); extern char * bb_getgrgid(char *group, long gid, int bufsize); extern char *bb_askpass(int timeout, const char * prompt); extern int device_open(const char *device, int mode); extern char *query_loop(const char *device); extern int del_loop(const char *device); extern int set_loop(char **device, const char *file, int offset); #if (__GLIBC__ < 2) extern int vdprintf(int d, const char *format, va_list ap); #endif int nfsmount(const char *spec, const char *node, int *flags, char **mount_opts, int running_bg); /* Include our own copy of struct sysinfo to avoid binary compatability * problems with Linux 2.4, which changed things. Grumble, grumble. */ struct sysinfo { long uptime; /* Seconds since boot */ unsigned long loads[3]; /* 1, 5, and 15 minute load averages */ unsigned long totalram; /* Total usable main memory size */ unsigned long freeram; /* Available memory size */ unsigned long sharedram; /* Amount of shared memory */ unsigned long bufferram; /* Memory used by buffers */ unsigned long totalswap; /* Total swap space size */ unsigned long freeswap; /* swap space still available */ unsigned short procs; /* Number of current processes */ unsigned short pad; /* Padding needed for m68k */ unsigned long totalhigh; /* Total high memory size */ unsigned long freehigh; /* Available high memory size */ unsigned int mem_unit; /* Memory unit size in bytes */ char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding: libc5 uses this.. */ }; extern int sysinfo (struct sysinfo* info); enum { KILOBYTE = 1024, MEGABYTE = (KILOBYTE*1024), GIGABYTE = (MEGABYTE*1024) }; const char *make_human_readable_str(unsigned long long size, unsigned long block_size, unsigned long display_unit); int bb_ask_confirmation(void); int klogctl(int type, char * b, int len); char *xgetcwd(char *cwd); char *xreadlink(const char *path); char *concat_path_file(const char *path, const char *filename); char *concat_subpath_file(const char *path, const char *filename); char *last_char_is(const char *s, int c); int read_package_field(const char *package_buffer, char **field_name, char **field_value); //#warning yuk! char *fgets_str(FILE *file, const char *terminating_string); extern int uncompress(int fd_in, int fd_out); extern int inflate(int in, int out); extern struct hostent *xgethostbyname(const char *name); extern struct hostent *xgethostbyname2(const char *name, int af); extern int create_icmp_socket(void); extern int create_icmp6_socket(void); extern unsigned short bb_lookup_port(const char *port, const char *protocol, unsigned short default_port); struct bb_addrinfo { int ai_family; int ai_socktype; int ai_protocol; int ai_addrlen; struct sockaddr_storage ai_addr; }; unsigned int bb_getport(const struct bb_addrinfo *s_ai); const char *bb_ptoa(const struct bb_addrinfo *s_ai); extern int xconnect(const struct bb_addrinfo *s_ai); extern void bb_lookup_host(struct bb_addrinfo *s_ai, const char *host, unsigned int port); //#warning wrap this? char *dirname (char *path); int bb_make_directory (char *path, long mode, int flags); const char *u_signal_names(const char *str_sig, int *signo, int startnum); char *bb_simplify_path(const char *path); enum { /* DO NOT CHANGE THESE VALUES! cp.c depends on them. */ FILEUTILS_PRESERVE_STATUS = 1, FILEUTILS_DEREFERENCE = 2, FILEUTILS_RECUR = 4, FILEUTILS_FORCE = 8, FILEUTILS_INTERACTIVE = 16 }; extern const char *bb_applet_name; extern const char * const bb_msg_full_version; extern const char * const bb_msg_memory_exhausted; extern const char * const bb_msg_invalid_date; extern const char * const bb_msg_io_error; extern const char * const bb_msg_read_error; extern const char * const bb_msg_write_error; extern const char * const bb_msg_name_longer_than_foo; extern const char * const bb_msg_unknown; extern const char * const bb_msg_can_not_create_raw_socket; extern const char * const bb_msg_perm_denied_are_you_root; extern const char * const bb_msg_standard_input; extern const char * const bb_msg_standard_output; extern const char * const bb_path_nologin_file; extern const char * const bb_path_passwd_file; extern const char * const bb_path_shadow_file; extern const char * const bb_path_gshadow_file; extern const char * const bb_path_group_file; extern const char * const bb_path_securetty_file; extern const char * const bb_path_motd_file; extern const char * const bb_dev_null; #ifndef BUFSIZ #define BUFSIZ 4096 #endif extern char bb_common_bufsiz1[BUFSIZ+1]; /* * You can change LIBBB_DEFAULT_LOGIN_SHELL, but don`t use, * use bb_default_login_shell and next defines, * if you LIBBB_DEFAULT_LOGIN_SHELL change, * don`t lose change increment constant! */ #define LIBBB_DEFAULT_LOGIN_SHELL "-/bin/sh" extern const char * const bb_default_login_shell; /* "/bin/sh" */ #define DEFAULT_SHELL (bb_default_login_shell+1) /* "sh" */ #define DEFAULT_SHELL_SHORT_NAME (bb_default_login_shell+6) extern const char bb_path_mtab_file[]; extern int bb_default_error_retval; #ifdef CONFIG_FEATURE_DEVFS # define CURRENT_VC "/dev/vc/0" # define VC_1 "/dev/vc/1" # define VC_2 "/dev/vc/2" # define VC_3 "/dev/vc/3" # define VC_4 "/dev/vc/4" # define VC_5 "/dev/vc/5" #if defined(__sh__) || defined(__H8300H__) || defined(__H8300S__) /* Yes, this sucks, but both SH (including sh64) and H8 have a SCI(F) for their respective serial ports .. as such, we can't use the common device paths for these. -- PFM */ # define SC_0 "/dev/ttsc/0" # define SC_1 "/dev/ttsc/1" # define SC_FORMAT "/dev/ttsc/%d" #else # define SC_0 "/dev/tts/0" # define SC_1 "/dev/tts/1" # define SC_FORMAT "/dev/tts/%d" #endif # define VC_FORMAT "/dev/vc/%d" # define LOOP_FORMAT "/dev/loop/%d" # define FB_0 "/dev/fb/0" #else # define CURRENT_VC "/dev/tty0" # define VC_1 "/dev/tty1" # define VC_2 "/dev/tty2" # define VC_3 "/dev/tty3" # define VC_4 "/dev/tty4" # define VC_5 "/dev/tty5" #if defined(__sh__) || defined(__H8300H__) || defined(__H8300S__) # define SC_0 "/dev/ttySC0" # define SC_1 "/dev/ttySC1" # define SC_FORMAT "/dev/ttySC%d" #else # define SC_0 "/dev/ttyS0" # define SC_1 "/dev/ttyS1" # define SC_FORMAT "/dev/ttyS%d" #endif # define VC_FORMAT "/dev/tty%d" # define LOOP_FORMAT "/dev/loop%d" # define FB_0 "/dev/fb0" #endif //#warning put these in .o files /* The following devices are the same on devfs and non-devfs systems. */ #define CURRENT_TTY "/dev/tty" #define CONSOLE_DEV "/dev/console" int is_in_ino_dev_hashtable(const struct stat *statbuf, char **name); void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name); void reset_ino_dev_hashtable(void); /* Stupid gcc always includes its own builtin strlen()... */ extern size_t bb_strlen(const char *string); #define strlen(x) bb_strlen(x) char *bb_xasprintf(const char *format, ...) __attribute__ ((format (printf, 1, 2))); #define FAIL_DELAY 3 extern void bb_do_delay(int seconds); extern void change_identity ( const struct passwd *pw ); extern const char *change_identity_e2str ( const struct passwd *pw ); extern void run_shell ( const char *shell, int loginshell, const char *command, const char **additional_args); #ifdef CONFIG_SELINUX extern void renew_current_security_context(void); extern void set_current_security_context(security_context_t sid); #endif extern int run_parts(char **args, const unsigned char test_mode, char **env); extern int restricted_shell ( const char *shell ); extern void setup_environment ( const char *shell, int loginshell, int changeenv, const struct passwd *pw ); extern int correct_password ( const struct passwd *pw ); extern char *pw_encrypt(const char *clear, const char *salt); extern struct spwd *pwd_to_spwd(const struct passwd *pw); extern int obscure(const char *old, const char *newval, const struct passwd *pwdp); extern int bb_xopen(const char *pathname, int flags); extern ssize_t bb_xread(int fd, void *buf, size_t count); extern void bb_xread_all(int fd, void *buf, size_t count); extern unsigned char bb_xread_char(int fd); #ifndef COMM_LEN /*#include <sched.h> *//* Task command name length */ #ifdef TASK_COMM_LEN #define COMM_LEN TASK_COMM_LEN #else #define COMM_LEN 16 /* synchronize with size of comm in struct task_struct in /usr/include/linux/sched.h */ #endif #endif typedef struct { int pid; char user[9]; char state[4]; unsigned long rss; int ppid; #ifdef CONFIG_FEATURE_TOP_CPU_USAGE_PERCENTAGE unsigned pcpu; unsigned pscpu; unsigned long stime, utime; #endif char *cmd; /* basename of executable file in call to exec(2), size from kernel headers */ char short_cmd[COMM_LEN]; } procps_status_t; extern procps_status_t * procps_scan(int save_user_arg0); extern int compare_string_array(const char * const string_array[], const char *key); extern int my_query_module(const char *name, int which, void **buf, size_t *bufsize, size_t *ret); typedef struct llist_s { char *data; struct llist_s *link; } llist_t; extern llist_t *llist_add_to(llist_t *old_head, char *new_item); extern llist_t *llist_add_to_end(llist_t *list_head, char *data); extern llist_t *llist_free_one(llist_t *elm); extern void llist_free(llist_t *elm); extern void print_login_issue(const char *issue_file, const char *tty); extern void print_login_prompt(void); extern void vfork_daemon_rexec(int nochdir, int noclose, int argc, char **argv, char *foreground_opt); extern int get_terminal_width_height(int fd, int *width, int *height); extern unsigned long get_ug_id(const char *s, long (*__bb_getxxnam)(const char *)); #define HASH_SHA1 1 #define HASH_MD5 2 extern int hash_fd(int fd, const size_t size, const uint8_t hash_algo, uint8_t *hashval); /* busybox.h will include dmalloc later for us, else include it here. */ #if !defined _BB_INTERNAL_H_ && defined DMALLOC #include <dmalloc.h> #endif #endif /* __LIBCONFIG_H__ */
jgunthorpe/busybox
include/libbb.h
C
gpl-2.0
18,498
# We borrow heavily from the kernel build setup, though we are simpler since # we don't have Kconfig tweaking settings on us. # The implicit make rules have it looking for RCS files, among other things. # We instead explicitly write all the rules we care about. # It's even quicker (saves ~200ms) to pass -r on the command line. MAKEFLAGS=-r # The source directory tree. srcdir := .. abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= . # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= Release # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := CC.target ?= $(CC) CFLAGS.target ?= $(CFLAGS) CXX.target ?= $(CXX) CXXFLAGS.target ?= $(CXXFLAGS) LINK.target ?= $(LINK) LDFLAGS.target ?= $(LDFLAGS) AR.target ?= $(AR) # C++ apps need to be linked with g++. # # Note: flock is used to seralize linking. Linking is a memory-intensive # process so running parallel links can often lead to thrashing. To disable # the serialization, override LINK via an envrionment variable as follows: # # export LINK=g++ # # This will allow make to invoke N linker processes as specified in -jN. LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= gcc CFLAGS.host ?= CXX.host ?= g++ CXXFLAGS.host ?= LINK.host ?= $(CXX.host) LDFLAGS.host ?= AR.host ?= ar # Define a dir function that can handle spaces. # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces replace_spaces = $(subst $(space),?,$1) unreplace_spaces = $(subst ?,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = -MMD -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \ # DEP3 # to # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters. define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1). sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines. sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_objc = CXX($(TOOLSET)) $@ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_objcxx = CXX($(TOOLSET)) $@ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # Commands for precompiled header files. quiet_cmd_pch_c = CXX($(TOOLSET)) $@ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_m = CXX($(TOOLSET)) $@ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # gyp-mac-tool is written next to the root Makefile by gyp. # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd # already. quiet_cmd_mac_tool = MACTOOL $(4) $< cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) quiet_cmd_infoplist = INFOPLIST $@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = rm -rf "$@" && cp -af "$<" "$@" quiet_cmd_alink = LIBTOOL-STATIC $@ cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain ? instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds until one fails. define do_postbuilds @E=0;\ for p in $(POSTBUILDS); do\ eval $$p;\ E=$$?;\ if [ $$E -ne 0 ]; then\ break;\ fi;\ done;\ if [ $$E -ne 0 ]; then\ rm -rf "$@";\ exit $$E;\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains ? for # spaces already and dirx strips the ? characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word 2,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "all" target first so it is the default, # even though we don't have the deps yet. .PHONY: all all: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: TOOLSET := target # Suffix rules, putting all outputs into $(obj). $(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) # Try building from generated source, too. $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ $(findstring $(join ^,$(prefix)),\ $(join ^,bufferutil.target.mk)))),) include bufferutil.target.mk endif quiet_cmd_regen_makefile = ACTION Regenerating $@ cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/AshleyBaird/real-time/real-time-rails/contact/realtime/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/node_modules/bufferutil/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/AshleyBaird/.node-gyp/0.12.4/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/AshleyBaird/.node-gyp/0.12.4" "-Dmodule_root_dir=/Users/AshleyBaird/real-time/real-time-rails/contact/realtime/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/node_modules/bufferutil" binding.gyp Makefile: $(srcdir)/../../../../../../../../../../../../../../.node-gyp/0.12.4/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(call do_cmd,regen_makefile) # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif
Ashley-Peter-Awesome-Chat-App/real-time-rails
contact/realtime/node_modules/socket.io/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/node_modules/bufferutil/build/Makefile
Makefile
gpl-2.0
13,902
<?php /* +---------------------------------------------------------------------------+ | OpenX v2.8 | | ========== | | | | Copyright (c) 2003-2009 OpenX Limited | | For contact details, see: http://www.openx.org/ | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by | | the Free Software Foundation; either version 2 of the License, or | | (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | | | | You should have received a copy of the GNU General Public License | | along with this program; if not, write to the Free Software | | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA | +---------------------------------------------------------------------------+ $Id: userlog-index.php 81439 2012-05-07 23:59:14Z chris.nutting $ */ // Require the initialisation file require_once '../../init.php'; // Required files require_once MAX_PATH . '/lib/max/Admin_DA.php'; require_once MAX_PATH . '/lib/max/other/lib-userlog.inc.php'; require_once MAX_PATH . '/lib/OA/Dal.php'; require_once MAX_PATH . '/lib/OA/Admin/Template.php'; require_once MAX_PATH . '/www/admin/config.php'; require_once MAX_PATH . '/lib/OA/Dll/Audit.php'; require_once MAX_PATH . '/lib/OA/Admin/UI/Field/AuditDaySpanField.php'; require_once 'Pager/Pager.php'; require_once MAX_PATH . '/lib/OX/Translation.php'; // Security check OA_Permission::enforceAccount(OA_ACCOUNT_ADMIN, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADVERTISER, OA_ACCOUNT_TRAFFICKER); OA_Permission::enforceAccountPermission(OA_ACCOUNT_ADVERTISER, OA_PERM_USER_LOG_ACCESS); OA_Permission::enforceAccountPermission(OA_ACCOUNT_TRAFFICKER, OA_PERM_USER_LOG_ACCESS); // Register input variables $advertiserId = MAX_getValue('advertiserId', 0); $campaignId = MAX_getValue('campaignId', 0); $publisherId = MAX_getValue('publisherId', 0); $zoneId = MAX_getValue('zoneId', 0); $startDate = MAX_getStoredValue('period_start', null); $endDate = MAX_getStoredValue('period_end', null); $periodPreset = MAX_getValue('period_preset', 'all_events'); if (!empty($advertiserId)) { OA_Permission::enforceAccessToObject('clients', $advertiserId); } if (!empty($campaignId)) { OA_Permission::enforceAccessToObject('campaigns', $campaignId); } if (!empty($publisherId)) { OA_Permission::enforceAccessToObject('affiliates', $publisherId); } if (!empty($zoneId)) { OA_Permission::enforceAccessToObject('zones', $zoneId); } /*-------------------------------------------------------*/ /* HTML framework */ /*-------------------------------------------------------*/ phpAds_PageHeader("5.4"); if (OA_Permission::isAccount(OA_ACCOUNT_ADMIN)) { // Show all "My Account" sections phpAds_ShowSections(array("5.1", "5.2", "5.3", "5.5", "5.6", "5.4")); phpAds_UserlogSelection("index"); } else if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) { // Show the "Preferences", "User Log" and "Channel Management" sections of the "My Account" sections phpAds_ShowSections(array("5.1", "5.2", "5.4", "5.7")); } else if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER) || OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) { phpAds_ShowSections(array("5.1", "5.2", "5.4")); } // Paging related input variables $listorder = htmlspecialchars(MAX_getStoredValue('listorder', 'updated')); $oAudit = &OA_Dal::factoryDO('audit'); $aAuditColumns = $oAudit->table(); $aColumnNamesFound = array_keys($aAuditColumns, $listorder); if (empty($aColumnNamesFound)) { // Invalid column name to order by, set to default $listorder = 'updated'; } $orderdirection = htmlspecialchars(MAX_getStoredValue('orderdirection', 'up')); if (!($orderdirection == 'up' || $orderdirection == 'down')) { if (stristr($orderdirection, 'down')) { $orderdirection = 'down'; } else { $orderdirection = 'up'; } } $setPerPage = MAX_getStoredValue('setPerPage', 10); $pageID = MAX_getStoredValue('pageID', 1); // Setup date selector $aPeriod = array( 'period_preset' => $periodPreset, 'period_start' => $startDate, 'period_end' => $endDate ); $daySpan = new OA_Admin_UI_Audit_DaySpanField('period'); $daySpan->setValueFromArray($aPeriod); $daySpan->enableAutoSubmit(); // Initialize parameters $pageName = basename($_SERVER['SCRIPT_NAME']); // Load template $oTpl = new OA_Admin_Template('userlog-index.html'); // Get advertisers & publishers for filters $showAdvertisers = OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADMIN); $showPublishers = OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER, OA_ACCOUNT_MANAGER, OA_ACCOUNT_ADMIN); $agencyId = OA_Permission::getAgencyId(); // Get advertisers if we show them $aAdvertiser = $aPublisher = array(); if ($showAdvertisers) { if (OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) { $tempAdvertiserId = OA_Permission::getEntityId(); $aAdvertiserList = Admin_DA::getAdvertisers(array('advertiser_id' => $tempAdvertiserId)); } else { $aAdvertiserList = Admin_DA::getAdvertisers(array('agency_id' => $agencyId)); } $aAdvertiser[0] = $GLOBALS['strSelectAdvertiser']; foreach($aAdvertiserList as $key => $aValue) { $aAdvertiser[$aValue['advertiser_id']] = $aValue['name']; } $aCampaign = array(); if (!empty($advertiserId)) { $campaign = Admin_DA::getCampaigns(array('client_id' => $advertiserId)); $aCampaign[0] = $GLOBALS['strSelectPlacement']; foreach($campaign as $key => $aValue) { $aCampaign[$aValue['campaign_id']] = $aValue['campaignname']; } } } // Get publishers if we show them if ($showPublishers) { if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER)) { $tempPublisherId = OA_Permission::getEntityId(); $aPublisherList = Admin_DA::getPublishers(array('publisher_id' => $tempPublisherId)); } else { $aPublisherList = Admin_DA::getPublishers(array('agency_id' => $agencyId)); } $aPublisher[0] = $GLOBALS['strSelectPublisher']; foreach ($aPublisherList as $key => $aValue) { $aPublisher[$aValue['publisher_id']] = $aValue['name']; } if (!empty($publisherId)) { $zone = Admin_DA::getZones(array('publisher_id' => $publisherId)); $aZone[0] = $GLOBALS['strSelectZone']; foreach ($zone as $key => $aValue) { $aZone[$aValue['zone_id']] = $aValue['name']; } } } $oTrans = new OX_Translation(); $aParams = array( 'order' => $orderdirection, 'listorder' => $listorder, 'start_date' => $startDate, 'end_date' => $endDate, 'prevImg' => '<< ' . $oTrans->translate('Back'), 'nextImg' => $oTrans->translate('Next') . ' >>' ); // Only pass advertiser or website props if we show related checkboxes if ($showAdvertisers) { $aParams['advertiser_id']= $advertiserId; $aParams['campaign_id'] = $campaignId; } if ($showPublishers) { $aParams['publisher_id'] = $publisherId; $aParams['zone_id'] = $zoneId; } // Account security if (OA_Permission::isAccount(OA_ACCOUNT_MANAGER)) { $aParams['account_id'] = OA_Permission::getAccountId(); } if (OA_Permission::isAccount(OA_ACCOUNT_ADVERTISER)) { $aParams['advertiser_account_id'] = OA_Permission::getAccountId(); } if (OA_Permission::isAccount(OA_ACCOUNT_TRAFFICKER)) { $aParams['website_account_id'] = OA_Permission::getAccountId(); } $oUserlog = new OA_Dll_Audit(); $aAuditData = $oUserlog->getAuditLog($aParams); $aParams['totalItems'] = count($aAuditData); if (!isset($pageID) || $pageID == 1) { $aParams['startRecord'] = 0; } else { $aParams['startRecord'] = ($pageID * $setPerPage) - $setPerPage; } if ($aParams['startRecord'] > $aParams['totalItems']) { $aParams['startRecord'] = 0; } $aParams['perPage'] = MAX_getStoredValue('setPerPage', 10); // Retrieve audit details $aAuditData = $oUserlog->getAuditLog($aParams); $pager = & Pager::factory($aParams); $per_page = $pager->_perPage; $pager->history = $pager->getPageData(); $pager->pagerLinks = $pager->getLinks(); $pager->pagerLinks = $pager->pagerLinks['all']; $pager->pagerSelect = preg_replace('/(<select.*?)(>)/i', '$1 onchange="submitForm()" id="setPerPage"$2', $pager->getPerPageSelectBox(10, 100, 10)); // Build column header link params $aAllowdParams = array('advertiserId', 'campaignId', 'publisherId', 'zoneId'); foreach ($aAllowdParams as $key) { if (!empty($$key)) { $aUrlParam[$key] = "$key=".$$key; } } $aUrlParam['listorder'] = "listorder=$listorder"; $aUrlParam['$orderdirection'] = ($orderdirection == 'down') ? "orderdirection=up" : "orderdirection=down"; $urlParam = implode('&', $aUrlParam); // Replace context with translation foreach ($aAuditData as $key => $aValue) { $k = 'str'. str_replace(' ', '', $aValue['context']); if (!empty($GLOBALS[$k])) { $aAuditData[$key]['context'] = $GLOBALS[$k]; } } // Assign vars to template $oTpl->assign('showAdvertisers', $showAdvertisers); $oTpl->assign('showPublishers', $showPublishers); if ($showAdvertisers) { $oTpl->assign('aAdvertiser', $aAdvertiser); $oTpl->assign('aCampaign', $aCampaign); } if ($showPublishers) { $oTpl->assign('aPublisher', $aPublisher); $oTpl->assign('aZone', $aZone); } $oTpl->assign('aAuditEnabled', OA::getConfigOption('audit', 'enabled', false)); $oTpl->assign('aAuditData', $aAuditData); $oTpl->assign('aPeriodPreset', $aPeriodPreset); $oTpl->assign('context', $context); $oTpl->assign('advertiserId', $advertiserId); $oTpl->assign('campaignId', $campaignId); $oTpl->assign('publisherId', $publisherId); $oTpl->assign('zoneId', $zoneId); $oTpl->assign('urlParam', $urlParam); $oTpl->assign('listorder', $listorder); $oTpl->assign('orderdirection', $orderdirection); $oTpl->assign('setPerPage', $setPerPage); $oTpl->assign('pager', $pager); $oTpl->assign('daySpan', $daySpan); // Display page $oTpl->display(); // display footer phpAds_PageFooter(); // Store filter variables in session $session['prefs'][$pageName]['advertiserId'] = $advertiserId; $session['prefs'][$pageName]['campaignId'] = $campaignId; $session['prefs'][$pageName]['publisherId'] = $publisherId; $session['prefs'][$pageName]['zoneId'] = $zoneId; $session['prefs'][$pageName]['period_preset'] = $periodPreset; $seesion['prefs'][$pageName]['setPerPage'] = $setPerPage; $session['prefs'][$pageName]['listorder'] = $listorder; $session['prefs'][$pageName]['orderdirection'] = $orderdirection; phpAds_SessionDataStore(); ?>
soeffing/openx_test
www/admin/userlog-index.php
PHP
gpl-2.0
11,731
package com.comphenix.xp.parser; import static org.junit.Assert.*; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.junit.Test; import com.comphenix.xp.expressions.RangeExpression; import com.google.common.collect.Lists; public class RangeParserTest { @Test public void test() { RangeParser parser = new RangeParser(); String key = "range"; ConfigurationSection listValue = createWithKey(key, Lists.newArrayList(12)); ConfigurationSection textValue = createWithKey(key, "5 - 10"); ConfigurationSection doubleValue = createWithKey(key, 6.5); try { assertEquals(new RangeExpression(12), parser.parse(listValue, key)); assertEquals(new RangeExpression(5, 10), parser.parse(textValue, key)); assertEquals(new RangeExpression(6.5), parser.parse(doubleValue, key)); } catch (ParsingException e) { // None of these should throw an exception fail(e.toString()); } } private ConfigurationSection createWithKey(String key, Object value) { MemoryConfiguration config = new MemoryConfiguration(); // Set the key-value pair config.set(key, value); return config; } }
aadnk/ExperienceMod
ExperienceMod/src/test/java/com/comphenix/xp/parser/RangeParserTest.java
Java
gpl-2.0
1,231
<?php declare(strict_types=1); use TYPO3\CMS\Core\Authentication\AuthenticationService; use TYPO3\CMS\Core\Controller\FileDumpController; use TYPO3\CMS\Core\Controller\RequireJsController; use TYPO3\CMS\Core\Hooks\BackendUserGroupIntegrityCheck; use TYPO3\CMS\Core\Hooks\BackendUserPasswordCheck; use TYPO3\CMS\Core\Hooks\CreateSiteConfiguration; use TYPO3\CMS\Core\Hooks\DestroySessionHook; use TYPO3\CMS\Core\Hooks\PagesTsConfigGuard; use TYPO3\CMS\Core\MetaTag\EdgeMetaTagManager; use TYPO3\CMS\Core\MetaTag\Html5MetaTagManager; use TYPO3\CMS\Core\MetaTag\MetaTagManagerRegistry; use TYPO3\CMS\Core\Resource\Index\ExtractorRegistry; use TYPO3\CMS\Core\Resource\OnlineMedia\Metadata\Extractor; use TYPO3\CMS\Core\Resource\Rendering\AudioTagRenderer; use TYPO3\CMS\Core\Resource\Rendering\RendererRegistry; use TYPO3\CMS\Core\Resource\Rendering\VideoTagRenderer; use TYPO3\CMS\Core\Resource\Rendering\VimeoRenderer; use TYPO3\CMS\Core\Resource\Rendering\YouTubeRenderer; use TYPO3\CMS\Core\Resource\Security\FileMetadataPermissionsAspect; use TYPO3\CMS\Core\Resource\Security\SvgHookHandler; use TYPO3\CMS\Core\Resource\TextExtraction\PlainTextExtractor; use TYPO3\CMS\Core\Resource\TextExtraction\TextExtractorRegistry; use TYPO3\CMS\Core\Utility\ExtensionManagementUtility; use TYPO3\CMS\Core\Utility\GeneralUtility; defined('TYPO3') or die(); $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][GeneralUtility::class]['moveUploadedFile'][] = SvgHookHandler::class . '->processMoveUploadedFile'; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = FileMetadataPermissionsAspect::class; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = BackendUserGroupIntegrityCheck::class; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = BackendUserPasswordCheck::class; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/alt_doc.php']['makeEditForm_accessCheck'][] = FileMetadataPermissionsAspect::class . '->isAllowedToShowEditForm'; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'][] = FileMetadataPermissionsAspect::class . '->isAllowedToShowEditForm'; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['checkModifyAccessList'][] = FileMetadataPermissionsAspect::class; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = DestroySessionHook::class; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][] = PagesTsConfigGuard::class; $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][CreateSiteConfiguration::class] = CreateSiteConfiguration::class; $GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['dumpFile'] = FileDumpController::class . '::dumpAction'; $GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['requirejs'] = RequireJsController::class . '::retrieveConfiguration'; $rendererRegistry = GeneralUtility::makeInstance(RendererRegistry::class); $rendererRegistry->registerRendererClass(AudioTagRenderer::class); $rendererRegistry->registerRendererClass(VideoTagRenderer::class); $rendererRegistry->registerRendererClass(YouTubeRenderer::class); $rendererRegistry->registerRendererClass(VimeoRenderer::class); unset($rendererRegistry); $textExtractorRegistry = GeneralUtility::makeInstance(TextExtractorRegistry::class); $textExtractorRegistry->registerTextExtractor(PlainTextExtractor::class); unset($textExtractorRegistry); $extractorRegistry = GeneralUtility::makeInstance(ExtractorRegistry::class); $extractorRegistry->registerExtractionService(Extractor::class); unset($extractorRegistry); // Register base authentication service ExtensionManagementUtility::addService( 'core', 'auth', AuthenticationService::class, [ 'title' => 'User authentication', 'description' => 'Authentication with username/password.', 'subtype' => 'getUserBE,getUserFE,authUserBE,authUserFE,processLoginDataBE,processLoginDataFE', 'available' => true, 'priority' => 50, 'quality' => 50, 'os' => '', 'exec' => '', 'className' => TYPO3\CMS\Core\Authentication\AuthenticationService::class, ] ); $metaTagManagerRegistry = GeneralUtility::makeInstance(MetaTagManagerRegistry::class); $metaTagManagerRegistry->registerManager( 'html5', Html5MetaTagManager::class ); $metaTagManagerRegistry->registerManager( 'edge', EdgeMetaTagManager::class ); unset($metaTagManagerRegistry); // Add module configuration ExtensionManagementUtility::addTypoScriptSetup( 'config.pageTitleProviders.record.provider = TYPO3\CMS\Core\PageTitle\RecordPageTitleProvider' ); // Register preset for sys_news if (empty($GLOBALS['TYPO3_CONF_VARS']['RTE']['Presets']['sys_news'])) { $GLOBALS['TYPO3_CONF_VARS']['RTE']['Presets']['sys_news'] = 'EXT:core/Configuration/RTE/SysNews.yaml'; }
TYPO3-CMS/core
ext_localconf.php
PHP
gpl-2.0
5,021
<?php class Redux_Validation_url extends Redux_Options { /* for PRO users! - * * Field Constructor. * * Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function * * @since Redux_Options 1.0.0 */ function __construct($field, $value, $current) { parent::__construct(); $this->field = $field; $this->field['msg'] = (isset($this->field['msg'])) ? $this->field['msg'] : __('You must provide a valid URL for this option.', Redux_TEXT_DOMAIN); $this->value = $value; $this->current = $current; $this->validate(); } /* for PRO users! - * * Field Render Function. * * Takes the vars and validates them * * @since Redux_Options 1.0.0 */ function validate() { if (function_exists('filter_var') && filter_var($this->value, FILTER_VALIDATE_URL) == false) { $this->value = (isset($this->current))?$this->current:''; $this->error = $this->field; } else { $this->value = esc_url_raw($this->value); } } }
EmmaTope/SolidSteps
wp-content/themes/dante/includes/options/validation/url/validation_url.php
PHP
gpl-2.0
1,019
/* Marco X display handler */ /* * Copyright (C) 2001 Havoc Pennington * Copyright (C) 2002, 2003, 2004 Red Hat, Inc. * Copyright (C) 2003, 2004 Rob Adams * Copyright (C) 2004-2006 Elijah Newren * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * \file display.c Handles operations on an X display. * * The display is represented as a MetaDisplay struct. */ #include <config.h> #include <glib/gi18n-lib.h> #include "display-private.h" #include "util.h" #include "main.h" #include "screen-private.h" #include "window-private.h" #include "window-props.h" #include "group-props.h" #include "frame-private.h" #include "errors.h" #include "keybindings.h" #include "prefs.h" #include "resizepopup.h" #include "xprops.h" #include "workspace.h" #include "bell.h" #include "effects.h" #include "compositor.h" #include <X11/Xatom.h> #include <X11/cursorfont.h> #ifdef HAVE_SOLARIS_XINERAMA #include <X11/extensions/xinerama.h> #endif #ifdef HAVE_XFREE_XINERAMA #include <X11/extensions/Xinerama.h> #endif #ifdef HAVE_RANDR #include <X11/extensions/Xrandr.h> #endif #ifdef HAVE_SHAPE #include <X11/extensions/shape.h> #endif #ifdef HAVE_RENDER #include <X11/extensions/Xrender.h> #endif #ifdef HAVE_XKB #include <X11/XKBlib.h> #endif #ifdef HAVE_XCURSOR #include <X11/Xcursor/Xcursor.h> #endif #ifdef HAVE_COMPOSITE_EXTENSIONS #include <X11/extensions/Xcomposite.h> #include <X11/extensions/Xdamage.h> #include <X11/extensions/Xfixes.h> #include <gtk/gtk.h> #endif #include <gdk/gdkx.h> #include <string.h> #define GRAB_OP_IS_WINDOW_SWITCH(g) \ (g == META_GRAB_OP_KEYBOARD_TABBING_NORMAL || \ g == META_GRAB_OP_KEYBOARD_TABBING_DOCK || \ g == META_GRAB_OP_KEYBOARD_TABBING_GROUP || \ g == META_GRAB_OP_KEYBOARD_TABBING_NORMAL_ALL_WORKSPACES || \ g == META_GRAB_OP_KEYBOARD_ESCAPING_NORMAL || \ g == META_GRAB_OP_KEYBOARD_ESCAPING_NORMAL_ALL_WORKSPACES || \ g == META_GRAB_OP_KEYBOARD_ESCAPING_DOCK || \ g == META_GRAB_OP_KEYBOARD_ESCAPING_GROUP) /** * \defgroup pings Pings * * Sometimes we want to see whether a window is responding, * so we send it a "ping" message and see whether it sends us back a "pong" * message within a reasonable time. Here we have a system which lets us * nominate one function to be called if we get the pong in time and another * function if we don't. The system is rather more complicated than it needs * to be, since we only ever use it to destroy windows which are asked to * close themselves and don't do so within a reasonable amount of time, and * therefore we always use the same callbacks. It's possible that we might * use it for other things in future, or on the other hand we might decide * that we're never going to do so and simplify it a bit. */ /** * Describes a ping on a window. When we send a ping to a window, we build * one of these structs, and it eventually gets passed to the timeout function * or to the function which handles the response from the window. If the window * does or doesn't respond to the ping, we use this information to deal with * these facts; we have a handler function for each. * * \ingroup pings */ typedef struct { MetaDisplay *display; Window xwindow; guint32 timestamp; MetaWindowPingFunc ping_reply_func; MetaWindowPingFunc ping_timeout_func; void *user_data; guint ping_timeout_id; } MetaPingData; typedef struct { MetaDisplay *display; Window xwindow; } MetaAutoRaiseData; /** * The display we're managing. This is a singleton object. (Historically, * this was a list of displays, but there was never any way to add more * than one element to it.) The goofy name is because we don't want it * to shadow the parameter in its object methods. */ static MetaDisplay *the_display = NULL; #ifdef WITH_VERBOSE_MODE static void meta_spew_event (MetaDisplay *display, XEvent *event); #endif static gboolean event_callback (XEvent *event, gpointer data); static Window event_get_modified_window (MetaDisplay *display, XEvent *event); static guint32 event_get_time (MetaDisplay *display, XEvent *event); static void process_request_frame_extents (MetaDisplay *display, XEvent *event); static void process_pong_message (MetaDisplay *display, XEvent *event); static void process_selection_request (MetaDisplay *display, XEvent *event); static void process_selection_clear (MetaDisplay *display, XEvent *event); static void update_window_grab_modifiers (MetaDisplay *display); static void prefs_changed_callback (MetaPreference pref, void *data); static void sanity_check_timestamps (MetaDisplay *display, guint32 known_good_timestamp); MetaGroup* get_focussed_group (MetaDisplay *display); /** * Destructor for MetaPingData structs. Will destroy the * event source for the struct as well. * * \ingroup pings */ static void ping_data_free (MetaPingData *ping_data) { /* Remove the timeout */ if (ping_data->ping_timeout_id != 0) g_source_remove (ping_data->ping_timeout_id); g_free (ping_data); } /** * Frees every pending ping structure for the given X window on the * given display. This means that we also destroy the timeouts. * * \param display The display the window appears on * \param xwindow The X ID of the window whose pings we should remove * * \ingroup pings * */ static void remove_pending_pings_for_window (MetaDisplay *display, Window xwindow) { GSList *tmp; GSList *dead; /* could obviously be more efficient, don't care */ /* build list to be removed */ dead = NULL; for (tmp = display->pending_pings; tmp; tmp = tmp->next) { MetaPingData *ping_data = tmp->data; if (ping_data->xwindow == xwindow) dead = g_slist_prepend (dead, ping_data); } /* remove what we found */ for (tmp = dead; tmp; tmp = tmp->next) { MetaPingData *ping_data = tmp->data; display->pending_pings = g_slist_remove (display->pending_pings, ping_data); ping_data_free (ping_data); } g_slist_free (dead); } #ifdef HAVE_STARTUP_NOTIFICATION static void sn_error_trap_push (SnDisplay *sn_display, Display *xdisplay) { MetaDisplay *display; display = meta_display_for_x_display (xdisplay); if (display != NULL) meta_error_trap_push (display); } static void sn_error_trap_pop (SnDisplay *sn_display, Display *xdisplay) { MetaDisplay *display; display = meta_display_for_x_display (xdisplay); if (display != NULL) meta_error_trap_pop (display, FALSE); } #endif static void enable_compositor (MetaDisplay *display, gboolean composite_windows) { GSList *list; if (!META_DISPLAY_HAS_COMPOSITE (display) || !META_DISPLAY_HAS_DAMAGE (display) || !META_DISPLAY_HAS_XFIXES (display) || !META_DISPLAY_HAS_RENDER (display)) { meta_warning (_("Missing %s extension required for compositing"), !META_DISPLAY_HAS_COMPOSITE (display) ? "composite" : !META_DISPLAY_HAS_DAMAGE (display) ? "damage" : !META_DISPLAY_HAS_XFIXES (display) ? "xfixes" : "render"); return; } if (!display->compositor) display->compositor = meta_compositor_new (display); if (!display->compositor) return; for (list = display->screens; list != NULL; list = list->next) { MetaScreen *screen = list->data; meta_compositor_manage_screen (screen->display->compositor, screen); if (composite_windows) meta_screen_composite_all_windows (screen); } } static void disable_compositor (MetaDisplay *display) { GSList *list; if (!display->compositor) return; for (list = display->screens; list != NULL; list = list->next) { MetaScreen *screen = list->data; meta_compositor_unmanage_screen (screen->display->compositor, screen); } meta_compositor_destroy (display->compositor); display->compositor = NULL; } /** * Opens a new display, sets it up, initialises all the X extensions * we will need, and adds it to the list of displays. * * \return True if the display was opened successfully, and False * otherwise-- that is, if the display doesn't exist or it already * has a window manager. * * \ingroup main */ gboolean meta_display_open (void) { Display *xdisplay; GSList *screens; GSList *tmp; int i; guint32 timestamp; /* A list of all atom names, so that we can intern them in one go. */ char *atom_names[] = { #define item(x) #x, #include "atomnames.h" #undef item }; Atom atoms[G_N_ELEMENTS(atom_names)]; meta_verbose ("Opening display '%s'\n", XDisplayName (NULL)); xdisplay = meta_ui_get_display (); if (xdisplay == NULL) { meta_warning (_("Failed to open X Window System display '%s'\n"), XDisplayName (NULL)); return FALSE; } if (meta_is_syncing ()) XSynchronize (xdisplay, True); g_assert (the_display == NULL); the_display = g_new (MetaDisplay, 1); the_display->closing = 0; /* here we use XDisplayName which is what the user * probably put in, vs. DisplayString(display) which is * canonicalized by XOpenDisplay() */ the_display->name = g_strdup (XDisplayName (NULL)); the_display->xdisplay = xdisplay; the_display->error_trap_synced_at_last_pop = TRUE; the_display->error_traps = 0; the_display->error_trap_handler = NULL; the_display->server_grab_count = 0; the_display->display_opening = TRUE; the_display->pending_pings = NULL; the_display->autoraise_timeout_id = 0; the_display->autoraise_window = NULL; the_display->focus_window = NULL; the_display->expected_focus_window = NULL; the_display->grab_old_window_stacking = NULL; the_display->mouse_mode = TRUE; /* Only relevant for mouse or sloppy focus */ the_display->allow_terminal_deactivation = TRUE; /* Only relevant for when a terminal has the focus */ #ifdef HAVE_XSYNC the_display->grab_sync_request_alarm = None; #endif /* FIXME copy the checks from GDK probably */ the_display->static_gravity_works = g_getenv ("MARCO_USE_STATIC_GRAVITY") != NULL; the_display->tab_popup_mouse_pressed = FALSE; meta_bell_init (the_display); meta_display_init_keys (the_display); update_window_grab_modifiers (the_display); meta_prefs_add_listener (prefs_changed_callback, the_display); meta_verbose ("Creating %d atoms\n", (int) G_N_ELEMENTS (atom_names)); XInternAtoms (the_display->xdisplay, atom_names, G_N_ELEMENTS (atom_names), False, atoms); { int idx = 0; #define item(x) the_display->atom_##x = atoms[idx++]; #include "atomnames.h" #undef item } the_display->prop_hooks = NULL; meta_display_init_window_prop_hooks (the_display); the_display->group_prop_hooks = NULL; meta_display_init_group_prop_hooks (the_display); /* Offscreen unmapped window used for _NET_SUPPORTING_WM_CHECK, * created in screen_new */ the_display->leader_window = None; the_display->timestamp_pinging_window = None; the_display->xinerama_cache_invalidated = TRUE; the_display->groups_by_leader = NULL; the_display->window_with_menu = NULL; the_display->window_menu = NULL; the_display->screens = NULL; the_display->active_screen = NULL; #ifdef HAVE_STARTUP_NOTIFICATION the_display->sn_display = sn_display_new (the_display->xdisplay, sn_error_trap_push, sn_error_trap_pop); #endif the_display->events = NULL; /* Get events */ meta_ui_add_event_func (the_display->xdisplay, event_callback, the_display); the_display->window_ids = g_hash_table_new (meta_unsigned_long_hash, meta_unsigned_long_equal); i = 0; while (i < N_IGNORED_SERIALS) { the_display->ignored_serials[i] = 0; ++i; } the_display->ungrab_should_not_cause_focus_window = None; the_display->current_time = CurrentTime; the_display->sentinel_counter = 0; the_display->grab_resize_timeout_id = 0; the_display->grab_have_keyboard = FALSE; #ifdef HAVE_XKB the_display->last_bell_time = 0; #endif the_display->grab_op = META_GRAB_OP_NONE; the_display->grab_wireframe_active = FALSE; the_display->grab_window = NULL; the_display->grab_screen = NULL; the_display->grab_resize_popup = NULL; the_display->grab_tile_mode = META_TILE_NONE; the_display->grab_tile_monitor_number = -1; the_display->grab_edge_resistance_data = NULL; #ifdef HAVE_XSYNC { int major, minor; the_display->have_xsync = FALSE; the_display->xsync_error_base = 0; the_display->xsync_event_base = 0; /* I don't think we really have to fill these in */ major = SYNC_MAJOR_VERSION; minor = SYNC_MINOR_VERSION; if (!XSyncQueryExtension (the_display->xdisplay, &the_display->xsync_event_base, &the_display->xsync_error_base) || !XSyncInitialize (the_display->xdisplay, &major, &minor)) { the_display->xsync_error_base = 0; the_display->xsync_event_base = 0; } else the_display->have_xsync = TRUE; meta_verbose ("Attempted to init Xsync, found version %d.%d error base %d event base %d\n", major, minor, the_display->xsync_error_base, the_display->xsync_event_base); } #else /* HAVE_XSYNC */ meta_verbose ("Not compiled with Xsync support\n"); #endif /* !HAVE_XSYNC */ #ifdef HAVE_SHAPE { the_display->have_shape = FALSE; the_display->shape_error_base = 0; the_display->shape_event_base = 0; if (!XShapeQueryExtension (the_display->xdisplay, &the_display->shape_event_base, &the_display->shape_error_base)) { the_display->shape_error_base = 0; the_display->shape_event_base = 0; } else the_display->have_shape = TRUE; meta_verbose ("Attempted to init Shape, found error base %d event base %d\n", the_display->shape_error_base, the_display->shape_event_base); } #else /* HAVE_SHAPE */ meta_verbose ("Not compiled with Shape support\n"); #endif /* !HAVE_SHAPE */ #ifdef HAVE_RENDER { the_display->have_render = FALSE; the_display->render_error_base = 0; the_display->render_event_base = 0; if (!XRenderQueryExtension (the_display->xdisplay, &the_display->render_event_base, &the_display->render_error_base)) { the_display->render_error_base = 0; the_display->render_event_base = 0; } else the_display->have_render = TRUE; meta_verbose ("Attempted to init Render, found error base %d event base %d\n", the_display->render_error_base, the_display->render_event_base); } #else /* HAVE_RENDER */ meta_verbose ("Not compiled with Render support\n"); #endif /* !HAVE_RENDER */ #ifdef HAVE_COMPOSITE_EXTENSIONS { int composite_major_version = 0; int composite_minor_version = 0; the_display->have_composite = FALSE; the_display->composite_error_base = 0; the_display->composite_event_base = 0; if (!XCompositeQueryExtension (the_display->xdisplay, &the_display->composite_event_base, &the_display->composite_error_base)) { the_display->composite_error_base = 0; the_display->composite_event_base = 0; } else { if (XCompositeQueryVersion (the_display->xdisplay, &composite_major_version, &composite_minor_version)) { the_display->have_composite = TRUE; } else { composite_major_version = 0; composite_minor_version = 0; } } meta_verbose ("Attempted to init Composite, found error base %d event base %d " "extn ver %d %d\n", the_display->composite_error_base, the_display->composite_event_base, composite_major_version, composite_minor_version); the_display->have_damage = FALSE; the_display->damage_error_base = 0; the_display->damage_event_base = 0; if (!XDamageQueryExtension (the_display->xdisplay, &the_display->damage_event_base, &the_display->damage_error_base)) { the_display->damage_error_base = 0; the_display->damage_event_base = 0; } else the_display->have_damage = TRUE; meta_verbose ("Attempted to init Damage, found error base %d event base %d\n", the_display->damage_error_base, the_display->damage_event_base); the_display->have_xfixes = FALSE; the_display->xfixes_error_base = 0; the_display->xfixes_event_base = 0; if (!XFixesQueryExtension (the_display->xdisplay, &the_display->xfixes_event_base, &the_display->xfixes_error_base)) { the_display->xfixes_error_base = 0; the_display->xfixes_event_base = 0; } else the_display->have_xfixes = TRUE; meta_verbose ("Attempted to init XFixes, found error base %d event base %d\n", the_display->xfixes_error_base, the_display->xfixes_event_base); } #else /* HAVE_COMPOSITE_EXTENSIONS */ meta_verbose ("Not compiled with Composite support\n"); #endif /* !HAVE_COMPOSITE_EXTENSIONS */ #ifdef HAVE_XCURSOR { XcursorSetTheme (the_display->xdisplay, meta_prefs_get_cursor_theme ()); XcursorSetDefaultSize (the_display->xdisplay, meta_prefs_get_cursor_size ()); } #else /* HAVE_XCURSOR */ meta_verbose ("Not compiled with Xcursor support\n"); #endif /* !HAVE_XCURSOR */ /* Create the leader window here. Set its properties and * use the timestamp from one of the PropertyNotify events * that will follow. */ { gulong data[1]; XEvent event; /* We only care about the PropertyChangeMask in the next 30 or so lines of * code. Note that gdk will at some point unset the PropertyChangeMask for * this window, so we can't rely on it still being set later. See bug * 354213 for details. */ the_display->leader_window = meta_create_offscreen_window (the_display->xdisplay, DefaultRootWindow (the_display->xdisplay), PropertyChangeMask); meta_prop_set_utf8_string_hint (the_display, the_display->leader_window, the_display->atom__NET_WM_NAME, "Metacity (Marco)"); meta_prop_set_utf8_string_hint (the_display, the_display->leader_window, the_display->atom__MARCO_VERSION, VERSION); data[0] = the_display->leader_window; XChangeProperty (the_display->xdisplay, the_display->leader_window, the_display->atom__NET_SUPPORTING_WM_CHECK, XA_WINDOW, 32, PropModeReplace, (guchar*) data, 1); XWindowEvent (the_display->xdisplay, the_display->leader_window, PropertyChangeMask, &event); timestamp = event.xproperty.time; /* Make it painfully clear that we can't rely on PropertyNotify events on * this window, as per bug 354213. */ XSelectInput(the_display->xdisplay, the_display->leader_window, NoEventMask); } /* Make a little window used only for pinging the server for timestamps; note * that meta_create_offscreen_window already selects for PropertyChangeMask. */ the_display->timestamp_pinging_window = meta_create_offscreen_window (the_display->xdisplay, DefaultRootWindow (the_display->xdisplay), PropertyChangeMask); the_display->last_focus_time = timestamp; the_display->last_user_time = timestamp; the_display->compositor = NULL; screens = NULL; i = 0; while (i < ScreenCount (xdisplay)) { MetaScreen *screen; screen = meta_screen_new (the_display, i, timestamp); if (screen) screens = g_slist_prepend (screens, screen); ++i; } the_display->screens = screens; if (screens == NULL) { /* This would typically happen because all the screens already * have window managers. */ meta_display_close (the_display, timestamp); return FALSE; } /* We don't composite the windows here because they will be composited faster with the call to meta_screen_manage_all_windows further down the code */ if (meta_prefs_get_compositing_manager ()) enable_compositor (the_display, FALSE); meta_display_grab (the_display); /* Now manage all existing windows */ tmp = the_display->screens; while (tmp != NULL) { MetaScreen *screen = tmp->data; meta_screen_manage_all_windows (screen); tmp = tmp->next; } { Window focus; int ret_to; /* kinda bogus because GetInputFocus has no possible errors */ meta_error_trap_push (the_display); /* FIXME: This is totally broken; see comment 9 of bug 88194 about this */ focus = None; ret_to = RevertToPointerRoot; XGetInputFocus (the_display->xdisplay, &focus, &ret_to); /* Force a new FocusIn (does this work?) */ /* Use the same timestamp that was passed to meta_screen_new(), * as it is the most recent timestamp. */ if (focus == None || focus == PointerRoot) /* Just focus the no_focus_window on the first screen */ meta_display_focus_the_no_focus_window (the_display, the_display->screens->data, timestamp); else { MetaWindow * window; window = meta_display_lookup_x_window (the_display, focus); if (window) meta_display_set_input_focus_window (the_display, window, FALSE, timestamp); else /* Just focus the no_focus_window on the first screen */ meta_display_focus_the_no_focus_window (the_display, the_display->screens->data, timestamp); } meta_error_trap_pop (the_display, FALSE); } meta_display_ungrab (the_display); /* Done opening new display */ the_display->display_opening = FALSE; return TRUE; } static void listify_func (gpointer key, gpointer value, gpointer data) { GSList **listp; listp = data; *listp = g_slist_prepend (*listp, value); } static gint ptrcmp (gconstpointer a, gconstpointer b) { if (a < b) return -1; else if (a > b) return 1; else return 0; } GSList* meta_display_list_windows (MetaDisplay *display) { GSList *winlist; GSList *tmp; GSList *prev; winlist = NULL; g_hash_table_foreach (display->window_ids, listify_func, &winlist); /* Uniquify the list, since both frame windows and plain * windows are in the hash */ winlist = g_slist_sort (winlist, ptrcmp); prev = NULL; tmp = winlist; while (tmp != NULL) { GSList *next; next = tmp->next; if (next && next->data == tmp->data) { /* Delete tmp from list */ if (prev) prev->next = next; if (tmp == winlist) winlist = next; g_slist_free_1 (tmp); /* leave prev unchanged */ } else { prev = tmp; } tmp = next; } return winlist; } void meta_display_close (MetaDisplay *display, guint32 timestamp) { GSList *tmp; g_assert (display != NULL); if (display->closing != 0) { /* The display's already been closed. */ return; } if (display->error_traps > 0) meta_bug ("Display closed with error traps pending\n"); display->closing += 1; meta_prefs_remove_listener (prefs_changed_callback, display); meta_display_remove_autoraise_callback (display); if (display->grab_old_window_stacking) g_list_free (display->grab_old_window_stacking); /* Stop caring about events */ meta_ui_remove_event_func (display->xdisplay, event_callback, display); /* Free all screens */ tmp = display->screens; while (tmp != NULL) { MetaScreen *screen = tmp->data; meta_screen_free (screen, timestamp); tmp = tmp->next; } g_slist_free (display->screens); display->screens = NULL; #ifdef HAVE_STARTUP_NOTIFICATION if (display->sn_display) { sn_display_unref (display->sn_display); display->sn_display = NULL; } #endif /* Must be after all calls to meta_window_free() since they * unregister windows */ g_hash_table_destroy (display->window_ids); if (display->leader_window != None) XDestroyWindow (display->xdisplay, display->leader_window); XFlush (display->xdisplay); meta_display_free_window_prop_hooks (display); meta_display_free_group_prop_hooks (display); g_free (display->name); meta_display_shutdown_keys (display); if (display->compositor) meta_compositor_destroy (display->compositor); g_free (display); the_display = NULL; meta_quit (META_EXIT_SUCCESS); } MetaScreen* meta_display_screen_for_root (MetaDisplay *display, Window xroot) { GSList *tmp; tmp = display->screens; while (tmp != NULL) { MetaScreen *screen = tmp->data; if (xroot == screen->xroot) return screen; tmp = tmp->next; } return NULL; } MetaScreen* meta_display_screen_for_xwindow (MetaDisplay *display, Window xwindow) { XWindowAttributes attr; int result; meta_error_trap_push (display); attr.screen = NULL; result = XGetWindowAttributes (display->xdisplay, xwindow, &attr); meta_error_trap_pop (display, TRUE); /* Note, XGetWindowAttributes is on all kinds of crack * and returns 1 on success 0 on failure, rather than Success * on success. */ if (result == 0 || attr.screen == NULL) return NULL; return meta_display_screen_for_x_screen (display, attr.screen); } MetaScreen* meta_display_screen_for_x_screen (MetaDisplay *display, Screen *xscreen) { GSList *tmp; tmp = display->screens; while (tmp != NULL) { MetaScreen *screen = tmp->data; if (xscreen == screen->xscreen) return screen; tmp = tmp->next; } return NULL; } /* Grab/ungrab routines taken from fvwm */ void meta_display_grab (MetaDisplay *display) { if (display->server_grab_count == 0) { XGrabServer (display->xdisplay); } display->server_grab_count += 1; meta_verbose ("Grabbing display, grab count now %d\n", display->server_grab_count); } void meta_display_ungrab (MetaDisplay *display) { if (display->server_grab_count == 0) meta_bug ("Ungrabbed non-grabbed server\n"); display->server_grab_count -= 1; if (display->server_grab_count == 0) { /* FIXME we want to purge all pending "queued" stuff * at this point, such as window hide/show */ XUngrabServer (display->xdisplay); XFlush (display->xdisplay); } meta_verbose ("Ungrabbing display, grab count now %d\n", display->server_grab_count); } /** * Returns the singleton MetaDisplay if "xdisplay" matches the X display it's * managing; otherwise gives a warning and returns NULL. When we were claiming * to be able to manage multiple displays, this was supposed to find the * display out of the list which matched that display. Now it's merely an * extra sanity check. * * \param xdisplay An X display * \return The singleton X display, or NULL if "xdisplay" isn't the one * we're managing. */ MetaDisplay* meta_display_for_x_display (Display *xdisplay) { if (the_display->xdisplay == xdisplay) return the_display; meta_warning ("Could not find display for X display %p, probably going to crash\n", xdisplay); return NULL; } /** * Accessor for the singleton MetaDisplay. * * \return The only MetaDisplay there is. This can be NULL, but only * during startup. */ MetaDisplay* meta_get_display (void) { return the_display; } #ifdef WITH_VERBOSE_MODE static gboolean dump_events = TRUE; #endif static gboolean grab_op_is_mouse_only (MetaGrabOp op) { switch (op) { case META_GRAB_OP_MOVING: case META_GRAB_OP_RESIZING_SE: case META_GRAB_OP_RESIZING_S: case META_GRAB_OP_RESIZING_SW: case META_GRAB_OP_RESIZING_N: case META_GRAB_OP_RESIZING_NE: case META_GRAB_OP_RESIZING_NW: case META_GRAB_OP_RESIZING_W: case META_GRAB_OP_RESIZING_E: return TRUE; default: return FALSE; } } static gboolean grab_op_is_mouse (MetaGrabOp op) { switch (op) { case META_GRAB_OP_MOVING: case META_GRAB_OP_RESIZING_SE: case META_GRAB_OP_RESIZING_S: case META_GRAB_OP_RESIZING_SW: case META_GRAB_OP_RESIZING_N: case META_GRAB_OP_RESIZING_NE: case META_GRAB_OP_RESIZING_NW: case META_GRAB_OP_RESIZING_W: case META_GRAB_OP_RESIZING_E: case META_GRAB_OP_KEYBOARD_RESIZING_UNKNOWN: case META_GRAB_OP_KEYBOARD_RESIZING_S: case META_GRAB_OP_KEYBOARD_RESIZING_N: case META_GRAB_OP_KEYBOARD_RESIZING_W: case META_GRAB_OP_KEYBOARD_RESIZING_E: case META_GRAB_OP_KEYBOARD_RESIZING_SE: case META_GRAB_OP_KEYBOARD_RESIZING_NE: case META_GRAB_OP_KEYBOARD_RESIZING_SW: case META_GRAB_OP_KEYBOARD_RESIZING_NW: case META_GRAB_OP_KEYBOARD_MOVING: return TRUE; default: return FALSE; } } static gboolean grab_op_is_keyboard (MetaGrabOp op) { switch (op) { case META_GRAB_OP_KEYBOARD_MOVING: case META_GRAB_OP_KEYBOARD_RESIZING_UNKNOWN: case META_GRAB_OP_KEYBOARD_RESIZING_S: case META_GRAB_OP_KEYBOARD_RESIZING_N: case META_GRAB_OP_KEYBOARD_RESIZING_W: case META_GRAB_OP_KEYBOARD_RESIZING_E: case META_GRAB_OP_KEYBOARD_RESIZING_SE: case META_GRAB_OP_KEYBOARD_RESIZING_NE: case META_GRAB_OP_KEYBOARD_RESIZING_SW: case META_GRAB_OP_KEYBOARD_RESIZING_NW: case META_GRAB_OP_KEYBOARD_TABBING_NORMAL: case META_GRAB_OP_KEYBOARD_TABBING_NORMAL_ALL_WORKSPACES: case META_GRAB_OP_KEYBOARD_TABBING_DOCK: case META_GRAB_OP_KEYBOARD_TABBING_GROUP: case META_GRAB_OP_KEYBOARD_ESCAPING_NORMAL: case META_GRAB_OP_KEYBOARD_ESCAPING_NORMAL_ALL_WORKSPACES: case META_GRAB_OP_KEYBOARD_ESCAPING_DOCK: case META_GRAB_OP_KEYBOARD_ESCAPING_GROUP: case META_GRAB_OP_KEYBOARD_WORKSPACE_SWITCHING: case META_GRAB_OP_KEYBOARD_WORKSPACE_MOVING: return TRUE; default: return FALSE; } } gboolean meta_grab_op_is_resizing (MetaGrabOp op) { switch (op) { case META_GRAB_OP_RESIZING_SE: case META_GRAB_OP_RESIZING_S: case META_GRAB_OP_RESIZING_SW: case META_GRAB_OP_RESIZING_N: case META_GRAB_OP_RESIZING_NE: case META_GRAB_OP_RESIZING_NW: case META_GRAB_OP_RESIZING_W: case META_GRAB_OP_RESIZING_E: case META_GRAB_OP_KEYBOARD_RESIZING_UNKNOWN: case META_GRAB_OP_KEYBOARD_RESIZING_S: case META_GRAB_OP_KEYBOARD_RESIZING_N: case META_GRAB_OP_KEYBOARD_RESIZING_W: case META_GRAB_OP_KEYBOARD_RESIZING_E: case META_GRAB_OP_KEYBOARD_RESIZING_SE: case META_GRAB_OP_KEYBOARD_RESIZING_NE: case META_GRAB_OP_KEYBOARD_RESIZING_SW: case META_GRAB_OP_KEYBOARD_RESIZING_NW: return TRUE; default: return FALSE; } } gboolean meta_grab_op_is_moving (MetaGrabOp op) { switch (op) { case META_GRAB_OP_MOVING: case META_GRAB_OP_KEYBOARD_MOVING: return TRUE; default: return FALSE; } } /* Get time of current event, or CurrentTime if none. */ guint32 meta_display_get_current_time (MetaDisplay *display) { return display->current_time; } /* Get a timestamp, even if it means a roundtrip */ guint32 meta_display_get_current_time_roundtrip (MetaDisplay *display) { guint32 timestamp; timestamp = meta_display_get_current_time (display); if (timestamp == CurrentTime) { XEvent property_event; /* Using the property XA_PRIMARY because it's safe; nothing * would use it as a property. The type doesn't matter. */ XChangeProperty (display->xdisplay, display->timestamp_pinging_window, XA_PRIMARY, XA_STRING, 8, PropModeAppend, NULL, 0); XWindowEvent (display->xdisplay, display->timestamp_pinging_window, PropertyChangeMask, &property_event); timestamp = property_event.xproperty.time; } sanity_check_timestamps (display, timestamp); return timestamp; } static void add_ignored_serial (MetaDisplay *display, unsigned long serial) { int i; /* don't add the same serial more than once */ if (display->ignored_serials[N_IGNORED_SERIALS-1] == serial) return; /* shift serials to the left */ i = 0; while (i < (N_IGNORED_SERIALS - 1)) { display->ignored_serials[i] = display->ignored_serials[i+1]; ++i; } /* put new one on the end */ display->ignored_serials[i] = serial; } static gboolean serial_is_ignored (MetaDisplay *display, unsigned long serial) { int i; i = 0; while (i < N_IGNORED_SERIALS) { if (display->ignored_serials[i] == serial) return TRUE; ++i; } return FALSE; } static void reset_ignores (MetaDisplay *display) { int i; i = 0; while (i < N_IGNORED_SERIALS) { display->ignored_serials[i] = 0; ++i; } display->ungrab_should_not_cause_focus_window = None; } static gboolean window_raise_with_delay_callback (void *data) { MetaWindow *window; MetaAutoRaiseData *auto_raise; auto_raise = data; meta_topic (META_DEBUG_FOCUS, "In autoraise callback for window 0x%lx\n", auto_raise->xwindow); auto_raise->display->autoraise_timeout_id = 0; auto_raise->display->autoraise_window = NULL; window = meta_display_lookup_x_window (auto_raise->display, auto_raise->xwindow); if (window == NULL) return FALSE; /* If we aren't already on top, check whether the pointer is inside * the window and raise the window if so. */ if (meta_stack_get_top (window->screen->stack) != window) { int x, y, root_x, root_y; Window root, child; unsigned int mask; gboolean same_screen; gboolean point_in_window; meta_error_trap_push (window->display); same_screen = XQueryPointer (window->display->xdisplay, window->xwindow, &root, &child, &root_x, &root_y, &x, &y, &mask); meta_error_trap_pop (window->display, TRUE); point_in_window = (window->frame && POINT_IN_RECT (root_x, root_y, window->frame->rect)) || (window->frame == NULL && POINT_IN_RECT (root_x, root_y, window->rect)); if (same_screen && point_in_window) meta_window_raise (window); else meta_topic (META_DEBUG_FOCUS, "Pointer not inside window, not raising %s\n", window->desc); } return FALSE; } void meta_display_queue_autoraise_callback (MetaDisplay *display, MetaWindow *window) { MetaAutoRaiseData *auto_raise_data; meta_topic (META_DEBUG_FOCUS, "Queuing an autoraise timeout for %s with delay %d\n", window->desc, meta_prefs_get_auto_raise_delay ()); auto_raise_data = g_new (MetaAutoRaiseData, 1); auto_raise_data->display = window->display; auto_raise_data->xwindow = window->xwindow; if (display->autoraise_timeout_id != 0) g_source_remove (display->autoraise_timeout_id); display->autoraise_timeout_id = g_timeout_add_full (G_PRIORITY_DEFAULT, meta_prefs_get_auto_raise_delay (), window_raise_with_delay_callback, auto_raise_data, g_free); display->autoraise_window = window; } #if 0 static void handle_net_restack_window (MetaDisplay* display, XEvent *event) { MetaWindow *window; window = meta_display_lookup_x_window (display, event->xclient.window); if (window) { /* FIXME: The EWMH includes a sibling for the restack request, but we * (stupidly) don't currently support these types of raises. * * Also, unconditionally following these is REALLY stupid--we should * combine this code with the stuff in * meta_window_configure_request() which is smart about whether to * follow the request or do something else (though not smart enough * and is also too stupid to handle the sibling stuff). */ switch (event->xclient.data.l[2]) { case Above: meta_window_raise (window); break; case Below: meta_window_lower (window); break; case TopIf: case BottomIf: case Opposite: break; } } } #endif /* We do some of our event handling in core/frames.c, which expects * GDK events delivered by GTK+. However, since the transition to * client side windows, we can't let GDK see button events, since the * client-side tracking of implicit and explicit grabs it does will * get confused by our direct use of X grabs. * * So we do a very minimal GDK => GTK event conversion here and send on the * events we care about, and then filter them out so they don't go * through the normal GDK event handling. * * To reduce the amount of code, the only events fields filled out * below are the ones that frames.c uses. If frames.c is modified to * use more fields, more fields need to be filled out below. * * https://github.com/stefano-k/Mate-Desktop-Environment/commit/b0e5fb03eb21dae8f02692f11ef391bfc5ccba33 */ static gboolean maybe_send_event_to_gtk(MetaDisplay* display, XEvent* xevent) { /* We're always using the default display */ GdkDisplay* gdk_display = gdk_display_get_default(); GdkEvent* gdk_event = NULL; GdkWindow* gdk_window; Window window; GdkSeat *seat; GdkDevice *device; switch (xevent->type) { case ButtonPress: case ButtonRelease: window = xevent->xbutton.window; break; case MotionNotify: window = xevent->xmotion.window; break; case EnterNotify: case LeaveNotify: window = xevent->xcrossing.window; break; default: return FALSE; } gdk_window = gdk_x11_window_lookup_for_display(gdk_display, window); if (gdk_window == NULL) { return FALSE; } /* If GDK already things it has a grab, we better let it see events; this * is the menu-navigation case and events need to get sent to the appropriate * (client-side) subwindow for individual menu items. */ gdk_display = gdk_window_get_display (gdk_window); seat = gdk_display_get_default_seat (gdk_display); device = gdk_seat_get_pointer (seat); if (gdk_display_device_is_grabbed(gdk_display, device)) { return FALSE; } if (gdk_display_device_is_grabbed(gdk_display, device)) { return FALSE; } switch (xevent->type) { case ButtonPress: case ButtonRelease: if (xevent->type == ButtonPress) { GtkSettings* settings = gtk_settings_get_default(); int double_click_time; int double_click_distance; g_object_get (settings, "gtk-double-click-time", &double_click_time, "gtk-double-click-distance", &double_click_distance, NULL); if (xevent->xbutton.button == display->button_click_number && xevent->xbutton.window == display->button_click_window && xevent->xbutton.time < display->button_click_time + double_click_time && ABS(xevent->xbutton.x - display->button_click_x) <= double_click_distance && ABS (xevent->xbutton.y - display->button_click_y) <= double_click_distance) { gdk_event = gdk_event_new(GDK_2BUTTON_PRESS); display->button_click_number = 0; } else { gdk_event = gdk_event_new(GDK_BUTTON_PRESS); display->button_click_number = xevent->xbutton.button; display->button_click_window = xevent->xbutton.window; display->button_click_time = xevent->xbutton.time; display->button_click_x = xevent->xbutton.x; display->button_click_y = xevent->xbutton.y; } } else { gdk_event = gdk_event_new(GDK_BUTTON_RELEASE); } gdk_event->button.window = g_object_ref(gdk_window); gdk_event->button.send_event = 0; gdk_event->button.axes = NULL; gdk_event->button.state = 0; gdk_event->button.device = NULL; gdk_event->button.button = xevent->xbutton.button; gdk_event->button.time = xevent->xbutton.time; gdk_event->button.x = xevent->xbutton.x; gdk_event->button.y = xevent->xbutton.y; gdk_event->button.x_root = xevent->xbutton.x_root; gdk_event->button.y_root = xevent->xbutton.y_root; break; case MotionNotify: gdk_event = gdk_event_new(GDK_MOTION_NOTIFY); gdk_event->motion.window = g_object_ref(gdk_window); gdk_event->motion.send_event = FALSE; gdk_event->motion.time = 0; gdk_event->motion.x = 0; gdk_event->motion.y = 0; gdk_event->motion.axes = NULL; gdk_event->motion.state = 0; gdk_event->motion.is_hint = 0; gdk_event->motion.device = NULL; gdk_event->motion.x_root = 0; gdk_event->motion.y_root = 0; break; case EnterNotify: case LeaveNotify: gdk_event = gdk_event_new(xevent->type == EnterNotify ? GDK_ENTER_NOTIFY : GDK_LEAVE_NOTIFY); gdk_event->crossing.window = g_object_ref(gdk_window); gdk_event->crossing.send_event = 0; gdk_event->crossing.subwindow = NULL; gdk_event->crossing.time = 0; gdk_event->crossing.x = xevent->xcrossing.x; gdk_event->crossing.y = xevent->xcrossing.y; gdk_event->crossing.x_root = 0; gdk_event->crossing.y_root = 0; gdk_event->crossing.mode = 0; gdk_event->crossing.detail = 0; gdk_event->crossing.focus = FALSE; gdk_event->crossing.state = 0; break; default: g_assert_not_reached(); break; } gdk_event_set_device (gdk_event, device); /* If we've gotten here, we've filled in the gdk_event and should send it on */ gtk_main_do_event(gdk_event); gdk_event_free(gdk_event); return TRUE; } static gboolean mouse_event_is_in_tab_popup (MetaDisplay *display, MetaScreen *screen, Window event_window, int event_x, int event_y, int *popup_x, int *popup_y) { if (screen && screen->tab_popup) { int x, y; Window child1, child2; gboolean ok1 = XTranslateCoordinates (display->xdisplay, event_window, event_window, event_x, event_y, &x, &y, &child1); GtkWidget *popup_widget = meta_ui_tab_popup_get_widget (screen->tab_popup); if (ok1 && popup_widget != NULL) { GdkWindow * window = gtk_widget_get_window (popup_widget); if (window == NULL) return FALSE; Window popup_xid = gdk_x11_window_get_xid (window); gboolean ok2 = XTranslateCoordinates (display->xdisplay, event_window, popup_xid, event_x, event_y, popup_x, popup_y, &child2); if (ok2 && child1 == popup_xid) { int scale = gtk_widget_get_scale_factor (popup_widget); if (scale != 0) { *popup_x /= scale; *popup_y /= scale; } return TRUE; } } } return FALSE; } /** * This is the most important function in the whole program. It is the heart, * it is the nexus, it is the Grand Central Station of Marco's world. * When we create a MetaDisplay, we ask GDK to pass *all* events for *all* * windows to this function. So every time anything happens that we might * want to know about, this function gets called. You see why it gets a bit * busy around here. Most of this function is a ginormous switch statement * dealing with all the kinds of events that might turn up. * * \param event The event that just happened * \param data The MetaDisplay that events are coming from, cast to a gpointer * so that it can be sent to a callback * * \ingroup main */ static gboolean event_callback(XEvent* event, gpointer data) { MetaWindow *window; MetaWindow *property_for_window; MetaDisplay *display; Window modified; gboolean frame_was_receiver; gboolean filter_out_event; display = data; #ifdef WITH_VERBOSE_MODE if (dump_events) meta_spew_event (display, event); #endif #ifdef HAVE_STARTUP_NOTIFICATION sn_display_process_event (display->sn_display, event); #endif filter_out_event = FALSE; display->current_time = event_get_time (display, event); display->xinerama_cache_invalidated = TRUE; modified = event_get_modified_window (display, event); if (event->type == ButtonPress) { /* filter out scrollwheel */ if (event->xbutton.button == 4 || event->xbutton.button == 5) return FALSE; } else if (event->type == UnmapNotify) { if (meta_ui_window_should_not_cause_focus (display->xdisplay, modified)) { add_ignored_serial (display, event->xany.serial); meta_topic (META_DEBUG_FOCUS, "Adding EnterNotify serial %lu to ignored focus serials\n", event->xany.serial); } } else if (event->type == LeaveNotify && event->xcrossing.mode == NotifyUngrab && modified == display->ungrab_should_not_cause_focus_window) { add_ignored_serial (display, event->xany.serial); meta_topic (META_DEBUG_FOCUS, "Adding LeaveNotify serial %lu to ignored focus serials\n", event->xany.serial); } if (modified != None) window = meta_display_lookup_x_window (display, modified); else window = NULL; /* We only want to respond to _NET_WM_USER_TIME property notify * events on _NET_WM_USER_TIME_WINDOW windows; in particular, * responding to UnmapNotify events is kind of bad. */ property_for_window = NULL; if (window && modified == window->user_time_window) { property_for_window = window; window = NULL; } frame_was_receiver = FALSE; if (window && window->frame && modified == window->frame->xwindow) { /* Note that if the frame and the client both have an * XGrabButton (as is normal with our setup), the event * goes to the frame. */ frame_was_receiver = TRUE; meta_topic (META_DEBUG_EVENTS, "Frame was receiver of event for %s\n", window->desc); } #ifdef HAVE_XSYNC if (META_DISPLAY_HAS_XSYNC (display) && event->type == (display->xsync_event_base + XSyncAlarmNotify) && ((XSyncAlarmNotifyEvent*)event)->alarm == display->grab_sync_request_alarm) { filter_out_event = TRUE; /* GTK doesn't want to see this really */ if (display->grab_op != META_GRAB_OP_NONE && display->grab_window != NULL && grab_op_is_mouse (display->grab_op)) meta_window_handle_mouse_grab_op_event (display->grab_window, event); } #endif /* HAVE_XSYNC */ #ifdef HAVE_SHAPE if (META_DISPLAY_HAS_SHAPE (display) && event->type == (display->shape_event_base + ShapeNotify)) { filter_out_event = TRUE; /* GTK doesn't want to see this really */ if (window && !frame_was_receiver) { XShapeEvent *sev = (XShapeEvent*) event; if (sev->kind == ShapeBounding) { if (sev->shaped && !window->has_shape) { window->has_shape = TRUE; meta_topic (META_DEBUG_SHAPES, "Window %s now has a shape\n", window->desc); } else if (!sev->shaped && window->has_shape) { window->has_shape = FALSE; meta_topic (META_DEBUG_SHAPES, "Window %s no longer has a shape\n", window->desc); } else { meta_topic (META_DEBUG_SHAPES, "Window %s shape changed\n", window->desc); } if (window->frame) { window->frame->need_reapply_frame_shape = TRUE; meta_warning("from event callback\n"); meta_window_queue (window, META_QUEUE_MOVE_RESIZE); } } } else { meta_topic (META_DEBUG_SHAPES, "ShapeNotify not on a client window (window %s frame_was_receiver = %d)\n", window ? window->desc : "(none)", frame_was_receiver); } } #endif /* HAVE_SHAPE */ if (window && ((event->type == KeyPress) || (event->type == ButtonPress))) { if (CurrentTime == display->current_time) { /* We can't use missing (i.e. invalid) timestamps to set user time, * nor do we want to use them to sanity check other timestamps. * See bug 313490 for more details. */ meta_warning ("Event has no timestamp! You may be using a broken " "program such as xse. Please ask the authors of that " "program to fix it.\n"); } else { meta_window_set_user_time (window, display->current_time); sanity_check_timestamps (display, display->current_time); } } switch (event->type) { case KeyPress: case KeyRelease: meta_display_process_key_event (display, window, event); break; case ButtonPress: /* Use window under pointer when processing synthetic events from another client */ if (window == NULL && event->xbutton.send_event) { int x, y, root_x, root_y; Window root, child; guint mask; XQueryPointer (display->xdisplay, event->xany.window, &root, &child, &root_x, &root_y, &x, &y, &mask); window = meta_display_lookup_x_window (display, child); } if ((window && grab_op_is_mouse (display->grab_op) && display->grab_button != (int) event->xbutton.button && display->grab_window == window) || grab_op_is_keyboard (display->grab_op)) { gboolean is_in_tab_popup = FALSE; if (grab_op_is_keyboard (display->grab_op)) { MetaScreen *screen = meta_display_screen_for_root (display, event->xany.window); int popup_x, popup_y; is_in_tab_popup = mouse_event_is_in_tab_popup (display, screen, event->xany.window, event->xbutton.x, event->xbutton.y, &popup_x, &popup_y); if (is_in_tab_popup && event->xbutton.button == Button1) { display->tab_popup_mouse_pressed = TRUE; meta_ui_tab_popup_mouse_press(screen->tab_popup, popup_x, popup_y); } } if (!is_in_tab_popup) { meta_topic (META_DEBUG_WINDOW_OPS, "Ending grab op %u on window %s due to button press\n", display->grab_op, (display->grab_window ? display->grab_window->desc : "none")); if (GRAB_OP_IS_WINDOW_SWITCH (display->grab_op)) { MetaScreen *screen; meta_topic (META_DEBUG_WINDOW_OPS, "Syncing to old stack positions.\n"); screen = meta_display_screen_for_root (display, event->xany.window); if (screen!=NULL) meta_stack_set_positions (screen->stack, display->grab_old_window_stacking); } meta_display_end_grab_op (display, event->xbutton.time); } } else if (window && display->grab_op == META_GRAB_OP_NONE) { gboolean begin_move = FALSE; unsigned int grab_mask; gboolean unmodified; grab_mask = display->window_grab_modifiers; if (g_getenv ("MARCO_DEBUG_BUTTON_GRABS")) grab_mask |= ControlMask; /* Two possible sources of an unmodified event; one is a * client that's letting button presses pass through to the * frame, the other is our focus_window_grab on unmodified * button 1. So for all such events we focus the window. */ unmodified = (event->xbutton.state & grab_mask) == 0; if (unmodified || event->xbutton.button == 1) { /* don't focus if frame received, will be lowered in * frames.c or special-cased if the click was on a * minimize/close button. */ if (!frame_was_receiver) { if (meta_prefs_get_raise_on_click ()) meta_window_raise (window); else meta_topic (META_DEBUG_FOCUS, "Not raising window on click due to don't-raise-on-click option\n"); /* Don't focus panels--they must explicitly request focus. * See bug 160470 */ if (window->type != META_WINDOW_DOCK) { meta_topic (META_DEBUG_FOCUS, "Focusing %s due to unmodified button %u press (display.c)\n", window->desc, event->xbutton.button); meta_window_focus (window, event->xbutton.time); } else /* However, do allow terminals to lose focus due to new * window mappings after the user clicks on a panel. */ display->allow_terminal_deactivation = TRUE; } /* you can move on alt-click but not on * the click-to-focus */ if (!unmodified) begin_move = TRUE; } else if (!unmodified && event->xbutton.button == meta_prefs_get_mouse_button_resize()) { if (window->has_resize_func) { gboolean north, south; gboolean west, east; int root_x, root_y; MetaGrabOp op; meta_window_get_position (window, &root_x, &root_y); west = event->xbutton.x_root < (root_x + 1 * window->rect.width / 3); east = event->xbutton.x_root > (root_x + 2 * window->rect.width / 3); north = event->xbutton.y_root < (root_y + 1 * window->rect.height / 3); south = event->xbutton.y_root > (root_y + 2 * window->rect.height / 3); if (north && west) op = META_GRAB_OP_RESIZING_NW; else if (north && east) op = META_GRAB_OP_RESIZING_NE; else if (south && west) op = META_GRAB_OP_RESIZING_SW; else if (south && east) op = META_GRAB_OP_RESIZING_SE; else if (north) op = META_GRAB_OP_RESIZING_N; else if (west) op = META_GRAB_OP_RESIZING_W; else if (east) op = META_GRAB_OP_RESIZING_E; else if (south) op = META_GRAB_OP_RESIZING_S; else /* Middle region is no-op to avoid user triggering wrong action */ op = META_GRAB_OP_NONE; if (op != META_GRAB_OP_NONE) meta_display_begin_grab_op (display, window->screen, window, op, TRUE, FALSE, event->xbutton.button, 0, event->xbutton.time, event->xbutton.x_root, event->xbutton.y_root); } } else if (event->xbutton.button == meta_prefs_get_mouse_button_menu()) { if (meta_prefs_get_raise_on_click ()) meta_window_raise (window); meta_window_show_menu (window, event->xbutton.x_root, event->xbutton.y_root, event->xbutton.button, event->xbutton.time); } if (!frame_was_receiver && unmodified) { /* This is from our synchronous grab since * it has no modifiers and was on the client window */ int mode; /* When clicking a different app in click-to-focus * in application-based mode, and the different * app is not a dock or desktop, eat the focus click. */ if (meta_prefs_get_focus_mode () == META_FOCUS_MODE_CLICK && meta_prefs_get_application_based () && !window->has_focus && window->type != META_WINDOW_DOCK && window->type != META_WINDOW_DESKTOP && (display->focus_window == NULL || !meta_window_same_application (window, display->focus_window))) mode = AsyncPointer; /* eat focus click */ else mode = ReplayPointer; /* give event back */ meta_verbose ("Allowing events mode %s time %u\n", mode == AsyncPointer ? "AsyncPointer" : "ReplayPointer", (unsigned int)event->xbutton.time); XAllowEvents (display->xdisplay, mode, event->xbutton.time); } if (begin_move && window->has_move_func) { meta_display_begin_grab_op (display, window->screen, window, META_GRAB_OP_MOVING, TRUE, FALSE, event->xbutton.button, 0, event->xbutton.time, event->xbutton.x_root, event->xbutton.y_root); } } break; case ButtonRelease: if (display->grab_window == window && grab_op_is_mouse (display->grab_op)) meta_window_handle_mouse_grab_op_event (window, event); if (event->xbutton.button == Button1) display->tab_popup_mouse_pressed = FALSE; break; case MotionNotify: if (display->grab_window == window && grab_op_is_mouse (display->grab_op)) meta_window_handle_mouse_grab_op_event (window, event); else if (grab_op_is_keyboard (display->grab_op) && display->tab_popup_mouse_pressed) { MetaScreen *screen = meta_display_screen_for_root (display, event->xany.window); int popup_x, popup_y; gboolean is_in_tab_popup = mouse_event_is_in_tab_popup (display, screen, event->xany.window, event->xbutton.x, event->xbutton.y, &popup_x, &popup_y); if (is_in_tab_popup) meta_ui_tab_popup_mouse_press (screen->tab_popup, popup_x, popup_y); } break; case EnterNotify: if (display->grab_window == window && grab_op_is_mouse (display->grab_op)) { meta_window_handle_mouse_grab_op_event (window, event); break; } /* If the mouse switches screens, active the default window on the new * screen; this will make keybindings and workspace-launched items * actually appear on the right screen. */ { MetaScreen *new_screen = meta_display_screen_for_root (display, event->xcrossing.root); if (new_screen != NULL && display->active_screen != new_screen) meta_workspace_focus_default_window (new_screen->active_workspace, NULL, event->xcrossing.time); } /* Check if we've entered a window; do this even if window->has_focus to * avoid races. */ if (window && !serial_is_ignored (display, event->xany.serial) && event->xcrossing.mode != NotifyGrab && event->xcrossing.mode != NotifyUngrab && event->xcrossing.detail != NotifyInferior && meta_display_focus_sentinel_clear (display)) { switch (meta_prefs_get_focus_mode ()) { case META_FOCUS_MODE_SLOPPY: case META_FOCUS_MODE_MOUSE: display->mouse_mode = TRUE; if (window->type != META_WINDOW_DOCK && window->type != META_WINDOW_DESKTOP) { meta_topic (META_DEBUG_FOCUS, "Focusing %s due to enter notify with serial %lu " "at time %lu, and setting display->mouse_mode to " "TRUE.\n", window->desc, event->xany.serial, event->xcrossing.time); meta_window_focus (window, event->xcrossing.time); /* stop ignoring stuff */ reset_ignores (display); if (meta_prefs_get_auto_raise ()) { meta_display_queue_autoraise_callback (display, window); } else { meta_topic (META_DEBUG_FOCUS, "Auto raise is disabled\n"); } } /* In mouse focus mode, we defocus when the mouse *enters* * the DESKTOP window, instead of defocusing on LeaveNotify. * This is because having the mouse enter override-redirect * child windows unfortunately causes LeaveNotify events that * we can't distinguish from the mouse actually leaving the * toplevel window as we expect. But, since we filter out * EnterNotify events on override-redirect windows, this * alternative mechanism works great. */ if (window->type == META_WINDOW_DESKTOP && meta_prefs_get_focus_mode() == META_FOCUS_MODE_MOUSE && display->expected_focus_window != NULL) { meta_topic (META_DEBUG_FOCUS, "Unsetting focus from %s due to mouse entering " "the DESKTOP window\n", display->expected_focus_window->desc); meta_display_focus_the_no_focus_window (display, window->screen, event->xcrossing.time); } break; case META_FOCUS_MODE_CLICK: break; } if (window->type == META_WINDOW_DOCK) meta_window_raise (window); } break; case LeaveNotify: if (display->grab_window == window && grab_op_is_mouse (display->grab_op)) meta_window_handle_mouse_grab_op_event (window, event); else if (window != NULL) { if (window->type == META_WINDOW_DOCK && event->xcrossing.mode != NotifyGrab && event->xcrossing.mode != NotifyUngrab && !window->has_focus) meta_window_lower (window); } break; case FocusIn: case FocusOut: if (window) { meta_window_notify_focus (window, event); } else if (meta_display_xwindow_is_a_no_focus_window (display, event->xany.window)) { meta_topic (META_DEBUG_FOCUS, "Focus %s event received on no_focus_window 0x%lx " "mode %s detail %s\n", event->type == FocusIn ? "in" : event->type == FocusOut ? "out" : "???", event->xany.window, meta_event_mode_to_string (event->xfocus.mode), meta_event_detail_to_string (event->xfocus.detail)); } else { MetaScreen *screen = meta_display_screen_for_root(display, event->xany.window); if (screen == NULL) break; meta_topic (META_DEBUG_FOCUS, "Focus %s event received on root window 0x%lx " "mode %s detail %s\n", event->type == FocusIn ? "in" : event->type == FocusOut ? "out" : "???", event->xany.window, meta_event_mode_to_string (event->xfocus.mode), meta_event_detail_to_string (event->xfocus.detail)); if (event->type == FocusIn && event->xfocus.detail == NotifyDetailNone) { meta_topic (META_DEBUG_FOCUS, "Focus got set to None, probably due to " "brain-damage in the X protocol (see bug " "125492). Setting the default focus window.\n"); meta_workspace_focus_default_window (screen->active_workspace, NULL, meta_display_get_current_time_roundtrip (display)); } else if (event->type == FocusIn && event->xfocus.mode == NotifyNormal && event->xfocus.detail == NotifyInferior) { meta_topic (META_DEBUG_FOCUS, "Focus got set to root window, probably due to " "mate-session logout dialog usage (see bug " "153220). Setting the default focus window.\n"); meta_workspace_focus_default_window (screen->active_workspace, NULL, meta_display_get_current_time_roundtrip (display)); } } break; case KeymapNotify: break; case Expose: break; case GraphicsExpose: break; case NoExpose: break; case VisibilityNotify: break; case CreateNotify: break; case DestroyNotify: if (window) { /* FIXME: It sucks that DestroyNotify events don't come with * a timestamp; could we do something better here? Maybe X * will change one day? */ guint32 timestamp; timestamp = meta_display_get_current_time_roundtrip (display); if (display->grab_op != META_GRAB_OP_NONE && display->grab_window == window) meta_display_end_grab_op (display, timestamp); if (frame_was_receiver) { meta_warning ("Unexpected destruction of frame 0x%lx, not sure if this should silently fail or be considered a bug\n", window->frame->xwindow); meta_error_trap_push (display); meta_window_destroy_frame (window->frame->window); meta_error_trap_pop (display, FALSE); } else { /* Unmanage destroyed window */ meta_window_free (window, timestamp); window = NULL; } } break; case UnmapNotify: if (window) { /* FIXME: It sucks that UnmapNotify events don't come with * a timestamp; could we do something better here? Maybe X * will change one day? */ guint32 timestamp; timestamp = meta_display_get_current_time_roundtrip (display); if (display->grab_op != META_GRAB_OP_NONE && display->grab_window == window && ((window->frame == NULL) || !window->frame->mapped)) meta_display_end_grab_op (display, timestamp); if (!frame_was_receiver) { if (window->unmaps_pending == 0) { meta_topic (META_DEBUG_WINDOW_STATE, "Window %s withdrawn\n", window->desc); meta_effect_run_close (window, NULL, NULL); /* Unmanage withdrawn window */ window->withdrawn = TRUE; meta_window_free (window, timestamp); window = NULL; } else { window->unmaps_pending -= 1; meta_topic (META_DEBUG_WINDOW_STATE, "Received pending unmap, %d now pending\n", window->unmaps_pending); } } /* Unfocus on UnmapNotify, do this after the possible * window_free above so that window_free can see if window->has_focus * and move focus to another window */ if (window) meta_window_notify_focus (window, event); } break; case MapNotify: break; case MapRequest: if (window == NULL) { window = meta_window_new (display, event->xmaprequest.window, FALSE); } /* if frame was receiver it's some malicious send event or something */ else if (!frame_was_receiver && window) { meta_verbose ("MapRequest on %s mapped = %d minimized = %d\n", window->desc, window->mapped, window->minimized); if (window->minimized) { meta_window_unminimize (window); if (window->workspace != window->screen->active_workspace) { meta_verbose ("Changing workspace due to MapRequest mapped = %d minimized = %d\n", window->mapped, window->minimized); meta_window_change_workspace (window, window->screen->active_workspace); } } } break; case ReparentNotify: break; case ConfigureNotify: /* Handle screen resize */ { MetaScreen *screen; screen = meta_display_screen_for_root (display, event->xconfigure.window); if (screen != NULL) { #ifdef HAVE_RANDR /* do the resize the official way */ XRRUpdateConfiguration (event); #else /* poke around in Xlib */ screen->xscreen->width = event->xconfigure.width; screen->xscreen->height = event->xconfigure.height; #endif meta_screen_resize (screen, event->xconfigure.width, event->xconfigure.height); } } break; case ConfigureRequest: /* This comment and code is found in both twm and fvwm */ /* * According to the July 27, 1988 ICCCM draft, we should ignore size and * position fields in the WM_NORMAL_HINTS property when we map a window. * Instead, we'll read the current geometry. Therefore, we should respond * to configuration requests for windows which have never been mapped. */ if (window == NULL) { unsigned int xwcm; XWindowChanges xwc; xwcm = event->xconfigurerequest.value_mask & (CWX | CWY | CWWidth | CWHeight | CWBorderWidth); xwc.x = event->xconfigurerequest.x; xwc.y = event->xconfigurerequest.y; xwc.width = event->xconfigurerequest.width; xwc.height = event->xconfigurerequest.height; xwc.border_width = event->xconfigurerequest.border_width; meta_verbose ("Configuring withdrawn window to %d,%d %dx%d border %d (some values may not be in mask)\n", xwc.x, xwc.y, xwc.width, xwc.height, xwc.border_width); meta_error_trap_push (display); XConfigureWindow (display->xdisplay, event->xconfigurerequest.window, xwcm, &xwc); meta_error_trap_pop (display, FALSE); } else { if (!frame_was_receiver) meta_window_configure_request (window, event); } break; case GravityNotify: break; case ResizeRequest: break; case CirculateNotify: break; case CirculateRequest: break; case PropertyNotify: { MetaGroup *group; MetaScreen *screen; if (window && !frame_was_receiver) meta_window_property_notify (window, event); else if (property_for_window && !frame_was_receiver) meta_window_property_notify (property_for_window, event); group = meta_display_lookup_group (display, event->xproperty.window); if (group != NULL) meta_group_property_notify (group, event); screen = NULL; if (window == NULL && group == NULL) /* window/group != NULL means it wasn't a root window */ screen = meta_display_screen_for_root (display, event->xproperty.window); if (screen != NULL) { if (event->xproperty.atom == display->atom__NET_DESKTOP_LAYOUT) meta_screen_update_workspace_layout (screen); else if (event->xproperty.atom == display->atom__NET_DESKTOP_NAMES) meta_screen_update_workspace_names (screen); #if 0 else if (event->xproperty.atom == display->atom__NET_RESTACK_WINDOW) handle_net_restack_window (display, event); #endif /* we just use this property as a sentinel to avoid * certain race conditions. See the comment for the * sentinel_counter variable declaration in display.h */ if (event->xproperty.atom == display->atom__MARCO_SENTINEL) { meta_display_decrement_focus_sentinel (display); } } } break; case SelectionClear: /* do this here instead of at end of function * so we can return */ /* FIXME: Clearing display->current_time here makes no sense to * me; who put this here and why? */ display->current_time = CurrentTime; process_selection_clear (display, event); /* Note that processing that may have resulted in * closing the display... so return right away. */ return FALSE; case SelectionRequest: process_selection_request (display, event); break; case SelectionNotify: break; case ColormapNotify: if (window && !frame_was_receiver) window->colormap = event->xcolormap.colormap; break; case ClientMessage: if (window) { if (!frame_was_receiver) meta_window_client_message (window, event); } else { MetaScreen *screen; screen = meta_display_screen_for_root (display, event->xclient.window); if (screen) { if (event->xclient.message_type == display->atom__NET_CURRENT_DESKTOP) { int space; MetaWorkspace *workspace; guint32 time; space = event->xclient.data.l[0]; time = event->xclient.data.l[1]; meta_verbose ("Request to change current workspace to %d with " "specified timestamp of %u\n", space, time); workspace = meta_screen_get_workspace_by_index (screen, space); /* Handle clients using the older version of the spec... */ if (time == 0 && workspace) { meta_warning ("Received a NET_CURRENT_DESKTOP message " "from a broken (outdated) client who sent " "a 0 timestamp\n"); time = meta_display_get_current_time_roundtrip (display); } if (workspace) meta_workspace_activate (workspace, time); else meta_verbose ("Don't know about workspace %d\n", space); } else if (event->xclient.message_type == display->atom__NET_NUMBER_OF_DESKTOPS) { int num_spaces; num_spaces = event->xclient.data.l[0]; meta_verbose ("Request to set number of workspaces to %d\n", num_spaces); meta_prefs_set_num_workspaces (num_spaces); } else if (event->xclient.message_type == display->atom__NET_SHOWING_DESKTOP) { gboolean showing_desktop; guint32 timestamp; showing_desktop = event->xclient.data.l[0] != 0; /* FIXME: Braindead protocol doesn't have a timestamp */ timestamp = meta_display_get_current_time_roundtrip (display); meta_verbose ("Request to %s desktop\n", showing_desktop ? "show" : "hide"); if (showing_desktop) meta_screen_show_desktop (screen, timestamp); else { meta_screen_unshow_desktop (screen); meta_workspace_focus_default_window (screen->active_workspace, NULL, timestamp); } } else if (event->xclient.message_type == display->atom__MARCO_RESTART_MESSAGE) { meta_verbose ("Received restart request\n"); meta_restart (); } else if (event->xclient.message_type == display->atom__MARCO_RELOAD_THEME_MESSAGE) { meta_verbose ("Received reload theme request\n"); meta_ui_set_current_theme (meta_prefs_get_theme (), TRUE); meta_display_retheme_all (); } else if (event->xclient.message_type == display->atom__MARCO_SET_KEYBINDINGS_MESSAGE) { meta_verbose ("Received set keybindings request = %d\n", (int) event->xclient.data.l[0]); meta_set_keybindings_disabled (!event->xclient.data.l[0]); } else if (event->xclient.message_type == display->atom__MARCO_TOGGLE_VERBOSE) { meta_verbose ("Received toggle verbose message\n"); meta_set_verbose (!meta_is_verbose ()); } else if (event->xclient.message_type == display->atom_WM_PROTOCOLS) { meta_verbose ("Received WM_PROTOCOLS message\n"); if ((Atom)event->xclient.data.l[0] == display->atom__NET_WM_PING) { process_pong_message (display, event); /* We don't want ping reply events going into * the GTK+ event loop because gtk+ will treat * them as ping requests and send more replies. */ filter_out_event = TRUE; } } } if (event->xclient.message_type == display->atom__NET_REQUEST_FRAME_EXTENTS) { meta_verbose ("Received _NET_REQUEST_FRAME_EXTENTS message\n"); process_request_frame_extents (display, event); } } break; case MappingNotify: { gboolean ignore_current; ignore_current = FALSE; /* Check whether the next event is an identical MappingNotify * event. If it is, ignore the current event, we'll update * when we get the next one. */ if (XPending (display->xdisplay)) { XEvent next_event; XPeekEvent (display->xdisplay, &next_event); if (next_event.type == MappingNotify && next_event.xmapping.request == event->xmapping.request) ignore_current = TRUE; } if (!ignore_current) { /* Let XLib know that there is a new keyboard mapping. */ XRefreshKeyboardMapping (&event->xmapping); meta_display_process_mapping_event (display, event); } } break; default: #ifdef HAVE_XKB if (event->type == display->xkb_base_event_type) { XkbAnyEvent *xkb_ev = (XkbAnyEvent *) event; switch (xkb_ev->xkb_type) { case XkbBellNotify: if (XSERVER_TIME_IS_BEFORE(display->last_bell_time, xkb_ev->time - 100)) { display->last_bell_time = xkb_ev->time; meta_bell_notify (display, xkb_ev); } break; case XkbNewKeyboardNotify: case XkbMapNotify: meta_display_process_mapping_event (display, event); break; } } #endif break; } if (display->compositor) { meta_compositor_process_event (display->compositor, event, window); } /* generates event on wrong window. * https://github.com/stefano-k/Mate-Desktop-Environment/commit/b0e5fb03eb21dae8f02692f11ef391bfc5ccba33 */ if (maybe_send_event_to_gtk(display, event)) { filter_out_event = TRUE; } display->current_time = CurrentTime; return filter_out_event; } /* Return the window this has to do with, if any, rather * than the frame or root window that was selecting * for substructure */ static Window event_get_modified_window (MetaDisplay *display, XEvent *event) { switch (event->type) { case KeyPress: case KeyRelease: case ButtonPress: case ButtonRelease: case MotionNotify: case FocusIn: case FocusOut: case KeymapNotify: case Expose: case GraphicsExpose: case NoExpose: case VisibilityNotify: case ResizeRequest: case PropertyNotify: case SelectionClear: case SelectionRequest: case SelectionNotify: case ColormapNotify: case ClientMessage: case EnterNotify: case LeaveNotify: return event->xany.window; case CreateNotify: return event->xcreatewindow.window; case DestroyNotify: return event->xdestroywindow.window; case UnmapNotify: return event->xunmap.window; case MapNotify: return event->xmap.window; case MapRequest: return event->xmaprequest.window; case ReparentNotify: return event->xreparent.window; case ConfigureNotify: return event->xconfigure.window; case ConfigureRequest: return event->xconfigurerequest.window; case GravityNotify: return event->xgravity.window; case CirculateNotify: return event->xcirculate.window; case CirculateRequest: return event->xcirculaterequest.window; case MappingNotify: return None; default: #ifdef HAVE_SHAPE if (META_DISPLAY_HAS_SHAPE (display) && event->type == (display->shape_event_base + ShapeNotify)) { XShapeEvent *sev = (XShapeEvent*) event; return sev->window; } #endif return None; } } static guint32 event_get_time (MetaDisplay *display, XEvent *event) { switch (event->type) { case KeyPress: case KeyRelease: return event->xkey.time; case ButtonPress: case ButtonRelease: return event->xbutton.time; case MotionNotify: return event->xmotion.time; case PropertyNotify: return event->xproperty.time; case SelectionClear: case SelectionRequest: case SelectionNotify: return event->xselection.time; case EnterNotify: case LeaveNotify: return event->xcrossing.time; case FocusIn: case FocusOut: case KeymapNotify: case Expose: case GraphicsExpose: case NoExpose: case MapNotify: case UnmapNotify: case VisibilityNotify: case ResizeRequest: case ColormapNotify: case ClientMessage: case CreateNotify: case DestroyNotify: case MapRequest: case ReparentNotify: case ConfigureNotify: case ConfigureRequest: case GravityNotify: case CirculateNotify: case CirculateRequest: case MappingNotify: default: return CurrentTime; } } #ifdef WITH_VERBOSE_MODE const char* meta_event_detail_to_string (int d) { const char *detail = "???"; switch (d) { /* We are an ancestor in the A<->B focus change relationship */ case NotifyAncestor: detail = "NotifyAncestor"; break; case NotifyDetailNone: detail = "NotifyDetailNone"; break; /* We are a descendant in the A<->B focus change relationship */ case NotifyInferior: detail = "NotifyInferior"; break; case NotifyNonlinear: detail = "NotifyNonlinear"; break; case NotifyNonlinearVirtual: detail = "NotifyNonlinearVirtual"; break; case NotifyPointer: detail = "NotifyPointer"; break; case NotifyPointerRoot: detail = "NotifyPointerRoot"; break; case NotifyVirtual: detail = "NotifyVirtual"; break; } return detail; } #endif /* WITH_VERBOSE_MODE */ #ifdef WITH_VERBOSE_MODE const char* meta_event_mode_to_string (int m) { const char *mode = "???"; switch (m) { case NotifyNormal: mode = "NotifyNormal"; break; case NotifyGrab: mode = "NotifyGrab"; break; case NotifyUngrab: mode = "NotifyUngrab"; break; /* not sure any X implementations are missing this, but * it seems to be absent from some docs. */ #ifdef NotifyWhileGrabbed case NotifyWhileGrabbed: mode = "NotifyWhileGrabbed"; break; #endif } return mode; } #endif /* WITH_VERBOSE_MODE */ #ifdef WITH_VERBOSE_MODE static const char* stack_mode_to_string (int mode) { switch (mode) { case Above: return "Above"; case Below: return "Below"; case TopIf: return "TopIf"; case BottomIf: return "BottomIf"; case Opposite: return "Opposite"; } return "Unknown"; } #endif /* WITH_VERBOSE_MODE */ #ifdef WITH_VERBOSE_MODE static char* key_event_description (Display *xdisplay, XEvent *event) { #ifdef HAVE_XKB KeySym keysym; const char *str; keysym = XkbKeycodeToKeysym (xdisplay, event->xkey.keycode, 0, 0); str = XKeysymToString (keysym); return g_strdup_printf ("Key '%s' state 0x%x", str ? str : "none", event->xkey.state); #else return "none"; #endif } #endif /* WITH_VERBOSE_MODE */ #ifdef HAVE_XSYNC #ifdef WITH_VERBOSE_MODE static gint64 sync_value_to_64 (const XSyncValue *value) { gint64 v; v = XSyncValueLow32 (*value); v |= (((gint64)XSyncValueHigh32 (*value)) << 32); return v; } #endif /* WITH_VERBOSE_MODE */ #ifdef WITH_VERBOSE_MODE static const char* alarm_state_to_string (XSyncAlarmState state) { switch (state) { case XSyncAlarmActive: return "Active"; case XSyncAlarmInactive: return "Inactive"; case XSyncAlarmDestroyed: return "Destroyed"; default: return "(unknown)"; } } #endif /* WITH_VERBOSE_MODE */ #endif /* HAVE_XSYNC */ #ifdef WITH_VERBOSE_MODE static void meta_spew_event (MetaDisplay *display, XEvent *event) { const char *name = NULL; char *extra = NULL; char *winname; MetaScreen *screen; if (!meta_is_verbose()) return; /* filter overnumerous events */ if (event->type == Expose || event->type == MotionNotify || event->type == NoExpose) return; switch (event->type) { case KeyPress: name = "KeyPress"; extra = key_event_description (display->xdisplay, event); break; case KeyRelease: name = "KeyRelease"; extra = key_event_description (display->xdisplay, event); break; case ButtonPress: name = "ButtonPress"; extra = g_strdup_printf ("button %u state 0x%x x %d y %d root 0x%lx same_screen %d", event->xbutton.button, event->xbutton.state, event->xbutton.x, event->xbutton.y, event->xbutton.root, event->xbutton.same_screen); break; case ButtonRelease: name = "ButtonRelease"; extra = g_strdup_printf ("button %u state 0x%x x %d y %d root 0x%lx same_screen %d", event->xbutton.button, event->xbutton.state, event->xbutton.x, event->xbutton.y, event->xbutton.root, event->xbutton.same_screen); break; case MotionNotify: name = "MotionNotify"; extra = g_strdup_printf ("win: 0x%lx x: %d y: %d", event->xmotion.window, event->xmotion.x, event->xmotion.y); break; case EnterNotify: name = "EnterNotify"; extra = g_strdup_printf ("win: 0x%lx root: 0x%lx subwindow: 0x%lx mode: %s detail: %s focus: %d x: %d y: %d", event->xcrossing.window, event->xcrossing.root, event->xcrossing.subwindow, meta_event_mode_to_string (event->xcrossing.mode), meta_event_detail_to_string (event->xcrossing.detail), event->xcrossing.focus, event->xcrossing.x, event->xcrossing.y); break; case LeaveNotify: name = "LeaveNotify"; extra = g_strdup_printf ("win: 0x%lx root: 0x%lx subwindow: 0x%lx mode: %s detail: %s focus: %d x: %d y: %d", event->xcrossing.window, event->xcrossing.root, event->xcrossing.subwindow, meta_event_mode_to_string (event->xcrossing.mode), meta_event_detail_to_string (event->xcrossing.detail), event->xcrossing.focus, event->xcrossing.x, event->xcrossing.y); break; case FocusIn: name = "FocusIn"; extra = g_strdup_printf ("detail: %s mode: %s\n", meta_event_detail_to_string (event->xfocus.detail), meta_event_mode_to_string (event->xfocus.mode)); break; case FocusOut: name = "FocusOut"; extra = g_strdup_printf ("detail: %s mode: %s\n", meta_event_detail_to_string (event->xfocus.detail), meta_event_mode_to_string (event->xfocus.mode)); break; case KeymapNotify: name = "KeymapNotify"; break; case Expose: name = "Expose"; break; case GraphicsExpose: name = "GraphicsExpose"; break; case NoExpose: name = "NoExpose"; break; case VisibilityNotify: name = "VisibilityNotify"; break; case CreateNotify: name = "CreateNotify"; extra = g_strdup_printf ("parent: 0x%lx window: 0x%lx", event->xcreatewindow.parent, event->xcreatewindow.window); break; case DestroyNotify: name = "DestroyNotify"; extra = g_strdup_printf ("event: 0x%lx window: 0x%lx", event->xdestroywindow.event, event->xdestroywindow.window); break; case UnmapNotify: name = "UnmapNotify"; extra = g_strdup_printf ("event: 0x%lx window: 0x%lx from_configure: %d", event->xunmap.event, event->xunmap.window, event->xunmap.from_configure); break; case MapNotify: name = "MapNotify"; extra = g_strdup_printf ("event: 0x%lx window: 0x%lx override_redirect: %d", event->xmap.event, event->xmap.window, event->xmap.override_redirect); break; case MapRequest: name = "MapRequest"; extra = g_strdup_printf ("window: 0x%lx parent: 0x%lx\n", event->xmaprequest.window, event->xmaprequest.parent); break; case ReparentNotify: name = "ReparentNotify"; extra = g_strdup_printf ("window: 0x%lx parent: 0x%lx event: 0x%lx\n", event->xreparent.window, event->xreparent.parent, event->xreparent.event); break; case ConfigureNotify: name = "ConfigureNotify"; extra = g_strdup_printf ("x: %d y: %d w: %d h: %d above: 0x%lx override_redirect: %d", event->xconfigure.x, event->xconfigure.y, event->xconfigure.width, event->xconfigure.height, event->xconfigure.above, event->xconfigure.override_redirect); break; case ConfigureRequest: name = "ConfigureRequest"; extra = g_strdup_printf ("parent: 0x%lx window: 0x%lx x: %d %sy: %d %sw: %d %sh: %d %sborder: %d %sabove: %lx %sstackmode: %s %s", event->xconfigurerequest.parent, event->xconfigurerequest.window, event->xconfigurerequest.x, event->xconfigurerequest.value_mask & CWX ? "" : "(unset) ", event->xconfigurerequest.y, event->xconfigurerequest.value_mask & CWY ? "" : "(unset) ", event->xconfigurerequest.width, event->xconfigurerequest.value_mask & CWWidth ? "" : "(unset) ", event->xconfigurerequest.height, event->xconfigurerequest.value_mask & CWHeight ? "" : "(unset) ", event->xconfigurerequest.border_width, event->xconfigurerequest.value_mask & CWBorderWidth ? "" : "(unset)", event->xconfigurerequest.above, event->xconfigurerequest.value_mask & CWSibling ? "" : "(unset)", stack_mode_to_string (event->xconfigurerequest.detail), event->xconfigurerequest.value_mask & CWStackMode ? "" : "(unset)"); break; case GravityNotify: name = "GravityNotify"; break; case ResizeRequest: name = "ResizeRequest"; extra = g_strdup_printf ("width = %d height = %d", event->xresizerequest.width, event->xresizerequest.height); break; case CirculateNotify: name = "CirculateNotify"; break; case CirculateRequest: name = "CirculateRequest"; break; case PropertyNotify: { char *str; const char *state; name = "PropertyNotify"; meta_error_trap_push (display); str = XGetAtomName (display->xdisplay, event->xproperty.atom); meta_error_trap_pop (display, TRUE); if (event->xproperty.state == PropertyNewValue) state = "PropertyNewValue"; else if (event->xproperty.state == PropertyDelete) state = "PropertyDelete"; else state = "???"; extra = g_strdup_printf ("atom: %s state: %s", str ? str : "(unknown atom)", state); meta_XFree (str); } break; case SelectionClear: name = "SelectionClear"; break; case SelectionRequest: name = "SelectionRequest"; break; case SelectionNotify: name = "SelectionNotify"; break; case ColormapNotify: name = "ColormapNotify"; break; case ClientMessage: { char *str; name = "ClientMessage"; meta_error_trap_push (display); str = XGetAtomName (display->xdisplay, event->xclient.message_type); meta_error_trap_pop (display, TRUE); extra = g_strdup_printf ("type: %s format: %d\n", str ? str : "(unknown atom)", event->xclient.format); meta_XFree (str); } break; case MappingNotify: name = "MappingNotify"; break; default: #ifdef HAVE_XSYNC if (META_DISPLAY_HAS_XSYNC (display) && event->type == (display->xsync_event_base + XSyncAlarmNotify)) { XSyncAlarmNotifyEvent *aevent = (XSyncAlarmNotifyEvent*) event; name = "XSyncAlarmNotify"; extra = g_strdup_printf ("alarm: 0x%lx" " counter_value: %" G_GINT64_FORMAT " alarm_value: %" G_GINT64_FORMAT " time: %u alarm state: %s", aevent->alarm, (gint64) sync_value_to_64 (&aevent->counter_value), (gint64) sync_value_to_64 (&aevent->alarm_value), (unsigned int)aevent->time, alarm_state_to_string (aevent->state)); } else #endif /* HAVE_XSYNC */ #ifdef HAVE_SHAPE if (META_DISPLAY_HAS_SHAPE (display) && event->type == (display->shape_event_base + ShapeNotify)) { XShapeEvent *sev = (XShapeEvent*) event; name = "ShapeNotify"; extra = g_strdup_printf ("kind: %s " "x: %d y: %d w: %u h: %u " "shaped: %d", sev->kind == ShapeBounding ? "ShapeBounding" : (sev->kind == ShapeClip ? "ShapeClip" : "(unknown)"), sev->x, sev->y, sev->width, sev->height, sev->shaped); } else #endif /* HAVE_SHAPE */ { name = "(Unknown event)"; extra = g_strdup_printf ("type: %d", event->xany.type); } break; } screen = meta_display_screen_for_root (display, event->xany.window); if (screen) winname = g_strdup_printf ("root %d", screen->number); else winname = g_strdup_printf ("0x%lx", event->xany.window); meta_topic (META_DEBUG_EVENTS, "%s on %s%s %s %sserial %lu\n", name, winname, extra ? ":" : "", extra ? extra : "", event->xany.send_event ? "SEND " : "", event->xany.serial); g_free (winname); if (extra) g_free (extra); } #endif /* WITH_VERBOSE_MODE */ MetaWindow* meta_display_lookup_x_window (MetaDisplay *display, Window xwindow) { return g_hash_table_lookup (display->window_ids, &xwindow); } void meta_display_register_x_window (MetaDisplay *display, Window *xwindowp, MetaWindow *window) { g_return_if_fail (g_hash_table_lookup (display->window_ids, xwindowp) == NULL); g_hash_table_insert (display->window_ids, xwindowp, window); } void meta_display_unregister_x_window (MetaDisplay *display, Window xwindow) { g_return_if_fail (g_hash_table_lookup (display->window_ids, &xwindow) != NULL); g_hash_table_remove (display->window_ids, &xwindow); /* Remove any pending pings */ remove_pending_pings_for_window (display, xwindow); } gboolean meta_display_xwindow_is_a_no_focus_window (MetaDisplay *display, Window xwindow) { gboolean is_a_no_focus_window = FALSE; GSList *temp = display->screens; while (temp != NULL) { MetaScreen *screen = temp->data; if (screen->no_focus_window == xwindow) { is_a_no_focus_window = TRUE; break; } temp = temp->next; } return is_a_no_focus_window; } Cursor meta_display_create_x_cursor (MetaDisplay *display, MetaCursor cursor) { Cursor xcursor; guint glyph; switch (cursor) { case META_CURSOR_DEFAULT: glyph = XC_left_ptr; break; case META_CURSOR_NORTH_RESIZE: glyph = XC_top_side; break; case META_CURSOR_SOUTH_RESIZE: glyph = XC_bottom_side; break; case META_CURSOR_WEST_RESIZE: glyph = XC_left_side; break; case META_CURSOR_EAST_RESIZE: glyph = XC_right_side; break; case META_CURSOR_SE_RESIZE: glyph = XC_bottom_right_corner; break; case META_CURSOR_SW_RESIZE: glyph = XC_bottom_left_corner; break; case META_CURSOR_NE_RESIZE: glyph = XC_top_right_corner; break; case META_CURSOR_NW_RESIZE: glyph = XC_top_left_corner; break; case META_CURSOR_MOVE_OR_RESIZE_WINDOW: glyph = XC_fleur; break; case META_CURSOR_BUSY: glyph = XC_watch; break; default: g_assert_not_reached (); glyph = 0; /* silence compiler */ break; } xcursor = XCreateFontCursor (display->xdisplay, glyph); return xcursor; } static Cursor xcursor_for_op (MetaDisplay *display, MetaGrabOp op) { MetaCursor cursor = META_CURSOR_DEFAULT; switch (op) { case META_GRAB_OP_RESIZING_SE: case META_GRAB_OP_KEYBOARD_RESIZING_SE: cursor = META_CURSOR_SE_RESIZE; break; case META_GRAB_OP_RESIZING_S: case META_GRAB_OP_KEYBOARD_RESIZING_S: cursor = META_CURSOR_SOUTH_RESIZE; break; case META_GRAB_OP_RESIZING_SW: case META_GRAB_OP_KEYBOARD_RESIZING_SW: cursor = META_CURSOR_SW_RESIZE; break; case META_GRAB_OP_RESIZING_N: case META_GRAB_OP_KEYBOARD_RESIZING_N: cursor = META_CURSOR_NORTH_RESIZE; break; case META_GRAB_OP_RESIZING_NE: case META_GRAB_OP_KEYBOARD_RESIZING_NE: cursor = META_CURSOR_NE_RESIZE; break; case META_GRAB_OP_RESIZING_NW: case META_GRAB_OP_KEYBOARD_RESIZING_NW: cursor = META_CURSOR_NW_RESIZE; break; case META_GRAB_OP_RESIZING_W: case META_GRAB_OP_KEYBOARD_RESIZING_W: cursor = META_CURSOR_WEST_RESIZE; break; case META_GRAB_OP_RESIZING_E: case META_GRAB_OP_KEYBOARD_RESIZING_E: cursor = META_CURSOR_EAST_RESIZE; break; case META_GRAB_OP_MOVING: case META_GRAB_OP_KEYBOARD_MOVING: case META_GRAB_OP_KEYBOARD_RESIZING_UNKNOWN: cursor = META_CURSOR_MOVE_OR_RESIZE_WINDOW; break; default: break; } if (cursor == META_CURSOR_DEFAULT) return None; return meta_display_create_x_cursor (display, cursor); } void meta_display_set_grab_op_cursor (MetaDisplay *display, MetaScreen *screen, MetaGrabOp op, gboolean change_pointer, Window grab_xwindow, guint32 timestamp) { Cursor cursor; cursor = xcursor_for_op (display, op); #define GRAB_MASK (PointerMotionMask | \ ButtonPressMask | ButtonReleaseMask | \ EnterWindowMask | LeaveWindowMask) if (change_pointer) { meta_error_trap_push (display); XChangeActivePointerGrab (display->xdisplay, GRAB_MASK, cursor, timestamp); meta_topic (META_DEBUG_WINDOW_OPS, "Changed pointer with XChangeActivePointerGrab()\n"); if (meta_error_trap_pop_with_return (display, FALSE) != Success) { meta_topic (META_DEBUG_WINDOW_OPS, "Error trapped from XChangeActivePointerGrab()\n"); if (display->grab_have_pointer) display->grab_have_pointer = FALSE; } } else { g_assert (screen != NULL); meta_error_trap_push (display); if (XGrabPointer (display->xdisplay, grab_xwindow, False, GRAB_MASK, GrabModeAsync, GrabModeAsync, screen->xroot, cursor, timestamp) == GrabSuccess) { display->grab_have_pointer = TRUE; meta_topic (META_DEBUG_WINDOW_OPS, "XGrabPointer() returned GrabSuccess time %u\n", timestamp); } else { meta_topic (META_DEBUG_WINDOW_OPS, "XGrabPointer() failed time %u\n", timestamp); } meta_error_trap_pop (display, TRUE); } #undef GRAB_MASK if (cursor != None) XFreeCursor (display->xdisplay, cursor); } gboolean meta_display_begin_grab_op (MetaDisplay *display, MetaScreen *screen, MetaWindow *window, MetaGrabOp op, gboolean pointer_already_grabbed, gboolean frame_action, int button, gulong modmask, guint32 timestamp, int root_x, int root_y) { Window grab_xwindow; if (grab_op_is_mouse (op) && meta_grab_op_is_moving (op)) { if (display->compositor) { meta_compositor_begin_move (display->compositor, window, &window->rect, root_x, root_y); } } meta_topic (META_DEBUG_WINDOW_OPS, "Doing grab op %u on window %s button %d pointer already grabbed: %d pointer pos %d,%d\n", op, window ? window->desc : "none", button, pointer_already_grabbed, root_x, root_y); if (display->grab_op != META_GRAB_OP_NONE) { if (window) meta_warning ("Attempt to perform window operation %u on window %s when operation %u on %s already in effect\n", op, window->desc, display->grab_op, display->grab_window ? display->grab_window->desc : "none"); return FALSE; } if (window && (meta_grab_op_is_moving (op) || meta_grab_op_is_resizing (op))) { if (meta_prefs_get_raise_on_click ()) meta_window_raise (window); else { display->grab_initial_x = root_x; display->grab_initial_y = root_y; display->grab_threshold_movement_reached = FALSE; } } /* FIXME: * If we have no MetaWindow we do our best * and try to do the grab on the RootWindow. * This will fail if anyone else has any * key grab on the RootWindow. */ if (window) grab_xwindow = window->frame ? window->frame->xwindow : window->xwindow; else grab_xwindow = screen->xroot; display->grab_have_pointer = FALSE; if (pointer_already_grabbed) display->grab_have_pointer = TRUE; meta_display_set_grab_op_cursor (display, screen, op, FALSE, grab_xwindow, timestamp); if (!display->grab_have_pointer && !grab_op_is_keyboard (op)) { meta_topic (META_DEBUG_WINDOW_OPS, "XGrabPointer() failed\n"); return FALSE; } /* Grab keys for keyboard ops and mouse move/resizes; see #126497 */ if (grab_op_is_keyboard (op) || grab_op_is_mouse_only (op)) { if (window) display->grab_have_keyboard = (meta_window_grab_all_keys (window, timestamp) != FALSE); else display->grab_have_keyboard = (meta_screen_grab_all_keys (screen, timestamp) != FALSE); if (!display->grab_have_keyboard) { meta_topic (META_DEBUG_WINDOW_OPS, "grabbing all keys failed, ungrabbing pointer\n"); XUngrabPointer (display->xdisplay, timestamp); display->grab_have_pointer = FALSE; return FALSE; } } display->tab_popup_mouse_pressed = FALSE; display->grab_op = op; display->grab_window = window; display->grab_screen = screen; display->grab_xwindow = grab_xwindow; display->grab_button = button; display->grab_mask = modmask; if (window) { display->grab_tile_mode = window->tile_mode; display->grab_tile_monitor_number = window->tile_monitor_number; } else { display->grab_tile_mode = META_TILE_NONE; display->grab_tile_monitor_number = -1; } display->grab_anchor_root_x = root_x; display->grab_anchor_root_y = root_y; display->grab_latest_motion_x = root_x; display->grab_latest_motion_y = root_y; display->grab_last_moveresize_time = 0; display->grab_motion_notify_time = 0; display->grab_old_window_stacking = NULL; #ifdef HAVE_XSYNC display->grab_sync_request_alarm = None; display->grab_last_user_action_was_snap = FALSE; #endif display->grab_was_cancelled = FALSE; display->grab_frame_action = (frame_action != FALSE); if (display->grab_resize_timeout_id) { g_source_remove (display->grab_resize_timeout_id); display->grab_resize_timeout_id = 0; } if (display->grab_window) { meta_window_get_client_root_coords (display->grab_window, &display->grab_initial_window_pos); display->grab_anchor_window_pos = display->grab_initial_window_pos; display->grab_wireframe_active = (meta_prefs_get_reduced_resources () && !meta_prefs_get_mate_accessibility ()) && (meta_grab_op_is_resizing (display->grab_op) || meta_grab_op_is_moving (display->grab_op)); if (display->grab_wireframe_active) { meta_window_calc_showing (display->grab_window); meta_window_begin_wireframe (window); } #ifdef HAVE_XSYNC if (!display->grab_wireframe_active && meta_grab_op_is_resizing (display->grab_op) && display->grab_window->sync_request_counter != None) { XSyncAlarmAttributes values; XSyncValue init; meta_error_trap_push (display); /* Set the counter to 0, so we know that the application's * responses to the client messages will always trigger * a PositiveTransition */ XSyncIntToValue (&init, 0); XSyncSetCounter (display->xdisplay, display->grab_window->sync_request_counter, init); display->grab_window->sync_request_serial = 0; display->grab_window->sync_request_time = 0; values.trigger.counter = display->grab_window->sync_request_counter; values.trigger.value_type = XSyncAbsolute; values.trigger.test_type = XSyncPositiveTransition; XSyncIntToValue (&values.trigger.wait_value, display->grab_window->sync_request_serial + 1); /* After triggering, increment test_value by this. * (NOT wait_value above) */ XSyncIntToValue (&values.delta, 1); /* we want events (on by default anyway) */ values.events = True; display->grab_sync_request_alarm = XSyncCreateAlarm (display->xdisplay, XSyncCACounter | XSyncCAValueType | XSyncCAValue | XSyncCATestType | XSyncCADelta | XSyncCAEvents, &values); if (meta_error_trap_pop_with_return (display, FALSE) != Success) display->grab_sync_request_alarm = None; meta_topic (META_DEBUG_RESIZING, "Created update alarm 0x%lx\n", display->grab_sync_request_alarm); } #endif } meta_topic (META_DEBUG_WINDOW_OPS, "Grab op %u on window %s successful\n", display->grab_op, window ? window->desc : "(null)"); g_assert (display->grab_window != NULL || display->grab_screen != NULL); g_assert (display->grab_op != META_GRAB_OP_NONE); /* Save the old stacking */ if (GRAB_OP_IS_WINDOW_SWITCH (display->grab_op)) { meta_topic (META_DEBUG_WINDOW_OPS, "Saving old stack positions; old pointer was %p.\n", display->grab_old_window_stacking); display->grab_old_window_stacking = meta_stack_get_positions (screen->stack); } /* Do this last, after everything is set up. */ switch (op) { case META_GRAB_OP_KEYBOARD_TABBING_NORMAL: meta_screen_ensure_tab_popup (screen, META_TAB_LIST_NORMAL, META_TAB_SHOW_ICON); break; case META_GRAB_OP_KEYBOARD_TABBING_NORMAL_ALL_WORKSPACES: meta_screen_ensure_tab_popup (screen, META_TAB_LIST_NORMAL_ALL_WORKSPACES, META_TAB_SHOW_ICON); break; case META_GRAB_OP_KEYBOARD_ESCAPING_NORMAL: meta_screen_ensure_tab_popup (screen, META_TAB_LIST_NORMAL, META_TAB_SHOW_INSTANTLY); break; case META_GRAB_OP_KEYBOARD_ESCAPING_NORMAL_ALL_WORKSPACES: meta_screen_ensure_tab_popup (screen, META_TAB_LIST_NORMAL_ALL_WORKSPACES, META_TAB_SHOW_INSTANTLY); break; case META_GRAB_OP_KEYBOARD_TABBING_DOCK: meta_screen_ensure_tab_popup (screen, META_TAB_LIST_DOCKS, META_TAB_SHOW_ICON); break; case META_GRAB_OP_KEYBOARD_ESCAPING_DOCK: meta_screen_ensure_tab_popup (screen, META_TAB_LIST_DOCKS, META_TAB_SHOW_INSTANTLY); break; case META_GRAB_OP_KEYBOARD_TABBING_GROUP: meta_screen_ensure_tab_popup (screen, META_TAB_LIST_GROUP, META_TAB_SHOW_ICON); break; case META_GRAB_OP_KEYBOARD_ESCAPING_GROUP: meta_screen_ensure_tab_popup (screen, META_TAB_LIST_GROUP, META_TAB_SHOW_INSTANTLY); break; case META_GRAB_OP_KEYBOARD_WORKSPACE_SWITCHING: case META_GRAB_OP_KEYBOARD_WORKSPACE_MOVING: meta_screen_ensure_workspace_popup (screen); break; default: break; } if (display->grab_window) { meta_window_refresh_resize_popup (display->grab_window); } return TRUE; } void meta_display_end_grab_op (MetaDisplay *display, guint32 timestamp) { meta_topic (META_DEBUG_WINDOW_OPS, "Ending grab op %u at time %u\n", display->grab_op, timestamp); if (display->grab_op == META_GRAB_OP_NONE) return; if (display->grab_window != NULL) display->grab_window->shaken_loose = FALSE; /*if(display->grab_window != NULL && display->grab_window->tile_mode == META_TILE_MAXIMIZED) { display->grab_window->tile_mode = META_TILE_NONE; }*/ if (display->grab_window != NULL && !meta_prefs_get_raise_on_click () && (meta_grab_op_is_moving (display->grab_op) || meta_grab_op_is_resizing (display->grab_op))) { /* Only raise the window in orthogonal raise * ('do-not-raise-on-click') mode if the user didn't try to move * or resize the given window by at least a threshold amount. * For raise on click mode, the window was raised at the * beginning of the grab_op. */ if (!display->grab_threshold_movement_reached) meta_window_raise (display->grab_window); } if (GRAB_OP_IS_WINDOW_SWITCH (display->grab_op) || display->grab_op == META_GRAB_OP_KEYBOARD_WORKSPACE_SWITCHING || display->grab_op == META_GRAB_OP_KEYBOARD_WORKSPACE_MOVING) { meta_ui_tab_popup_free (display->grab_screen->tab_popup); display->grab_screen->tab_popup = NULL; display->tab_popup_mouse_pressed = FALSE; /* If the ungrab here causes an EnterNotify, ignore it for * sloppy focus */ display->ungrab_should_not_cause_focus_window = display->grab_xwindow; } /* If this was a move or resize clear out the edge cache */ if (meta_grab_op_is_resizing (display->grab_op) || meta_grab_op_is_moving (display->grab_op)) { meta_topic (META_DEBUG_WINDOW_OPS, "Clearing out the edges for resistance/snapping"); meta_display_cleanup_edges (display); } if (display->grab_old_window_stacking != NULL) { meta_topic (META_DEBUG_WINDOW_OPS, "Clearing out the old stack position, which was %p.\n", display->grab_old_window_stacking); g_list_free (display->grab_old_window_stacking); display->grab_old_window_stacking = NULL; } if (display->grab_wireframe_active) { display->grab_wireframe_active = FALSE; meta_window_end_wireframe (display->grab_window); if (!display->grab_was_cancelled) { if (meta_grab_op_is_moving (display->grab_op)) meta_window_move (display->grab_window, TRUE, display->grab_wireframe_rect.x, display->grab_wireframe_rect.y); if (meta_grab_op_is_resizing (display->grab_op)) meta_window_resize_with_gravity (display->grab_window, TRUE, display->grab_wireframe_rect.width, display->grab_wireframe_rect.height, meta_resize_gravity_from_grab_op (display->grab_op)); } meta_window_calc_showing (display->grab_window); } if (display->compositor && display->grab_window && grab_op_is_mouse (display->grab_op) && meta_grab_op_is_moving (display->grab_op)) { meta_compositor_end_move (display->compositor, display->grab_window); } if (display->grab_have_pointer) { meta_topic (META_DEBUG_WINDOW_OPS, "Ungrabbing pointer with timestamp %u\n", timestamp); XUngrabPointer (display->xdisplay, timestamp); } if (display->grab_have_keyboard) { meta_topic (META_DEBUG_WINDOW_OPS, "Ungrabbing all keys timestamp %u\n", timestamp); if (display->grab_window) meta_window_ungrab_all_keys (display->grab_window, timestamp); else meta_screen_ungrab_all_keys (display->grab_screen, timestamp); } #ifdef HAVE_XSYNC if (display->grab_sync_request_alarm != None) { XSyncDestroyAlarm (display->xdisplay, display->grab_sync_request_alarm); display->grab_sync_request_alarm = None; } #endif /* HAVE_XSYNC */ /* Hide the tile preview if it exists */ if (display->grab_screen->tile_preview) meta_tile_preview_hide (display->grab_screen->tile_preview); display->grab_window = NULL; display->grab_screen = NULL; display->grab_xwindow = None; display->grab_tile_mode = META_TILE_NONE; display->grab_tile_monitor_number = -1; display->grab_op = META_GRAB_OP_NONE; if (display->grab_resize_popup) { meta_ui_resize_popup_free (display->grab_resize_popup); display->grab_resize_popup = NULL; } if (display->grab_resize_timeout_id) { g_source_remove (display->grab_resize_timeout_id); display->grab_resize_timeout_id = 0; } } void meta_display_check_threshold_reached (MetaDisplay *display, int x, int y) { /* Don't bother doing the check again if we've already reached the threshold */ if (meta_prefs_get_raise_on_click () || display->grab_threshold_movement_reached != FALSE) return; if (ABS (display->grab_initial_x - x) >= 8 || ABS (display->grab_initial_y - y) >= 8) display->grab_threshold_movement_reached = TRUE; } static void meta_change_button_grab (MetaDisplay *display, Window xwindow, gboolean grab, gboolean sync, int button, int modmask) { unsigned int ignored_mask; meta_verbose ("%s 0x%lx sync = %d button = %d modmask 0x%x\n", grab ? "Grabbing" : "Ungrabbing", xwindow, sync, button, modmask); meta_error_trap_push (display); ignored_mask = 0; while (ignored_mask <= display->ignored_modifier_mask) { if (ignored_mask & ~(display->ignored_modifier_mask)) { /* Not a combination of ignored modifiers * (it contains some non-ignored modifiers) */ ++ignored_mask; continue; } if (meta_is_debugging ()) meta_error_trap_push (display); /* GrabModeSync means freeze until XAllowEvents */ if (grab) XGrabButton (display->xdisplay, button, modmask | ignored_mask, xwindow, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask | PointerMotionHintMask, sync ? GrabModeSync : GrabModeAsync, GrabModeAsync, False, None); else XUngrabButton (display->xdisplay, button, modmask | ignored_mask, xwindow); if (meta_is_debugging ()) { int result; result = meta_error_trap_pop_with_return (display, FALSE); if (result != Success) meta_verbose ("Failed to %s button %d with mask 0x%x for window 0x%lx error code %d\n", grab ? "grab" : "ungrab", button, modmask | ignored_mask, xwindow, result); } ++ignored_mask; } meta_error_trap_pop (display, FALSE); } void meta_display_grab_window_buttons (MetaDisplay *display, Window xwindow) { /* Grab Alt + button1 for moving window. * Grab Alt + button2 for resizing window. * Grab Alt + button3 for popping up window menu. * Grab Alt + Shift + button1 for snap-moving window. */ meta_verbose ("Grabbing window buttons for 0x%lx\n", xwindow); /* FIXME If we ignored errors here instead of spewing, we could * put one big error trap around the loop and avoid a bunch of * XSync() */ if (display->window_grab_modifiers != 0) { gboolean debug = g_getenv ("MARCO_DEBUG_BUTTON_GRABS") != NULL; int i; for (i = 1; i < 4; i++) { meta_change_button_grab (display, xwindow, TRUE, FALSE, i, display->window_grab_modifiers); /* This is for debugging, since I end up moving the Xnest * otherwise ;-) */ if (debug) meta_change_button_grab (display, xwindow, TRUE, FALSE, i, ControlMask); } /* In addition to grabbing Alt+Button1 for moving the window, * grab Alt+Shift+Button1 for snap-moving the window. See bug * 112478. Unfortunately, this doesn't work with * Shift+Alt+Button1 for some reason; so at least part of the * order still matters, which sucks (please FIXME). */ meta_change_button_grab (display, xwindow, TRUE, FALSE, 1, display->window_grab_modifiers | ShiftMask); } } void meta_display_ungrab_window_buttons (MetaDisplay *display, Window xwindow) { gboolean debug; int i; if (display->window_grab_modifiers == 0) return; debug = g_getenv ("MARCO_DEBUG_BUTTON_GRABS") != NULL; i = 1; while (i < 4) { meta_change_button_grab (display, xwindow, FALSE, FALSE, i, display->window_grab_modifiers); if (debug) meta_change_button_grab (display, xwindow, FALSE, FALSE, i, ControlMask); ++i; } } /* Grab buttons we only grab while unfocused in click-to-focus mode */ #define MAX_FOCUS_BUTTON 4 void meta_display_grab_focus_window_button (MetaDisplay *display, MetaWindow *window) { /* Grab button 1 for activating unfocused windows */ meta_verbose ("Grabbing unfocused window buttons for %s\n", window->desc); #if 0 /* FIXME:115072 */ /* Don't grab at all unless in click to focus mode. In click to * focus, we may sometimes be clever about intercepting and eating * the focus click. But in mouse focus, we never do that since the * focus window may not be raised, and who wants to think about * mouse focus anyway. */ if (meta_prefs_get_focus_mode () != META_FOCUS_MODE_CLICK) { meta_verbose (" (well, not grabbing since not in click to focus mode)\n"); return; } #endif if (window->have_focus_click_grab) { meta_verbose (" (well, not grabbing since we already have the grab)\n"); return; } /* FIXME If we ignored errors here instead of spewing, we could * put one big error trap around the loop and avoid a bunch of * XSync() */ { int i = 1; while (i < MAX_FOCUS_BUTTON) { meta_change_button_grab (display, window->xwindow, TRUE, TRUE, i, 0); ++i; } window->have_focus_click_grab = TRUE; } } void meta_display_ungrab_focus_window_button (MetaDisplay *display, MetaWindow *window) { meta_verbose ("Ungrabbing unfocused window buttons for %s\n", window->desc); if (!window->have_focus_click_grab) return; { int i = 1; while (i < MAX_FOCUS_BUTTON) { meta_change_button_grab (display, window->xwindow, FALSE, FALSE, i, 0); ++i; } window->have_focus_click_grab = FALSE; } } void meta_display_increment_event_serial (MetaDisplay *display) { /* We just make some random X request */ XDeleteProperty (display->xdisplay, display->leader_window, display->atom__MOTIF_WM_HINTS); } void meta_display_update_active_window_hint (MetaDisplay *display) { GSList *tmp; gulong data[1]; if (display->focus_window) data[0] = display->focus_window->xwindow; else data[0] = None; tmp = display->screens; while (tmp != NULL) { MetaScreen *screen = tmp->data; meta_error_trap_push (display); XChangeProperty (display->xdisplay, screen->xroot, display->atom__NET_ACTIVE_WINDOW, XA_WINDOW, 32, PropModeReplace, (guchar*) data, 1); meta_error_trap_pop (display, FALSE); tmp = tmp->next; } } void meta_display_queue_retheme_all_windows (MetaDisplay *display) { GSList* windows; GSList *tmp; windows = meta_display_list_windows (display); tmp = windows; while (tmp != NULL) { MetaWindow *window = tmp->data; meta_window_queue (window, META_QUEUE_MOVE_RESIZE); if (window->frame) { window->frame->need_reapply_frame_shape = TRUE; meta_frame_queue_draw (window->frame); } tmp = tmp->next; } g_slist_free (windows); } void meta_display_retheme_all (void) { meta_display_queue_retheme_all_windows (meta_get_display ()); } void meta_display_set_cursor_theme (const char *theme, int size) { #ifdef HAVE_XCURSOR GSList *tmp; MetaDisplay *display = meta_get_display (); XcursorSetTheme (display->xdisplay, theme); XcursorSetDefaultSize (display->xdisplay, size); tmp = display->screens; while (tmp != NULL) { MetaScreen *screen = tmp->data; meta_screen_update_cursor (screen); tmp = tmp->next; } #endif } /** * Stores whether syncing is currently enabled. */ static gboolean is_syncing = FALSE; /** * Returns whether X synchronisation is currently enabled. * * \return true if we must wait for events whenever we send X requests; * false otherwise. * * \bug This is *only* called by meta_display_open, but by that time * we have already turned syncing on or off on startup, and we don't * have any way to do so while Marco is running, so it's rather * pointless. */ gboolean meta_is_syncing (void) { return is_syncing; } /** * A handy way to turn on synchronisation on or off for every display. * * \bug Of course there is only one display ever anyway, so this can * be rather hugely simplified. */ void meta_set_syncing (gboolean setting) { if (setting != is_syncing) { is_syncing = setting; if (meta_get_display ()) XSynchronize (meta_get_display ()->xdisplay, is_syncing); } } /** * How long, in milliseconds, we should wait after pinging a window * before deciding it's not going to get back to us. */ #define PING_TIMEOUT_DELAY 5000 /** * Does whatever it is we decided to do when a window didn't respond * to a ping. We also remove the ping from the display's list of * pending pings. This function is called by the event loop when the timeout * times out which we created at the start of the ping. * * \param data All the information about this ping. It is a MetaPingData * cast to a void* in order to be passable to a timeout function. * This function will also free this parameter. * * \return Always returns false, because this function is called as a * timeout and we don't want to run the timer again. * * \ingroup pings */ static gboolean meta_display_ping_timeout (gpointer data) { MetaPingData *ping_data; ping_data = data; ping_data->ping_timeout_id = 0; meta_topic (META_DEBUG_PING, "Ping %u on window %lx timed out\n", ping_data->timestamp, ping_data->xwindow); (* ping_data->ping_timeout_func) (ping_data->display, ping_data->xwindow, ping_data->timestamp, ping_data->user_data); ping_data->display->pending_pings = g_slist_remove (ping_data->display->pending_pings, ping_data); ping_data_free (ping_data); return FALSE; } /** * Sends a ping request to a window. The window must respond to * the request within a certain amount of time. If it does, we * will call one callback; if the time passes and we haven't had * a response, we call a different callback. The window must have * the hint showing that it can respond to a ping; if it doesn't, * we call the "got a response" callback immediately and return. * This function returns straight away after setting things up; * the callbacks will be called from the event loop. * * \param display The MetaDisplay that the window is on * \param window The MetaWindow to send the ping to * \param timestamp The timestamp of the ping. Used for uniqueness. * Cannot be CurrentTime; use a real timestamp! * \param ping_reply_func The callback to call if we get a response. * \param ping_timeout_func The callback to call if we don't get a response. * \param user_data Arbitrary data that will be passed to the callback * function. (In practice it's often a pointer to * the window.) * * \bug This should probably be a method on windows, rather than displays * for one of their windows. * * \ingroup pings */ void meta_display_ping_window (MetaDisplay *display, MetaWindow *window, guint32 timestamp, MetaWindowPingFunc ping_reply_func, MetaWindowPingFunc ping_timeout_func, gpointer user_data) { MetaPingData *ping_data; if (timestamp == CurrentTime) { meta_warning ("Tried to ping a window with CurrentTime! Not allowed.\n"); return; } if (!window->net_wm_ping) { if (ping_reply_func) (* ping_reply_func) (display, window->xwindow, timestamp, user_data); return; } ping_data = g_new (MetaPingData, 1); ping_data->display = display; ping_data->xwindow = window->xwindow; ping_data->timestamp = timestamp; ping_data->ping_reply_func = ping_reply_func; ping_data->ping_timeout_func = ping_timeout_func; ping_data->user_data = user_data; ping_data->ping_timeout_id = g_timeout_add (PING_TIMEOUT_DELAY, meta_display_ping_timeout, ping_data); display->pending_pings = g_slist_prepend (display->pending_pings, ping_data); meta_topic (META_DEBUG_PING, "Sending ping with timestamp %u to window %s\n", timestamp, window->desc); meta_window_send_icccm_message (window, display->atom__NET_WM_PING, timestamp); } static void process_request_frame_extents (MetaDisplay *display, XEvent *event) { /* The X window whose frame extents will be set. */ Window xwindow = event->xclient.window; unsigned long data[4] = { 0, 0, 0, 0 }; MotifWmHints *hints = NULL; gboolean hints_set = FALSE; meta_verbose ("Setting frame extents for 0x%lx\n", xwindow); /* See if the window is decorated. */ hints_set = meta_prop_get_motif_hints (display, xwindow, display->atom__MOTIF_WM_HINTS, &hints); if ((hints_set && hints->decorations) || !hints_set) { MetaFrameBorders borders; MetaScreen *screen; screen = meta_display_screen_for_xwindow (display, event->xclient.window); if (screen == NULL) { meta_warning ("Received request to set _NET_FRAME_EXTENTS " "on 0x%lx which is on a screen we are not managing\n", event->xclient.window); meta_XFree (hints); return; } /* Return estimated frame extents for a normal window. */ meta_ui_theme_get_frame_borders (screen->ui, META_FRAME_TYPE_NORMAL, 0, &borders); data[0] = borders.visible.left; data[1] = borders.visible.right; data[2] = borders.visible.top; data[3] = borders.visible.bottom; } meta_topic (META_DEBUG_GEOMETRY, "Setting _NET_FRAME_EXTENTS on unmanaged window 0x%lx " "to top = %lu, left = %lu, bottom = %lu, right = %lu\n", xwindow, data[0], data[1], data[2], data[3]); meta_error_trap_push (display); XChangeProperty (display->xdisplay, xwindow, display->atom__NET_FRAME_EXTENTS, XA_CARDINAL, 32, PropModeReplace, (guchar*) data, 4); meta_error_trap_pop (display, FALSE); meta_XFree (hints); } /** * Process the pong (the response message) from the ping we sent * to the window. This involves removing the timeout, calling the * reply handler function, and freeing memory. * * \param display the display we got the pong from * \param event the XEvent which is a pong; we can tell which * ping it corresponds to because it bears the * same timestamp. * * \ingroup pings */ static void process_pong_message (MetaDisplay *display, XEvent *event) { GSList *tmp; guint32 timestamp = event->xclient.data.l[1]; meta_topic (META_DEBUG_PING, "Received a pong with timestamp %u\n", timestamp); for (tmp = display->pending_pings; tmp; tmp = tmp->next) { MetaPingData *ping_data = tmp->data; if (timestamp == ping_data->timestamp) { meta_topic (META_DEBUG_PING, "Matching ping found for pong %u\n", ping_data->timestamp); /* Remove the ping data from the list */ display->pending_pings = g_slist_remove (display->pending_pings, ping_data); /* Remove the timeout */ if (ping_data->ping_timeout_id != 0) { g_source_remove (ping_data->ping_timeout_id); ping_data->ping_timeout_id = 0; } /* Call callback */ (* ping_data->ping_reply_func) (display, ping_data->xwindow, ping_data->timestamp, ping_data->user_data); ping_data_free (ping_data); break; } } } /** * Finds whether a window has any pings waiting on it. * * \param display The MetaDisplay of the window. * \param window The MetaWindow whose pings we want to know about. * * \return True if there is at least one ping which has been sent * to the window without getting a response; false otherwise. * * \bug This should probably be a method on windows, rather than displays * for one of their windows. * * \ingroup pings */ gboolean meta_display_window_has_pending_pings (MetaDisplay *display, MetaWindow *window) { GSList *tmp; for (tmp = display->pending_pings; tmp; tmp = tmp->next) { MetaPingData *ping_data = tmp->data; if (ping_data->xwindow == window->xwindow) return TRUE; } return FALSE; } MetaGroup* get_focussed_group (MetaDisplay *display) { if (display->focus_window) return display->focus_window->group; else return NULL; } #define IN_TAB_CHAIN(w,t) \ (((t) == META_TAB_LIST_NORMAL && META_WINDOW_IN_NORMAL_TAB_CHAIN (w)) \ || ((t) == META_TAB_LIST_NORMAL_ALL_WORKSPACES && META_WINDOW_IN_NORMAL_TAB_CHAIN (w)) \ || ((t) == META_TAB_LIST_DOCKS && META_WINDOW_IN_DOCK_TAB_CHAIN (w)) \ || ((t) == META_TAB_LIST_GROUP && META_WINDOW_IN_GROUP_TAB_CHAIN (w, get_focussed_group(w->display)))) static MetaWindow* find_tab_forward (MetaDisplay *display, MetaTabList type, MetaScreen *screen, MetaWorkspace *workspace, GList *start, gboolean skip_first) { GList *tmp; g_return_val_if_fail (start != NULL, NULL); g_return_val_if_fail (workspace != NULL, NULL); tmp = start; if (skip_first) tmp = tmp->next; while (tmp != NULL) { MetaWindow *window = tmp->data; if (window->screen == screen && IN_TAB_CHAIN (window, type)) return window; tmp = tmp->next; } tmp = workspace->mru_list; while (tmp != start && tmp != NULL) { MetaWindow *window = tmp->data; if (IN_TAB_CHAIN (window, type)) return window; tmp = tmp->next; } return NULL; } static MetaWindow* find_tab_backward (MetaDisplay *display, MetaTabList type, MetaScreen *screen, MetaWorkspace *workspace, GList *start, gboolean skip_last) { GList *tmp; g_return_val_if_fail (start != NULL, NULL); g_return_val_if_fail (workspace != NULL, NULL); tmp = start; if (skip_last) tmp = tmp->prev; while (tmp != NULL) { MetaWindow *window = tmp->data; if (window->screen == screen && IN_TAB_CHAIN (window, type)) return window; tmp = tmp->prev; } tmp = g_list_last (workspace->mru_list); while (tmp != start) { MetaWindow *window = tmp->data; if (IN_TAB_CHAIN (window, type)) return window; tmp = tmp->prev; } return NULL; } GList* meta_display_get_tab_list (MetaDisplay *display, MetaTabList type, MetaScreen *screen, MetaWorkspace *active_workspace) { GList *tab_list, *workspace_list, *l, link; MetaWorkspace *workspace; g_return_val_if_fail (active_workspace != NULL, NULL); if (type == META_TAB_LIST_NORMAL_ALL_WORKSPACES) { workspace_list = screen->workspaces; type = META_TAB_LIST_NORMAL; } else { link.next = NULL; link.prev = NULL; link.data = active_workspace; workspace_list = &link; } tab_list = NULL; /* Windows sellout mode - MRU order. Collect unminimized windows * then minimized so minimized windows aren't in the way so much. */ for (l = workspace_list; l != NULL; l = l->next) { GList *tmp; workspace = l->data; tmp = workspace->mru_list; while (tmp != NULL) { MetaWindow *window = tmp->data; if (!window->minimized && window->screen == screen && IN_TAB_CHAIN (window, type)) tab_list = g_list_prepend (tab_list, window); tmp = tmp->next; } } for (l = workspace_list; l != NULL; l = l->next) { GList *tmp; workspace = l->data; tmp = workspace->mru_list; while (tmp != NULL) { MetaWindow *window = tmp->data; if (window->minimized && window->screen == screen && IN_TAB_CHAIN (window, type)) tab_list = g_list_prepend (tab_list, window); tmp = tmp->next; } } tab_list = g_list_reverse (tab_list); { GSList *windows, *tmp; MetaWindow *l_window; windows = meta_display_list_windows (display); tmp = windows; /* Go through all windows */ while (tmp != NULL) { l_window=tmp->data; /* Check to see if it demands attention */ if (l_window->wm_state_demands_attention && l_window->workspace!=active_workspace && IN_TAB_CHAIN (l_window, type)) { /* if it does, add it to the popup */ tab_list = g_list_prepend (tab_list, l_window); } tmp = tmp->next; } /* End while tmp!=NULL */ g_slist_free (windows); } return tab_list; } MetaWindow* meta_display_get_tab_next (MetaDisplay *display, MetaTabList type, MetaScreen *screen, MetaWorkspace *workspace, MetaWindow *window, gboolean backward) { gboolean skip; GList *tab_list; MetaWindow *ret; tab_list = meta_display_get_tab_list(display, type, screen, workspace); if (tab_list == NULL) return NULL; if (window != NULL) { g_assert (window->display == display); if (backward) ret = find_tab_backward (display, type, screen, workspace, g_list_find (tab_list, window), TRUE); else ret = find_tab_forward (display, type, screen, workspace, g_list_find (tab_list, window), TRUE); } else { skip = display->focus_window != NULL && tab_list->data == display->focus_window; if (backward) ret = find_tab_backward (display, type, screen, workspace, tab_list, skip); else ret = find_tab_forward (display, type, screen, workspace, tab_list, skip); } g_list_free (tab_list); return ret; } MetaWindow* meta_display_get_tab_current (MetaDisplay *display, MetaTabList type, MetaScreen *screen, MetaWorkspace *workspace) { MetaWindow *window; window = display->focus_window; if (window != NULL && window->screen == screen && IN_TAB_CHAIN (window, type) && (workspace == NULL || meta_window_located_on_workspace (window, workspace))) return window; else return NULL; } int meta_resize_gravity_from_grab_op (MetaGrabOp op) { int gravity; gravity = -1; switch (op) { case META_GRAB_OP_RESIZING_SE: case META_GRAB_OP_KEYBOARD_RESIZING_SE: gravity = NorthWestGravity; break; case META_GRAB_OP_KEYBOARD_RESIZING_S: case META_GRAB_OP_RESIZING_S: gravity = NorthGravity; break; case META_GRAB_OP_KEYBOARD_RESIZING_SW: case META_GRAB_OP_RESIZING_SW: gravity = NorthEastGravity; break; case META_GRAB_OP_KEYBOARD_RESIZING_N: case META_GRAB_OP_RESIZING_N: gravity = SouthGravity; break; case META_GRAB_OP_KEYBOARD_RESIZING_NE: case META_GRAB_OP_RESIZING_NE: gravity = SouthWestGravity; break; case META_GRAB_OP_KEYBOARD_RESIZING_NW: case META_GRAB_OP_RESIZING_NW: gravity = SouthEastGravity; break; case META_GRAB_OP_KEYBOARD_RESIZING_E: case META_GRAB_OP_RESIZING_E: gravity = WestGravity; break; case META_GRAB_OP_KEYBOARD_RESIZING_W: case META_GRAB_OP_RESIZING_W: gravity = EastGravity; break; case META_GRAB_OP_KEYBOARD_RESIZING_UNKNOWN: gravity = CenterGravity; break; default: break; } return gravity; } static MetaScreen* find_screen_for_selection (MetaDisplay *display, Window owner, Atom selection) { GSList *tmp; tmp = display->screens; while (tmp != NULL) { MetaScreen *screen = tmp->data; if (screen->wm_sn_selection_window == owner && screen->wm_sn_atom == selection) return screen; tmp = tmp->next; } return NULL; } /* from fvwm2, Copyright Matthias Clasen, Dominik Vogt */ static gboolean convert_property (MetaDisplay *display, MetaScreen *screen, Window w, Atom target, Atom property) { #define N_TARGETS 4 Atom conversion_targets[N_TARGETS]; long icccm_version[] = { 2, 0 }; conversion_targets[0] = display->atom_TARGETS; conversion_targets[1] = display->atom_MULTIPLE; conversion_targets[2] = display->atom_TIMESTAMP; conversion_targets[3] = display->atom_VERSION; meta_error_trap_push (display); if (target == display->atom_TARGETS) XChangeProperty (display->xdisplay, w, property, XA_ATOM, 32, PropModeReplace, (unsigned char *)conversion_targets, N_TARGETS); else if (target == display->atom_TIMESTAMP) XChangeProperty (display->xdisplay, w, property, XA_INTEGER, 32, PropModeReplace, (unsigned char *)&screen->wm_sn_timestamp, 1); else if (target == display->atom_VERSION) XChangeProperty (display->xdisplay, w, property, XA_INTEGER, 32, PropModeReplace, (unsigned char *)icccm_version, 2); else { meta_error_trap_pop_with_return (display, FALSE); return FALSE; } if (meta_error_trap_pop_with_return (display, FALSE) != Success) return FALSE; /* Be sure the PropertyNotify has arrived so we * can send SelectionNotify */ /* FIXME the error trap pop synced anyway, right? */ meta_topic (META_DEBUG_SYNC, "Syncing on %s\n", G_STRFUNC); XSync (display->xdisplay, False); return TRUE; } /* from fvwm2, Copyright Matthias Clasen, Dominik Vogt */ static void process_selection_request (MetaDisplay *display, XEvent *event) { XSelectionEvent reply; MetaScreen *screen; screen = find_screen_for_selection (display, event->xselectionrequest.owner, event->xselectionrequest.selection); if (screen == NULL) { char *str; meta_error_trap_push (display); str = XGetAtomName (display->xdisplay, event->xselectionrequest.selection); meta_error_trap_pop (display, TRUE); meta_verbose ("Selection request with selection %s window 0x%lx not a WM_Sn selection we recognize\n", str ? str : "(bad atom)", event->xselectionrequest.owner); meta_XFree (str); return; } reply.type = SelectionNotify; reply.display = display->xdisplay; reply.requestor = event->xselectionrequest.requestor; reply.selection = event->xselectionrequest.selection; reply.target = event->xselectionrequest.target; reply.property = None; reply.time = event->xselectionrequest.time; if (event->xselectionrequest.target == display->atom_MULTIPLE) { if (event->xselectionrequest.property != None) { Atom type, *adata; int i, format; unsigned long num, rest; unsigned char *data; meta_error_trap_push (display); if (XGetWindowProperty (display->xdisplay, event->xselectionrequest.requestor, event->xselectionrequest.property, 0, 256, False, display->atom_ATOM_PAIR, &type, &format, &num, &rest, &data) != Success) { meta_error_trap_pop_with_return (display, TRUE); return; } if (meta_error_trap_pop_with_return (display, TRUE) == Success) { /* FIXME: to be 100% correct, should deal with rest > 0, * but since we have 4 possible targets, we will hardly ever * meet multiple requests with a length > 8 */ adata = (Atom*)data; i = 0; while (i < (int) num) { if (!convert_property (display, screen, event->xselectionrequest.requestor, adata[i], adata[i+1])) adata[i+1] = None; i += 2; } meta_error_trap_push (display); XChangeProperty (display->xdisplay, event->xselectionrequest.requestor, event->xselectionrequest.property, display->atom_ATOM_PAIR, 32, PropModeReplace, data, num); meta_error_trap_pop (display, FALSE); meta_XFree (data); } } } else { if (event->xselectionrequest.property == None) event->xselectionrequest.property = event->xselectionrequest.target; if (convert_property (display, screen, event->xselectionrequest.requestor, event->xselectionrequest.target, event->xselectionrequest.property)) reply.property = event->xselectionrequest.property; } XSendEvent (display->xdisplay, event->xselectionrequest.requestor, False, 0L, (XEvent*)&reply); meta_verbose ("Handled selection request\n"); } static void process_selection_clear (MetaDisplay *display, XEvent *event) { /* We need to unmanage the screen on which we lost the selection */ MetaScreen *screen; screen = find_screen_for_selection (display, event->xselectionclear.window, event->xselectionclear.selection); if (screen != NULL) { meta_verbose ("Got selection clear for screen %d on display %s\n", screen->number, display->name); meta_display_unmanage_screen (display, screen, event->xselectionclear.time); /* display and screen may both be invalid memory... */ return; } { char *str; meta_error_trap_push (display); str = XGetAtomName (display->xdisplay, event->xselectionclear.selection); meta_error_trap_pop (display, TRUE); meta_verbose ("Selection clear with selection %s window 0x%lx not a WM_Sn selection we recognize\n", str ? str : "(bad atom)", event->xselectionclear.window); meta_XFree (str); } } void meta_display_unmanage_screen (MetaDisplay *display, MetaScreen *screen, guint32 timestamp) { meta_verbose ("Unmanaging screen %d on display %s\n", screen->number, display->name); g_return_if_fail (g_slist_find (display->screens, screen) != NULL); meta_screen_free (screen, timestamp); display->screens = g_slist_remove (display->screens, screen); if (display->screens == NULL) meta_display_close (display, timestamp); } void meta_display_unmanage_windows_for_screen (MetaDisplay *display, MetaScreen *screen, guint32 timestamp) { GSList *tmp; GSList *winlist; winlist = meta_display_list_windows (display); winlist = g_slist_sort (winlist, meta_display_stack_cmp); /* Unmanage all windows */ tmp = winlist; while (tmp != NULL) { meta_window_free (tmp->data, timestamp); tmp = tmp->next; } g_slist_free (winlist); } int meta_display_stack_cmp (const void *a, const void *b) { MetaWindow *aw = (void*) a; MetaWindow *bw = (void*) b; if (aw->screen == bw->screen) return meta_stack_windows_cmp (aw->screen->stack, aw, bw); /* Then assume screens are stacked by number */ else if (aw->screen->number < bw->screen->number) return -1; else if (aw->screen->number > bw->screen->number) return 1; else return 0; /* not reached in theory, if windows on same display */ } void meta_display_devirtualize_modifiers (MetaDisplay *display, MetaVirtualModifier modifiers, unsigned int *mask) { *mask = 0; if (modifiers & META_VIRTUAL_SHIFT_MASK) *mask |= ShiftMask; if (modifiers & META_VIRTUAL_CONTROL_MASK) *mask |= ControlMask; if (modifiers & META_VIRTUAL_ALT_MASK) *mask |= Mod1Mask; if (modifiers & META_VIRTUAL_META_MASK) *mask |= display->meta_mask; if (modifiers & META_VIRTUAL_HYPER_MASK) *mask |= display->hyper_mask; if (modifiers & META_VIRTUAL_SUPER_MASK) *mask |= display->super_mask; if (modifiers & META_VIRTUAL_MOD2_MASK) *mask |= Mod2Mask; if (modifiers & META_VIRTUAL_MOD3_MASK) *mask |= Mod3Mask; if (modifiers & META_VIRTUAL_MOD4_MASK) *mask |= Mod4Mask; if (modifiers & META_VIRTUAL_MOD5_MASK) *mask |= Mod5Mask; } static void update_window_grab_modifiers (MetaDisplay *display) { MetaVirtualModifier virtual_mods; unsigned int mods; virtual_mods = meta_prefs_get_mouse_button_mods (); meta_display_devirtualize_modifiers (display, virtual_mods, &mods); display->window_grab_modifiers = mods; } static void prefs_changed_callback (MetaPreference pref, void *data) { MetaDisplay *display = data; /* It may not be obvious why we regrab on focus mode * change; it's because we handle focus clicks a * bit differently for the different focus modes. */ if (pref == META_PREF_MOUSE_BUTTON_MODS || pref == META_PREF_FOCUS_MODE) { GSList *windows; GSList *tmp; windows = meta_display_list_windows (display); /* Ungrab all */ tmp = windows; while (tmp != NULL) { MetaWindow *w = tmp->data; meta_display_ungrab_window_buttons (display, w->xwindow); meta_display_ungrab_focus_window_button (display, w); tmp = tmp->next; } /* change our modifier */ if (pref == META_PREF_MOUSE_BUTTON_MODS) update_window_grab_modifiers (display); /* Grab all */ tmp = windows; while (tmp != NULL) { MetaWindow *w = tmp->data; if (w->type != META_WINDOW_DOCK) { meta_display_grab_focus_window_button (display, w); meta_display_grab_window_buttons (display, w->xwindow); } tmp = tmp->next; } g_slist_free (windows); } else if (pref == META_PREF_AUDIBLE_BELL) { meta_bell_set_audible (display, meta_prefs_bell_is_audible ()); } else if (pref == META_PREF_COMPOSITING_MANAGER) { gboolean cm = meta_prefs_get_compositing_manager (); if (cm) enable_compositor (display, TRUE); else disable_compositor (display); } else if (pref == META_PREF_ATTACH_MODAL_DIALOGS) { GSList *windows; GSList *tmp; windows = meta_display_list_windows (display); for (tmp = windows; tmp != NULL; tmp = tmp->next) { MetaWindow *w = tmp->data; MetaWindow *parent = meta_window_get_transient_for (w); meta_window_recalc_features (w); if (w->type == META_WINDOW_MODAL_DIALOG && parent && parent != w) { int x, y; /* Forcing a call to move_resize() does two things: first, it handles * resizing the dialog frame window to the correct size when we remove * or add the decorations. Second, it will take care of positioning the * dialog as "attached" to the parent when we turn the preference on * via the constrain_modal_dialog() constraint. **/ meta_window_get_position (w, &x, &y); meta_window_move (w, FALSE, x, y); } } } } void meta_display_increment_focus_sentinel (MetaDisplay *display) { unsigned long data[1]; data[0] = meta_display_get_current_time (display); XChangeProperty (display->xdisplay, ((MetaScreen*) display->screens->data)->xroot, display->atom__MARCO_SENTINEL, XA_CARDINAL, 32, PropModeReplace, (guchar*) data, 1); display->sentinel_counter += 1; } void meta_display_decrement_focus_sentinel (MetaDisplay *display) { display->sentinel_counter -= 1; if (display->sentinel_counter < 0) display->sentinel_counter = 0; } gboolean meta_display_focus_sentinel_clear (MetaDisplay *display) { return (display->sentinel_counter == 0); } static void sanity_check_timestamps (MetaDisplay *display, guint32 timestamp) { if (XSERVER_TIME_IS_BEFORE (timestamp, display->last_focus_time)) { meta_warning ("last_focus_time (%u) is greater than comparison " "timestamp (%u). This most likely represents a buggy " "client sending inaccurate timestamps in messages such as " "_NET_ACTIVE_WINDOW. Trying to work around...\n", display->last_focus_time, timestamp); display->last_focus_time = timestamp; } if (XSERVER_TIME_IS_BEFORE (timestamp, display->last_user_time)) { GSList *windows; GSList *tmp; meta_warning ("last_user_time (%u) is greater than comparison " "timestamp (%u). This most likely represents a buggy " "client sending inaccurate timestamps in messages such as " "_NET_ACTIVE_WINDOW. Trying to work around...\n", display->last_user_time, timestamp); display->last_user_time = timestamp; windows = meta_display_list_windows (display); tmp = windows; while (tmp != NULL) { MetaWindow *window = tmp->data; if (XSERVER_TIME_IS_BEFORE (timestamp, window->net_wm_user_time)) { meta_warning ("%s appears to be one of the offending windows " "with a timestamp of %u. Working around...\n", window->desc, window->net_wm_user_time); window->net_wm_user_time = timestamp; } tmp = tmp->next; } g_slist_free (windows); } } static gboolean timestamp_too_old (MetaDisplay *display, MetaWindow *window, guint32 *timestamp) { /* FIXME: If Soeren's suggestion in bug 151984 is implemented, it will allow * us to sanity check the timestamp here and ensure it doesn't correspond to * a future time (though we would want to rename to * timestamp_too_old_or_in_future). */ if (*timestamp == CurrentTime) { meta_warning ("Got a request to focus %s with a timestamp of 0. This " "shouldn't happen!\n", window ? window->desc : "the no_focus_window"); meta_print_backtrace (); *timestamp = meta_display_get_current_time_roundtrip (display); return FALSE; } else if (XSERVER_TIME_IS_BEFORE (*timestamp, display->last_focus_time)) { if (XSERVER_TIME_IS_BEFORE (*timestamp, display->last_user_time)) { meta_topic (META_DEBUG_FOCUS, "Ignoring focus request for %s since %u " "is less than %u and %u.\n", window ? window->desc : "the no_focus_window", *timestamp, display->last_user_time, display->last_focus_time); return TRUE; } else { meta_topic (META_DEBUG_FOCUS, "Received focus request for %s which is newer than most " "recent user_time, but less recent than " "last_focus_time (%u < %u < %u); adjusting " "accordingly. (See bug 167358)\n", window ? window->desc : "the no_focus_window", display->last_user_time, *timestamp, display->last_focus_time); *timestamp = display->last_focus_time; return FALSE; } } return FALSE; } void meta_display_set_input_focus_window (MetaDisplay *display, MetaWindow *window, gboolean focus_frame, guint32 timestamp) { if (timestamp_too_old (display, window, &timestamp)) return; meta_error_trap_push (display); XSetInputFocus (display->xdisplay, focus_frame ? window->frame->xwindow : window->xwindow, RevertToPointerRoot, timestamp); meta_error_trap_pop (display, FALSE); display->expected_focus_window = window; display->last_focus_time = timestamp; display->active_screen = window->screen; if (window != display->autoraise_window) meta_display_remove_autoraise_callback (window->display); } void meta_display_focus_the_no_focus_window (MetaDisplay *display, MetaScreen *screen, guint32 timestamp) { if (timestamp_too_old (display, NULL, &timestamp)) return; XSetInputFocus (display->xdisplay, screen->no_focus_window, RevertToPointerRoot, timestamp); display->expected_focus_window = NULL; display->last_focus_time = timestamp; display->active_screen = screen; meta_display_remove_autoraise_callback (display); } void meta_display_remove_autoraise_callback (MetaDisplay *display) { if (display->autoraise_timeout_id != 0) { g_source_remove (display->autoraise_timeout_id); display->autoraise_timeout_id = 0; display->autoraise_window = NULL; } } Display * meta_display_get_xdisplay (MetaDisplay *display) { return display->xdisplay; } MetaCompositor * meta_display_get_compositor (MetaDisplay *display) { return display->compositor; } GSList * meta_display_get_screens (MetaDisplay *display) { return display->screens; } gboolean meta_display_has_shape (MetaDisplay *display) { return META_DISPLAY_HAS_SHAPE (display); } MetaWindow * meta_display_get_focus_window (MetaDisplay *display) { return display->focus_window; } #ifdef HAVE_COMPOSITE_EXTENSIONS int meta_display_get_damage_event_base (MetaDisplay *display) { return display->damage_event_base; } #endif #ifdef HAVE_COMPOSITE_EXTENSIONS #ifdef HAVE_SHAPE int meta_display_get_shape_event_base (MetaDisplay *display) { return display->shape_event_base; } #endif #endif
mate-desktop/marco
src/core/display.c
C
gpl-2.0
172,523
<?php $this->currencies = array ( 'adp' => 'Andorransk peseta', 'aed' => 'Förenade arabemiratens dirham', 'afa' => 'Afghani (1927-2002)', 'afn' => 'Afghani', 'all' => 'Albansk lek', 'amd' => 'Armenisk dram', 'ang' => 'Nederländsk antillisk gulden', 'aoa' => 'Angolansk kwanza', 'aok' => 'Angolansk kwanza (1977-1990)', 'aon' => 'Angolansk ny kwanza (1990-2000)', 'aor' => 'Angolansk kwanza – Reajustado (1995-1999)', 'ara' => 'Argentinsk austral', 'arp' => 'Argentinsk peso (1983-1985)', 'ars' => 'Argentinsk peso', 'ats' => 'Österrikisk schilling', 'aud' => 'Australisk dollar', 'awg' => 'Aruba-florin', 'azm' => 'Azerbajdzjansk manat', 'bad' => 'Bosnisk-hercegovinsk dinar', 'bam' => 'Konvertibel bosnisk-hercegovinsk mark', 'bbd' => 'Barbadisk dollar', 'bdt' => 'Bangladeshisk taka', 'bec' => 'Belgisk franc (konvertibel)', 'bef' => 'Belgisk franc', 'bel' => 'Belgisk franc (finansiell)', 'bgl' => 'Bulgarisk hård lev', 'bgn' => 'Bulgarisk ny lev', 'bhd' => 'Bahrainsk dinar', 'bif' => 'Burundisk franc', 'bmd' => 'Bermuda-dollar', 'bnd' => 'Bruneisk dollar', 'bob' => 'Boliviano', 'bop' => 'Boliviansk peso', 'bov' => 'Boliviansk mvdol', 'brb' => 'Brasiliansk cruzeiro novo (1967-1986)', 'brc' => 'Brasiliansk cruzado', 'bre' => 'Brasiliansk cruzeiro (1990-1993)', 'brl' => 'Brasiliansk real', 'brn' => 'Brasiliansk cruzado novo', 'brr' => 'Brasiliansk cruzeiro', 'bsd' => 'Bahamansk dollar', 'btn' => 'Bhutanesisk ngultrum', 'buk' => 'Burmesisk kyat', 'bwp' => 'Botswansk pula', 'byb' => 'Vitrysk ny rubel (1994-1999)', 'byr' => 'Vitrysk rubel', 'bzd' => 'Belizisk dollar', 'cad' => 'Kanadensisk dollar', 'cdf' => 'Kongolesisk franc congolais', 'che' => 'WIR Euro', 'chf' => 'Schweizisk franc', 'chw' => 'WIR Franc', 'clf' => 'Chilensk unidad de fomento', 'clp' => 'Chilensk peso', 'cny' => 'Kinesisk yuan renminbi', 'cop' => 'Colombiansk peso', 'cou' => 'Unidad de Valor Real', 'crc' => 'Costarikansk colón', 'csd' => 'Serbian Dinar', 'csk' => 'Tjeckisk hård koruna', 'cup' => 'Kubansk peso', 'cve' => 'Kapverdisk escudo', 'cyp' => 'Cypriotiskt pund', 'czk' => 'Tjeckisk koruna', 'ddm' => 'Östtysk mark', 'dem' => 'Tysk mark', 'djf' => 'Djiboutisk franc', 'dkk' => 'Dansk krona', 'dop' => 'Dominikansk peso', 'dzd' => 'Algerisk dinar', 'ecs' => 'Ecuadoriansk sucre', 'ecv' => 'Ecuadoriansk Unidad de Valor Constante (UVC)', 'eek' => 'Estnisk krona', 'egp' => 'Egyptiskt pund', 'eqe' => 'Ekwele', 'ern' => 'Eritreansk nakfa', 'esa' => 'Spanish Peseta (A account)', 'esb' => 'Spanish Peseta (convertible account)', 'esp' => 'Spansk peseta', 'etb' => 'Etiopisk birr', 'eur' => 'Euro', 'fim' => 'Finsk mark', 'fjd' => 'Fijiansk dollar', 'fkp' => 'Falklandsöarnas pund', 'frf' => 'Fransk franc', 'gbp' => 'Brittiskt pund sterling', 'gek' => 'Georgisk kupon larit', 'gel' => 'Georgisk lari', 'ghc' => 'Ghanansk cedi', 'gip' => 'Gibraltiskt pund', 'gmd' => 'Gambisk dalasi', 'gnf' => 'Guineansk franc', 'gns' => 'Guineansk syli', 'gqe' => 'Ekvatorialguineansk ekwele guineana', 'grd' => 'Grekisk drachma', 'gtq' => 'Guatemalansk quetzal', 'gwe' => 'Portugisiska Guinea-escudo', 'gwp' => 'Guinea-Bissau-peso', 'gyd' => 'Guyanansk dollar', 'hkd' => 'Hongkong-dollar', 'hnl' => 'Hoduransk lempira', 'hrd' => 'Kroatisk dinar', 'hrk' => 'Kroatisk kuna', 'htg' => 'Haitisk gourde', 'huf' => 'Ungersk forint', 'idr' => 'Indonesisk rupiah', 'iep' => 'Irländskt pund', 'ilp' => 'Israeliskt pund', 'ils' => 'Israelisk ny shekel', 'inr' => 'Indisk rupie', 'iqd' => 'Irakisk dinar', 'irr' => 'Iransk rial', 'isk' => 'Isländsk krona', 'itl' => 'Italiensk lira', 'jmd' => 'Jamaicansk dollar', 'jod' => 'Jordansk dinar', 'jpy' => 'Japansk yen', 'kes' => 'Kenyansk shilling', 'kgs' => 'Kirgizistansk som', 'khr' => 'Kambodjansk riel', 'kmf' => 'Komorisk franc', 'kpw' => 'Nordkoreansk won', 'krw' => 'Sydkoreansk won', 'kwd' => 'Kuwaitisk dinar', 'kyd' => 'Cayman-dollar', 'kzt' => 'Kazakisk tenge', 'lak' => 'Laotisk kip', 'lbp' => 'Libanesiskt pund', 'lkr' => 'Srilankesisk rupie', 'lrd' => 'Liberisk dollar', 'lsl' => 'Lesothisk loti', 'lsm' => 'Maloti', 'ltl' => 'Lettisk lita', 'ltt' => 'Lettisk talonas', 'luc' => 'Luxembourg Convertible Franc', 'luf' => 'Luxemburgsk franc', 'lul' => 'Luxembourg Financial Franc', 'lvl' => 'Lettisk lats', 'lvr' => 'Lettisk rubel', 'lyd' => 'Libysk dinar', 'mad' => 'Marockansk dirham', 'maf' => 'Marockansk franc', 'mdl' => 'Moldavisk leu', 'mga' => 'Madagaskisk ariary', 'mgf' => 'Madagaskisk franc', 'mkd' => 'Makedonisk denar', 'mlf' => 'Malisk franc', 'mmk' => 'Myanmarisk kyat', 'mnt' => 'Mongolisk tugrik', 'mop' => 'Macaoisk pataca', 'mro' => 'Mauretansk ouguiya', 'mtl' => 'Maltesisk lira', 'mtp' => 'Maltesiskt pund', 'mur' => 'Mauritisk rupie', 'mvr' => 'Maldivisk rufiyaa', 'mwk' => 'Malawisk kwacha', 'mxn' => 'Mexikansk peso', 'mxp' => 'Mexikansk silverpeso (1861-1992)', 'mxv' => 'Mexikansk Unidad de Inversion (UDI)', 'myr' => 'Malaysisk ringgit', 'mze' => 'Moçambikisk escudo', 'mzm' => 'Moçambikisk metical', 'nad' => 'Namibisk dollar', 'ngn' => 'Nigeriansk naira', 'nic' => 'Nicaraguansk córdoba', 'nio' => 'Nicaraguansk córdoba oro', 'nlg' => 'Nederländsk gulden', 'nok' => 'Norsk krona', 'npr' => 'Nepalesisk rupie', 'nzd' => 'Nyzeeländsk dollar', 'omr' => 'Omansk rial', 'pab' => 'Panamansk balboa', 'pei' => 'Peruansk inti', 'pen' => 'Peruansk sol nuevo', 'pes' => 'Peruansk sol', 'pgk' => 'Papuansk kina', 'php' => 'Filippinsk peso', 'pkr' => 'Pakistansk rupie', 'pln' => 'Polsk zloty', 'plz' => 'Polsk zloty (1950-1995)', 'pte' => 'Portugisisk escudo', 'pyg' => 'Paraguaysk guarani', 'qar' => 'Qatarisk rial', 'rhd' => 'Rhodesian Dollar', 'rol' => 'Rumänsk leu', 'ron' => 'Romanian Leu', 'rub' => 'Rysk rubel', 'rur' => 'Rysk rubel (1991-1998)', 'rwf' => 'Rwandisk franc', 'sar' => 'Saudisk riyal', 'sbd' => 'Salomon-dollar', 'scr' => 'Seychellisk rupie', 'sdd' => 'Sudanesisk dinar', 'sdp' => 'Sudanesiskt pund', 'sek' => 'Svensk krona', 'sgd' => 'Singaporiansk dollar', 'shp' => 'S:t Helena-pund', 'sit' => 'Slovensk tolar', 'skk' => 'Slovakisk koruna', 'sll' => 'Sierraleonsk leone', 'sos' => 'Somalisk shilling', 'srd' => 'Surinam Dollar', 'srg' => 'Surinamesisk gulden', 'std' => 'São Tomé och Príncipe-dobra', 'sur' => 'Sovjetisk rubel', 'svc' => 'Salvadoransk colón', 'syp' => 'Syriskt pund', 'szl' => 'Swaziländsk lilangeni', 'thb' => 'Thailändsk baht', 'tjr' => 'Tadzjikisk rubel', 'tjs' => 'Tadzjikisk somoni', 'tmm' => 'Turkmensk manat', 'tnd' => 'Tunisisk dinar', 'top' => 'Tongansk paʻanga', 'tpe' => 'Timoriansk escudo', 'trl' => 'Turkisk lira', 'try' => 'Ny turkisk lira', 'ttd' => 'Trinidadisk dollar', 'twd' => 'Taiwanesisk ny dollar', 'tzs' => 'Tanzanisk shilling', 'uah' => 'Ukrainsk hryvnia', 'uak' => 'Ukrainsk karbovanetz', 'ugs' => 'Ugandisk shilling (1966-1987)', 'ugx' => 'Ugandisk shilling', 'usd' => 'US-dollar', 'usn' => 'US-dollar (nästa dag)', 'uss' => 'US-dollar (samma dag)', 'uyp' => 'Uruguayansk peso (1975-1993)', 'uyu' => 'Uruguayansk peso uruguayo', 'uzs' => 'Uzbekisk sum', 'veb' => 'Venezuelansk bolivar', 'vnd' => 'Vietnamesisk dong', 'vuv' => 'Vanuatisk vatu', 'wst' => 'Västsamoansk tala', 'xaf' => 'CFA Franc BEAC', 'xag' => 'Silver', 'xau' => 'Gold', 'xba' => 'European Composite Unit', 'xbb' => 'European Monetary Unit', 'xbc' => 'European Unit of Account (XBC)', 'xbd' => 'European Unit of Account (XBD)', 'xcd' => 'Östkaribisk dollar', 'xdr' => 'Special Drawing Rights', 'xeu' => 'European Currency Unit', 'xfo' => 'Fransk guldfranc', 'xfu' => 'French UIC-Franc', 'xof' => 'CFA Franc BCEAO', 'xpd' => 'Palladium', 'xpf' => 'CFP-franc', 'xpt' => 'Platinum', 'xre' => 'RINET Funds', 'xts' => 'Testing Currency Code', 'xxx' => 'No Currency', 'ydd' => 'Jemenitisk dinar', 'yer' => 'Jemenitisk rial', 'yud' => 'Jugoslavisk hård dinar', 'yum' => 'Dinar (Serbien och Montenegro)', 'yun' => 'Jugoslavisk konvertibel dinar', 'zal' => 'Sydafrikansk rand (finansiell)', 'zar' => 'Sydafrikansk rand', 'zmk' => 'Zambisk kwacha', 'zrn' => 'Zairisk ny zaire', 'zrz' => 'Zairisk zaire', 'zwd' => 'Zimbabwisk dollar', );
prdatur/soopfw
language/currencies/sv.php
PHP
gpl-2.0
8,556
#pragma once #include <vector_types.h> template<class TReal, class TCoord> class DataTypes { public: typedef TReal Real; typedef TCoord Coord; static const char* name(); }; /// 1f DOF, single precision typedef DataTypes<float, float> DataType1f; template<> inline const char* DataType1f::name() { return "DataType1f"; } /// 2f DOF, single precision typedef DataTypes<float, float2> DataType2f; template<> inline const char* DataType2f::name() { return "DataType2f"; } /// 3f DOF, single precision typedef DataTypes<float, float3> DataType3f; template<> inline const char* DataType3f::name() { return "DataType3f"; } /// 3f DOF, single precision typedef DataTypes<float, float4> DataType4f; template<> inline const char* DataType4f::name() { return "DataType4f"; } /// 1d DOF, double precision typedef DataTypes<double, double> DataType1d; template<> inline const char* DataType1d::name() { return "DataType1d"; } /// 2d DOF, double precision typedef DataTypes<double, double2> DataType2d; template<> inline const char* DataType2d::name() { return "DataType2d"; } /// 3d DOF, double precision typedef DataTypes<double, double3> DataType3d; template<> inline const char* DataType3d::name() { return "DataType3d"; } /// 4d DOF, double precision typedef DataTypes<double, double4> DataType4d; template<> inline const char* DataType4d::name() { return "DataType4d"; }
suitmyself/Physika
Physika_Src/Physika_Framework/Framework/DataTypes.h
C
gpl-2.0
1,377
\set ON_ERROR_STOP SET SESSION AUTHORIZATION 'tms'; BEGIN; SELECT iris.update_version('4.65.0', '4.66.0'); -- Drop bitmaps column from sign_message ALTER TABLE iris.sign_message DROP COLUMN bitmaps; -- Add system blank sign message INSERT INTO iris.sign_message (name, multi, beacon_enabled, a_priority, r_priority, source) VALUES ('system_blank', '', false, 21, 1, 1); -- Update all blank signs to the same sign message UPDATE iris._dms SET msg_current = 'system_blank' FROM iris.sign_message AS sm WHERE msg_current = sm.name AND sm.multi = '' OR msg_current IS NULL; DELETE FROM iris.sign_message WHERE multi = '' AND name != 'system_blank'; -- Make msg_current not null ALTER TABLE iris._dms ALTER COLUMN msg_current SET NOT NULL; -- Add controller condition to dms_message_view DROP VIEW dms_message_view; CREATE VIEW dms_message_view AS SELECT d.name, cc.description AS condition, multi, beacon_enabled, iris.sign_msg_sources(source) AS sources, duration, deploy_time, owner FROM iris.dms d LEFT JOIN iris.controller c ON d.controller = c.name LEFT JOIN iris.condition cc ON c.condition = cc.id LEFT JOIN iris.sign_message s ON d.msg_current = s.name; GRANT SELECT ON dms_message_view TO PUBLIC; COMMIT;
CA-IRIS/mn-iris
sql/migrate-4.66.sql
SQL
gpl-2.0
1,244
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ class Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1SubscriberEvent extends Google_Model { protected $customerEventType = 'Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent'; protected $customerEventDataType = ''; protected $entitlementEventType = 'Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent'; protected $entitlementEventDataType = ''; /** * @param Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent */ public function setCustomerEvent(Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent $customerEvent) { $this->customerEvent = $customerEvent; } /** * @return Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1CustomerEvent */ public function getCustomerEvent() { return $this->customerEvent; } /** * @param Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent */ public function setEntitlementEvent(Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent $entitlementEvent) { $this->entitlementEvent = $entitlementEvent; } /** * @return Google_Service_Cloudchannel_GoogleCloudChannelV1alpha1EntitlementEvent */ public function getEntitlementEvent() { return $this->entitlementEvent; } }
palasthotel/grid-wordpress-box-social
vendor/google/apiclient-services/src/Google/Service/Cloudchannel/GoogleCloudChannelV1alpha1SubscriberEvent.php
PHP
gpl-2.0
1,892
#!/usr/bin/perl # release file perl script for pyukiwiki # $Id: compactmagic.pl,v 1.19 2006/03/04 13:12:52 papu Exp $ $header="#----------------------------------------------------------------------\n"; $output=0; $chk=0; $title=0; $file=$ARGV[0]; $opt=$ARGV[1]; if(open(R,$file)) { foreach $f (<R>) { chomp $f; if($f=~/^\#\-\-\-\-/) { $output=0; $chk++; next; } elsif($chk > 0) { $chk++; $chk=0 if($chk > 2); $output=&check($f); if($output eq 1) { print "$header"; print "$f\n"; $chk=0; $title=1; } next; } if($output eq 1) { if($f=~/^#.+/) { next if($title eq 0); } elsif($f=~/^#\s*$/) { next; } else { $title=0; } next if($f=~/^\s*$/); $f=~s/\s\s+/\t/g; print "$f\n"; } } close(R); } sub check { $_=lc shift; $ret=0; $ret=1 if(/archive/); $ret=1 if(/jpeg/); $ret=1 if(/images/); $ret=1 if(/compress\:/); if($opt ne 'compact') { $ret=1 if(/cabinet/); $ret=1 if(/msdos/); $ret=1 if(/rtf/); $ret=1 if(/animation/); $ret=1 if(/macintosh/); $ret=1 if(/commands/); $ret=1 if(/mail*news/); $ret=1 if(/rpm/); $ret=1 if(/perl/); $ret=1 if(/flash/); $ret=1 if(/pdf/); $ret=1 if(/sgml|html|hypertext/); $ret=1 if(/mime/); $ret=1 if(/uuencode/); $ret=1 if(/audio/); $ret=1 if(/riff/); $ret=1 if(/program/); $ret=1 if(/pgp/); $ret=1 if(/python/); } $ret=0 if(/sccs/); $ret=1 if(/\$id.*exp/); $ret=0 if(!/^#/); return $ret; }
argrath/pyukiwiki-alt
build/compactmagic.pl
Perl
gpl-2.0
1,459
#!/bin/sh cd "$( dirname "${BASH_SOURCE[0]}" )" PROJECT="org.kde.activeWindowControl" NAME="plasma_applet_$PROJECT" # svn checkout svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/scripts # export PATH=/path/to/l10n-kf5/scripts:$PATH extract-messages.sh sed -e "s,Report-Msgid-Bugs-To: http://bugs.kde.org,Report-Msgid-Bugs-To: https://github.com/kotelnik/plasma-applet-active-window-control/issues," -i "po/$NAME.pot" echo "Merging translations" catalogs=`find ./po -name '*.po'` for cat in $catalogs; do echo $cat msgmerge -o $cat.new $cat po/$NAME.pot mv $cat.new $cat done echo "Done merging translations"
kotelnik/plasma-applet-active-window-control
translations/update-translations.sh
Shell
gpl-2.0
618
/* * fixup-lm2f.c * * Copyright (C) 2004 ICT CAS * Author: Li xiaoyu, ICT CAS * lixy@ict.ac.cn * * Copyright (C) 2007 Lemote, Inc. & Institute of Computing Technology * Author: Fuxin Zhang, zhangfx@lemote.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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * 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 <linux/init.h> #include <linux/pci.h> #include <asm/mips-boards/bonito64.h> /* PCI interrupt pins */ /* These should not be changed, or you should consider godson2f interrupt register and * your pci card dispatch */ #define PCIA 4 #define PCIB 5 #define PCIC 6 #define PCID 7 /* all the pci device has the PCIA pin, check the datasheet. */ static char irq_tab[][5] __initdata = { /* INTA INTB INTC INTD */ {0, 0, 0, 0, 0 }, /* 11: Unused */ {0, 0, 0, 0, 0 }, /* 12: Unused */ {0, 0, 0, 0, 0 }, /* 13: Unused */ {0, 0, 0, 0, 0 }, /* 14: Unused */ {0, 0, 0, 0, 0 }, /* 15: Unused */ {0, 0, 0, 0, 0 }, /* 16: Unused */ {0, PCIA, 0, 0, 0 }, /* 17: RTL8110-0 */ {0, PCIB, 0, 0, 0 }, /* 18: RTL8110-1 */ {0, PCIC, 0, 0, 0 }, /* 19: SiI3114 */ {0, PCID, 0, 0, 0 }, /* 20: 3-ports nec usb*/ {0, PCIA, PCIB, PCIC, PCID }, /* 21: PCI-SLOT */ {0, 0, 0, 0, 0 }, /* 22: Unused */ {0, 0, 0, 0, 0 }, /* 23: Unused */ {0, 0, 0, 0, 0 }, /* 24: Unused */ {0, 0, 0, 0, 0 }, /* 25: Unused */ {0, 0, 0, 0, 0 }, /* 26: Unused */ {0, 0, 0, 0, 0 }, /* 27: Unused */ }; int __init pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) { int virq; if( (PCI_SLOT(dev->devfn) != (14)) && (PCI_SLOT(dev->devfn) < 32) ){ virq = irq_tab[slot][pin]; printk("slot: %d, pin: %d, irq: %d\n", slot, pin, virq+BONITO_IRQ_BASE); if(virq != 0) return (BONITO_IRQ_BASE + virq); else return 0; }else if( PCI_SLOT(dev->devfn) == 14){ // cs5536 switch(PCI_FUNC(dev->devfn)){ case 2 : pci_write_config_byte(dev, PCI_INTERRUPT_LINE, 14); return 14; // for IDE case 3 : pci_write_config_byte(dev, PCI_INTERRUPT_LINE, 9); return 9; // for AUDIO case 4 : // for OHCI case 5 : // for EHCI case 6 : // for UDC case 7 : // for OTG pci_write_config_byte(dev, PCI_INTERRUPT_LINE, 11); return 11; } return dev->irq; }else{ printk(" strange pci slot number.\n"); return 0; } } /* Do platform specific device initialization at pci_enable_device() time */ int pcibios_plat_dev_init(struct pci_dev *dev) { return 0; } #ifndef TEST_NO_CS5536 extern void _wrmsr(u32 reg, u32 hi, u32 lo); extern void _rdmsr(u32 reg, u32 *hi, u32 *lo); /* CS5536 SPEC. fixup */ static void __init loongson2f_cs5536_isa_fixup(struct pci_dev *pdev) { /* the uart1 and uart2 interrupt in PIC is enabled as default */ pci_write_config_dword(pdev, 0x50, 1); pci_write_config_dword(pdev, 0x54, 1); /* enable the pci MASTER ABORT/ TARGET ABORT etc. */ //pci_write_config_dword(pdev, 0x58, 1); return; } static void __init loongson2f_cs5536_ide_fixup(struct pci_dev *pdev) { /* setting the mutex pin as IDE function */ /* the IDE interrupt in PIC is enabled as default */ pci_write_config_dword(pdev, 0x40, 0xDEADBEEF); return; } static void __init loongson2f_cs5536_acc_fixup(struct pci_dev *pdev) { u8 val; /* enable the AUDIO interrupt in PIC */ pci_write_config_dword(pdev, 0x50, 1); #if 1 pci_read_config_byte(pdev, PCI_LATENCY_TIMER, &val); printk("cs5536 acc latency %x\n", val); pci_write_config_byte(pdev, PCI_LATENCY_TIMER, 0xc0); #endif return; } static void __init loongson2f_cs5536_ohci_fixup(struct pci_dev *pdev) { /* enable the OHCI interrupt in PIC */ /* THE OHCI, EHCI, UDC, OTG are shared with interrupt in PIC */ pci_write_config_dword(pdev, 0x50, 1); return; } static void __init loongson2f_cs5536_ehci_fixup(struct pci_dev *pdev) { u32 hi, lo; #if 0 u32 bar; void __iomem *base; #endif /* Serial short detect enable */ _rdmsr(0x40000001, &hi, &lo); _wrmsr(0x40000001, (1<<1)|(1<<2)|(1<<3), lo); #if 0 /* Write to clear diag register */ _rdmsr(0x40000005, &hi, &lo); _wrmsr(0x40000005, hi, lo); pci_read_config_dword(pdev, 0x10, &bar); base = ioremap_nocache(bar, 0x100); /* Make HCCAPARMS writable */ writel(readl(base + 0xA0) | (1<<1), (base + 0xA0)); /* EECP=50h, IST=01h, ASPC=1h */ writel(0x00000012, base + 0x08); iounmap(base); #endif /* setting the USB2.0 micro frame length */ pci_write_config_dword(pdev, 0x60, 0x2000); return; } #endif /* TEST_NO_CS5536 */ static void __init loongson2f_fixup_pcimap(struct pci_dev *pdev) { static int first = 1; (void)pdev; if (first) first = 0; else return; /* local to PCI mapping: [256M,512M] -> [256M,512M]; differ from pmon */ /* * cpu address space [256M,448M] is window for accessing pci space * we set pcimap_lo[0,1,2] to map it to pci space [256M,448M] * pcimap: bit18,pcimap_2; bit[17-12],lo2;bit[11-6],lo1;bit[5-0],lo0 */ /* 1,00 0110 ,0001 01,00 0000 */ BONITO_PCIMAP = 0x46140; //1, 00 0010, 0000,01, 00 0000 //BONITO_PCIMAP = 0x42040; /* * PCI to local mapping: [2G,2G+256M] -> [0,256M] */ #if 1 // for GODSON2F BONITO_PCIBASE0 = 0x80000000; BONITO_PCIBASE1 = 0x00000000; BONITO(BONITO_REGBASE + 0x50) = 0xc000000c; BONITO(BONITO_REGBASE + 0x54) = 0xffffffff; BONITO(BONITO_REGBASE + 0x58) = 0x00000006; BONITO(BONITO_REGBASE + 0x5c) = 0x00000000; BONITO(BONITO_REGBASE + 0x60) = 0x00000006; BONITO(BONITO_REGBASE + 0x64) = 0x00000000; #else // for GODSON2E BONITO_PCIBASE0 = 0x80000000; BONITO_PCIBASE1 = 0x00800000; BONITO_PCIBASE2 = 0x90000000; #endif #ifdef CONFIG_64BIT *(volatile u32*)0xffffffffbfe0004c = 0xd2000001; #else *(volatile u32*)0xbfe0004c = 0xd2000001; #endif } static void __init loongson2f_nec_fixup(struct pci_dev *pdev) { unsigned int val; /* Configues port 1, 2, 3 to be validate*/ pci_read_config_dword(pdev, 0xe0, &val); pci_write_config_dword(pdev, 0xe0, (val & ~3) | 0x2); /*Only 2 port be used*/ } #ifndef TEST_NO_CS5536 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_ISA, loongson2f_cs5536_isa_fixup); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_OHC, loongson2f_cs5536_ohci_fixup); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_EHC, loongson2f_cs5536_ehci_fixup); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_AUDIO, loongson2f_cs5536_acc_fixup); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_IDE, loongson2f_cs5536_ide_fixup); #endif /* TEST_NO_CS5536 */ DECLARE_PCI_FIXUP_HEADER(PCI_ANY_ID, PCI_ANY_ID, loongson2f_fixup_pcimap); DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_USB, loongson2f_nec_fixup);
loongson-community/linux_loongson
arch/mips/pci/fixup-lmbook.c
C
gpl-2.0
7,831
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_COCOA_BROWSER_AVATAR_MENU_BUBBLE_CONTROLLER_H_ #define CHROME_BROWSER_UI_COCOA_BROWSER_AVATAR_MENU_BUBBLE_CONTROLLER_H_ #import <Cocoa/Cocoa.h> #include "base/mac/scoped_nsobject.h" #include "base/memory/scoped_ptr.h" #import "chrome/browser/ui/cocoa/base_bubble_controller.h" #import "ui/base/cocoa/tracking_area.h" class AvatarMenu; class Browser; @interface AvatarMenuBubbleController : BaseBubbleController { @private scoped_ptr<AvatarMenu> menu_; base::scoped_nsobject<NSMutableArray> items_; BOOL expanded_; } - (id)initWithBrowser:(Browser*)parentBrowser anchoredAt:(NSPoint)point; - (IBAction)newProfile:(id)sender; - (IBAction)switchToProfile:(id)sender; - (IBAction)editProfile:(id)sender; - (IBAction)switchProfile:(id)sender; @end @interface AvatarMenuItemController : NSViewController<NSAnimationDelegate> { @private __weak AvatarMenuBubbleController* controller_; size_t menuIndex_; BOOL isHighlighted_; base::scoped_nsobject<NSAnimation> linkAnimation_; __weak NSImageView* iconView_; __weak NSImageView* activeView_; __weak NSTextField* nameField_; __weak NSTextField* emailField_; __weak NSButton* editButton_; } @property(readonly, nonatomic) size_t menuIndex; @property(assign, nonatomic) BOOL isHighlighted; @property(assign, nonatomic) IBOutlet NSImageView* iconView; @property(assign, nonatomic) IBOutlet NSImageView* activeView; @property(assign, nonatomic) IBOutlet NSTextField* nameField; @property(assign, nonatomic) IBOutlet NSTextField* emailField; @property(assign, nonatomic) IBOutlet NSButton* editButton; - (id)initWithMenuIndex:(size_t)menuIndex menuController:(AvatarMenuBubbleController*)controller; - (IBAction)switchToProfile:(id)sender; - (IBAction)editProfile:(id)sender; - (void)highlightForEventType:(NSEventType)type; @end @interface AvatarMenuItemView : NSView { @private __weak AvatarMenuItemController* viewController_; ui::ScopedCrTrackingArea trackingArea_; } @property(assign, nonatomic) IBOutlet AvatarMenuItemController* viewController; @end @interface AccessibilityIgnoredImageCell : NSImageCell @end @interface AccessibilityIgnoredTextFieldCell : NSTextFieldCell @end @interface AvatarMenuBubbleController (ExposedForTesting) - (id)initWithMenu:(AvatarMenu*)menu parentWindow:(NSWindow*)parent anchoredAt:(NSPoint)point; - (void)performLayout; - (NSMutableArray*)items; @end @interface AvatarMenuItemController (ExposedForTesting) - (void)willStartAnimation:(NSAnimation*)animation; @end #endif
qtekfun/htcDesire820Kernel
external/chromium_org/chrome/browser/ui/cocoa/browser/avatar_menu_bubble_controller.h
C
gpl-2.0
2,787
<?php /** * content-gallery.php * * The default template for displaying posts with the Gallery post format. * @package Theme_Material * GPL3 Licensed */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <!-- Article header --> <header class="entry-header"> <?php // If single page, display the title // Else, we display the title in a link if ( is_single() ) : ?> <h1><?php the_title(); ?></h1> <?php else : ?> <h1><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h1> <?php endif; ?> <p class="entry-meta"> <?php // Display the meta information material_post_meta(); ?> </p> </header> <!-- end entry-header --> <!-- Article content --> <div class="entry-content"> <?php the_content( __( 'Continue reading &rarr;', 'material' ) ); wp_link_pages(); ?> </div> <!-- end entry-content --> <!-- Article footer --> <footer class="entry-footer"> <?php // If we have a single page and the author bio exists, display it if ( is_single() && get_the_author_meta( 'description' ) ) { echo '<h2>' . __( 'Written by ', 'material' ) . get_the_author() . '</h2>'; echo '<p>' . the_author_meta( 'description' ) . '</p>'; } ?> </footer> <!-- end entry-footer --> </article>
puuga/wordpress
wp-content/themes/material/content-gallery.php
PHP
gpl-2.0
1,286
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * Free SoftwareFoundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package javax.jms; /** * The exception */ public class InvalidSelectorException extends JMSException { public InvalidSelectorException(String reason) { super(reason); } public InvalidSelectorException(String reason, String errorCode) { super(reason, errorCode); } }
christianchristensen/resin
modules/jms/src/javax/jms/InvalidSelectorException.java
Java
gpl-2.0
1,322
# Libraries example This example shows how cmake can find libraries and can use configure options. ## Structure * **main.c** * Program that encodes the first argument into several formats: * *Base64* Non-optional * *GZip2 -> Base64* Disabled by default * *BZip -> Base64* Disabled by default # CMake features * CMake can find packages installed on the setup * **find_package** * Sets some values automatically: * `<package>_FOUND` will be set to indicate whether the package was found * `<package>_LIBRARIES` will be set to the path where the package libraries are * `<package>_INCLUDES` will be set to the path where the package heades are * CMake supports build options * **option** * Use `add_definitions` to pass pre-processor flags to the compiler * ifdef out code that is not used/supported in the current build
luisggpina/cmake-examples
3-libraries/README.md
Markdown
gpl-2.0
862
# exercise from http://www.ling.gu.se/~lager/python_exercises.html # solution from http://rosettacode.org/wiki/99_Bottles_of_Beer#Python # "99 bottle of beer" is a traditional song in the US and Canada. # it is popular to sing on long trips, as it has a very repetitive # format which is easy to memorize, and can take a long time to sing. # the song's simple lyrics are as follows: # 99 bottles of beer on the wall, 99 bottles of beer. # take one down, pass it around, 98 bottles of beer on the wall. # the same verse is repeated, each time with one fewer bottle. # the song is completed when the singers reach zero. # Task now is to write a Python program # capable of generating all the verses of the song. print '------------------------------' print '99 Bottles of Beer on the Wall' print '------------------------------' bottles = 99 song = ''' %d bottles of beer on the wall, %d bottles of beer.\n Take one down, pass it around, %d bottles of beer. ''' for bottles in range(99,0,-1): print song %(bottles,bottles,bottles-1)
SurAnand/pyuthon
99beer.py
Python
gpl-2.0
1,042
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_27) on Thu Sep 12 23:41:40 EST 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Constant Field Values (iCal4j 1.0.5 API)</title> <meta name="date" content="2013-09-12"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Constant Field Values (iCal4j 1.0.5 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="index.html?constant-values.html" target="_top">FRAMES</a></li> <li><a href="constant-values.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Constant Field Values" class="title">Constant Field Values</h1> <h2 title="Contents">Contents</h2> <ul> <li><a href="#net.fortuna">net.fortuna.*</a></li> </ul> </div> <div class="constantValuesContainer"><a name="net.fortuna"> <!-- --> </a> <h2 title="net.fortuna">net.fortuna.*</h2> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.data.<a href="net/fortuna/ical4j/data/CalendarParserFactory.html" title="class in net.fortuna.ical4j.data">CalendarParserFactory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.data.CalendarParserFactory.KEY_FACTORY_CLASS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/data/CalendarParserFactory.html#KEY_FACTORY_CLASS">KEY_FACTORY_CLASS</a></code></td> <td class="colLast"><code>"net.fortuna.ical4j.parser"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.data.<a href="net/fortuna/ical4j/data/FoldingWriter.html" title="class in net.fortuna.ical4j.data">FoldingWriter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.data.FoldingWriter.MAX_FOLD_LENGTH"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/data/FoldingWriter.html#MAX_FOLD_LENGTH">MAX_FOLD_LENGTH</a></code></td> <td class="colLast"><code>75</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.data.FoldingWriter.REDUCED_FOLD_LENGTH"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/data/FoldingWriter.html#REDUCED_FOLD_LENGTH">REDUCED_FOLD_LENGTH</a></code></td> <td class="colLast"><code>73</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.filter.<a href="net/fortuna/ical4j/filter/Filter.html" title="class in net.fortuna.ical4j.filter">Filter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.filter.Filter.MATCH_ALL"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/filter/Filter.html#MATCH_ALL">MATCH_ALL</a></code></td> <td class="colLast"><code>2</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.filter.Filter.MATCH_ANY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/filter/Filter.html#MATCH_ANY">MATCH_ANY</a></code></td> <td class="colLast"><code>1</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.<a href="net/fortuna/ical4j/model/Calendar.html" title="class in net.fortuna.ical4j.model">Calendar</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Calendar.BEGIN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Calendar.html#BEGIN">BEGIN</a></code></td> <td class="colLast"><code>"BEGIN"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Calendar.END"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Calendar.html#END">END</a></code></td> <td class="colLast"><code>"END"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Calendar.VCALENDAR"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Calendar.html#VCALENDAR">VCALENDAR</a></code></td> <td class="colLast"><code>"VCALENDAR"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.<a href="net/fortuna/ical4j/model/Component.html" title="class in net.fortuna.ical4j.model">Component</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.AVAILABLE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#AVAILABLE">AVAILABLE</a></code></td> <td class="colLast"><code>"AVAILABLE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.BEGIN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#BEGIN">BEGIN</a></code></td> <td class="colLast"><code>"BEGIN"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.END"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#END">END</a></code></td> <td class="colLast"><code>"END"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.EXPERIMENTAL_PREFIX"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#EXPERIMENTAL_PREFIX">EXPERIMENTAL_PREFIX</a></code></td> <td class="colLast"><code>"X-"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.VALARM"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#VALARM">VALARM</a></code></td> <td class="colLast"><code>"VALARM"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.VAVAILABILITY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#VAVAILABILITY">VAVAILABILITY</a></code></td> <td class="colLast"><code>"VAVAILABILITY"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.VEVENT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#VEVENT">VEVENT</a></code></td> <td class="colLast"><code>"VEVENT"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.VFREEBUSY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#VFREEBUSY">VFREEBUSY</a></code></td> <td class="colLast"><code>"VFREEBUSY"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.VJOURNAL"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#VJOURNAL">VJOURNAL</a></code></td> <td class="colLast"><code>"VJOURNAL"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.VTIMEZONE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#VTIMEZONE">VTIMEZONE</a></code></td> <td class="colLast"><code>"VTIMEZONE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.VTODO"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#VTODO">VTODO</a></code></td> <td class="colLast"><code>"VTODO"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Component.VVENUE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Component.html#VVENUE">VVENUE</a></code></td> <td class="colLast"><code>"VVENUE"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.<a href="net/fortuna/ical4j/model/DateRange.html" title="class in net.fortuna.ical4j.model">DateRange</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.DateRange.INCLUSIVE_END"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/model/DateRange.html#INCLUSIVE_END">INCLUSIVE_END</a></code></td> <td class="colLast"><code>2</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.DateRange.INCLUSIVE_START"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/model/DateRange.html#INCLUSIVE_START">INCLUSIVE_START</a></code></td> <td class="colLast"><code>1</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.<a href="net/fortuna/ical4j/model/Parameter.html" title="class in net.fortuna.ical4j.model">Parameter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.ABBREV"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#ABBREV">ABBREV</a></code></td> <td class="colLast"><code>"ABBREV"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.ALTREP"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#ALTREP">ALTREP</a></code></td> <td class="colLast"><code>"ALTREP"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.CN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#CN">CN</a></code></td> <td class="colLast"><code>"CN"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.CUTYPE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#CUTYPE">CUTYPE</a></code></td> <td class="colLast"><code>"CUTYPE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.DELEGATED_FROM"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#DELEGATED_FROM">DELEGATED_FROM</a></code></td> <td class="colLast"><code>"DELEGATED-FROM"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.DELEGATED_TO"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#DELEGATED_TO">DELEGATED_TO</a></code></td> <td class="colLast"><code>"DELEGATED-TO"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.DIR"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#DIR">DIR</a></code></td> <td class="colLast"><code>"DIR"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.ENCODING"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#ENCODING">ENCODING</a></code></td> <td class="colLast"><code>"ENCODING"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.EXPERIMENTAL_PREFIX"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#EXPERIMENTAL_PREFIX">EXPERIMENTAL_PREFIX</a></code></td> <td class="colLast"><code>"X-"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.FBTYPE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#FBTYPE">FBTYPE</a></code></td> <td class="colLast"><code>"FBTYPE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.FMTTYPE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#FMTTYPE">FMTTYPE</a></code></td> <td class="colLast"><code>"FMTTYPE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.LANGUAGE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#LANGUAGE">LANGUAGE</a></code></td> <td class="colLast"><code>"LANGUAGE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.MEMBER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#MEMBER">MEMBER</a></code></td> <td class="colLast"><code>"MEMBER"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.PARTSTAT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#PARTSTAT">PARTSTAT</a></code></td> <td class="colLast"><code>"PARTSTAT"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.RANGE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#RANGE">RANGE</a></code></td> <td class="colLast"><code>"RANGE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.RELATED"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#RELATED">RELATED</a></code></td> <td class="colLast"><code>"RELATED"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.RELTYPE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#RELTYPE">RELTYPE</a></code></td> <td class="colLast"><code>"RELTYPE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.ROLE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#ROLE">ROLE</a></code></td> <td class="colLast"><code>"ROLE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.RSVP"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#RSVP">RSVP</a></code></td> <td class="colLast"><code>"RSVP"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.SCHEDULE_AGENT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#SCHEDULE_AGENT">SCHEDULE_AGENT</a></code></td> <td class="colLast"><code>"SCHEDULE-AGENT"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.SCHEDULE_STATUS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#SCHEDULE_STATUS">SCHEDULE_STATUS</a></code></td> <td class="colLast"><code>"SCHEDULE-STATUS"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.SENT_BY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#SENT_BY">SENT_BY</a></code></td> <td class="colLast"><code>"SENT-BY"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.TYPE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#TYPE">TYPE</a></code></td> <td class="colLast"><code>"TYPE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.TZID"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#TZID">TZID</a></code></td> <td class="colLast"><code>"TZID"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.VALUE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#VALUE">VALUE</a></code></td> <td class="colLast"><code>"VALUE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Parameter.VVENUE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Parameter.html#VVENUE">VVENUE</a></code></td> <td class="colLast"><code>"VVENUE"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.<a href="net/fortuna/ical4j/model/Property.html" title="class in net.fortuna.ical4j.model">Property</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.ACTION"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#ACTION">ACTION</a></code></td> <td class="colLast"><code>"ACTION"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.ATTACH"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#ATTACH">ATTACH</a></code></td> <td class="colLast"><code>"ATTACH"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.ATTENDEE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#ATTENDEE">ATTENDEE</a></code></td> <td class="colLast"><code>"ATTENDEE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.BUSYTYPE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#BUSYTYPE">BUSYTYPE</a></code></td> <td class="colLast"><code>"BUSYTYPE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.CALSCALE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#CALSCALE">CALSCALE</a></code></td> <td class="colLast"><code>"CALSCALE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.CATEGORIES"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#CATEGORIES">CATEGORIES</a></code></td> <td class="colLast"><code>"CATEGORIES"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.CLASS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#CLASS">CLASS</a></code></td> <td class="colLast"><code>"CLASS"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.COMMENT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#COMMENT">COMMENT</a></code></td> <td class="colLast"><code>"COMMENT"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.COMPLETED"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#COMPLETED">COMPLETED</a></code></td> <td class="colLast"><code>"COMPLETED"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.CONTACT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#CONTACT">CONTACT</a></code></td> <td class="colLast"><code>"CONTACT"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.COUNTRY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#COUNTRY">COUNTRY</a></code></td> <td class="colLast"><code>"COUNTRY"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.CREATED"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#CREATED">CREATED</a></code></td> <td class="colLast"><code>"CREATED"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.DESCRIPTION"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#DESCRIPTION">DESCRIPTION</a></code></td> <td class="colLast"><code>"DESCRIPTION"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.DTEND"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#DTEND">DTEND</a></code></td> <td class="colLast"><code>"DTEND"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.DTSTAMP"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#DTSTAMP">DTSTAMP</a></code></td> <td class="colLast"><code>"DTSTAMP"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.DTSTART"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#DTSTART">DTSTART</a></code></td> <td class="colLast"><code>"DTSTART"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.DUE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#DUE">DUE</a></code></td> <td class="colLast"><code>"DUE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.DURATION"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#DURATION">DURATION</a></code></td> <td class="colLast"><code>"DURATION"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.EXDATE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#EXDATE">EXDATE</a></code></td> <td class="colLast"><code>"EXDATE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.EXPERIMENTAL_PREFIX"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#EXPERIMENTAL_PREFIX">EXPERIMENTAL_PREFIX</a></code></td> <td class="colLast"><code>"X-"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.EXRULE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#EXRULE">EXRULE</a></code></td> <td class="colLast"><code>"EXRULE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.EXTENDED_ADDRESS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#EXTENDED_ADDRESS">EXTENDED_ADDRESS</a></code></td> <td class="colLast"><code>"EXTENDED-ADDRESS"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.FREEBUSY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#FREEBUSY">FREEBUSY</a></code></td> <td class="colLast"><code>"FREEBUSY"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.GEO"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#GEO">GEO</a></code></td> <td class="colLast"><code>"GEO"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.LAST_MODIFIED"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#LAST_MODIFIED">LAST_MODIFIED</a></code></td> <td class="colLast"><code>"LAST-MODIFIED"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.LOCALITY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#LOCALITY">LOCALITY</a></code></td> <td class="colLast"><code>"LOCALITY"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.LOCATION"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#LOCATION">LOCATION</a></code></td> <td class="colLast"><code>"LOCATION"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.LOCATION_TYPE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#LOCATION_TYPE">LOCATION_TYPE</a></code></td> <td class="colLast"><code>"LOCATION-TYPE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.METHOD"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#METHOD">METHOD</a></code></td> <td class="colLast"><code>"METHOD"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.NAME"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#NAME">NAME</a></code></td> <td class="colLast"><code>"NAME"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.ORGANIZER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#ORGANIZER">ORGANIZER</a></code></td> <td class="colLast"><code>"ORGANIZER"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.PERCENT_COMPLETE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#PERCENT_COMPLETE">PERCENT_COMPLETE</a></code></td> <td class="colLast"><code>"PERCENT-COMPLETE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.POSTALCODE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#POSTALCODE">POSTALCODE</a></code></td> <td class="colLast"><code>"POSTAL-CODE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.PRIORITY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#PRIORITY">PRIORITY</a></code></td> <td class="colLast"><code>"PRIORITY"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.PRODID"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#PRODID">PRODID</a></code></td> <td class="colLast"><code>"PRODID"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.RDATE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#RDATE">RDATE</a></code></td> <td class="colLast"><code>"RDATE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.RECURRENCE_ID"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#RECURRENCE_ID">RECURRENCE_ID</a></code></td> <td class="colLast"><code>"RECURRENCE-ID"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.REGION"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#REGION">REGION</a></code></td> <td class="colLast"><code>"REGION"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.RELATED_TO"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#RELATED_TO">RELATED_TO</a></code></td> <td class="colLast"><code>"RELATED-TO"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.REPEAT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#REPEAT">REPEAT</a></code></td> <td class="colLast"><code>"REPEAT"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.REQUEST_STATUS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#REQUEST_STATUS">REQUEST_STATUS</a></code></td> <td class="colLast"><code>"REQUEST-STATUS"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.RESOURCES"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#RESOURCES">RESOURCES</a></code></td> <td class="colLast"><code>"RESOURCES"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.RRULE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#RRULE">RRULE</a></code></td> <td class="colLast"><code>"RRULE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.SEQUENCE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#SEQUENCE">SEQUENCE</a></code></td> <td class="colLast"><code>"SEQUENCE"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.STATUS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#STATUS">STATUS</a></code></td> <td class="colLast"><code>"STATUS"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.STREET_ADDRESS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#STREET_ADDRESS">STREET_ADDRESS</a></code></td> <td class="colLast"><code>"STREET-ADDRESS"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.SUMMARY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#SUMMARY">SUMMARY</a></code></td> <td class="colLast"><code>"SUMMARY"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.TEL"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#TEL">TEL</a></code></td> <td class="colLast"><code>"TEL"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.TRANSP"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#TRANSP">TRANSP</a></code></td> <td class="colLast"><code>"TRANSP"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.TRIGGER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#TRIGGER">TRIGGER</a></code></td> <td class="colLast"><code>"TRIGGER"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.TZID"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#TZID">TZID</a></code></td> <td class="colLast"><code>"TZID"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.TZNAME"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#TZNAME">TZNAME</a></code></td> <td class="colLast"><code>"TZNAME"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.TZOFFSETFROM"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#TZOFFSETFROM">TZOFFSETFROM</a></code></td> <td class="colLast"><code>"TZOFFSETFROM"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.TZOFFSETTO"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#TZOFFSETTO">TZOFFSETTO</a></code></td> <td class="colLast"><code>"TZOFFSETTO"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.TZURL"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#TZURL">TZURL</a></code></td> <td class="colLast"><code>"TZURL"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.UID"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#UID">UID</a></code></td> <td class="colLast"><code>"UID"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.URL"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#URL">URL</a></code></td> <td class="colLast"><code>"URL"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Property.VERSION"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Property.html#VERSION">VERSION</a></code></td> <td class="colLast"><code>"VERSION"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.<a href="net/fortuna/ical4j/model/Recur.html" title="class in net.fortuna.ical4j.model">Recur</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Recur.DAILY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Recur.html#DAILY">DAILY</a></code></td> <td class="colLast"><code>"DAILY"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Recur.HOURLY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Recur.html#HOURLY">HOURLY</a></code></td> <td class="colLast"><code>"HOURLY"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Recur.KEY_MAX_INCREMENT_COUNT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Recur.html#KEY_MAX_INCREMENT_COUNT">KEY_MAX_INCREMENT_COUNT</a></code></td> <td class="colLast"><code>"net.fortuna.ical4j.recur.maxincrementcount"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Recur.MINUTELY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Recur.html#MINUTELY">MINUTELY</a></code></td> <td class="colLast"><code>"MINUTELY"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Recur.MONTHLY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Recur.html#MONTHLY">MONTHLY</a></code></td> <td class="colLast"><code>"MONTHLY"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Recur.SECONDLY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Recur.html#SECONDLY">SECONDLY</a></code></td> <td class="colLast"><code>"SECONDLY"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Recur.WEEKLY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Recur.html#WEEKLY">WEEKLY</a></code></td> <td class="colLast"><code>"WEEKLY"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.Recur.YEARLY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/Recur.html#YEARLY">YEARLY</a></code></td> <td class="colLast"><code>"YEARLY"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.<a href="net/fortuna/ical4j/model/TimeZoneRegistryFactory.html" title="class in net.fortuna.ical4j.model">TimeZoneRegistryFactory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.TimeZoneRegistryFactory.KEY_FACTORY_CLASS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/TimeZoneRegistryFactory.html#KEY_FACTORY_CLASS">KEY_FACTORY_CLASS</a></code></td> <td class="colLast"><code>"net.fortuna.ical4j.timezone.registry"</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.component.<a href="net/fortuna/ical4j/model/component/Observance.html" title="class in net.fortuna.ical4j.model.component">Observance</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.component.Observance.DAYLIGHT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/component/Observance.html#DAYLIGHT">DAYLIGHT</a></code></td> <td class="colLast"><code>"DAYLIGHT"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.component.Observance.STANDARD"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/component/Observance.html#STANDARD">STANDARD</a></code></td> <td class="colLast"><code>"STANDARD"</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.parameter.<a href="net/fortuna/ical4j/model/parameter/TzId.html" title="class in net.fortuna.ical4j.model.parameter">TzId</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.parameter.TzId.PREFIX"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/parameter/TzId.html#PREFIX">PREFIX</a></code></td> <td class="colLast"><code>"/"</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.property.<a href="net/fortuna/ical4j/model/property/RequestStatus.html" title="class in net.fortuna.ical4j.model.property">RequestStatus</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.property.RequestStatus.CLIENT_ERROR"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/property/RequestStatus.html#CLIENT_ERROR">CLIENT_ERROR</a></code></td> <td class="colLast"><code>"3"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.property.RequestStatus.PRELIM_SUCCESS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/property/RequestStatus.html#PRELIM_SUCCESS">PRELIM_SUCCESS</a></code></td> <td class="colLast"><code>"1"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.property.RequestStatus.SCHEDULING_ERROR"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/property/RequestStatus.html#SCHEDULING_ERROR">SCHEDULING_ERROR</a></code></td> <td class="colLast"><code>"4"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.property.RequestStatus.SUCCESS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/property/RequestStatus.html#SUCCESS">SUCCESS</a></code></td> <td class="colLast"><code>"2"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.model.property.<a href="net/fortuna/ical4j/model/property/TzId.html" title="class in net.fortuna.ical4j.model.property">TzId</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.model.property.TzId.PREFIX"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/model/property/TzId.html#PREFIX">PREFIX</a></code></td> <td class="colLast"><code>"/"</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.util.<a href="net/fortuna/ical4j/util/CompatibilityHints.html" title="class in net.fortuna.ical4j.util">CompatibilityHints</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.CompatibilityHints.KEY_NOTES_COMPATIBILITY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/CompatibilityHints.html#KEY_NOTES_COMPATIBILITY">KEY_NOTES_COMPATIBILITY</a></code></td> <td class="colLast"><code>"ical4j.compatibility.notes"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/CompatibilityHints.html#KEY_OUTLOOK_COMPATIBILITY">KEY_OUTLOOK_COMPATIBILITY</a></code></td> <td class="colLast"><code>"ical4j.compatibility.outlook"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.CompatibilityHints.KEY_RELAXED_PARSING"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/CompatibilityHints.html#KEY_RELAXED_PARSING">KEY_RELAXED_PARSING</a></code></td> <td class="colLast"><code>"ical4j.parsing.relaxed"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.CompatibilityHints.KEY_RELAXED_UNFOLDING"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/CompatibilityHints.html#KEY_RELAXED_UNFOLDING">KEY_RELAXED_UNFOLDING</a></code></td> <td class="colLast"><code>"ical4j.unfolding.relaxed"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.CompatibilityHints.KEY_RELAXED_VALIDATION"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/CompatibilityHints.html#KEY_RELAXED_VALIDATION">KEY_RELAXED_VALIDATION</a></code></td> <td class="colLast"><code>"ical4j.validation.relaxed"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.CompatibilityHints.KEY_VCARD_COMPATIBILITY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/CompatibilityHints.html#KEY_VCARD_COMPATIBILITY">KEY_VCARD_COMPATIBILITY</a></code></td> <td class="colLast"><code>"ical4j.compatibility.vcard"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.util.<a href="net/fortuna/ical4j/util/Dates.html" title="class in net.fortuna.ical4j.util">Dates</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.DAYS_PER_WEEK"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#DAYS_PER_WEEK">DAYS_PER_WEEK</a></code></td> <td class="colLast"><code>7</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.MAX_DAYS_PER_MONTH"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#MAX_DAYS_PER_MONTH">MAX_DAYS_PER_MONTH</a></code></td> <td class="colLast"><code>31</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.MAX_DAYS_PER_YEAR"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#MAX_DAYS_PER_YEAR">MAX_DAYS_PER_YEAR</a></code></td> <td class="colLast"><code>366</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.MAX_WEEKS_PER_YEAR"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#MAX_WEEKS_PER_YEAR">MAX_WEEKS_PER_YEAR</a></code></td> <td class="colLast"><code>53</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.MILLIS_PER_DAY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;long</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#MILLIS_PER_DAY">MILLIS_PER_DAY</a></code></td> <td class="colLast"><code>86400000L</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.MILLIS_PER_HOUR"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;long</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#MILLIS_PER_HOUR">MILLIS_PER_HOUR</a></code></td> <td class="colLast"><code>3600000L</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.MILLIS_PER_MINUTE"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;long</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#MILLIS_PER_MINUTE">MILLIS_PER_MINUTE</a></code></td> <td class="colLast"><code>60000L</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.MILLIS_PER_SECOND"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;long</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#MILLIS_PER_SECOND">MILLIS_PER_SECOND</a></code></td> <td class="colLast"><code>1000L</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.MILLIS_PER_WEEK"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;long</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#MILLIS_PER_WEEK">MILLIS_PER_WEEK</a></code></td> <td class="colLast"><code>604800000L</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.PRECISION_DAY"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#PRECISION_DAY">PRECISION_DAY</a></code></td> <td class="colLast"><code>1</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Dates.PRECISION_SECOND"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;int</code></td> <td><code><a href="net/fortuna/ical4j/util/Dates.html#PRECISION_SECOND">PRECISION_SECOND</a></code></td> <td class="colLast"><code>0</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.util.<a href="net/fortuna/ical4j/util/DecoderFactory.html" title="class in net.fortuna.ical4j.util">DecoderFactory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.DecoderFactory.KEY_FACTORY_CLASS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/DecoderFactory.html#KEY_FACTORY_CLASS">KEY_FACTORY_CLASS</a></code></td> <td class="colLast"><code>"net.fortuna.ical4j.factory.decoder"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.util.<a href="net/fortuna/ical4j/util/EncoderFactory.html" title="class in net.fortuna.ical4j.util">EncoderFactory</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.EncoderFactory.KEY_FACTORY_CLASS"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/EncoderFactory.html#KEY_FACTORY_CLASS">KEY_FACTORY_CLASS</a></code></td> <td class="colLast"><code>"net.fortuna.ical4j.factory.encoder"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.util.<a href="net/fortuna/ical4j/util/Strings.html" title="class in net.fortuna.ical4j.util">Strings</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Strings.LINE_SEPARATOR"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/Strings.html#LINE_SEPARATOR">LINE_SEPARATOR</a></code></td> <td class="colLast"><code>"\r\n"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.util.<a href="net/fortuna/ical4j/util/TimeZones.html" title="class in net.fortuna.ical4j.util">TimeZones</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.TimeZones.GMT_ID"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/TimeZones.html#GMT_ID">GMT_ID</a></code></td> <td class="colLast"><code>"Etc/GMT"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.TimeZones.IBM_UTC_ID"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/TimeZones.html#IBM_UTC_ID">IBM_UTC_ID</a></code></td> <td class="colLast"><code>"GMT"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.TimeZones.UTC_ID"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/TimeZones.html#UTC_ID">UTC_ID</a></code></td> <td class="colLast"><code>"Etc/UTC"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>net.fortuna.ical4j.util.<a href="net/fortuna/ical4j/util/Uris.html" title="class in net.fortuna.ical4j.util">Uris</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="net.fortuna.ical4j.util.Uris.INVALID_SCHEME"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="net/fortuna/ical4j/util/Uris.html#INVALID_SCHEME">INVALID_SCHEME</a></code></td> <td class="colLast"><code>"net.fortunal.ical4j.invalid"</code></td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>PREV</li> <li>NEXT</li> </ul> <ul class="navList"> <li><a href="index.html?constant-values.html" target="_top">FRAMES</a></li> <li><a href="constant-values.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2004-2013 <a href="http://micronode.com">Micronode</a>. All Rights Reserved.</small></p> </body> </html>
MartijnTheunissen/PLNR
lib/ical4j-1.0.5/docs/apidocs/constant-values.html
HTML
gpl-2.0
81,599
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2017 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <U2Core/U2AssemblyUtils.h> #include <U2Core/Log.h> #include "BAMDbiPlugin.h" #include "InvalidFormatException.h" #include "SamReader.h" #include "CigarValidator.h" #include <SamtoolsAdapter.h> namespace U2 { namespace BAM { const int SamReader::LOCAL_READ_BUFFER_SIZE = 100000; Alignment SamReader::parseAlignmentString(QByteArray line) { Alignment alignment; if(line.isEmpty()) { assert(0); throw InvalidFormatException(BAMDbiPlugin::tr("Unexpected empty string")); } QByteArray recordTag; QHash<QByteArray, QByteArray> fields; QList<QByteArray> tokens = line.split('\t'); if (tokens.length() < 11) { throw InvalidFormatException(BAMDbiPlugin::tr("Not enough fields in one of alignments")); } { QByteArray &qname = tokens[0]; // workaround for malformed SAMs if(!QRegExp("[ -~]{1,255}").exactMatch(qname)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid query template name: %1").arg(QString(qname))); } alignment.setName(qname); } { bool ok = false; int flagsValue = tokens[1].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid FLAG value: %1").arg(QString(tokens[1]))); } qint64 flags = 0; if(flagsValue & 0x1) { flags |= Fragmented; } if(flagsValue & 0x2) { flags |= FragmentsAligned; } if(flagsValue & 0x4) { flags |= Unmapped; } if(flagsValue & 0x8) { flags |= NextUnmapped; } if(flagsValue & 0x10) { flags |= Reverse; } if(flagsValue & 0x20) { flags |= NextReverse; } if(flagsValue & 0x40) { flags |= FirstInTemplate; } if(flagsValue & 0x80) { flags |= LastInTemplate; } if(flagsValue & 0x100) { flags |= SecondaryAlignment; } if(flagsValue & 0x200) { flags |= FailsChecks; } if(flagsValue & 0x400) { flags |= Duplicate; } alignment.setFlags(flags); } { QByteArray &rname = tokens[2]; // workaround for malformed SAMs if(!QRegExp("[*]|[!-()+-<>-~][ -~]*").exactMatch(rname)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid reference name: %1").arg(QString(rname))); } if ("*" == rname) { alignment.setReferenceId(-1); } else { if (!referencesMap.contains(rname)) { throw InvalidFormatException(BAMDbiPlugin::tr("Undefined reference name: %1").arg(QString(rname))); } alignment.setReferenceId(referencesMap[rname]); } } { bool ok = false; int position = tokens[3].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid read position value: %1").arg(QString(tokens[3]))); } if(position < 0) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid read position: %1").arg(position)); } alignment.setPosition(position - 1); //to 0-based mapping } { bool ok = false; int mapQuality = tokens[4].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mapping quality value: %1").arg(QString(tokens[4]))); } if(mapQuality < 0 || mapQuality > 255) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mapping quality: %1").arg(mapQuality)); } alignment.setMapQuality(mapQuality); } { QByteArray &cigarString = tokens[5]; if(!QRegExp("[*]|([0-9]+[MIDNSHPX=])+").exactMatch(cigarString)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar value: %1").arg(QString(cigarString))); } if ("*" != cigarString) { QString err; QList<U2CigarToken> res = U2AssemblyUtils::parseCigar(cigarString, err); if (!err.isEmpty()) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar value: %1").arg(QString(cigarString))); } QList<Alignment::CigarOperation> cigar; for(int i = 0; i < res.length(); i++) { Alignment::CigarOperation::Operation operation; switch(res[i].op) { case U2CigarOp_M: operation = Alignment::CigarOperation::AlignmentMatch; break; case U2CigarOp_I: operation = Alignment::CigarOperation::Insertion; break; case U2CigarOp_D: operation = Alignment::CigarOperation::Deletion; break; case U2CigarOp_N: operation = Alignment::CigarOperation::Skipped; break; case U2CigarOp_S: operation = Alignment::CigarOperation::SoftClip; break; case U2CigarOp_H: operation = Alignment::CigarOperation::HardClip; break; case U2CigarOp_P: operation = Alignment::CigarOperation::Padding; break; case U2CigarOp_EQ: operation = Alignment::CigarOperation::SequenceMatch; break; case U2CigarOp_X: operation = Alignment::CigarOperation::SequenceMismatch; break; default: throw InvalidFormatException(BAMDbiPlugin::tr("Invalid cigar operation code: %1").arg(res[i].op)); } int operatonLength = res[i].count; cigar.append(Alignment::CigarOperation(operatonLength, operation)); } alignment.setCigar(cigar); } } { QByteArray nextReference = tokens[6]; // workaround for malformed SAMs if(!QRegExp("[*]|[=]|[!-()+-<>-~][ -~]*").exactMatch(nextReference)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate reference name: %1").arg(QString(nextReference))); } if ("*" == nextReference) { alignment.setNextReferenceId(-1); } else if ("=" == nextReference) { alignment.setNextReferenceId(alignment.getReferenceId()); } else { if (!referencesMap.contains(nextReference)) { throw InvalidFormatException(BAMDbiPlugin::tr("Undefined mate reference name: %1").arg(QString(nextReference))); } alignment.setNextReferenceId(referencesMap[nextReference]); } alignment.setNextReferenceName(nextReference); } { bool ok = false; int nextPosition = tokens[7].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate position value: %1").arg(QString(tokens[7]))); } if(nextPosition < 0) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid mate position: %1").arg(nextPosition)); } alignment.setNextPosition(nextPosition - 1); //to 0-based mapping } { bool ok = false; int templateLength = tokens[8].toInt(&ok); if(!ok) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid template length value: %1").arg(QString(tokens[8]))); } if(!(alignment.getFlags() & Fragmented)) { if(0 != templateLength) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid template length of a single-fragment template: %1").arg(templateLength)); } } alignment.setTemplateLength(templateLength); } { QByteArray sequence = tokens[9]; if(!QRegExp("[*]|[A-Za-z=.]+").exactMatch(sequence)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid sequence: %1").arg(QString(sequence))); } alignment.setSequence(sequence); } { QByteArray quality = tokens[10]; if ("*" != quality) { if(QRegExp("[!-~]+").exactMatch(quality)) { alignment.setQuality(quality); } } } { QByteArray samAuxString; bool first = true; QMap<QByteArray, QVariant> optionalFields; for (int i = 11; i < tokens.length(); i++) { if (!first) { samAuxString += '\t'; } samAuxString += tokens[i]; first = false; } alignment.setAuxData(SamtoolsAdapter::samString2aux(samAuxString)); } { // Validation of the CIGAR string. int totalLength = 0; int length = alignment.getSequence().length(); const QList<Alignment::CigarOperation> &cigar = alignment.getCigar(); CigarValidator validator(cigar); validator.validate(&totalLength); if(!cigar.isEmpty() && length != totalLength) { const_cast<QList<Alignment::CigarOperation>&>(cigar).clear(); //Ignore invalid cigar } } return alignment; } SamReader::SamReader(IOAdapter &ioAdapter): Reader(ioAdapter), readBuffer(LOCAL_READ_BUFFER_SIZE, '\0') { readHeader(); } const Header &SamReader::getHeader()const { return header; } Alignment SamReader::readAlignment(bool &eof) { QByteArray alignmentString = readString(eof); return parseAlignmentString(alignmentString); } bool SamReader::isEof()const { return ioAdapter.isEof(); } QByteArray SamReader::readString(bool &eof) { char* buff = readBuffer.data(); bool lineOk = false; int len = 0; QByteArray result; while((len = ioAdapter.readLine(buff, LOCAL_READ_BUFFER_SIZE, &lineOk)) == 0) {} if (len == -1) { eof = true; } else { result = QByteArray::fromRawData(buff, len); } return result; } void SamReader::readHeader() { char* buff = readBuffer.data(); bool lineOk = false; int len = 0; qint64 bRead = ioAdapter.bytesRead(); QList<Header::Reference> references; { QList<Header::ReadGroup> readGroups; QList<Header::Program> programs; QList<QByteArray> previousProgramIds; while ((len = ioAdapter.readLine(buff, LOCAL_READ_BUFFER_SIZE, &lineOk)) >= 0) { if(isEof()){ break; } QByteArray line = QByteArray::fromRawData(buff, len); if(line.isEmpty()) { continue; } if(line.startsWith("@CO")) { continue; } if(!line.startsWith('@')) { ioAdapter.skip(bRead - ioAdapter.bytesRead()); break; } bRead = ioAdapter.bytesRead(); QByteArray recordTag; QHash<QByteArray, QByteArray> fields; { QList<QByteArray> tokens = line.split('\t'); recordTag = tokens[0].mid(1); if(!QRegExp("[A-Za-z][A-Za-z]").exactMatch(recordTag)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header record tag: %1").arg(QString(recordTag))); } for(int index = 1;index < tokens.size();index++) { QByteArray fieldTag; QByteArray fieldValue; { int colonIndex = tokens[index].indexOf(':'); if(-1 != colonIndex) { fieldTag = tokens[index].mid(0, colonIndex); fieldValue = tokens[index].mid(colonIndex + 1); } else if("PG" == recordTag) { // workaround for invalid headers produced by some programs continue; } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header field: %1").arg(QString(tokens[index]))); } } if(!QRegExp("[A-Za-z][A-Za-z]").exactMatch(fieldTag) && "M5" != fieldTag) { //workaround for bug in the spec throw InvalidFormatException(BAMDbiPlugin::tr("Invalid header field tag: %1").arg(QString(fieldTag))); } // CL and PN tags of can contain any string if(fieldTag!="CL" && fieldTag!="PN" && !QRegExp("[ -~]+").exactMatch(fieldValue)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid %1-%2 value: %3").arg(QString(recordTag)).arg(QString(fieldTag)).arg(QString(fieldValue))); } if(!fields.contains(fieldTag)) { fields.insert(fieldTag, fieldValue); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Duplicate header field: %1").arg(QString(fieldTag))); } } } if("HD" == recordTag) { if(fields.contains("VN")) { QByteArray value = fields["VN"]; if(!QRegExp("[0-9]+\\.[0-9]+").exactMatch(value)) { //Do nothing to support malformed BAMs //throw InvalidFormatException(BAMDbiPlugin::tr("Invalid HD-VN value: %1").arg(QString(value))); } header.setFormatVersion(Version::parseVersion(value)); } else { throw InvalidFormatException(BAMDbiPlugin::tr("HD record without VN field")); } if(fields.contains("SO")) { QByteArray value = fields["SO"]; if("unknown" == value) { header.setSortingOrder(Header::Unknown); } else if("unsorted" == value) { header.setSortingOrder(Header::Unsorted); } else if("queryname" == value) { header.setSortingOrder(Header::QueryName); } else if("coordinate" == value) { header.setSortingOrder(Header::Coordinate); } else if("sorted" == value) { // workaround for invalid headers produced by some programs header.setSortingOrder(Header::Coordinate); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid HD-SO value: %1").arg(QString(value))); } } else { header.setSortingOrder(Header::Unknown); } } else if("SQ" == recordTag) { Header::Reference *reference = NULL; QByteArray name; if(fields.contains("SN")) { name = fields["SN"]; } else { throw InvalidFormatException(BAMDbiPlugin::tr("SQ record without SN field")); } if(fields.contains("LN")) { QByteArray value = fields["LN"]; bool ok = false; int length = value.toInt(&ok); if(ok) { Header::Reference newRef(name, length); referencesMap.insert(name, references.size()); references.append(newRef); reference = &(references.last()); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid SQ-LN value: %1").arg(QString(value))); } } else { throw InvalidFormatException(BAMDbiPlugin::tr("SQ record without LN field")); } assert(NULL != reference); if(fields.contains("AS")) { reference->setAssemblyId(fields["AS"]); } if(fields.contains("M5")) { QByteArray value = fields["M5"]; //[a-f] is a workaround (not matching to SAM-1.3 spec) to open 1000 Genomes project BAMs if(!QRegExp("[0-9A-Fa-f]+").exactMatch(value)) { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid SQ-M5 value: %1").arg(QString(value))); } reference->setMd5(fields["M5"]); } if(fields.contains("SP")) { reference->setSpecies(fields["SP"]); } if(fields.contains("UR")) { reference->setUri(fields["UR"]); } } else if("RG" == recordTag) { Header::ReadGroup readGroup; if(fields.contains("ID")) { QByteArray value = fields["SN"]; readGroupsMap.insert(value, readGroups.size()); } else { fields.insert("ID", "-1"); } if(fields.contains("CN")) { readGroup.setSequencingCenter(fields["CN"]); } if(fields.contains("DS")) { readGroup.setDescription(fields["DS"]); } if(fields.contains("DT")) { QByteArray value = fields["DT"]; QDateTime dateTime = QDateTime::fromString(value, Qt::ISODate); if(dateTime.isValid()) { readGroup.setDate(dateTime); } else { QDate date = QDate::fromString(value, Qt::ISODate); if(date.isValid()) { readGroup.setDate(date); } else { //Allow anything. //throw InvalidFormatException(BAMDbiPlugin::tr("Invalid RG-DT field value: %1").arg(QString(value))); } } } if(fields.contains("LB")) { readGroup.setLibrary(fields["LB"]); } if(fields.contains("PG")) { readGroup.setPrograms(fields["PG"]); } if(fields.contains("PI")) { QByteArray value = fields["PI"]; bool ok = false; int predictedInsertSize = value.toInt(&ok); if(ok) { readGroup.setPredictedInsertSize(predictedInsertSize); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid RG-PI field value: %1").arg(QString(value))); } } if(fields.contains("PL")) { readGroup.setPlatform(fields["PL"]); } if(fields.contains("PU")) { readGroup.setPlatformUnit(fields["PU"]); } if(fields.contains("SM")) { readGroup.setSample(fields["SM"]); } readGroups.append(readGroup); } else if("PG" == recordTag) { Header::Program program; if(!fields.contains("ID")) { fields.insert("ID", QByteArray::number(programs.size())); } programsMap.insert(fields["ID"], programs.size()); if(fields.contains("PN")) { program.setName(fields["PN"]); } if(fields.contains("CL")) { program.setCommandLine(fields["CL"]); } if(fields.contains("PP")) { previousProgramIds.append(fields["PP"]); } else { previousProgramIds.append(QByteArray()); } if(fields.contains("VN")) { program.setVersion(fields["VN"]); } programs.append(program); } } for(int index = 0;index < programs.size();index++) { const QByteArray &previousProgramId = previousProgramIds[index]; if(!previousProgramId.isEmpty()) { if(programsMap.contains(previousProgramId)) { programs[index].setPreviousId(programsMap[previousProgramId]); } else { throw InvalidFormatException(BAMDbiPlugin::tr("Invalid PG-PP field value: %1").arg(QString(previousProgramId))); } } } header.setReferences(references); header.setReadGroups(readGroups); header.setPrograms(programs); } } } // namespace BAM } // namespace U2
mfursov/ugene
src/plugins/dbi_bam/src/SamReader.cpp
C++
gpl-2.0
21,739
package com.code.taskmanager.bean; import android.graphics.drawable.Drawable; public class AppInfo { public Drawable icon; public String name; public String packagename; public boolean sysApp; public long mem; }
silvernoo/KillTask
src/com/code/taskmanager/bean/AppInfo.java
Java
gpl-2.0
219
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyostila # # 2008 Alarian # # 2008 myfingershurt # # 2008 Capo # # 2008 Glorandwarf # # 2008 QQStarS # # 2008 Blazingamer # # 2008 evilynux <evilynux@gmail.com> # # # # This program is free software; you can redistribute it and/or # # modify it under the terms of the GNU General Public License # # as published by the Free Software Foundation; either version 2 # # of the License, or (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # # MA 02110-1301, USA. # ##################################################################### from Song import Note, Tempo from Mesh import Mesh from Neck import Neck import random from copy import deepcopy from Shader import shaders from OpenGL.GL import * import math #myfingershurt: needed for multi-OS file fetching import os import Log import Song #need the base song defines as well from Instrument import * class Guitar(Instrument): def __init__(self, engine, playerObj, editorMode = False, player = 0, bass = False): Instrument.__init__(self, engine, playerObj, player) self.isDrum = False self.isBassGuitar = bass self.isVocal = False self.debugMode = False self.gameMode2p = self.engine.world.multiMode self.matchingNotes = [] self.starSpinFrameIndex = 0 self.starSpinFrames = 16 self.logClassInits = self.engine.config.get("game", "log_class_inits") if self.logClassInits == 1: Log.debug("Guitar class init...") #death_au: fixed neck size #if self.engine.theme.twoDnote == False or self.engine.theme.twoDkeys == False: #self.boardWidth = 3.6 #self.boardLength = 9.0 self.lastPlayedNotes = [] #MFH - for reverting when game discovers it implied incorrectly self.missedNotes = [] self.missedNoteNums = [] self.editorMode = editorMode #########For Animations self.Animspeed = 30#Lower value = Faster animations #For Animated Starnotes self.indexCount = 0 #Alarian, For animated hitglow self.HCountAni = False #myfingershurt: self.hopoStyle = self.engine.config.get("game", "hopo_system") self.gh2sloppy = self.engine.config.get("game", "gh2_sloppy") if self.gh2sloppy == 1: self.hopoStyle = 4 self.sfxVolume = self.engine.config.get("audio", "SFX_volume") #blazingamer self.killfx = self.engine.config.get("performance", "killfx") self.killCount = 0 self.bigMax = 1 #Get theme themename = self.engine.data.themeLabel #now theme determination logic is only in data.py: self.theme = self.engine.data.theme self.oFlash = None #myfingershurt: self.bassGrooveNeckMode = self.engine.config.get("game", "bass_groove_neck") self.starspin = self.engine.config.get("performance", "starspin") if self.twoDnote == True: #Spinning starnotes or not? #myfingershurt: allowing any non-Rock Band theme to have spinning starnotes if the SpinNotes.png is available in that theme's folder if self.starspin == True and self.theme < 2: #myfingershurt: check for SpinNotes, if not there then no animation if self.gameMode2p == 6: if engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"spinnotesbattle.png")): self.starSpinFrames = 8 else: self.starspin = False if not engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notesbattle.png")): engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png")) else: if not engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"spinnotes.png")): self.starspin = False engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png")) else: if self.gameMode2p == 6: if not engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notesbattle.png")): engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png")) else: engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png")) #mfh - adding fallback for beta option else: #MFH - can't use IOError for fallback logic for a Mesh() call... if self.engine.fileExists(os.path.join("themes", themename, "note.dae")): engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "note.dae"))) else: engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("note.dae"))) for i in range(5): if engine.loadImgDrawing(self, "notetex"+chr(97+i), os.path.join("themes", themename, "notetex_"+chr(97+i)+".png")): self.notetex = True else: self.notetex = False break if self.engine.fileExists(os.path.join("themes", themename, "star.dae")): engine.resource.load(self, "starMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "star.dae"))) else: self.starMesh = None for i in range(5): if engine.loadImgDrawing(self, "startex"+chr(97+i), os.path.join("themes", themename, "startex_"+chr(97+i)+".png")): self.startex = True else: self.startex = False break for i in range(5): if engine.loadImgDrawing(self, "staratex"+chr(97+i), os.path.join("themes", themename, "staratex_"+chr(97+i)+".png")): self.staratex = True else: self.staratex = False break if self.gameMode2p == 6: if not engine.loadImgDrawing(self, "battleFrets", os.path.join("themes", themename,"battle_frets.png")): self.battleFrets = None if self.twoDkeys == True: engine.loadImgDrawing(self, "fretButtons", os.path.join("themes",themename,"fretbuttons.png")) else: defaultKey = False #MFH - can't use IOError for fallback logic for a Mesh() call... if self.engine.fileExists(os.path.join("themes", themename, "key.dae")): engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "key.dae"))) else: engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("key.dae"))) defaultKey = True if defaultKey: self.keytex = False else: for i in range(5): if engine.loadImgDrawing(self, "keytex"+chr(97+i), os.path.join("themes", themename, "keytex_"+chr(97+i)+".png")): self.keytex = True else: self.keytex = False break #inkk: loading theme-dependant tail images #myfingershurt: must ensure the new tails don't affect the Rock Band mod... self.simpleTails = False for i in range(0,7): if not engine.loadImgDrawing(self, "tail"+str(i), os.path.join("themes",themename,"tails","tail"+str(i)+".png"), textureSize = (128, 128)): self.simpleTails = True break if not engine.loadImgDrawing(self, "taile"+str(i), os.path.join("themes",themename,"tails","taile"+str(i)+".png"), textureSize = (128, 128)): self.simpleTails = True break if not engine.loadImgDrawing(self, "btail"+str(i), os.path.join("themes",themename,"tails","btail"+str(i)+".png"), textureSize = (128, 128)): self.simpleTails = True break if not engine.loadImgDrawing(self, "btaile"+str(i), os.path.join("themes",themename,"tails","btaile"+str(i)+".png"), textureSize = (128, 128)): self.simpleTails = True break if self.simpleTails: Log.debug("Simple tails used; complex tail loading error...") if not engine.loadImgDrawing(self, "tail1", os.path.join("themes",themename,"tail1.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "tail1", "tail1.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "tail2", os.path.join("themes",themename,"tail2.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "tail2", "tail2.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "bigTail1", os.path.join("themes",themename,"bigtail1.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "bigTail1", "bigtail1.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "bigTail2", os.path.join("themes",themename,"bigtail2.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "bigTail2", "bigtail2.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "kill1", os.path.join("themes", themename, "kill1.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "kill1", "kill1.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "kill2", os.path.join("themes", themename, "kill2.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "kill2", "kill2.png", textureSize = (128, 128)) #MFH - freestyle tails (for drum fills & BREs) if not engine.loadImgDrawing(self, "freestyle1", os.path.join("themes", themename, "freestyletail1.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "freestyle1", "freestyletail1.png", textureSize = (128, 128)) if not engine.loadImgDrawing(self, "freestyle2", os.path.join("themes", themename, "freestyletail2.png"), textureSize = (128, 128)): engine.loadImgDrawing(self, "freestyle2", "freestyletail2.png", textureSize = (128, 128)) self.twoChordMax = False self.rockLevel = 0.0 self.neck = Neck(self.engine, self, playerObj) def selectPreviousString(self): self.selectedString = (self.selectedString - 1) % self.strings def selectString(self, string): self.selectedString = string % self.strings def selectNextString(self): self.selectedString = (self.selectedString + 1) % self.strings def noteBeingHeld(self): noteHeld = False for i in range(0,5): if self.hit[i] == True: noteHeld = True return noteHeld def isKillswitchPossible(self): possible = False for i in range(0,5): if self.hit[i] == True: possible = True return possible def renderTail(self, length, sustain, kill, color, flat = False, tailOnly = False, isTappable = False, big = False, fret = 0, spNote = False, freestyleTail = 0, pos = 0): #volshebnyi - if freestyleTail == 0, act normally. # if freestyleTail == 1, render an freestyle tail # if freestyleTail == 2, render highlighted freestyle tail if not self.simpleTails:#Tail Colors tailcol = (1,1,1, color[3]) else: if big == False and tailOnly == True: tailcol = (.6, .6, .6, color[3]) else: tailcol = (color) #volshebnyi - tail color when sp is active if self.starPowerActive and self.theme != 2 and not color == (0,0,0,1):#8bit c = self.fretColors[5] tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], color[3]) if flat: tailscale = (1, .1, 1) else: tailscale = None if sustain: if not length == None: size = (.08, length) if size[1] > self.boardLength: s = self.boardLength else: s = length # if freestyleTail == 1, render freestyle tail if freestyleTail == 0: #normal tail rendering #myfingershurt: so any theme containing appropriate files can use new tails if not self.simpleTails: if big == True and tailOnly == True: if kill and self.killfx == 0: zsize = .25 tex1 = self.kill1 tex2 = self.kill2 #volshebnyi - killswitch tail width and color change kEffect = ( math.sin( pos / 50 ) + 1 ) /2 size = (0.02+kEffect*0.15, s - zsize) c = [self.killColor[0],self.killColor[1],self.killColor[2]] if c != [0,0,0]: for i in range(0,3): c[i]=c[i]*kEffect+color[i]*(1-kEffect) tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1) else: zsize = .25 size = (.17, s - zsize) if self.starPowerActive and not color == (0,0,0,1): tex1 = self.btail6 tex2 = self.btaile6 else: if fret == 0: tex1 = self.btail1 tex2 = self.btaile1 elif fret == 1: tex1 = self.btail2 tex2 = self.btaile2 elif fret == 2: tex1 = self.btail3 tex2 = self.btaile3 elif fret == 3: tex1 = self.btail4 tex2 = self.btaile4 elif fret == 4: tex1 = self.btail5 tex2 = self.btaile5 else: zsize = .15 size = (.1, s - zsize) if tailOnly:#Note let go tex1 = self.tail0 tex2 = self.taile0 else: if self.starPowerActive and not color == (0,0,0,1): tex1 = self.tail6 tex2 = self.taile6 else: if fret == 0: tex1 = self.tail1 tex2 = self.taile1 elif fret == 1: tex1 = self.tail2 tex2 = self.taile2 elif fret == 2: tex1 = self.tail3 tex2 = self.taile3 elif fret == 3: tex1 = self.tail4 tex2 = self.taile4 elif fret == 4: tex1 = self.tail5 tex2 = self.taile5 else: if big == True and tailOnly == True: if kill: zsize = .25 tex1 = self.kill1 tex2 = self.kill2 #volshebnyi - killswitch tail width and color change kEffect = ( math.sin( pos / 50 ) + 1 ) /2 size = (0.02+kEffect*0.15, s - zsize) c = [self.killColor[0],self.killColor[1],self.killColor[2]] if c != [0,0,0]: for i in range(0,3): c[i]=c[i]*kEffect+color[i]*(1-kEffect) tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1) else: zsize = .25 size = (.11, s - zsize) tex1 = self.bigTail1 tex2 = self.bigTail2 else: zsize = .15 size = (.08, s - zsize) tex1 = self.tail1 tex2 = self.tail2 else: #freestyleTail > 0 # render an inactive freestyle tail (self.freestyle1 & self.freestyle2) zsize = .25 if self.freestyleActive: size = (.30, s - zsize) #was .15 else: size = (.15, s - zsize) tex1 = self.freestyle1 tex2 = self.freestyle2 if freestyleTail == 1: #glColor4f(*color) c1, c2, c3, c4 = color tailGlow = 1 - (pos - self.freestyleLastFretHitTime[fret] ) / self.freestylePeriod if tailGlow < 0: tailGlow = 0 color = (c1 + c1*2.0*tailGlow, c2 + c2*2.0*tailGlow, c3 + c3*2.0*tailGlow, c4*0.6 + c4*0.4*tailGlow) #MFH - this fades inactive tails' color darker tailcol = (color) if self.theme == 2 and freestyleTail == 0 and big and tailOnly and shaders.enable("tail"): color = (color[0]*1.5,color[1]*1.5,color[2]*1.5,1.0) shaders.setVar("color",color) if kill and self.killfx == 0: h = shaders.getVar("height") shaders.modVar("height",0.5,0.06/h-0.1) shaders.setVar("offset",(5.0-size[1],0.0)) size=(size[0]*15,size[1]) self.engine.draw3Dtex(tex1, vertex = (-size[0], 0, size[0], size[1]), texcoord = (0.0, 0.0, 1.0, 1.0), scale = tailscale, color = tailcol) self.engine.draw3Dtex(tex2, vertex = (-size[0], size[1], size[0], size[1] + (zsize)), scale = tailscale, texcoord = (0.0, 0.05, 1.0, 0.95), color = tailcol) shaders.disable() #MFH - this block of code renders the tail "beginning" - before the note, for freestyle "lanes" only #volshebnyi if freestyleTail > 0 and pos < self.freestyleStart + self.freestyleLength: self.engine.draw3Dtex(tex2, vertex = (-size[0], 0-(zsize), size[0], 0 + (.05)), scale = tailscale, texcoord = (0.0, 0.95, 1.0, 0.05), color = tailcol) if tailOnly: return def renderNote(self, length, sustain, kill, color, flat = False, tailOnly = False, isTappable = False, big = False, fret = 0, spNote = False): if flat: glScalef(1, .1, 1) if tailOnly: return if self.twoDnote == True: #myfingershurt: this should be retrieved once at init, not repeatedly in-game whenever tails are rendered. if self.notedisappear == True:#Notes keep on going when missed notecol = (1,1,1)#capo else: if flat:#Notes disappear when missed notecol = (.1,.1,.1) else: notecol = (1,1,1) tailOnly == True if self.theme < 2: if self.starspin: size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2) texSize = (fret/5.0,fret/5.0+0.2) if spNote == True: if isTappable: texY = (0.150+self.starSpinFrameIndex*0.05, 0.175+self.starSpinFrameIndex*0.05) else: texY = (0.125+self.starSpinFrameIndex*0.05, 0.150+self.starSpinFrameIndex*0.05) else: if isTappable: texY = (0.025,0.05) else: texY = (0,0.025) if self.starPowerActive: texY = (0.10,0.125) #QQstarS if isTappable: texSize = (0.2,0.4) else: texSize = (0,0.2) else: size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2) texSize = (fret/5.0,fret/5.0+0.2) if spNote == True: if isTappable: texY = (0.6, 0.8) else: texY = (0.4,0.6) else: if isTappable: texY = (0.2,0.4) else: texY = (0,0.2) if self.starPowerActive: texY = (0.8,1) if isTappable: texSize = (0.2,0.4) else: texSize = (0,0.2) elif self.theme == 2: size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2) texSize = (fret/5.0,fret/5.0+0.2) if spNote == True: if isTappable: texY = (3*0.166667, 4*0.166667) else: texY = (2*0.166667, 3*0.166667) else: if isTappable: texY = (1*0.166667, 2*0.166667) else: texY = (0, 1*0.166667) #myfingershurt: adding spNote==False conditional so that star notes can appear in overdrive if self.starPowerActive and spNote == False: if isTappable: texY = (5*0.166667, 1) else: texY = (4*0.166667, 5*0.166667) self.engine.draw3Dtex(self.noteButtons, vertex = (-size[0],size[1],size[0],-size[1]), texcoord = (texSize[0],texY[0],texSize[1],texY[1]), scale = (1,1,0), rot = (30,1,0,0), multiples = True, color = color, vertscale = .27) else: shaders.setVar("Material",color,"notes") #mesh = outer ring (black) #mesh_001 = main note (key color) #mesh_002 = top (spot or hopo if no mesh_003) #mesh_003 = hopo bump (hopo color) if spNote == True and self.starMesh is not None: meshObj = self.starMesh else: meshObj = self.noteMesh glPushMatrix() glEnable(GL_DEPTH_TEST) glDepthMask(1) glShadeModel(GL_SMOOTH) if self.noterotate: glRotatef(90, 0, 1, 0) glRotatef(-90, 1, 0, 0) if spNote == True and self.threeDspin == True: glRotate(90 + self.time/3, 0, 1, 0) #death_au: fixed 3D note colours #volshebnyi - note color when sp is active glColor4f(*color) if self.starPowerActive and self.theme != 2 and not color == (0,0,0,1): c = self.fretColors[5] glColor4f(.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1) if fret == 0: # green note glRotate(self.engine.theme.noterot[0], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[0], 0) elif fret == 1: # red note glRotate(self.engine.theme.noterot[1], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[1], 0) elif fret == 2: # yellow glRotate(self.engine.theme.noterot[2], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[2], 0) elif fret == 3:# blue note glRotate(self.engine.theme.noterot[3], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[3], 0) elif fret == 4:# blue note glRotate(self.engine.theme.noterot[4], 0, 0, 1), glTranslatef(0, self.engine.theme.notepos[4], 0) if self.staratex == True and self.starPowerActive and spNote == False: glColor3f(1,1,1) glEnable(GL_TEXTURE_2D) getattr(self,"staratex"+chr(97+fret)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) glScalef(self.boardScaleX, self.boardScaleY, 1) if isTappable: mesh = "Mesh_001" else: mesh = "Mesh" meshObj.render(mesh) if shaders.enable("notes"): shaders.setVar("isTextured",True) meshObj.render(mesh) shaders.disable() glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) elif self.notetex == True and spNote == False: glColor3f(1,1,1) glEnable(GL_TEXTURE_2D) getattr(self,"notetex"+chr(97+fret)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) glScalef(self.boardScaleX, self.boardScaleY, 1) if isTappable: mesh = "Mesh_001" else: mesh = "Mesh" meshObj.render(mesh) if shaders.enable("notes"): shaders.setVar("isTextured",True) meshObj.render(mesh) shaders.disable() glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) elif self.startex == True and spNote == True: glColor3f(1,1,1) glEnable(GL_TEXTURE_2D) getattr(self,"startex"+chr(97+fret)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) glScalef(self.boardScaleX, self.boardScaleY, 1) if isTappable: mesh = "Mesh_001" else: mesh = "Mesh" meshObj.render(mesh) if shaders.enable("notes"): shaders.setVar("isTextured",True) meshObj.render(mesh) shaders.disable() glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) else: if shaders.enable("notes"): shaders.setVar("isTextured",False) meshObj.render("Mesh_001") shaders.disable() glColor3f(self.spotColor[0], self.spotColor[1], self.spotColor[2]) if isTappable: if self.hopoColor[0] == -2: glColor4f(*color) else: glColor3f(self.hopoColor[0], self.hopoColor[1], self.hopoColor[2]) if(meshObj.find("Mesh_003")) == True: meshObj.render("Mesh_003") glColor3f(self.spotColor[0], self.spotColor[1], self.spotColor[2]) meshObj.render("Mesh_002") glColor3f(self.meshColor[0], self.meshColor[1], self.meshColor[2]) meshObj.render("Mesh") glDepthMask(0) glPopMatrix() def renderFreestyleLanes(self, visibility, song, pos): if not song: return if not song.readyToGo: return #boardWindowMin = pos - self.currentPeriod * 2 boardWindowMax = pos + self.currentPeriod * self.beatsPerBoard track = song.midiEventTrack[self.player] #MFH - render 5 freestyle tails when Song.freestyleMarkingNote comes up if self.freestyleEnabled: freestyleActive = False #for time, event in track.getEvents(boardWindowMin, boardWindowMax): for time, event in track.getEvents(pos - self.freestyleOffset , boardWindowMax + self.freestyleOffset): if isinstance(event, Song.MarkerNote): if event.number == Song.freestyleMarkingNote: length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit w = self.boardWidth / self.strings self.freestyleLength = event.length #volshebnyi self.freestyleStart = time # volshebnyi z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit if z > self.boardLength * .8: f = (self.boardLength - z) / (self.boardLength * .2) elif z < 0: f = min(1, max(0, 1 + z2)) else: f = 1.0 #MFH - must extend the tail past the first fretboard section dynamically so we don't have to render the entire length at once #volshebnyi - allow tail to move under frets if time - self.freestyleOffset < pos: freestyleActive = True if z < -1.5: length += z +1.5 z = -1.5 #MFH - render 5 freestyle tails for theFret in range(0,5): x = (self.strings / 2 - theFret) * w c = self.fretColors[theFret] color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f) glPushMatrix() glTranslatef(x, (1.0 - visibility) ** (theFret + 1), z) freestyleTailMode = 1 self.renderTail(length, sustain = True, kill = False, color = color, flat = False, tailOnly = True, isTappable = False, big = True, fret = theFret, spNote = False, freestyleTail = freestyleTailMode, pos = pos) glPopMatrix() self.freestyleActive = freestyleActive def renderNotes(self, visibility, song, pos, killswitch): if not song: return if not song.readyToGo: return # Update dynamic period self.currentPeriod = self.neckSpeed #self.targetPeriod = self.neckSpeed self.killPoints = False w = self.boardWidth / self.strings track = song.track[self.player] num = 0 enable = True starEventsInView = False renderedNotes = reversed(self.getRequiredNotesForRender(song,pos)) for time, event in renderedNotes: #for time, event in reversed(track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)): #MFH - reverse order of note rendering if isinstance(event, Tempo): self.tempoBpm = event.bpm if self.lastBpmChange > 0 and self.disableVBPM == True: continue if (pos - time > self.currentPeriod or self.lastBpmChange < 0) and time > self.lastBpmChange: self.baseBeat += (time - self.lastBpmChange) / self.currentPeriod self.targetBpm = event.bpm self.lastBpmChange = time self.neck.lastBpmChange = time self.neck.baseBeat = self.baseBeat # self.setBPM(self.targetBpm) # glorandwarf: was setDynamicBPM(self.targetBpm) continue if not isinstance(event, Note): continue if (event.noteBpm == 0.0): event.noteBpm = self.tempoBpm if self.coOpFailed: if self.coOpRestart: if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2): continue elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False Log.debug("Turning off coOpFailed. Rescue successful.") else: continue #can't break. Tempo. c = self.fretColors[event.number] x = (self.strings / 2 - event.number) * w z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit if z > self.boardLength * .8: f = (self.boardLength - z) / (self.boardLength * .2) elif z < 0: f = min(1, max(0, 1 + z2)) else: f = 1.0 #volshebnyi - hide notes in BRE zone if BRE enabled if self.freestyleEnabled and self.freestyleStart > 0: if time >= self.freestyleStart-self.freestyleOffset and time < self.freestyleStart + self.freestyleLength+self.freestyleOffset: z = -2.0 if self.twoDnote == True and not self.useFretColors: color = (1,1,1, 1 * visibility * f) else: color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f) if event.length > 120: length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit else: length = 0 flat = False tailOnly = False spNote = False #myfingershurt: user setting for starpower refill / replenish notes if self.starPowerActive: if self.spRefillMode == 0: #mode 0 = no starpower / overdrive refill notes self.spEnabled = False elif self.spRefillMode == 1 and self.theme != 2: #mode 1 = overdrive refill notes in RB themes only self.spEnabled = False elif self.spRefillMode == 2 and song.midiStyle != 1: #mode 2 = refill based on MIDI type self.spEnabled = False if event.star: #self.isStarPhrase = True starEventsInView = True if event.finalStar: self.finalStarSeen = True starEventsInView = True if event.star and self.spEnabled: spNote = True if event.finalStar and self.spEnabled: spNote = True if event.played or event.hopod: if event.flameCount < 1 and not self.starPowerGained: Log.debug("star power added") if self.gameMode2p == 6: if self.battleSuddenDeath: self.battleObjects = [1] + self.battleObjects[:2] else: self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2] self.battleGetTime = pos self.battleObjectGained = True Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects)) else: if self.starPower < 100: self.starPower += 25 if self.starPower > 100: self.starPower = 100 self.neck.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer self.starPowerGained = True if event.tappable < 2: isTappable = False else: isTappable = True # Clip the played notes to the origin #myfingershurt: this should be loaded once at init, not every render... if self.notedisappear == True:#Notes keep on going when missed ###Capo### if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue if z < 0 and not (event.played or event.hopod): color = (.6, .6, .6, .5 * visibility * f) flat = True ###endCapo### else:#Notes disappear when missed if z < 0: if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue else: color = (.6, .6, .6, .5 * visibility * f) flat = True big = False self.bigMax = 0 for i in range(0,5): if self.hit[i]: big = True self.bigMax += 1 #MFH - filter out this tail whitening when starpower notes have been disbled from a screwup if self.spEnabled and killswitch: if event.star or event.finalStar: if big == True and tailOnly == True: self.killPoints = True color = (1,1,1,1) if z + length < -1.0: continue if event.length <= 120: length = None sustain = False if event.length > (1.4 * (60000.0 / event.noteBpm) / 4): sustain = True glPushMatrix() glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z) if shaders.turnon: shaders.setVar("note_position",(x, (1.0 - visibility) ** (event.number + 1), z),"notes") if self.battleStatus[8]: renderNote = random.randint(0,2) else: renderNote = 0 if renderNote == 0: if big == True and num < self.bigMax: num += 1 self.renderNote(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, big = True, fret = event.number, spNote = spNote) else: self.renderNote(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote) glPopMatrix() if (not starEventsInView and self.finalStarSeen): self.spEnabled = True self.finalStarSeen = False self.isStarPhrase = False def renderTails(self, visibility, song, pos, killswitch): if not song: return if not song.readyToGo: return # Update dynamic period self.currentPeriod = self.neckSpeed #self.targetPeriod = self.neckSpeed self.killPoints = False w = self.boardWidth / self.strings track = song.track[self.player] num = 0 enable = True renderedNotes = self.getRequiredNotesForRender(song,pos) for time, event in renderedNotes: #for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard): if isinstance(event, Tempo): self.tempoBpm = event.bpm continue if not isinstance(event, Note): continue if (event.noteBpm == 0.0): event.noteBpm = self.tempoBpm if self.coOpFailed: if self.coOpRestart: if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2): continue elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos: self.coOpFailed = False self.coOpRestart = False Log.debug("Turning off coOpFailed. Rescue successful.") else: continue c = self.fretColors[event.number] x = (self.strings / 2 - event.number) * w z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit if z > self.boardLength * .8: f = (self.boardLength - z) / (self.boardLength * .2) elif z < 0: f = min(1, max(0, 1 + z2)) else: f = 1.0 color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f) if event.length > 120: length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit else: length = 0 flat = False tailOnly = False spNote = False #myfingershurt: user setting for starpower refill / replenish notes if event.star and self.spEnabled: spNote = True if event.finalStar and self.spEnabled: spNote = True if event.played or event.hopod: if event.flameCount < 1 and not self.starPowerGained: if self.gameMode2p == 6: if self.battleSuddenDeath: self.battleObjects = [1] + self.battleObjects[:2] else: self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2] self.battleGetTime = pos self.battleObjectGained = True Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects)) else: if self.starPower < 100: self.starPower += 25 if self.starPower > 100: self.starPower = 100 self.neck.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer self.starPowerGained = True self.neck.ocount = 0 if event.tappable < 2: isTappable = False else: isTappable = True # Clip the played notes to the origin #myfingershurt: this should be loaded once at init, not every render... if self.notedisappear == True:#Notes keep on going when missed ###Capo### if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue if z < 0 and not (event.played or event.hopod): color = (.6, .6, .6, .5 * visibility * f) flat = True ###endCapo### else:#Notes disappear when missed if z < 0: if event.played or event.hopod: tailOnly = True length += z z = 0 if length <= 0: continue else: color = (.6, .6, .6, .5 * visibility * f) flat = True big = False self.bigMax = 0 for i in range(0,5): if self.hit[i]: big = True self.bigMax += 1 if self.spEnabled and killswitch: if event.star or event.finalStar: if big == True and tailOnly == True: self.killPoints = True color = (1,1,1,1) if z + length < -1.0: continue if event.length <= 120: length = None sustain = False if event.length > (1.4 * (60000.0 / event.noteBpm) / 4): sustain = True glPushMatrix() glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z) if self.battleStatus[8]: renderNote = random.randint(0,2) else: renderNote = 0 if renderNote == 0: if big == True and num < self.bigMax: num += 1 self.renderTail(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, big = True, fret = event.number, spNote = spNote, pos = pos) else: self.renderTail(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote, pos = pos) glPopMatrix() if killswitch and self.killfx == 1: glBlendFunc(GL_SRC_ALPHA, GL_ONE) for time, event in self.playedNotes: step = self.currentPeriod / 16 t = time + event.length x = (self.strings / 2 - event.number) * w c = self.fretColors[event.number] s = t proj = 1.0 / self.currentPeriod / self.beatsPerUnit zStep = step * proj def waveForm(t): u = ((t - time) * -.1 + pos - time) / 64.0 + .0001 return (math.sin(event.number + self.time * -.01 + t * .03) + math.cos(event.number + self.time * .01 + t * .02)) * .1 + .1 + math.sin(u) / (5 * u) glBegin(GL_TRIANGLE_STRIP) f1 = 0 while t > time: if ((t-pos)*proj) < self.boardLength: z = (t - pos) * proj else: z = self.boardLength if z < 0: break f2 = min((s - t) / (6 * step), 1.0) a1 = waveForm(t) * f1 a2 = waveForm(t - step) * f2 if self.starPowerActive and self.theme != 2:#8bit glColor4f(self.spColor[0],self.spColor[1],self.spColor[2],1) #(.3,.7,.9,1) else: glColor4f(c[0], c[1], c[2], .5) glVertex3f(x - a1, 0, z) glVertex3f(x - a2, 0, z - zStep) glColor4f(1, 1, 1, .75) glVertex3f(x, 0, z) glVertex3f(x, 0, z - zStep) if self.starPowerActive and self.theme != 2:#8bit glColor4f(self.spColor[0],self.spColor[1],self.spColor[2],1) #(.3,.7,.9,1) else: glColor4f(c[0], c[1], c[2], .5) glVertex3f(x + a1, 0, z) glVertex3f(x + a2, 0, z - zStep) glVertex3f(x + a2, 0, z - zStep) glVertex3f(x - a2, 0, z - zStep) t -= step f1 = f2 glEnd() glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) def renderFrets(self, visibility, song, controls): w = self.boardWidth / self.strings size = (.22, .22) v = 1.0 - visibility glEnable(GL_DEPTH_TEST) #Hitglow color option - myfingershurt sez this should be a Guitar class global, not retrieved ever fret render in-game... for n in range(self.strings): f = self.fretWeight[n] c = self.fretColors[n] if f and (controls.getState(self.actions[0]) or controls.getState(self.actions[1])): f += 0.25 glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility) if self.fretPress: y = v + f / 6 else: y = v / 6 x = (self.strings / 2 - n) * w if self.twoDkeys == True: if self.battleStatus[4]: fretWhamOffset = self.battleWhammyNow * .15 fretColor = (1,1,1,.5) else: fretWhamOffset = 0 fretColor = (1,1,1,1) size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2.4) if self.battleStatus[3] and self.battleFrets != None and self.battleBreakString == n: texSize = (n/5.0+.042,n/5.0+0.158) size = (.30, .40) fretPos = 8 - round((self.battleBreakNow/self.battleBreakLimit) * 8) texY = (fretPos/8.0,(fretPos + 1.0)/8) self.engine.draw3Dtex(self.battleFrets, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]), coord = (x,v + .08 + fretWhamOffset,0), multiples = True,color = fretColor, depth = True) else: texSize = (n/5.0,n/5.0+0.2) texY = (0.0,1.0/3.0) if controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]): texY = (1.0/3.0,2.0/3.0) if self.hit[n] or (self.battleStatus[3] and self.battleBreakString == n): texY = (2.0/3.0,1.0) self.engine.draw3Dtex(self.fretButtons, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]), coord = (x,v + fretWhamOffset,0), multiples = True,color = fretColor, depth = True) else: if self.keyMesh: glPushMatrix() glDepthMask(1) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glShadeModel(GL_SMOOTH) glRotatef(90, 0, 1, 0) glLightfv(GL_LIGHT0, GL_POSITION, (5.0, 10.0, -10.0, 0.0)) glLightfv(GL_LIGHT0, GL_AMBIENT, (.2, .2, .2, 0.0)) glLightfv(GL_LIGHT0, GL_DIFFUSE, (1.0, 1.0, 1.0, 0.0)) glRotatef(-90, 1, 0, 0) glRotatef(-90, 0, 0, 1) if n == 0: #green fret button glRotate(self.engine.theme.keyrot[0], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[0]) elif n == 1: #red fret button glRotate(self.engine.theme.keyrot[1], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[1]) elif n == 2: #yellow fret button glRotate(self.engine.theme.keyrot[2], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[2]) elif n == 3: #blue fret button glRotate(self.engine.theme.keyrot[3], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[3]) elif n == 4: #orange fret button glRotate(self.engine.theme.keyrot[4], 0, 1, 0), glTranslatef(0, 0, self.engine.theme.keypos[4]) #Mesh - Main fret #Key_001 - Top of fret (key_color) #Key_002 - Bottom of fret (key2_color) #Glow_001 - Only rendered when a note is hit along with the glow.svg #if self.complexkey == True: # glColor4f(.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], visibility) # if self.battleStatus[4]: # glTranslatef(x, y + self.battleWhammyNow * .15, 0) # else: # glTranslatef(x, y, 0) if self.keytex == True: glColor4f(1,1,1,visibility) if self.battleStatus[4]: glTranslatef(x, y + self.battleWhammyNow * .15, 0) else: glTranslatef(x, y, 0) glEnable(GL_TEXTURE_2D) getattr(self,"keytex"+chr(97+n)).texture.bind() glMatrixMode(GL_TEXTURE) glScalef(1, -1, 1) glMatrixMode(GL_MODELVIEW) glScalef(self.boardScaleX, self.boardScaleY, 1) if f and not self.hit[n]: self.keyMesh.render("Mesh_001") elif self.hit[n]: self.keyMesh.render("Mesh_002") else: self.keyMesh.render("Mesh") glMatrixMode(GL_TEXTURE) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glDisable(GL_TEXTURE_2D) else: glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility) if self.battleStatus[4]: glTranslatef(x, y + self.battleWhammyNow * .15 + v * 6, 0) else: glTranslatef(x, y + v * 6, 0) key = self.keyMesh if(key.find("Glow_001")) == True: key.render("Mesh") if(key.find("Key_001")) == True: glColor3f(self.keyColor[0], self.keyColor[1], self.keyColor[2]) key.render("Key_001") if(key.find("Key_002")) == True: glColor3f(self.key2Color[0], self.key2Color[1], self.key2Color[2]) key.render("Key_002") else: key.render() glDisable(GL_LIGHTING) glDisable(GL_LIGHT0) glDepthMask(0) glPopMatrix() ###################### f = self.fretActivity[n] if f and self.disableFretSFX != True: if self.glowColor[0] == -1: s = 1.0 else: s = 0.0 while s < 1: ms = s * (math.sin(self.time) * .25 + 1) if self.glowColor[0] == -2: glColor3f(c[0] * (1 - ms), c[1] * (1 - ms), c[2] * (1 - ms)) else: glColor3f(self.glowColor[0] * (1 - ms), self.glowColor[1] * (1 - ms), self.glowColor[2] * (1 - ms)) glPushMatrix() if self.battleStatus[4]: glTranslatef(x, y + self.battleWhammyNow * .15, 0) else: glTranslatef(x, y, 0) glScalef(.1 + .02 * ms * f, .1 + .02 * ms * f, .1 + .02 * ms * f) glRotatef( 90, 0, 1, 0) glRotatef(-90, 1, 0, 0) glRotatef(-90, 0, 0, 1) if self.twoDkeys == False and self.keytex == False: if(self.keyMesh.find("Glow_001")) == True: key.render("Glow_001") else: key.render() glPopMatrix() s += 0.2 #Hitglow color if self.hitglow_color == 0: glowcol = (c[0], c[1], c[2])#Same as fret elif self.hitglow_color == 1: glowcol = (1, 1, 1)#Actual color in .svg-file f += 2 if self.battleStatus[4]: self.engine.draw3Dtex(self.glowDrawing, coord = (x, y + self.battleWhammyNow * .15, 0.01), rot = (f * 90 + self.time, 0, 1, 0), texcoord = (0.0, 0.0, 1.0, 1.0), vertex = (-size[0] * f, -size[1] * f, size[0] * f, size[1] * f), multiples = True, alpha = True, color = glowcol) else: self.engine.draw3Dtex(self.glowDrawing, coord = (x, y, 0.01), rot = (f * 90 + self.time, 0, 1, 0), texcoord = (0.0, 0.0, 1.0, 1.0), vertex = (-size[0] * f, -size[1] * f, size[0] * f, size[1] * f), multiples = True, alpha = True, color = glowcol) #self.hit[n] = False #MFH -- why? This prevents frets from being rendered under / before the notes... glDisable(GL_DEPTH_TEST) def renderFreestyleFlames(self, visibility, controls): if self.flameColors[0][0][0] == -1: return w = self.boardWidth / self.strings #track = song.track[self.player] size = (.22, .22) v = 1.0 - visibility if self.disableFlameSFX != True: flameLimit = 10.0 flameLimitHalf = round(flameLimit/2.0) for fretNum in range(self.strings): if controls.getState(self.keys[fretNum]) or controls.getState(self.keys[fretNum+5]): if self.freestyleHitFlameCounts[fretNum] < flameLimit: ms = math.sin(self.time) * .25 + 1 x = (self.strings / 2 - fretNum) * w ff = 1 + 0.25 y = v + ff / 6 if self.theme == 2: y -= 0.5 #flameSize = self.flameSizes[self.scoreMultiplier - 1][fretNum] flameSize = self.flameSizes[self.cappedScoreMult - 1][fretNum] if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) flameColor = self.gh3flameColor else: #MFH - fixing crash! #try: # flameColor = self.flameColors[self.scoreMultiplier - 1][fretNum] #except IndexError: flameColor = self.fretColors[fretNum] if flameColor[0] == -2: flameColor = self.fretColors[fretNum] ff += 1.5 #ff first time is 2.75 after this if self.freestyleHitFlameCounts[fretNum] < flameLimitHalf: flamecol = tuple([flameColor[ifc] for ifc in range(3)]) rbStarColor = (.1, .1, .2, .3) xOffset = (.0, - .005, .005, .0) yOffset = (.20, .255, .255, .255) scaleMod = .6 * ms * ff scaleFix = (6.0, 5.5, 5.0, 4.7) for step in range(4): if self.starPowerActive and self.theme < 2: flamecol = self.spColor else: #Default starcolor (Rockband) flamecol = (rbStarColor[step],)*3 hfCount = self.freestyleHitFlameCounts[fretNum] if step == 0: hfCount += 1 self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x+xOffset[step], y+yOffset[step], 0), rot = (90, 1, 0, 0), scale = (.25 + .05 * step + scaleMod, hfCount/scaleFix[step] + scaleMod, hfCount/scaleFix[step] + scaleMod), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) else: flameColorMod = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum]) flamecol = tuple([flameColor[ifc]*flameColorMod for ifc in range(3)]) xOffset = (.0, - .005, .005, .005) yOffset = (.35, .405, .355, .355) scaleMod = .6 * ms * ff scaleFix = (3.0, 2.5, 2.0, 1.7) for step in range(4): hfCount = self.freestyleHitFlameCounts[fretNum] if step == 0: hfCount += 1 else: if self.starPowerActive and self.theme < 2: flamecol = self.spColor else: #Default starcolor (Rockband) flamecol = (.4+.1*step,)*3 self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x+xOffset[step], y+yOffset[step], 0), rot = (90, 1, 0, 0), scale = (.25 + .05 * step + scaleMod, hfCount/scaleFix[step] + scaleMod, hfCount/scaleFix[step] + scaleMod), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) self.freestyleHitFlameCounts[fretNum] += 1 else: #MFH - flame count is done - reset it! self.freestyleHitFlameCounts[fretNum] = 0 #MFH def renderFlames(self, visibility, song, pos, controls): if not song or self.flameColors[0][0][0] == -1: return w = self.boardWidth / self.strings track = song.track[self.player] size = (.22, .22) v = 1.0 - visibility if self.disableFlameSFX != True and (self.HCountAni == True and self.HCount2 > 12): for n in range(self.strings): f = self.fretWeight[n] c = self.fretColors[n] if f and (controls.getState(self.actions[0]) or controls.getState(self.actions[1])): f += 0.25 y = v + f / 6 x = (self.strings / 2 - n) * w f = self.fretActivity[n] if f: ms = math.sin(self.time) * .25 + 1 ff = f ff += 1.2 #myfingershurt: need to cap flameSizes use of scoreMultiplier to 4x, the 5x and 6x bass groove mults cause crash: self.cappedScoreMult = min(self.scoreMultiplier,4) flameSize = self.flameSizes[self.cappedScoreMult - 1][n] if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) flameColor = self.gh3flameColor else: flameColor = self.flameColors[self.cappedScoreMult - 1][n] flameColorMod = (1.19, 1.97, 10.59) flamecol = tuple([flameColor[ifc]*flameColorMod[ifc] for ifc in range(3)]) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor else: #Default starcolor (Rockband) flamecol = (.9,.9,.9) if self.Hitanim != True: self.engine.draw3Dtex(self.hitglowDrawing, coord = (x, y + .125, 0), rot = (90, 1, 0, 0), scale = (0.5 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) #Alarian: Animated hitflames else: self.HCount = self.HCount + 1 if self.HCount > self.Animspeed-1: self.HCount = 0 HIndex = (self.HCount * 16 - (self.HCount * 16) % self.Animspeed) / self.Animspeed if HIndex > 15: HIndex = 0 texX = (HIndex*(1/16.0), HIndex*(1/16.0)+(1/16.0)) self.engine.draw3Dtex(self.hitglowAnim, coord = (x, y + .225, 0), rot = (90, 1, 0, 0), scale = (2.4, 1, 3.3), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (texX[0],0.0,texX[1],1.0), multiples = True, alpha = True, color = (1,1,1)) ff += .3 flameColorMod = (1.19, 1.78, 12.22) flamecol = tuple([flameColor[ifc]*flameColorMod[ifc] for ifc in range(3)]) if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor flamecol = self.spColor else: #Default starcolor (Rockband) flamecol = (.8,.8,.8) if self.Hitanim != True: self.engine.draw3Dtex(self.hitglow2Drawing, coord = (x, y + .25, .05), rot = (90, 1, 0, 0), scale = (.40 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) if self.disableFlameSFX != True: flameLimit = 10.0 flameLimitHalf = round(flameLimit/2.0) renderedNotes = self.getRequiredNotesForRender(song,pos) for time, event in renderedNotes: if isinstance(event, Tempo): continue if not isinstance(event, Note): continue if (event.played or event.hopod) and event.flameCount < flameLimit: ms = math.sin(self.time) * .25 + 1 x = (self.strings / 2 - event.number) * w xlightning = (self.strings / 2 - event.number)*2.2*w ff = 1 + 0.25 y = v + ff / 6 if self.theme == 2: y -= 0.5 flameSize = self.flameSizes[self.cappedScoreMult - 1][event.number] if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py) flameColor = self.gh3flameColor else: flameColor = self.flameColors[self.cappedScoreMult - 1][event.number] if flameColor[0] == -2: flameColor = self.fretColors[event.number] ff += 1.5 #ff first time is 2.75 after this if self.Hitanim2 == True: self.HCount2 = self.HCount2 + 1 self.HCountAni = False if self.HCount2 > 12: if not event.length > (1.4 * (60000.0 / event.noteBpm) / 4): self.HCount2 = 0 else: self.HCountAni = True if event.flameCount < flameLimitHalf: HIndex = (self.HCount2 * 13 - (self.HCount2 * 13) % 13) / 13 if HIndex > 12 and self.HCountAni != True: HIndex = 0 texX = (HIndex*(1/13.0), HIndex*(1/13.0)+(1/13.0)) self.engine.draw3Dtex(self.hitflamesAnim, coord = (x, y + .665, 0), rot = (90, 1, 0, 0), scale = (1.6, 1.6, 4.9), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (texX[0],0.0,texX[1],1.0), multiples = True, alpha = True, color = (1,1,1)) else: flameColorMod = 0.1 * (flameLimit - event.flameCount) flamecol = tuple([ifc*flameColorMod for ifc in flameColor]) scaleChange = (3.0,2.5,2.0,1.7) yOffset = (.35, .405, .355, .355) vtx = flameSize * ff scaleMod = .6 * ms * ff for step in range(4): #draw lightning in GH themes on SP gain if step == 0 and self.theme != 2 and event.finalStar and self.spEnabled: self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0), scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1)) continue if step == 0: yzscaleMod = event.flameCount/ scaleChange[step] else: yzscaleMod = (event.flameCount + 1)/ scaleChange[step] if self.starPowerActive: if self.theme == 0 or self.theme == 1: spcolmod = .7+step*.1 flamecol = tuple([isp*spcolmod for isp in self.spColor]) else: flamecol = (.4+step*.1,)*3#Default starcolor (Rockband) if self.hitFlamesPresent == True: self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + yOffset[step], 0), rot = (90, 1, 0, 0), scale = (.25 + step*.05 + scaleMod, yzscaleMod + scaleMod, yzscaleMod + scaleMod), vertex = (-vtx,-vtx,vtx,vtx), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) elif self.hitFlamesPresent == True and self.Hitanim2 == False: self.HCount2 = 13 self.HCountAni = True if event.flameCount < flameLimitHalf: flamecol = flameColor if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor spcolmod = .3 flamecol = tuple([isp*spcolmod for isp in self.spColor]) else: #Default starcolor (Rockband) flamecol = (.1,.1,.1) self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x, y + .20, 0), rot = (90, 1, 0, 0), scale = (.25 + .6 * ms * ff, event.flameCount/6.0 + .6 * ms * ff, event.flameCount / 6.0 + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) for i in range(3): if self.starPowerActive: if self.theme == 0 or self.theme == 1: #GH3 starcolor spcolmod = 0.4+i*0.1 flamecol = tuple([isp*spcolmod for isp in self.spColor]) else: #Default starcolor (Rockband) flamecol = (0.1+i*0.1,)*3 self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x-.005, y + .255, 0), rot = (90, 1, 0, 0), scale = (.30 + i*0.05 + .6 * ms * ff, event.flameCount/(5.5 - i*0.4) + .6 * ms * ff, event.flameCount / (5.5 - i*0.4) + .6 * ms * ff), vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) else: flameColorMod = 0.1 * (flameLimit - event.flameCount) flamecol = tuple([ifc*flameColorMod for ifc in flameColor]) scaleChange = (3.0,2.5,2.0,1.7) yOffset = (.35, .405, .355, .355) vtx = flameSize * ff scaleMod = .6 * ms * ff for step in range(4): #draw lightning in GH themes on SP gain if step == 0 and self.theme != 2 and event.finalStar and self.spEnabled: self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0), scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1)) continue if step == 0: yzscaleMod = event.flameCount/ scaleChange[step] else: yzscaleMod = (event.flameCount + 1)/ scaleChange[step] if self.starPowerActive: if self.theme == 0 or self.theme == 1: spcolmod = .7+step*.1 flamecol = tuple([isp*spcolmod for isp in self.spColor]) else: flamecol = (.4+step*.1,)*3#Default starcolor (Rockband) self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + yOffset[step], 0), rot = (90, 1, 0, 0), scale = (.25 + step*.05 + scaleMod, yzscaleMod + scaleMod, yzscaleMod + scaleMod), vertex = (-vtx,-vtx,vtx,vtx), texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol) event.flameCount += 1 def render(self, visibility, song, pos, controls, killswitch): if shaders.turnon: shaders.globals["dfActive"] = self.drumFillsActive shaders.globals["breActive"] = self.freestyleActive shaders.globals["rockLevel"] = self.rockLevel if shaders.globals["killswitch"] != killswitch: shaders.globals["killswitchPos"] = pos shaders.globals["killswitch"] = killswitch shaders.modVar("height",0.2,0.2,1.0,"tail") if not self.starNotesSet == True: self.totalNotes = 0 for time, event in song.track[self.player].getAllEvents(): if not isinstance(event, Note): continue self.totalNotes += 1 stars = [] maxStars = [] maxPhrase = self.totalNotes/120 for q in range(0,maxPhrase): for n in range(0,10): stars.append(self.totalNotes/maxPhrase*(q)+n+maxPhrase/4) maxStars.append(self.totalNotes/maxPhrase*(q)+10+maxPhrase/4) i = 0 for time, event in song.track[self.player].getAllEvents(): if not isinstance(event, Note): continue for a in stars: if i == a: self.starNotes.append(time) event.star = True for a in maxStars: if i == a: self.maxStars.append(time) event.finalStar = True i += 1 for time, event in song.track[self.player].getAllEvents(): if not isinstance(event, Note): continue for q in self.starNotes: if time == q: event.star = True for q in self.maxStars: #if time == q and not event.finalStar: # event.star = True if time == q: #MFH - no need to mark only the final SP phrase note as the finalStar as in drums, they will be hit simultaneously here. event.finalStar = True self.starNotesSet = True if not (self.coOpFailed and not self.coOpRestart): glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_COLOR_MATERIAL) if self.leftyMode: if not self.battleStatus[6]: glScalef(-1, 1, 1) elif self.battleStatus[6]: glScalef(-1, 1, 1) if self.freestyleActive: self.renderTails(visibility, song, pos, killswitch) self.renderNotes(visibility, song, pos, killswitch) self.renderFreestyleLanes(visibility, song, pos) #MFH - render the lanes on top of the notes. self.renderFrets(visibility, song, controls) if self.hitFlamesPresent: #MFH - only if present! self.renderFreestyleFlames(visibility, controls) #MFH - freestyle hit flames else: self.renderTails(visibility, song, pos, killswitch) if self.fretsUnderNotes: #MFH if self.twoDnote == True: self.renderFrets(visibility, song, controls) self.renderNotes(visibility, song, pos, killswitch) else: self.renderNotes(visibility, song, pos, killswitch) self.renderFrets(visibility, song, controls) else: self.renderNotes(visibility, song, pos, killswitch) self.renderFrets(visibility, song, controls) self.renderFreestyleLanes(visibility, song, pos) #MFH - render the lanes on top of the notes. if self.hitFlamesPresent: #MFH - only if present! self.renderFlames(visibility, song, pos, controls) #MFH - only when freestyle inactive! if self.leftyMode: if not self.battleStatus[6]: glScalef(-1, 1, 1) elif self.battleStatus[6]: glScalef(-1, 1, 1) #return notes #MFH - corrected and optimized: #def getRequiredNotesMFH(self, song, pos): def getRequiredNotesMFH(self, song, pos, hopoTroubleCheck = False): if self.battleStatus[2] and self.difficulty != 0: if pos < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or pos > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength: song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue] else: song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1] track = song.track[self.player] if hopoTroubleCheck: notes = [(time, event) for time, event in track.getEvents(pos, pos + (self.earlyMargin*2)) if isinstance(event, Note)] notes = [(time, event) for time, event in notes if not time==pos] #MFH - filter out the problem note that caused this check! else: notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)] notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)] notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))] sorted(notes, key=lambda x: x[0]) if self.battleStatus[7]: notes = self.getDoubleNotes(notes) return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number.... def getDoubleNotes(self, notes): if self.battleStatus[7] and notes != []: notes = sorted(notes, key=lambda x: x[0]) curTime = 0 tempnotes = [] tempnumbers = [] tempnote = None curNumbers = [] noteCount = 0 for time, note in notes: noteCount += 1 if not isinstance(note, Note): if noteCount == len(notes) and len(curNumbers) < 3 and len(curNumbers) > 0: maxNote = curNumbers[0] minNote = curNumbers[0] for i in range(0, len(curNumbers)): if curNumbers[i] > maxNote: maxNote = curNumbers[i] if curNumbers[i] < minNote: minNote = curNumbers[i] curNumbers = [] if maxNote < 4: tempnumbers.append(maxNote + 1) elif minNote > 0: tempnumbers.append(minNote - 1) else: tempnumbers.append(2) elif noteCount == len(notes) and len(curNumbers) > 2: tempnumbers.append(-1) curNumbers = [] continue if time != curTime: if curTime != 0 and len(curNumbers) < 3: maxNote = curNumbers[0] minNote = curNumbers[0] for i in range(0, len(curNumbers)): if curNumbers[i] > maxNote: maxNote = curNumbers[i] if curNumbers[i] < minNote: minNote = curNumbers[i] curNumbers = [] if maxNote < 4: tempnumbers.append(maxNote + 1) elif minNote > 0: tempnumbers.append(minNote - 1) else: tempnumbers.append(2) elif (curTime != 0 or noteCount == len(notes)) and len(curNumbers) > 2: tempnumbers.append(-1) curNumbers = [] tempnotes.append((time,deepcopy(note))) curTime = time curNumbers.append(note.number) if noteCount == len(notes) and len(curNumbers) < 3: maxNote = curNumbers[0] minNote = curNumbers[0] for i in range(0, len(curNumbers)): if curNumbers[i] > maxNote: maxNote = curNumbers[i] if curNumbers[i] < minNote: minNote = curNumbers[i] curNumbers = [] if maxNote < 4: tempnumbers.append(maxNote + 1) elif minNote > 0: tempnumbers.append(minNote - 1) else: tempnumbers.append(2) elif noteCount == len(notes) and len(curNumbers) > 2: tempnumbers.append(-1) curNumbers = [] else: curNumbers.append(note.number) if noteCount == len(notes) and len(curNumbers) < 3: maxNote = curNumbers[0] minNote = curNumbers[0] for i in range(0, len(curNumbers)): if curNumbers[i] > maxNote: maxNote = curNumbers[i] if curNumbers[i] < minNote: minNote = curNumbers[i] curNumbers = [] if maxNote < 4: tempnumbers.append(maxNote + 1) elif minNote > 0: tempnumbers.append(minNote - 1) else: tempnumbers.append(2) elif noteCount == len(notes) and len(curNumbers) > 2: tempnumbers.append(-1) curNumbers = [] noteCount = 0 for time, note in tempnotes: if tempnumbers[noteCount] != -1: note.number = tempnumbers[noteCount] noteCount += 1 if time > self.battleStartTimes[7] + self.currentPeriod * self.beatsPerBoard and time < self.battleStartTimes[7] - self.currentPeriod * self.beatsPerBoard + self.battleDoubleLength: notes.append((time,note)) else: noteCount += 1 return sorted(notes, key=lambda x: x[0]) def getRequiredNotesForRender(self, song, pos): if self.battleStatus[2] and self.difficulty != 0: Log.debug(self.battleDiffUpValue) song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue] track0 = song.track[self.player] notes0 = [(time, event) for time, event in track0.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)] song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1] track1 = song.track[self.player] notes1 = [(time, event) for time, event in track1.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)] notes = [] for time,note in notes0: if time < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or time > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength: notes.append((time,note)) for time,note in notes1: if time > self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard and time < self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength: notes.append((time,note)) notes0 = None notes1 = None track0 = None track1 = None notes = sorted(notes, key=lambda x: x[0]) #Log.debug(notes) else: track = song.track[self.player] notes = [(time, event) for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)] if self.battleStatus[7]: notes = self.getDoubleNotes(notes) return notes #MFH - corrected and optimized: def getRequiredNotesForJurgenOnTime(self, song, pos): track = song.track[self.player] notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + 30) if isinstance(event, Note)] notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)] if self.battleStatus[7]: notes = self.getDoubleNotes(notes) return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number.... def controlsMatchNotes(self, controls, notes): # no notes? if not notes: return False # check each valid chord chords = {} for time, note in notes: if not time in chords: chords[time] = [] chords[time].append((time, note)) #Make sure the notes are in the right time order chordlist = chords.values() chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0])) twochord = 0 for chord in chordlist: # matching keys? requiredKeys = [note.number for time, note in chord] requiredKeys = self.uniqify(requiredKeys) if len(requiredKeys) > 2 and self.twoChordMax == True: twochord = 0 for k in self.keys: if controls.getState(k): twochord += 1 if twochord == 2: skipped = len(requiredKeys) - 2 requiredKeys = [min(requiredKeys), max(requiredKeys)] else: twochord = 0 for n in range(self.strings): if n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])): return False if not n in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])): # The lower frets can be held down if n > max(requiredKeys): return False if twochord != 0: if twochord != 2: for time, note in chord: note.played = True else: self.twoChordApply = True for time, note in chord: note.skipped = True chord[0][1].skipped = False chord[-1][1].skipped = False chord[0][1].played = True chord[-1][1].played = True if twochord == 2: self.twoChord += skipped return True def controlsMatchNotes2(self, controls, notes, hopo = False): # no notes? if not notes: return False # check each valid chord chords = {} for time, note in notes: if note.hopod == True and (controls.getState(self.keys[note.number]) or controls.getState(self.keys[note.number + 5])): #if hopo == True and controls.getState(self.keys[note.number]): self.playedNotes = [] return True if not time in chords: chords[time] = [] chords[time].append((time, note)) #Make sure the notes are in the right time order chordlist = chords.values() chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0])) twochord = 0 for chord in chordlist: # matching keys? requiredKeys = [note.number for time, note in chord] requiredKeys = self.uniqify(requiredKeys) if len(requiredKeys) > 2 and self.twoChordMax == True: twochord = 0 for n, k in enumerate(self.keys): if controls.getState(k): twochord += 1 if twochord == 2: skipped = len(requiredKeys) - 2 requiredKeys = [min(requiredKeys), max(requiredKeys)] else: twochord = 0 for n in range(self.strings): if n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])): return False if not n in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])): # The lower frets can be held down if hopo == False and n >= min(requiredKeys): return False if twochord != 0: if twochord != 2: for time, note in chord: note.played = True else: self.twoChordApply = True for time, note in chord: note.skipped = True chord[0][1].skipped = False chord[-1][1].skipped = False chord[0][1].played = True chord[-1][1].played = True if twochord == 2: self.twoChord += skipped return True def controlsMatchNotes3(self, controls, notes, hopo = False): # no notes? if not notes: return False # check each valid chord chords = {} for time, note in notes: if note.hopod == True and (controls.getState(self.keys[note.number]) or controls.getState(self.keys[note.number + 5])): #if hopo == True and controls.getState(self.keys[note.number]): self.playedNotes = [] return True if not time in chords: chords[time] = [] chords[time].append((time, note)) #Make sure the notes are in the right time order chordlist = chords.values() #chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0])) chordlist.sort(key=lambda a: a[0][0]) self.missedNotes = [] self.missedNoteNums = [] twochord = 0 for chord in chordlist: # matching keys? requiredKeys = [note.number for time, note in chord] requiredKeys = self.uniqify(requiredKeys) if len(requiredKeys) > 2 and self.twoChordMax == True: twochord = 0 for n, k in enumerate(self.keys): if controls.getState(k): twochord += 1 if twochord == 2: skipped = len(requiredKeys) - 2 requiredKeys = [min(requiredKeys), max(requiredKeys)] else: twochord = 0 if (self.controlsMatchNote3(controls, chord, requiredKeys, hopo)): if twochord != 2: for time, note in chord: note.played = True else: self.twoChordApply = True for time, note in chord: note.skipped = True chord[0][1].skipped = False chord[-1][1].skipped = False chord[0][1].played = True chord[-1][1].played = True break if hopo == True: break self.missedNotes.append(chord) else: self.missedNotes = [] self.missedNoteNums = [] for chord in self.missedNotes: for time, note in chord: if self.debugMode: self.missedNoteNums.append(note.number) note.skipped = True note.played = False if twochord == 2: self.twoChord += skipped return True #MFH - special function for HOPO intentions checking def controlsMatchNextChord(self, controls, notes): # no notes? if not notes: return False # check each valid chord chords = {} for time, note in notes: if not time in chords: chords[time] = [] chords[time].append((time, note)) #Make sure the notes are in the right time order chordlist = chords.values() chordlist.sort(key=lambda a: a[0][0]) twochord = 0 for chord in chordlist: # matching keys? self.requiredKeys = [note.number for time, note in chord] self.requiredKeys = self.uniqify(self.requiredKeys) if len(self.requiredKeys) > 2 and self.twoChordMax == True: twochord = 0 self.twoChordApply = True for n, k in enumerate(self.keys): if controls.getState(k): twochord += 1 if twochord == 2: skipped = len(self.requiredKeys) - 2 self.requiredKeys = [min(self.requiredKeys), max(self.requiredKeys)] else: twochord = 0 if (self.controlsMatchNote3(controls, chord, self.requiredKeys, False)): return True else: return False def uniqify(self, seq, idfun=None): # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) # in old Python versions: # if seen.has_key(marker) # but in new ones: if marker in seen: continue seen[marker] = 1 result.append(item) return result def controlsMatchNote3(self, controls, chordTuple, requiredKeys, hopo): if len(chordTuple) > 1: #Chords must match exactly for n in range(self.strings): if (n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]))) or (n not in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]))): return False else: #Single Note must match that note requiredKey = requiredKeys[0] if not controls.getState(self.keys[requiredKey]) and not controls.getState(self.keys[requiredKey+5]): return False #myfingershurt: this is where to filter out higher frets held when HOPOing: if hopo == False or self.hopoStyle == 2 or self.hopoStyle == 3: #Check for higher numbered frets if not a HOPO or if GH2 strict mode for n, k in enumerate(self.keys): if (n > requiredKey and n < 5) or (n > 4 and n > requiredKey + 5): #higher numbered frets cannot be held if controls.getState(k): return False return True def areNotesTappable(self, notes): if not notes: return for time, note in notes: if note.tappable > 1: return True return False def startPick(self, song, pos, controls, hopo = False): if hopo == True: res = startPick2(song, pos, controls, hopo) return res if not song: return False if not song.readyToGo: return False self.playedNotes = [] self.matchingNotes = self.getRequiredNotes(song, pos) if self.controlsMatchNotes(controls, self.matchingNotes): self.pickStartPos = pos for time, note in self.matchingNotes: if note.skipped == True: continue self.pickStartPos = max(self.pickStartPos, time) note.played = True self.playedNotes.append([time, note]) if self.guitarSolo: self.currentGuitarSoloHitNotes += 1 return True return False def startPick2(self, song, pos, controls, hopo = False): if not song: return False if not song.readyToGo: return False self.playedNotes = [] self.matchingNotes = self.getRequiredNotes2(song, pos, hopo) if self.controlsMatchNotes2(controls, self.matchingNotes, hopo): self.pickStartPos = pos for time, note in self.matchingNotes: if note.skipped == True: continue self.pickStartPos = max(self.pickStartPos, time) if hopo: note.hopod = True else: note.played = True if note.tappable == 1 or note.tappable == 2: self.hopoActive = time self.wasLastNoteHopod = True elif note.tappable == 3: self.hopoActive = -time self.wasLastNoteHopod = True else: self.hopoActive = 0 self.wasLastNoteHopod = False self.playedNotes.append([time, note]) if self.guitarSolo: self.currentGuitarSoloHitNotes += 1 self.hopoLast = note.number return True return False def startPick3(self, song, pos, controls, hopo = False): if not song: return False if not song.readyToGo: return False self.lastPlayedNotes = self.playedNotes self.playedNotes = [] self.matchingNotes = self.getRequiredNotesMFH(song, pos) self.controlsMatchNotes3(controls, self.matchingNotes, hopo) #myfingershurt for time, note in self.matchingNotes: if note.played != True: continue if shaders.turnon: shaders.var["fret"][self.player][note.number]=shaders.time() shaders.var["fretpos"][self.player][note.number]=pos self.pickStartPos = pos self.pickStartPos = max(self.pickStartPos, time) if hopo: note.hopod = True else: note.played = True #self.wasLastNoteHopod = False if note.tappable == 1 or note.tappable == 2: self.hopoActive = time self.wasLastNoteHopod = True elif note.tappable == 3: self.hopoActive = -time self.wasLastNoteHopod = True if hopo: #MFH - you just tapped a 3 - make a note of it. (har har) self.hopoProblemNoteNum = note.number self.sameNoteHopoString = True else: self.hopoActive = 0 self.wasLastNoteHopod = False self.hopoLast = note.number self.playedNotes.append([time, note]) if self.guitarSolo: self.currentGuitarSoloHitNotes += 1 #myfingershurt: be sure to catch when a chord is played if len(self.playedNotes) > 1: lastPlayedNote = None for time, note in self.playedNotes: if isinstance(lastPlayedNote, Note): if note.tappable == 1 and lastPlayedNote.tappable == 1: self.LastStrumWasChord = True #self.sameNoteHopoString = False else: self.LastStrumWasChord = False lastPlayedNote = note elif len(self.playedNotes) > 0: #ensure at least that a note was played here self.LastStrumWasChord = False if len(self.playedNotes) != 0: return True return False def soloFreestylePick(self, song, pos, controls): numHits = 0 for theFret in range(5): self.freestyleHit[theFret] = controls.getState(self.keys[theFret+5]) if self.freestyleHit[theFret]: if shaders.turnon: shaders.var["fret"][self.player][theFret]=shaders.time() shaders.var["fretpos"][self.player][theFret]=pos numHits += 1 return numHits #MFH - TODO - handle freestyle picks here def freestylePick(self, song, pos, controls): numHits = 0 #if not song: # return numHits if not controls.getState(self.actions[0]) and not controls.getState(self.actions[1]): return 0 for theFret in range(5): self.freestyleHit[theFret] = controls.getState(self.keys[theFret]) if self.freestyleHit[theFret]: if shaders.turnon: shaders.var["fret"][self.player][theFret]=shaders.time() shaders.var["fretpos"][self.player][theFret]=pos numHits += 1 return numHits def endPick(self, pos): for time, note in self.playedNotes: if time + note.length > pos + self.noteReleaseMargin: self.playedNotes = [] return False self.playedNotes = [] return True def getPickLength(self, pos): if not self.playedNotes: return 0.0 # The pick length is limited by the played notes pickLength = pos - self.pickStartPos for time, note in self.playedNotes: pickLength = min(pickLength, note.length) return pickLength def coOpRescue(self, pos): self.coOpRestart = True #initializes Restart Timer self.coOpRescueTime = pos self.starPower = 0 Log.debug("Rescued at " + str(pos)) def run(self, ticks, pos, controls): if not self.paused: self.time += ticks #MFH - Determine which frame to display for starpower notes if self.starspin: self.indexCount = self.indexCount + 1 if self.indexCount > self.Animspeed-1: self.indexCount = 0 self.starSpinFrameIndex = (self.indexCount * self.starSpinFrames - (self.indexCount * self.starSpinFrames) % self.Animspeed) / self.Animspeed if self.starSpinFrameIndex > self.starSpinFrames - 1: self.starSpinFrameIndex = 0 #myfingershurt: must not decrease SP if paused. if self.starPowerActive == True and self.paused == False: self.starPower -= ticks/self.starPowerDecreaseDivisor if self.starPower <= 0: self.starPower = 0 self.starPowerActive = False #MFH - call to play star power deactivation sound, if it exists (if not play nothing) if self.engine.data.starDeActivateSoundFound: #self.engine.data.starDeActivateSound.setVolume(self.sfxVolume) self.engine.data.starDeActivateSound.play() # update frets if self.editorMode: if (controls.getState(self.actions[0]) or controls.getState(self.actions[1])): for i in range(self.strings): if controls.getState(self.keys[i]) or controls.getState(self.keys[i+5]): activeFrets.append(i) activeFrets = activeFrets or [self.selectedString] else: activeFrets = [] else: activeFrets = [note.number for time, note in self.playedNotes] for n in range(self.strings): if controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]) or (self.editorMode and self.selectedString == n): self.fretWeight[n] = 0.5 else: self.fretWeight[n] = max(self.fretWeight[n] - ticks / 64.0, 0.0) if n in activeFrets: self.fretActivity[n] = min(self.fretActivity[n] + ticks / 32.0, 1.0) else: self.fretActivity[n] = max(self.fretActivity[n] - ticks / 64.0, 0.0) #MFH - THIS is where note sustains should be determined... NOT in renderNotes / renderFrets / renderFlames -.- if self.fretActivity[n]: self.hit[n] = True else: self.hit[n] = False if self.vbpmLogicType == 0: #MFH - VBPM (old) if self.currentBpm != self.targetBpm: diff = self.targetBpm - self.currentBpm if (round((diff * .03), 4) != 0): self.currentBpm = round(self.currentBpm + (diff * .03), 4) else: self.currentBpm = self.targetBpm self.setBPM(self.currentBpm) # glorandwarf: was setDynamicBPM(self.currentBpm) for time, note in self.playedNotes: if pos > time + note.length: return False return True
cherbib/fofix
src/Guitar.py
Python
gpl-2.0
95,964
#include "hw/hw.h" #include "hw/usb.h" #include "hw/qdev.h" #include "sysemu/sysemu.h" #include "monitor/monitor.h" #include "trace.h" static void usb_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent); static char *usb_get_dev_path(DeviceState *dev); static char *usb_get_fw_dev_path(DeviceState *qdev); static int usb_qdev_exit(DeviceState *qdev); static Property usb_props[] = { DEFINE_PROP_STRING("port", USBDevice, port_path), DEFINE_PROP_BIT("full-path", USBDevice, flags, USB_DEV_FLAG_FULL_PATH, true), DEFINE_PROP_END_OF_LIST() }; static void usb_bus_class_init(ObjectClass *klass, void *data) { BusClass *k = BUS_CLASS(klass); k->print_dev = usb_bus_dev_print; k->get_dev_path = usb_get_dev_path; k->get_fw_dev_path = usb_get_fw_dev_path; } static const TypeInfo usb_bus_info = { .name = TYPE_USB_BUS, .parent = TYPE_BUS, .instance_size = sizeof(USBBus), .class_init = usb_bus_class_init, }; static int next_usb_bus = 0; static QTAILQ_HEAD(, USBBus) busses = QTAILQ_HEAD_INITIALIZER(busses); static int usb_device_post_load(void *opaque, int version_id) { USBDevice *dev = opaque; if (dev->state == USB_STATE_NOTATTACHED) { dev->attached = 0; } else { dev->attached = 1; } return 0; } const VMStateDescription vmstate_usb_device = { .name = "USBDevice", .version_id = 1, .minimum_version_id = 1, .post_load = usb_device_post_load, .fields = (VMStateField []) { VMSTATE_UINT8(addr, USBDevice), VMSTATE_INT32(state, USBDevice), VMSTATE_INT32(remote_wakeup, USBDevice), VMSTATE_INT32(setup_state, USBDevice), VMSTATE_INT32(setup_len, USBDevice), VMSTATE_INT32(setup_index, USBDevice), VMSTATE_UINT8_ARRAY(setup_buf, USBDevice, 8), VMSTATE_END_OF_LIST(), } }; void usb_bus_new(USBBus *bus, USBBusOps *ops, DeviceState *host) { qbus_create_inplace(&bus->qbus, TYPE_USB_BUS, host, NULL); bus->ops = ops; bus->busnr = next_usb_bus++; bus->qbus.allow_hotplug = 1; /* Yes, we can */ QTAILQ_INIT(&bus->free); QTAILQ_INIT(&bus->used); QTAILQ_INSERT_TAIL(&busses, bus, next); } USBBus *usb_bus_find(int busnr) { USBBus *bus; if (-1 == busnr) return QTAILQ_FIRST(&busses); QTAILQ_FOREACH(bus, &busses, next) { if (bus->busnr == busnr) return bus; } return NULL; } static int usb_device_init(USBDevice *dev) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->init) { return klass->init(dev); } return 0; } USBDevice *usb_device_find_device(USBDevice *dev, uint8_t addr) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->find_device) { return klass->find_device(dev, addr); } return NULL; } static void usb_device_handle_destroy(USBDevice *dev) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->handle_destroy) { klass->handle_destroy(dev); } } void usb_device_cancel_packet(USBDevice *dev, USBPacket *p) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->cancel_packet) { klass->cancel_packet(dev, p); } } void usb_device_handle_attach(USBDevice *dev) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->handle_attach) { klass->handle_attach(dev); } } void usb_device_handle_reset(USBDevice *dev) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->handle_reset) { klass->handle_reset(dev); } } void usb_device_handle_control(USBDevice *dev, USBPacket *p, int request, int value, int index, int length, uint8_t *data) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->handle_control) { klass->handle_control(dev, p, request, value, index, length, data); } } void usb_device_handle_data(USBDevice *dev, USBPacket *p) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->handle_data) { klass->handle_data(dev, p); } } const char *usb_device_get_product_desc(USBDevice *dev) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); return klass->product_desc; } const USBDesc *usb_device_get_usb_desc(USBDevice *dev) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (dev->usb_desc) { return dev->usb_desc; } return klass->usb_desc; } void usb_device_set_interface(USBDevice *dev, int interface, int alt_old, int alt_new) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->set_interface) { klass->set_interface(dev, interface, alt_old, alt_new); } } void usb_device_flush_ep_queue(USBDevice *dev, USBEndpoint *ep) { USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev); if (klass->flush_ep_queue) { klass->flush_ep_queue(dev, ep); } } static int usb_qdev_init(DeviceState *qdev) { USBDevice *dev = USB_DEVICE(qdev); int rc; pstrcpy(dev->product_desc, sizeof(dev->product_desc), usb_device_get_product_desc(dev)); dev->auto_attach = 1; QLIST_INIT(&dev->strings); usb_ep_init(dev); rc = usb_claim_port(dev); if (rc != 0) { return rc; } rc = usb_device_init(dev); if (rc != 0) { usb_release_port(dev); return rc; } if (dev->auto_attach) { rc = usb_device_attach(dev); if (rc != 0) { usb_qdev_exit(qdev); return rc; } } return 0; } static int usb_qdev_exit(DeviceState *qdev) { USBDevice *dev = USB_DEVICE(qdev); if (dev->attached) { usb_device_detach(dev); } usb_device_handle_destroy(dev); if (dev->port) { usb_release_port(dev); } return 0; } typedef struct LegacyUSBFactory { const char *name; const char *usbdevice_name; USBDevice *(*usbdevice_init)(USBBus *bus, const char *params); } LegacyUSBFactory; static GSList *legacy_usb_factory; void usb_legacy_register(const char *typename, const char *usbdevice_name, USBDevice *(*usbdevice_init)(USBBus *bus, const char *params)) { if (usbdevice_name) { LegacyUSBFactory *f = g_malloc0(sizeof(*f)); f->name = typename; f->usbdevice_name = usbdevice_name; f->usbdevice_init = usbdevice_init; legacy_usb_factory = g_slist_append(legacy_usb_factory, f); } } USBDevice *usb_create(USBBus *bus, const char *name) { DeviceState *dev; dev = qdev_create(&bus->qbus, name); return USB_DEVICE(dev); } USBDevice *usb_create_simple(USBBus *bus, const char *name) { USBDevice *dev = usb_create(bus, name); int rc; if (!dev) { error_report("Failed to create USB device '%s'", name); return NULL; } rc = qdev_init(&dev->qdev); if (rc < 0) { error_report("Failed to initialize USB device '%s'", name); return NULL; } return dev; } static void usb_fill_port(USBPort *port, void *opaque, int index, USBPortOps *ops, int speedmask) { port->opaque = opaque; port->index = index; port->ops = ops; port->speedmask = speedmask; usb_port_location(port, NULL, index + 1); } void usb_register_port(USBBus *bus, USBPort *port, void *opaque, int index, USBPortOps *ops, int speedmask) { usb_fill_port(port, opaque, index, ops, speedmask); QTAILQ_INSERT_TAIL(&bus->free, port, next); bus->nfree++; } int usb_register_companion(const char *masterbus, USBPort *ports[], uint32_t portcount, uint32_t firstport, void *opaque, USBPortOps *ops, int speedmask) { USBBus *bus; int i; QTAILQ_FOREACH(bus, &busses, next) { if (strcmp(bus->qbus.name, masterbus) == 0) { break; } } if (!bus || !bus->ops->register_companion) { qerror_report(QERR_INVALID_PARAMETER_VALUE, "masterbus", "an USB masterbus"); if (bus) { error_printf_unless_qmp( "USB bus '%s' does not allow companion controllers\n", masterbus); } return -1; } for (i = 0; i < portcount; i++) { usb_fill_port(ports[i], opaque, i, ops, speedmask); } return bus->ops->register_companion(bus, ports, portcount, firstport); } void usb_port_location(USBPort *downstream, USBPort *upstream, int portnr) { if (upstream) { snprintf(downstream->path, sizeof(downstream->path), "%s.%d", upstream->path, portnr); } else { snprintf(downstream->path, sizeof(downstream->path), "%d", portnr); } } void usb_unregister_port(USBBus *bus, USBPort *port) { if (port->dev) qdev_free(&port->dev->qdev); QTAILQ_REMOVE(&bus->free, port, next); bus->nfree--; } int usb_claim_port(USBDevice *dev) { USBBus *bus = usb_bus_from_device(dev); USBPort *port; assert(dev->port == NULL); if (dev->port_path) { QTAILQ_FOREACH(port, &bus->free, next) { if (strcmp(port->path, dev->port_path) == 0) { break; } } if (port == NULL) { error_report("Error: usb port %s (bus %s) not found (in use?)", dev->port_path, bus->qbus.name); return -1; } } else { if (bus->nfree == 1 && strcmp(object_get_typename(OBJECT(dev)), "usb-hub") != 0) { /* Create a new hub and chain it on */ usb_create_simple(bus, "usb-hub"); } if (bus->nfree == 0) { error_report("Error: tried to attach usb device %s to a bus " "with no free ports", dev->product_desc); return -1; } port = QTAILQ_FIRST(&bus->free); } trace_usb_port_claim(bus->busnr, port->path); QTAILQ_REMOVE(&bus->free, port, next); bus->nfree--; dev->port = port; port->dev = dev; QTAILQ_INSERT_TAIL(&bus->used, port, next); bus->nused++; return 0; } void usb_release_port(USBDevice *dev) { USBBus *bus = usb_bus_from_device(dev); USBPort *port = dev->port; assert(port != NULL); trace_usb_port_release(bus->busnr, port->path); QTAILQ_REMOVE(&bus->used, port, next); bus->nused--; dev->port = NULL; port->dev = NULL; QTAILQ_INSERT_TAIL(&bus->free, port, next); bus->nfree++; } int usb_device_attach(USBDevice *dev) { USBBus *bus = usb_bus_from_device(dev); USBPort *port = dev->port; assert(port != NULL); assert(!dev->attached); trace_usb_port_attach(bus->busnr, port->path); if (!(port->speedmask & dev->speedmask)) { error_report("Warning: speed mismatch trying to attach " "usb device %s to bus %s", dev->product_desc, bus->qbus.name); return -1; } dev->attached++; usb_attach(port); return 0; } int usb_device_detach(USBDevice *dev) { USBBus *bus = usb_bus_from_device(dev); USBPort *port = dev->port; assert(port != NULL); assert(dev->attached); trace_usb_port_detach(bus->busnr, port->path); usb_detach(port); dev->attached--; return 0; } int usb_device_delete_addr(int busnr, int addr) { USBBus *bus; USBPort *port; USBDevice *dev; bus = usb_bus_find(busnr); if (!bus) return -1; QTAILQ_FOREACH(port, &bus->used, next) { if (port->dev->addr == addr) break; } if (!port) return -1; dev = port->dev; qdev_free(&dev->qdev); return 0; } static const char *usb_speed(unsigned int speed) { static const char *txt[] = { [ USB_SPEED_LOW ] = "1.5", [ USB_SPEED_FULL ] = "12", [ USB_SPEED_HIGH ] = "480", [ USB_SPEED_SUPER ] = "5000", }; if (speed >= ARRAY_SIZE(txt)) return "?"; return txt[speed]; } static void usb_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent) { USBDevice *dev = USB_DEVICE(qdev); USBBus *bus = usb_bus_from_device(dev); monitor_printf(mon, "%*saddr %d.%d, port %s, speed %s, name %s%s\n", indent, "", bus->busnr, dev->addr, dev->port ? dev->port->path : "-", usb_speed(dev->speed), dev->product_desc, dev->attached ? ", attached" : ""); } static char *usb_get_dev_path(DeviceState *qdev) { USBDevice *dev = USB_DEVICE(qdev); DeviceState *hcd = qdev->parent_bus->parent; char *id = NULL; if (dev->flags & (1 << USB_DEV_FLAG_FULL_PATH)) { id = qdev_get_dev_path(hcd); } if (id) { char *ret = g_strdup_printf("%s/%s", id, dev->port->path); g_free(id); return ret; } else { return g_strdup(dev->port->path); } } static char *usb_get_fw_dev_path(DeviceState *qdev) { USBDevice *dev = USB_DEVICE(qdev); char *fw_path, *in; ssize_t pos = 0, fw_len; long nr; fw_len = 32 + strlen(dev->port->path) * 6; fw_path = g_malloc(fw_len); in = dev->port->path; while (fw_len - pos > 0) { nr = strtol(in, &in, 10); if (in[0] == '.') { /* some hub between root port and device */ pos += snprintf(fw_path + pos, fw_len - pos, "hub@%ld/", nr); in++; } else { /* the device itself */ pos += snprintf(fw_path + pos, fw_len - pos, "%s@%ld", qdev_fw_name(qdev), nr); break; } } return fw_path; } void usb_info(Monitor *mon) { USBBus *bus; USBDevice *dev; USBPort *port; if (QTAILQ_EMPTY(&busses)) { monitor_printf(mon, "USB support not enabled\n"); return; } QTAILQ_FOREACH(bus, &busses, next) { QTAILQ_FOREACH(port, &bus->used, next) { dev = port->dev; if (!dev) continue; monitor_printf(mon, " Device %d.%d, Port %s, Speed %s Mb/s, Product %s\n", bus->busnr, dev->addr, port->path, usb_speed(dev->speed), dev->product_desc); } } } /* handle legacy -usbdevice cmd line option */ USBDevice *usbdevice_create(const char *cmdline) { USBBus *bus = usb_bus_find(-1 /* any */); LegacyUSBFactory *f = NULL; GSList *i; char driver[32]; const char *params; int len; params = strchr(cmdline,':'); if (params) { params++; len = params - cmdline; if (len > sizeof(driver)) len = sizeof(driver); pstrcpy(driver, len, cmdline); } else { params = ""; pstrcpy(driver, sizeof(driver), cmdline); } for (i = legacy_usb_factory; i; i = i->next) { f = i->data; if (strcmp(f->usbdevice_name, driver) == 0) { break; } } if (i == NULL) { #if 0 /* no error because some drivers are not converted (yet) */ error_report("usbdevice %s not found", driver); #endif return NULL; } if (!bus) { error_report("Error: no usb bus to attach usbdevice %s, " "please try -machine usb=on and check that " "the machine model supports USB", driver); return NULL; } if (!f->usbdevice_init) { if (*params) { error_report("usbdevice %s accepts no params", driver); return NULL; } return usb_create_simple(bus, f->name); } return f->usbdevice_init(bus, params); } static void usb_device_class_init(ObjectClass *klass, void *data) { DeviceClass *k = DEVICE_CLASS(klass); k->bus_type = TYPE_USB_BUS; k->init = usb_qdev_init; k->unplug = qdev_simple_unplug_cb; k->exit = usb_qdev_exit; k->props = usb_props; } static TypeInfo usb_device_type_info = { .name = TYPE_USB_DEVICE, .parent = TYPE_DEVICE, .instance_size = sizeof(USBDevice), .abstract = true, .class_size = sizeof(USBDeviceClass), .class_init = usb_device_class_init, }; static void usb_register_types(void) { type_register_static(&usb_bus_info); type_register_static(&usb_device_type_info); } type_init(usb_register_types)
poblces/qemu
hw/usb/bus.c
C
gpl-2.0
16,421
/* * This class was automatically generated with * <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML * Schema. * $Id$ */ package org.opennms.netmgt.config.rrd.types.descriptors; //---------------------------------/ //- Imported classes and packages -/ //---------------------------------/ import org.opennms.netmgt.config.rrd.types.Backend; /** * Class BackendDescriptor. * * @version $Revision$ $Date$ */ @SuppressWarnings("all") public class BackendDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl { //--------------------------/ //- Class/Member Variables -/ //--------------------------/ /** * Field _elementDefinition. */ private boolean _elementDefinition; /** * Field _nsPrefix. */ private java.lang.String _nsPrefix; /** * Field _nsURI. */ private java.lang.String _nsURI; /** * Field _xmlName. */ private java.lang.String _xmlName; /** * Field _identity. */ private org.exolab.castor.xml.XMLFieldDescriptor _identity; //----------------/ //- Constructors -/ //----------------/ public BackendDescriptor() { super(); _nsURI = "http://xmlns.opennms.org/xsd/rrd"; _xmlName = "Backend"; _elementDefinition = false; } //-----------/ //- Methods -/ //-----------/ /** * Method getAccessMode. * * @return the access mode specified for this class. */ @Override() public org.exolab.castor.mapping.AccessMode getAccessMode( ) { return null; } /** * Method getIdentity. * * @return the identity field, null if this class has no * identity. */ @Override() public org.exolab.castor.mapping.FieldDescriptor getIdentity( ) { return _identity; } /** * Method getJavaClass. * * @return the Java class represented by this descriptor. */ @Override() public java.lang.Class<?> getJavaClass( ) { return org.opennms.netmgt.config.rrd.types.Backend.class; } /** * Method getNameSpacePrefix. * * @return the namespace prefix to use when marshaling as XML. */ @Override() public java.lang.String getNameSpacePrefix( ) { return _nsPrefix; } /** * Method getNameSpaceURI. * * @return the namespace URI used when marshaling and * unmarshaling as XML. */ @Override() public java.lang.String getNameSpaceURI( ) { return _nsURI; } /** * Method getValidator. * * @return a specific validator for the class described by this * ClassDescriptor. */ @Override() public org.exolab.castor.xml.TypeValidator getValidator( ) { return this; } /** * Method getXMLName. * * @return the XML Name for the Class being described. */ @Override() public java.lang.String getXMLName( ) { return _xmlName; } /** * Method isElementDefinition. * * @return true if XML schema definition of this Class is that * of a global * element or element with anonymous type definition. */ public boolean isElementDefinition( ) { return _elementDefinition; } }
vishwaAbhinav/OpenNMS
opennms-webapp/target/generated-sources/castor/org/opennms/netmgt/config/rrd/types/descriptors/BackendDescriptor.java
Java
gpl-2.0
3,367
#include "string\string.h" #include "..\testcommon.h" #include <gtest/gtest.h> const struct test_isnumeric { std::wstring given; bool is; bool allowDecimals; friend std::ostream& operator <<(std::ostream& os, const test_isnumeric& obj) { return os << "Given : " << myodd::strings::WString2String(obj.given) << " Expected : " << (obj.is ? "true" : "false") << " Allow decimals : " << (obj.allowDecimals ? "true" : "false"); } }; struct MyOddStringIsNumeric : testing::Test, testing::WithParamInterface<test_isnumeric> { }; struct MyOddStringIsNumericWithAllowDecimals : testing::Test, testing::WithParamInterface<test_isnumeric> { }; TEST_P(MyOddStringIsNumeric, IsNumericDefaultParams) { auto param = GetParam(); auto given = GetParam().given; auto is = GetParam().is; ASSERT_EQ(is, myodd::strings::IsNumeric(given)); } TEST_P(MyOddStringIsNumericWithAllowDecimals, UseAllowDecimalsFlag) { auto param = GetParam(); auto given = GetParam().given; auto is = GetParam().is; auto allowDecimals = GetParam().allowDecimals; ASSERT_EQ(is, myodd::strings::IsNumeric(given, allowDecimals)); } INSTANTIATE_TEST_CASE_P(NegativeStrings, MyOddStringIsNumeric, testing::Values( test_isnumeric{ L"-1", true }, test_isnumeric{ L"-0", true }, test_isnumeric{ L"-.1", true }, test_isnumeric{ L"-0.1", true }, test_isnumeric{ L"-1.1", true }, test_isnumeric{ L"-999", true }, test_isnumeric{ L"-999.a", false }, test_isnumeric{ L"-1.1.1", false } )); INSTANTIATE_TEST_CASE_P(NegativeStringsDecimalsAllowed, MyOddStringIsNumericWithAllowDecimals, testing::Values( test_isnumeric{ L"-1", true, true }, test_isnumeric{ L"-0", true, true }, test_isnumeric{ L"-.1", true, true }, test_isnumeric{ L"-0.1", true, true }, test_isnumeric{ L"-1.1", true, true }, test_isnumeric{ L"-999", true, true }, test_isnumeric{ L"-999.a", false, true }, test_isnumeric{ L"-1.1.1", false, true } )); INSTANTIATE_TEST_CASE_P(NegativeStringsDecimalsNotAllowed, MyOddStringIsNumericWithAllowDecimals, testing::Values( test_isnumeric{ L"-1", true, false }, test_isnumeric{ L"-0", true, false }, test_isnumeric{ L"-1.", true, false }, // 1. is not a decimal test_isnumeric{ L"-.1", false, false }, test_isnumeric{ L"-0.1", false, false }, test_isnumeric{ L"-1.1", false, false }, test_isnumeric{ L"-999", true, false }, test_isnumeric{ L"-999.a", false, false }, test_isnumeric{ L"-1.1.1", false, false } )); INSTANTIATE_TEST_CASE_P(PositiveStrings, MyOddStringIsNumeric, testing::Values( test_isnumeric{ L"1", true }, test_isnumeric{ L"+0", true }, test_isnumeric{ L".1", true }, test_isnumeric{ L"0.1", true }, test_isnumeric{ L"+0.1", true }, test_isnumeric{ L"+.1", true }, test_isnumeric{ L"1.1", true }, test_isnumeric{ L"-999", true }, test_isnumeric{ L"-999.a", false }, test_isnumeric{ L"-1.1.1", false }, test_isnumeric{ L"1.", true }, test_isnumeric{ L" 1. ", true }, test_isnumeric{ L" 10 ", true }, test_isnumeric{ L" 10.4 ", true }, test_isnumeric{ L" 10 . 4 ", false } )); INSTANTIATE_TEST_CASE_P(PositiveStringsDecimalsNotAllowed, MyOddStringIsNumericWithAllowDecimals, testing::Values( test_isnumeric{ L"1", true, false }, test_isnumeric{ L"+0", true, false }, test_isnumeric{ L".1", false, false }, test_isnumeric{ L"0.1", false, false }, test_isnumeric{ L"+0.1", false, false }, test_isnumeric{ L"+.1", false, false }, test_isnumeric{ L"1.1", false, false }, test_isnumeric{ L"-999", true, false }, test_isnumeric{ L"-999.a", false, false }, test_isnumeric{ L"-1.1.1", false, false }, test_isnumeric{ L"1.", true, false }, test_isnumeric{ L" 1. ", true, false }, test_isnumeric{ L" 10 ", true, false }, test_isnumeric{ L" 10.4 ", false, false }, test_isnumeric{ L" 10 . 4 ", false, false } )); INSTANTIATE_TEST_CASE_P(MiscStrings, MyOddStringIsNumeric, testing::Values( test_isnumeric{ L"-", false }, test_isnumeric{ L".", false }, test_isnumeric{ L"+", false }, test_isnumeric{ L"A1,1", false }, test_isnumeric{ L"1,1", false }, test_isnumeric{ L"+A11", false }, test_isnumeric{ L"A11", false }, test_isnumeric{ L"11A", false }, test_isnumeric{ L"11A", false }, test_isnumeric{ L" 1 2 ", false }, test_isnumeric{ L"-999.1 2", false }, test_isnumeric{ L"999.1 2", false }, test_isnumeric{ L"", false }, // empty test_isnumeric{ L" ", false } // empty )); INSTANTIATE_TEST_CASE_P(MiscStringsWithDecimalFlag, MyOddStringIsNumericWithAllowDecimals, testing::Values( test_isnumeric{ L"-", false, false }, test_isnumeric{ L".", false, false }, test_isnumeric{ L"+", false, false }, test_isnumeric{ L"A1,1", false, false }, test_isnumeric{ L"1,1", false, false }, test_isnumeric{ L"+A11", false, false }, test_isnumeric{ L"A11", false, false }, test_isnumeric{ L"11A", false, false }, test_isnumeric{ L"11A", false, false }, test_isnumeric{ L" 1 2 ", false, false }, test_isnumeric{ L"-999.1 2", false, false }, test_isnumeric{ L"999.1 2", false, false }, test_isnumeric{ L"", false, false }, // empty test_isnumeric{ L" ", false, false }, // empty test_isnumeric{ L"-", false, true }, test_isnumeric{ L".", false, true }, test_isnumeric{ L"+", false, true }, test_isnumeric{ L"A1,1", false, true }, test_isnumeric{ L"1,1", false, true }, test_isnumeric{ L"+A11", false, true }, test_isnumeric{ L"A11", false, true }, test_isnumeric{ L"11A", false, true }, test_isnumeric{ L"11A", false, true }, test_isnumeric{ L" 1 2 ", false, true }, test_isnumeric{ L"-999.1 2", false, true }, test_isnumeric{ L"999.1 2", false, true }, test_isnumeric{ L"", false, true }, // empty test_isnumeric{ L" ", false, true } // empty ));
FFMG/myoddweb.piger
myoddtest/string/teststring_isnumeric.cpp
C++
gpl-2.0
6,066
/* DWARF2 EH unwinding support for Alpha Linux. Copyright (C) 2004, 2005 Free Software Foundation, Inc. This file is part of GCC. GCC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. In addition to the permissions in the GNU General Public License, the Free Software Foundation gives you unlimited permission to link the compiled version of this file with other programs, and to distribute those programs without any restriction coming from the use of this file. (The General Public License restrictions do apply in other respects; for example, they cover modification of the file, and distribution when not linked into another program.) GCC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GCC; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Do code reading to identify a signal frame, and set the frame state data appropriately. See unwind-dw2.c for the structs. */ #include <signal.h> #include <sys/ucontext.h> #define MD_FALLBACK_FRAME_STATE_FOR alpha_fallback_frame_state static _Unwind_Reason_Code alpha_fallback_frame_state (struct _Unwind_Context *context, _Unwind_FrameState *fs) { unsigned int *pc = context->ra; struct sigcontext *sc; long new_cfa, i; if (pc[0] != 0x47fe0410 /* mov $30,$16 */ || pc[2] != 0x00000083 /* callsys */) return _URC_END_OF_STACK; if (context->cfa == 0) return _URC_END_OF_STACK; if (pc[1] == 0x201f0067) /* lda $0,NR_sigreturn */ sc = context->cfa; else if (pc[1] == 0x201f015f) /* lda $0,NR_rt_sigreturn */ { struct rt_sigframe { struct siginfo info; struct ucontext uc; } *rt_ = context->cfa; sc = &rt_->uc.uc_mcontext; } else return _URC_END_OF_STACK; new_cfa = sc->sc_regs[30]; fs->regs.cfa_how = CFA_REG_OFFSET; fs->regs.cfa_reg = 30; fs->regs.cfa_offset = new_cfa - (long) context->cfa; for (i = 0; i < 30; ++i) { fs->regs.reg[i].how = REG_SAVED_OFFSET; fs->regs.reg[i].loc.offset = (long)&sc->sc_regs[i] - new_cfa; } for (i = 0; i < 31; ++i) { fs->regs.reg[i+32].how = REG_SAVED_OFFSET; fs->regs.reg[i+32].loc.offset = (long)&sc->sc_fpregs[i] - new_cfa; } fs->regs.reg[64].how = REG_SAVED_OFFSET; fs->regs.reg[64].loc.offset = (long)&sc->sc_pc - new_cfa; fs->retaddr_column = 64; return _URC_NO_REASON; }
epicsdeb/rtems-gcc-newlib
gcc/config/alpha/linux-unwind.h
C
gpl-2.0
2,811
LASCHOOL ======== Laschool let us create and manage school labels. Right now only PDFs files are supported for creating labels. ============= RELEASE 1.023 - Multi user support - Create school labels for different schools and store the label and subjects in the system, - Now the user can other labels to the system. - PDF file created for labels. - Added cutting lines. Laschool was first created for Papeleria Multiplik (www.papeleriamultiplik.com.mx) By Sergio Flores
saflogar/laschool
README.md
Markdown
gpl-2.0
478
# ZF Action Injections Makes dependency injection possible in action methods. ## Summary For example this: ```php <?php class MyController extends AbstractActionController { public function registerAction() { $form = $this->serviceLocator->get('RegisterForm'); $userCreator = $this->serviceLocator->get('UserCreator'); // .. code, code, code return ['form' => $form]; } } ``` becomes this: ```php <?php class MyController extends AbstractActionController { public function registerAction(RegisterForm $form, UserCreator $userCreator) { // .. code, code, code return ['form' => $form]; } } ``` ## Installation and usage ### Install You can install this module with composer: ``composer require bulgaria-php/zf-action-injections`` Don't forget to add it to your ``application.config.php``: ```php <?php return [ // This should be an array of module namespaces used in the application. 'modules' => [ 'Application', // .. your other modules 'ActionInjections' ] // rest of the configuration ] ``` ### Usage The way Action Injections works is by defining a provider for each action on which you want to inject dependencies. Furthermore, **it is necessary your controllers to extend \ActionInjections\Mvc\Controller\AbstractActionController** (see below why). After that you need to create providers for each action that needs dependencies. Lets consider this ``ArticlesController`` for example: ```php <?php namespace MyBlog\Controller; use ActionInjections\Mvc\Controller\AbstractActionController; class ArticlesController extends AbstractActionController { public function listAction() { $articlesRepository = $this->serviceLocator->get('ArticlesRepository'); return ['articles' => $articles->getArticles()]; } } ``` If we want to inject ArticlesRepository as a dependency we need a action injection provider. First we create the provider class itself. We need a folder ``MODULE/src/ActionProvider/CONTROLLER`` in which we are going to store action injection providers. Here is a provider for the example above: ```php <?php namespace MyBlog\ActionProvider\Articles; use ActionInjections\ActionDependencies\ProviderInterface; use Zend\Mvc\Controller\Plugin\Params; use Zend\ServiceManager\ServiceLocatorInterface; class List implements ProviderInterface { /** * Returns an array, which values will be used as arguments when calling actions * * @param ServiceLocatorInterface $serviceLocator * @param Params $params * @return array */ public function createActionParameters(ServiceLocatorInterface $serviceLocator, Params $params) { $articlesRepository = $serviceLocator->get('ArticlesRepository'); return [$articlesRepository]; } } ``` Next step is to register our new provider in the module configuration (``module.config.php``): ```php <?php return [ 'action_injections' => [ \MyBlog\Controller\ArticlesController::class => [ 'listAction' => \MyBlog\ActionProvider\Articles\List::class ] ]; ``` ### Usage with request parameters You may have noticed the ``Params $params``. Simply put, you can get parameters from the request through this object. This is the same as calling ``$this->params()`` from inside the controller. ## Cons ### ActionInjections\Mvc\Controller\AbstractActionController As mentioned above, you need to extend ``ActionInjections\Mvc\Controller\AbstractActionController`` class on each of the controllers where you want to use action injections. ### Provider for each action Creating classes for each action could be a bit irritating. I am planning to improve this by including annotations in the next version
BulgariaPHP/zf-action-injections
README.md
Markdown
gpl-2.0
3,895
# Copyright 1999 by Jeffrey Chang. All rights reserved. # Copyright 2000 by Jeffrey Chang. All rights reserved. # Revisions Copyright 2007 by Peter Cock. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Module for working with Prosite files from ExPASy (DEPRECATED). Most of the functionality in this module has moved to Bio.ExPASy.Prosite; please see Bio.ExPASy.Prosite.read To read a Prosite file containing one entry. Bio.ExPASy.Prosite.parse Iterates over entries in a Prosite file. Bio.ExPASy.Prosite.Record Holds Prosite data. For scan_sequence_expasy Scan a sequence for occurrences of Prosite patterns. _extract_pattern_hits Extract Prosite patterns from a web page. PatternHit Holds data from a hit against a Prosite pattern. please see the new module Bio.ExPASy.ScanProsite. The other functions and classes in Bio.Prosite (including Bio.Prosite.index_file and Bio.Prosite.Dictionary) are considered deprecated, and were not moved to Bio.ExPASy.Prosite. If you use this functionality, please contact the Biopython developers at biopython-dev@biopython.org to avoid permanent removal of this module from Biopython. This module provides code to work with the prosite dat file from Prosite. http://www.expasy.ch/prosite/ Tested with: Release 15.0, July 1998 Release 16.0, July 1999 Release 17.0, Dec 2001 Release 19.0, Mar 2006 Functions: parse Iterates over entries in a Prosite file. scan_sequence_expasy Scan a sequence for occurrences of Prosite patterns. index_file Index a Prosite file for a Dictionary. _extract_record Extract Prosite data from a web page. _extract_pattern_hits Extract Prosite patterns from a web page. Classes: Record Holds Prosite data. PatternHit Holds data from a hit against a Prosite pattern. Dictionary Accesses a Prosite file using a dictionary interface. RecordParser Parses a Prosite record into a Record object. _Scanner Scans Prosite-formatted data. _RecordConsumer Consumes Prosite data to a Record object. """ import warnings import Bio warnings.warn("Bio.Prosite is deprecated, and will be removed in a"\ " future release of Biopython. Most of the functionality " " is now provided by Bio.ExPASy.Prosite. If you want to " " continue to use Bio.Prosite, please get in contact " " via the mailing lists to avoid its permanent removal from"\ " Biopython.", Bio.BiopythonDeprecationWarning) from types import * import re import sgmllib from Bio import File from Bio import Index from Bio.ParserSupport import * # There is probably a cleaner way to write the read/parse functions # if we don't use the "parser = RecordParser(); parser.parse(handle)" # approach. Leaving that for the next revision of Bio.Prosite. def parse(handle): import cStringIO parser = RecordParser() text = "" for line in handle: text += line if line[:2]=='//': handle = cStringIO.StringIO(text) record = parser.parse(handle) text = "" if not record: # Then this was the copyright notice continue yield record def read(handle): parser = RecordParser() try: record = parser.parse(handle) except ValueError, error: if error.message=="There doesn't appear to be a record": raise ValueError("No Prosite record found") else: raise error # We should have reached the end of the record by now remainder = handle.read() if remainder: raise ValueError("More than one Prosite record found") return record class Record: """Holds information from a Prosite record. Members: name ID of the record. e.g. ADH_ZINC type Type of entry. e.g. PATTERN, MATRIX, or RULE accession e.g. PS00387 created Date the entry was created. (MMM-YYYY) data_update Date the 'primary' data was last updated. info_update Date data other than 'primary' data was last updated. pdoc ID of the PROSITE DOCumentation. description Free-format description. pattern The PROSITE pattern. See docs. matrix List of strings that describes a matrix entry. rules List of rule definitions (from RU lines). (strings) prorules List of prorules (from PR lines). (strings) NUMERICAL RESULTS nr_sp_release SwissProt release. nr_sp_seqs Number of seqs in that release of Swiss-Prot. (int) nr_total Number of hits in Swiss-Prot. tuple of (hits, seqs) nr_positive True positives. tuple of (hits, seqs) nr_unknown Could be positives. tuple of (hits, seqs) nr_false_pos False positives. tuple of (hits, seqs) nr_false_neg False negatives. (int) nr_partial False negatives, because they are fragments. (int) COMMENTS cc_taxo_range Taxonomic range. See docs for format cc_max_repeat Maximum number of repetitions in a protein cc_site Interesting site. list of tuples (pattern pos, desc.) cc_skip_flag Can this entry be ignored? cc_matrix_type cc_scaling_db cc_author cc_ft_key cc_ft_desc cc_version version number (introduced in release 19.0) DATA BANK REFERENCES - The following are all lists of tuples (swiss-prot accession, swiss-prot name) dr_positive dr_false_neg dr_false_pos dr_potential Potential hits, but fingerprint region not yet available. dr_unknown Could possibly belong pdb_structs List of PDB entries. """ def __init__(self): self.name = '' self.type = '' self.accession = '' self.created = '' self.data_update = '' self.info_update = '' self.pdoc = '' self.description = '' self.pattern = '' self.matrix = [] self.rules = [] self.prorules = [] self.postprocessing = [] self.nr_sp_release = '' self.nr_sp_seqs = '' self.nr_total = (None, None) self.nr_positive = (None, None) self.nr_unknown = (None, None) self.nr_false_pos = (None, None) self.nr_false_neg = None self.nr_partial = None self.cc_taxo_range = '' self.cc_max_repeat = '' self.cc_site = [] self.cc_skip_flag = '' self.dr_positive = [] self.dr_false_neg = [] self.dr_false_pos = [] self.dr_potential = [] self.dr_unknown = [] self.pdb_structs = [] class PatternHit: """Holds information from a hit against a Prosite pattern. Members: name ID of the record. e.g. ADH_ZINC accession e.g. PS00387 pdoc ID of the PROSITE DOCumentation. description Free-format description. matches List of tuples (start, end, sequence) where start and end are indexes of the match, and sequence is the sequence matched. """ def __init__(self): self.name = None self.accession = None self.pdoc = None self.description = None self.matches = [] def __str__(self): lines = [] lines.append("%s %s %s" % (self.accession, self.pdoc, self.name)) lines.append(self.description) lines.append('') if len(self.matches) > 1: lines.append("Number of matches: %s" % len(self.matches)) for i in range(len(self.matches)): start, end, seq = self.matches[i] range_str = "%d-%d" % (start, end) if len(self.matches) > 1: lines.append("%7d %10s %s" % (i+1, range_str, seq)) else: lines.append("%7s %10s %s" % (' ', range_str, seq)) return "\n".join(lines) class Dictionary: """Accesses a Prosite file using a dictionary interface. """ __filename_key = '__filename' def __init__(self, indexname, parser=None): """__init__(self, indexname, parser=None) Open a Prosite Dictionary. indexname is the name of the index for the dictionary. The index should have been created using the index_file function. parser is an optional Parser object to change the results into another form. If set to None, then the raw contents of the file will be returned. """ self._index = Index.Index(indexname) self._handle = open(self._index[Dictionary.__filename_key]) self._parser = parser def __len__(self): return len(self._index) def __getitem__(self, key): start, len = self._index[key] self._handle.seek(start) data = self._handle.read(len) if self._parser is not None: return self._parser.parse(File.StringHandle(data)) return data def __getattr__(self, name): return getattr(self._index, name) class RecordParser(AbstractParser): """Parses Prosite data into a Record object. """ def __init__(self): self._scanner = _Scanner() self._consumer = _RecordConsumer() def parse(self, handle): self._scanner.feed(handle, self._consumer) return self._consumer.data class _Scanner: """Scans Prosite-formatted data. Tested with: Release 15.0, July 1998 """ def feed(self, handle, consumer): """feed(self, handle, consumer) Feed in Prosite data for scanning. handle is a file-like object that contains prosite data. consumer is a Consumer object that will receive events as the report is scanned. """ if isinstance(handle, File.UndoHandle): uhandle = handle else: uhandle = File.UndoHandle(handle) consumer.finished = False while not consumer.finished: line = uhandle.peekline() if not line: break elif is_blank_line(line): # Skip blank lines between records uhandle.readline() continue elif line[:2] == 'ID': self._scan_record(uhandle, consumer) elif line[:2] == 'CC': self._scan_copyrights(uhandle, consumer) else: raise ValueError("There doesn't appear to be a record") def _scan_copyrights(self, uhandle, consumer): consumer.start_copyrights() self._scan_line('CC', uhandle, consumer.copyright, any_number=1) self._scan_terminator(uhandle, consumer) consumer.end_copyrights() def _scan_record(self, uhandle, consumer): consumer.start_record() for fn in self._scan_fns: fn(self, uhandle, consumer) # In Release 15.0, C_TYPE_LECTIN_1 has the DO line before # the 3D lines, instead of the other way around. # Thus, I'll give the 3D lines another chance after the DO lines # are finished. if fn is self._scan_do.im_func: self._scan_3d(uhandle, consumer) consumer.end_record() def _scan_line(self, line_type, uhandle, event_fn, exactly_one=None, one_or_more=None, any_number=None, up_to_one=None): # Callers must set exactly one of exactly_one, one_or_more, or # any_number to a true value. I do not explicitly check to # make sure this function is called correctly. # This does not guarantee any parameter safety, but I # like the readability. The other strategy I tried was have # parameters min_lines, max_lines. if exactly_one or one_or_more: read_and_call(uhandle, event_fn, start=line_type) if one_or_more or any_number: while 1: if not attempt_read_and_call(uhandle, event_fn, start=line_type): break if up_to_one: attempt_read_and_call(uhandle, event_fn, start=line_type) def _scan_id(self, uhandle, consumer): self._scan_line('ID', uhandle, consumer.identification, exactly_one=1) def _scan_ac(self, uhandle, consumer): self._scan_line('AC', uhandle, consumer.accession, exactly_one=1) def _scan_dt(self, uhandle, consumer): self._scan_line('DT', uhandle, consumer.date, exactly_one=1) def _scan_de(self, uhandle, consumer): self._scan_line('DE', uhandle, consumer.description, exactly_one=1) def _scan_pa(self, uhandle, consumer): self._scan_line('PA', uhandle, consumer.pattern, any_number=1) def _scan_ma(self, uhandle, consumer): self._scan_line('MA', uhandle, consumer.matrix, any_number=1) ## # ZN2_CY6_FUNGAL_2, DNAJ_2 in Release 15 ## # contain a CC line buried within an 'MA' line. Need to check ## # for that. ## while 1: ## if not attempt_read_and_call(uhandle, consumer.matrix, start='MA'): ## line1 = uhandle.readline() ## line2 = uhandle.readline() ## uhandle.saveline(line2) ## uhandle.saveline(line1) ## if line1[:2] == 'CC' and line2[:2] == 'MA': ## read_and_call(uhandle, consumer.comment, start='CC') ## else: ## break def _scan_pp(self, uhandle, consumer): #New PP line, PostProcessing, just after the MA line self._scan_line('PP', uhandle, consumer.postprocessing, any_number=1) def _scan_ru(self, uhandle, consumer): self._scan_line('RU', uhandle, consumer.rule, any_number=1) def _scan_nr(self, uhandle, consumer): self._scan_line('NR', uhandle, consumer.numerical_results, any_number=1) def _scan_cc(self, uhandle, consumer): self._scan_line('CC', uhandle, consumer.comment, any_number=1) def _scan_dr(self, uhandle, consumer): self._scan_line('DR', uhandle, consumer.database_reference, any_number=1) def _scan_3d(self, uhandle, consumer): self._scan_line('3D', uhandle, consumer.pdb_reference, any_number=1) def _scan_pr(self, uhandle, consumer): #New PR line, ProRule, between 3D and DO lines self._scan_line('PR', uhandle, consumer.prorule, any_number=1) def _scan_do(self, uhandle, consumer): self._scan_line('DO', uhandle, consumer.documentation, exactly_one=1) def _scan_terminator(self, uhandle, consumer): self._scan_line('//', uhandle, consumer.terminator, exactly_one=1) #This is a list of scan functions in the order expected in the file file. #The function definitions define how many times each line type is exected #(or if optional): _scan_fns = [ _scan_id, _scan_ac, _scan_dt, _scan_de, _scan_pa, _scan_ma, _scan_pp, _scan_ru, _scan_nr, _scan_cc, # This is a really dirty hack, and should be fixed properly at # some point. ZN2_CY6_FUNGAL_2, DNAJ_2 in Rel 15 and PS50309 # in Rel 17 have lines out of order. Thus, I have to rescan # these, which decreases performance. _scan_ma, _scan_nr, _scan_cc, _scan_dr, _scan_3d, _scan_pr, _scan_do, _scan_terminator ] class _RecordConsumer(AbstractConsumer): """Consumer that converts a Prosite record to a Record object. Members: data Record with Prosite data. """ def __init__(self): self.data = None def start_record(self): self.data = Record() def end_record(self): self._clean_record(self.data) def identification(self, line): cols = line.split() if len(cols) != 3: raise ValueError("I don't understand identification line\n%s" \ % line) self.data.name = self._chomp(cols[1]) # don't want ';' self.data.type = self._chomp(cols[2]) # don't want '.' def accession(self, line): cols = line.split() if len(cols) != 2: raise ValueError("I don't understand accession line\n%s" % line) self.data.accession = self._chomp(cols[1]) def date(self, line): uprline = line.upper() cols = uprline.split() # Release 15.0 contains both 'INFO UPDATE' and 'INF UPDATE' if cols[2] != '(CREATED);' or \ cols[4] != '(DATA' or cols[5] != 'UPDATE);' or \ cols[7][:4] != '(INF' or cols[8] != 'UPDATE).': raise ValueError("I don't understand date line\n%s" % line) self.data.created = cols[1] self.data.data_update = cols[3] self.data.info_update = cols[6] def description(self, line): self.data.description = self._clean(line) def pattern(self, line): self.data.pattern = self.data.pattern + self._clean(line) def matrix(self, line): self.data.matrix.append(self._clean(line)) def postprocessing(self, line): postprocessing = self._clean(line).split(";") self.data.postprocessing.extend(postprocessing) def rule(self, line): self.data.rules.append(self._clean(line)) def numerical_results(self, line): cols = self._clean(line).split(";") for col in cols: if not col: continue qual, data = [word.lstrip() for word in col.split("=")] if qual == '/RELEASE': release, seqs = data.split(",") self.data.nr_sp_release = release self.data.nr_sp_seqs = int(seqs) elif qual == '/FALSE_NEG': self.data.nr_false_neg = int(data) elif qual == '/PARTIAL': self.data.nr_partial = int(data) elif qual in ['/TOTAL', '/POSITIVE', '/UNKNOWN', '/FALSE_POS']: m = re.match(r'(\d+)\((\d+)\)', data) if not m: raise Exception("Broken data %s in comment line\n%s" \ % (repr(data), line)) hits = tuple(map(int, m.groups())) if(qual == "/TOTAL"): self.data.nr_total = hits elif(qual == "/POSITIVE"): self.data.nr_positive = hits elif(qual == "/UNKNOWN"): self.data.nr_unknown = hits elif(qual == "/FALSE_POS"): self.data.nr_false_pos = hits else: raise ValueError("Unknown qual %s in comment line\n%s" \ % (repr(qual), line)) def comment(self, line): #Expect CC lines like this: #CC /TAXO-RANGE=??EPV; /MAX-REPEAT=2; #Can (normally) split on ";" and then on "=" cols = self._clean(line).split(";") for col in cols: if not col or col[:17] == 'Automatic scaling': # DNAJ_2 in Release 15 has a non-standard comment line: # CC Automatic scaling using reversed database # Throw it away. (Should I keep it?) continue if col.count("=") == 0: #Missing qualifier! Can we recover gracefully? #For example, from Bug 2403, in PS50293 have: #CC /AUTHOR=K_Hofmann; N_Hulo continue qual, data = [word.lstrip() for word in col.split("=")] if qual == '/TAXO-RANGE': self.data.cc_taxo_range = data elif qual == '/MAX-REPEAT': self.data.cc_max_repeat = data elif qual == '/SITE': pos, desc = data.split(",") self.data.cc_site.append((int(pos), desc)) elif qual == '/SKIP-FLAG': self.data.cc_skip_flag = data elif qual == '/MATRIX_TYPE': self.data.cc_matrix_type = data elif qual == '/SCALING_DB': self.data.cc_scaling_db = data elif qual == '/AUTHOR': self.data.cc_author = data elif qual == '/FT_KEY': self.data.cc_ft_key = data elif qual == '/FT_DESC': self.data.cc_ft_desc = data elif qual == '/VERSION': self.data.cc_version = data else: raise ValueError("Unknown qual %s in comment line\n%s" \ % (repr(qual), line)) def database_reference(self, line): refs = self._clean(line).split(";") for ref in refs: if not ref: continue acc, name, type = [word.strip() for word in ref.split(",")] if type == 'T': self.data.dr_positive.append((acc, name)) elif type == 'F': self.data.dr_false_pos.append((acc, name)) elif type == 'N': self.data.dr_false_neg.append((acc, name)) elif type == 'P': self.data.dr_potential.append((acc, name)) elif type == '?': self.data.dr_unknown.append((acc, name)) else: raise ValueError("I don't understand type flag %s" % type) def pdb_reference(self, line): cols = line.split() for id in cols[1:]: # get all but the '3D' col self.data.pdb_structs.append(self._chomp(id)) def prorule(self, line): #Assume that each PR line can contain multiple ";" separated rules rules = self._clean(line).split(";") self.data.prorules.extend(rules) def documentation(self, line): self.data.pdoc = self._chomp(self._clean(line)) def terminator(self, line): self.finished = True def _chomp(self, word, to_chomp='.,;'): # Remove the punctuation at the end of a word. if word[-1] in to_chomp: return word[:-1] return word def _clean(self, line, rstrip=1): # Clean up a line. if rstrip: return line[5:].rstrip() return line[5:] def scan_sequence_expasy(seq=None, id=None, exclude_frequent=None): """scan_sequence_expasy(seq=None, id=None, exclude_frequent=None) -> list of PatternHit's Search a sequence for occurrences of Prosite patterns. You can specify either a sequence in seq or a SwissProt/trEMBL ID or accession in id. Only one of those should be given. If exclude_frequent is true, then the patterns with the high probability of occurring will be excluded. """ from Bio import ExPASy if (seq and id) or not (seq or id): raise ValueError("Please specify either a sequence or an id") handle = ExPASy.scanprosite1(seq, id, exclude_frequent) return _extract_pattern_hits(handle) def _extract_pattern_hits(handle): """_extract_pattern_hits(handle) -> list of PatternHit's Extract hits from a web page. Raises a ValueError if there was an error in the query. """ class parser(sgmllib.SGMLParser): def __init__(self): sgmllib.SGMLParser.__init__(self) self.hits = [] self.broken_message = 'Some error occurred' self._in_pre = 0 self._current_hit = None self._last_found = None # Save state of parsing def handle_data(self, data): if data.find('try again') >= 0: self.broken_message = data return elif data == 'illegal': self.broken_message = 'Sequence contains illegal characters' return if not self._in_pre: return elif not data.strip(): return if self._last_found is None and data[:4] == 'PDOC': self._current_hit.pdoc = data self._last_found = 'pdoc' elif self._last_found == 'pdoc': if data[:2] != 'PS': raise ValueError("Expected accession but got:\n%s" % data) self._current_hit.accession = data self._last_found = 'accession' elif self._last_found == 'accession': self._current_hit.name = data self._last_found = 'name' elif self._last_found == 'name': self._current_hit.description = data self._last_found = 'description' elif self._last_found == 'description': m = re.findall(r'(\d+)-(\d+) (\w+)', data) for start, end, seq in m: self._current_hit.matches.append( (int(start), int(end), seq)) def do_hr(self, attrs): # <HR> inside a <PRE> section means a new hit. if self._in_pre: self._current_hit = PatternHit() self.hits.append(self._current_hit) self._last_found = None def start_pre(self, attrs): self._in_pre = 1 self.broken_message = None # Probably not broken def end_pre(self): self._in_pre = 0 p = parser() p.feed(handle.read()) if p.broken_message: raise ValueError(p.broken_message) return p.hits def index_file(filename, indexname, rec2key=None): """index_file(filename, indexname, rec2key=None) Index a Prosite file. filename is the name of the file. indexname is the name of the dictionary. rec2key is an optional callback that takes a Record and generates a unique key (e.g. the accession number) for the record. If not specified, the id name will be used. """ import os if not os.path.exists(filename): raise ValueError("%s does not exist" % filename) index = Index.Index(indexname, truncate=1) index[Dictionary._Dictionary__filename_key] = filename handle = open(filename) records = parse(handle) end = 0L for record in records: start = end end = handle.tell() length = end - start if rec2key is not None: key = rec2key(record) else: key = record.name if not key: raise KeyError("empty key was produced") elif key in index: raise KeyError("duplicate key %s found" % key) index[key] = start, length
BlogomaticProject/Blogomatic
opt/blog-o-matic/usr/lib/python/Bio/Prosite/__init__.py
Python
gpl-2.0
27,006
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.orionline.entidade; /** * * @author ronald */ public class BarrasRelacionadas extends ProdutoAUX{ }
ronaldsantos63/ConversorOrionline
src/br/com/orionline/entidade/BarrasRelacionadas.java
Java
gpl-2.0
323
// taikaDlg.cpp : implementation file // #include "stdafx.h" #include "taika.h" #include "taikaDlg.h" #include "Props.h" #include "DlgVarmuuskopioi.h" #include "DlgSiivoaTietokanta.h" #include "DlgAsetukset.h" #include "DlgLuoUusiTietokanta.h" #include "DlgAbout.h" #include "StringHelper_luokka.h" #include <afxpriv.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTaikaDlg dialog CTaikaDlg::CTaikaDlg(CWnd* pParent /*=NULL*/) : CDialog(CTaikaDlg::IDD, pParent), m_pMenu(NULL) { //{{AFX_DATA_INIT(CTaikaDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CTaikaDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTaikaDlg) DDX_Control(pDX, IDC_TABMAIN, m_tabMain); DDX_Control(pDX, IDC_SHEET_PLACEHOLDER, m_picPlaceHolder); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CTaikaDlg, CDialog) //{{AFX_MSG_MAP(CTaikaDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_CLOSE() ON_WM_DESTROY() ON_COMMAND(IDM_AVAA_RAPORTTI, OnAvaaRaportti) ON_COMMAND(IDM_TALLETA_RAPORTTI, OnTalletaRaportti) ON_COMMAND(IDM_VARMUUSKOPIOI_TIETOKANTA, OnVarmuuskopioiTietokanta) ON_COMMAND(IDM_VAIHDA_TIETOKANTA, OnVaihdaTietokanta) ON_COMMAND(IDM_TALLETA_LISTAT, OnTalletaListat) ON_COMMAND(IDM_AVAA_LISTAT, OnAvaaListat) ON_COMMAND(IDM_AVAA_RAPORTTI_TM, OnAvaaRaporttiTm) ON_COMMAND(IDM_TALLETA_RAPORTTI_TM, OnTalletaRaporttiTm) ON_COMMAND(IDM_SIIVOA_TIETOKANTA, OnSiivoaTietokanta) ON_COMMAND(IDM_EMAIL, OnEmail) ON_COMMAND(IDK_VALITSEKAIKKI, OnValitsekaikki) ON_COMMAND(IDK_AVAA, OnAvaa) ON_COMMAND(IDK_TALLETA, OnTalleta) ON_COMMAND(IDK_ETSI, OnEtsi) ON_COMMAND(IDK_ETSI_F3, OnEtsiF3) ON_COMMAND(IDK_UUSI, OnUusi) ON_NOTIFY(TCN_SELCHANGE, IDC_TABMAIN, OnSelchangeTabmain) ON_WM_SIZE() ON_WM_SIZING() ON_COMMAND(IDM_ASETUKSET, OnAsetukset) ON_COMMAND(IDM_LUO_UUSI_TIETOKANTA, OnLuoUusiTietokanta) ON_COMMAND(IDK_IMPORT, OnImport) ON_COMMAND(IDM_TUO_LASKUTUSOHJELMASTA, OnTuoLaskutusohjelmasta) ON_COMMAND(IDK_POISTA_X, OnPoista) ON_COMMAND(IDK_PAIVITA_V5, OnPaivitaV5) ON_COMMAND(IDK_EMAIL, OnEmail) ON_COMMAND(IDM_ABOUT, OnAbout) //}}AFX_MSG_MAP ON_WM_INITMENUPOPUP() ON_MESSAGE(WM_USER_NEW_REPORT, OnMsgUusiRaportti) ON_MESSAGE(WM_IDLEUPDATECMDUI, OnIdleUpdateCmdUI) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTaikaDlg message handlers LRESULT CTaikaDlg::OnIdleUpdateCmdUI(WPARAM wParam, LPARAM lparam) { return 0L; } BOOL CTaikaDlg::OnInitDialog() { int ret; RECT trect, crect; TCITEM tci; CString cs; DbSqlite db; Parse parse; CRect rcSheet; string use_db; CDialog::OnInitDialog(); SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // Päällimmäisin dialogi - aluksi raportit m_mainShowMode = SHOW_RAPORTIT; // Kansiot - luo kansiot, jos niitä ei löydy luoKansiot(Props::e().m_app_path); // Asetukset - luo perusasetukset, jos ei löydy if(Props::i().get(OPTIONS_AIKAJARJESTYS_R) == "") { use_db = Props::e().m_app_path + DEFAULT_DB_NAME; Props::i().set(OPTIONS_DB_PATH, use_db); Props::i().set(OPTIONS_DB_NAME, DEFAULT_DB_NAME); Props::i().set(OPTIONS_AUTOPARSE, "TRUE"); Props::i().set(OPTIONS_LASKUTUSOHJELMA, LAS_NONE); Props::i().set(OPTIONS_LASKUTUSOHJELMA_POLKU, "c:\\"); Props::i().set(OPTIONS_LASKUTUSOHJELMA_KOKO_POLKU, ""); Props::i().set(OPTIONS_KAYNTIKERTAVELOITUS, C_TRUE); Props::i().set(OPTIONS_HINNAT, HINNAT_LASKOHJ); Props::i().set(OPTIONS_LASKUTUSTILA, LTILA_LASKUTTAMATTOMAT); Props::i().set(OPTIONS_LASKUNMAKSUAIKA, "30"); Props::i().set(OPTIONS_YHDISTATAPAHTUMAT, C_TRUE); Props::i().set(OPTIONS_OPENPATH, (LPCSTR)Props::e().m_app_path); Props::i().set(OPTIONS_SAVEPATH, (LPCSTR)Props::e().m_app_path); Props::i().set(OPTIONS_AJAT, StringHelper::itoa(TIME_MINUTES, 10)); Props::i().set(OPTIONS_ALKAEN_R, DATE_VANHIN_TYO); Props::i().set(OPTIONS_PAATTYEN_R, DATE_UUSIN_TYO); Props::i().set(OPTIONS_ALKAEN_VIIMEISIN_R, "1.1.2008"); Props::i().set(OPTIONS_PAATTYEN_VIIMEISIN_R, "1.1.2008"); Props::i().set(OPTIONS_ALKAEN_T, DATE_VANHIN_TYO); Props::i().set(OPTIONS_PAATTYEN_T, DATE_UUSIN_TYO); Props::i().set(OPTIONS_ALKAEN_VIIMEISIN_T, "1.1.2008"); Props::i().set(OPTIONS_PAATTYEN_VIIMEISIN_T, "1.1.2008"); Props::i().set(OPTIONS_AIKAJARJESTYS_R, DESCENT_S); Props::i().set(OPTIONS_AIKAJARJESTYS_T, DESCENT_S); Props::i().set(OPTIONS_KMKERROIN, "0.43"); use_db = Props::e().m_app_path + "varmuuskopiot\\"; Props::i().set(OPTIONS_DB_BACKUP_PATH, use_db); Props::i().set(OPTIONS_EM_RECIPIENTS, ""); Props::i().set(OPTIONS_EM_FROM, ""); Props::i().set(OPTIONS_EM_SMTP_SERVER, ""); Props::i().set(OPTIONS_EM_SMTP_PORT, "25"); Props::i().set(OPTIONS_PRNT_ASNIMI, PRNT_ASNIMINRO); Props::i().set(OPTIONS_PRNT_ASALOITUSPVM, PRNT_PVM_AIKA); Props::i().set(OPTIONS_PRNT_ASLOPETUSPVM, PRNT_PVM_AIKA); Props::i().set(OPTIONS_PRNT_ASTYOAIKA, PRNT_TYOAIKA_MIN); Props::i().set(OPTIONS_PRNT_ASTYOTYYPIT, PRNT_TYOTYYPIT); Props::i().set(OPTIONS_PRNT_TTALOITUSPVM, PRNT_PVM_AIKA); Props::i().set(OPTIONS_PRNT_TTLOPETUSPVM, PRNT_PVM_AIKA); Props::i().set(OPTIONS_PRNT_TTTYOAIKA, PRNT_TYOAIKA_MIN); Props::i().set(OPTIONS_PRNT_TTTYOTYYPIT, PRNT_TYOTYYPIT); Props::i().set(OPTIONS_PRNT_TMPAIVAYKSET, PRNT_PVM_AIKA_MOLEMMAT); Props::i().set(OPTIONS_PRNT_TMMATKA, PRNT_MATKAT_TARKOITUS); Props::i().set(OPTIONS_PRNT_TMLUKEMAT, PRNT_LUKEMAT); Props::i().set(OPTIONS_PRNT_TMYKSAJOA, PRNT_YKSAJOA); Props::i().set(OPTIONS_PRNT_TMTYOAJOA, PRNT_TYOAJOA); Props::i().set(OPTIONS_PRNT_SIVUTUS, C_TRUE); Props::i().set(OPTIONS_PRNT_YLATUNNISTE_TEXT, ""); Props::i().set(OPTIONS_PRNT_ALATUNNISTE_TEXT, ""); Props::i().set(OPTIONS_PRNT_YLATUNNISTE, C_TRUE); Props::i().set(OPTIONS_PRNT_ALATUNNISTE, C_TRUE); Props::i().set(OPTIONS_PRNT_YLAPAIVAYS, C_TRUE); Props::i().set(OPTIONS_PRNT_FONTINKOKO, FONTSIZE_8); Props::i().set(OPTIONS_PRNT_FONTINNIMI, "Arial"); Props::i().set(OPTIONS_PRNT_YHTEENVETO, C_TRUE); Props::i().set(OPTIONS_PRNT_KMKORVAUS, C_TRUE); Props::i().set(OPTIONS_PRNT_YHDISTATAPAHTUMAT, C_TRUE); Props::i().set(OPTIONS_EM_SMTP_USE_AUTH, C_FALSE); Props::i().set(OPTIONS_EM_SMTP_RMBR_UN, C_FALSE); Props::i().set(OPTIONS_EM_SMTP_USERNAME, ""); Props::i().set(OPTIONS_LSTHEADER_RATA, ""); Props::i().set(OPTIONS_LSTHEADER_RAMY, ""); Props::i().set(OPTIONS_LSTHEADER_LIAR, ""); Props::i().set(OPTIONS_LSTHEADER_LIAS, ""); Props::i().set(OPTIONS_LSTHEADER_LILA, ""); Props::i().set(OPTIONS_LSTHEADER_LITT, ""); Props::i().set(OPTIONS_LSTHEADER_LITR, ""); Props::i().set(OPTIONS_LSTHEADER_LITU, ""); Props::i().set(OPTIONS_LSTHEADER_TYTY, ""); } // Otetaan tietokannan polku asetuksista, Tarkistetaan tietokanta (luodaan, jos ei ole olemassa) Props::e().m_db_path = Props::i().get(OPTIONS_DB_PATH).c_str(); if((ret = db.check()) != RETURN_OK) Props::e().m_db_path = ""; // Virheen sattuessa, ei tietokantaa!!! //EndDialog(IDCANCEL); // Tarkistetaan onko saapuneet kansiossa uusia raportteja if(ret == RETURN_OK) parse.parseSaapuneet(PARSE_SAAPUNEET); // Dialogin otsikko resurssista ja tietokannan nimi asetuksista usedDB(); // Menu paikoilleen (aluksi IDR_RAPORTIT_MENU, asetetaan eri dilogeissa vastaamaan paremmin niiden toimintoja) m_pMenu = pageRaportit.createMenu(); this->SetMenu(m_pMenu); AfxGetMainWnd()->DrawMenuBar(); // Koko ruutu ShowWindow(SW_MAXIMIZE); // Alustetaan tab-kontolli GetClientRect(&crect); m_tabMain.SetWindowPos(NULL, 0, 0, crect.right, crect.bottom, SWP_NOMOVE|SWP_NOZORDER); tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_1"); m_tabMain.InsertItem(0, &tci); tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_2"); m_tabMain.InsertItem(1, &tci); tci.mask = TCIF_IMAGE|TCIF_TEXT; tci.iImage = 0; tci.pszText = (LPSTR)(LPCSTR)Props::i().lang("TAIKADLG_3"); m_tabMain.InsertItem(2, &tci); // Placeholder ylänurkkaan m_tabMain.GetItemRect(0, &trect); // tabin headerin koko m_tabMain.GetClientRect(&crect); // tabin koko m_picPlaceHolder.SetWindowPos(NULL, PAGE_LEFT, PAGE_TOP + trect.bottom, crect.right - PAGE_LEFT - PAGE_RIGHT, crect.bottom - trect.bottom - PAGE_TOP - PAGE_BOTTOM, SWP_NOZORDER); // Luo dialogit pageRaportit.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL); pageListat.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL); pageTyomatkat.CRHCreateGenericChildDialog(this, IDC_SHEET_PLACEHOLDER, 0, NULL); // Ja uudestaan menu - dialogien luonti voi sotkea näytettävän menun if(m_pMenu) m_pMenu->DestroyMenu(); m_pMenu = pageRaportit.createMenu(); this->SetMenu(m_pMenu); AfxGetMainWnd()->DrawMenuBar(); return TRUE; // return TRUE unless you set the focus to a control } void CTaikaDlg::OnClose() { CDialog::OnClose(); } void CTaikaDlg::OnDestroy() { CDialog::OnDestroy(); if(m_pMenu) m_pMenu->DestroyMenu(); // Tuhoa menu } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CTaikaDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } HCURSOR CTaikaDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } BOOL CTaikaDlg::PreTranslateMessage(MSG* pMsg) { if(pMsg->message == WM_KEYDOWN) // Estetään RETURNIN painaminen dialogissa (dialogi ei sulkeudu vahingossa) { if(pMsg->wParam == VK_RETURN) return TRUE; } SendMessageToDescendants(WM_KICKIDLE, 0, 0, FALSE, FALSE); return CDialog::PreTranslateMessage(pMsg); } void CTaikaDlg::OnOK() {} void CTaikaDlg::OnCancel() { CDialog::OnCancel(); } void CTaikaDlg::OnSize(UINT nType, int cx, int cy) { BOOL resize = FALSE; RECT crect, trect; int page_width, page_height; // Varmista, että ikkunat on luotu if(this->GetSafeHwnd() == 0) return; if(m_tabMain.GetSafeHwnd() == 0) return; if(m_picPlaceHolder.GetSafeHwnd() == 0) return; CDialog::OnSize(nType, cx, cy); // tab-control ruudun kokoiseksi GetClientRect(&crect); m_tabMain.SetWindowPos(NULL, 0, 0, crect.right, crect.bottom, SWP_NOMOVE|SWP_NOZORDER); // placeholder tabin kokoiseksi m_tabMain.GetItemRect(0, &trect); // tabin headerin koko m_tabMain.GetClientRect(&crect); // tabin koko page_width = crect.right - PAGE_LEFT - PAGE_RIGHT; // sivun koko: w = tabin w - marginaalit, h = tabin h - tabin h - marginaalit page_height = crect.bottom - trect.bottom - PAGE_TOP - PAGE_BOTTOM; m_picPlaceHolder.SetWindowPos(NULL, 0, 0, page_width, page_height, SWP_NOMOVE|SWP_NOZORDER); // Muuta lapsidialogien koot if(pageRaportit.GetSafeHwnd() != NULL) pageRaportit.windowSize(); if(pageListat.GetSafeHwnd() != NULL) pageListat.windowSize(); if(pageTyomatkat.GetSafeHwnd() != NULL) pageTyomatkat.windowSize(); } void CTaikaDlg::OnSizing(UINT nSide, LPRECT lpRect) { if(lpRect->right - lpRect->left < 890) lpRect->right = lpRect->left + 890; if(lpRect->bottom - lpRect->top < 500) lpRect->bottom = lpRect->top + 500; } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // Komentojen käsittelijät // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // void CTaikaDlg::OnSelchangeTabmain(NMHDR* pNMHDR, LRESULT* pResult) { int sel = m_tabMain.GetCurSel(); if(sel == 0 && m_mainShowMode != SHOW_RAPORTIT) { m_mainShowMode = SHOW_RAPORTIT; pageRaportit.ShowWindow(SW_SHOW); pageListat.ShowWindow(SW_HIDE); pageTyomatkat.ShowWindow(SW_HIDE); pageRaportit.OnSetActive(); } else if(sel == 1) { m_mainShowMode = SHOW_LISTAT; pageRaportit.ShowWindow(SW_HIDE); pageListat.ShowWindow(SW_SHOW); pageTyomatkat.ShowWindow(SW_HIDE); pageListat.OnSetActive(); } else if(sel == 2) { m_mainShowMode = SHOW_TYOMATKAT; pageRaportit.ShowWindow(SW_HIDE); pageListat.ShowWindow(SW_HIDE); pageTyomatkat.ShowWindow(SW_SHOW); pageTyomatkat.OnSetActive(); } *pResult = 0; } LRESULT CTaikaDlg::OnMsgUusiRaportti(WPARAM wparam, LPARAM lparam) { //int s; Parse parse; this->BringWindowToTop(); parse.parseSaapuneet(PARSE_ADD_FILE); // Parsitaan saapuneet lista ja päivitetään näytöt if(wparam == PARAM_TTI || wparam == PARAM_TTA) paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); return 0; } void CTaikaDlg::luoKansiot(CString app_path) { // Luo kansiot jos niitä ei löydy WIN32_FIND_DATA fd; HANDLE hfile = NULL; CString dirpath, cs; dirpath = app_path + "saapuneet\\"; if((hfile = FindFirstFile(dirpath, &fd)) != INVALID_HANDLE_VALUE) FindClose(hfile); else { if(GetLastError() == ERROR_PATH_NOT_FOUND) CreateDirectory(dirpath, NULL); } dirpath = app_path + "raportit\\"; if((hfile = FindFirstFile(dirpath, &fd)) != INVALID_HANDLE_VALUE) FindClose(hfile); else { if(GetLastError() == ERROR_PATH_NOT_FOUND) CreateDirectory(dirpath, NULL); } dirpath = app_path + "varmuuskopiot\\"; if((hfile = FindFirstFile(dirpath, &fd)) != INVALID_HANDLE_VALUE) FindClose(hfile); else { if(GetLastError() == ERROR_PATH_NOT_FOUND) CreateDirectory(dirpath, NULL); } } ///////////////////////////////////////////////////////////////////////////// // Menun itemien disablointi/enablointi logiikka void CTaikaDlg::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) setRaporttiMenu(nIndex); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) setListatMenu(nIndex); } void CTaikaDlg::setRaporttiMenu(UINT nIndex) { int flags; CMenu *pMenu = this->GetMenu(); if(nIndex == 0) // Tiedosto-menu { // IDM_TALLETA_RAPORTTI if(pageRaportit.m_lstAsiakkaat.GetSelCount() > 0 || pageRaportit.m_plstRaportit->GetItemCount() > 0) flags = MF_ENABLED; else flags = MF_DISABLED|MF_GRAYED; pMenu->EnableMenuItem(IDM_TALLETA_RAPORTTI, flags); } } void CTaikaDlg::setListatMenu(UINT nIndex) {} ///////////////////////////////////////////////////////////////////////////// // IDM_RAPORTIT_MENU - Menu itemien viestit void CTaikaDlg::OnAvaaRaportti() { //int s; Parse parse; if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) // Avaa .tti-tiedosto { if(!parse.avaaTTI(this->GetSafeHwnd())) return; } paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); } void CTaikaDlg::OnTalletaRaportti() { Parse parse; if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) // Talleta valitut ID_WORKUNIT/ID_SALESUNIT-tiedostoon (.tta) { parse.talletaTTI(this->GetSafeHwnd(), pageRaportit.getMode()); } } void CTaikaDlg::OnEmail() { Parse parse; //if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.email(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.email(); } void CTaikaDlg::OnAbout() { CDlgAbout dlga; dlga.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // IDM_LISTAT_MENU - Menu itemien viestit void CTaikaDlg::OnAvaaListat() { Parse parse; if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) // Avaa .tta-tiedosto { if(!parse.avaaTTA(this->GetSafeHwnd())) return; } paivitaNaytot(FALSE, FALSE, FALSE, SYNC_ALL); } void CTaikaDlg::OnTalletaListat() { Parse parse; if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) // Talleta listat { parse.talletaTTA(this->GetSafeHwnd(), "", 0, 0, 0, 0, MODE_SAVE); } } void CTaikaDlg::OnTuoLaskutusohjelmasta() { OnImport(); } ///////////////////////////////////////////////////////////////////////////// // IDM_TYOMATKAT_MENU - Menu itemien viestit void CTaikaDlg::OnAvaaRaporttiTm() { //int s; Parse parse; if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) // Avaa .tti-tiedosto { if(!parse.avaaTTI(this->GetSafeHwnd())) return; } paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); } void CTaikaDlg::OnTalletaRaporttiTm() { Parse parse; vector <ItemData_travel*> id_vect; // Haetaan GetSaveFileName()-funktiossa valitun tilan mukaan vektoriin talletettavat tiedot if(m_mainShowMode != SHOW_TYOMATKAT || !pageTyomatkat.IsWindowVisible()) return; pageTyomatkat.haeItemDataList(&id_vect, MODE_TYONTEKIJANTIEDOT); if(id_vect.size() > 0) { parse.talletaTTI_tyomatkat(this->GetSafeHwnd(), id_vect); // Talletetaan pageTyomatkat.vapautaItemDataList(&id_vect, MODE_TYONTEKIJANTIEDOT); // Vapautetaan muisti } } ///////////////////////////////////////////////////////////////////////////// // IDM_RAPORTIT_MENU, IDM_LISTAT_MENU, IDM_ASETUKSET - Menu itemien yhteiset viestit void CTaikaDlg::OnVarmuuskopioiTietokanta() { DlgVarmuuskopioi dlg; if(dlg.DoModal() == IDOK) paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); } void CTaikaDlg::OnVaihdaTietokanta() { DWORD e; CString file; char buf[128] = {0}; OPENFILENAME ofn; DlgParseInfo dlg; char *lpstrFile = NULL, strFileTitle[MAX_PATH]; try { file = Props::i().get(OPTIONS_DB_PATH).c_str(); if(!(lpstrFile = new char[MAX_PATH * 100])) throw(0); // Tarpeeksi tilaa useammalle tiedostonimelle ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = this->GetSafeHwnd(); ofn.lpstrFilter = Props::i().langs("TAIKADLG_4", buf, 128); ofn.lpstrTitle = Props::i().lang("TAIKADLG_5"); ofn.lpstrInitialDir = file; ofn.lpstrCustomFilter = NULL; ofn.nFilterIndex = 1; *lpstrFile = NULL; ofn.lpstrFile = lpstrFile; ofn.nMaxFile = MAX_PATH * 100; ofn.lpstrFileTitle = strFileTitle; ofn.nMaxFileTitle = MAX_PATH; ofn.Flags = OFN_EXPLORER|OFN_HIDEREADONLY|OFN_LONGNAMES|OFN_PATHMUSTEXIST; ofn.lpstrDefExt = NULL; ofn.lCustData = NULL; if(!GetOpenFileName(&ofn)) throw(0); Props::i().set(OPTIONS_DB_PATH, ofn.lpstrFile); // talleta, mahdollisesti uusi, polku asetuksiin Props::i().set(OPTIONS_DB_NAME, (char*)(ofn.lpstrFile + ofn.nFileOffset)); Props::e().m_db_path = ofn.lpstrFile; paivitaNaytot(TRUE, TRUE, TRUE, SYNC_ALL); } catch(...) { if((e = CommDlgExtendedError()) != ERROR_SUCCESS) { file.Format(Props::i().lang("TAIKADLG_6"), e); MessageBox(file, Props::e().m_app_title, MB_ICONEXCLAMATION|MB_TASKMODAL|MB_TOPMOST|MB_OK); } } if(lpstrFile) delete [] lpstrFile; } void CTaikaDlg::OnAsetukset() { CDlgAsetukset dlg; dlg.DoModal(); } void CTaikaDlg::OnLuoUusiTietokanta() { CDlgLuoUusiTietokanta dlg; if(dlg.DoModal() == IDOK) paivitaNaytot(TRUE, TRUE, TRUE, SYNC_ALL); } void CTaikaDlg::OnSiivoaTietokanta() { DlgSiivoaTietokanta dlg; if(dlg.DoModal() == IDOK) paivitaNaytot(TRUE, TRUE, FALSE, SYNC_ALL); } // Accelerator-näppäimet (kaasutusnäppäimet) void CTaikaDlg::OnValitsekaikki() { if(GetForegroundWindow() != this) GetForegroundWindow()->PostMessage(WM_USER_SELECTALL); else { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.valitseKaikki(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.valitseKaikki(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) pageTyomatkat.valitseKaikki(); } } void CTaikaDlg::OnAvaa() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) OnAvaaRaportti(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) OnAvaaListat(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) OnAvaaRaporttiTm(); } } void CTaikaDlg::OnTalleta() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) OnTalletaRaportti(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) OnTalletaListat(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) OnTalletaRaporttiTm(); } } void CTaikaDlg::OnEtsi() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.etsi(KEY_CTRLF); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.etsi(KEY_CTRLF); } } void CTaikaDlg::OnEtsiF3() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.etsi(KEY_F3); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.etsi(KEY_F3); } } void CTaikaDlg::OnPoista() { poista(); } BOOL CTaikaDlg::poista() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.poistaItems(); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.poista(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) pageTyomatkat.poistaValitut(); return TRUE; } return FALSE; } void CTaikaDlg::OnUusi() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_RAPORTIT && pageRaportit.IsWindowVisible()) pageRaportit.lisaaTapahtuma(0); if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) pageListat.lisaa(); if(m_mainShowMode == SHOW_TYOMATKAT && pageTyomatkat.IsWindowVisible()) pageTyomatkat.lisaaUusi(0); } } void CTaikaDlg::OnImport() { if(GetForegroundWindow() == this) { if(m_mainShowMode == SHOW_LISTAT && pageListat.IsWindowVisible()) { if(pageListat.importListat() == IDOK) paivitaNaytot(TRUE, FALSE, FALSE, SYNC_ALL); } } } void CTaikaDlg::OnPaivitaV5() { if(GetForegroundWindow() == this) paivitaNaytot(TRUE, TRUE, TRUE, SYNC_ALL); } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // Yhteiset funktiot // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // void CTaikaDlg::paivitaNaytot(BOOL date, BOOL select, BOOL database, int type) { // Keskitetty näyttöjen päivitys if(m_mainShowMode == SHOW_RAPORTIT) { pageRaportit.paivitaAARListat("", NULL, FALSE); pageRaportit.paivitaTyontekijat("", NULL, FALSE); pageRaportit.paivitaTyotyyppi("", NULL, FALSE); pageRaportit.paivitaPaivays(0, "", NULL, FALSE); if(date) pageRaportit.paivitaPaivays(0, "", NULL, FALSE); if(select) pageRaportit.uusiHaku(NULL); syncListat(SYNC_FROM_RAPORTIT, type); } if(m_mainShowMode == SHOW_LISTAT) { pageListat.paivitaAsiakasryhmat("", TRUE); pageListat.paivitaAsiakkaat(""); pageListat.paivitaTila(); syncListat(SYNC_FROM_LISTAT, type); } if(m_mainShowMode == SHOW_TYOMATKAT) { pageTyomatkat.paivitaTyontekijat("", NULL, FALSE); pageTyomatkat.paivitaPaivays(0, "", NULL, FALSE); if(date) pageTyomatkat.paivitaPaivays(0, "", NULL, FALSE); if(select) pageTyomatkat.uusiHaku(NULL); syncListat(SYNC_FROM_TYOMATKAT, type); } if(database) usedDB(); } void CTaikaDlg::syncListat(int from, int type) { // Listojen muutokset heijastuu kaikkien eri näyttöjen listoihin -> välitä tieto päivityksestä näytöille if(from != SYNC_FROM_RAPORTIT) Props::e().m_sync_raportit |= type; if(from != SYNC_FROM_LISTAT) Props::e().m_sync_listat |= type; if(from != SYNC_FROM_TYOMATKAT) Props::e().m_sync_tyomatkat |= type; // Etsi-toiminnon vanhat osumat poistetaan, jos asiakkaat muuttuneet if((type&SYNC_ASIAKKAAT) || (type&SYNC_ASIAKASRYHMAT)) Props::e().m_dlgEtsi.clear(); } void CTaikaDlg::usedDB() { CString cs; cs = Props::i().lang("APPNAME") + CString(" - ") + Props::i().get(OPTIONS_DB_NAME).c_str(); this->SetWindowText(cs); }
ptesavol/t-time
VS2005App/taikaDlg.cpp
C++
gpl-2.0
25,345
// Generated by CoffeeScript 1.8.0 (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; (function(jQuery) { var $, $event, AwesomeGallery, CustomAdapter, FooBoxAdapter, GalleryFilters, JetpackAdapter, LightboxAdapter, MagnificPopupAdapter, Modernizr, PrettyPhotoAdapter, SwipeboxAdapter, capitalize, classes, dispatchMethod, document, getStyleProperty, iLightboxAdapter, prefixes, resizeTimeout, result, setIsoTransform, testName, tests, transformFnNotations, transformProp, transitionDurProp, transitionEndEvent, transitionProp; if (!jQuery) { return alert('Message from UberGrid: jQuery not found!'); } else { if (parseInt(jQuery().jquery.replace(/\./g, '')) < 172) { return alert('Message from Awesome Gallery: You have jQuery < 1.7.2. Please upgrade your jQuery or enable "Force new jQuery version" option at Awesome Gallery settings page.'); } else { $ = jQuery; document = window.document; Modernizr = window.Modernizr; transitionEndEvent = null; capitalize = function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }; prefixes = "Moz Webkit O Ms".split(" "); getStyleProperty = function(propName) { var i, len, prefixed, style; style = document.documentElement.style; prefixed = void 0; if (typeof style[propName] === "string") { return propName; } propName = capitalize(propName); i = 0; len = prefixes.length; while (i < len) { prefixed = prefixes[i] + propName; if (typeof style[prefixed] === "string") { return prefixed; } i++; } }; transformProp = getStyleProperty("transform"); transitionProp = getStyleProperty("transitionProperty"); tests = { csstransforms: function() { return !!transformProp; }, csstransforms3d: function() { var $div, $style, mediaQuery, test, vendorCSSPrefixes; test = !!getStyleProperty("perspective"); if (test) { vendorCSSPrefixes = " -o- -moz- -ms- -webkit- -khtml- ".split(" "); mediaQuery = "@media (" + vendorCSSPrefixes.join("transform-3d),(") + "modernizr)"; $style = $("<style>" + mediaQuery + "{#modernizr{height:3px}}" + "</style>").appendTo("head"); $div = $("<div id=\"modernizr\" />").appendTo("html"); test = $div.height() === 3; $div.remove(); $style.remove(); } return test; }, csstransitions: function() { return !!transitionProp; } }; testName = void 0; if (Modernizr) { for (testName in tests) { if (!Modernizr.hasOwnProperty(testName)) { Modernizr.addTest(testName, tests[testName]); } } } else { Modernizr = window.Modernizr = { _version: "1.6ish: miniModernizr for Isotope" }; classes = " "; result = void 0; for (testName in tests) { result = tests[testName](); Modernizr[testName] = result; classes += " " + (result ? "" : "no-") + testName; } $("html").addClass(classes); } /* provides hooks for .css({ scale: value, translate: [x, y] }) Progressively enhanced CSS transforms Uses hardware accelerated 3D transforms for Safari or falls back to 2D transforms. */ if (Modernizr.csstransforms) { transformFnNotations = (Modernizr.csstransforms3d ? { translate: function(position) { return "translate3d(" + position[0] + "px, " + position[1] + "px, 0) "; }, scale: function(scale) { return "scale3d(" + scale + ", " + scale + ", 1) "; } } : { translate: function(position) { return "translate(" + position[0] + "px, " + position[1] + "px) "; }, scale: function(scale) { return "scale(" + scale + ") "; } }); setIsoTransform = function(elem, name, value) { var data, fnName, newData, scaleFn, transformObj, transformValue, translateFn, valueFns; data = $.data(elem, "isoTransform") || {}; newData = {}; fnName = void 0; transformObj = {}; transformValue = void 0; newData[name] = value; $.extend(data, newData); for (fnName in data) { transformValue = data[fnName]; transformObj[fnName] = transformFnNotations[fnName](transformValue); } translateFn = transformObj.translate || ""; scaleFn = transformObj.scale || ""; valueFns = translateFn + scaleFn; $.data(elem, "isoTransform", data); elem.style[transformProp] = valueFns; }; $.cssNumber.scale = true; $.cssHooks.scale = { set: function(elem, value) { setIsoTransform(elem, "scale", value); }, get: function(elem, computed) { var transform; transform = $.data(elem, "isoTransform"); if (transform && transform.scale) { return transform.scale; } else { return 1; } } }; $.fx.step.scale = function(fx) { $.cssHooks.scale.set(fx.elem, fx.now + fx.unit); }; $.cssNumber.translate = true; $.cssHooks.translate = { set: function(elem, value) { setIsoTransform(elem, "translate", value); }, get: function(elem, computed) { var transform; transform = $.data(elem, "isoTransform"); if (transform && transform.translate) { return transform.translate; } else { return [0, 0]; } } }; } transitionEndEvent = void 0; transitionDurProp = void 0; if (Modernizr.csstransitions) { transitionEndEvent = { WebkitTransitionProperty: "webkitTransitionEnd", MozTransitionProperty: "transitionend", OTransitionProperty: "oTransitionEnd otransitionend", transitionProperty: "transitionend" }; [ { transitionProp: transitionProp } ]; transitionDurProp = getStyleProperty("transitionDuration"); } $event = $.event; dispatchMethod = ($.event.handle ? "handle" : "dispatch"); resizeTimeout = void 0; $event.special.smartresize = { setup: function() { $(this).bind("resize", $event.special.smartresize.handler); }, teardown: function() { $(this).unbind("resize", $event.special.smartresize.handler); }, handler: function(event, execAsap) { var args, context; context = this; args = arguments; event.type = "smartresize"; if (resizeTimeout) { clearTimeout(resizeTimeout); } resizeTimeout = setTimeout(function() { $event[dispatchMethod].apply(context, args); }, (execAsap === "execAsap" ? 0 : 100)); } }; $.fn.smartresize = function(fn) { if (fn) { return this.bind("smartresize", fn); } else { return this.trigger("smartresize", ["execAsap"]); } }; LightboxAdapter = (function() { LightboxAdapter.create = function($images, config) { switch (config.name) { case 'magnific-popup': return new MagnificPopupAdapter($images, config); case 'swipebox': return new SwipeboxAdapter($images, config); case 'prettyphoto': return new PrettyPhotoAdapter($images, config); case 'ilightbox': return new iLightboxAdapter($images, config); case 'jetpack': return new JetpackAdapter($images, config); case 'foobox': return new FooBoxAdapter($images, config); default: return null; } }; function LightboxAdapter($el, config) { this.onPrevSlide = __bind(this.onPrevSlide, this); this.onNextSlide = __bind(this.onNextSlide, this); this.onAfterClose = __bind(this.onAfterClose, this); this.onKeyUp = __bind(this.onKeyUp, this); this.setHash = __bind(this.setHash, this); this.getInstanceIndex = __bind(this.getInstanceIndex, this); this.onImageClicked = __bind(this.onImageClicked, this); this.getLightboxCaption2 = __bind(this.getLightboxCaption2, this); this.getLightboxCaption1 = __bind(this.getLightboxCaption1, this); this.getSlug = __bind(this.getSlug, this); this.getId = __bind(this.getId, this); this.getAllLightboxLinks = __bind(this.getAllLightboxLinks, this); this.getLightboxLinks = __bind(this.getLightboxLinks, this); this.getDeeplinkImage = __bind(this.getDeeplinkImage, this); this.clickImage = __bind(this.clickImage, this); this.loadDeepLink = __bind(this.loadDeepLink, this); this.checkForDeeplink = __bind(this.checkForDeeplink, this); this.addImages = __bind(this.addImages, this); this.reset = __bind(this.reset, this); this.$el = $el; this.config = config; this.getAllLightboxLinks().off('click').removeClass('prettyphoto').removeClass('thickbox'); setTimeout(this.reset, 1); this.reset(); this.checkForDeeplink(); } LightboxAdapter.prototype.reset = function() { this.getAllLightboxLinks().off('click', this.onImageClicked); return this.getLightboxLinks().on('click', this.onImageClicked); }; LightboxAdapter.prototype.addImages = function(images) { return this.reset(); }; LightboxAdapter.prototype.checkForDeeplink = function() { var gridId, image; if (location.hash.match(/^#\d+\-/)) { gridId = location.hash.replace(/^\#/, '').replace(/\-.*/, ''); if (gridId !== this.getId()) { return false; } image = location.hash.replace(/^.*\//, ''); this.loadDeepLink(image); return true; } }; LightboxAdapter.prototype.loadDeepLink = function(image) { var linkedImage; linkedImage = this.getDeeplinkImage(image); if (linkedImage.length > 0) { return this.clickImage(linkedImage); } else { return this.config.loadMoreCallback(); } }; LightboxAdapter.prototype.clickImage = function(image) { return $(image).find('a.asg-lightbox').click(); }; LightboxAdapter.prototype.getDeeplinkImage = function(id) { return jQuery.grep(this.getLightboxLinks().closest('.asg-image'), (function(_this) { return function(cell) { return $(cell).data('slug').toString() === id; }; })(this)); }; LightboxAdapter.prototype.linkSelector = '.asg-image:not(.asg-hidden) .asg-image-wrapper.asg-lightbox'; LightboxAdapter.prototype.allLinkSelector = '.asg-image .asg-image-wrapper.asg-lightbox'; LightboxAdapter.prototype.getLightboxLinks = function() { return this.$el.find(this.linkSelector); }; LightboxAdapter.prototype.getAllLightboxLinks = function() { return this.$el.find(this.allLinkSelector); }; LightboxAdapter.prototype.getId = function() { return this.$el.parent().attr('id').replace(/\-\d+$/, '').replace(/^.*\-/, ''); }; LightboxAdapter.prototype.getSlug = function() { return this.$el.parent().attr('data-slug'); }; LightboxAdapter.prototype.getLightboxCaption1 = function(el) { var caption_1; if (caption_1 = el.find('.asg-lightbox-caption1').html()) { caption_1 = $('<h3 />').html(caption_1)[0].outerHTML; } else { caption_1 = ''; } return caption_1; }; LightboxAdapter.prototype.getLightboxCaption2 = function(el) { var caption_2; if (caption_2 = el.find('.asg-lightbox-caption2').html()) { caption_2 = $('<div />').html(caption_2)[0].outerHTML; } else { caption_2 = ''; } return caption_2; }; LightboxAdapter.prototype.onImageClicked = function(event) { var cell; cell = jQuery(event.target).closest('.asg-image'); this.scrollTop = jQuery(document).scrollTop(); return this.setHash(cell); }; LightboxAdapter.prototype.getID = function() { return this.$el.parent().attr('id').replace(/\-\d+$/, '').replace(/.+\-/, ''); }; LightboxAdapter.prototype.getInstanceIndex = function() { return this.$el.parent().attr('id').replace(/.*\-/, ''); }; LightboxAdapter.prototype.setHash = function(cell) { var cellSlug, id; id = this.getID(); cellSlug = cell.data('slug'); this.prevHash = location.hash; return location.hash = "" + id + "-" + (this.getSlug()) + "/" + cellSlug; }; LightboxAdapter.prototype.resetHash = function() { if (this.prevHash) { location.hash = this.prevHash; delete this.prevHash; } else { location.hash = '#'; } if (this.scrollTop && this.scrollTop > 0) { return jQuery(document).scrollTop(this.scrollTop); } }; LightboxAdapter.prototype.onKeyUp = function(event) { if (event.keyCode === 37) { return this.onPrevSlide(); } else if (event.keyCode === 39) { return this.onNextSlide(); } else if (event.keyCode === 27) { return this.onAfterClose(); } }; LightboxAdapter.prototype.onAfterClose = function() { $(window).off('keyup', this.onKeyup); return this.resetHash(); }; LightboxAdapter.prototype.onNextSlide = function() { var lightboxLinks; this.currentIndex += 1; lightboxLinks = this.getLightboxLinks(); if (this.currentIndex === lightboxLinks.length) { this.currentIndex = lightboxLinks.length - 1; } return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); }; LightboxAdapter.prototype.onPrevSlide = function() { this.currentIndex -= 1; if (this.currentIndex < 0) { this.currentIndex = 0; } return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); }; return LightboxAdapter; })(); CustomAdapter = (function(_super) { __extends(CustomAdapter, _super); function CustomAdapter() { return CustomAdapter.__super__.constructor.apply(this, arguments); } return CustomAdapter; })(LightboxAdapter); FooBoxAdapter = (function(_super) { __extends(FooBoxAdapter, _super); function FooBoxAdapter() { this.addImages = __bind(this.addImages, this); this.initFoobox = __bind(this.initFoobox, this); this.fooboxPresent = __bind(this.fooboxPresent, this); this.reset = __bind(this.reset, this); return FooBoxAdapter.__super__.constructor.apply(this, arguments); } FooBoxAdapter.prototype.reset = function() { FooBoxAdapter.__super__.reset.call(this); if (this.fooboxPresent()) { return this.initFoobox(); } else { return $((function(_this) { return function() { if (_this.fooboxPresent()) { return _this.initFoobox(); } }; })(this)); } }; FooBoxAdapter.prototype.fooboxPresent = function() { return window.FOOBOX && window.FOOBOX.o; }; FooBoxAdapter.prototype.initFoobox = function() { var fooboxOptions; fooboxOptions = jQuery.extend({}, window.FOOBOX.o, { deeplinking: false, affiliate: false, slideshow: { enabled: true }, selector: this.linkSelector }); return this.$el.foobox(fooboxOptions).on('foobox.afterLoad', (function(_this) { return function(event) { return _this.setHash(_this.getLightboxLinks().eq(event.fb.item.index).closest('.asg-image')); }; })(this)).on('foobox.close', (function(_this) { return function() { return _this.resetHash(); }; })(this)); }; FooBoxAdapter.prototype.addImages = function(images) { var image, _i, _len; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; image = $(image).closest('.asg-image'); image.attr('title', this.getLightboxCaption1(image)); image.find('img').attr('alt', this.getLightboxCaption2(image)); } return FooBoxAdapter.__super__.addImages.call(this, images); }; return FooBoxAdapter; })(LightboxAdapter); JetpackAdapter = (function(_super) { __extends(JetpackAdapter, _super); function JetpackAdapter($el, config) { this.onPrevSlide = __bind(this.onPrevSlide, this); this.onNextSlide = __bind(this.onNextSlide, this); this.setHashFromCurrentIndex = __bind(this.setHashFromCurrentIndex, this); this.onAfterClose = __bind(this.onAfterClose, this); this.startCarousel = __bind(this.startCarousel, this); this.onImageClicked = __bind(this.onImageClicked, this); this.addImages = __bind(this.addImages, this); JetpackAdapter.__super__.constructor.call(this, $el, config); this.$el.data('carousel-extra', { blog_id: 1, permalink: 'http://awesome-gallery.dev' }); } JetpackAdapter.prototype.addImages = function(images) { var image, url, wrapper, _i, _len; images.addClass('tiled-gallery-item'); for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; image = $(image); wrapper = image.closest('.asg-image'); url = image.find('.asg-image-wrapper').attr('href'); image.find('img').data({ 'orig-file': url, 'orig-size': "" + (wrapper.data('width')) + "," + (wrapper.data('height')), 'large-file': url, 'medium-file': url, 'small-file': url, 'image-title': this.getLightboxCaption1(wrapper), 'image-description': this.getLightboxCaption2(wrapper), 'image-meta': wrapper.data('meta'), 'attachment-id': wrapper.data('attachment-id') ? wrapper.data('attachment-id') : 'asg-hack', 'comments-opened': wrapper.data('attachment-id') ? 1 : null }); } return images.on('click', this.onImageClicked); }; JetpackAdapter.prototype.onImageClicked = function(event) { event.preventDefault(); if ($.fn.jp_carousel) { return this.startCarousel(event); } else { return $(document).ready(setTimeout(((function(_this) { return function() { return _this.startCarousel(event); }; })(this)), 500)); } }; JetpackAdapter.prototype.startCarousel = function(event) { this.currentIndex = this.$el.find(this.linkSelector).index($(event.target).closest('.asg-image-wrapper')); if (this.$el.jp_carousel) { this.$el.jp_carousel({ start_index: this.currentIndex, 'items_selector': ".asg-image:not(.asg-hidden) .asg-image-wrapper img" }); return setTimeout(this.setHashFromCurrentIndex, 500); } else { return $(document).ready((function(_this) { return function() { return setTimeout(function() { _this.$el.jp_carousel({ start_index: _this.currentIndex, 'items_selector': ".asg-image:not(.asg-hidden) .asg-image-wrapper img" }); return setTimeout(_this.setHashFromCurrentIndex, 500); }, 600); }; })(this)); } }; JetpackAdapter.prototype.onAfterClose = function() { JetpackAdapter.__super__.onAfterClose.apply(this, arguments); jQuery(document).off('keyup', this.onKeyUp); $('.jp-carousel-next-button').off('click', this.onNextSlide); return $('.jp-carousel-previous-button').off('click', this.onPrevSlide); }; JetpackAdapter.prototype.setHashFromCurrentIndex = function() { this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); $('.jp-carousel-next-button').click(this.onNextSlide); $('.jp-carousel-previous-button').click(this.onPrevSlide); $(document).on('keyup', this.onKeyUp); return $(document).on('click', '.jp-carousel-close-hint', this.onAfterClose); }; JetpackAdapter.prototype.onNextSlide = function() { var lightboxLinks; this.currentIndex += 1; lightboxLinks = this.getLightboxLinks(); if (this.currentIndex === lightboxLinks.length) { this.currentIndex = 0; } return setTimeout(this.setHashFromCurrentIndex, 400); }; JetpackAdapter.prototype.onPrevSlide = function() { this.currentIndex -= 1; if (this.currentIndex < 0) { this.currentIndex = this.getLightboxLinks().size() - 1; } return setTimeout(this.setHashFromCurrentIndex, 400); }; return JetpackAdapter; })(LightboxAdapter); MagnificPopupAdapter = (function(_super) { __extends(MagnificPopupAdapter, _super); function MagnificPopupAdapter($el, config) { var _this; _this = this; $el.magnificPopup({ type: 'image', delegate: this.linkSelector, gallery: { enabled: true }, mainClass: 'mfp-asg', image: { titleSrc: function() { var caption_1, caption_2, el; el = this.currItem.el.parent(); if (caption_1 = el.find('.asg-lightbox-caption1').html()) { caption_1 = $('<h3 />').html(caption_1)[0].outerHTML; } else { caption_1 = ''; } if (caption_2 = el.find('.asg-lightbox-caption2').html()) { caption_2 = $('<div />').html(caption_2)[0].outerHTML; } else { caption_2 = ''; } if (caption_1 + caption_2) { return caption_1 + caption_2; } return null; }, markup: '<div class="mfp-figure">' + '<div class="mfp-close"></div>' + '<figure>' + '<div class="mfp-img"></div>' + '<div class="mfp-asg-border"></div>' + '<figcaption>' + '<div class="mfp-bottom-bar">' + '<div class="mfp-title"></div>' + '<div class="mfp-counter"></div>' + '</div>' + '</figcaption>' + '</figure>' + '</div>' }, callbacks: { open: (function() { jQuery('.mfp-wrap').addClass('mfp-asg'); return this._lastFocusedEl = null; }), markupParse: (function(template) { return template.find('.mfp-counter').remove(); }), afterClose: (function(_this) { return function() { return _this.resetHash(); }; })(this), afterChange: function() { return _this.setHash(this.currItem.el.closest('.asg-image')); } } }); MagnificPopupAdapter.__super__.constructor.call(this, $el, config); } return MagnificPopupAdapter; })(LightboxAdapter); SwipeboxAdapter = (function(_super) { __extends(SwipeboxAdapter, _super); function SwipeboxAdapter() { this.onImageClicked = __bind(this.onImageClicked, this); return SwipeboxAdapter.__super__.constructor.apply(this, arguments); } SwipeboxAdapter.prototype.onImageClicked = function(event) { var elements, lightboxImages; SwipeboxAdapter.__super__.onImageClicked.call(this, event); event.preventDefault(); elements = this.$el.find(this.linkSelector); lightboxImages = $.map(elements, (function(_this) { return function(image) { image = $(image); return { href: image.attr('href'), title: function() { var caption1, caption2, html; image = image.closest('.asg-image'); html = $('<div/>'); if (caption2 = _this.getLightboxCaption2(image)) { html.append($('<small class="asg-small"/>').html(caption2)); } if (caption1 = _this.getLightboxCaption1(image)) { html.append($('<div />').html(caption1)); } return html.html(); } }; }; })(this)); this.currentIndex = elements.index($(event.target).closest('a.asg-image-wrapper')); $.swipebox(lightboxImages, { initialIndexOnArray: this.currentIndex }); jQuery('#swipebox-next').click(this.onNextSlide); jQuery('#swipebox-prev').click(this.onPrevSlide); return jQuery(window).on('keyup', this.onKeyUp); }; return SwipeboxAdapter; })(LightboxAdapter); PrettyPhotoAdapter = (function(_super) { __extends(PrettyPhotoAdapter, _super); function PrettyPhotoAdapter() { this.onPrevSlide = __bind(this.onPrevSlide, this); this.onNextSlide = __bind(this.onNextSlide, this); this.onKeyUp = __bind(this.onKeyUp, this); this.onImageClicked = __bind(this.onImageClicked, this); return PrettyPhotoAdapter.__super__.constructor.apply(this, arguments); } PrettyPhotoAdapter.prototype.onImageClicked = function(event) { var descriptions, elements, titles, urls; event.preventDefault(); event.stopPropagation(); elements = this.$el.find(this.linkSelector); urls = elements.map((function(_this) { return function(index, image) { return $(image).closest('a.asg-image-wrapper').attr('href'); }; })(this)); titles = elements.map((function(_this) { return function(index, image) { return _this.getLightboxCaption1($(image).closest('.asg-image')); }; })(this)); descriptions = elements.map((function(_this) { return function(index, image) { return _this.getLightboxCaption2($(image).closest('.asg-image')); }; })(this)); $.fn.prettyPhoto(this.config.settings); $.prettyPhoto.open(urls, titles, descriptions, this.currentIndex = elements.index($(event.target).closest('.asg-image-wrapper'))); this.setHash($(event.target).closest('.asg-image')); $(document).on('keydown.prettyphoto', this.onKeyUp); $('.pp_previous').on('click.asg', this.onPrevSlide); return $('.pp_next').on('click.asg', this.onNextSlide); }; PrettyPhotoAdapter.prototype.onKeyUp = function(event) { if (event.keyCode === 37) { return this.onPrevSlide(); } else if (event.keyCode === 39) { return this.onNextSlide(); } else if (event.keyCode === 27) { return this.resetHash(); } }; PrettyPhotoAdapter.prototype.onNextSlide = function() { var lightboxLinks; this.currentIndex += 1; lightboxLinks = this.getLightboxLinks(); if (this.currentIndex === lightboxLinks.length) { this.currentIndex = lightboxLinks.length - 1; } return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); }; PrettyPhotoAdapter.prototype.onPrevSlide = function() { this.currentIndex -= 1; if (this.currentIndex < 0) { this.currentIndex = 0; } return this.setHash(this.getLightboxLinks().eq(this.currentIndex).closest('.asg-image')); }; return PrettyPhotoAdapter; })(LightboxAdapter); iLightboxAdapter = (function(_super) { __extends(iLightboxAdapter, _super); function iLightboxAdapter($el, config) { this.onImageClicked = __bind(this.onImageClicked, this); if (!$.iLightBox) { alert('iLightbox not detected. Please install end enable iLightbox plugin.'); } iLightboxAdapter.__super__.constructor.call(this, $el, config); } iLightboxAdapter.prototype.onImageClicked = function(event) { var elements, index, lightboxImages, options; iLightboxAdapter.__super__.onImageClicked.call(this, event); event.preventDefault(); elements = this.$el.find(this.linkSelector); lightboxImages = $.map(elements, (function(_this) { return function(el) { var data; data = $(el); return { title: _this.getLightboxCaption1(data), url: data.attr('href'), caption: _this.getLightboxCaption2(data), thumbnail: $(el).find('.asg-image-wrapper img').attr('src') }; }; })(this)); this.currentIndex = index = elements.index($(event.target).closest('.asg-image-wrapper')); options = $.extend(this.config.settings, ILIGHTBOX.options && eval("(" + rawurldecode(ILIGHTBOX.options) + ")") || {}); return $.iLightBox(lightboxImages, $.extend({ startFrom: index, callback: { onAfterChange: (function(_this) { return function(instance) { _this.currentIndex = instance.currentItem; return _this.setHash(elements.eq(_this.currentIndex).closest('.asg-image')); }; })(this), onHide: (function(_this) { return function() { return _this.resetHash(); }; })(this) } }, options)); }; return iLightboxAdapter; })(LightboxAdapter); GalleryFilters = (function() { function GalleryFilters($el, filterCallback) { this.onFilterClick = __bind(this.onFilterClick, this); this.createFilter = __bind(this.createFilter, this); this.createSortedFilters = __bind(this.createSortedFilters, this); this.createAll = __bind(this.createAll, this); this.add = __bind(this.add, this); var list; this.$el = $el; this.tags = []; this.filterCallback = filterCallback; this.current = null; this.$el.on('click', '.asg-filter', this.onFilterClick); this.$el.hide(); this.suspendCreation = false; if ((list = this.$el.data('list')) && list !== '') { this.add(list.split(/,\s*/)); this.suspendCreation = true; } } GalleryFilters.prototype.add = function(tags) { var tag, _i, _len; if (this.suspendCreation) { return; } for (_i = 0, _len = tags.length; _i < _len; _i++) { tag = tags[_i]; if (tag === '') { continue; } if (!this.tags.hasOwnProperty(tag)) { this.tags[tag] = true; if (!this.$el.data('sort')) { this.createFilter(tag); this.$el.show(); } } } if (this.$el.data('sort')) { this.$el.empty(); return this.createSortedFilters(); } else { if (this.tags.length !== 0) { return this.createAll(); } } }; GalleryFilters.prototype.createAll = function() { var all; this.$el.prepend(all = $("<div class='asg-filter' />").append($("<a data-tag='' href='#' />").text(this.$el.data('all')))); if (this.current === '' || this.current === null) { return all.addClass('asg-active'); } }; GalleryFilters.prototype.createSortedFilters = function() { var tag, tags, _i, _len; this.createAll(); tags = []; for (tag in this.tags) { if (this.tags.hasOwnProperty(tag)) { tags.push(tag); } } tags.sort(); for (_i = 0, _len = tags.length; _i < _len; _i++) { tag = tags[_i]; this.createFilter(tag); } if (tags.length > 0) { return this.$el.show(); } }; GalleryFilters.prototype.createFilter = function(tag) { var a, filter; filter = $('<div class="asg-filter" />').append(a = $("<a href='#' />").text(tag).attr('data-tag', tag)).appendTo(this.$el); if (tag === this.current) { return filter.addClass('asg-active'); } }; GalleryFilters.prototype.onFilterClick = function(event) { var filter; event.preventDefault(); filter = $(event.target); this.$el.find('> div').removeClass('asg-active'); $(filter).parent().addClass('asg-active'); this.current = $(filter).attr('data-tag'); return this.filterCallback(this.current); }; return GalleryFilters; })(); AwesomeGallery = (function() { var AnimationQueue, GalleryImage, GridLayoutStrategy, HorizontalFlowLayoutStrategy, ImageCaption, ImageOverlay, LayoutStrategy, SlidingElement, VerticalFlowLayoutStrategy; function AwesomeGallery(id, config) { this.dispose = __bind(this.dispose, this); this.applyFiltering = __bind(this.applyFiltering, this); this.getFilteredImages = __bind(this.getFilteredImages, this); this.add = __bind(this.add, this); this.loadMore = __bind(this.loadMore, this); this.initLoadMore = __bind(this.initLoadMore, this); this.loadMoreActive = __bind(this.loadMoreActive, this); this.deepLinkLoadMoreCallback = __bind(this.deepLinkLoadMoreCallback, this); this.showDeeplinkLoadOverlay = __bind(this.showDeeplinkLoadOverlay, this); this.showWhenVisible = __bind(this.showWhenVisible, this); var lightboxConfig; this.$window = $(window); this.id = id; this.config = config; this.page = 1; this.$el = $("#awesome-gallery-" + id); this.$el.data('awesome-gallery', this); this.$images = this.$el.find('.asg-images'); this.recursive = 0; this.animationQueue = new AnimationQueue(); if ((this.$filters = this.$el.find('.asg-filters')).size() > 0) { this.filters = new GalleryFilters(this.$filters, this.applyFiltering); } this.images = []; this.layout = LayoutStrategy.create(this.$images, this.config.layout, this.animationQueue); this.loading = false; this.loadMoreCount = 0; lightboxConfig = this.config.lightbox; if (this.loadMoreActive()) { lightboxConfig = $.extend({ loadMoreCallback: this.deepLinkLoadMoreCallback }, lightboxConfig); this.initLoadMore(); } this.lightboxAdapter = LightboxAdapter.create(this.$images, lightboxConfig); this.add(this.$el.find('.asg-image')); this.showWhenVisible(); } AwesomeGallery.prototype.showWhenVisible = function() { if (!this.$el.is(':visible') || this.$el.width() < 50) { return setTimeout(this.showWhenVisible, 250); } else { return this.layout.reLayout(); } }; AwesomeGallery.prototype.showDeeplinkLoadOverlay = function() { return this.$images.append('<div class="asg-deeplink-overlay"><div class="asg-deeplink-loader"></div></div>'); }; AwesomeGallery.prototype.deepLinkLoadMoreCallback = function() { this.loadMoreCount += 1; this.showDeeplinkLoadOverlay(); if (this.loadMoreCount < 3) { return this.loadMore((function(_this) { return function() { if (_this.lightboxAdapter.checkForDeeplink()) { return _this.$images.find('.asg-deeplink-overlay').remove(); } }; })(this)); } else { return this.$images.find('.asg-deeplink-overlay').remove(); } }; AwesomeGallery.prototype.loadMoreActive = function() { return this.$el.find('.asg-bottom').size() > 0; }; AwesomeGallery.prototype.initLoadMore = function() { if ((this.$loadMore = this.$el.find('.asg-bottom .asg-load-more')).size() > 0) { return this.$loadMore.click((function(_this) { return function() { _this.recursive = 0; return _this.loadMore(); }; })(this)); } else { return this.$window.on('scroll.asg', (function(_this) { return function() { if (!(_this.loading || _this.allLoaded)) { if (_this.$images.height() + _this.$images.offset().top - 400 < _this.$window.scrollTop() + _this.$window.height()) { return _this.loadMore(); } } }; })(this)); } }; AwesomeGallery.prototype.loadMore = function(callback) { if (this.loading || this.allLoaded) { return; } this.loading = true; if (this.$loadMore && this.$loadMore.size() > 0) { this.$loadMore.hide(); } this.$loading = this.$el.find('.asg-bottom .asg-loading').addClass('asg-visible'); return setTimeout((function(_this) { return function() { return $.post("" + _this.config.ajaxurl + "&page=" + (_this.page + 1) + "&id=" + _this.id, function(response) { var tmp; _this.loading = false; _this.page += 1; _this.$loading.removeClass('asg-visible'); if (response.have_more) { _this.$loadMore.show(); } else { _this.$el.find('.asg-bottom .asg-all-loaded').show(); _this.allLoaded = true; } tmp = $('<div/>').html(response.images); _this.add(tmp.find('.asg-image').appendTo(_this.$images)); if (callback) { return callback(); } }); }; })(this), 50); }; AwesomeGallery.prototype.add = function(images) { var image, newFilteredImages, newImage, newImages, _i, _len; newImages = []; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; newImage = new GalleryImage($(image), this.animationQueue, this.config); this.images.push(newImage); newImages.push(newImage); if (this.filters) { this.filters.add(newImage.getTags()); } } if (this.lightboxAdapter) { this.lightboxAdapter.addImages(images); } newFilteredImages = this.getFilteredImages(newImages); this.layout.add(newImages); this.layout.layout(newFilteredImages); if (newFilteredImages.length > 0) { } else { if (!this.loading && this.recursive < 2) { this.recursive += 1; return this.loadMore(); } } }; AwesomeGallery.prototype.getFilteredImages = function(images) { return images = $.grep(images, (function(_this) { return function(item) { var matches; matches = !_this.currentFilter || (jQuery.inArray(_this.currentFilter, item.getTags()) !== -1); if (matches) { item.show(); } else { item.hide(); } return matches; }; })(this)); }; AwesomeGallery.prototype.applyFiltering = function(filter) { this.currentFilter = filter; this.layout.reLayout(this.getFilteredImages(this.images)); if (this.lightboxAdapter) { this.lightboxAdapter.reset(); } return this.recursive = 0; }; AwesomeGallery.prototype.dispose = function() { this.$window.off('scroll', this.windowScrolled); if (this.$loadMore) { return this.$loadMore.off('click', this.loadNextPage); } }; SlidingElement = (function() { function SlidingElement($el, $wrapper, animationQueue) { this.slideOut = __bind(this.slideOut, this); this.cleanupClass = __bind(this.cleanupClass, this); this.slideIn = __bind(this.slideIn, this); this.getTransitionClass = __bind(this.getTransitionClass, this); this.$el = $el; this.$wrapper = $wrapper; this.animationQueue = animationQueue; if (transitionEndEvent) { this.$el.on(transitionEndEvent[transitionProp], this.cleanupClass); } else { setTimeout(((function(_this) { return function() { return _this.cleanupClass(); }; })(this)), 200); } if (!($el.hasClass('asg-position-bottom') && $el.hasClass('asg-effect-slide') && $el.hasClass('asg-on-hover'))) { if (!this.$el.hasClass('asg-off-hover')) { this.$wrapper.on('mouseout', this.cleanupClass); } if (this.$el.hasClass('asg-on-hover') && this.$el.hasClass('asg-effect-slide')) { this.$wrapper.hover(((function(_this) { return function(event) { return _this.slideIn(event); }; })(this)), (function(_this) { return function(event) { return _this.slideOut(event); }; })(this)); } } if (this.$el.hasClass('asg-off-hover') && this.$el.hasClass('asg-effect-slide')) { this.$wrapper.hover(((function(_this) { return function(event) { return _this.slideOut(event); }; })(this)), (function(_this) { return function(event) { return _this.slideIn(event); }; })(this)); } } SlidingElement.prototype.getTransitionClass = function(event) { var klass, x, y; x = event.offsetX - this.$wrapper.width() / 2; y = event.offsetY - this.$wrapper.height() / 2; if (x > 0) { if (Math.abs(x) > Math.abs(y)) { klass = 'asg-slide-right'; } else { if (y < 0) { klass = 'asg-slide-top'; } else { klass = 'asg-slide-bottom'; } } } else { if (Math.abs(x) > Math.abs(y)) { klass = 'asg-slide-left'; } else { if (y < 0) { klass = 'asg-slide-top'; } else { klass = 'asg-slide-bottom'; } } } return klass; }; SlidingElement.prototype.slideIn = function(event) { this.$el.addClass('asg-no-transition'); this.cleanupClass(); this.$el.addClass(this.getTransitionClass(event)); this.$el.height(); this.$el.removeClass('asg-no-transition'); return this.cleanupClass(); }; SlidingElement.prototype.cleanupClass = function() { var klass, _i, _len, _ref, _results; _ref = ['asg-slide-left', 'asg-slide-right', 'asg-slide-top', 'asg-slide-bottom']; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { klass = _ref[_i]; _results.push(this.$el.removeClass(klass)); } return _results; }; SlidingElement.prototype.slideOut = function(event) { var klass; klass = this.getTransitionClass(event); return this.$el.addClass(klass); }; return SlidingElement; })(); ImageOverlay = (function(_super) { __extends(ImageOverlay, _super); function ImageOverlay($el, $wrapper, animationQueue) { ImageOverlay.__super__.constructor.call(this, $el, $wrapper, animationQueue); } return ImageOverlay; })(SlidingElement); ImageCaption = (function(_super) { __extends(ImageCaption, _super); function ImageCaption($el, $wrapper, animationQueue) { this.layout = __bind(this.layout, this); var h, img; ImageCaption.__super__.constructor.call(this, $el, $wrapper, animationQueue); this.centered = $el.hasClass('asg-position-center'); if (this.centered) { $wrapper.hover(((function(_this) { return function() { return $el.css({ 'margin-top': -$el.outerHeight() / 2 }); }; })(this)), null); $el.on('resize', (function(_this) { return function() { return _this.layout(); }; })(this)); } img = $el.parent().find('img'); h = $el.height(); if ($el.hasClass('asg-position-bottom') && $el.hasClass('asg-effect-slide') && $el.hasClass('asg-on-hover')) { this.$wrapper.hover(((function(_this) { return function() { h = $el.outerHeight(); img.animate({ 'top': "-" + (h / 2) + "px" }, { 'queue': false, duration: 400 }); return $el.css({ bottom: "-" + h + "px" }).animate({ bottom: 0 }, { queue: false, duration: 350 }); }; })(this)), ((function(_this) { return function() { img.animate({ top: 0 }, { queue: false, duration: 400 }); return $el.animate({ bottom: "-" + h + "px" }, { queue: false, duration: 350 }); }; })(this))); } } ImageCaption.prototype.layout = function() { if (this.centered) { if (this.$el.hasClass('asg-mode-on') || this.$el.hasClass('asg-mode-on-hover')) { this.$el.css({ opacity: 0 }); } return setTimeout((function(_this) { return function() { var style; style = { 'margin-top': -_this.$el.outerHeight() / 2 }; if (_this.$el.hasClass('asg-mode-on') || _this.$el.hasClass('asg-mode-on-hover')) { _this.$el.css('opacity', ''); } return _this.$el.css(style); }; })(this), Math.random(500) + 600); } }; return ImageCaption; })(SlidingElement); AnimationQueue = (function() { function AnimationQueue() { this.flush = __bind(this.flush, this); this.clear = __bind(this.clear, this); this.enqueue = __bind(this.enqueue, this); } AnimationQueue.prototype.queue = []; AnimationQueue.prototype.queues = []; AnimationQueue.prototype.flushInterval = null; AnimationQueue.prototype.flushTimespan = 10; AnimationQueue.prototype.enqueue = function($el, style) { this.queue.push([$el, style]); if (!this.flushInterval) { return this.flushInterval = setTimeout(this.flush, this.flushTimespan); } }; AnimationQueue.prototype.clear = function() { this.queue = []; clearTimeout(this.flushInterval); return this.flushInterval = null; }; AnimationQueue.prototype.flush = function() { var i, item; i = 50; while (i > 0 && this.queue.length > 0) { item = this.queue.shift(); item[0].css(item[1]); i -= 1; } if (this.queue.length > 0) { this.flushInterval = setTimeout(this.flush, this.flushTimespan); return this.flushInterval = null; } }; return AnimationQueue; })(); GalleryImage = (function() { function GalleryImage($el, animationQueue, config) { this.slideIn = __bind(this.slideIn, this); this.layout = __bind(this.layout, this); this.getTags = __bind(this.getTags, this); this.show = __bind(this.show, this); this.hide = __bind(this.hide, this); var $caption, $overlay; this.$el = $el; this.animationQueue = animationQueue; this.$image = this.$el.find('.asg-image-wrapper img'); if (window.devicePixelRatio) { this.$image.attr('src', this.$image.attr('src') + ("&zoom=" + window.devicePixelRatio)); } if (this.$image[0].complete || this.$image[0].naturalWidth > 0) { this.$el.addClass('asg-loaded'); } else { this.$image.on('load', (function(_this) { return function() { return _this.$el.addClass('asg-loaded'); }; })(this)); } this.naturalWidth = this.$el.data('width'); this.naturalHeight = this.$el.data('height'); this.$el.data('asg-image', this); this.config = config; if (($overlay = this.$el.find('.asg-image-overlay')).size() > 0) { this.overlay = new ImageOverlay($overlay, this.$el, this.animationQueue); } if (($caption = this.$el.find('.asg-image-caption-wrapper')).size() > 0) { this.caption = new ImageCaption($caption, this.$el, this.animationQueue); } this.laidOut = false; this.$el.on('transitionend', (function(_this) { return function() { return setTimeout(function() { _this.$el.addClass('asg-laid-out'); return _this.laidOut = true; }, Math.random() * 1000 + 100); }; })(this)); } GalleryImage.prototype.hide = function() { return this.$el.addClass('asg-hidden'); }; GalleryImage.prototype.show = function() { return this.$el.removeClass('asg-hidden'); }; GalleryImage.prototype.getTags = function() { if (this.tags) { return this.tags; } return this.tags = this.$el.data('tags').split(', '); }; GalleryImage.prototype.layout = function(x, y, width, height) { var css; if (!this.laidOut) { setTimeout((function(_this) { return function() { _this.$el.addClass('asg-laid-out'); return _this.laidOut = true; }; })(this), Math.random() * 1000 + 100); } if (Modernizr.csstransforms && Modernizr.csstransitions) { css = { translate: [x, y] }; } else { css = { left: x, top: y }; } if (width && height) { this.animationQueue.enqueue(this.$el, $.extend(css, { width: width, height: height })); } else { this.animationQueue.enqueue(this.$el, css); } if (this.caption) { return this.caption.layout(); } }; GalleryImage.prototype.slideIn = function(event, element, zero) { var css, x, y; x = event.offsetX - this.wrapper.width() / 2; y = event.offsetY - this.wrapper.height() / 2; if (Math.abs(x) > Math.abs(y)) { if (x > 0) { css = { 'left': "" + (this.wrapper.width()) + "px", top: 0 }; } else { css = { 'left': "-" + (this.wrapper.width()) + "px", top: 0 }; } } else { if (y < 0) { css = { 'top': "-" + (this.wrapper.height()) + "px", left: 0 }; } else { css = { 'top': "" + (this.wrapper.height()) + "px", left: 0 }; } } return element.css(css).animate(zero, 'fast'); }; GalleryImage.prototype.slideOut = function(event, element) { var css, x, y; x = event.offsetX - this.wrapper.width() / 2; y = event.offsetY - this.wrapper.height() / 2; if (x > 0) { if (Math.abs(x) > Math.abs(y)) { css = { 'left': "" + (this.wrapper.width()) + "px" }; } else { if (y < 0) { css = { 'top': "-" + (this.wrapper.height()) + "px" }; } else { css = { 'top': "" + (this.wrapper.height()) + "px" }; } } } else { if (Math.abs(x) > Math.abs(y)) { css = { 'left': "-" + (this.wrapper.width()) + "px" }; } else { if (y < 0) { css = { 'top': "-" + (this.wrapper.height()) + "px" }; } else { css = { 'top': "" + (this.wrapper.height()) + "px" }; } } } return element.animate(css, 'fast'); }; return GalleryImage; })(); LayoutStrategy = (function() { LayoutStrategy.create = function(wrapper, config, animationQueue) { if (config.mode === "usual") { return new GridLayoutStrategy(wrapper, config, animationQueue); } else if (config.mode === "vertical-flow") { return new VerticalFlowLayoutStrategy(wrapper, config, animationQueue); } else if (config.mode === 'horizontal-flow') { return new HorizontalFlowLayoutStrategy(wrapper, config, animationQueue); } }; function LayoutStrategy($el, options, animationQueue) { this.getColumnWidth = __bind(this.getColumnWidth, this); this.getColumns = __bind(this.getColumns, this); this.reLayoutRequired = __bind(this.reLayoutRequired, this); this.layout = __bind(this.layout, this); this.add = __bind(this.add, this); this.reset = __bind(this.reset, this); this.reLayout = __bind(this.reLayout, this); this.onResized = __bind(this.onResized, this); this.$el = $el; this.images = []; this.animationQueue = animationQueue; $(window).smartresize(this.onResized); this.checkLayoutInterval = setInterval(this.onResized, 500); this.options = options; this.reset(); } LayoutStrategy.prototype.onResized = function() { if (this.reLayoutRequired()) { return this.reLayout(); } }; LayoutStrategy.prototype.reLayout = function(images) { if (images == null) { images = null; } if (images) { this.images = images; } this.reset(); return this.layout(); }; LayoutStrategy.prototype.reset = function() { this.index = 0; this.width = this.$el.parent().width(); this.columns = this.getColumns(); return this.columnWidth = this.getColumnWidth(); }; LayoutStrategy.prototype.add = function(images) { return this.images = this.images.concat(images); }; LayoutStrategy.prototype.layout = function(images) { var size; if (images == null) { images = null; } images = images || this.images; this.animationQueue.clear(); this.placeItems(images); size = this.getContainerSize(); return this.$el.css({ width: size.width + "px", height: size.height + "px" }); }; LayoutStrategy.prototype.reLayoutRequired = function() { return this.$el.parent().width() !== this.width; }; LayoutStrategy.prototype.getColumns = function() { var columns, fullWidth, width; width = this.width; columns = Math.floor((width + this.options.gap) / (this.options.width + this.options.gap + this.options.border * 2)); fullWidth = columns * (this.options.width + this.options.border * 2) + (columns - 1) * this.options.gap; if (width > fullWidth) { columns = columns + 1; } if (columns === 0) { columns = 1; } return columns; }; LayoutStrategy.prototype.getColumnWidth = function() { var columns; columns = this.columns; if (columns > 1) { return Math.floor((this.width + this.options.gap) / columns - this.options.gap); } return this.width; }; return LayoutStrategy; })(); GridLayoutStrategy = (function(_super) { __extends(GridLayoutStrategy, _super); function GridLayoutStrategy() { this.getContainerSize = __bind(this.getContainerSize, this); this.placeItems = __bind(this.placeItems, this); this.reset = __bind(this.reset, this); return GridLayoutStrategy.__super__.constructor.apply(this, arguments); } GridLayoutStrategy.prototype.reset = function() { GridLayoutStrategy.__super__.reset.apply(this, arguments); return this.rowHeight = Math.floor(this.options.height * this.columnWidth / this.options.width); }; GridLayoutStrategy.prototype.placeItems = function(images) { var border, col, image, row, x, y, _i, _len, _results; if (this.index === 0 && images.length < this.columns) { this.columns = images.length; this.columnWidth = this.options.width; this.rowHeight = this.options.height; } border = this.options.border * 2; _results = []; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; col = this.index % this.columns; row = Math.floor(this.index / this.columns); x = col * (this.columnWidth + this.options.gap); y = row * (this.rowHeight + this.options.gap); image.layout(x, y, this.columnWidth - border, Math.floor(this.rowHeight - border)); _results.push(this.index += 1); } return _results; }; GridLayoutStrategy.prototype.getContainerSize = function() { var size; size = {}; size.height = Math.ceil(1.0 * this.index / this.columns) * (this.rowHeight + this.options.gap + this.options.border); if (this.options.hanging === 'hide' && this.index % this.columns !== 0) { size.height -= this.rowHeight + this.options.gap + this.options.border; } if (this.index <= this.columns) { size.width = this.columnWidth * this.index + this.options.gap * this.index - 1; } else { size.width = this.width; } return size; }; return GridLayoutStrategy; })(LayoutStrategy); VerticalFlowLayoutStrategy = (function(_super) { __extends(VerticalFlowLayoutStrategy, _super); function VerticalFlowLayoutStrategy() { this.placeItems = __bind(this.placeItems, this); this.reset = __bind(this.reset, this); return VerticalFlowLayoutStrategy.__super__.constructor.apply(this, arguments); } VerticalFlowLayoutStrategy.prototype.reset = function() { var col, _i, _ref, _results; VerticalFlowLayoutStrategy.__super__.reset.apply(this, arguments); this.columnHeights = []; this.columnImages = []; _results = []; for (col = _i = 0, _ref = this.columns - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; col = 0 <= _ref ? ++_i : --_i) { this.columnImages[col] = []; _results.push(this.columnHeights[col] = 0); } return _results; }; VerticalFlowLayoutStrategy.prototype.placeItems = function(images) { var columnIndex, columnWidth, columns, highestColumn, highestHeight, image, imageHeight, imageWidth, lastInHighestColumn, lastInHighestColumnHeight, lowestColumn, lowestHeight, newLowestHeight, _i, _len; if (this.index === 0 && images.length < this.columns) { this.columns = images.length; this.columnWidth = this.options.width; } columns = this.columns; columnWidth = this.columnWidth; imageWidth = columnWidth - this.options.border * 2; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; imageHeight = image.naturalHeight * imageWidth * 1.0 / image.naturalWidth; columnIndex = this.index % columns; this.columnImages[columnIndex].push(image); image.layout(columnIndex * columnWidth + this.options.gap * columnIndex, this.columnHeights[columnIndex] + this.options.gap, imageWidth, imageHeight); this.columnHeights[columnIndex] += imageHeight + this.options.gap + this.options.border * 2; this.index += 1; } while (true) { lowestColumn = $.inArray(Math.min.apply(null, this.columnHeights), this.columnHeights); highestColumn = $.inArray(Math.max.apply(null, this.columnHeights), this.columnHeights); if (lowestColumn === highestColumn) { return; } lastInHighestColumn = this.columnImages[highestColumn].pop(); if (!lastInHighestColumn) { return; } lastInHighestColumnHeight = lastInHighestColumn.naturalHeight * imageWidth / lastInHighestColumn.naturalWidth + this.options.gap + this.options.border * 2; lowestHeight = this.columnHeights[lowestColumn]; highestHeight = this.columnHeights[highestColumn]; newLowestHeight = lowestHeight + lastInHighestColumnHeight; if (newLowestHeight >= highestHeight) { return; } this.columnImages[lowestColumn].push(lastInHighestColumn); lastInHighestColumn.layout(lowestColumn * (this.columnWidth + this.options.gap), this.columnHeights[lowestColumn] + this.options.gap); this.columnHeights[highestColumn] -= lastInHighestColumnHeight; this.columnHeights[lowestColumn] += lastInHighestColumnHeight; } }; VerticalFlowLayoutStrategy.prototype.getContainerSize = function() { var height, i, size, _i, _ref; height = 0; size = {}; for (i = _i = 0, _ref = this.columns - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) { if (this.columnHeights[i] > height) { height = this.columnHeights[i]; } } if (this.index < this.columns) { size.width = this.columnWidth * this.index; } else { size.width = this.width; } size.height = height + this.options.gap; return size; }; return VerticalFlowLayoutStrategy; })(LayoutStrategy); HorizontalFlowLayoutStrategy = (function(_super) { __extends(HorizontalFlowLayoutStrategy, _super); function HorizontalFlowLayoutStrategy() { this.getContainerSize = __bind(this.getContainerSize, this); this.placeItems = __bind(this.placeItems, this); this.startNewRow = __bind(this.startNewRow, this); this.shrinkCurrentRow = __bind(this.shrinkCurrentRow, this); this.reset = __bind(this.reset, this); return HorizontalFlowLayoutStrategy.__super__.constructor.apply(this, arguments); } HorizontalFlowLayoutStrategy.prototype.reset = function() { HorizontalFlowLayoutStrategy.__super__.reset.apply(this, arguments); this.currentRow = []; this.sizes = []; this.currentRowWidth = 0; this.rows = [this.currentRow]; this.elementSizes = [this.sizes]; this.height = 0; return this.prevWidth = 0; }; HorizontalFlowLayoutStrategy.prototype.shrinkCurrentRow = function(newHeight) { var shrinkFactor, x; x = 0; shrinkFactor = this.options.height / newHeight; return $.each(this.currentRow, (function(_this) { return function(rowIndex, image) { var imageWidth; if (rowIndex !== _this.currentRow.length - 1 || _this.currentRowWidth < _this.prevWidth) { imageWidth = Math.floor(_this.sizes[rowIndex] / shrinkFactor); image.layout(x, _this.height, imageWidth, newHeight); return x += imageWidth + _this.options.gap + _this.options.border * 2; } else { return image.layout(x, _this.height, _this.width - x - _this.options.border * 2, newHeight); } }; })(this)); }; HorizontalFlowLayoutStrategy.prototype.startNewRow = function() { this.rows.push(this.currentRow = []); this.elementSizes.push(this.sizes = []); return this.currentRowWidth = 0; }; HorizontalFlowLayoutStrategy.prototype.placeItems = function(images) { var elementWidth, height, image, index, shrinkFactor, width, x, _i, _len; width = this.width; index = 0; for (_i = 0, _len = images.length; _i < _len; _i++) { image = images[_i]; this.currentRow.push(image); this.sizes.push(elementWidth = image.naturalWidth / image.naturalHeight * this.options.height); this.currentRowWidth += elementWidth + this.options.gap + this.options.border * 2; if (this.currentRowWidth >= width + this.options.gap) { this.currentRowWidth -= this.options.gap; shrinkFactor = (this.currentRowWidth - (this.currentRow.length - 1) * this.options.gap - this.currentRow.length * this.options.border * 2) / (width - (this.currentRow.length - 1) * this.options.gap - this.currentRow.length * this.options.border * 2); height = Math.floor(this.options.height / shrinkFactor); this.shrinkCurrentRow(height); this.height += height + this.options.gap + this.options.border * 2; this.startNewRow(); } index += 1; } if (this.currentRowWidth < this.width) { x = 0; return $.each(this.currentRow, (function(_this) { return function(rowIndex, image) { var imageWidth; imageWidth = Math.floor(_this.sizes[rowIndex]); image.layout(x, _this.height, imageWidth, _this.options.height); return x += imageWidth + _this.options.gap + _this.options.border * 2; }; })(this)); } }; HorizontalFlowLayoutStrategy.prototype.getContainerSize = function() { var size; size = {}; if (this.rows.length > 1) { size.height = this.height; if (this.options.allowHanging && this.currentRowWidth < this.width && this.currentRowWidth > 0) { size.height += this.options.height + this.options.gap + this.options.border * 2; } } else { if (this.currentRow.length > 0) { size.height = this.options.height + this.options.gap + this.options.border * 2; } else { size.height = 0; } } if (this.rows.length < 2 && this.currentRowWidth > 0) { size.width = this.currentRowWidth; } else { size.width = this.width; } return size; }; return HorizontalFlowLayoutStrategy; })(LayoutStrategy); return AwesomeGallery; })(); return window.AwesomeGallery = AwesomeGallery; } } })(window.asgjQuery || window.jQuery || window.$ || jQuery || $); }).call(this);
jcwproductions/jcwproductions-blog
wp-content/plugins/awesome-gallery/assets/js/awesome-gallery.js
JavaScript
gpl-2.0
76,673
/* * tlp-dualfs.c * * TALPA Filesystem Interceptor * * Copyright (C) 2004-2011 Sophos Limited, Oxford, England. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License Version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; if not, * write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/version.h> #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/fs.h> #include <linux/unistd.h> #include <linux/slab.h> #include <linux/string.h> #include <asm/uaccess.h> #include <asm/errno.h> #include "tlp-test.h" #include "common/bool.h" #define TALPA_SUBSYS "dualfstest" #include "common/talpa.h" #include "components/services/configurator_impl/dualfs_configurator.h" #define CFGDATASIZE (sizeof(char) * 16) typedef struct { char name[CFGDATASIZE]; char value[CFGDATASIZE]; } DualfsTestConfigData; typedef struct tag_DualfsTest { IConfigurable i_IConfigurable; void (*delete)(struct tag_DualfsTest* object); bool mEnabled; PODConfigurationElement mConfig[2]; DualfsTestConfigData mConfigData[1]; } DualfsTest; static bool enable(void* self); static void disable(void* self); static const char* configName(const void* self); static const PODConfigurationElement* allConfig(const void* self); static const char* config(const void* self, const char* name); static void setConfig(void* self, const char* name, const char* value); static void deleteDualfsTest(struct tag_DualfsTest* object); #define CFG_STATUS "status" #define CFG_VALUE_ENABLED "enabled" #define CFG_VALUE_DISABLED "disabled" #define CFG_ACTION_ENABLE "enable" #define CFG_ACTION_DISABLE "disable" static DualfsTest template_DualfsTest = { { configName, allConfig, config, setConfig, 0, (void (*)(void*))deleteDualfsTest }, deleteDualfsTest, true, { {0, 0, CFGDATASIZE, true }, {0, 0, 0, false } }, { { CFG_STATUS, CFG_VALUE_ENABLED } } }; #define this ((DualfsTest*)self) static DualfsConfigurator* mConfig; static DualfsTest* mDualfsTest; DualfsTest* newDualfsTest(void) { DualfsTest* object; object = kmalloc(sizeof(template_DualfsTest), GFP_KERNEL); if (object != 0) { memcpy(object, &template_DualfsTest, sizeof(template_DualfsTest)); object->i_IConfigurable.object = object; object->mConfig[0].name = object->mConfigData[0].name; object->mConfig[0].value = object->mConfigData[0].value; } return object; } static void deleteDualfsTest(struct tag_DualfsTest* object) { if (object != 0) { kfree(object); } return; } #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36) long talpa_ioctl(struct file *file, unsigned int cmd, unsigned long parm) #else int talpa_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long parm) #endif { int ret = -ENOTTY; switch ( cmd ) { } return ret; } struct file_operations talpa_fops = { owner: THIS_MODULE, #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36) unlocked_ioctl: talpa_ioctl #else ioctl: talpa_ioctl #endif }; static int __init talpa_test_init(void) { int ret; mConfig = newDualfsConfigurator(false); if ( !mConfig ) { err("Failed to allocate configurator"); return -ENOMEM; } mDualfsTest = newDualfsTest(); if ( !mDualfsTest ) { mConfig->delete(mConfig); err("Failed to allocate dualfs test"); return -ENOMEM; } ret = mConfig->i_IConfigurator.attach(mConfig, ECG_InterceptProcessor, &mDualfsTest->i_IConfigurable); if ( ret ) { err("Failed to attach configuration!"); mDualfsTest->delete(mDualfsTest); mConfig->delete(mConfig); return ret; } ret = register_chrdev(TALPA_MAJOR, TALPA_DEVICE, &talpa_fops); if ( ret ) { err("Failed to register TALPA Test character device!"); mConfig->i_IConfigurator.detach(mConfig, &mDualfsTest->i_IConfigurable); mDualfsTest->delete(mDualfsTest); mConfig->delete(mConfig); return ret; } return 0; } static void __exit talpa_test_exit(void) { int ret; mConfig->i_IConfigurator.detach(mConfig, &mDualfsTest->i_IConfigurable); mDualfsTest->delete(mDualfsTest); mConfig->delete(mConfig); ret = talpa_unregister_chrdev(TALPA_MAJOR, TALPA_DEVICE); if ( ret ) { err("Hmmmmmm... very strange things are happening!"); } } static bool enable(void* self) { if (!this->mEnabled) { this->mEnabled = true; strcpy(this->mConfig[0].value, CFG_VALUE_ENABLED); info("Filter enabled."); } return true; } static void disable(void* self) { if (this->mEnabled) { this->mEnabled = false; strcpy(this->mConfig[0].value, CFG_VALUE_DISABLED); info("Filter disabled."); } return; } /* * IConfigurable. */ static const char* configName(const void* self) { return "DualfsTest"; } static const PODConfigurationElement* allConfig(const void* self) { return this->mConfig; } static const char* config(const void* self, const char* name) { PODConfigurationElement* cfgElement; /* * Find the named item. */ for (cfgElement = this->mConfig; cfgElement->name != 0; cfgElement++) { if (strcmp(name, cfgElement->name) == 0) { break; } } /* * Return what was found else a null pointer. */ if (cfgElement->name != 0) { return cfgElement->value; } return 0; } static void setConfig(void* self, const char* name, const char* value) { PODConfigurationElement* cfgElement; /* * Find the named item. */ for (cfgElement = this->mConfig; cfgElement->name != 0; cfgElement++) { if (strcmp(name, cfgElement->name) == 0) { break; } } /* * Cant set that which does not exist! */ if (cfgElement->name == 0) { return; } /* * OK time to do some work... */ if (strcmp(name, CFG_STATUS) == 0) { if (strcmp(value, CFG_ACTION_ENABLE) == 0) { enable(this); } else if (strcmp(value, CFG_ACTION_DISABLE) == 0) { disable(this); } } return; } /* * * Module information. * */ MODULE_AUTHOR("Sophos Limited"); MODULE_DESCRIPTION("TALPA Filesystem Interceptor Test Module"); MODULE_LICENSE("GPL"); module_init(talpa_test_init); module_exit(talpa_test_exit);
paperclip/talpa
tests/modules/tlp_dualfs.c
C
gpl-2.0
7,316
#include "packet.h" #include "net.h" #include "rtl8139.h" #include "dcload.h" unsigned int escape_loop = 0; rtl_status_t rtl; /* 8, 16, and 32 bit access to the PCI I/O space (configured by GAPS) */ static vuc * const nic8 = REGC(0xa1001700); static vus * const nic16 = REGS(0xa1001700); static vul * const nic32 = REGL(0xa1001700); /* 8, 16, and 32 bit access to the PCI MEMMAP space (configured by GAPS) */ static vuc * const mem8 = REGC(0xa1840000); static vus * const mem16 = REGS(0xa1840000); static vul * const mem32 = REGL(0xa1840000); int bb_detect() { const char *str = (char*)REGC(0xa1001400); if (!memcmp(str, "GAPSPCI_BRIDGE_2", 16)) return 0; else return -1; } void rtl_init() { unsigned int tmp; /* Soft-reset the chip */ nic8[RT_CHIPCMD] = RT_CMD_RESET; /* Wait for it to come back */ while (nic8[RT_CHIPCMD] & RT_CMD_RESET); /* Reset CONFIG1 */ nic8[RT_CONFIG1] = 0; /* Enable auto-negotiation and restart that process */ nic16[RT_MII_BMCR/2] = 0x9200; /* Do another reset */ nic8[RT_CHIPCMD] = RT_CMD_RESET; /* Wait for it to come back */ while (nic8[RT_CHIPCMD] & RT_CMD_RESET); /* Enable writing to the config registers */ nic8[RT_CFG9346] = 0xc0; /* Read MAC address */ tmp = nic32[RT_IDR0]; rtl.mac[0] = tmp & 0xff; rtl.mac[1] = (tmp >> 8) & 0xff; rtl.mac[2] = (tmp >> 16) & 0xff; rtl.mac[3] = (tmp >> 24) & 0xff; tmp = nic32[RT_IDR0+1]; rtl.mac[4] = tmp & 0xff; rtl.mac[5] = (tmp >> 8) & 0xff; /* Enable receive and transmit functions */ nic8[RT_CHIPCMD] = RT_CMD_RX_ENABLE | RT_CMD_TX_ENABLE; /* Set Rx FIFO threashold to 16 bytes, Rx size to 16k+16, 1024 byte DMA burst */ nic32[RT_RXCONFIG/4] = 0x00000e00; /* Set Tx 1024 byte DMA burst */ nic32[RT_TXCONFIG/4] = 00000600; /* Turn off lan-wake and set the driver-loaded bit */ nic8[RT_CONFIG1] = (nic8[RT_CONFIG1] & ~0x30) | 0x20; /* Enable FIFO auto-clear */ nic8[RT_CONFIG4] |= 0x80; /* Switch back to normal operation mode */ nic8[RT_CFG9346] = 0; /* Setup Rx and Tx buffers */ nic32[RT_RXBUF/4] = 0x01840000; nic32[RT_TXADDR0/4 + 0] = 0x01846000; nic32[RT_TXADDR0/4 + 1] = 0x01846800; nic32[RT_TXADDR0/4 + 2] = 0x01847000; nic32[RT_TXADDR0/4 + 3] = 0x01847800; /* Reset RXMISSED counter */ nic32[RT_RXMISSED/4] = 0; /* Enable receiving broadcast and physical match packets */ nic32[RT_RXCONFIG/4] |= 0x0000000a; /* Filter out all multicast packets */ nic32[RT_MAR0/4 + 0] = 0; nic32[RT_MAR0/4 + 1] = 0; /* Disable all multi-interrupts */ nic16[RT_MULTIINTR/2] = 0; /* clear all interrupts */ nic16[RT_INTRSTATUS/2] = 0xffff; /* Enable RX/TX once more */ nic8[RT_CHIPCMD] = RT_CMD_RX_ENABLE | RT_CMD_TX_ENABLE; /* Initialize status vars */ rtl.cur_tx = 0; rtl.cur_rx = 0; } int bb_init() { vuc * const g28 = REGC(0xa1000000); vus * const g216 = REGS(0xa1000000); vul * const g232 = REGL(0xa1000000); int i; unsigned int tmp; /* Initialize the "GAPS" PCI glue controller. It ain't pretty but it works. */ g232[0x1418/4] = 0x5a14a501; /* M */ i = 10000; while (!(g232[0x1418/4] & 1) && i > 0) i--; if (!(g232[0x1418/4] & 1)) { return -1; } g232[0x1420/4] = 0x01000000; g232[0x1424/4] = 0x01000000; g232[0x1428/4] = 0x01840000; /* DMA Base */ g232[0x142c/4] = 0x01840000 + 32*1024; /* DMA End */ g232[0x1414/4] = 0x00000001; g232[0x1434/4] = 0x00000001; /* Configure PCI bridge (very very hacky). If we wanted to be proper, we ought to implement a full PCI subsystem. In this case that is ridiculous for accessing a single card that will probably never change. Considering that the DC is now out of production officially, there is a VERY good chance it will never change. */ g216[0x1606/2] = 0xf900; g232[0x1630/4] = 0x00000000; g28[0x163c] = 0x00; g28[0x160d] = 0xf0; (void)g216[0x04/2]; g216[0x1604/2] = 0x0006; g232[0x1614/4] = 0x01000000; (void)g28[0x1650]; rtl_init(); return 0; } void bb_stop(void) { nic32[RT_RXCONFIG/4] &= 0xfffffff5; } void bb_start(void) { nic32[RT_RXCONFIG/4] |= 0x0000000a; } static vuc * const txdesc[4] = { REGC(0xa1846000), REGC(0xa1846800), REGC(0xa1847000), REGC(0xa1847800) }; int bb_tx(unsigned char * pkt, int len) { while (!(nic32[RT_TXSTATUS0/4 + rtl.cur_tx] & 0x2000)) if (nic32[RT_TXSTATUS0/4 + rtl.cur_tx] & 0x40000000) nic32[RT_TXSTATUS0/4 + rtl.cur_tx] |= 1; memcpy(txdesc[rtl.cur_tx], pkt, len); if (len < 60) /* 8139 doesn't auto-pad */ len = 60; nic32[RT_TXSTATUS0/4 + rtl.cur_tx] = len; rtl.cur_tx = (rtl.cur_tx + 1) % 4; } void pktcpy(unsigned char *dest, unsigned char *src, int n) { if (n > 1514) return; if ((unsigned int)(src + n) < (unsigned int)(0xa1840000 + 16384)) memcpy(dest, src, n); else { memcpy(dest, src, (0xa1840000 + 16384) - (unsigned int)src); memcpy(dest + ((0xa1840000 + 16384) - (unsigned int)src), (unsigned char *)0xa1840000, (unsigned int)(src + n) - (0xa1840000 + 16384)); } } unsigned char current_pkt[1514]; int bb_rx() { int avail; int processed; unsigned int rx_status; int rx_size, pkt_size, ring_offset; int i; unsigned char *pkt; processed = 0; /* While we have frames left to process... */ while (!(nic8[RT_CHIPCMD] & 1)) { /* Get frame size and status */ rx_status = mem16[0x0000/2 + rtl.cur_rx/2]; rx_size = mem16[0x0000/2 + rtl.cur_rx/2 + 1]; /* apparently this means the rtl8139 is still copying */ if (rx_size == 0xfff0) { break; } pkt_size = rx_size - 4; if (rx_status & 1) { pkt = (unsigned char*)(mem8 + 0x0000 + rtl.cur_rx + 4); pktcpy(current_pkt, pkt, pkt_size); } rtl.cur_rx = (rtl.cur_rx + rx_size + 4 + 3) & ~3; if (rtl.cur_rx >= 16384) rtl.cur_rx = rtl.cur_rx - 16384; nic16[RT_RXBUFTAIL/2] = rtl.cur_rx - 16; if (rx_status & 1) { if (pkt_size <= 1514) process_pkt(current_pkt, pkt_size); } processed++; } return processed; } extern void uint_to_string(unsigned int foo, unsigned char *bar); void bb_loop() { unsigned int intr; int i; char value[256]; intr = 0; while(!escape_loop) { /* Check interrupt status */ if (nic16[RT_INTRSTATUS/2] != intr) { intr = nic16[RT_INTRSTATUS/2]; nic16[RT_INTRSTATUS/2] = intr; } /* Did we receive some data? */ if (intr & RT_INT_RX_OK) { i = bb_rx(); } /* link change */ if (intr & RT_INT_RXFIFO_UNDERRUN) { if (booted && !running) { clear_lines(96, 24, 0); draw_string(0, 96, "link change...", 0xffff); } nic16[RT_MII_BMCR/2] = 0x9200; /* wait for valid link */ while (!(nic16[RT_MII_BMSR/2] & 0x20)); /* wait for the additional link change interrupt that is coming */ while (!(nic16[RT_INTRSTATUS/2] & RT_INT_RXFIFO_UNDERRUN)); nic16[RT_INTRSTATUS/2] = RT_INT_RXFIFO_UNDERRUN; if (booted && !running) { clear_lines(96, 24, 0); draw_string(0, 96, "idle...", 0xffff); } } /* Rx FIFO overflow */ if (intr & RT_INT_RXFIFO_OVERFLOW) { /* must clear Rx Buffer Overflow too for some reason */ nic16[RT_INTRSTATUS/2] = RT_INT_RXBUF_OVERFLOW; } /* Rx Buffer overflow */ if (intr & RT_INT_RXBUF_OVERFLOW) { rtl.cur_rx = nic16[RT_RXBUFHEAD]; nic16[RT_RXBUFTAIL]= rtl.cur_rx - 16; rtl.cur_rx = 0; nic8[RT_CHIPCMD] = RT_CMD_TX_ENABLE; nic32[RT_RXCONFIG/4] = 0x00000e0a; while ( !(nic8[RT_CHIPCMD] & RT_CMD_RX_ENABLE)) nic8[RT_CHIPCMD] = RT_CMD_TX_ENABLE | RT_CMD_RX_ENABLE; nic32[RT_RXCONFIG/4] = 0x00000e0a; nic16[RT_INTRSTATUS/2] = 0xffff; } } escape_loop = 0; }
thentenaar/dc-load-ip
target-src/dcload/rtl8139.c
C
gpl-2.0
8,056
import pathlib import h5py import numpy as np import pytest from scipy.ndimage.filters import gaussian_filter import dclab from dclab.rtdc_dataset.feat_anc_plugin.plugin_feature import ( PlugInFeature, import_plugin_feature_script, remove_plugin_feature, remove_all_plugin_features, PluginImportError) from dclab.rtdc_dataset.feat_anc_core.ancillary_feature import ( BadFeatureSizeWarning) from helper_methods import retrieve_data data_dir = pathlib.Path(__file__).parent / "data" @pytest.fixture(autouse=True) def cleanup_plugin_features(): """Fixture used to cleanup plugin feature tests""" # code run before the test pass # then the test is run yield # code run after the test # remove our test plugin examples remove_all_plugin_features() def compute_single_plugin_feature(rtdc_ds): """Basic plugin method""" circ_per_area = rtdc_ds["circ"] / rtdc_ds["area_um"] return circ_per_area def compute_multiple_plugin_features(rtdc_ds): """Basic plugin method with dictionary returned""" circ_per_area = rtdc_ds["circ"] / rtdc_ds["area_um"] circ_times_area = rtdc_ds["circ"] * rtdc_ds["area_um"] return {"circ_per_area": circ_per_area, "circ_times_area": circ_times_area} def compute_non_scalar_plugin_feature(rtdc_ds): """Basic non-scalar plugin method""" image_gauss_filter = gaussian_filter(rtdc_ds["image"], sigma=(0, 1, 1)) return {"image_gauss_filter": image_gauss_filter} def example_plugin_info_single_feature(): """plugin info for a single feature""" info = { "method": compute_single_plugin_feature, "description": "This plugin will compute a feature", "long description": "Even longer description that " "can span multiple lines", "feature names": ["circ_per_area"], "feature labels": ["Circularity per Area"], "features required": ["circ", "area_um"], "config required": [], "method check required": lambda x: True, "scalar feature": [True], "version": "0.1.0", } return info def example_plugin_info_multiple_feature(): """plugin info for multiple features""" info = { "method": compute_multiple_plugin_features, "description": "This plugin will compute some features", "long description": "Even longer description that " "can span multiple lines", "feature names": ["circ_per_area", "circ_times_area"], "feature labels": ["Circularity per Area", "Circularity times Area"], "features required": ["circ", "area_um"], "config required": [], "method check required": lambda x: True, "scalar feature": [True, True], "version": "0.1.0", } return info def example_plugin_info_non_scalar_feature(): """plugin info for non-scalar feature""" info = { "method": compute_non_scalar_plugin_feature, "description": "This plugin will compute a non-scalar feature", "long description": "This non-scalar feature is a Gaussian filter of " "the image", "feature names": ["image_gauss_filter"], "feature labels": ["Gaussian Filtered Image"], "features required": ["image"], "config required": [], "method check required": lambda x: True, "scalar feature": [False], "version": "0.1.0", } return info def compute_with_user_section(rtdc_ds): """setup a plugin method that uses user config section The "user:n_constrictions" metadata must be set """ nc = rtdc_ds.config["user"]["n_constrictions"] assert isinstance(nc, int), ( '"n_constrictions" should be an integer value.') area_of_region = rtdc_ds["area_um"] * nc return {"area_of_region": area_of_region} def test_pf_attribute_ancill_info(): """Check the plugin feature attribute input to AncillaryFeature""" info = example_plugin_info_single_feature() pf = PlugInFeature("circ_per_area", info) assert pf.plugin_feature_info["feature name"] == "circ_per_area" assert pf.plugin_feature_info["method"] is compute_single_plugin_feature assert pf.plugin_feature_info["config required"] == [] assert pf.plugin_feature_info["features required"] == ["circ", "area_um"] def test_pf_attribute_plugin_feature_info(): """Check the plugin feature info attribute""" info = example_plugin_info_single_feature() # comparing lambda functions fails due to differing memory locations info.pop("method check required") pf = PlugInFeature("circ_per_area", info) pf.plugin_feature_info.pop("method check required") plugin_feature_info = { "method": compute_single_plugin_feature, "description": "This plugin will compute a feature", "long description": "Even longer description that " "can span multiple lines", "feature name": "circ_per_area", "feature label": "Circularity per Area", "feature shape": (1,), "features required": ["circ", "area_um"], "config required": [], "scalar feature": True, "version": "0.1.0", "plugin path": None, "identifier": "3a3e72c4cb015424ebbe6d4af63f2170", } assert pf.plugin_feature_info == plugin_feature_info def test_pf_attributes(): """Check the plugin feature attributes""" plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) pf1, pf2 = plugin_list plugin_file_info = import_plugin_feature_script(plugin_path) assert pf1.feature_name == pf1.feature_name == \ plugin_file_info["feature names"][0] assert pf2.feature_name == pf2.feature_name == \ plugin_file_info["feature names"][1] assert plugin_path.samefile(pf1.plugin_path) assert plugin_path.samefile(pf1.plugin_feature_info["plugin path"]) assert plugin_path.samefile(pf2.plugin_path) assert plugin_path.samefile(pf2.plugin_feature_info["plugin path"]) assert pf1._original_info == plugin_file_info assert pf2._original_info == plugin_file_info def test_pf_attributes_af_inherited(): """Check the plugin feature attributes inherited from AncillaryFeature""" plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) pf, _ = plugin_list plugin_file_info = import_plugin_feature_script(plugin_path) assert pf.feature_name == plugin_file_info["feature names"][0] assert pf.method == plugin_file_info["method"] assert pf.req_config == plugin_file_info["config required"] assert pf.req_features == plugin_file_info["features required"] assert pf.req_func == plugin_file_info["method check required"] assert pf.priority == 0 def test_pf_bad_plugin_feature_name_list(): """Basic test of a bad feature name for PlugInFeature""" info = example_plugin_info_single_feature() info["feature names"] = "Peter-Pan's Best Friend!" with pytest.raises(ValueError, match="must be a list, got"): PlugInFeature("Peter-Pan's Best Friend!", info) def test_pf_bad_plugin_feature_name(): """Basic test of a bad feature name for PlugInFeature""" info = example_plugin_info_single_feature() info["feature names"] = ["Peter-Pan's Best Friend!"] with pytest.raises(ValueError, match="only contain lower-case characters"): PlugInFeature("Peter-Pan's Best Friend!", info) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_exists_in_hierarchy(): """Test that RTDCHierarchy works with PlugInFeature""" info = example_plugin_info_single_feature() pf = PlugInFeature("circ_per_area", info) h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: assert pf.feature_name in ds assert dclab.dfn.feature_exists(pf.feature_name) child = dclab.new_dataset(ds) assert pf.feature_name in child @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_and_load(): """Check that exported and loaded hdf5 file will keep a plugin feature""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") # initialize PlugInFeature instance info = example_plugin_info_single_feature() pf = PlugInFeature("circ_per_area", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features circ_per_area = ds[pf.feature_name] # export the data to a new file expath = h5path.with_name("exported.rtdc") ds.export.hdf5(expath, features=ds.features_innate + [pf.feature_name]) # make sure that worked with h5py.File(expath, "r") as h5: assert pf.feature_name in h5["events"] assert np.allclose(h5["events"][pf.feature_name], circ_per_area) # now check again with dclab with dclab.new_dataset(expath) as ds2: assert pf in PlugInFeature.features assert pf.feature_name in ds2 assert pf.feature_name in ds2.features_innate assert np.allclose(ds2[pf.feature_name], circ_per_area) # and a control check remove_plugin_feature(pf) assert pf.feature_name not in ds2 @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_non_scalar(): h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip") # initialize PlugInFeature instance info = example_plugin_info_non_scalar_feature() pf = PlugInFeature("image_gauss_filter", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features image_gauss_filter = ds[pf.feature_name] # export the data to a new file expath = h5path.with_name("exported.rtdc") with pytest.warns(UserWarning, match="out on a limb"): ds.export.hdf5(expath, features=[pf.feature_name]) # make sure that worked with h5py.File(expath, "r") as h5: assert pf.feature_name in h5["events"] assert np.allclose(h5["events"][pf.feature_name], image_gauss_filter) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_non_scalar_single_event(): h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip") # initialize PlugInFeature instance info = example_plugin_info_non_scalar_feature() info["feature shapes"] = [(80, 250)] pf = PlugInFeature("image_gauss_filter", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features image_gauss_filter = ds[pf.feature_name] # export the data to a new file expath = h5path.with_name("exported.rtdc") ds.export.hdf5(expath, features=["image", pf.feature_name]) # write another single event with dclab.RTDCWriter(expath) as hw: hw.store_feature(pf.feature_name, ds["image"][0]) hw.store_feature("image", ds["image"][0]) # make sure that worked with h5py.File(expath, "r") as h5: assert pf.feature_name in h5["events"] assert np.allclose(h5["events"][pf.feature_name][:-1], image_gauss_filter) assert np.allclose(h5["events"][pf.feature_name][-1], h5["events/image"][0]) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_non_scalar_no_warning(): h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip") # initialize PlugInFeature instance info = example_plugin_info_non_scalar_feature() info["feature shapes"] = [(80, 250)] pf = PlugInFeature("image_gauss_filter", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features image_gauss_filter = ds[pf.feature_name] # export the data to a new file expath = h5path.with_name("exported.rtdc") ds.export.hdf5(expath, features=[pf.feature_name]) # make sure that worked with h5py.File(expath, "r") as h5: assert pf.feature_name in h5["events"] assert np.allclose(h5["events"][pf.feature_name], image_gauss_filter) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_export_non_scalar_bad_shape(): h5path = retrieve_data("fmt-hdf5_image-bg_2020.zip") # initialize PlugInFeature instance info = example_plugin_info_non_scalar_feature() info["feature shapes"] = [(42, 27)] pf = PlugInFeature("image_gauss_filter", info) with dclab.new_dataset(h5path) as ds: # extract the feature information from the dataset assert pf in PlugInFeature.features # export the data to a new file expath = h5path.with_name("exported.rtdc") with pytest.raises(ValueError, match="Bad shape"): ds.export.hdf5(expath, features=[pf.feature_name]) def test_pf_feature_exists(): """Basic check that the plugin feature name exists in definitions""" plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) assert dclab.dfn.feature_exists(plugin_list[0].feature_name) assert dclab.dfn.feature_exists(plugin_list[1].feature_name) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_filtering_with_plugin_feature(): """Filtering with plugin feature""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() pf = PlugInFeature("circ_per_area", info) ds.config["filtering"][f"{pf.feature_name} min"] = 0.030 ds.config["filtering"][f"{pf.feature_name} max"] = 0.031 ds.apply_filter() assert np.sum(ds.filter.all) == 1 assert ds.filter.all[4] def test_pf_import_plugin_info(): """Check the plugin test example info is a dict""" plugin_path = data_dir / "feat_anc_plugin_creative.py" info = import_plugin_feature_script(plugin_path) assert isinstance(info, dict) def test_pf_import_plugin_info_bad_path(): """Raise error when a bad pathname is given""" bad_plugin_path = "not/a/real/path/plugin.py" with pytest.raises(PluginImportError, match="could be not be found"): import_plugin_feature_script(bad_plugin_path) def test_pf_incorrect_input_info(): """Raise error when info is not a dictionary""" info = ["this", "is", "not", "a", "dict"] with pytest.raises(ValueError, match="must be a dict"): PlugInFeature("feature_1", info) def test_pf_incorrect_input_feature_name(): """Raise error when the feature_name doesn't match info feature name""" info = example_plugin_info_single_feature() # `feature_name` is "circ_per_area" in info with pytest.raises(ValueError, match="is not defined"): PlugInFeature("not_the_correct_name", info) def test_pf_incorrect_input_method(): """Raise error when method is not callable""" info = example_plugin_info_single_feature() # set `info["method"]` to something that isn't callable info["method"] = "this_is_a_string" with pytest.raises(ValueError, match="is not callable"): PlugInFeature("circ_per_area", info) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_initialize_plugin_after_loading(): """plugin feature loads correctly after feature added to hdf5 file""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: circ_per_area = compute_single_plugin_feature(ds) with h5py.File(h5path, "a") as h5: h5["events"]["circ_per_area"] = circ_per_area with dclab.new_dataset(h5path) as ds: assert "circ_per_area" not in ds info = example_plugin_info_single_feature() PlugInFeature("circ_per_area", info) assert "circ_per_area" in ds assert "circ_per_area" in ds.features_innate @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_initialize_plugin_feature_single(): """Check that single plugin feature exists independant of loaded dataset""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) info = example_plugin_info_single_feature() PlugInFeature("circ_per_area", info) assert "circ_per_area" in ds circ_per_area = ds["circ_per_area"] assert np.allclose(circ_per_area, ds["circ"] / ds["area_um"]) # check that PlugInFeature exists independent of loaded ds ds2 = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" in ds2 @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_initialize_plugin_feature_non_scalar(): """Check that the non-scalar plugin feature works""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) info = example_plugin_info_non_scalar_feature() PlugInFeature("image_gauss_filter", info) assert "image_gauss_filter" in ds image_gauss_filter = ds["image_gauss_filter"] assert np.allclose(image_gauss_filter, gaussian_filter(ds["image"], sigma=(0, 1, 1))) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_initialize_plugin_features_multiple(): """Check multiple plugin features exist independant of loaded dataset""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" not in ds.features_innate assert "circ_times_area" not in ds.features_innate info = example_plugin_info_multiple_feature() PlugInFeature("circ_per_area", info) PlugInFeature("circ_times_area", info) assert "circ_per_area" in ds assert "circ_times_area" in ds assert dclab.dfn.feature_exists("circ_per_area") assert dclab.dfn.feature_exists("circ_times_area") circ_per_area = ds["circ_per_area"] circ_times_area = ds["circ_times_area"] assert np.allclose(circ_per_area, ds["circ"] / ds["area_um"]) assert np.allclose(circ_times_area, ds["circ"] * ds["area_um"]) def test_pf_input_no_feature_labels(): """Check that feature labels are populated even if not given""" info = example_plugin_info_single_feature() info.pop("feature labels") feature_name = "circ_per_area" pf = PlugInFeature(feature_name, info) assert dclab.dfn.feature_exists(feature_name) label = dclab.dfn.get_feature_label(feature_name) assert label == "Plugin feature {}".format(feature_name) assert label == pf.plugin_feature_info["feature label"] def test_pf_input_no_scalar_feature(): """Check that scalar feature bools are populated even if not given""" info = example_plugin_info_single_feature() info.pop("scalar feature") pf = PlugInFeature("circ_per_area", info) assert pf.plugin_feature_info["scalar feature"] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_load_plugin(): """Basic check for loading a plugin feature via a script""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" not in ds.features_innate assert "circ_times_area" not in ds.features_innate plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) assert isinstance(plugin_list[0], PlugInFeature) assert isinstance(plugin_list[1], PlugInFeature) assert "circ_per_area" in ds assert "circ_times_area" in ds circ_per_area = ds["circ_per_area"] circ_times_area = ds["circ_times_area"] assert np.allclose(circ_per_area, ds["circ"] / ds["area_um"]) assert np.allclose(circ_times_area, ds["circ"] * ds["area_um"]) def test_pf_minimum_info_input(): """Only method and feature names are required to create PlugInFeature""" info = {"method": compute_single_plugin_feature, "feature names": ["circ_per_area"]} pf = PlugInFeature("circ_per_area", info) # check that all other plugin_feature_info is populated assert "method" in pf.plugin_feature_info assert callable(pf.plugin_feature_info["method"]) assert "description" in pf.plugin_feature_info assert "long description" in pf.plugin_feature_info assert "feature name" in pf.plugin_feature_info assert "feature label" in pf.plugin_feature_info assert "features required" in pf.plugin_feature_info assert "config required" in pf.plugin_feature_info assert "method check required" in pf.plugin_feature_info assert "scalar feature" in pf.plugin_feature_info assert "version" in pf.plugin_feature_info assert "plugin path" in pf.plugin_feature_info @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_remove_all_plugin_features(): """Remove all plugin features at once""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" not in ds.features_innate assert "circ_times_area" not in ds.features_innate plugin_path = data_dir / "feat_anc_plugin_creative.py" dclab.load_plugin_feature(plugin_path) assert "circ_per_area" in ds assert "circ_times_area" in ds assert dclab.dfn.feature_exists("circ_per_area") assert dclab.dfn.feature_exists("circ_times_area") remove_all_plugin_features() assert "circ_per_area" not in ds assert "circ_times_area" not in ds assert not dclab.dfn.feature_exists("circ_per_area") assert not dclab.dfn.feature_exists("circ_times_area") @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_remove_plugin_feature(): """Remove individual plugin features""" ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "circ_per_area" not in ds assert "circ_times_area" not in ds plugin_path = data_dir / "feat_anc_plugin_creative.py" plugin_list = dclab.load_plugin_feature(plugin_path) assert len(plugin_list) == 2 assert "circ_per_area" in ds assert "circ_per_area" not in ds.features_innate assert "circ_times_area" in ds assert "circ_times_area" not in ds.features_innate assert dclab.dfn.feature_exists("circ_per_area") assert dclab.dfn.feature_exists("circ_times_area") remove_plugin_feature(plugin_list[0]) remove_plugin_feature(plugin_list[1]) assert "circ_per_area" not in ds assert "circ_times_area" not in ds assert not dclab.dfn.feature_exists("circ_per_area") assert not dclab.dfn.feature_exists("circ_times_area") with pytest.raises(TypeError, match="hould be an instance of PlugInFeature"): not_a_plugin_instance = [4, 6, 5] remove_plugin_feature(not_a_plugin_instance) def test_pf_try_existing_feature_fails(): """An existing feature name is not allowed""" info = example_plugin_info_single_feature() info["feature names"] = ["deform"] with pytest.raises(ValueError, match="Feature 'deform' already exists"): PlugInFeature("deform", info) def test_pf_with_empty_feature_label_string(): """An empty string is replaced with a real feature label Show that an empty `feature_label` will still give a descriptive feature label. See `dclab.dfn._add_feature_to_definitions` for details. """ info = example_plugin_info_single_feature() info["feature labels"] = [""] feature_name = "circ_per_area" PlugInFeature(feature_name, info) assert dclab.dfn.feature_exists("circ_per_area") label = dclab.dfn.get_feature_label("circ_per_area") assert label != "" assert label == "Plugin feature {}".format(feature_name) def test_pf_with_feature_label(): """Check that a plugin feature label is added to definitions""" info = example_plugin_info_single_feature() info["feature labels"] = ["Circ / Area [1/µm²]"] feature_name = "circ_per_area" PlugInFeature(feature_name, info) assert dclab.dfn.feature_exists("circ_per_area") label = dclab.dfn.get_feature_label("circ_per_area") assert label == "Circ / Area [1/µm²]" def test_pf_with_no_feature_label(): """A feature label of None is replaced with a real feature label Show that `feature_label=None` will still give a descriptive feature label. See `dclab.dfn._add_feature_to_definitions` for details. """ info = example_plugin_info_single_feature() info["feature labels"] = [None] feature_name = "circ_per_area" PlugInFeature(feature_name, info) assert dclab.dfn.feature_exists("circ_per_area") label = dclab.dfn.get_feature_label("circ_per_area") assert label is not None assert label == "Plugin feature {}".format(feature_name) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_with_user_config_section(): """Use a plugin feature with the user defined config section""" info = {"method": compute_with_user_section, "feature names": ["area_of_region"], "config required": [["user", ["n_constrictions"]]]} PlugInFeature("area_of_region", info) ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) assert "area_of_region" not in ds, "not available b/c missing metadata" # add some metadata to the user config section metadata = {"channel": True, "n_constrictions": 3} ds.config["user"].update(metadata) assert ds.config["user"] == metadata assert "area_of_region" in ds, "available b/c metadata is set" area_of_region1 = ds["area_of_region"] area_of_region1_calc = (ds["area_um"] * ds.config["user"]["n_constrictions"]) assert np.allclose(area_of_region1, area_of_region1_calc) @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_with_user_config_section_fails(): """Use a plugin feature with the user defined config section""" info = {"method": compute_with_user_section, "feature names": ["area_of_region"], "config required": [["user", ["n_constrictions"]]]} PlugInFeature("area_of_region", info) ds = dclab.new_dataset(retrieve_data("fmt-hdf5_fl_2018.zip")) # show that the plugin feature is not available before setting the # user metadata ds.config["user"].clear() with pytest.raises(KeyError, match=r"Feature \'area_of_region\' does not exist"): ds["area_of_region"] # show that the plugin fails when the user metadata type is wrong ds.config["user"]["n_constrictions"] = 4.99 with pytest.raises(AssertionError, match="should be an integer value"): ds["area_of_region"] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_wrong_data_shape_1(): h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() info["scalar feature"] = [False] pf = PlugInFeature("circ_per_area", info) with pytest.raises(ValueError, match="is not a scalar feature"): ds[pf.feature_name] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_wrong_data_shape_2(): h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() info["scalar feature"] = [True] info["method"] = lambda x: np.arange(len(ds) * 2).reshape(-1, 2) pf = PlugInFeature("circ_per_area", info) with pytest.raises(ValueError, match="is a scalar feature"): ds[pf.feature_name] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_wrong_length_1(): """plugin feature should have same length""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() info["method"] = lambda x: np.arange(len(ds) // 2) pf = PlugInFeature("circ_per_area", info) with pytest.warns(BadFeatureSizeWarning, match="to match event number"): ds[pf.feature_name] @pytest.mark.filterwarnings( "ignore::dclab.rtdc_dataset.config.WrongConfigurationTypeWarning") def test_pf_wrong_length_2(): """plugin feature should have same length""" h5path = retrieve_data("fmt-hdf5_fl_2018.zip") with dclab.new_dataset(h5path) as ds: info = example_plugin_info_single_feature() info["method"] = lambda x: np.arange(len(ds) * 2) pf = PlugInFeature("circ_per_area", info) with pytest.warns(BadFeatureSizeWarning, match="to match event number"): ds[pf.feature_name] if __name__ == "__main__": # Run all tests loc = locals() for key in list(loc.keys()): if key.startswith("test_") and hasattr(loc[key], "__call__"): loc[key]() remove_all_plugin_features()
ZellMechanik-Dresden/dclab
tests/test_rtdc_feat_anc_plugin.py
Python
gpl-2.0
29,760
package net.idtoki.instelec.controller; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.ResourceBundle; import java.util.logging.Logger; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import org.apache.torque.TorqueException; import org.apache.torque.util.Criteria; import net.idtoki.instelec.manager.TareasManager; import net.idtoki.instelec.group.TareasGroupBean; import net.idtoki.instelec.helper.TareasHelper; import net.idtoki.instelec.model.TareasPeer; import net.idtoki.instelec.model.Tareas; import net.idtoki.instelec.manager.OrdenestrabajoManager; import net.idtoki.instelec.group.OrdenestrabajoGroupBean; import net.idtoki.instelec.model.OrdenestrabajoPeer; import net.idtoki.instelec.helper.OrdenestrabajoHelper; import net.idtoki.instelec.manager.TipotareasManager; import net.idtoki.instelec.group.TipotareasGroupBean; import net.idtoki.instelec.model.TipotareasPeer; import net.idtoki.instelec.helper.TipotareasHelper; import net.idtoki.instelec.manager.CategoriasManager; import net.idtoki.instelec.group.CategoriasGroupBean; import net.idtoki.instelec.model.CategoriasPeer; import net.idtoki.instelec.helper.CategoriasHelper; import net.idtoki.instelec.helper.MaterialesHelper; import net.zylk.tools.ajax.AjaxUtils; import net.zylk.tools.ajax.AjaxUtils.DinamicGridBean; import net.zylk.tools.format.FormatUtils; import net.zylk.tools.pdf.PdfUtils; import net.zylk.tools.xml.XmlUtils; import net.zylk.torque.TorqueUtils; import net.zylk.web.WebUtils; /** * The skeleton for this class was autogenerated by Torque on: * * [Thu Aug 10 13:35:35 CEST 2006] * * You should add additional methods to this class to meet the * application requirements. This class will only be generated as * long as it does not already exist in the output directory. */ public class TareasController extends net.idtoki.instelec.controller.BaseTareasController { private static final Logger logger = Logger.getLogger("net.idtoki.instelec.controller.TareasController"); private TransformerFactory tFactory = TransformerFactory.newInstance(); private Transformer tareas_transformer = null; private Transformer tareass_transformer = null; public void init(ServletConfig config) { super.init(); ResourceBundle resource = ResourceBundle.getBundle("net/idtoki/instelec/app/config/app-config"); File tareas = new File(resource.getString("app.xsl.templates.dir")+"/PdfTareas.xslt"); Source xslSource = new StreamSource(tareas); File tareass = new File(resource.getString("app.xsl.templates.dir")+"/PdfListaTareas.xslt"); Source xslSourceT = new StreamSource(tareass); try{ tareas_transformer = tFactory.newTransformer(xslSource); tareass_transformer = tFactory.newTransformer(xslSourceT); }catch (Exception e){ e.printStackTrace(); } } //Función para la inserción/actualización de registros public void serviceAddTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Con esto se consigue transformar el request a UTF //para temas de acentos y otros caracteres utf8RequestService(request); //recojo los parametros del formulario y doy de alta un nuevo elmento try { Tareas elTareas = TareasHelper.createObj(request); TareasGroupBean gbTareas = new TareasGroupBean(); elTareas.setFechainicio(FormatUtils.ddmmaaaa2aaaammdd(elTareas.getFechainicio(),"-","")); gbTareas.setElemento(elTareas); gbTareas.save(); } catch(TorqueException te) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } //Función para la eliminación de un registro //este método invoca al método public void deleteTareas(int idBorrar) //definido en el TareasManager public void serviceDeleteTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { int idBorrar=-1; idBorrar=WebUtils.getintParam(request, "borrarId"); if (idBorrar!=-1) if (TareasManager.borraTareas(idBorrar)) WebUtils.writeXmlResponse(response,XmlUtils.buildXmlOKResponse("ISO-8859-1")); else WebUtils.writeXmlResponse(response,XmlUtils.buildXmlNotOKResponse("ISO-8859-1")); } // Funciones para las ordenaciones y filtrados de información private Criteria ordenacion(Criteria c,String CampoOrdenacion,String OrdenOrdenacion) { if((OrdenOrdenacion != null )&& (OrdenOrdenacion.compareTo("ASC")==0)) if ((CampoOrdenacion != null)) { c.addAscendingOrderByColumn(CampoOrdenacion.toString()); } if ((OrdenOrdenacion != null) && (OrdenOrdenacion.compareTo("DESC")==0)) if ((CampoOrdenacion != null)) { c.addDescendingOrderByColumn(CampoOrdenacion.toString()); } return c; } private Criteria filtro(Criteria c,int filtro) { String cadena = null; switch (filtro) { case 1: //Caso uno de Filtrado //c.add(Campo,valor); break; case 2: //Caso dos de Filtrado //c.add(Campo,valor); break; default: //caso por defecto break; } return c; } public StringBuffer replaceStringBuffer (StringBuffer strBA, String strOrigen, String strDestino) { return new StringBuffer(strBA.toString().replaceAll(strOrigen,strDestino)); } private Criteria criteriaTareasTableContent(HttpServletRequest request,Criteria c) throws IOException, ServletException { String param = ""; param = WebUtils.getStringParam(request, new OrdenestrabajoHelper().getIdordenName()); if(param != null) TorqueUtils.addEqualCriteria(c,TareasPeer.IDORDEN,param); param = WebUtils.getStringParam(request, new TipotareasHelper().getIdtipotareaName()); if(param != null) TorqueUtils.addEqualCriteria(c,TareasPeer.IDTIPOTAREA,param); param = WebUtils.getStringParam(request, new CategoriasHelper().getIdcategoriaName()); if(param != null) TorqueUtils.addEqualCriteria(c,TareasPeer.IDCATEGORIA,param); String paramSortCol = WebUtils.getStringParam(request, "sort_col"); String paramSortDir = WebUtils.getStringParam(request, "sort_dir"); int paramFiltro = WebUtils.getintParam(request, "filtro"); c = ordenacion(c,paramSortCol,paramSortDir); c = filtro(c,paramFiltro); return c; } public String getPathElementTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException { Criteria c= new Criteria(); String strPath = ""; int claveId=-1; int claveFkId=-1; claveId=WebUtils.getintParam(request, "tareas.IDTAREA"); if (claveId!=-1) { c.add(TareasPeer.IDTAREA, claveId); TareasGroupBean trgb = TareasManager.getTareass(c); strPath = trgb.getTareas(0).getPathTareasParsed(request.getQueryString()); } return "<path>" + strPath + "</path>"; } public String getPathTableContentTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException { Criteria c= new Criteria(); String strPath = ""; int claveId=-1; claveId=WebUtils.getintParam(request, "ordenestrabajo.IDORDEN"); if(claveId != -1){ strPath = OrdenestrabajoManager.getOrdenestrabajo(claveId).getPathOrdenestrabajoParsed(request.getQueryString()); } claveId=WebUtils.getintParam(request, "tipotareas.IDTIPOTAREA"); if(claveId != -1){ strPath = TipotareasManager.getTipotareas(claveId).getPathTipotareasParsed(request.getQueryString()); } claveId=WebUtils.getintParam(request, "categorias.IDCATEGORIA"); if(claveId != -1){ strPath = CategoriasManager.getCategorias(claveId).getPathCategoriasParsed(request.getQueryString()); } return "<path>" + strPath + "</path>"; } public void serviceTareasTableContent(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException { utf8RequestService(request); int numElemPedidosBD = 40; int gap = 0;//gap = viewedRows - numElemVisiblesUltPag DinamicGridBean dgb = WebUtils.getDinamicGridBeanParam(request,numElemPedidosBD,gap); Criteria c =TareasManager.buildSearchCriteria(dgb); c =criteriaTareasTableContent(request,c); TareasGroupBean cgb = TareasManager.getTareass(c); dgb.setTotalSize(cgb.getTotalSize()); String[] methodos= new String[] { TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed" ,"getHijosMaterialesTareas" ,"getEditTareas" ,"getDeleteTareas" }; StringBuffer cadena=null; cadena = AjaxUtils.buildXmlAjaxResponseTableContentFromListObj(cgb.getAlmacen(),methodos,TareasHelper.IDTAREA_GET_METHOD_NAME, dgb,"ISO-8859-1"); cadena.insert(cadena.indexOf("</ajax-response>"),"<response type='object' id='divPath'>" + getPathTableContentTareas(request,response) + "</response>"); xmlResponseService(response,cadena); } public void serviceTareasUlContent(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { utf8RequestService(request); String[] methodos= new String[] { "getULContentTareasParsed" }; String param = WebUtils.getStringParam(request, "value"); if(param==null || param.length() <= 0) param = WebUtils.getStringParam(request, new MaterialesHelper().getIdtareaName()); TareasGroupBean mgb = TareasManager.getTareass(TareasManager.buildSearchCriteria(param)); simpleResponseService(response, AjaxUtils.buildAjaxULContentFromListObj(mgb.getAlmacen(),methodos, TareasHelper.COMPLEX_ID_GET_METHOD,"Tareas")); } public void serviceTareasElement(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, TorqueException { StringBuffer cadena=null; Criteria c= new Criteria(); int claveId=-1; claveId=WebUtils.getintParam(request, "tareas.IDTAREA"); if (claveId!=-1) { c.add(TareasPeer.IDTAREA, claveId); } c.addAscendingOrderByColumn(TareasPeer.IDTAREA); TareasGroupBean trgb = TareasManager.getTareass(c); if (trgb.getTotalSize()!=0) { String [] parametros={ TareasHelper.IDTAREA_GET_METHOD_NAME ,TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed" ,"getImporteCalculadoTareasParsed" ,"getManoObraCalculadoTareasParsed" }; cadena=trgb.buildXml(parametros,null,"ISO-8859-1"); cadena.insert(cadena.indexOf("</result>"),getPathElementTareas(request,response)); } xmlResponseService(response, cadena); } protected StringBuffer updateIdtareaResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdtareaTareasParsed()); } protected StringBuffer updateFechainicioResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getFechainicioTareasParsed()); } protected StringBuffer updateHorasResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getHorasTareasParsed()); } protected StringBuffer updateIdordenResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdordenTareasParsed()); } protected StringBuffer updateIdtipotareaResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdtipotareaTareasParsed()); } protected StringBuffer updateIdcategoriaResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getIdcategoriaTareasParsed()); } protected StringBuffer updateObservacionesResponseCallBack(String s) { ArrayList a = AjaxUtils.splitIdFields(s); return new StringBuffer(TareasManager.getTareas(Integer.parseInt(a.get(0).toString())).getObservacionesTareasParsed()); } public void serviceTareasOrdenestrabajo(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException { String cadena=null; Criteria c= new Criteria(); int claveId=-1; claveId=WebUtils.getintParam(request, "ordenestrabajo.IDORDEN"); if (claveId!=-1) { c.add(OrdenestrabajoPeer.IDORDEN, claveId); } c.addAscendingOrderByColumn(OrdenestrabajoPeer.IDORDEN); OrdenestrabajoGroupBean trgb = OrdenestrabajoManager.getOrdenestrabajos(c); if (trgb.getTotalSize()!=0) { cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>"; cadena = cadena + "<result><tareas.IDORDEN>" + trgb.getOrdenestrabajo(0).getULContentOrdenestrabajoParsed() + "</tareas.IDORDEN></result>"; } xmlResponseService(response, new StringBuffer(cadena)); } public void serviceTareasTipotareas(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException { String cadena=null; Criteria c= new Criteria(); int claveId=-1; claveId=WebUtils.getintParam(request, "tipotareas.IDTIPOTAREA"); if (claveId!=-1) { c.add(TipotareasPeer.IDTIPOTAREA, claveId); } c.addAscendingOrderByColumn(TipotareasPeer.IDTIPOTAREA); TipotareasGroupBean trgb = TipotareasManager.getTipotareass(c); if (trgb.getTotalSize()!=0) { cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>"; cadena = cadena + "<result><tareas.IDTIPOTAREA>" + trgb.getTipotareas(0).getULContentTipotareasParsed() + "</tareas.IDTIPOTAREA></result>"; } xmlResponseService(response, new StringBuffer(cadena)); } public void serviceTareasCategorias(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException { String cadena=null; Criteria c= new Criteria(); int claveId=-1; claveId=WebUtils.getintParam(request, "categorias.IDCATEGORIA"); if (claveId!=-1) { c.add(CategoriasPeer.IDCATEGORIA, claveId); } c.addAscendingOrderByColumn(CategoriasPeer.IDCATEGORIA); CategoriasGroupBean trgb = CategoriasManager.getCategoriass(c); if (trgb.getTotalSize()!=0) { cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>"; cadena = cadena + "<result><tareas.IDCATEGORIA>" + trgb.getCategorias(0).getULContentCategoriasParsed() + "</tareas.IDCATEGORIA></result>"; } xmlResponseService(response, new StringBuffer(cadena)); } public void serviceGetTareasDetallePdf(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { utf8RequestService(request); String[] getMethodos= new String[] { TareasHelper.IDTAREA_GET_METHOD_NAME ,TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed" }; TareasGroupBean tgb = new TareasGroupBean(); try { tgb.setElemento(TareasHelper.getTareas(request)); } catch (TorqueException e) { logger.severe(e.getMessage()); } byte[] content = PdfUtils.getBytes(replaceStringBuffer(tgb.buildXml(getMethodos, null,"ISO-8859-1"),"n/a"," "), tareas_transformer,"ISO-8859-1"); response.addHeader("content-disposition","attachment;filename=Tareas.pdf"); response.setContentType("application/pdf"); response.setHeader("Cache-Control", "");//para que funcione en IE response.setContentLength(content.length); response.getOutputStream().write(content); response.getOutputStream().flush(); response.getOutputStream().close(); } public void serviceTareasTableContentPdf(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { utf8RequestService(request); Criteria c= new Criteria(); String paramQuery = WebUtils.getStringParam(request, "query"); if ((paramQuery != null)&& (paramQuery.compareTo("")!=0) ) c = TareasManager.buildSearchCriteria(paramQuery); c =criteriaTareasTableContent(request,c); TareasGroupBean tgb = TareasManager.getTareass(c); String[] methodos= new String[] { TareasHelper.FECHAINICIO_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.HORAS_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDORDEN_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDTIPOTAREA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.IDCATEGORIA_GET_METHOD_NAME+"TareasParsed" ,TareasHelper.OBSERVACIONES_GET_METHOD_NAME+"TareasParsed" }; byte[] content = PdfUtils.getBytes(replaceStringBuffer(tgb.buildXml(methodos, null,"ISO-8859-1"),"n/a"," "), tareass_transformer,"ISO-8859-1"); response.addHeader("content-disposition","attachment;filename=ListaTareas.pdf"); response.setContentType("application/pdf"); response.setHeader("Cache-Control", "");//para que funcione en IE response.setContentLength(content.length); response.getOutputStream().write(content); response.getOutputStream().flush(); response.getOutputStream().close(); } public void serviceCosteCategoriasTareas(HttpServletRequest request, HttpServletResponse response) throws IOException, TorqueException, ServletException { String cadena=null; Criteria c= new Criteria(); String claveId=""; claveId=WebUtils.getStringParam(request, "tareas.IDCATEGORIA"); if (claveId!="") { int iId = Integer.parseInt(claveId.split("-")[0]); c.add(CategoriasPeer.IDCATEGORIA, iId); } CategoriasGroupBean trgb = CategoriasManager.getCategoriass(c); if (trgb.getTotalSize()!=0) { cadena = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>"; cadena = cadena + "<result><tareas.COSTECATEGORIA>" + trgb.getCategorias(0).getCoste() + "</tareas.COSTECATEGORIA></result>"; } xmlResponseService(response, new StringBuffer(cadena)); } }
Esleelkartea/instelec-app
instelecapp_v1.0.0_src/src/net/idtoki/instelec/controller/TareasController.java
Java
gpl-2.0
18,850
// SPDX-License-Identifier: GPL-2.0 #include <errno.h> #include <QtBluetooth/QBluetoothAddress> #include <QLowEnergyController> #include <QLowEnergyService> #include <QCoreApplication> #include <QElapsedTimer> #include <QEventLoop> #include <QThread> #include <QTimer> #include <QDebug> #include <QLoggingCategory> #include <libdivecomputer/version.h> #include "libdivecomputer.h" #include "core/qt-ble.h" #include "core/btdiscovery.h" #if defined(SSRF_CUSTOM_IO) #include <libdivecomputer/custom_io.h> #define BLE_TIMEOUT 12000 // 12 seconds seems like a very long time to wait #define DEBUG_THRESHOLD 20 static int debugCounter; #define IS_HW(_d) same_string((_d)->vendor, "Heinrichs Weikamp") #define IS_SHEARWATER(_d) same_string((_d)->vendor, "Shearwater") #define MAXIMAL_HW_CREDIT 255 #define MINIMAL_HW_CREDIT 32 extern "C" { void waitFor(int ms) { Q_ASSERT(QCoreApplication::instance()); Q_ASSERT(QThread::currentThread()); QElapsedTimer timer; timer.start(); do { QCoreApplication::processEvents(QEventLoop::AllEvents, ms); QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); QThread::msleep(10); } while (timer.elapsed() < ms); } void BLEObject::serviceStateChanged(QLowEnergyService::ServiceState s) { Q_UNUSED(s) QList<QLowEnergyCharacteristic> list; auto service = qobject_cast<QLowEnergyService*>(sender()); if (service) list = service->characteristics(); Q_FOREACH(QLowEnergyCharacteristic c, list) { qDebug() << " " << c.uuid().toString(); } } void BLEObject::characteristcStateChanged(const QLowEnergyCharacteristic &c, const QByteArray &value) { if (IS_HW(device)) { if (c.uuid() == hwAllCharacteristics[HW_OSTC_BLE_DATA_TX]) { hw_credit--; receivedPackets.append(value); if (hw_credit == MINIMAL_HW_CREDIT) setHwCredit(MAXIMAL_HW_CREDIT - MINIMAL_HW_CREDIT); } else { qDebug() << "ignore packet from" << c.uuid() << value.toHex(); } } else { receivedPackets.append(value); } } void BLEObject::characteristicWritten(const QLowEnergyCharacteristic &c, const QByteArray &value) { if (IS_HW(device)) { if (c.uuid() == hwAllCharacteristics[HW_OSTC_BLE_CREDITS_RX]) { bool ok; hw_credit += value.toHex().toInt(&ok, 16); isCharacteristicWritten = true; } } else { if (debugCounter < DEBUG_THRESHOLD) qDebug() << "BLEObject::characteristicWritten"; } } void BLEObject::writeCompleted(const QLowEnergyDescriptor &d, const QByteArray &value) { Q_UNUSED(value) Q_UNUSED(d) qDebug() << "BLE write completed"; } void BLEObject::addService(const QBluetoothUuid &newService) { qDebug() << "Found service" << newService; bool isStandardUuid = false; newService.toUInt16(&isStandardUuid); if (IS_HW(device)) { /* The HW BT/BLE piece or hardware uses, what we * call here, "a Standard UUID. It is standard because the Telit/Stollmann * manufacturer applied for an own UUID for its product, and this was granted * by the Bluetooth SIG. */ if (newService != QUuid("{0000fefb-0000-1000-8000-00805f9b34fb}")) return; // skip all services except the right one } else if (isStandardUuid) { qDebug () << " .. ignoring standard service"; return; } auto service = controller->createServiceObject(newService, this); qDebug() << " .. created service object" << service; if (service) { services.append(service); connect(service, &QLowEnergyService::stateChanged, this, &BLEObject::serviceStateChanged); connect(service, &QLowEnergyService::characteristicChanged, this, &BLEObject::characteristcStateChanged); connect(service, &QLowEnergyService::characteristicWritten, this, &BLEObject::characteristicWritten); connect(service, &QLowEnergyService::descriptorWritten, this, &BLEObject::writeCompleted); service->discoverDetails(); } } BLEObject::BLEObject(QLowEnergyController *c, dc_user_device_t *d) { controller = c; device = d; debugCounter = 0; } BLEObject::~BLEObject() { qDebug() << "Deleting BLE object"; } dc_status_t BLEObject::write(const void *data, size_t size, size_t *actual) { Q_UNUSED(actual) // that seems like it might cause problems if (!receivedPackets.isEmpty()) { qDebug() << ".. write HIT with still incoming packets in queue"; } QList<QLowEnergyCharacteristic> list = preferredService()->characteristics(); if (list.isEmpty()) return DC_STATUS_IO; QByteArray bytes((const char *)data, (int) size); const QLowEnergyCharacteristic &c = list.constFirst(); QLowEnergyService::WriteMode mode; mode = (c.properties() & QLowEnergyCharacteristic::WriteNoResponse) ? QLowEnergyService::WriteWithoutResponse : QLowEnergyService::WriteWithResponse; if (IS_SHEARWATER(device)) bytes.prepend("\1\0", 2); preferredService()->writeCharacteristic(c, bytes, mode); return DC_STATUS_SUCCESS; } dc_status_t BLEObject::read(void *data, size_t size, size_t *actual) { if (actual) *actual = 0; if (receivedPackets.isEmpty()) { QList<QLowEnergyCharacteristic> list = preferredService()->characteristics(); if (list.isEmpty()) return DC_STATUS_IO; int msec = BLE_TIMEOUT; while (msec > 0 && receivedPackets.isEmpty()) { waitFor(100); msec -= 100; }; } // Still no packet? if (receivedPackets.isEmpty()) return DC_STATUS_IO; QByteArray packet = receivedPackets.takeFirst(); if (IS_SHEARWATER(device)) packet.remove(0,2); if ((size_t)packet.size() > size) return DC_STATUS_NOMEMORY; memcpy((char *)data, packet.data(), packet.size()); if (actual) *actual += packet.size(); return DC_STATUS_SUCCESS; } dc_status_t BLEObject::setHwCredit(unsigned int c) { /* The Terminal I/O client transmits initial UART credits to the server (see 6.5). * * Notice that we have to write to the characteristic here, and not to its * descriptor as for the enabeling of notifications or indications. * * Futher notice that this function has the implicit effect of processing the * event loop (due to waiting for the confirmation of the credit request). * So, as characteristcStateChanged will be triggered, while receiving * data from the OSTC, these are processed too. */ QList<QLowEnergyCharacteristic> list = preferredService()->characteristics(); isCharacteristicWritten = false; preferredService()->writeCharacteristic(list[HW_OSTC_BLE_CREDITS_RX], QByteArray(1, c), QLowEnergyService::WriteWithResponse); /* And wait for the answer*/ int msec = BLE_TIMEOUT; while (msec > 0 && !isCharacteristicWritten) { waitFor(100); msec -= 100; }; if (!isCharacteristicWritten) return DC_STATUS_TIMEOUT; return DC_STATUS_SUCCESS; } dc_status_t BLEObject::setupHwTerminalIo(QList<QLowEnergyCharacteristic> allC) { /* This initalizes the Terminal I/O client as described in * http://www.telit.com/fileadmin/user_upload/products/Downloads/sr-rf/BlueMod/TIO_Implementation_Guide_r04.pdf * Referenced section numbers below are from that document. * * This is for all HW computers, that use referenced BT/BLE hardware module from Telit * (formerly Stollmann). The 16 bit UUID 0xFEFB (or a derived 128 bit UUID starting with * 0x0000FEFB is a clear indication that the OSTC is equipped with this BT/BLE hardware. */ if (allC.length() != 4) { qDebug() << "This should not happen. HW/OSTC BT/BLE device without 4 Characteristics"; return DC_STATUS_IO; } /* The Terminal I/O client subscribes to indications of the UART credits TX * characteristic (see 6.4). * * Notice that indications are subscribed to by writing 0x0200 to its descriptor. This * can be understood by looking for Client Characteristic Configuration, Assigned * Number: 0x2902. Enabling/Disabeling is setting the proper bit, and they * differ for indications and notifications. */ QLowEnergyDescriptor d = allC[HW_OSTC_BLE_CREDITS_TX].descriptors().first(); preferredService()->writeDescriptor(d, QByteArray::fromHex("0200")); /* The Terminal I/O client subscribes to notifications of the UART data TX * characteristic (see 6.2). */ d = allC[HW_OSTC_BLE_DATA_TX].descriptors().first(); preferredService()->writeDescriptor(d, QByteArray::fromHex("0100")); /* The Terminal I/O client transmits initial UART credits to the server (see 6.5). */ return setHwCredit(MAXIMAL_HW_CREDIT); } dc_status_t qt_ble_open(dc_custom_io_t *io, dc_context_t *context, const char *devaddr) { Q_UNUSED(context) debugCounter = 0; QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = true")); /* * LE-only devices get the "LE:" prepended by the scanning * code, so that the rfcomm code can see they only do LE. * * We just skip that prefix (and it doesn't always exist, * since the device may support both legacy BT and LE). */ if (!strncmp(devaddr, "LE:", 3)) devaddr += 3; // HACK ALERT! Qt 5.9 needs this for proper Bluez operation qputenv("QT_DEFAULT_CENTRAL_SERVICES", "1"); #if defined(Q_OS_MACOS) || defined(Q_OS_IOS) QBluetoothDeviceInfo remoteDevice = getBtDeviceInfo(devaddr); QLowEnergyController *controller = QLowEnergyController::createCentral(remoteDevice); #else // this is deprecated but given that we don't use Qt to scan for // devices on Android, we don't have QBluetoothDeviceInfo for the // paired devices and therefore cannot use the newer interfaces // that are preferred starting with Qt 5.7 QBluetoothAddress remoteDeviceAddress(devaddr); QLowEnergyController *controller = new QLowEnergyController(remoteDeviceAddress); #endif qDebug() << "qt_ble_open(" << devaddr << ")"; if (IS_SHEARWATER(io->user_device)) controller->setRemoteAddressType(QLowEnergyController::RandomAddress); // Try to connect to the device controller->connectToDevice(); // Create a timer. If the connection doesn't succeed after five seconds or no error occurs then stop the opening step int msec = BLE_TIMEOUT; while (msec > 0 && controller->state() == QLowEnergyController::ConnectingState) { waitFor(100); msec -= 100; }; switch (controller->state()) { case QLowEnergyController::ConnectedState: qDebug() << "connected to the controller for device" << devaddr; break; default: qDebug() << "failed to connect to the controller " << devaddr << "with error" << controller->errorString(); report_error("Failed to connect to %s: '%s'", devaddr, controller->errorString().toUtf8().data()); controller->disconnectFromDevice(); delete controller; return DC_STATUS_IO; } /* We need to discover services etc here! */ BLEObject *ble = new BLEObject(controller, io->user_device); ble->connect(controller, SIGNAL(serviceDiscovered(QBluetoothUuid)), SLOT(addService(QBluetoothUuid))); qDebug() << " .. discovering services"; controller->discoverServices(); msec = BLE_TIMEOUT; while (msec > 0 && controller->state() == QLowEnergyController::DiscoveringState) { waitFor(100); msec -= 100; }; qDebug() << " .. done discovering services"; if (ble->preferredService() == nullptr) { qDebug() << "failed to find suitable service on" << devaddr; report_error("Failed to find suitable service on '%s'", devaddr); controller->disconnectFromDevice(); delete controller; return DC_STATUS_IO; } qDebug() << " .. discovering details"; msec = BLE_TIMEOUT; while (msec > 0 && ble->preferredService()->state() == QLowEnergyService::DiscoveringServices) { waitFor(100); msec -= 100; }; if (ble->preferredService()->state() != QLowEnergyService::ServiceDiscovered) { qDebug() << "failed to find suitable service on" << devaddr; report_error("Failed to find suitable service on '%s'", devaddr); controller->disconnectFromDevice(); delete controller; return DC_STATUS_IO; } qDebug() << " .. enabling notifications"; /* Enable notifications */ QList<QLowEnergyCharacteristic> list = ble->preferredService()->characteristics(); if (!list.isEmpty()) { const QLowEnergyCharacteristic &c = list.constLast(); if (IS_HW(io->user_device)) { dc_status_t r = ble->setupHwTerminalIo(list); if (r != DC_STATUS_SUCCESS) return r; } else { QList<QLowEnergyDescriptor> l = c.descriptors(); qDebug() << "Descriptor list with" << l.length() << "elements"; QLowEnergyDescriptor d; foreach(d, l) qDebug() << "Descriptor:" << d.name() << "uuid:" << d.uuid().toString(); if (!l.isEmpty()) { bool foundCCC = false; foreach (d, l) { if (d.type() == QBluetoothUuid::ClientCharacteristicConfiguration) { // pick the correct characteristic foundCCC = true; break; } } if (!foundCCC) // if we didn't find a ClientCharacteristicConfiguration, try the first one d = l.first(); qDebug() << "now writing \"0x0100\" to the descriptor" << d.uuid().toString(); ble->preferredService()->writeDescriptor(d, QByteArray::fromHex("0100")); } } } // Fill in info io->userdata = (void *)ble; return DC_STATUS_SUCCESS; } dc_status_t qt_ble_close(dc_custom_io_t *io) { BLEObject *ble = (BLEObject *) io->userdata; io->userdata = NULL; delete ble; return DC_STATUS_SUCCESS; } static void checkThreshold() { if (++debugCounter == DEBUG_THRESHOLD) { QLoggingCategory::setFilterRules(QStringLiteral("qt.bluetooth* = false")); qDebug() << "turning off further BT debug output"; } } dc_status_t qt_ble_read(dc_custom_io_t *io, void* data, size_t size, size_t *actual) { checkThreshold(); BLEObject *ble = (BLEObject *) io->userdata; return ble->read(data, size, actual); } dc_status_t qt_ble_write(dc_custom_io_t *io, const void* data, size_t size, size_t *actual) { checkThreshold(); BLEObject *ble = (BLEObject *) io->userdata; return ble->write(data, size, actual); } } /* extern "C" */ #endif
neolit123/subsurface
core/qt-ble.cpp
C++
gpl-2.0
13,635
/* Generated by Font Squirrel (http://www.fontsquirrel.com) on June 6, 2013 */ @font-face { font-family: 'existencelight'; src: url('existence-light-webfont.eot'); src: url('existence-light-webfont.eot?#iefix') format('embedded-opentype'), url('existence-light-webfont.woff') format('woff'), url('existence-light-webfont.ttf') format('truetype'), url('existence-light-webfont.svg#existencelight') format('svg'); font-weight: normal; font-style: normal; }
joshrcook/erin
wp-content/themes/erin_theme/fonts/existence/existence-font.css
CSS
gpl-2.0
505
package com.uvic.textshare.service.rest; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.io.UnsupportedEncodingException; import java.lang.String; import com.uvic.textshare.service.matching.MatchingFunction; import com.uvic.textshare.service.model.*; import com.google.appengine.api.users.*; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Query.Filter; import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.CompositeFilterOperator; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.gson.Gson; @SuppressWarnings("unused") @Path("/") public class TextbookResource { private static int numberOf_offered_books; private static int numberOf_requested_books; private static int numberOf_matches; MatchingFunction matchingFunction = new MatchingFunction(); String matchDate; /* * * Start of REST Methods * */ @POST @Path("/retrieve") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String getTextbook(String input) { try { //Create a filter for retrieving all the books associated with that user JSONObject obj = new JSONObject(input); String user_id = obj.getString("uid"); Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, user_id); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); if(user == null && !user_id.equals("")) { createUser(obj); return "[]"; } else { Query q2 = new Query("Textbook").setFilter(userFilter); PreparedQuery pd2 = datastore.prepare(q2); List<Entity> textbooks = pd2.asList(FetchOptions.Builder.withDefaults()); String json = new Gson().toJson(textbooks); return json; } } catch(NullPointerException e) { e.printStackTrace(); return "[]"; //something went wrong } } @POST @Path("/add") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String addTextbook(String input) throws ParseException { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); JSONObject text = new JSONObject(input); Date addDate = new Date(); matchDate = "emtpy"; String response = matchingFunction.checkForMatch( text.getString("isbn"), text.getString("uid"), text.getString("type"), text.getString("title"), text.getDouble("condition"), text.getString("edition")); String[] parts = response.split("-"); String matched = parts[0]; if(matched.equals("yes")) { matchDate = parts[1]; numberOf_matches++; } double radius = text.getDouble("radius"); radius = radius / 1000.0; if(radius > 30 || radius < 5) { radius = 15.0; } Entity textbook = new Entity("Textbook"); textbook.setProperty("uid", text.getString("uid")); textbook.setProperty("type", text.getString("type")); textbook.setUnindexedProperty("title", text.getString("title")); textbook.setUnindexedProperty("author", text.getString("author")); textbook.setProperty("isbn", text.getString("isbn")); textbook.setProperty("edition", text.getString("edition")); textbook.setProperty("condition", text.getDouble("condition")); textbook.setProperty("date", addDate); textbook.setProperty("matchDate", matchDate); textbook.setProperty("matched", matched); textbook.setUnindexedProperty("image", text.getString("image")); textbook.setUnindexedProperty("lat", text.getDouble("lat")); textbook.setUnindexedProperty("lon", text.getDouble("lon")); textbook.setUnindexedProperty("radius", radius); datastore.put(textbook); String bookOwner = text.getString("uid"); String typeOfEntry = text.getString("type"); updateUserKarma(bookOwner, typeOfEntry, 5); if(typeOfEntry.equals("offer")) TextbookResource.numberOf_offered_books++; else TextbookResource.numberOf_requested_books++; String json = new Gson().toJson(textbook); return json; } catch(NullPointerException e) { e.printStackTrace(); return "{}"; //something went wrong! } } @POST @Path("/delete") @Consumes(MediaType.APPLICATION_JSON) public void deleteTextbook(String input) throws JSONException { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); JSONObject obj = new JSONObject(input); Long id = (long) obj.getDouble("id"); Key textbookKey = KeyFactory.createKey("Textbook", id); datastore.delete(textbookKey); } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/updateUserRadius") @Consumes(MediaType.APPLICATION_JSON) public void updateUserRadius(String input) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); try { JSONObject obj = new JSONObject(input); String uid = obj.getString("uid"); double radius = obj.getDouble("radius"); radius = radius / 1000.0; if(radius > 30 || radius < 5) { radius = 15.0; } Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); user.setUnindexedProperty("radius", radius); datastore.put(user); q = new Query("Textbook").setFilter(userFilter); List<Entity> textbooks = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); if(!textbooks.isEmpty()) { for(int i = 0; i < textbooks.size(); i++) { Delay.oneSecondDelay(); Entity textbook = textbooks.get(i); textbook.setUnindexedProperty("radius", radius); datastore.put(textbook); } } } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/updateUserLocation") @Consumes(MediaType.APPLICATION_JSON) public void updateUserLocation(String input) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); try { JSONObject obj = new JSONObject(input); String uid = obj.getString("uid"); double lat = obj.getDouble("lat"); double lon = obj.getDouble("lon"); Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); user.setUnindexedProperty("lat", lat); user.setUnindexedProperty("lon", lon); datastore.put(user); q = new Query("Textbook").setFilter(userFilter); List<Entity> textbooks = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults()); if(!textbooks.isEmpty()) { for(int i = 0; i < textbooks.size(); i++) { Delay.oneSecondDelay(); Entity textbook = textbooks.get(i); textbook.setUnindexedProperty("lat", lat); textbook.setUnindexedProperty("lon", lon); datastore.put(textbook); } } } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/unmatchTextbook") @Consumes(MediaType.APPLICATION_JSON) public void unmatchTextbook(String input) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); try { JSONObject obj = new JSONObject(input); Long id = (long) obj.getDouble("id"); String title = obj.getString("title"); String isbn = obj.getString("isbn"); String type = obj.getString("type"); String uid = obj.getString("uid"); String matchDate = obj.getString("matchDate"); double condition = obj.getDouble("condition"); String edition = obj.getString("edition"); String uidTwo; String typeTwo; if(type.equals("offer")) typeTwo = "request"; else typeTwo = "offer"; //Delete the match entry and retrieve other user's UID. Filter matchFilter = new FilterPredicate("matchDate", FilterOperator.EQUAL, matchDate); Query q = new Query("Match").setFilter(matchFilter); Entity match = datastore.prepare(q).asSingleEntity(); if(!uid.equals((String) match.getProperty("userOneId"))) uidTwo = (String) match.getProperty("userOneId"); else uidTwo = (String) match.getProperty("userTwoId"); Key matchKey = match.getKey(); datastore.delete(matchKey); Delay.oneSecondDelay(); //Check for a new match. Omit matching each other again. String matchedOne = matchingFunction.checkForMatch(isbn, uid, type, title, condition, edition); Delay.oneSecondDelay(); String matchedTwo = matchingFunction.checkForMatch(isbn, uidTwo, typeTwo, title, condition, edition); //Update database based on the result of new searches for matches. if(matchedOne.equals("no")) { Key textbookKey = KeyFactory.createKey("Textbook", id); Query q2 = new Query(textbookKey); Entity textbook = datastore.prepare(q2).asSingleEntity(); textbook.setProperty("matched", "no"); textbook.setProperty("matchDate", null); datastore.put(textbook); } else { String[] parts = matchedOne.split("-"); String matchDateOne = parts[1]; Key textbookKey = KeyFactory.createKey("Textbook", id); Query q2 = new Query(textbookKey); Entity textbook = datastore.prepare(q2).asSingleEntity(); textbook.setProperty("matched", "yes"); textbook.setProperty("matchDate", matchDateOne); datastore.put(textbook); } Filter isbnFilter = new FilterPredicate("isbn", FilterOperator.EQUAL,isbn); Filter uidFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uidTwo); Filter searchFilter = CompositeFilterOperator.and(isbnFilter, uidFilter); Delay.oneSecondDelay(); if(matchedTwo.equals("no")) { q = new Query("Textbook").setFilter(searchFilter); Entity textbookTwo = datastore.prepare(q).asSingleEntity(); textbookTwo.setProperty("matched", "no"); textbookTwo.setProperty("matchDate", null); datastore.put(textbookTwo); } else { String[] parts = matchedTwo.split("-"); String matchDateTwo = parts[1]; q = new Query("Textbook").setFilter(searchFilter); Entity textbookTwo = datastore.prepare(q).asSingleEntity(); textbookTwo.setProperty("matched", "yes"); textbookTwo.setProperty("matchDate", matchDateTwo); datastore.put(textbookTwo); } } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/completeMatch") @Consumes(MediaType.APPLICATION_JSON) public void completeMatch(String input) { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); JSONObject obj = new JSONObject(input); Long idOfInitiator = (long) obj.getDouble("id"); String uidOfInitiator = obj.getString("uid"); String matchDate = obj.getString("matchDate"); String type = obj.getString("type"); String uidofMatch; //Delete the match entry Filter matchFilter = new FilterPredicate("matchDate", FilterOperator.EQUAL, matchDate); Query q = new Query("Match").setFilter(matchFilter); Entity match = datastore.prepare(q).asSingleEntity(); if(!uidOfInitiator.equals((String) match.getProperty("userOneId"))) uidofMatch = (String) match.getProperty("userOneId"); else uidofMatch = (String) match.getProperty("userTwoId"); Key matchKey = match.getKey(); datastore.delete(matchKey); //Delete Books Key textbookKey = KeyFactory.createKey("Textbook", idOfInitiator); datastore.delete(textbookKey); Filter uidFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uidofMatch); Filter searchFilter = CompositeFilterOperator.and(uidFilter, matchFilter); q = new Query("Textbook").setFilter(searchFilter); Entity textbook = datastore.prepare(q).asSingleEntity(); matchKey = textbook.getKey(); datastore.delete(matchKey); } catch(NullPointerException e) { e.printStackTrace(); } } @POST @Path("/getUser") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public String getUser(String input) { try { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); JSONObject obj = new JSONObject(input); String uid = obj.getString("uid"); Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); if(user == null) return "{}"; String json = new Gson().toJson(user); return json; } catch(NullPointerException e) { e.printStackTrace(); return "{}"; } } @GET @Path("/getLastFiveBooks") @Produces(MediaType.APPLICATION_JSON) public String getLastFiveBooks() { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query query = new Query("Textbook").addSort("date", Query.SortDirection.DESCENDING); List<Entity> textbooks = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5)); String json = new Gson().toJson(textbooks); return json; } @GET @Path("/getStatistics") @Produces(MediaType.APPLICATION_JSON) public String getStatistics() { Statistics stats = new Statistics(numberOf_offered_books, numberOf_requested_books, numberOf_matches); String json = new Gson().toJson(stats); return json; } /* * * End of REST Methods * */ /* * * Start of Support Methods * */ private void createUser(JSONObject obj) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity user = new Entity("User"); user.setUnindexedProperty("name", obj.getString("name")); user.setProperty("uid", obj.getString("uid")); user.setUnindexedProperty("email", obj.getString("email")); user.setUnindexedProperty("lat", obj.getDouble("lat")); user.setUnindexedProperty("lon", obj.getDouble("lon")); user.setUnindexedProperty("request_karma", 0); user.setUnindexedProperty("offer_karma", 0); user.setUnindexedProperty("radius", 15.0); //default value for radius. datastore.put(user); } private void updateUserKarma(String uid, String type, int points) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Filter userFilter = new FilterPredicate("uid", FilterOperator.EQUAL, uid); Query q = new Query("User").setFilter(userFilter); Entity user = datastore.prepare(q).asSingleEntity(); int updatedKarma; if(type.equals("offer")) { updatedKarma = Integer.parseInt(user.getProperty("offer_karma").toString()); updatedKarma += 5; user.setUnindexedProperty("offer_karma", updatedKarma); } else { updatedKarma = Integer.parseInt(user.getProperty("request_karma").toString()); updatedKarma += 5; user.setUnindexedProperty("request_karma", updatedKarma); } datastore.put(user); } /* * * End of Support Methods * */ }
Brkk/flybrary
src/main/java/com/uvic/textshare/service/rest/TextbookResource.java
Java
gpl-2.0
16,036
/* Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file @brief Implementation of name resolution stage @defgroup Query_Resolver Query Resolver @{ */ #include "sql_select.h" #include "sql_resolver.h" #include "sql_optimizer.h" #include "opt_trace.h" #include "sql_base.h" #include "auth_common.h" #include "opt_explain_format.h" #include "sql_test.h" // print_where #include "aggregate_check.h" static void propagate_nullability(List<TABLE_LIST> *tables, bool nullable); static const Item::enum_walk walk_subquery= Item::enum_walk(Item::WALK_POSTFIX | Item::WALK_SUBQUERY); uint build_bitmap_for_nested_joins(List<TABLE_LIST> *join_list, uint first_unused); /** Prepare query block for optimization. Resolve table and column information. Resolve all expressions (item trees), ie WHERE clause, join conditions, GROUP BY clause, HAVING clause, ORDER BY clause, LIMIT clause. Prepare all subqueries recursively as part of resolving the expressions. Apply permanent transformations to the abstract syntax tree, such as semi-join transformation, derived table transformation, elimination of constant values and redundant clauses (e.g ORDER BY, GROUP BY). @param thd thread handler @returns false if success, true if error @note on privilege checking for SELECT query that possibly contains view or derived table references: - When this function is called, it is assumed that the precheck() function has been called. precheck() ensures that the user has some SELECT privileges to the tables involved in the query. When resolving views it has also been established that the user has some privileges for them. To prepare a view for privilege checking, it is also needed to call check_view_privileges() after views have been merged into the query. This is not necessary for unnamed derived tables since it has already been established that we have SELECT privileges for the underlying tables by the precheck functions. (precheck() checks a query without resolved views, ie. before tables are opened, so underlying tables of views are not yet available). - When a query block is resolved, always ensure that the user has SELECT privileges to the columns referenced in the WHERE clause, the join conditions, the GROUP BY clause, the HAVING clause and the ORDER BY clause. - When resolving the outer-most query block, ensure that the user also has SELECT privileges to the columns in the selected expressions. - When setting up a derived table or view for materialization, ensure that the user has SELECT privileges to the columns in the selected expressions - Column privileges are normally checked by Item_field::fix_fields(). Exceptions are select list of derived tables/views which are checked in TABLE_LIST::setup_materialized_derived(), and natural/using join conditions that are checked in mark_common_columns(). - As far as INSERT, UPDATE and DELETE statements have the same expressions as a SELECT statement, this note applies to those statements as well. */ bool SELECT_LEX::prepare(THD *thd) { DBUG_ENTER("SELECT_LEX::prepare"); // We may do subquery transformation, or Item substitution: Prepare_error_tracker tracker(thd); DBUG_ASSERT(this == thd->lex->current_select()); DBUG_ASSERT(join == NULL); SELECT_LEX_UNIT *const unit= master_unit(); if (top_join_list.elements > 0) propagate_nullability(&top_join_list, false); is_item_list_lookup= true; Opt_trace_context * const trace= &thd->opt_trace; Opt_trace_object trace_wrapper(trace); Opt_trace_object trace_prepare(trace, "join_preparation"); trace_prepare.add_select_number(select_number); Opt_trace_array trace_steps(trace, "steps"); // Initially, "all_fields" is the select list all_fields= fields_list; /* Check that all tables, fields, conds and order are ok */ if (!(active_options() & OPTION_SETUP_TABLES_DONE)) { if (setup_tables(thd, get_table_list(), false)) DBUG_RETURN(true); if (derived_table_count && resolve_derived(thd, true)) DBUG_RETURN(true); // Wait with privilege checking until all derived tables are resolved. if (!thd->derived_tables_processing && check_view_privileges(thd, SELECT_ACL, SELECT_ACL)) DBUG_RETURN(true); } // Precompute and store the row types of NATURAL/USING joins. if (setup_natural_join_row_types(thd, join_list, &context)) DBUG_RETURN(true); Mem_root_array<Item_exists_subselect *, true> sj_candidates_local(thd->mem_root); sj_candidates= &sj_candidates_local; /* Item and Item_field CTORs will both increment some counters in current_select(), based on the current parsing context. We are not parsing anymore: any new Items created now are due to query rewriting, so stop incrementing counters. */ DBUG_ASSERT(parsing_place == CTX_NONE); parsing_place= CTX_NONE; resolve_place= RESOLVE_SELECT_LIST; /* Setup the expressions in the SELECT list. Wait with privilege checking until all derived tables are resolved, except do privilege checking for subqueries inside a derived table. */ const bool check_privs= !thd->derived_tables_processing || master_unit()->item != NULL; thd->mark_used_columns= check_privs ? MARK_COLUMNS_READ : MARK_COLUMNS_NONE; ulonglong want_privilege_saved= thd->want_privilege; thd->want_privilege= check_privs ? SELECT_ACL : 0; if (with_wild && setup_wild(thd)) DBUG_RETURN(true); if (setup_ref_array(thd)) DBUG_RETURN(true); /* purecov: inspected */ if (setup_fields(thd, ref_ptrs, fields_list, thd->want_privilege, &all_fields, true)) DBUG_RETURN(true); resolve_place= RESOLVE_NONE; const nesting_map save_allow_sum_func= thd->lex->allow_sum_func; // Do not allow local set functions for join conditions, WHERE and GROUP BY thd->lex->allow_sum_func&= ~((nesting_map)1 << nest_level); thd->mark_used_columns= MARK_COLUMNS_READ; thd->want_privilege= SELECT_ACL; // Set up join conditions and WHERE clause if (setup_conds(thd)) DBUG_RETURN(true); // Set up the GROUP BY clause int all_fields_count= all_fields.elements; if (group_list.elements && setup_group(thd)) DBUG_RETURN(true); hidden_group_field_count= all_fields.elements - all_fields_count; // Allow local set functions in HAVING and ORDER BY thd->lex->allow_sum_func|= (nesting_map)1 << nest_level; // Setup the HAVING clause if (m_having_cond) { thd->where="having clause"; having_fix_field= true; resolve_place= RESOLVE_HAVING; if (!m_having_cond->fixed && (m_having_cond->fix_fields(thd, &m_having_cond) || m_having_cond->check_cols(1))) DBUG_RETURN(true); having_fix_field= false; resolve_place= RESOLVE_NONE; } // Set up the ORDER BY clause all_fields_count= all_fields.elements; int hidden_order_field_count= 0; if (order_list.elements) { if (setup_order(thd, ref_ptrs, get_table_list(), fields_list, all_fields, order_list.first)) DBUG_RETURN(true); hidden_order_field_count= all_fields.elements - all_fields_count; } // Query block is completely resolved, restore set function allowance thd->lex->allow_sum_func= save_allow_sum_func; thd->want_privilege= want_privilege_saved; /* Permanently remove redundant parts from the query if 1) This is a subquery 2) This is the first time this query is prepared (since the transformation is permanent) 3) Not normalizing a view. Removal should take place when a query involving a view is optimized, not when the view is created */ if (unit->item && // 1) first_execution && // 2) !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) // 3) { remove_redundant_subquery_clauses(thd, hidden_group_field_count, hidden_order_field_count); } if (order_list.elements && setup_order_final(thd, hidden_order_field_count)) DBUG_RETURN(true); /* purecov: inspected */ if (is_distinct() && is_grouped() && hidden_group_field_count == 0 && olap == UNSPECIFIED_OLAP_TYPE) { /* All GROUP expressions are in SELECT list, so resulting rows are distinct. ROLLUP is not specified, so adds no row. So all rows in the result set are distinct, DISTINCT is useless. @todo could remove DISTINCT if ROLLUP were specified and all GROUP expressions were non-nullable, because ROLLUP adds only NULL values. Currently, ROLLUP+DISTINCT is rejected because executor cannot handle it in all cases. */ remove_base_options(SELECT_DISTINCT); } /* Printing the expanded query should happen here and not elsewhere, because when a view is merged (when the view is opened in open_tables()), the parent query's select_lex does not yet contain a correct WHERE clause (it misses the view's merged WHERE clause). This is corrected only just above, in TABLE_LIST::prep_where(), called by setup_without_group()->setup_conds(). We also have to wait for fix_fields() on HAVING, above. At this stage, we also have properly set up Item_ref-s. */ { Opt_trace_object trace_wrapper(trace); opt_trace_print_expanded_query(thd, this, &trace_wrapper); } /* When normalizing a view (like when writing a view's body to the FRM), subquery transformations don't apply (if they did, IN->EXISTS could not be undone in favour of materialization, when optimizing a later statement using the view) */ if (unit->item && // This is a subquery this != unit->fake_select_lex && // A real query block // Not normalizing a view !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) { // Query block represents a subquery within an IN/ANY/ALL/EXISTS predicate if (resolve_subquery(thd)) DBUG_RETURN(true); } if (m_having_cond && m_having_cond->with_sum_func) m_having_cond->split_sum_func2(thd, ref_ptrs, all_fields, &m_having_cond, true); if (inner_sum_func_list) { Item_sum *end=inner_sum_func_list; Item_sum *item_sum= end; do { item_sum= item_sum->next; item_sum->split_sum_func2(thd, ref_ptrs, all_fields, item_sum->ref_by, false); } while (item_sum != end); } if (inner_refs_list.elements && fix_inner_refs(thd)) DBUG_RETURN(true); /* purecov: inspected */ if (group_list.elements) { /* Because HEAP tables can't index BIT fields we need to use an additional hidden field for grouping because later it will be converted to a LONG field. Original field will remain of the BIT type and will be returned to a client. */ for (ORDER *ord= (ORDER *)group_list.first; ord; ord= ord->next) { if ((*ord->item)->type() == Item::FIELD_ITEM && (*ord->item)->field_type() == MYSQL_TYPE_BIT) { Item_field *field= new Item_field(thd, *(Item_field**)ord->item); int el= all_fields.elements; ref_ptrs[el]= field; all_fields.push_front(field); ord->item= &ref_ptrs[el]; } } } if (setup_ftfuncs(this)) /* should be after having->fix_fields */ DBUG_RETURN(true); if (query_result() && query_result()->prepare(fields_list, unit)) DBUG_RETURN(true); if (olap == ROLLUP_TYPE && resolve_rollup(thd)) DBUG_RETURN(true); /* purecov: inspected */ if (flatten_subqueries()) DBUG_RETURN(true); sj_candidates= NULL; if (!outer_select()) { /* This code is invoked in the following cases: - if this is an outer-most query block of a SELECT or multi-table UPDATE/DELETE statement. Notice that for a UNION, this applies to all query blocks. It also applies to a fake_select_lex object. - if this is one of highest-level subqueries, if the statement is something else; like subq-i in: UPDATE t1 SET col1=(subq-1), col2=(subq-2); Local transforms are applied after query block merging. This means that we avoid unnecessary invocations, as local transforms would otherwise have been performed first before query block merging and then another time after query block merging. Thus, apply_local_transforms() may run only after the top query is finished with query block merging. That's why apply_local_transforms() is initiated only by the top query, and then recurses into subqueries. */ if (apply_local_transforms(thd, true)) DBUG_RETURN(true); } DBUG_ASSERT(!thd->is_error()); DBUG_RETURN(false); } /** Apply local transformations, such as query block merging. Also perform partition pruning, which is most effective after transformations have been done. @param thd thread handler @param prune if true, then prune partitions based on const conditions @returns false if success, true if error Since this is called after flattening of query blocks, call this function while traversing the query block hierarchy top-down. */ bool SELECT_LEX::apply_local_transforms(THD *thd, bool prune) { DBUG_ENTER("SELECT_LEX::apply_local_transforms"); /* If query block contains one or more merged derived tables/views, walk through lists of columns in select lists and remove unused columns. */ if (derived_table_count && first_execution && !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) delete_unused_merged_columns(&top_join_list); for (SELECT_LEX_UNIT *unit= first_inner_unit(); unit; unit= unit->next_unit()) { for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select()) { // Prune all subqueries, regardless of passed argument if (sl->apply_local_transforms(thd, true)) DBUG_RETURN(true); } if (unit->fake_select_lex && unit->fake_select_lex->apply_local_transforms(thd, false)) DBUG_RETURN(true); } if (first_execution && !(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) { /* The following code will allocate the new items in a permanent MEMROOT for prepared statements and stored procedures. */ Prepared_stmt_arena_holder ps_arena_holder(thd); // Convert all outer joins to inner joins if possible if (simplify_joins(thd, &top_join_list, true, false, &m_where_cond)) DBUG_RETURN(true); if (record_join_nest_info(&top_join_list)) DBUG_RETURN(true); build_bitmap_for_nested_joins(&top_join_list, 0); /* Here are reasons why we do the following check here (i.e. late). * setup_fields () may have done split_sum_func () on aggregate items of the SELECT list, so for reliable comparison of the ORDER BY list with the SELECT list, we need to wait until split_sum_func() has been done on the ORDER BY list. * we get "most of the time" fixed items, which is always a good thing. Some outer references may not be fixed, though. * we need nested_join::used_tables, and this member is set in simplify_joins() * simplify_joins() does outer-join-to-inner conversion, which increases opportunities for functional dependencies (weak-to-strong, which is unusable, becomes strong-to-strong). * check_only_full_group_by() is dependent on processing done by simplify_joins() (for example it uses the value of SELECT_LEX::outer_join). The drawback is that the checks are after resolve_subquery(), so can meet strange "internally added" items. Note that when we are creating a view, simplify_joins() doesn't run so check_only_full_group_by() cannot run, any error will be raised only when the view is later used (SELECTed...) */ if ((thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY) && (is_distinct() || is_grouped()) && check_only_full_group_by(thd)) DBUG_RETURN(true); } fix_prepare_information(thd); /* Prune partitions for all query blocks after query block merging, if pruning is wanted. */ if (partitioned_table_count && prune) { for (TABLE_LIST *tbl= leaf_tables; tbl; tbl= tbl->next_leaf) { /* This will only prune constant conditions, which will be used for lock pruning. */ if (prune_partitions(thd, tbl->table, tbl->join_cond() ? tbl->join_cond() : m_where_cond)) DBUG_RETURN(true); /* purecov: inspected */ } } DBUG_RETURN(false); } /** Check if the subquery predicate can be executed via materialization. @param predicate IN subquery predicate @param thd THD @param select_lex SELECT_LEX of the subquery @param outer Parent SELECT_LEX (outer to subquery) @return TRUE if subquery allows materialization, FALSE otherwise. */ bool subquery_allows_materialization(Item_in_subselect *predicate, THD *thd, SELECT_LEX *select_lex, const SELECT_LEX *outer) { const uint elements= predicate->unit->first_select()->item_list.elements; DBUG_ENTER("subquery_allows_materialization"); DBUG_ASSERT(elements >= 1); DBUG_ASSERT(predicate->left_expr->cols() == elements); OPT_TRACE_TRANSFORM(&thd->opt_trace, trace_wrapper, trace_mat, select_lex->select_number, "IN (SELECT)", "materialization"); const char *cause= NULL; if (predicate->substype() != Item_subselect::IN_SUBS) { // Subq-mat cannot handle 'outer_expr > {ANY|ALL}(subq)'... cause= "not an IN predicate"; } else if (select_lex->is_part_of_union()) { // Subquery must be a single query specification clause (not a UNION) cause= "in UNION"; } else if (!select_lex->master_unit()->first_select()->leaf_tables) { // Subquery has no tables, hence no point in materializing. cause= "no inner tables"; } else if (!outer->join) { /* Maybe this is a subquery of a single table UPDATE/DELETE (TODO: handle this by switching to multi-table UPDATE/DELETE). */ cause= "parent query has no JOIN"; } else if (!outer->leaf_tables) { // The upper query is SELECT ... FROM DUAL. No gain in materializing. cause= "no tables in outer query"; } else if (predicate->dependent_before_in2exists()) { /* Subquery should not be correlated; the correlation due to predicates injected by IN->EXISTS does not count as we will remove them if we choose materialization. TODO: This is an overly restrictive condition. It can be extended to: (Subquery is non-correlated || Subquery is correlated to any query outer to IN predicate || (Subquery is correlated to the immediate outer query && Subquery !contains {GROUP BY, ORDER BY [LIMIT], aggregate functions}) && subquery predicate is not under "NOT IN")) */ cause= "correlated"; } else { /* Check that involved expression types allow materialization. This is a temporary fix for BUG#36752; see bug report for description of restrictions we need to put on the compared expressions. */ DBUG_ASSERT(predicate->left_expr->fixed); // @see comment in Item_subselect::element_index() bool has_nullables= predicate->left_expr->maybe_null; List_iterator<Item> it(predicate->unit->first_select()->item_list); for (uint i= 0; i < elements; i++) { Item * const inner= it++; Item * const outer= predicate->left_expr->element_index(i); if (!types_allow_materialization(outer, inner)) { cause= "type mismatch"; break; } if (inner->is_blob_field()) // 6 { cause= "inner blob"; break; } has_nullables|= inner->maybe_null; } if (!cause) { trace_mat.add("has_nullable_expressions", has_nullables); /* Subquery materialization cannot handle NULLs partial matching properly, yet. If the outer or inner values are NULL, the subselect_hash_sj_engine may reply FALSE when it should reply UNKNOWN. So, we must limit it to those three cases: - when FALSE and UNKNOWN are equivalent answers. I.e. this is a a top-level predicate (this implies it is not negated). - when outer and inner values cannot be NULL. - when there is a single inner column (because for this we have a limited implementation of NULLs partial matching). */ const bool is_top_level= predicate->is_top_level_item(); trace_mat.add("treat_UNKNOWN_as_FALSE", is_top_level); if (!is_top_level && has_nullables && (elements > 1)) cause= "cannot_handle_partial_matches"; else { trace_mat.add("possible", true); DBUG_RETURN(TRUE); } } } DBUG_ASSERT(cause != NULL); trace_mat.add("possible", false).add_alnum("cause", cause); DBUG_RETURN(false); } /** Make list of leaf tables of join table tree @param list pointer to pointer on list first element @param tables table list @returns pointer on pointer to next_leaf of last element */ static TABLE_LIST **make_leaf_tables(TABLE_LIST **list, TABLE_LIST *tables) { for (TABLE_LIST *table= tables; table; table= table->next_local) { // A mergable view is not allowed to have a table pointer. DBUG_ASSERT(!(table->is_view() && table->is_merged() && table->table)); if (table->merge_underlying_list) { DBUG_ASSERT(table->is_merged()); list= make_leaf_tables(list, table->merge_underlying_list); } else { *list= table; list= &table->next_leaf; } } return list; } /** Check privileges for the view tables merged into a query block. @param thd Thread context. @param want_privilege_first Privileges requested for the first leaf. @param want_privilege_next Privileges requested for the remaining leaves. @note Beware that it can't properly check privileges in cases when table being changed is not the first table in the list of leaf tables (for example, for multi-UPDATE). @note The inner loop is slightly inefficient. A view will have its privileges checked once for every base table that it refers to. @returns false if success, true if error. */ bool st_select_lex::check_view_privileges(THD *thd, ulong want_privilege_first, ulong want_privilege_next) { ulong want_privilege= want_privilege_first; Internal_error_handler_holder<View_error_handler, TABLE_LIST> view_handler(thd, true, leaf_tables); for (TABLE_LIST *tl= leaf_tables; tl; tl= tl->next_leaf) { for (TABLE_LIST *ref= tl; ref->referencing_view; ref= ref->referencing_view) { if (check_single_table_access(thd, want_privilege, ref, false)) return true; } want_privilege= want_privilege_next; } return false; } /** Set up table leaves in the query block based on list of tables. @param thd Thread handler @param tables List of tables to handle @param select_insert It is SELECT ... INSERT command @note Check also that the 'used keys' and 'ignored keys' exists and set up the table structure accordingly. Create a list of leaf tables. This function has to be called for all tables that are used by items, as otherwise table->map is not set and all Item_field will be regarded as const items. @returns False on success, true on error */ bool st_select_lex::setup_tables(THD *thd, TABLE_LIST *tables, bool select_insert) { DBUG_ENTER("st_select_lex::setup_tables"); DBUG_ASSERT ((select_insert && !tables->next_name_resolution_table) || !tables || (context.table_list && context.first_name_resolution_table)); make_leaf_tables(&leaf_tables, tables); TABLE_LIST *first_select_table= NULL; if (select_insert) { // "insert_table" is needed for remap_tables(). thd->lex->insert_table= leaf_tables->top_table(); // Get first table in SELECT part first_select_table= thd->lex->insert_table->next_local; // Then, find the first leaf table if (first_select_table) first_select_table= first_select_table->first_leaf_table(); } uint tableno= 0; leaf_table_count= 0; partitioned_table_count= 0; Opt_hints_qb *qb_hints= context.select_lex->opt_hints_qb; for (TABLE_LIST *tr= leaf_tables; tr; tr= tr->next_leaf, tableno++) { TABLE *const table= tr->table; if (tr == first_select_table) { /* For INSERT ... SELECT command, restart numbering from zero for first leaf table from SELECT part of query. */ first_select_table= 0; tableno= 0; } if (tableno >= MAX_TABLES) { my_error(ER_TOO_MANY_TABLES,MYF(0), static_cast<int>(MAX_TABLES)); DBUG_RETURN(true); } tr->set_tableno(tableno); leaf_table_count++; // Count the input tables of the query if (table == NULL) continue; table->pos_in_table_list= tr; tr->reset(); if (qb_hints && // QB hints initialized !tr->opt_hints_table) // Table hints are not adjusted yet { tr->opt_hints_table= qb_hints->adjust_table_hints(table, tr->alias); } if (tr->process_index_hints(table)) DBUG_RETURN(true); if (table->part_info) // Count number of partitioned tables partitioned_table_count++; } if (qb_hints) qb_hints->check_unresolved(thd); DBUG_RETURN(false); } /** Re-map table numbers for all tables in a query block. @param thd Thread handler @note This function needs to be called after setup_tables() has been called, and after a query block for a subquery has been merged into a parent quary block. */ void st_select_lex::remap_tables(THD *thd) { LEX *const lex= thd->lex; TABLE_LIST *first_select_table= NULL; if (lex->insert_table && lex->insert_table == leaf_tables->top_table()) { /* For INSERT ... SELECT command, restart numbering from zero for first leaf table from SELECT part of query. */ // Get first table in SELECT part first_select_table= lex->insert_table->next_local; // Then, recurse down to get first leaf table if (first_select_table) first_select_table= first_select_table->first_leaf_table(); } uint tableno= 0; for (TABLE_LIST *tl= leaf_tables; tl; tl= tl->next_leaf) { // Reset table number after having reached first table after insert table if (first_select_table == tl) tableno= 0; tl->set_tableno(tableno++); } } /** @brief Resolve derived table and view references in query block @param thd Pointer to THD. @param apply_semijoin if true, apply semi-join transform when possible @return false if success, true if error */ bool st_select_lex::resolve_derived(THD *thd, bool apply_semijoin) { DBUG_ENTER("st_select_lex::resolve_derived"); DBUG_ASSERT(derived_table_count); materialized_derived_table_count= 0; // Prepare derived tables and views that belong to this query block. for (TABLE_LIST *tl= get_table_list(); tl; tl= tl->next_local) { if (!tl->is_view_or_derived() || tl->is_merged()) continue; if (tl->resolve_derived(thd, apply_semijoin)) DBUG_RETURN(true); } /* Merge the derived tables that do not require materialization into the current query block, if possible. Merging is only done once and must not be repeated for prepared execs. */ if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) && first_execution) { for (TABLE_LIST *tl= get_table_list(); tl; tl= tl->next_local) { if (!tl->is_view_or_derived() || tl->is_merged() || !tl->is_mergeable()) continue; if (merge_derived(thd, tl)) DBUG_RETURN(true); /* purecov: inspected */ } } // Prepare remaining derived tables for materialization for (TABLE_LIST *tl= get_table_list(); tl; tl= tl->next_local) { // Ensure that any derived table is merged or materialized after prepare: DBUG_ASSERT(first_execution || !tl->is_view_or_derived() || tl->is_merged() || tl->uses_materialization()); if (!tl->is_view_or_derived() || tl->is_merged()) continue; if (tl->setup_materialized_derived(thd)) DBUG_RETURN(true); materialized_derived_table_count++; } /* The loops above will not reach derived tables that are contained within other derived tables that have been merged into the enclosing query block. To reach them, traverse the list of leaf tables and resolve and setup for materialization those derived tables that have no TABLE object (they have not been set up yet). */ if (!first_execution) { for (TABLE_LIST *tl= leaf_tables; tl; tl= tl->next_leaf) { if (!tl->is_view_or_derived() || tl->table != NULL) continue; DBUG_ASSERT(!tl->is_merged()); if (tl->resolve_derived(thd, apply_semijoin)) DBUG_RETURN(true); /* purecov: inspected */ if (tl->setup_materialized_derived(thd)) DBUG_RETURN(true); /* purecov: inspected */ materialized_derived_table_count++; } } DBUG_RETURN(false); } /** @brief Resolve predicate involving subquery @param thd Pointer to THD. @retval FALSE Success. @retval TRUE Error. @details Perform early unconditional subquery transformations: - Convert subquery predicate into semi-join, or - Mark the subquery for execution using materialization, or - Perform IN->EXISTS transformation, or - Perform more/less ALL/ANY -> MIN/MAX rewrite - Substitute trivial scalar-context subquery with its value @todo for PS, make the whole block execute only on the first execution */ bool SELECT_LEX::resolve_subquery(THD *thd) { DBUG_ENTER("resolve_subquery"); bool chose_semijoin= false; SELECT_LEX *const outer= outer_select(); /* @todo for PS, make the whole block execute only on the first execution. resolve_subquery() is only invoked in the first execution for subqueries that are transformed to semijoin, but for other subqueries, this function is called for every execution. One solution is perhaps to define exec_method in class Item_subselect and exit immediately if unequal to EXEC_UNSPECIFIED. */ Item_subselect *subq_predicate= master_unit()->item; DBUG_ASSERT(subq_predicate); /** @note In this case: IN (SELECT ... UNION SELECT ...), SELECT_LEX::prepare() is called for each of the two UNION members, and in those two calls, subq_predicate is the same, not sure this is desired (double work?). */ Item_in_subselect * const in_predicate= (subq_predicate->substype() == Item_subselect::IN_SUBS) ? static_cast<Item_in_subselect *>(subq_predicate) : NULL; if (in_predicate) { thd->lex->set_current_select(outer); char const *save_where= thd->where; thd->where= "IN/ALL/ANY subquery"; Disable_semijoin_flattening DSF(outer, true); bool result= !in_predicate->left_expr->fixed && in_predicate->left_expr->fix_fields(thd, &in_predicate->left_expr); thd->lex->set_current_select(this); thd->where= save_where; if (result) DBUG_RETURN(true); /* Check if the left and right expressions have the same # of columns, i.e. we don't have a case like (oe1, oe2) IN (SELECT ie1, ie2, ie3 ...) TODO why do we have this duplicated in IN->EXISTS transformers? psergey-todo: fix these: grep for duplicated_subselect_card_check */ if (item_list.elements != in_predicate->left_expr->cols()) { my_error(ER_OPERAND_COLUMNS, MYF(0), in_predicate->left_expr->cols()); DBUG_RETURN(true); } } DBUG_PRINT("info", ("Checking if subq can be converted to semi-join")); /* Check if we're in subquery that is a candidate for flattening into a semi-join (which is done in flatten_subqueries()). The requirements are: 1. Subquery predicate is an IN/=ANY subquery predicate 2. Subquery is a single SELECT (not a UNION) 3. Subquery does not have GROUP BY 4. Subquery does not use aggregate functions or HAVING 5. Subquery predicate is (a) in an ON/WHERE clause, and (b) at the AND-top-level of that clause. 6. Parent query block accepts semijoins (i.e we are not in a subquery of a single table UPDATE/DELETE (TODO: We should handle this at some point by switching to multi-table UPDATE/DELETE) 7. We're not in a confluent table-less subquery, like "SELECT 1". 8. No execution method was already chosen (by a prepared statement) 9. Parent select is not a confluent table-less select 10. Neither parent nor child select have STRAIGHT_JOIN option. */ if (thd->optimizer_switch_flag(OPTIMIZER_SWITCH_SEMIJOIN) && in_predicate && // 1 !is_part_of_union() && // 2 !group_list.elements && // 3 !m_having_cond && !with_sum_func && // 4 (outer->resolve_place == st_select_lex::RESOLVE_CONDITION || // 5a outer->resolve_place == st_select_lex::RESOLVE_JOIN_NEST) && // 5a !outer->semijoin_disallowed && // 5b outer->sj_candidates && // 6 leaf_table_count && // 7 in_predicate->exec_method == Item_exists_subselect::EXEC_UNSPECIFIED && // 8 outer->leaf_table_count && // 9 !((active_options() | outer->active_options()) & SELECT_STRAIGHT_JOIN)) //10 { DBUG_PRINT("info", ("Subquery is semi-join conversion candidate")); /* Notify in the subquery predicate where it belongs in the query graph */ in_predicate->embedding_join_nest= outer->resolve_nest; /* Register the subquery for further processing in flatten_subqueries() */ outer->sj_candidates->push_back(in_predicate); chose_semijoin= true; } if (in_predicate) { Opt_trace_context * const trace= &thd->opt_trace; OPT_TRACE_TRANSFORM(trace, oto0, oto1, select_number, "IN (SELECT)", "semijoin"); oto1.add("chosen", chose_semijoin); } if (!chose_semijoin && subq_predicate->select_transformer(this) == Item_subselect::RES_ERROR) DBUG_RETURN(true); DBUG_RETURN(false); } /** Expand all '*' in list of expressions with the matching column references Function should not be called with no wild cards in select list @param thd thread handler @returns false if OK, true if error */ bool SELECT_LEX::setup_wild(THD *thd) { DBUG_ENTER("SELECT_LEX::setup_wild"); DBUG_ASSERT(with_wild); // PS/SP uses arena so that changes are made permanently. Prepared_stmt_arena_holder ps_arena_holder(thd); Item *item; List_iterator<Item> it(fields_list); while (with_wild && (item= it++)) { Item_field *item_field; if (item->type() == Item::FIELD_ITEM && (item_field= (Item_field *) item) && item_field->field_name && item_field->field_name[0] == '*' && !item_field->field) { const uint elem= fields_list.elements; const bool any_privileges= item_field->any_privileges; Item_subselect *subsel= master_unit()->item; if (subsel && subsel->substype() == Item_subselect::EXISTS_SUBS) { /* It is EXISTS(SELECT * ...) and we can replace * by any constant. Item_int do not need fix_fields() because it is basic constant. */ it.replace(new Item_int(NAME_STRING("Not_used"), (longlong) 1, MY_INT64_NUM_DECIMAL_DIGITS)); } else { if (insert_fields(thd, item_field->context, item_field->db_name, item_field->table_name, &it, any_privileges)) DBUG_RETURN(true); } /* all_fields is a list that has the fields list as a tail. Because of this we have to update the element count also for this list after expanding the '*' entry. */ all_fields.elements+= fields_list.elements - elem; with_wild--; } } DBUG_RETURN(false); } /** Resolve WHERE condition and join conditions @param thd thread handler @returns false if success, true if error */ bool SELECT_LEX::setup_conds(THD *thd) { DBUG_ENTER("SELECT_LEX::setup_conds"); /* it_is_update set to TRUE when tables of primary SELECT_LEX (SELECT_LEX which belong to LEX, i.e. most up SELECT) will be updated by INSERT/UPDATE/LOAD NOTE: using this condition helps to prevent call of prepare_check_option() from subquery of VIEW, because tables of subquery belongs to VIEW (see condition before prepare_check_option() call) */ const bool it_is_update= (this == thd->lex->select_lex) && thd->lex->which_check_option_applicable(); const bool save_is_item_list_lookup= is_item_list_lookup; is_item_list_lookup= false; DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns)); if (m_where_cond) { resolve_place= st_select_lex::RESOLVE_CONDITION; thd->where="where clause"; if ((!m_where_cond->fixed && m_where_cond->fix_fields(thd, &m_where_cond)) || m_where_cond->check_cols(1)) DBUG_RETURN(true); resolve_place= st_select_lex::RESOLVE_NONE; } /* Apply fix_fields() to all ON clauses at all levels of nesting, including the ones inside view definitions. */ for (TABLE_LIST *table= leaf_tables; table; table= table->next_leaf) { TABLE_LIST *embedded; /* The table at the current level of nesting. */ TABLE_LIST *embedding= table; /* The parent nested table reference. */ do { embedded= embedding; if (embedded->join_cond()) { resolve_place= st_select_lex::RESOLVE_JOIN_NEST; resolve_nest= embedded; thd->where="on clause"; if ((!embedded->join_cond()->fixed && embedded->join_cond()->fix_fields(thd, embedded->join_cond_ref())) || embedded->join_cond()->check_cols(1)) DBUG_RETURN(true); cond_count++; resolve_place= st_select_lex::RESOLVE_NONE; resolve_nest= NULL; } embedding= embedded->embedding; } while (embedding && embedding->nested_join->join_list.head() == embedded); /* process CHECK OPTION */ if (it_is_update) { TABLE_LIST *view= table->top_table(); if (view->effective_with_check) { if (view->prepare_check_option(thd)) DBUG_RETURN(true); /* purecov: inspected */ thd->change_item_tree(&table->check_option, view->check_option); } } } is_item_list_lookup= save_is_item_list_lookup; DBUG_ASSERT(thd->lex->current_select() == this); DBUG_ASSERT(!thd->is_error()); DBUG_RETURN(false); } /** Set NESTED_JOIN::counter=0 in all nested joins in passed list. @param join_list Pass NULL. Non-NULL is reserved for recursive inner calls, then it is a list of nested joins to process, and may also contain base tables which will be ignored. */ void SELECT_LEX::reset_nj_counters(List<TABLE_LIST> *join_list) { if (join_list == NULL) join_list= &top_join_list; List_iterator<TABLE_LIST> li(*join_list); TABLE_LIST *table; DBUG_ENTER("reset_nj_counters"); while ((table= li++)) { NESTED_JOIN *nested_join; if ((nested_join= table->nested_join)) { nested_join->nj_counter= 0; reset_nj_counters(&nested_join->join_list); } } DBUG_VOID_RETURN; } /** Simplify joins replacing outer joins by inner joins whenever it's possible. The function, during a retrieval of join_list, eliminates those outer joins that can be converted into inner join, possibly nested. It also moves the join conditions for the converted outer joins and from inner joins to conds. The function also calculates some attributes for nested joins: - used_tables - not_null_tables - dep_tables. - on_expr_dep_tables The first two attributes are used to test whether an outer join can be substituted for an inner join. The third attribute represents the relation 'to be dependent on' for tables. If table t2 is dependent on table t1, then in any evaluated execution plan table access to table t2 must precede access to table t2. This relation is used also to check whether the query contains invalid cross-references. The forth attribute is an auxiliary one and is used to calculate dep_tables. As the attribute dep_tables qualifies possibles orders of tables in the execution plan, the dependencies required by the straight join modifiers are reflected in this attribute as well. The function also removes all braces that can be removed from the join expression without changing its meaning. @note An outer join can be replaced by an inner join if the where condition or the join condition for an embedding nested join contains a conjunctive predicate rejecting null values for some attribute of the inner tables. E.g. in the query: @code SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a WHERE t2.b < 5 @endcode the predicate t2.b < 5 rejects nulls. The query is converted first to: @code SELECT * FROM t1 INNER JOIN t2 ON t2.a=t1.a WHERE t2.b < 5 @endcode then to the equivalent form: @code SELECT * FROM t1, t2 ON t2.a=t1.a WHERE t2.b < 5 AND t2.a=t1.a @endcode Similarly the following query: @code SELECT * from t1 LEFT JOIN (t2, t3) ON t2.a=t1.a t3.b=t1.b WHERE t2.c < 5 @endcode is converted to: @code SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a t3.b=t1.b @endcode One conversion might trigger another: @code SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a LEFT JOIN t3 ON t3.b=t2.b WHERE t3 IS NOT NULL => SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t1.a, t3 WHERE t3 IS NOT NULL AND t3.b=t2.b => SELECT * FROM t1, t2, t3 WHERE t3 IS NOT NULL AND t3.b=t2.b AND t2.a=t1.a @endcode The function removes all unnecessary braces from the expression produced by the conversions. E.g. @code SELECT * FROM t1, (t2, t3) WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b @endcode finally is converted to: @code SELECT * FROM t1, t2, t3 WHERE t2.c < 5 AND t2.a=t1.a AND t3.b=t1.b @endcode It also will remove braces from the following queries: @code SELECT * from (t1 LEFT JOIN t2 ON t2.a=t1.a) LEFT JOIN t3 ON t3.b=t2.b SELECT * from (t1, (t2,t3)) WHERE t1.a=t2.a AND t2.b=t3.b. @endcode The benefit of this simplification procedure is that it might return a query for which the optimizer can evaluate execution plan with more join orders. With a left join operation the optimizer does not consider any plan where one of the inner tables is before some of outer tables. IMPLEMENTATION The function is implemented by a recursive procedure. On the recursive ascent all attributes are calculated, all outer joins that can be converted are replaced and then all unnecessary braces are removed. As join list contains join tables in the reverse order sequential elimination of outer joins does not require extra recursive calls. SEMI-JOIN NOTES Remove all semi-joins that have are within another semi-join (i.e. have an "ancestor" semi-join nest) EXAMPLES Here is an example of a join query with invalid cross references: @code SELECT * FROM t1 LEFT JOIN t2 ON t2.a=t3.a LEFT JOIN t3 ON t3.b=t1.b @endcode @param thd thread handler @param join_list list representation of the join to be converted @param top true <=> cond is the where condition @param in_sj TRUE <=> processing semi-join nest's children @param[in,out] cond In: condition to which the join condition for converted outer joins is to be added; Out: new condition @param changelog Don't specify this parameter, it is reserved for recursive calls inside this function @returns true for error, false for success */ bool SELECT_LEX::simplify_joins(THD *thd, List<TABLE_LIST> *join_list, bool top, bool in_sj, Item **cond, uint *changelog) { /* Each type of change done by this function, or its recursive calls, is tracked in a bitmap: */ enum change { NONE= 0, OUTER_JOIN_TO_INNER= 1 << 0, JOIN_COND_TO_WHERE= 1 << 1, PAREN_REMOVAL= 1 << 2, SEMIJOIN= 1 << 3 }; uint changes= 0; // To keep track of changes. if (changelog == NULL) // This is the top call. changelog= &changes; TABLE_LIST *table; NESTED_JOIN *nested_join; TABLE_LIST *prev_table= 0; List_iterator<TABLE_LIST> li(*join_list); const bool straight_join= active_options() & SELECT_STRAIGHT_JOIN; DBUG_ENTER("simplify_joins"); /* Try to simplify join operations from join_list. The most outer join operation is checked for conversion first. */ while ((table= li++)) { table_map used_tables; table_map not_null_tables= (table_map) 0; if ((nested_join= table->nested_join)) { /* If the element of join_list is a nested join apply the procedure to its nested join list first. */ if (table->join_cond()) { Item *join_cond= table->join_cond(); /* If a join condition JC is attached to the table, check all null rejected predicates in this condition. If such a predicate over an attribute belonging to an inner table of an embedded outer join is found, the outer join is converted to an inner join and the corresponding join condition is added to JC. */ if (simplify_joins(thd, &nested_join->join_list, false, in_sj || table->sj_cond(), &join_cond, changelog)) DBUG_RETURN(true); if (join_cond != table->join_cond()) { DBUG_ASSERT(join_cond); table->set_join_cond(join_cond); } } nested_join->used_tables= (table_map) 0; nested_join->not_null_tables=(table_map) 0; if (simplify_joins(thd, &nested_join->join_list, top, in_sj || table->sj_cond(), cond, changelog)) DBUG_RETURN(true); used_tables= nested_join->used_tables; not_null_tables= nested_join->not_null_tables; } else { used_tables= table->map(); if (*cond) not_null_tables= (*cond)->not_null_tables(); } if (table->embedding) { table->embedding->nested_join->used_tables|= used_tables; table->embedding->nested_join->not_null_tables|= not_null_tables; } if (!table->outer_join || (used_tables & not_null_tables)) { /* For some of the inner tables there are conjunctive predicates that reject nulls => the outer join can be replaced by an inner join. */ if (table->outer_join) { *changelog|= OUTER_JOIN_TO_INNER; table->outer_join= 0; } if (table->join_cond()) { *changelog|= JOIN_COND_TO_WHERE; /* Add join condition to the WHERE or upper-level join condition. */ if (*cond) { Item_cond_and *new_cond= static_cast<Item_cond_and*>(and_conds(*cond, table->join_cond())); if (!new_cond) DBUG_RETURN(true); new_cond->top_level_item(); /* It is always a new item as both the upper-level condition and a join condition existed */ DBUG_ASSERT(!new_cond->fixed); if (new_cond->fix_fields(thd, NULL)) DBUG_RETURN(true); /* If join condition has a pending rollback in THD::change_list */ List_iterator<Item> lit(*new_cond->argument_list()); Item *arg; while ((arg= lit++)) { /* The join condition isn't necessarily the second argument anymore, since fix_fields may have merged it into an existing AND expr. */ if (arg == table->join_cond()) thd->change_item_tree_place(table->join_cond_ref(), lit.ref()); else if (arg == *cond) thd->change_item_tree_place(cond, lit.ref()); } *cond= new_cond; } else { *cond= table->join_cond(); /* If join condition has a pending rollback in THD::change_list */ thd->change_item_tree_place(table->join_cond_ref(), cond); } table->set_join_cond(NULL); } } if (!top) continue; /* Only inner tables of non-convertible outer joins remain with the join condition. */ if (table->join_cond()) { table->dep_tables|= table->join_cond()->used_tables(); // At this point the joined tables always have an embedding join nest: DBUG_ASSERT(table->embedding); table->dep_tables&= ~table->embedding->nested_join->used_tables; // Embedding table depends on tables used in embedded join conditions. table->embedding->on_expr_dep_tables|= table->join_cond()->used_tables(); } if (prev_table) { /* The order of tables is reverse: prev_table follows table */ if (prev_table->straight || straight_join) prev_table->dep_tables|= used_tables; if (prev_table->join_cond()) { prev_table->dep_tables|= table->on_expr_dep_tables; table_map prev_used_tables= prev_table->nested_join ? prev_table->nested_join->used_tables : prev_table->map(); /* If join condition contains only references to inner tables we still make the inner tables dependent on the outer tables. It would be enough to set dependency only on one outer table for them. Yet this is really a rare case. Note: PSEUDO_TABLE_BITS mask should not be counted as it prevents update of inner table dependencies. For example it might happen if RAND()/COUNT(*) function is used in JOIN ON clause. */ if (!((prev_table->join_cond()->used_tables() & ~PSEUDO_TABLE_BITS) & ~prev_used_tables)) prev_table->dep_tables|= used_tables; } } prev_table= table; } /* Flatten nested joins that can be flattened. no join condition and not a semi-join => can be flattened. */ li.rewind(); while ((table= li++)) { nested_join= table->nested_join; if (table->sj_cond() && !in_sj) { /* If this is a semi-join that is not contained within another semi-join, leave it intact (otherwise it is flattened) */ *changelog|= SEMIJOIN; } else if (nested_join && !table->join_cond()) { *changelog|= PAREN_REMOVAL; TABLE_LIST *tbl; List_iterator<TABLE_LIST> it(nested_join->join_list); while ((tbl= it++)) { tbl->embedding= table->embedding; tbl->join_list= table->join_list; tbl->dep_tables|= table->dep_tables; } li.replace(nested_join->join_list); } } if (changes) { Opt_trace_context * trace= &thd->opt_trace; if (unlikely(trace->is_started())) { Opt_trace_object trace_wrapper(trace); Opt_trace_object trace_object(trace, "transformations_to_nested_joins"); { Opt_trace_array trace_changes(trace, "transformations"); if (changes & SEMIJOIN) trace_changes.add_alnum("semijoin"); if (changes & OUTER_JOIN_TO_INNER) trace_changes.add_alnum("outer_join_to_inner_join"); if (changes & JOIN_COND_TO_WHERE) trace_changes.add_alnum("JOIN_condition_to_WHERE"); if (changes & PAREN_REMOVAL) trace_changes.add_alnum("parenthesis_removal"); } // the newly transformed query is worth printing opt_trace_print_expanded_query(thd, this, &trace_object); } } DBUG_RETURN(false); } /** Record join nest info in the select block. After simplification of inner join, outer join and semi-join structures: - record the remaining semi-join structures in the enclosing query block. - record transformed join conditions in TABLE_LIST objects. This function is called recursively for each join nest and/or table in the query block. @param select The query block @param tables List of tables and join nests @return False if successful, True if failure */ bool SELECT_LEX::record_join_nest_info(List<TABLE_LIST> *tables) { TABLE_LIST *table; List_iterator<TABLE_LIST> li(*tables); DBUG_ENTER("record_join_nest_info"); while ((table= li++)) { if (table->nested_join == NULL) { if (table->join_cond()) outer_join|= table->map(); continue; } if (record_join_nest_info(&table->nested_join->join_list)) DBUG_RETURN(true); /* sj_inner_tables is set properly later in pull_out_semijoin_tables(). This assignment is required in case pull_out_semijoin_tables() is not called. */ if (table->sj_cond()) table->sj_inner_tables= table->nested_join->used_tables; if (table->sj_cond() && sj_nests.push_back(table)) DBUG_RETURN(true); if (table->join_cond()) outer_join|= table->nested_join->used_tables; } DBUG_RETURN(false); } static int subq_sj_candidate_cmp(Item_exists_subselect* const *el1, Item_exists_subselect* const *el2) { /* Remove this assert when we support semijoin on non-IN subqueries. */ DBUG_ASSERT((*el1)->substype() == Item_subselect::IN_SUBS && (*el2)->substype() == Item_subselect::IN_SUBS); return ((*el1)->sj_convert_priority < (*el2)->sj_convert_priority) ? 1 : ( ((*el1)->sj_convert_priority == (*el2)->sj_convert_priority)? 0 : -1); } /** Update table reference information for conditions and expressions due to query blocks having been merged in from derived tables/views and due to semi-join transformation. This is needed for two reasons: 1. Since table numbers are changed, we need to update used_tables information for all conditions and expressions that are possibly touched. 2. For semi-join, some column references are changed from outer references to local references. The function needs to recursively walk down into join nests, in order to cover all conditions and expressions. For a semi-join, tables from the subquery are added last in the query block. This means that conditions and expressions from the outer query block are unaffected. But all conditions inside the semi-join nest, including join conditions, must have their table numbers changed. For a derived table/view, tables from the subquery are merged into the outer query, and this function is called for every derived table that is merged in. This algorithm only works when derived tables are merged in the order of their original table numbers. A hypothetical example with a triple self-join over a mergeable view: CREATE VIEW v AS SELECT t1.a, t2.b FROM t1 JOIN t2 USING (a); SELECT v1.a, v1.b, v2.b, v3.b FROM v AS v1 JOIN v AS v2 ON ... JOIN v AS v3 ON ...; The analysis starts with three tables v1, v2 and v3 having numbers 0, 1, 2. First we merge in v1, so we get (t1, t2, v2, v3). v2 and v3 are shifted up. Tables from v1 need to have their table numbers altered (actually they do not since both old and new numbers are 0 and 1, but this is a special case). v2 and v3 are not merged in yet, so we delay pullout on them until they are merged. Conditions and expressions from the outer query are not resolved yet, so regular resolving will take of them later. Then we merge in v2, so we get (t1, t2, t1, t2, v3). The tables from this view gets numbers 2 and 3, and v3 gets number 4. Because v2 had a higher number than the tables from v1, the join nest representing v1 is unaffected. And v3 is still not merged, so the only join nest we need to consider is v2. Finally we merge in v3, and then we have tables (t1, t2, t1, t2, t1, t2), with numbers 0 through 5. Again, since v3 has higher number than any of the already merged in views, only this join nest needs the pullout. @param parent_select Query block being merged into @param removed_select Query block that is removed (subquery) @param tr Table object this pullout is applied to @param table_adjust Number of positions that a derived table nest is adjusted, used to fix up semi-join related fields. Tables are adjusted from position N to N+table_adjust */ static void fix_tables_after_pullout(st_select_lex *parent_select, st_select_lex *removed_select, TABLE_LIST *tr, uint table_adjust) { if (tr->is_merged()) { // Update select list of merged derived tables: for (Field_translator *transl= tr->field_translation; transl < tr->field_translation_end; transl++) { DBUG_ASSERT(transl->item->fixed); transl->item->fix_after_pullout(parent_select, removed_select); } // Update used table info for the WHERE clause of the derived table DBUG_ASSERT(!tr->derived_where_cond || tr->derived_where_cond->fixed); if (tr->derived_where_cond) tr->derived_where_cond->fix_after_pullout(parent_select, removed_select); } /* If join_cond() is fixed, it contains a join condition from a subquery that has already been resolved. Call fix_after_pullout() to update used table information since table numbers may have changed. If join_cond() is not fixed, it contains a condition that was generated in the derived table merge operation, which will be fixed later. This condition may also contain a fixed part, but this is saved as derived_where_cond and is pulled out explicitly. */ if (tr->join_cond() && tr->join_cond()->fixed) tr->join_cond()->fix_after_pullout(parent_select, removed_select); if (tr->nested_join) { // In case a derived table is merged-in, these fields need adjustment: tr->nested_join->sj_corr_tables<<= table_adjust; tr->nested_join->sj_depends_on<<= table_adjust; List_iterator<TABLE_LIST> it(tr->nested_join->join_list); TABLE_LIST *child; while ((child= it++)) fix_tables_after_pullout(parent_select, removed_select, child, table_adjust); } } /** Convert a subquery predicate of this query block into a TABLE_LIST semi-join nest. @param subq_pred Subquery predicate to be converted. This is either an IN, =ANY or EXISTS predicate. @retval FALSE OK @retval TRUE Error @details The following transformations are performed: 1. IN/=ANY predicates on the form: SELECT ... FROM ot1 ... otN WHERE (oe1, ... oeM) IN (SELECT ie1, ..., ieM) FROM it1 ... itK [WHERE inner-cond]) [AND outer-cond] [GROUP BY ...] [HAVING ...] [ORDER BY ...] are transformed into: SELECT ... FROM (ot1 ... otN) SJ (it1 ... itK) ON (oe1, ... oeM) = (ie1, ..., ieM) [AND inner-cond] [WHERE outer-cond] [GROUP BY ...] [HAVING ...] [ORDER BY ...] Notice that the inner-cond may contain correlated and non-correlated expressions. Further transformations will analyze and break up such expressions. Prepared Statements: the transformation is permanent: - Changes in TABLE_LIST structures are naturally permanent - Item tree changes are performed on statement MEM_ROOT: = we activate statement MEM_ROOT = this function is called before the first fix_prepare_information call. This is intended because the criteria for subquery-to-sj conversion remain constant for the lifetime of the Prepared Statement. */ bool SELECT_LEX::convert_subquery_to_semijoin(Item_exists_subselect *subq_pred) { TABLE_LIST *emb_tbl_nest= NULL; List<TABLE_LIST> *emb_join_list= &top_join_list; THD *const thd= subq_pred->unit->thd; DBUG_ENTER("convert_subquery_to_semijoin"); DBUG_ASSERT(subq_pred->substype() == Item_subselect::IN_SUBS); bool outer_join= false; // True if predicate is inner to an outer join /* Find out where to insert the semi-join nest and the generated condition. For t1 LEFT JOIN t2, embedding_join_nest will be t2. Note that t2 may be a simple table or may itself be a join nest (e.g. in the case t1 LEFT JOIN (t2 JOIN t3)) */ if (subq_pred->embedding_join_nest != NULL) { // Is this on inner side of an outer join? outer_join= subq_pred->embedding_join_nest->is_inner_table_of_outer_join(); if (subq_pred->embedding_join_nest->nested_join) { /* We're dealing with ... [LEFT] JOIN ( ... ) ON (subquery AND condition) ... The sj-nest will be inserted into the brackets nest. */ emb_tbl_nest= subq_pred->embedding_join_nest; emb_join_list= &emb_tbl_nest->nested_join->join_list; } else if (!subq_pred->embedding_join_nest->outer_join) { /* We're dealing with ... INNER JOIN tblX ON (subquery AND condition) ... The sj-nest will be tblX's "sibling", i.e. another child of its parent. This is ok because tblX is joined as an inner join. */ emb_tbl_nest= subq_pred->embedding_join_nest->embedding; if (emb_tbl_nest) emb_join_list= &emb_tbl_nest->nested_join->join_list; } else if (!subq_pred->embedding_join_nest->nested_join) { TABLE_LIST *outer_tbl= subq_pred->embedding_join_nest; /* We're dealing with ... LEFT JOIN tbl ON (on_expr AND subq_pred) ... we'll need to convert it into: ... LEFT JOIN ( tbl SJ (subq_tables) ) ON (on_expr AND subq_pred) ... | | |<----- wrap_nest ---->| Q: other subqueries may be pointing to this element. What to do? A1: simple solution: copy *subq_pred->embedding_join_nest= *parent_nest. But we'll need to fix other pointers. A2: Another way: have TABLE_LIST::next_ptr so the following subqueries know the table has been nested. A3: changes in the TABLE_LIST::outer_join will make everything work automatically. */ TABLE_LIST *const wrap_nest= TABLE_LIST::new_nested_join(thd->mem_root, "(sj-wrap)", outer_tbl->embedding, outer_tbl->join_list, this); if (wrap_nest == NULL) DBUG_RETURN(true); wrap_nest->nested_join->join_list.push_back(outer_tbl); outer_tbl->embedding= wrap_nest; outer_tbl->join_list= &wrap_nest->nested_join->join_list; /* An important note, if this 'PREPARE stmt'. The FROM clause of the outer query now looks like CONCAT(original FROM clause of outer query, sj-nest). Given that the original FROM clause is reversed, this list is interpreted as "sj-nest is first". Thus, at a next execution, setup_natural_join_types() will decide that the name resolution context of the FROM clause should start at the first inner table in sj-nest. However, note that in the present function we do not change first_name_resolution_table (and friends) of sj-inner tables. So, at the next execution, name resolution for columns of outer-table columns is bound to fail (the first inner table does not have outer tables in its chain of resolution). Fortunately, Item_field::cached_table, which is set during resolution of 'PREPARE stmt', gives us the answer and avoids a failing search. */ /* wrap_nest will take place of outer_tbl, so move the outer join flag and join condition. */ wrap_nest->outer_join= outer_tbl->outer_join; outer_tbl->outer_join= 0; // There are item-rollback problems in this function: see bug#16926177 wrap_nest->set_join_cond(outer_tbl->join_cond()->real_item()); outer_tbl->set_join_cond(NULL); List_iterator<TABLE_LIST> li(*wrap_nest->join_list); TABLE_LIST *tbl; while ((tbl= li++)) { if (tbl == outer_tbl) { li.replace(wrap_nest); break; } } /* Ok now wrap_nest 'contains' outer_tbl and we're ready to add the semi-join nest into it */ emb_join_list= &wrap_nest->nested_join->join_list; emb_tbl_nest= wrap_nest; } } TABLE_LIST *const sj_nest= TABLE_LIST::new_nested_join(thd->mem_root, "(sj-nest)", emb_tbl_nest, emb_join_list, this); if (sj_nest == NULL) DBUG_RETURN(true); /* purecov: inspected */ NESTED_JOIN *const nested_join= sj_nest->nested_join; /* Nests do not participate in those 'chains', so: */ /* sj_nest->next_leaf= sj_nest->next_local= sj_nest->next_global == NULL*/ emb_join_list->push_back(sj_nest); /* Natural joins inside a semi-join nest were already processed when the subquery went through initial preparation. */ sj_nest->nested_join->natural_join_processed= true; /* nested_join->used_tables and nested_join->not_null_tables are initialized in simplify_joins(). */ st_select_lex *const subq_select= subq_pred->unit->first_select(); nested_join->query_block_id= subq_select->select_number; // Merge tables from underlying query block into this join nest if (sj_nest->merge_underlying_tables(subq_select)) DBUG_RETURN(true); /* purecov: inspected */ /* Add tables from subquery at end of leaf table chain. (This also means that table map for parent query block tables are unchanged) */ TABLE_LIST *tl; for (tl= leaf_tables; tl->next_leaf; tl= tl->next_leaf) {} tl->next_leaf= subq_select->leaf_tables; // Add tables from subquery at end of next_local chain. for (tl= get_table_list(); tl->next_local; tl= tl->next_local) {} tl->next_local= subq_select->get_table_list(); // Note that subquery's tables are already in the next_global chain // Remove the original subquery predicate from the WHERE/ON // The subqueries were replaced for Item_int(1) earlier // @todo also reset the 'with_subselect' there. // Walk through child's tables and adjust table map uint table_no= leaf_table_count; for (tl= subq_select->leaf_tables; tl; tl= tl->next_leaf, table_no++) tl->set_tableno(table_no); // Adjust table and expression counts in parent query block: derived_table_count+= subq_select->derived_table_count; materialized_derived_table_count+= subq_select->materialized_derived_table_count; has_sj_nests|= subq_select->has_sj_nests; partitioned_table_count+= subq_select->partitioned_table_count; leaf_table_count+= subq_select->leaf_table_count; cond_count+= subq_select->cond_count; between_count+= subq_select->between_count; if (outer_join) propagate_nullability(&sj_nest->nested_join->join_list, true); nested_join->sj_outer_exprs.empty(); nested_join->sj_inner_exprs.empty(); /* @todo: Add similar conversion for subqueries other than IN. */ if (subq_pred->substype() == Item_subselect::IN_SUBS) { Item_in_subselect *in_subq_pred= (Item_in_subselect *)subq_pred; DBUG_ASSERT(is_fixed_or_outer_ref(in_subq_pred->left_expr)); in_subq_pred->exec_method= Item_exists_subselect::EXEC_SEMI_JOIN; /* sj_corr_tables is supposed to contain non-trivially correlated tables, but here it is set to contain all correlated tables. @todo: Add analysis step that assigns only the set of non-trivially correlated tables to sj_corr_tables. */ nested_join->sj_corr_tables= subq_pred->used_tables(); /* sj_depends_on contains the set of outer tables referred in the subquery's WHERE clause as well as tables referred in the IN predicate's left-hand side. */ nested_join->sj_depends_on= subq_pred->used_tables() | in_subq_pred->left_expr->used_tables(); // Put the subquery's WHERE into semi-join's condition. Item *sj_cond= subq_select->where_cond(); /* Create the IN-equalities and inject them into semi-join's ON condition. Additionally, for LooseScan strategy - Record the number of IN-equalities. - Create list of pointers to (oe1, ..., ieN). We'll need the list to see which of the expressions are bound and which are not (for those we'll produce a distinct stream of (ie_i1,...ie_ik). (TODO: can we just create a list of pointers and hope the expressions will not substitute themselves on fix_fields()? or we need to wrap them into Item_direct_view_refs and store pointers to those. The pointers to Item_direct_view_refs are guaranteed to be stable as Item_direct_view_refs doesn't substitute itself with anything in Item_direct_view_ref::fix_fields. We have a special case for IN predicates with a scalar subquery or a row subquery in the predicand (left operand), such as this: (SELECT 1,2 FROM t1) IN (SELECT x,y FROM t2) We cannot make the join condition 1=x AND 2=y, since that might evaluate to TRUE even if t1 is empty. Instead make the join condition (SELECT 1,2 FROM t1) = (x,y) in this case. */ Item_subselect *left_subquery= (in_subq_pred->left_expr->type() == Item::SUBSELECT_ITEM) ? static_cast<Item_subselect *>(in_subq_pred->left_expr) : NULL; if (left_subquery && (left_subquery->substype() == Item_subselect::SINGLEROW_SUBS)) { List<Item> ref_list; Item *header= subq_select->ref_pointer_array[0]; for (uint i= 1; i < in_subq_pred->left_expr->cols(); i++) { ref_list.push_back(subq_select->ref_pointer_array[i]); } Item_row *right_expr= new Item_row(header, ref_list); if (!right_expr) DBUG_RETURN(true); /* purecov: inspected */ nested_join->sj_outer_exprs.push_back(in_subq_pred->left_expr); nested_join->sj_inner_exprs.push_back(right_expr); Item_func_eq *item_eq= new Item_func_eq(in_subq_pred->left_expr, right_expr); if (item_eq == NULL) DBUG_RETURN(true); /* purecov: inspected */ sj_cond= and_items(sj_cond, item_eq); if (sj_cond == NULL) DBUG_RETURN(true); /* purecov: inspected */ } else { for (uint i= 0; i < in_subq_pred->left_expr->cols(); i++) { nested_join->sj_outer_exprs.push_back(in_subq_pred->left_expr-> element_index(i)); nested_join->sj_inner_exprs.push_back(subq_select->ref_pointer_array[i]); Item_func_eq *item_eq= new Item_func_eq(in_subq_pred->left_expr->element_index(i), subq_select->ref_pointer_array[i]); if (item_eq == NULL) DBUG_RETURN(true); /* purecov: inspected */ sj_cond= and_items(sj_cond, item_eq); if (sj_cond == NULL) DBUG_RETURN(true); /* purecov: inspected */ } } // Fix the created equality and AND Opt_trace_array sj_on_trace(&thd->opt_trace, "evaluating_constant_semijoin_conditions"); sj_cond->top_level_item(); if (sj_cond->fix_fields(thd, &sj_cond)) DBUG_RETURN(true); /* purecov: inspected */ // Attach semi-join condition to semi-join nest sj_nest->set_sj_cond(sj_cond); } // Unlink the subquery's query expression: subq_select->master_unit()->exclude_level(); /* Add Name res objects belonging to subquery to parent query block. Update all name res objects to have this base query block. */ for (Name_resolution_context *ctx= subq_select->first_context; ctx != NULL; ctx= ctx->next_context) { ctx->select_lex= this; if (ctx->next_context == NULL) { ctx->next_context= first_context; first_context= subq_select->first_context; subq_select->first_context= NULL; break; } } repoint_contexts_of_join_nests(subq_select->top_join_list); // Update table map for the semi-join condition sj_nest->sj_cond()->fix_after_pullout(this, subq_select); // Update table map for semi-join nest's WHERE condition and join conditions fix_tables_after_pullout(this, subq_select, sj_nest, 0); //TODO fix QT_ DBUG_EXECUTE("where", print_where(sj_nest->sj_cond(),"SJ-COND", QT_ORDINARY);); if (emb_tbl_nest) { // Inject semi-join condition into parent's join condition emb_tbl_nest->set_join_cond(and_items(emb_tbl_nest->join_cond(), sj_nest->sj_cond())); if (emb_tbl_nest->join_cond() == NULL) DBUG_RETURN(true); emb_tbl_nest->join_cond()->top_level_item(); if (!emb_tbl_nest->join_cond()->fixed && emb_tbl_nest->join_cond()->fix_fields(thd, emb_tbl_nest->join_cond_ref())) DBUG_RETURN(true); } else { // Inject semi-join condition into parent's WHERE condition m_where_cond= and_items(m_where_cond, sj_nest->sj_cond()); if (m_where_cond == NULL) DBUG_RETURN(true); m_where_cond->top_level_item(); if (m_where_cond->fix_fields(thd, &m_where_cond)) DBUG_RETURN(true); } if (subq_select->ftfunc_list->elements && add_ftfunc_list(subq_select->ftfunc_list)) DBUG_RETURN(true); /* purecov: inspected */ // This query block has semi-join nests has_sj_nests= true; DBUG_RETURN(false); } /** Merge a derived table or view into a query block. If some constraint prevents the derived table from being merged then do nothing, which means the table will be prepared for materialization later. After this call, check is_merged() to see if the table was really merged. @param thd Thread handler @param derived_table Derived table which is to be merged. @return false if successful, true if error */ bool SELECT_LEX::merge_derived(THD *thd, TABLE_LIST *derived_table) { DBUG_ENTER("SELECT_LEX::merge_derived"); if (!derived_table->is_view_or_derived() || derived_table->is_merged()) DBUG_RETURN(false); SELECT_LEX_UNIT *const derived_unit= derived_table->derived_unit(); // A derived table must be prepared before we can merge it DBUG_ASSERT(derived_unit->is_prepared()); LEX *const lex= parent_lex; // Check whether the outer query allows merged views if ((master_unit() == lex->unit && !lex->can_use_merged()) || lex->can_not_use_merged()) DBUG_RETURN(false); // Check whether derived table is mergeable, and directives allow merging if (!derived_unit->is_mergeable() || derived_table->algorithm == VIEW_ALGORITHM_TEMPTABLE || (!thd->optimizer_switch_flag(OPTIMIZER_SWITCH_DERIVED_MERGE) && derived_table->algorithm != VIEW_ALGORITHM_MERGE)) DBUG_RETURN(false); SELECT_LEX *const derived_select= derived_unit->first_select(); /* If STRAIGHT_JOIN is specified, it is not valid to merge in a query block that contains semi-join nests */ if ((active_options() & SELECT_STRAIGHT_JOIN) && derived_select->has_sj_nests) DBUG_RETURN(false); // Check that we have room for the merged tables in the table map: if (leaf_table_count + derived_select->leaf_table_count - 1 > MAX_TABLES) DBUG_RETURN(false); derived_table->set_merged(); DBUG_PRINT("info", ("algorithm: MERGE")); Opt_trace_context *const trace= &thd->opt_trace; Opt_trace_object trace_wrapper(trace); Opt_trace_object trace_derived(trace, derived_table->is_view() ? "view" : "derived"); trace_derived.add_utf8_table(derived_table). add("select#", derived_select->select_number). add("merged", true); Prepared_stmt_arena_holder ps_arena_holder(thd); // Save offset for table number adjustment uint table_adjust= derived_table->tableno(); // Set up permanent list of underlying tables of a merged view derived_table->merge_underlying_list= derived_select->get_table_list(); if (derived_table->updatable_view && (derived_table->merge_underlying_list == NULL || derived_table->merge_underlying_list->is_updatable())) derived_table->set_updatable(); derived_table->effective_with_check= lex->get_effective_with_check(derived_table); // Add a nested join object to the derived table object if (!(derived_table->nested_join= (NESTED_JOIN *) thd->mem_calloc(sizeof(NESTED_JOIN)))) DBUG_RETURN(true); /* purecov: inspected */ derived_table->nested_join->join_list.empty();//Should be done by constructor! // Merge tables from underlying query block into this join nest if (derived_table->merge_underlying_tables(derived_select)) DBUG_RETURN(true); /* purecov: inspected */ // Replace derived table in leaf table list with underlying tables: for (TABLE_LIST **tl= &leaf_tables; *tl; tl= &(*tl)->next_leaf) { if (*tl == derived_table) { for (TABLE_LIST *leaf= derived_select->leaf_tables; leaf; leaf= leaf->next_leaf) { if (leaf->next_leaf == NULL) { leaf->next_leaf= (*tl)->next_leaf; break; } } *tl= derived_select->leaf_tables; break; } } leaf_table_count+= (derived_select->leaf_table_count - 1); derived_table_count+= derived_select->derived_table_count; materialized_derived_table_count+= derived_select->materialized_derived_table_count; has_sj_nests|= derived_select->has_sj_nests; partitioned_table_count+= derived_select->partitioned_table_count; cond_count+= derived_select->cond_count; between_count+= derived_select->between_count; // Propagate schema table indication: // @todo: Add to BASE options instead if (derived_select->active_options() & OPTION_SCHEMA_TABLE) add_base_options(OPTION_SCHEMA_TABLE); // Propagate nullability for derived tables within outer joins: if (derived_table->is_inner_table_of_outer_join()) propagate_nullability(&derived_table->nested_join->join_list, true); select_n_having_items+= derived_select->select_n_having_items; // Merge the WHERE clause into the outer query block if (derived_table->merge_where(thd)) DBUG_RETURN(true); /* purecov: inspected */ if (derived_table->create_field_translation(thd)) DBUG_RETURN(true); /* purecov: inspected */ // Exclude the derived table query expression from query graph. derived_unit->exclude_level(); // Don't try to access it: derived_table->set_derived_unit((SELECT_LEX_UNIT *)1); /* Add Name res objects belonging to subquery to parent query block. Update all name res objects to have this base query block. */ for (Name_resolution_context *ctx= derived_select->first_context; ctx != NULL; ctx= ctx->next_context) { ctx->select_lex= this; if (ctx->next_context == NULL) { ctx->next_context= first_context; first_context= derived_select->first_context; derived_select->first_context= NULL; break; } } repoint_contexts_of_join_nests(derived_select->top_join_list); // Leaf tables have been shuffled, so update table numbers for them remap_tables(thd); // Update table info of referenced expressions after query block is merged fix_tables_after_pullout(this, derived_select, derived_table, table_adjust); if (derived_select->is_ordered()) { /* An ORDER BY clause is moved to an outer query block - if the outer query block allows ordering, and - that refers to this view/derived table only, and - is not part of a UNION, and - may have a WHERE clause but is not grouped or aggregated and is not itself ordered. Otherwise the ORDER BY clause is ignored. Up to version 5.6 included, ORDER BY was unconditionally merged. Currently we only merge in the simple case above, which ensures backward compatibility for most reasonable use cases. Note that table numbers in order_list do not need updating, since the outer query contains only one table reference. */ // LIMIT currently blocks derived table merge DBUG_ASSERT(!derived_select->has_limit()); if (!(master_unit()->is_union() || lex->sql_command == SQLCOM_UPDATE_MULTI || lex->sql_command == SQLCOM_DELETE_MULTI || is_grouped() || is_distinct() || is_ordered() || get_table_list()->next_local != NULL)) order_list.push_back(&derived_select->order_list); } // Add any full-text functions from derived table into outer query if (derived_select->ftfunc_list->elements && add_ftfunc_list(derived_select->ftfunc_list)) DBUG_RETURN(true); /* purecov: inspected */ DBUG_RETURN(false); } /** Destructively replaces a sub-condition inside a condition tree. The parse tree is also altered. @note Because of current requirements for semijoin flattening, we do not need to recurse here, hence this function will only examine the top-level AND conditions. (see SELECT_LEX::prepare, comment starting with "Check if the subquery predicate can be executed via materialization".) @param thd thread handler @param tree Must be the handle to the top level condition. This is needed when the top-level condition changes. @param old_cond The condition to be replaced. @param new_cond The condition to be substituted. @param do_fix_fields If true, Item::fix_fields(THD*, Item**) is called for the new condition. @return error status @retval true If there was an error. @retval false If successful. */ static bool replace_subcondition(THD *thd, Item **tree, Item *old_cond, Item *new_cond, bool do_fix_fields) { if (*tree == old_cond) { *tree= new_cond; if (do_fix_fields && new_cond->fix_fields(thd, tree)) return TRUE; return FALSE; } else if ((*tree)->type() == Item::COND_ITEM) { List_iterator<Item> li(*((Item_cond*)(*tree))->argument_list()); Item *item; while ((item= li++)) { if (item == old_cond) { li.replace(new_cond); if (do_fix_fields && new_cond->fix_fields(thd, li.ref())) return TRUE; return FALSE; } } } else // If we came here it means there were an error during prerequisites check. DBUG_ASSERT(FALSE); return TRUE; } /* Convert semi-join subquery predicates into semi-join join nests DESCRIPTION Convert candidate subquery predicates into semi-join join nests. This transformation is performed once in query lifetime and is irreversible. Conversion of one subquery predicate ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We start with a join that has a semi-join subquery: SELECT ... FROM ot, ... WHERE oe IN (SELECT ie FROM it1 ... itN WHERE subq_where) AND outer_where and convert it into a semi-join nest: SELECT ... FROM ot SEMI JOIN (it1 ... itN), ... WHERE outer_where AND subq_where AND oe=ie that is, in order to do the conversion, we need to * Create the "SEMI JOIN (it1 .. itN)" part and add it into the parent query's FROM structure. * Add "AND subq_where AND oe=ie" into parent query's WHERE (or ON if the subquery predicate was in an ON expression) * Remove the subquery predicate from the parent query's WHERE Considerations when converting many predicates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A join may have at most MAX_TABLES tables. This may prevent us from flattening all subqueries when the total number of tables in parent and child selects exceeds MAX_TABLES. In addition, one slot is reserved per semi-join nest, in case the subquery needs to be materialized in a temporary table. We deal with this problem by flattening children's subqueries first and then using a heuristic rule to determine each subquery predicate's "priority". RETURN FALSE OK TRUE Error */ bool SELECT_LEX::flatten_subqueries() { DBUG_ENTER("flatten_subqueries"); if (sj_candidates->empty()) DBUG_RETURN(FALSE); Item_exists_subselect **subq, **subq_begin= sj_candidates->begin(), **subq_end= sj_candidates->end(); THD *const thd= (*subq_begin)->unit->thd; Opt_trace_context *const trace= &thd->opt_trace; /* Semijoin flattening is bottom-up. Indeed, we have this execution flow, for SELECT#1 WHERE X IN (SELECT #2 WHERE Y IN (SELECT#3)) : SELECT_LEX::prepare() (select#1) -> fix_fields() on IN condition -> SELECT_LEX::prepare() on subquery (select#2) -> fix_fields() on IN condition -> SELECT_LEX::prepare() on subquery (select#3) <- SELECT_LEX::prepare() <- fix_fields() -> flatten_subqueries: merge #3 in #2 <- flatten_subqueries <- SELECT_LEX::prepare() <- fix_fields() -> flatten_subqueries: merge #2 in #1 Note that flattening of #(N) is done by its parent JOIN#(N-1), because there are cases where flattening is not possible and only the parent can know. */ for (subq= subq_begin; subq < subq_end; subq++) { /* Currently, we only support transformation of IN subqueries. */ DBUG_ASSERT((*subq)->substype() == Item_subselect::IN_SUBS); st_select_lex *child_select= (*subq)->unit->first_select(); // Check that we proceeded bottom-up DBUG_ASSERT(child_select->sj_candidates == NULL); (*subq)->sj_convert_priority= (((*subq)->unit->uncacheable & UNCACHEABLE_DEPENDENT) ? MAX_TABLES : 0) + child_select->leaf_table_count; } /* 2. Pick which subqueries to convert: sort the subquery array - prefer correlated subqueries over uncorrelated; - prefer subqueries that have greater number of outer tables; */ my_qsort(subq_begin, sj_candidates->size(), sj_candidates->element_size(), reinterpret_cast<qsort_cmp>(subq_sj_candidate_cmp)); // A permanent transformation is going to start, so: Prepared_stmt_arena_holder ps_arena_holder(thd); // #tables-in-parent-query + #tables-in-subquery + sj nests <= MAX_TABLES /* Replace all subqueries to be flattened with Item_int(1) */ uint table_count= leaf_table_count; for (subq= subq_begin; subq < subq_end; subq++) { // Add the tables in the subquery nest plus one in case of materialization: const uint tables_added= (*subq)->unit->first_select()->leaf_table_count + 1; (*subq)->sj_chosen= table_count + tables_added <= MAX_TABLES; if (!(*subq)->sj_chosen) continue; table_count+= tables_added; // In WHERE/ON of parent query, replace IN(subq) with "1" (<=>TRUE) Item **tree= ((*subq)->embedding_join_nest == NULL) ? &m_where_cond : (*subq)->embedding_join_nest->join_cond_ref(); if (replace_subcondition(thd, tree, *subq, new Item_int(1), FALSE)) DBUG_RETURN(TRUE); /* purecov: inspected */ } for (subq= subq_begin; subq < subq_end; subq++) { if (!(*subq)->sj_chosen) continue; OPT_TRACE_TRANSFORM(trace, oto0, oto1, (*subq)->unit->first_select()->select_number, "IN (SELECT)", "semijoin"); oto1.add("chosen", true); if (convert_subquery_to_semijoin(*subq)) DBUG_RETURN(TRUE); } /* 3. Finalize the subqueries that we did not convert, ie. perform IN->EXISTS rewrite. */ for (subq= subq_begin; subq < subq_end; subq++) { if ((*subq)->sj_chosen) continue; { OPT_TRACE_TRANSFORM(trace, oto0, oto1, (*subq)->unit->first_select()->select_number, "IN (SELECT)", "semijoin"); oto1.add("chosen", false); } Item_subselect::trans_res res; (*subq)->changed= 0; (*subq)->fixed= 0; SELECT_LEX *save_select_lex= thd->lex->current_select(); thd->lex->set_current_select((*subq)->unit->first_select()); // This is the only part of the function which uses a JOIN. res= (*subq)->select_transformer((*subq)->unit->first_select()); thd->lex->set_current_select(save_select_lex); if (res == Item_subselect::RES_ERROR) DBUG_RETURN(TRUE); (*subq)->changed= 1; (*subq)->fixed= 1; Item *substitute= (*subq)->substitution; const bool do_fix_fields= !(*subq)->substitution->fixed; const bool subquery_in_join_clause= (*subq)->embedding_join_nest != NULL; Item **tree= subquery_in_join_clause ? ((*subq)->embedding_join_nest->join_cond_ref()) : &m_where_cond; if (replace_subcondition(thd, tree, *subq, substitute, do_fix_fields)) DBUG_RETURN(TRUE); (*subq)->substitution= NULL; } sj_candidates->clear(); DBUG_RETURN(FALSE); } /** Propagate nullability into inner tables of outer join operation @param tables: List of tables and join nests, start at top_join_list @param nullable: true: Set all underlying tables as nullable */ static void propagate_nullability(List<TABLE_LIST> *tables, bool nullable) { List_iterator<TABLE_LIST> li(*tables); TABLE_LIST *tr; while ((tr= li++)) { if (tr->table && !tr->table->is_nullable() && (nullable || tr->outer_join)) tr->table->set_nullable(); if (tr->nested_join == NULL) continue; propagate_nullability(&tr->nested_join->join_list, nullable || tr->outer_join); } } /** Propagate exclusion from unique table check into all subqueries belonging to this query block. This function can be applied to all subqueries of a materialized derived table or view. */ void st_select_lex::propagate_unique_test_exclusion() { for (SELECT_LEX_UNIT *unit= first_inner_unit(); unit; unit= unit->next_unit()) for (SELECT_LEX *sl= unit->first_select(); sl; sl= sl->next_select()) sl->propagate_unique_test_exclusion(); exclude_from_table_unique_test= true; } /** Add a list of full-text function elements into a query block. @param ftfuncs List of full-text function elements to add. @returns false if success, true if error */ bool SELECT_LEX::add_ftfunc_list(List<Item_func_match> *ftfuncs) { Item_func_match *ifm; List_iterator_fast<Item_func_match> li(*ftfuncs); while ((ifm= li++)) { if (ftfunc_list->push_front(ifm)) return true; /* purecov: inspected */ } return false; } /** Go through a list of tables and join nests, recursively, and repoint its select_lex pointer. @param join_list List of tables and join nests */ void SELECT_LEX::repoint_contexts_of_join_nests(List<TABLE_LIST> join_list) { List_iterator_fast<TABLE_LIST> ti(join_list); TABLE_LIST *tbl; while ((tbl= ti++)) { tbl->select_lex= this; if (tbl->nested_join) repoint_contexts_of_join_nests(tbl->nested_join->join_list); } } /** Fix fields referenced from inner query blocks. @param thd Thread handle @details The function serves 3 purposes - adds fields referenced from inner query blocks to the current select list - Decides which class to use to reference the items (Item_ref or Item_direct_ref) - fixes references (Item_ref objects) to these fields. If a field isn't already on the select list and the ref_ptrs array is provided then it is added to the all_fields list and the pointer to it is saved in the ref_ptrs array. The class to access the outer field is determined by the following rules: -#. If the outer field isn't used under an aggregate function then the Item_ref class should be used. -#. If the outer field is used under an aggregate function and this function is, in turn, aggregated in the query block where the outer field was resolved or some query nested therein, then the Item_direct_ref class should be used. Also it should be used if we are grouping by a subquery containing the outer field. The resolution is done here and not at the fix_fields() stage as it can be done only after aggregate functions are fixed and pulled up to selects where they are to be aggregated. When the class is chosen it substitutes the original field in the Item_outer_ref object. After this we proceed with fixing references (Item_outer_ref objects) to this field from inner subqueries. @return false if success, true if error */ bool SELECT_LEX::fix_inner_refs(THD *thd) { Item_outer_ref *ref; List_iterator<Item_outer_ref> ref_it(inner_refs_list); while ((ref= ref_it++)) { bool direct_ref= false; Item *item= ref->outer_ref; Item **item_ref= ref->ref; /* TODO: this field item already might be present in the select list. In this case instead of adding new field item we could use an existing one. The change will lead to less operations for copying fields, smaller temporary tables and less data passed through filesort. */ if (!ref_ptrs.is_null() && !ref->found_in_select_list) { int el= all_fields.elements; ref_ptrs[el]= item; /* Add the field item to the select list of the current select. */ all_fields.push_front(item); /* If it's needed reset each Item_ref item that refers this field with a new reference taken from ref_pointer_array. */ item_ref= &ref_ptrs[el]; } if (ref->in_sum_func) { if (ref->in_sum_func->nest_level > nest_level) direct_ref= true; else { for (Item_sum *sum_func= ref->in_sum_func; sum_func && sum_func->aggr_level >= nest_level; sum_func= sum_func->in_sum_func) { if (sum_func->aggr_level == nest_level) { direct_ref= true; break; } } } } else { /* Check if GROUP BY item trees contain the outer ref: in this case we have to use Item_direct_ref instead of Item_ref. */ for (ORDER *group= group_list.first; group; group= group->next) { if ((*group->item)->walk(&Item::find_item_processor, walk_subquery, (uchar *) ref)) { direct_ref= true; break; } } } Item_ref *const new_ref= direct_ref ? new Item_direct_ref(ref->context, item_ref, ref->table_name, ref->field_name, ref->is_alias_of_expr()) : new Item_ref(ref->context, item_ref, ref->table_name, ref->field_name, ref->is_alias_of_expr()); if (!new_ref) return true; /* purecov: inspected */ ref->outer_ref= new_ref; ref->ref= &ref->outer_ref; if (!ref->fixed && ref->fix_fields(thd, 0)) return true; /* purecov: inspected */ thd->lex->used_tables|= item->used_tables(); select_list_tables|= item->used_tables(); } return false; } /** Since LIMIT is not supported for table subquery predicates (IN/ALL/EXISTS/etc), the following clauses are redundant for subqueries: ORDER BY DISTINCT GROUP BY if there are no aggregate functions and no HAVING clause This removal is permanent. Thus, it only makes sense to call this function for regular queries and on first execution of SP/PS @param thd thread handler @param hidden_group_field_count Number of hidden group fields added by setup_group(). @param hidden_order_field_count Number of hidden order fields added by setup_order(). */ void SELECT_LEX::remove_redundant_subquery_clauses(THD *thd, int hidden_group_field_count, int hidden_order_field_count) { Item_subselect *subq_predicate= master_unit()->item; /* The removal should happen for IN, ALL, ANY and EXISTS subqueries, which means all but single row subqueries. Example single row subqueries: a) SELECT * FROM t1 WHERE t1.a = (<single row subquery>) b) SELECT a, (<single row subquery) FROM t1 */ if (subq_predicate->substype() == Item_subselect::SINGLEROW_SUBS) return; // A subquery that is not single row should be one of IN/ALL/ANY/EXISTS. DBUG_ASSERT (subq_predicate->substype() == Item_subselect::EXISTS_SUBS || subq_predicate->substype() == Item_subselect::IN_SUBS || subq_predicate->substype() == Item_subselect::ALL_SUBS || subq_predicate->substype() == Item_subselect::ANY_SUBS); enum change { REMOVE_NONE=0, REMOVE_ORDER= 1 << 0, REMOVE_DISTINCT= 1 << 1, REMOVE_GROUP= 1 << 2 }; uint changelog= 0; if (order_list.elements) { changelog|= REMOVE_ORDER; empty_order_list(hidden_order_field_count); } if (is_distinct()) { changelog|= REMOVE_DISTINCT; remove_base_options(SELECT_DISTINCT); } // Remove GROUP BY if there are no aggregate functions and no HAVING clause if (group_list.elements && !agg_func_used() && !having_cond()) { changelog|= REMOVE_GROUP; for (ORDER *g= group_list.first; g != NULL; g= g->next) { if (*g->item == g->item_ptr) (*g->item)->walk(&Item::clean_up_after_removal, walk_subquery, reinterpret_cast<uchar*>(this)); } group_list.empty(); while (hidden_group_field_count-- > 0) { all_fields.pop(); ref_ptrs[all_fields.elements]= NULL; } } if (changelog) { Opt_trace_context * trace= &thd->opt_trace; if (unlikely(trace->is_started())) { Opt_trace_object trace_wrapper(trace); Opt_trace_array trace_changes(trace, "transformations_to_subquery"); if (changelog & REMOVE_ORDER) trace_changes.add_alnum("removed_ordering"); if (changelog & REMOVE_DISTINCT) trace_changes.add_alnum("removed_distinct"); if (changelog & REMOVE_GROUP) trace_changes.add_alnum("removed_grouping"); } } } /** Empty the ORDER list. Delete corresponding elements from all_fields and ref_ptrs too. If ORDER list contain any subqueries, delete them from the query block list. @param hidden_order_field_count Number of hidden order fields to remove */ void SELECT_LEX::empty_order_list(int hidden_order_field_count) { for (ORDER *o= order_list.first; o != NULL; o= o->next) { if (*o->item == o->item_ptr) (*o->item)->walk(&Item::clean_up_after_removal, walk_subquery, reinterpret_cast<uchar*>(this)); } order_list.empty(); while (hidden_order_field_count-- > 0) { all_fields.pop(); ref_ptrs[all_fields.elements]= NULL; } } /***************************************************************************** Group and order functions *****************************************************************************/ /** Resolve an ORDER BY or GROUP BY column reference. Given a column reference (represented by 'order') from a GROUP BY or ORDER BY clause, find the actual column it represents. If the column being resolved is from the GROUP BY clause, the procedure searches the SELECT list 'fields' and the columns in the FROM list 'tables'. If 'order' is from the ORDER BY clause, only the SELECT list is being searched. If 'order' is resolved to an Item, then order->item is set to the found Item. If there is no item for the found column (that is, it was resolved into a table field), order->item is 'fixed' and is added to all_fields and ref_pointer_array. ref_pointer_array and all_fields are updated. @param[in] thd Pointer to current thread structure @param[in,out] ref_pointer_array All select, group and order by fields @param[in] tables List of tables to search in (usually FROM clause) @param[in] order Column reference to be resolved @param[in] fields List of fields to search in (usually SELECT list) @param[in,out] all_fields All select, group and order by fields @param[in] is_group_field True if order is a GROUP field, false if ORDER by field @retval FALSE if OK @retval TRUE if error occurred */ static bool find_order_in_list(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, ORDER *order, List<Item> &fields, List<Item> &all_fields, bool is_group_field) { Item *order_item= *order->item; /* The item from the GROUP/ORDER caluse. */ Item::Type order_item_type; Item **select_item; /* The corresponding item from the SELECT clause. */ Field *from_field; /* The corresponding field from the FROM clause. */ uint counter; enum_resolution_type resolution; /* Local SP variables may be int but are expressions, not positions. (And they can't be used before fix_fields is called for them). */ if (order_item->type() == Item::INT_ITEM && order_item->basic_const_item()) { /* Order by position */ uint count= (uint) order_item->val_int(); if (!count || count > fields.elements) { my_error(ER_BAD_FIELD_ERROR, MYF(0), order_item->full_name(), thd->where); return TRUE; } order->item= &ref_pointer_array[count - 1]; order->in_field_list= 1; return FALSE; } /* Lookup the current GROUP/ORDER field in the SELECT clause. */ select_item= find_item_in_list(order_item, fields, &counter, REPORT_EXCEPT_NOT_FOUND, &resolution); if (!select_item) return TRUE; /* The item is not unique, or some other error occured. */ /* Check whether the resolved field is not ambiguos. */ if (select_item != not_found_item) { Item *view_ref= NULL; /* If we have found field not by its alias in select list but by its original field name, we should additionally check if we have conflict for this name (in case if we would perform lookup in all tables). */ if (resolution == RESOLVED_BEHIND_ALIAS && !order_item->fixed && order_item->fix_fields(thd, order->item)) return TRUE; /* Lookup the current GROUP field in the FROM clause. */ order_item_type= order_item->type(); from_field= (Field*) not_found_field; if ((is_group_field && order_item_type == Item::FIELD_ITEM) || order_item_type == Item::REF_ITEM) { from_field= find_field_in_tables(thd, (Item_ident*) order_item, tables, NULL, &view_ref, IGNORE_ERRORS, TRUE, FALSE); if (!from_field) from_field= (Field*) not_found_field; } if (from_field == not_found_field || (from_field != view_ref_found ? /* it is field of base table => check that fields are same */ ((*select_item)->type() == Item::FIELD_ITEM && ((Item_field*) (*select_item))->field->eq(from_field)) : /* in is field of view table => check that references on translation table are same */ ((*select_item)->type() == Item::REF_ITEM && view_ref->type() == Item::REF_ITEM && ((Item_ref *) (*select_item))->ref == ((Item_ref *) view_ref)->ref))) { /* If there is no such field in the FROM clause, or it is the same field as the one found in the SELECT clause, then use the Item created for the SELECT field. As a result if there was a derived field that 'shadowed' a table field with the same name, the table field will be chosen over the derived field. If we replace *order->item with one from the select list or from a table in the FROM list, we should clean up after removing the old *order->item from the query. The item has not been fixed (so there are no aggregation functions that need cleaning up), but it may contain subqueries that should be unlinked. */ if (*order->item != *select_item) (*order->item)->walk(&Item::clean_up_after_removal, walk_subquery, NULL); order->item= &ref_pointer_array[counter]; order->in_field_list=1; if (resolution == RESOLVED_AGAINST_ALIAS) order->used_alias= true; return FALSE; } else { /* There is a field with the same name in the FROM clause. This is the field that will be chosen. In this case we issue a warning so the user knows that the field from the FROM clause overshadows the column reference from the SELECT list. */ push_warning_printf(thd, Sql_condition::SL_WARNING, ER_NON_UNIQ_ERROR, ER(ER_NON_UNIQ_ERROR), ((Item_ident*) order_item)->field_name, current_thd->where); } } order->in_field_list=0; /* The call to order_item->fix_fields() means that here we resolve 'order_item' to a column from a table in the list 'tables', or to a column in some outer query. Exactly because of the second case we come to this point even if (select_item == not_found_item), inspite of that fix_fields() calls find_item_in_list() one more time. We check order_item->fixed because Item_func_group_concat can put arguments for which fix_fields already was called. group_fix_field= TRUE is to resolve aliases from the SELECT list without creating of Item_ref-s: JOIN::exec() wraps aliased items in SELECT list with Item_copy items. To re-evaluate such a tree that includes Item_copy items we have to refresh Item_copy caches, but: - filesort() never refresh Item_copy items, - end_send_group() checks every record for group boundary by the test_if_group_changed function that obtain data from these Item_copy items, but the copy_fields function that refreshes Item copy items is called after group boundaries only - that is a vicious circle. So we prevent inclusion of Item_copy items. */ bool save_group_fix_field= thd->lex->current_select()->group_fix_field; if (is_group_field) thd->lex->current_select()->group_fix_field= TRUE; bool ret= (!order_item->fixed && (order_item->fix_fields(thd, order->item) || (order_item= *order->item)->check_cols(1))); thd->lex->current_select()->group_fix_field= save_group_fix_field; if (ret) return TRUE; /* Wrong field. */ uint el= all_fields.elements; all_fields.push_front(order_item); /* Add new field to field list. */ ref_pointer_array[el]= order_item; /* If the order_item is a SUM_FUNC_ITEM, when fix_fields is called ref_by is set to order->item which is the address of order_item. But this needs to be address of order_item in the all_fields list. As a result, when it gets replaced with Item_aggregate_ref object in Item::split_sum_func2, we will be able to retrieve the newly created object. */ if (order_item->type() == Item::SUM_FUNC_ITEM) ((Item_sum *)order_item)->ref_by= all_fields.head_ref(); /* Currently, we assume that this assertion holds. If it turns out that it fails for some query, order->item has changed and the old item is removed from the query. In that case, we must call walk() with clean_up_after_removal() on the old order->item. */ DBUG_ASSERT(order_item == *order->item); order->item= &ref_pointer_array[el]; return FALSE; } /** Resolve and setup list of expressions in ORDER BY clause. Change order to point at item in select list. If item isn't a number and doesn't exists in the select list, add it to the the field list. @param thd Thread handler @returns false if success, true if error */ bool setup_order(THD *thd, Ref_ptr_array ref_pointer_array, TABLE_LIST *tables, List<Item> &fields, List<Item> &all_fields, ORDER *order) { DBUG_ASSERT(order); SELECT_LEX *const select= thd->lex->current_select(); thd->where="order clause"; const bool for_union= select->master_unit()->is_union() && select == select->master_unit()->fake_select_lex; const bool is_aggregated= select->is_grouped(); for (uint number= 1; order; order=order->next, number++) { if (find_order_in_list(thd, ref_pointer_array, tables, order, fields, all_fields, false)) return true; if ((*order->item)->with_sum_func) { /* Aggregated expressions in ORDER BY are not supported by SQL standard, but MySQL has some limited support for them. The limitations are checked below: 1. A UNION query is not aggregated, so ordering by a set function is always wrong. */ if (for_union) { my_error(ER_AGGREGATE_ORDER_FOR_UNION, MYF(0), number); return true; } /* 2. A non-aggregated query combined with a set function in ORDER BY that does not contain an outer reference is illegal, because it would cause the query to become aggregated. (Since is_aggregated is false, this expression would cause agg_func_used() to become true). */ if (!is_aggregated && select->agg_func_used()) { my_error(ER_AGGREGATE_ORDER_NON_AGG_QUERY, MYF(0), number); return true; } } } return false; } /** Runs checks mandated by ONLY_FULL_GROUP_BY @param thd THD pointer @returns true if ONLY_FULL_GROUP_BY is violated. */ bool SELECT_LEX::check_only_full_group_by(THD *thd) { bool rc= false; if (is_grouped()) { MEM_ROOT root; /* "root" has very short lifetime, and should not consume much => not instrumented. */ init_sql_alloc(PSI_NOT_INSTRUMENTED, &root, MEM_ROOT_BLOCK_SIZE, 0); { Group_check gc(this, &root); rc= gc.check_query(thd); gc.to_opt_trace(thd); } // scope, to let any destructor run before free_root(). free_root(&root, MYF(0)); } if (!rc && is_distinct() && // aggregate without GROUP => single-row result => don't bother user !(!group_list.elements && agg_func_used())) { Distinct_check dc(this); rc= dc.check_query(thd); } return rc; } /** Do final setup of ORDER BY clause, after the query block is fully resolved. Check that ORDER BY clause is not redundant. Split any aggregate functions. @param thd Thread handler @param hidden_order_field_count Number of fields to delete from ref array if ORDER BY clause is redundant. @returns false if success, true if error */ bool SELECT_LEX::setup_order_final(THD *thd, int hidden_order_field_count) { if (is_implicitly_grouped()) { // Result will contain zero or one row - ordering is redundant empty_order_list(hidden_order_field_count); return false; } if ((master_unit()->is_union() || master_unit()->fake_select_lex) && this != master_unit()->fake_select_lex && !(braces && explicit_limit)) { // Part of UNION which requires global ordering may skip local order empty_order_list(hidden_order_field_count); return false; } for (ORDER *ord= (ORDER *)order_list.first; ord; ord= ord->next) { Item *const item= *ord->item; if (item->with_sum_func && item->type() != Item::SUM_FUNC_ITEM) { item->split_sum_func(thd, ref_ptrs, all_fields); if (thd->is_error()) return true; /* purecov: inspected */ } } return false; } /** Resolve and set up the GROUP BY list. @param thd Thread handler @todo change ER_WRONG_FIELD_WITH_GROUP to more detailed ER_NON_GROUPING_FIELD_USED @returns false if success, true if error */ bool SELECT_LEX::setup_group(THD *thd) { DBUG_ASSERT(group_list.elements); thd->where="group statement"; for (ORDER *group= group_list.first; group; group= group->next) { if (find_order_in_list(thd, ref_ptrs, get_table_list(), group, fields_list, all_fields, true)) return true; if ((*group->item)->with_sum_func) { my_error(ER_WRONG_GROUP_FIELD, MYF(0), (*group->item)->full_name()); return true; } } return false; } /**************************************************************************** ROLLUP handling ****************************************************************************/ /** Replace occurrences of group by fields in an expression by ref items. The function replaces occurrences of group by fields in expr by ref objects for these fields unless they are under aggregate functions. The function also corrects value of the the maybe_null attribute for the items of all subexpressions containing group by fields. @b EXAMPLES @code SELECT a+1 FROM t1 GROUP BY a WITH ROLLUP SELECT SUM(a)+a FROM t1 GROUP BY a WITH ROLLUP @endcode @b IMPLEMENTATION The function recursively traverses the tree of the expr expression, looks for occurrences of the group by fields that are not under aggregate functions and replaces them for the corresponding ref items. @note This substitution is needed GROUP BY queries with ROLLUP if SELECT list contains expressions over group by attributes. @param thd reference to the context @param expr expression to make replacement @param changed[out] returns true if item contains a replaced field item @todo - TODO: Some functions are not null-preserving. For those functions updating of the maybe_null attribute is an overkill. @returns false if success, true if error */ bool SELECT_LEX::change_group_ref(THD *thd, Item_func *expr, bool *changed) { bool arg_changed= false; for (uint i= 0; i < expr->arg_count; i++) { Item **arg= expr->arguments() + i; Item *const item= *arg; if (item->type() == Item::FIELD_ITEM || item->type() == Item::REF_ITEM) { for (ORDER *group= (ORDER *)group_list.first; group; group= group->next) { if (item->eq(*group->item, 0)) { Item *new_item; if (!(new_item= new Item_ref(&context, group->item, 0, item->item_name.ptr()))) return true; /* purecov: inspected */ thd->change_item_tree(arg, new_item); arg_changed= true; } } } else if (item->type() == Item::FUNC_ITEM) { if (change_group_ref(thd, (Item_func *) item, &arg_changed)) return true; } } if (arg_changed) { expr->maybe_null= true; *changed= true; } return false; } /** Resolve items for rollup processing @param thd Thread handler @returns false if success, true if error */ bool SELECT_LEX::resolve_rollup(THD *thd) { List_iterator<Item> it(all_fields); Item *item; while ((item= it++)) { bool found_in_group= false; for (ORDER *group= (ORDER *)group_list.first; group; group= group->next) { if (*group->item == item) { item->maybe_null= true; found_in_group= true; break; } } if (item->type() == Item::FUNC_ITEM && !found_in_group) { bool changed= false; if (change_group_ref(thd, (Item_func *) item, &changed)) return true; /* purecov: inspected */ /* We have to prevent creation of a field in a temporary table for an expression that contains GROUP BY attributes. Marking the expression item as 'with_sum_func' will ensure this. */ if (changed) item->with_sum_func= true; } } return false; } /** @brief validate_gc_assignment Check whether the other values except DEFAULT are assigned for generated columns. @param thd thread handler @param fields Item_fields list to be filled @param values values to fill with @param table table to be checked @return Operation status @retval false OK @retval true Error occured @Note: This function must be called after table->write_set has been filled. */ bool validate_gc_assignment(THD * thd, List<Item> *fields, List<Item> *values, TABLE *table) { Field **fld= NULL; MY_BITMAP *bitmap= table->write_set; bool use_table_field= false; DBUG_ENTER("validate_gc_assignment"); if (!values || (values->elements == 0)) DBUG_RETURN(false); // If fields has no elements, we use all table fields if (fields->elements == 0) { use_table_field= true; fld= table->field; } List_iterator_fast<Item> f(*fields),v(*values); Item *value; while ((value= v++)) { Field *rfield; if (!use_table_field) rfield= ((Item_field *)f++)->field; else rfield= *(fld++); if (rfield->table != table) continue; /* skip non marked fields */ if (!bitmap_is_set(bitmap, rfield->field_index)) continue; if (rfield->gcol_info && value->type() != Item::DEFAULT_VALUE_ITEM) { my_error(ER_NON_DEFAULT_VALUE_FOR_GENERATED_COLUMN, MYF(0), rfield->field_name, rfield->table->s->table_name.str); DBUG_RETURN(true); } } DBUG_RETURN(false); } /** Delete unused columns from merged tables. This function is called recursively for each join nest and/or table in the query block. For each merged table that it finds, each column that contains a subquery and is not marked as used is removed and the translation item is set to NULL. @param tables List of tables and join nests */ void SELECT_LEX::delete_unused_merged_columns(List<TABLE_LIST> *tables) { DBUG_ENTER("delete_unused_merged_columns"); TABLE_LIST *tl; List_iterator<TABLE_LIST> li(*tables); while ((tl= li++)) { if (tl->nested_join == NULL) continue; if (tl->is_merged()) { for (Field_translator *transl= tl->field_translation; transl < tl->field_translation_end; transl++) { DBUG_ASSERT(transl->item->fixed); if (transl->item->has_subquery() && !transl->item->is_derived_used()) { transl->item->walk(&Item::clean_up_after_removal, walk_subquery, (uchar *)this); transl->item= NULL; } } } delete_unused_merged_columns(&tl->nested_join->join_list); } DBUG_VOID_RETURN; } /** @} (end of group Query_Resolver) */
ForcerKing/ShaoqunXu-mysql5.7
sql/sql_resolver.cc
C++
gpl-2.0
121,648
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.core.soa; import java.util.Collection; import java.util.Map; /** * ServiceRegistry * * @author brozow * @version $Id: $ */ public interface ServiceRegistry { /** * <p>register</p> * * @param serviceProvider a {@link java.lang.Object} object. * @param services a {@link java.lang.Class} object. * @return a {@link org.opennms.core.soa.Registration} object. */ public Registration register(Object serviceProvider, Class<?>... services); /** * <p>register</p> * * @param serviceProvider a {@link java.lang.Object} object. * @param properties a {@link java.util.Map} object. * @param services a {@link java.lang.Class} object. * @return a {@link org.opennms.core.soa.Registration} object. */ public Registration register(Object serviceProvider, Map<String, String> properties, Class<?>... services); /** * <p>findProvider</p> * * @param seviceInterface a {@link java.lang.Class} object. * @param <T> a T object. * @return a T object. */ public <T> T findProvider(Class<T> seviceInterface); /** * <p>findProvider</p> * * @param serviceInterface a {@link java.lang.Class} object. * @param filter a {@link java.lang.String} object. * @param <T> a T object. * @return a T object. */ public <T> T findProvider(Class<T> serviceInterface, String filter); /** * <p>findProviders</p> * * @param service a {@link java.lang.Class} object. * @param <T> a T object. * @return a {@link java.util.Collection} object. */ public <T> Collection<T> findProviders(Class<T> service); /** * <p>findProviders</p> * * @param service a {@link java.lang.Class} object. * @param filter a {@link java.lang.String} object. * @param <T> a T object. * @return a {@link java.util.Collection} object. */ public <T> Collection<T> findProviders(Class<T> service, String filter); /** * <p>addListener</p> * * @param service a {@link java.lang.Class} object. * @param listener a {@link org.opennms.core.soa.RegistrationListener} object. * @param <T> a T object. */ public <T> void addListener(Class<T> service, RegistrationListener<T> listener); /** * <p>addListener</p> * * @param service a {@link java.lang.Class} object. * @param listener a {@link org.opennms.core.soa.RegistrationListener} object. * @param notifyForExistingProviders a boolean. * @param <T> a T object. */ public <T> void addListener(Class<T> service, RegistrationListener<T> listener, boolean notifyForExistingProviders); /** * <p>removeListener</p> * * @param service a {@link java.lang.Class} object. * @param listener a {@link org.opennms.core.soa.RegistrationListener} object. * @param <T> a T object. */ public <T> void removeListener(Class<T> service, RegistrationListener<T> listener); }
vishwaAbhinav/OpenNMS
core/soa/src/main/java/org/opennms/core/soa/ServiceRegistry.java
Java
gpl-2.0
4,248
<div id="<?php echo $iname; ?>messages" class="messages"> <?php // if there are messages loop through all messages if ($this->getInput('messages')) { foreach ($this->getInput('messages') as $message) { ?> <div class="messageblock"> <div class="header"> <div class="datetime"><?php echo $message["date_time"]; ?></div> <div class="username"> <span class="name"><?php echo $message["name"]; ?></span> <span class="said">said...</span> </div> </div> <div class="messagetext"><?php echo $message["message"]; ?></div> </div> <?php } } // end loop ?> </div>
peeto/DarkChat
src/web/displaymessages.php
PHP
gpl-2.0
667
/* Style the thumbnails */ .pika-thumbs{ padding: 0 16px; height: 75px; } .pika-thumbs li{ width: 144px; height:74px; margin: 10px 0 0 17px; padding: 0; overflow: hidden; float: left; list-style-type: none;padding: 3px; margin: 0 5px; background: #fafafa; border: 1px solid #e5e5e5; cursor: pointer;} .pika-thumbs li .clip {position:relative;height:100%;text-align: center; vertical-align: middle; overflow: hidden;} /* The stage is the wrapper. The image fills 100% the height of the stage */ .pika-stage, .pika-textnav {width: 500px;} .pika-stage {position: relative; background: #fafafa; border: 1px solid #e5e5e5; padding: 10px 10px 40px 10px; text-align:center; height:250px;} .pika-stage img{height:100%;} .pika-stage .caption {position: absolute; background: #000; background: rgba(0,0,0,0.75); border: 1px solid #141414; font-size: 11px; color: #fafafa; padding: 10px; text-align: right; bottom: 50px; right: 10px;} .pika-stage .caption p {padding: 0; margin: 0; line-height: 14px;} /* Ths play, pause, prev and next buttons */ .pika-imgnav a {position: absolute; text-indent: -5000px; display: block;z-index:3;} .pika-imgnav a.previous {background: url(prev.png) no-repeat left 45%; height: 100%; width: 50px; top: 10px; left: 10px;cursor:pointer;} .pika-imgnav a.next {background: url(next.png) no-repeat right 45%; height: 100%; width: 50px; top: 10px; right: 10px;cursor:pointer;} .pika-imgnav a.play {background: url(play.png) no-repeat 0% 50%; height: 100px; width: 44px;top:0;left:50%;display: none;cursor:pointer;} .pika-imgnav a.pause {background: url(pause.png) no-repeat 0% 50%; height: 100px; width: 44px;top:0;left:50%;display:none;cursor:pointer;} /* The previous and next textual buttons */ .pika-textnav {overflow: hidden; margin: 10px 0 0 0;bottom:10px; position:absolute;} .pika-textnav a {font-size: 12px; text-decoration: none; color: #333; padding: 4px;} .pika-textnav a.previous {float: left; width: auto; display: block;} .pika-textnav a.next {float: right; width: auto; display: block;} /*for the tool tips*/ .pika-tooltip{font-size:12px;position:absolute;color:white;padding:3px; background-color: rgba(0,0,0,0.7);border:3px solid black;} .pika-counter{position: absolute;bottom: 45px;left:15px;color:white;background:rgba(0,0,0,0.7);font-size:11px;padding:3px;-moz-border-radius: 5px;border-radius:5px;} /* If using user thumbnails there's a pause well the new large image loads. This is the loader for that */ .pika-loader{ background:url(loading.gif) 3px 3px no-repeat #000; background-color:rgba(0,0,0,0.9); color:white; width:60px; font-size:11px; padding:5px 3px; text-align:right; position:absolute; top:15px; right:15px; }
yogenyogen/margbillini
pikachoose/styles/base.css
CSS
gpl-2.0
2,691
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import re import urllib import urlparse import kodi import dom_parser from salts_lib import scraper_utils from salts_lib.constants import FORCE_NO_MATCH from salts_lib.constants import QUALITIES from salts_lib.constants import VIDEO_TYPES import scraper BASE_URL = 'http://watch8now.me' class Scraper(scraper.Scraper): base_url = BASE_URL def __init__(self, timeout=scraper.DEFAULT_TIMEOUT): self.timeout = timeout self.base_url = kodi.get_setting('%s-base_url' % (self.get_name())) @classmethod def provides(cls): return frozenset([VIDEO_TYPES.TVSHOW, VIDEO_TYPES.EPISODE]) @classmethod def get_name(cls): return 'Watch8Now' def resolve_link(self, link): html = self._http_get(link, cache_limit=.5) match = re.search('<iframe[^>]*src="([^"]+)', html, re.I) if match: return match.group(1) else: match = re.search('Nothing in HERE<br>([^<]+)', html, re.I) if match: return match.group(1).strip() return link def get_sources(self, video): source_url = self.get_url(video) hosters = [] if source_url and source_url != FORCE_NO_MATCH: url = urlparse.urljoin(self.base_url, source_url) html = self._http_get(url, cache_limit=.5) for table_cell in dom_parser.parse_dom(html, 'td', {'class': 'domain'}): match = re.search('href="([^"]+)(?:[^>]+>){2}\s*([^<]+)', table_cell) if match: link, host = match.groups() hoster = {'multi-part': False, 'host': host, 'class': self, 'quality': scraper_utils.get_quality(video, host, QUALITIES.HIGH), 'views': None, 'rating': None, 'url': link, 'direct': False} hosters.append(hoster) return hosters def _get_episode_url(self, show_url, video): episode_pattern = 'href="([^"]+[sS]%s[eE]%s\.html)"' % (video.season, video.episode) title_pattern = 'href="(?P<url>[^"]+[sS]\d+[eE]\d+\.html)"(?:[^>]+>){6}(?P<title>[^<]+)' return self._default_get_episode_url(show_url, video, episode_pattern, title_pattern) def search(self, video_type, title, year, season=''): search_url = urlparse.urljoin(self.base_url, '/search?q=') search_url += urllib.quote_plus(title) html = self._http_get(search_url, cache_limit=8) results = [] for item in dom_parser.parse_dom(html, 'h4', {'class': 'media-heading'}): match = re.search('href="([^"]+)">([^<]+)', item) if match: url, match_title = match.groups() result = {'url': scraper_utils.pathify_url(url), 'title': scraper_utils.cleanse_title(match_title), 'year': ''} results.append(result) return results
felipenaselva/repo.felipe
plugin.video.salts/scrapers/watch8now_scraper.py
Python
gpl-2.0
3,576
/******************************************************************************* LLDP Agent Daemon (LLDPAD) Software Copyright(c) 2007-2012 Intel Corporation. This program is free software; you can redistribute it and/or modify it under the terms and conditions of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. The full GNU General Public License is included in this distribution in the file called "COPYING". Contact Information: open-lldp Mailing List <lldp-devel@open-lldp.org> *******************************************************************************/ #ifndef _LLDP_BASMAN_CLIF_H #define _LLDP_BASMAN_CLIF_H struct lldp_module *basman_cli_register(void); void basman_cli_unregister(struct lldp_module *); int basman_print_tlv(u32, u16, char *); #define ARG_IPV4_ADDR "ipv4" #define ARG_IPV6_ADDR "ipv6" #define ARG_TLVINFO "info" #endif
openSUSE/lldpad
include/lldp_basman_clif.h
C
gpl-2.0
1,362
/*************************************************************************** qgsmemoryfeatureiterator.h --------------------- begin : Juli 2012 copyright : (C) 2012 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef QGSMEMORYFEATUREITERATOR_H #define QGSMEMORYFEATUREITERATOR_H #include "qgsfeatureiterator.h" #include "qgsexpressioncontext.h" #include "qgsfields.h" #include "qgsgeometry.h" class QgsMemoryProvider; typedef QMap<QgsFeatureId, QgsFeature> QgsFeatureMap; class QgsSpatialIndex; class QgsMemoryFeatureSource : public QgsAbstractFeatureSource { public: explicit QgsMemoryFeatureSource( const QgsMemoryProvider *p ); ~QgsMemoryFeatureSource(); virtual QgsFeatureIterator getFeatures( const QgsFeatureRequest &request ) override; protected: QgsFields mFields; QgsFeatureMap mFeatures; QgsSpatialIndex *mSpatialIndex = nullptr; QString mSubsetString; QgsExpressionContext mExpressionContext; friend class QgsMemoryFeatureIterator; }; class QgsMemoryFeatureIterator : public QgsAbstractFeatureIteratorFromSource<QgsMemoryFeatureSource> { public: QgsMemoryFeatureIterator( QgsMemoryFeatureSource *source, bool ownSource, const QgsFeatureRequest &request ); ~QgsMemoryFeatureIterator(); virtual bool rewind() override; virtual bool close() override; protected: virtual bool fetchFeature( QgsFeature &feature ) override; bool nextFeatureUsingList( QgsFeature &feature ); bool nextFeatureTraverseAll( QgsFeature &feature ); QgsGeometry mSelectRectGeom; QgsFeatureMap::const_iterator mSelectIterator; bool mUsingFeatureIdList; QList<QgsFeatureId> mFeatureIdList; QList<QgsFeatureId>::const_iterator mFeatureIdListIterator; QgsExpression *mSubsetExpression = nullptr; }; #endif // QGSMEMORYFEATUREITERATOR_H
myarjunar/QGIS
src/providers/memory/qgsmemoryfeatureiterator.h
C
gpl-2.0
2,518
#ifndef PTM_CONSTANTS_H #define PTM_CONSTANTS_H //------------------------------------ // definitions //------------------------------------ #define PTM_NO_ERROR 0 #define PTM_CHECK_FCC (1 << 0) #define PTM_CHECK_HCP (1 << 1) #define PTM_CHECK_BCC (1 << 2) #define PTM_CHECK_ICO (1 << 3) #define PTM_CHECK_SC (1 << 4) #define PTM_CHECK_DCUB (1 << 5) #define PTM_CHECK_DHEX (1 << 6) #define PTM_CHECK_NONDIAMOND (PTM_CHECK_SC | PTM_CHECK_FCC | PTM_CHECK_HCP | PTM_CHECK_ICO | PTM_CHECK_BCC) #define PTM_CHECK_ALL (PTM_CHECK_SC | PTM_CHECK_FCC | PTM_CHECK_HCP | PTM_CHECK_ICO | PTM_CHECK_BCC | PTM_CHECK_DCUB | PTM_CHECK_DHEX) #define PTM_MATCH_NONE 0 #define PTM_MATCH_FCC 1 #define PTM_MATCH_HCP 2 #define PTM_MATCH_BCC 3 #define PTM_MATCH_ICO 4 #define PTM_MATCH_SC 5 #define PTM_MATCH_DCUB 6 #define PTM_MATCH_DHEX 7 #define PTM_ALLOY_NONE 0 #define PTM_ALLOY_PURE 1 #define PTM_ALLOY_L10 2 #define PTM_ALLOY_L12_CU 3 #define PTM_ALLOY_L12_AU 4 #define PTM_ALLOY_B2 5 #define PTM_ALLOY_SIC 6 #define PTM_MAX_INPUT_POINTS 35 #define PTM_MAX_NBRS 16 #define PTM_MAX_POINTS (PTM_MAX_NBRS + 1) #define PTM_MAX_FACETS 28 //2 * PTM_MAX_NBRS - 4 #define PTM_MAX_EDGES 42 //3 * PTM_MAX_NBRS - 6 //------------------------------------ // number of neighbours //------------------------------------ #define PTM_NUM_NBRS_FCC 12 #define PTM_NUM_NBRS_HCP 12 #define PTM_NUM_NBRS_BCC 14 #define PTM_NUM_NBRS_ICO 12 #define PTM_NUM_NBRS_SC 6 #define PTM_NUM_NBRS_DCUB 16 #define PTM_NUM_NBRS_DHEX 16 #define PTM_NUM_POINTS_FCC (PTM_NUM_NBRS_FCC + 1) #define PTM_NUM_POINTS_HCP (PTM_NUM_NBRS_HCP + 1) #define PTM_NUM_POINTS_BCC (PTM_NUM_NBRS_BCC + 1) #define PTM_NUM_POINTS_ICO (PTM_NUM_NBRS_ICO + 1) #define PTM_NUM_POINTS_SC (PTM_NUM_NBRS_SC + 1) #define PTM_NUM_POINTS_DCUB (PTM_NUM_NBRS_DCUB + 1) #define PTM_NUM_POINTS_DHEX (PTM_NUM_NBRS_DHEX + 1) const int ptm_num_nbrs[8] = {0, PTM_NUM_NBRS_FCC, PTM_NUM_NBRS_HCP, PTM_NUM_NBRS_BCC, PTM_NUM_NBRS_ICO, PTM_NUM_NBRS_SC, PTM_NUM_NBRS_DCUB, PTM_NUM_NBRS_DHEX}; //------------------------------------ // template structures //------------------------------------ //these point sets have barycentre {0, 0, 0} and are scaled such that the mean neighbour distance is 1 const double ptm_template_fcc[PTM_NUM_POINTS_FCC][3] = { { 0. , 0. , 0. }, { 0. , 0.707106781187, 0.707106781187 }, { 0. , -0.707106781187, -0.707106781187 }, { 0. , 0.707106781187, -0.707106781187 }, { 0. , -0.707106781187, 0.707106781187 }, { 0.707106781187, 0. , 0.707106781187 }, { -0.707106781187, 0. , -0.707106781187 }, { 0.707106781187, 0. , -0.707106781187 }, { -0.707106781187, 0. , 0.707106781187 }, { 0.707106781187, 0.707106781187, 0. }, { -0.707106781187, -0.707106781187, 0. }, { 0.707106781187, -0.707106781187, 0. }, { -0.707106781187, 0.707106781187, 0. } }; const double ptm_template_hcp[PTM_NUM_POINTS_HCP][3] = { { 0. , 0. , 0. }, { 0.707106781186, 0. , 0.707106781186 }, { -0.235702260395, -0.942809041583, -0.235702260395 }, { 0.707106781186, 0.707106781186, 0. }, { -0.235702260395, -0.235702260395, -0.942809041583 }, { 0. , 0.707106781186, 0.707106781186 }, { -0.942809041583, -0.235702260395, -0.235702260395 }, { -0.707106781186, 0.707106781186, 0. }, { 0. , 0.707106781186, -0.707106781186 }, { 0.707106781186, 0. , -0.707106781186 }, { 0.707106781186, -0.707106781186, 0. }, { -0.707106781186, 0. , 0.707106781186 }, { 0. , -0.707106781186, 0.707106781186 } }; const double ptm_template_bcc[PTM_NUM_POINTS_BCC][3] = { { 0. , 0. , 0. }, { -0.541451884327, -0.541451884327, -0.541451884327 }, { 0.541451884327, 0.541451884327, 0.541451884327 }, { 0.541451884327, -0.541451884327, -0.541451884327 }, { -0.541451884327, 0.541451884327, 0.541451884327 }, { -0.541451884327, 0.541451884327, -0.541451884327 }, { 0.541451884327, -0.541451884327, 0.541451884327 }, { -0.541451884327, -0.541451884327, 0.541451884327 }, { 0.541451884327, 0.541451884327, -0.541451884327 }, { 0. , 0. , -1.082903768655 }, { 0. , 0. , 1.082903768655 }, { 0. , -1.082903768655, 0. }, { 0. , 1.082903768655, 0. }, { -1.082903768655, 0. , 0. }, { 1.082903768655, 0. , 0. } }; const double ptm_template_ico[PTM_NUM_POINTS_ICO][3] = { { 0. , 0. , 0. }, { 0. , 0.525731112119, 0.850650808352 }, { 0. , -0.525731112119, -0.850650808352 }, { 0. , 0.525731112119, -0.850650808352 }, { 0. , -0.525731112119, 0.850650808352 }, { -0.525731112119, -0.850650808352, 0. }, { 0.525731112119, 0.850650808352, 0. }, { 0.525731112119, -0.850650808352, 0. }, { -0.525731112119, 0.850650808352, 0. }, { -0.850650808352, 0. , -0.525731112119 }, { 0.850650808352, 0. , 0.525731112119 }, { 0.850650808352, 0. , -0.525731112119 }, { -0.850650808352, 0. , 0.525731112119 } }; const double ptm_template_sc[PTM_NUM_POINTS_SC][3] = { { 0. , 0. , 0. }, { 0. , 0. , -1. }, { 0. , 0. , 1. }, { 0. , -1. , 0. }, { 0. , 1. , 0. }, { -1. , 0. , 0. }, { 1. , 0. , 0. } }; const double ptm_template_dcub[PTM_NUM_POINTS_DCUB][3] = { { 0. , 0. , 0. }, { -0.391491627053, 0.391491627053, 0.391491627053 }, { -0.391491627053, -0.391491627053, -0.391491627053 }, { 0.391491627053, -0.391491627053, 0.391491627053 }, { 0.391491627053, 0.391491627053, -0.391491627053 }, { -0.782983254107, 0. , 0.782983254107 }, { -0.782983254107, 0.782983254107, 0. }, { 0. , 0.782983254107, 0.782983254107 }, { -0.782983254107, -0.782983254107, 0. }, { -0.782983254107, 0. , -0.782983254107 }, { 0. , -0.782983254107, -0.782983254107 }, { 0. , -0.782983254107, 0.782983254107 }, { 0.782983254107, -0.782983254107, 0. }, { 0.782983254107, 0. , 0.782983254107 }, { 0. , 0.782983254107, -0.782983254107 }, { 0.782983254107, 0. , -0.782983254107 }, { 0.782983254107, 0.782983254107, 0. } }; const double ptm_template_dhex[PTM_NUM_POINTS_DHEX][3] = { { 0. , 0. , 0. }, { -0.391491627053, -0.391491627053, -0.391491627053 }, { 0.391491627053, -0.391491627053, 0.391491627053 }, { -0.391491627053, 0.391491627053, 0.391491627053 }, { 0.391491627053, 0.391491627053, -0.391491627053 }, { -0.260994418036, -1.043977672142, -0.260994418036 }, { -1.043977672142, -0.260994418036, -0.260994418036 }, { -0.260994418036, -0.260994418036, -1.043977672142 }, { 0.782983254107, 0. , 0.782983254107 }, { 0.782983254107, -0.782983254107, 0. }, { 0. , -0.782983254107, 0.782983254107 }, { 0. , 0.782983254107, 0.782983254107 }, { -0.782983254107, 0.782983254107, 0. }, { -0.782983254107, 0. , 0.782983254107 }, { 0.782983254107, 0.782983254107, 0. }, { 0. , 0.782983254107, -0.782983254107 }, { 0.782983254107, 0. , -0.782983254107 } }; #endif
quang-ha/lammps
src/USER-PTM/ptm_constants.h
C
gpl-2.0
8,604
/* * ²Î¿¼ drivers\mtd\maps\physmap.c */ #include <linux/module.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/mtd/mtd.h> #include <linux/mtd/map.h> #include <linux/mtd/partitions.h> #include <asm/io.h> static struct map_info *s3c_nor_map; static struct mtd_info *s3c_nor_mtd; static struct mtd_partition s3c_nor_parts[] = { [0] = { .name = "bootloader_nor", .size = 0x00040000, .offset = 0, }, [1] = { .name = "root_nor", .offset = MTDPART_OFS_APPEND, .size = MTDPART_SIZ_FULL, } }; static int s3c_nor_init(void) { /* 1. ·ÖÅämap_info½á¹¹Ìå */ s3c_nor_map = kzalloc(sizeof(struct map_info), GFP_KERNEL);; /* 2. ÉèÖÃ: ÎïÀí»ùµØÖ·(phys), ´óС(size), λ¿í(bankwidth), ÐéÄâ»ùµØÖ·(virt) */ s3c_nor_map->name = "s3c_nor"; s3c_nor_map->phys = 0; s3c_nor_map->size = 0x1000000; /* >= NORµÄÕæÕý´óС */ s3c_nor_map->bankwidth = 2; s3c_nor_map->virt = ioremap(s3c_nor_map->phys, s3c_nor_map->size); simple_map_init(s3c_nor_map); /* 3. ʹÓÃ: µ÷ÓÃNOR FLASHЭÒé²ãÌṩµÄº¯ÊýÀ´Ê¶±ð */ printk("use cfi_probe\n"); s3c_nor_mtd = do_map_probe("cfi_probe", s3c_nor_map); if (!s3c_nor_mtd) { printk("use jedec_probe\n"); s3c_nor_mtd = do_map_probe("jedec_probe", s3c_nor_map); } if (!s3c_nor_mtd) { iounmap(s3c_nor_map->virt); kfree(s3c_nor_map); return -EIO; } /* 4. add_mtd_partitions */ add_mtd_partitions(s3c_nor_mtd, s3c_nor_parts, 2); return 0; } static void s3c_nor_exit(void) { del_mtd_partitions(s3c_nor_mtd); iounmap(s3c_nor_map->virt); kfree(s3c_nor_map); } module_init(s3c_nor_init); module_exit(s3c_nor_exit); MODULE_LICENSE("GPL");
cyj1988jyc/jz2440-android-kernel-2.6.27
drivers/a_drivers_and_test/15th_nor/2th/s3c_nor.c
C
gpl-2.0
1,848
{- Copyright (C) 2008-2014 John MacFarlane <jgm@berkeley.edu> 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 -} {- | Module : Text.Pandoc.Highlighting Copyright : Copyright (C) 2008-2014 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <jgm@berkeley.edu> Stability : alpha Portability : portable Exports functions for syntax highlighting. -} module Text.Pandoc.Highlighting ( languages , languagesByExtension , highlight , formatLaTeXInline , formatLaTeXBlock , styleToLaTeX , formatHtmlInline , formatHtmlBlock , styleToCss , pygments , espresso , zenburn , tango , kate , monochrome , haddock , Style , fromListingsLanguage , toListingsLanguage ) where import Text.Pandoc.Definition import Text.Pandoc.Shared (safeRead) import Text.Highlighting.Kate import Data.List (find) import Data.Maybe (fromMaybe) import Data.Char (toLower) import qualified Data.Map as M import Control.Applicative ((<|>)) lcLanguages :: [String] lcLanguages = map (map toLower) languages highlight :: (FormatOptions -> [SourceLine] -> a) -- ^ Formatter -> Attr -- ^ Attributes of the CodeBlock -> String -- ^ Raw contents of the CodeBlock -> Maybe a -- ^ Maybe the formatted result highlight formatter (_, classes, keyvals) rawCode = let firstNum = case safeRead (fromMaybe "1" $ lookup "startFrom" keyvals) of Just n -> n Nothing -> 1 fmtOpts = defaultFormatOpts{ startNumber = firstNum, numberLines = any (`elem` ["number","numberLines", "number-lines"]) classes } lcclasses = map (map toLower) classes in case find (`elem` lcLanguages) lcclasses of Nothing -> Nothing Just language -> Just $ formatter fmtOpts{ codeClasses = [language], containerClasses = classes } $ highlightAs language rawCode -- Functions for correlating latex listings package's language names -- with highlighting-kate language names: langToListingsMap :: M.Map String String langToListingsMap = M.fromList langsList listingsToLangMap :: M.Map String String listingsToLangMap = M.fromList $ map switch langsList where switch (a,b) = (b,a) langsList :: [(String, String)] langsList = [("ada","Ada") ,("java","Java") ,("prolog","Prolog") ,("python","Python") ,("gnuassembler","Assembler") ,("commonlisp","Lisp") ,("r","R") ,("awk","Awk") ,("bash","bash") ,("makefile","make") ,("c","C") ,("matlab","Matlab") ,("ruby","Ruby") ,("cpp","C++") ,("ocaml","Caml") ,("modula2","Modula-2") ,("sql","SQL") ,("eiffel","Eiffel") ,("tcl","tcl") ,("erlang","erlang") ,("verilog","Verilog") ,("fortran","Fortran") ,("vhdl","VHDL") ,("pascal","Pascal") ,("perl","Perl") ,("xml","XML") ,("haskell","Haskell") ,("php","PHP") ,("xslt","XSLT") ,("html","HTML") ] listingsLangs :: [String] listingsLangs = ["Ada","Java","Prolog","Algol","JVMIS","Promela", "Ant","ksh","Python","Assembler","Lisp","R","Awk", "Logo","Reduce","bash","make","Rexx","Basic", "Mathematica","RSL","C","Matlab","Ruby","C++", "Mercury","S","Caml","MetaPost","SAS","Clean", "Miranda","Scilab","Cobol","Mizar","sh","Comal", "ML","SHELXL","csh","Modula-2","Simula","Delphi", "MuPAD","SQL","Eiffel","NASTRAN","tcl","Elan", "Oberon-2","TeX","erlang","OCL","VBScript","Euphoria", "Octave","Verilog","Fortran","Oz","VHDL","GCL", "Pascal","VRML","Gnuplot","Perl","XML","Haskell", "PHP","XSLT","HTML","PL/I"] -- Determine listings language name from highlighting-kate language name. toListingsLanguage :: String -> Maybe String toListingsLanguage lang = (if lang `elem` listingsLangs then Just lang else Nothing) <|> M.lookup (map toLower lang) langToListingsMap -- Determine highlighting-kate language name from listings language name. fromListingsLanguage :: String -> Maybe String fromListingsLanguage lang = M.lookup lang listingsToLangMap
nickbart1980/pandoc
src/Text/Pandoc/Highlighting.hs
Haskell
gpl-2.0
5,985
/* * Fuel gauge driver for Maxim 17050 / 8966 / 8997 * Note that Maxim 8966 and 8997 are mfd and this is its subdevice. * * Copyright (C) 2012 LG Electronics * * 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 * * This driver is based on max17040_battery.c */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/i2c.h> #include <linux/mod_devicetable.h> #include <linux/power_supply.h> #include <linux/max17050_battery.h> #include <linux/mfd/pm8xxx/pm8921-charger.h> #include <linux/delay.h> /*#include <mach/board_lge.h>*/ #include <linux/module.h> /*#include "../../lge/include/lg_backup_items.h"*/ #include <mach/msm_smsm.h> #ifdef CONFIG_LGE_PM #include <linux/of.h> #include <linux/of_device.h> #include <linux/of_gpio.h> #include <linux/qpnp/qpnp-charger.h> #include <linux/i2c/smb349_charger.h> #include <mach/board_lge.h> #endif #define MAX17050_FULL_DEBUG /*#define MAX17050_LIGHT_DEBUG #define MAX17050_CORE_PRINT*/ #ifdef MAX17050_FULL_DEBUG #define F_bat(fmt, args...) printk(KERN_INFO fmt, ##args) #else #define F_bat(fmt, args...) do {} while (0) #endif #ifdef MAX17050_LIGHT_DEBUG #define L_bat(fmt, args...) printk(KERN_INFO fmt, ##args) #else #define L_bat(fmt, args...) do {} while (0) #endif #ifdef MAX17050_CORE_PRINT #define C_bat(fmt, args...) printk(KERN_INFO fmt, ##args) #else #define C_bat(fmt, args...) do {} while (0) #endif static struct i2c_client *max17050_i2c_client; u16 pre_soc = 100; u16 real_soc = 100; struct max17050_chip { struct i2c_client *client; /*struct power_supply battery;*/ struct max17050_platform_data *pdata; }; /* */ int lge_power_test_flag_max17050 = 1; /* */ /*static int max17050_access_control_of_flash(void); bool max17050_count_control(u8 select, u8 count_up); int max17050_save_bat_info_check(void);*/ static int max17050_write_reg(struct i2c_client *client, u8 reg, u16 value) { int ret = i2c_smbus_write_word_data(client, reg, value); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); return ret; } static int max17050_read_reg(struct i2c_client *client, u8 reg) { int ret = i2c_smbus_read_word_data(client, reg); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); return ret; } static int max17050_multi_write_data(struct i2c_client *client, int reg, const u8 *values, int length) { int ret; ret = i2c_smbus_write_i2c_block_data(client, reg, length, values); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); return ret; } static int max17050_multi_read_data(struct i2c_client *client, int reg, u8 *values, int length) { int ret; ret = i2c_smbus_read_i2c_block_data(client, reg, length, values); if (ret < 0) dev_err(&client->dev, "%s: err %d\n", __func__, ret); return ret; } int max17050_get_mvolts(void) { u16 read_reg; int vbatt_mv; /*if (max17050_nobattery) return 3950;*/ if (max17050_i2c_client == NULL) { pr_info("[MAX17050] %s: i2c NULL vbatt = 800 mV\n", __func__); return 800; } read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_V_CELL); if (read_reg < 0) return 800; vbatt_mv = (read_reg >> 3); vbatt_mv = (vbatt_mv * 625) / 1000; #ifdef MAX17050_DEBUG pr_debug("%s: vbatt = %d mV\n", __func__, vbatt_mv); #endif return vbatt_mv; } int max17050_suspend_get_mvolts(void) { u16 read_reg; int vbatt_mv; /*if (max17050_nobattery) return 3950;*/ if (max17050_i2c_client == NULL) { pr_info("[MAX17050] %s: i2c NULL vbatt = 3950 mV\n", __func__); return 800; } read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_V_CELL); if (read_reg < 0) return 800; vbatt_mv = (read_reg >> 3); vbatt_mv = (vbatt_mv * 625) / 1000; pr_debug("%s: vbatt = %d mV\n", __func__, vbatt_mv); return vbatt_mv; } int max17050_get_capacity_percent(void) { int battery_soc = 0; int read_reg = 0; u8 upper_reg; u8 lower_reg; if (max17050_i2c_client == NULL) { return 80; } else { read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_SOC_REP); if (read_reg < 0) { pr_err("[MAX17050] %s: i2c Read Fail battery SOC = %d\n", __func__, pre_soc); return pre_soc; } upper_reg = (read_reg & 0xFF00)>>8 ; lower_reg = (read_reg & 0xFF); #ifdef MAX17050_DEBUG F_bat("%s: read_reg = %X upper_reg = %X lower_reg = %X\n", __func__, read_reg, upper_reg, lower_reg); #endif /* SOC scaling for stable max SOC and changed Cut-off */ /*Adj SOC = (FG SOC-Emply)/(Full-Empty)*100*/ /* cut off vol 3.48V : (soc - 1.132%)*100/(94.28% - 1.132%) */ /* full capacity soc 106.5% , real battery SoC 100.7%*/ battery_soc = ((upper_reg * 256)+lower_reg)*10/256; #ifdef MAX17050_DEBUG F_bat("%s: battery_soc = %d\n", __func__, battery_soc); #endif battery_soc = (battery_soc * 100) * 100; battery_soc = (battery_soc / 9440) - 1; /* 100 -> 105.8% scailing */ if (((battery_soc/10) < 1) && ((battery_soc%10) >= 5)) { battery_soc = 10; } battery_soc /= 10; #ifdef MAX17050_DEBUG pr_debug("%s: battery_soc = %d (upper_reg = %d lower_reg = %d)\n", __func__, battery_soc, upper_reg, lower_reg); #endif real_soc = battery_soc; if (battery_soc >= 100) battery_soc = 100; if (battery_soc < 0) battery_soc = 0; } pre_soc = battery_soc; return battery_soc; } int max17050_get_current(void) { u16 read_reg; int ibatt_ma; int avg_ibatt_ma; u16 sign_bit; if (max17050_i2c_client == NULL) { pr_info("[MAX17050] %s: i2c NULL", __func__); return 999; } read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_CURRENT); if (read_reg < 0) return 999; /*Error Value return.*/ sign_bit = (read_reg & 0x8000)>>15; if (sign_bit == 1) ibatt_ma = (15625 * (read_reg - 65536))/100000; else ibatt_ma = (15625 * read_reg) / 100000; read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_AVERAGE_CURRENT); if (read_reg < 0) return 999;/*Error Value return.*/ sign_bit = (read_reg & 0x8000)>>15; if (sign_bit == 1) avg_ibatt_ma = (15625 * (read_reg - 65536)) / 100000; else avg_ibatt_ma = (15625 * read_reg) / 100000; #ifdef MAX17050_DEBUG pr_debug("%s: I_batt = %d mA avg_I_batt = %d mA\n", __func__, ibatt_ma, avg_ibatt_ma); #endif return avg_ibatt_ma; } bool max17050_write_temp(int battery_temp) { u16 ret; u16 write_temp; battery_temp = battery_temp/10; if (battery_temp < 0) write_temp = (battery_temp + 256)<<8; else write_temp = (battery_temp)<<8; pr_debug("max17050_write_temp - battery_temp (%d)\n", battery_temp); ret = max17050_write_reg(max17050_i2c_client, MAX17050_TEMPERATURE, write_temp); if (ret < 0) { pr_debug("max17050_write_temp error.\n"); return 1; } return 0; } int max17050_read_battery_age(void) { u16 read_reg; int battery_age; if (max17050_i2c_client == NULL) { pr_debug("MAX17050] %s: i2c NULL battery age: 800\n", __func__); return 800; } read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_AGE); if (read_reg < 0) return 999; /*Error Value return.*/ battery_age = (read_reg >> 8); #ifdef MAX17050_DEBUG F_bat("%s: battery_age = %d\n", __func__, battery_age); #endif return battery_age; } bool max17050_battery_full_info_print(void) { u16 read_reg; int battery_age; int battery_remain_capacity; int battery_time_to_empty_sec; int battery_soc; int battery_voltage; int battery_temp; int battery_current; int battery_full_cap; battery_age = max17050_read_battery_age(); read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_REM_CAP_REP); battery_remain_capacity = (5 * read_reg)/10; read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_FULL_CAP); battery_full_cap = (5 * read_reg)/10; read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_TTE); battery_time_to_empty_sec = (5625 * read_reg)/1000; battery_soc = max17050_get_capacity_percent(); battery_voltage = max17050_get_mvolts(); read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_TEMPERATURE); battery_temp = (read_reg >> 8); if (battery_temp > 127) battery_temp = battery_temp - 256; else battery_temp = battery_temp; battery_current = max17050_get_current(); pr_debug("* -- max17050 battery full info print ---------- *\n"); pr_debug("battery age = %d %% remain capacity = %d mAh\n", battery_age, battery_remain_capacity); pr_debug("battery current = %d mA Time to Empty = %d min\n", battery_current, battery_time_to_empty_sec/60); pr_debug("battery SOC = %d %% Voltage = %d mV\n", battery_soc, battery_voltage); pr_debug("battery TEMP = %d C full capacity = %d mAh\n", battery_temp, battery_full_cap); pr_debug("* ---------------------------------------------- *\n"); return 0; } bool max17050_i2c_write_and_verify(u8 addr, u16 value) { u16 read_reg; max17050_write_reg(max17050_i2c_client, addr, value); read_reg = max17050_read_reg(max17050_i2c_client, addr); if (read_reg == value) { F_bat("[MAX17050] %s() Addr = 0x%X,", __func__, addr); F_bat(" Value = 0x%X Success\n", value); return 1; } else { pr_debug("[MAX17050] %s() Addr = 0x%X,", __func__, addr); pr_debug(" Value = 0x%X Fail to write.", value); pr_debug(" Write once more.\n"); max17050_write_reg(max17050_i2c_client, addr, value); return 0; } return 1; } static int max17050_new_custom_model_write(void) { /*u16 ret;*/ u16 read_reg; /*u16 write_reg;*/ u16 vfsoc; u16 full_cap_0; u16 rem_cap; u16 rep_cap; u16 dQ_acc; #if defined(CONFIG_MACH_MSM8974_G2_DCM) u16 capacity = 0x17B6; #else u16 capacity = 0x1802; #endif u16 i; #if defined(CONFIG_MACH_MSM8974_G2_DCM) u8 custom_model_1[32] = { 0xC0, 0x9C, 0xC0, 0xA5, 0xF0, 0xAD, 0x30, 0xB6, 0x90, 0xB9, 0x30, 0xBC, 0x30, 0xBD, 0xB0, 0xBD, 0xC0, 0xBE, 0xF0, 0xBF, 0x30, 0xC2, 0x70, 0xC7, 0x40, 0xCA, 0x00, 0xCD, 0x60, 0xD2, 0x00, 0xD8, }; u8 custom_model_2[32] = { 0x90, 0x00, 0xA0, 0x01, 0xA0, 0x01, 0x00, 0x0D, 0x00, 0x0E, 0x10, 0x19, 0x20, 0x32, 0x70, 0x11, 0xC0, 0x10, 0xD0, 0x0C, 0xF0, 0x08, 0xA0, 0x08, 0xF0, 0x08, 0xF0, 0x06, 0xF0, 0x06, 0xF0, 0x06, }; #else u8 custom_model_1[32] = { 0x20, 0xAC, 0x40, 0xAD, 0xF0, 0xB1, 0xE0, 0xB8, 0x60, 0xBA, 0x90, 0xBB, 0x20, 0xBD, 0x00, 0xBE, 0xD0, 0xBE, 0xB0, 0xBF, 0x60, 0xC1, 0xD0, 0xC5, 0xE0, 0xCB, 0xC0, 0xD1, 0xC0, 0xD4, 0x20, 0xD7, }; u8 custom_model_2[32] = { 0xB0, 0x00, 0x30, 0x06, 0x00, 0x04, 0x70, 0x18, 0x30, 0x0F, 0xB0, 0x17, 0x00, 0x18, 0x10, 0x22, 0xA0, 0x0A, 0x90, 0x0D, 0xC0, 0x09, 0xF0, 0x07, 0xF0, 0x06, 0xA0, 0x09, 0xE0, 0x04, 0xE0, 0x04, }; #endif u8 custom_model_3[32] = { 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, }; u8 read_custom_model_1[32]; u8 read_custom_model_2[32]; u8 read_custom_model_3[32]; F_bat("[MAX17050] %s() Start\n", __func__); /*0. Check for POR or Battery Insertion*/ read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_STATUS); F_bat("[MAX17050] %s() MAX17050_STATUS = 0x%X\n", __func__, read_reg); if (read_reg == 0) { pr_debug("[MAX17050] IC Non-Power-On-Reset state."); pr_debug(" Go to max17050_save_bat_info_to_flash.\n"); return 2; /*Go to save the custom model.*/ } else pr_debug("[MAX17050] IC Power On Reset state. Start Custom Model Write.\n"); /*Skip if the cable is Factory Mode.*/ /* if ((usb_cable_info == 6) || (usb_cable_info == 7) || (usb_cable_info == 11)) { pr_debug("[MAX17050] IC Power-On-Reset state. But Skip Custom model in Factory Mode.\n"); return 2; } */ /*1. Delay 500mS*/ msleep(500); /*1.1 Version Check*/ read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_VERSION); F_bat("[MAX17050] %s() MAX17050_VERSION = 0x%X\n", __func__, read_reg); if (read_reg != 0xAC) { pr_debug("[MAX17050] Version Check Error."); pr_debug(" Version Check = 0x%x\n", read_reg); return 1; /*Version Check Error*/ } /*2. Initialize Configuration*/ max17050_write_reg(max17050_i2c_client, MAX17050_RELAX_CFG, 0x506B); #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* External temp and enable alert function */ max17050_write_reg(max17050_i2c_client, MAX17050_CONFIG, 0x2104); #else /* External temp */ max17050_write_reg(max17050_i2c_client, MAX17050_CONFIG, 0x2100); #endif max17050_write_reg(max17050_i2c_client, MAX17050_FILTER_CFG, 0x87A4); max17050_write_reg(max17050_i2c_client, MAX17050_LEARN_CFG, 0x2607); max17050_write_reg(max17050_i2c_client, MAX17050_MISC_CFG, 0x0870); max17050_write_reg(max17050_i2c_client, MAX17050_FULL_SOC_THR, 0x5F00); /*4. Unlock Model Access*/ max17050_write_reg(max17050_i2c_client, 0x62, 0x0059); max17050_write_reg(max17050_i2c_client, 0x63, 0x00C4); /*5. Write/Read/Verify the Custom Model*/ max17050_multi_write_data(max17050_i2c_client, 0x80, &custom_model_1[0], 32); max17050_multi_write_data(max17050_i2c_client, 0x90, &custom_model_2[0], 32); max17050_multi_write_data(max17050_i2c_client, 0xA0, &custom_model_3[0], 32); /*For test only. Read back written-custom model data.*/ max17050_multi_read_data(max17050_i2c_client, 0x80, &read_custom_model_1[0], 32); max17050_multi_read_data(max17050_i2c_client, 0x90, &read_custom_model_2[0], 32); max17050_multi_read_data(max17050_i2c_client, 0xA0, &read_custom_model_3[0], 32); /*Compare with original one.*/ for (i = 0 ; i < 32 ; i++) { if (read_custom_model_1[i] != custom_model_1[i]) { pr_debug("[MAX17050] Custom Model"); pr_debug(" 1[%d] Write Error\n", i); } } for (i = 0 ; i < 32 ; i++) { if (read_custom_model_2[i] != custom_model_2[i]) { pr_debug("[MAX17050] Custom Model"); pr_debug(" 2[%d] Write Error\n", i); } } for (i = 0 ; i < 32 ; i++) { if (read_custom_model_3[i] != custom_model_3[i]) { pr_debug("[MAX17050] Custom Model"); pr_debug(" 3[%d] Write Error\n", i); } } /*For Test only end.*/ /*8. Lock Model Access*/ max17050_write_reg(max17050_i2c_client, 0x62, 0x0000); max17050_write_reg(max17050_i2c_client, 0x63, 0x0000); /*9. Verify the Model Access is locked.*/ /*Skip.*/ /*10. Write Custom Parameters*/ #if defined(CONFIG_MACH_MSM8974_G2_DCM) max17050_i2c_write_and_verify(MAX17050_RCOMP_0, 0x0048); max17050_i2c_write_and_verify(MAX17050_TEMP_CO, 0x1D2A); max17050_i2c_write_and_verify(MAX17050_TEMP_NOM, 0x1400); max17050_write_reg(max17050_i2c_client, MAX17050_T_GAIN, 0xE932); max17050_write_reg(max17050_i2c_client, MAX17050_T_OFF, 0x2381); /*Termination Current 400mA*/ max17050_write_reg(max17050_i2c_client, MAX17050_I_CHG_TERM, 0x0280); max17050_i2c_write_and_verify(MAX17050_V_EMPTY, 0xA2DA); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_00, 0x2602); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_10, 0x1A82); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_20, 0x0A04); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_30, 0x0804); #else max17050_i2c_write_and_verify(MAX17050_RCOMP_0, 0x0066); max17050_i2c_write_and_verify(MAX17050_TEMP_CO, 0x2436); max17050_i2c_write_and_verify(MAX17050_TEMP_NOM, 0x1400); max17050_write_reg(max17050_i2c_client, MAX17050_T_GAIN, 0xE932); max17050_write_reg(max17050_i2c_client, MAX17050_T_OFF, 0x2381); /*Termination Current 150mA*/ max17050_write_reg(max17050_i2c_client, MAX17050_I_CHG_TERM, 0x03C0); max17050_i2c_write_and_verify(MAX17050_V_EMPTY, 0xACDA); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_00, 0x8400); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_10, 0x5A84); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_20, 0x270A); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_30, 0x198A); #endif /*11. Update Full Capacity Parameters*/ max17050_i2c_write_and_verify(MAX17050_FULL_CAP, capacity); max17050_write_reg(max17050_i2c_client, MAX17050_DESIGN_CAP, capacity); max17050_i2c_write_and_verify(MAX17050_FULL_CAP_NOM, capacity); /*13. Delay at least 350mS*/ msleep(360); /*14. Write VFSOC value to VFSOC 0*/ vfsoc = max17050_read_reg(max17050_i2c_client, MAX17050_SOC_VF); F_bat("[MAX17050] %s() vfsoc = 0x%X\n", __func__, vfsoc); max17050_write_reg(max17050_i2c_client, 0x60, 0x0080); max17050_i2c_write_and_verify(0x48, vfsoc); max17050_write_reg(max17050_i2c_client, 0x60, 0x0000); /*15. Write temperature (default 20 deg C)*/ max17050_i2c_write_and_verify(MAX17050_TEMPERATURE, 0x1400); /*16. Load New Capacity Parameters*/ full_cap_0 = max17050_read_reg(max17050_i2c_client, 0x35); F_bat("[MAX17050] %s() full_cap_0 = %d = 0x%X\n", __func__, full_cap_0, full_cap_0); rem_cap = (vfsoc * full_cap_0) / 25600; F_bat("[MAX17050] %s() rem_cap = %d = 0x%X\n", __func__, rem_cap, rem_cap); max17050_i2c_write_and_verify(MAX17050_REM_CAP_MIX, rem_cap); rep_cap = rem_cap; max17050_i2c_write_and_verify(MAX17050_REM_CAP_REP, rep_cap); dQ_acc = (capacity / 4); max17050_i2c_write_and_verify(MAX17050_D_QACC, dQ_acc); max17050_i2c_write_and_verify(MAX17050_D_PACC, 0x3200); max17050_i2c_write_and_verify(MAX17050_FULL_CAP, capacity); max17050_write_reg(max17050_i2c_client, MAX17050_DESIGN_CAP, capacity); max17050_i2c_write_and_verify(MAX17050_FULL_CAP_NOM, capacity); max17050_write_reg(max17050_i2c_client, MAX17050_SOC_REP, vfsoc); /*17. Initialization Complete*/ read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_STATUS); max17050_i2c_write_and_verify(MAX17050_STATUS, (read_reg & 0xFFFD)); /*End of the Custom Model step 1.*/ pr_debug("[MAX17050] End of the max17050_new_custom_model_write.\n"); F_bat("[MAX17050] %s() End\n", __func__); return 0; /*Success to write.*/ } static int max17050_force_custom_model_write(void) { /*u16 ret;*/ u16 read_reg; /*u16 write_reg;*/ u16 vfsoc; u16 full_cap_0; u16 rem_cap; u16 rep_cap; u16 dQ_acc; u16 capacity = 0x1770; u16 i; u8 custom_model_1[32] = { 0x30, 0x7F, 0x10, 0xB6, 0xD0, 0xB7, 0xA0, 0xB9, 0xC0, 0xBB, 0xA0, 0xBC, 0xE0, 0xBC, 0x30, 0xBD, 0x90, 0xBD, 0xD0, 0xBE, 0xE0, 0xC1, 0xF0, 0xC3, 0x10, 0xC6, 0x30, 0xC9, 0x60, 0xCC, 0x90, 0xCF, }; u8 custom_model_2[32] = { 0xE0, 0x00, 0x70, 0x0E, 0xF0, 0x0D, 0x00, 0x0F, 0x20, 0x15, 0xF0, 0x46, 0xC0, 0x38, 0x70, 0x19, 0x00, 0x18, 0x60, 0x0C, 0x20, 0x0D, 0xC0, 0x0C, 0xE0, 0x07, 0xF0, 0x08, 0xF0, 0x08, 0xF0, 0x08, }; u8 custom_model_3[32] = { 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, }; u8 read_custom_model_1[32]; u8 read_custom_model_2[32]; u8 read_custom_model_3[32]; F_bat("[MAX17050] %s() Start\n", __func__); /*0. No Check for POR or Battery Insertion*/ pr_debug("[MAX17050]Start Force Custom Model Write.\n"); /*Skip if the cable is Factory Mode.*/ /* if ((usb_cable_info == 6) || (usb_cable_info == 7) || (usb_cable_info == 11)) { pr_debug("[MAX17050] Force Custom Write. But Skip Custom model in Factory Mode.\n"); return 2; }*/ /*1. Delay 500mS*/ msleep(500); /*1.1 Version Check*/ read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_VERSION); F_bat("[MAX17050] %s() MAX17050_VERSION = 0x%X\n", __func__, read_reg); /*if (read_reg != 0xAC) { pr_debug("[MAX17050] Version Check Error.\n"); return 1; //Version Check Error }*/ /*2. Initialize Configuration*/ max17050_write_reg(max17050_i2c_client, MAX17050_RELAX_CFG, 0x506B); max17050_write_reg(max17050_i2c_client, MAX17050_CONFIG, 0x2100); max17050_write_reg(max17050_i2c_client, MAX17050_FILTER_CFG, 0x87A4); max17050_write_reg(max17050_i2c_client, MAX17050_LEARN_CFG, 0x2607); max17050_write_reg(max17050_i2c_client, MAX17050_MISC_CFG, 0x0870); max17050_write_reg(max17050_i2c_client, MAX17050_FULL_SOC_THR, 0x5F00); /*4. Unlock Model Access*/ max17050_write_reg(max17050_i2c_client, 0x62, 0x0059); max17050_write_reg(max17050_i2c_client, 0x63, 0x00C4); /*5. Write/Read/Verify the Custom Model*/ max17050_multi_write_data(max17050_i2c_client, 0x80, &custom_model_1[0], 32); max17050_multi_write_data(max17050_i2c_client, 0x90, &custom_model_2[0], 32); max17050_multi_write_data(max17050_i2c_client, 0xA0, &custom_model_3[0], 32); /*For test only. Read back written-custom model data.*/ max17050_multi_read_data(max17050_i2c_client, 0x80, &read_custom_model_1[0], 32); max17050_multi_read_data(max17050_i2c_client, 0x90, &read_custom_model_2[0], 32); max17050_multi_read_data(max17050_i2c_client, 0xA0, &read_custom_model_3[0], 32); /*Compare with original one.*/ for (i = 0 ; i < 32 ; i++) { if (read_custom_model_1[i] != custom_model_1[i]) { pr_debug("[MAX17050] Custom Model"); pr_debug(" 1[%d] Write Error\n", i); } } for (i = 0 ; i < 32 ; i++) { if (read_custom_model_2[i] != custom_model_2[i]) { pr_debug("[MAX17050] Custom Model"); pr_debug(" 2[%d] Write Error\n", i); } } for (i = 0 ; i < 32 ; i++) { if (read_custom_model_3[i] != custom_model_3[i]) { pr_debug("[MAX17050] Custom Model"); pr_debug(" 3[%d] Write Error\n", i); } } /*For Test only end.*/ /*8. Lock Model Access*/ max17050_write_reg(max17050_i2c_client, 0x62, 0x0000); max17050_write_reg(max17050_i2c_client, 0x63, 0x0000); /*9. Verify the Model Access is locked.*/ /*Skip.*/ /*10. Write Custom Parameters*/ max17050_i2c_write_and_verify(MAX17050_RCOMP_0, 0x0058); max17050_i2c_write_and_verify(MAX17050_TEMP_CO, 0x2230); max17050_i2c_write_and_verify(MAX17050_TEMP_NOM, 0x1400); max17050_write_reg(max17050_i2c_client, MAX17050_T_GAIN, 0xE932); max17050_write_reg(max17050_i2c_client, MAX17050_T_OFF, 0x2381); /*Termination Current 150mA*/ max17050_write_reg(max17050_i2c_client, MAX17050_I_CHG_TERM, 0x03C0); max17050_i2c_write_and_verify(MAX17050_V_EMPTY, 0xACDA); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_00, 0x9680); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_10, 0x3800); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_20, 0x3805); max17050_i2c_write_and_verify(MAX17050_Q_RESIDUAL_30, 0x2513); /*11. Update Full Capacity Parameters*/ max17050_i2c_write_and_verify(MAX17050_FULL_CAP, capacity); max17050_write_reg(max17050_i2c_client, MAX17050_DESIGN_CAP, capacity); max17050_i2c_write_and_verify(MAX17050_FULL_CAP_NOM, capacity); /*13. Delay at least 350mS*/ msleep(360); /*14. Write VFSOC value to VFSOC 0*/ vfsoc = max17050_read_reg(max17050_i2c_client, MAX17050_SOC_VF); F_bat("[MAX17050] %s() vfsoc = 0x%X\n", __func__, vfsoc); max17050_write_reg(max17050_i2c_client, 0x60, 0x0080); max17050_i2c_write_and_verify(0x48, vfsoc); max17050_write_reg(max17050_i2c_client, 0x60, 0x0000); /*15. Write temperature (default 20 deg C)*/ max17050_i2c_write_and_verify(MAX17050_TEMPERATURE, 0x1400); /*16. Load New Capacity Parameters*/ full_cap_0 = max17050_read_reg(max17050_i2c_client, 0x35); F_bat("[MAX17050] %s() full_cap_0 = %d = 0x%X\n", __func__, full_cap_0, full_cap_0); rem_cap = (vfsoc * full_cap_0) / 25600; F_bat("[MAX17050] %s() rem_cap = %d = 0x%X\n", __func__, rem_cap, rem_cap); max17050_i2c_write_and_verify(MAX17050_REM_CAP_MIX, rem_cap); rep_cap = rem_cap; max17050_i2c_write_and_verify(MAX17050_REM_CAP_REP, rep_cap); dQ_acc = (capacity / 4); max17050_i2c_write_and_verify(MAX17050_D_QACC, dQ_acc); max17050_i2c_write_and_verify(MAX17050_D_PACC, 0x3200); max17050_i2c_write_and_verify(MAX17050_FULL_CAP, capacity); max17050_write_reg(max17050_i2c_client, MAX17050_DESIGN_CAP, capacity); max17050_i2c_write_and_verify(MAX17050_FULL_CAP_NOM, capacity); max17050_write_reg(max17050_i2c_client, MAX17050_SOC_REP, vfsoc); /*17. Initialization Complete*/ read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_STATUS); max17050_i2c_write_and_verify(MAX17050_STATUS, (read_reg & 0xFFFD)); /*End of the Custom Model step 1.*/ pr_debug("[MAX17050] End of the max17050_new_custom_model_write.\n"); F_bat("[MAX17050] %s() End\n", __func__); return 0; /*Success to write.*/ } int max17050_battery_exchange_program(void) { int ret = 0; /* */ { /*Call max17050_new_custom_model_write*/ ret = max17050_force_custom_model_write(); if (ret == 2) pr_debug("NON-POWER_ON reset. Proceed Booting.\n"); /*Error occurred. Write once more.*/ else if (ret == 1) max17050_force_custom_model_write(); /*New Custom model write End. Go to max17050_restore_bat_info_from_flash.*/ else if (ret == 0) pr_debug("POWER_ON reset. Custom Model Success.\n"); } return 0; } bool max17050_quick_start(void) { u16 read_reg; u16 write_reg; u16 check_reg; #if defined(CONFIG_MACH_MSM8974_G2_DCM) u16 capacity = 0x17B6; #else u16 capacity = 0x1802; #endif /*1. Set the QuickStart and Verify bits*/ read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_MISC_CFG); write_reg = read_reg | 0x1400; max17050_write_reg(max17050_i2c_client, MAX17050_MISC_CFG, write_reg); /*2. Verify no memory leaks during Quickstart writing*/ read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_MISC_CFG); check_reg = read_reg & 0x1000; if (check_reg != 0x1000) { pr_debug(" [MAX17050] quick_start error !!!!\n"); return 1; } /*3. Clean the Verify bit*/ read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_MISC_CFG); write_reg = read_reg & 0xefff; max17050_write_reg(max17050_i2c_client, MAX17050_MISC_CFG, write_reg); /*4. Verify no memory leaks during Verify bit clearing*/ read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_MISC_CFG); check_reg = read_reg & 0x1000; if (check_reg != 0x0000) { pr_debug(" [MAX17050] quick_start error !!!!\n"); return 1; } /*5. Delay 500ms*/ msleep(500); /*6. Writing and Verify FullCAP Register Value*/ max17050_i2c_write_and_verify(MAX17050_FULL_CAP, capacity); /*7. Delay 500ms*/ msleep(500); return 0; } int max17050_get_soc_for_charging_complete_at_cmd() { int guage_level = 0; /* pm8921_charger_enable(0); pm8921_disable_source_current(1);*/ #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* Reduce charger source */ external_smb349_enable_charging(0); #endif pr_debug(" [AT_CMD][at_fuel_guage_level_show] max17050_quick_start\n"); max17050_quick_start(); guage_level = max17050_get_capacity_percent(); if (guage_level != 0) { if (guage_level >= 80) guage_level = (real_soc * 962) / 1000; else guage_level = (guage_level * 100) / 100; } if (guage_level > 100) guage_level = 100; else if (guage_level < 0) guage_level = 0; /* pm8921_disable_source_current(0); pm8921_charger_enable(1);*/ #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* Restore charger source */ external_smb349_enable_charging(1); #endif pr_debug(" [AT_CMD][at_fuel_guage_soc_for_charging_complete]"); pr_debug(" BATT guage_level = %d ,", guage_level); pr_debug(" real_soc = %d\n", real_soc); return guage_level; } EXPORT_SYMBOL(max17050_get_soc_for_charging_complete_at_cmd); int max17050_get_battery_mvolts(void) { return max17050_get_mvolts(); } EXPORT_SYMBOL(max17050_get_battery_mvolts); u8 at_cmd_buf[2] = {0xff, 0xff}; int max17050_get_battery_capacity_percent(void) { if (at_cmd_buf[0] == 1) return at_cmd_buf[1]; return max17050_get_capacity_percent(); } EXPORT_SYMBOL(max17050_get_battery_capacity_percent); int max17050_get_battery_current(void) { return max17050_get_current(); } EXPORT_SYMBOL(max17050_get_battery_current); bool max17050_write_battery_temp(int battery_temp) { return max17050_write_temp(battery_temp); } EXPORT_SYMBOL(max17050_write_battery_temp); int max17050_get_battery_age(void) { return max17050_read_battery_age(); } EXPORT_SYMBOL(max17050_get_battery_age); /* For max17050 AT cmd */ bool max17050_set_battery_atcmd(int flag, int value) { bool ret; u16 soc_read; u16 vbat_mv; if (flag == 0) { /*Call max17050 Quick Start function.*/ ret = max17050_quick_start(); if (ret == 0) { /*Read and Verify Outputs*/ soc_read = max17050_get_capacity_percent(); vbat_mv = max17050_suspend_get_mvolts(); pr_debug("[MAX17050] max17050_quick_start end"); pr_debug(" Reset_SOC = %d %% vbat = %d mV\n", soc_read, vbat_mv); if ((vbat_mv >= 4100) && (soc_read < 91)) { at_cmd_buf[0] = 1; at_cmd_buf[1] = 100; pr_debug("[MAX17050] max17050_quick_start error correction works.\n"); return 1; } else at_cmd_buf[0] = 0; } else { at_cmd_buf[0] = 1; at_cmd_buf[1] = 100; pr_debug("[MAX17050] max17050_quick_start error correction works.\n"); return 1; } } else if (flag == 1) { at_cmd_buf[0] = 0; } return 0; } static ssize_t at_fuel_guage_reset_show (struct device *dev, struct device_attribute *attr, char *buf) { int r = 0; bool ret = 0; #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* Reduce charger source */ external_smb349_enable_charging(0); #endif ret = max17050_set_battery_atcmd(0, 100); /* Reset the fuel guage IC*/ if (ret == 1) pr_debug("at_fuel_guage_reset_show error.\n"); r = snprintf(buf, PAGE_SIZE, "%d\n", true); /*at_cmd_force_control = TRUE;*/ msleep(100); #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* Restore charger source */ external_smb349_enable_charging(1); #endif return r; } static ssize_t at_fuel_guage_level_show (struct device *dev, struct device_attribute *attr, char *buf) { int r = 0; int guage_level = 0; /* */ if (lge_power_test_flag_max17050 == 1) { /*pm8921_charger_enable(0); pm8921_disable_source_current(1);*/ pr_debug(" [AT_CMD][at_fuel_guage_level_show]"); pr_debug(" max17050_quick_start\n"); #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* Reduce charger source */ external_smb349_enable_charging(0); #endif max17050_quick_start(); guage_level = max17050_get_capacity_percent(); if (guage_level != 0) { if (guage_level >= 80) guage_level = (real_soc * 962) / 1000; else guage_level = (guage_level * 100) / 100; } if (guage_level > 100) guage_level = 100; else if (guage_level < 0) guage_level = 0; pr_debug(" [AT_CMD][at_fuel_guage_level_show]"); pr_debug(" BATT guage_level = %d ,", guage_level); pr_debug(" real_soc = %d\n", real_soc); /*pm8921_disable_source_current(0); pm8921_charger_enable(1);*/ #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* Restore charger source */ external_smb349_enable_charging(1); #endif return snprintf(buf, PAGE_SIZE, "%d\n", guage_level); } /* */ guage_level = max17050_get_capacity_percent(); pr_debug(" [AT_CMD][at_fuel_guage_level_show]"); pr_debug(" not quick start BATT guage_level = %d\n", guage_level); r = snprintf(buf, PAGE_SIZE, "%d\n", guage_level); return r; } static ssize_t at_batt_level_show (struct device *dev, struct device_attribute *attr, char *buf) { int r = 0; int battery_level = 0; /* */ if (lge_power_test_flag_max17050 == 1) { /*pm8921_charger_enable(0); pm8921_disable_source_current(1);*/ #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* Reduce charger source */ external_smb349_enable_charging(0); #endif pr_debug(" [AT_CMD][at_batt_level_show] max17050_quick_start\n"); max17050_quick_start(); battery_level = max17050_get_battery_mvolts(); /*pm8921_disable_source_current(0); pm8921_charger_enable(1);*/ #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* Restore charger source */ external_smb349_enable_charging(1); #endif pr_debug(" [AT_CMD][at_batt_level_show] BATT LVL = %d\n", battery_level); return snprintf(buf, PAGE_SIZE, "%d\n", battery_level); } /* */ battery_level = max17050_get_battery_mvolts(); pr_debug(" [AT_CMD][at_batt_level_show]"); pr_debug(" not quick start BATT LVL = %d\n", battery_level); r = snprintf(buf, PAGE_SIZE, "%d\n", battery_level); return r; } DEVICE_ATTR(at_fuelrst, 0644, at_fuel_guage_reset_show, NULL); DEVICE_ATTR(at_fuelval, 0644, at_fuel_guage_level_show, NULL); DEVICE_ATTR(at_batl, 0644, at_batt_level_show, NULL); static int max17050_quickstart_check_chglogo_boot (u16 v_cell, u16 v_focv) { u16 result; int ret = 0; result = v_focv - v_cell; pr_info("[MAX17050]chglogoboot-result(%d),v_focv(%d),vcell(%d)\n", result, v_focv, v_cell); if(result >= 25 && result <= 100) { pr_info("[MAX17050] - skip quickstart\n"); } else { pr_info("[MAX17050] - quick_start !!\n"); ret = 1; } return ret; } static int max17050_quickstart_check_normalboot (u16 v_cell, u16 v_focv) { u16 result; int ret = 0; #if defined(CONFIG_MACH_MSM8974_G2_DCM) u16 result2; bool power_ok; result2 = v_cell - v_focv; #endif result = v_focv - v_cell; pr_debug("[MAX17050]normalboot -result (%d),", result); pr_debug(" v_focv (%d), vcell(%d)\n", v_focv, v_cell); #if defined(CONFIG_MACH_MSM8974_G2_DCM) power_ok = external_smb349_is_charger_present(); #endif #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* For A1 DCM with BT-L7(3000mAh) battery*/ if (!power_ok) { if (v_cell >= 3800) { if (result <= 100 || result2 <= 100) { F_bat("[MAX17050] skip quickstart more than 3.8V = %d\n", result); F_bat("[MAX17050] skip quickstart more than 3.8V = %d\n", result2); } else { ret = 1; F_bat("[MAX17050] quickstart more than 3.8V = %d\n", result); F_bat("[MAX17050] quickstart more than 3.8V = %d\n", result2); } } else { if (result <= 120 || result2 <= 120) { F_bat("[MAX17050] skip quickstart under 3.8V = %d\n", result); F_bat("[MAX17050] skip quickstart under 3.8V = %d\n", result2); } else { ret = 1; F_bat("[MAX17050] quickstart under 3.8V = %d\n", result); F_bat("[MAX17050] quickstart under 3.8V = %d\n", result2); } } } else if (power_ok) { if (result <= 170 || result2 <= 170) { F_bat("[MAX17050] skip quickstart in case of chg result2 = %d\n", result); F_bat("[MAX17050] skip quickstart in case of chg result2 = %d\n", result2); } else { F_bat("[MAX17050] quickstart in case of chg result2 = %d\n", result); F_bat("[MAX17050] quickstart in case of chg result2 = %d\n", result2); ret = 1; } } #else /* Brought from Vu, GV model. */ if (v_cell >= 3800) { if (result >= 67 && result <= 100) { pr_debug("[MAX17047] - skip quickstart\n"); } else { pr_debug("[MAX17047] - quick_start !!\n"); ret = 1; } } else { if (result >= 72 && result <= 100) { pr_debug("[MAX17047] - skip quickstart\n"); } else { pr_debug("[MAX17047] - quick_start !!\n"); ret = 1; } } #endif return ret; } void max17050_initial_quickstart_check(void) { u16 read_reg; /*u16 write_reg;*/ u16 vfocv; u16 vcell; unsigned int *power_on_status = 0; unsigned int smem_size; read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_V_CELL); vcell = (read_reg >> 3); vcell = (vcell * 625) / 1000; read_reg = max17050_read_reg(max17050_i2c_client, MAX17050_V_FOCV); vfocv = (read_reg >> 4); vfocv = (vfocv * 125) / 100; power_on_status = smem_get_entry(SMEM_POWER_ON_STATUS_INFO, &smem_size); if (smem_size == 0 || !power_on_status) { pr_err("max17050 subsystem failure reason:"); pr_err(" (unknown, smem_get_entry failed).\n"); return; } #if defined(CONFIG_MACH_MSM8974_G2_DCM) /* for A1 DCM PM8941 */ if((0xff & *power_on_status) ==0x10) #else /* for G, GV PM8941 */ if((0xff & *power_on_status) ==0x20) #endif { if(max17050_quickstart_check_chglogo_boot(vcell, vfocv)) F_bat("[MAX17050] chglogo quicksart!!\n"); /*goto quick_start;*/ } else { if (max17050_quickstart_check_normalboot(vcell, vfocv)) F_bat("[MAX17050] normalboot quicksart!!\n"); /*goto quick_start;*/ } return; /*quick_start: max17050_quick_start(); return;*/ } EXPORT_SYMBOL(max17050_initial_quickstart_check); static int __devinit max17050_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent); struct max17050_chip *chip; #ifdef CONFIG_LGE_PM hw_rev_type rev; #endif int ret = 0; /*Test only int i = 0; u16 read_reg;*/ F_bat("[MAX17050] %s() Start\n", __func__); if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA)) return -EIO; chip = kzalloc(sizeof(*chip), GFP_KERNEL); if (!chip) return -ENOMEM; #ifdef CONFIG_LGE_PM rev = lge_get_board_revno(); if (rev > HW_REV_A) { ret = smb349_is_ready(); } else if (rev == HW_REV_A) { pr_debug("[MAX17050] HW_REV_A not used MAX17050."); goto error; } else { ret = qpnp_charger_is_ready(); } if (ret) goto error; #endif chip->client = client; #ifdef CONFIG_OF if (!(&client->dev.of_node)) { pr_debug("max17050_probe of_node err.\n"); goto error; } #else chip->pdata = client->dev.platform_data; #endif i2c_set_clientdata(client, chip); max17050_i2c_client = client; /*Call max17050_new_custom_model_write*/ ret = max17050_new_custom_model_write(); if (ret == 2) pr_debug("NON-POWER_ON reset. Proceed Booting.\n"); /*Error occurred. Write once more.*/ else if (ret == 1) max17050_new_custom_model_write(); /*New Custom model write End. Go to max17050_restore_bat_info_from_flash.*/ else if (ret == 0) pr_debug("POWER_ON reset. Custom Model Success.\n"); ret = device_create_file(&client->dev, &dev_attr_at_fuelrst); if (ret < 0) { pr_err("%s:File device creation failed: %d\n", __func__, ret); ret = -ENODEV; goto err_create_file_fuelrst_failed; } ret = device_create_file(&client->dev, &dev_attr_at_fuelval); if (ret < 0) { pr_err("%s:File device creation failed: %d\n", __func__, ret); ret = -ENODEV; goto err_create_file_fuelval_failed; } ret = device_create_file(&client->dev, &dev_attr_at_batl); if (ret < 0) { pr_err("%s:File device creation failed: %d\n", __func__, ret); ret = -ENODEV; goto err_create_file_batl_failed; } //batt_id_pullup_out_low(); gpio_tlmm_config(GPIO_CFG(BATT_ID, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA),GPIO_CFG_DISABLE); gpio_tlmm_config(GPIO_CFG(BATT_ID_PULLUP, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA),GPIO_CFG_DISABLE); F_bat("[MAX17050] %s() End\n", __func__); return 0; err_create_file_fuelrst_failed: device_remove_file(&client->dev, &dev_attr_at_fuelrst); err_create_file_fuelval_failed: device_remove_file(&client->dev, &dev_attr_at_fuelval); err_create_file_batl_failed: device_remove_file(&client->dev, &dev_attr_at_batl); error: kfree(chip); return ret; } static int __devexit max17050_remove(struct i2c_client *client) { struct max17050_chip *chip = i2c_get_clientdata(client); device_remove_file(&client->dev, &dev_attr_at_fuelrst); device_remove_file(&client->dev, &dev_attr_at_fuelval); device_remove_file(&client->dev, &dev_attr_at_batl); /*power_supply_unregister(&chip->battery);*/ i2c_set_clientdata(client, NULL); kfree(chip); return 0; } #ifdef CONFIG_OF static struct of_device_id max17050_match_table[] = { { .compatible = "maxim,max17050", }, { }, }; #endif static const struct i2c_device_id max17050_id[] = { { "max17050", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, max17050_id); static struct i2c_driver max17050_i2c_driver = { .driver = { .name = "max17050", #ifdef CONFIG_LGE_PM .owner = THIS_MODULE, #endif #ifdef CONFIG_OF .of_match_table = max17050_match_table, #endif }, .probe = max17050_probe, .remove = __devexit_p(max17050_remove), .id_table = max17050_id, }; static int __init max17050_init(void) { return i2c_add_driver(&max17050_i2c_driver); } module_init(max17050_init); static void __exit max17050_exit(void) { i2c_del_driver(&max17050_i2c_driver); } module_exit(max17050_exit); MODULE_AUTHOR("LG Power <lge.com>"); MODULE_DESCRIPTION("MAX17050 Fuel Gauge"); MODULE_LICENSE("GPL");
shengdie/Dorimanx-LG-G2-D802-Kernel
drivers/power/max17050_battery.c
C
gpl-2.0
40,592
<?php /** * http://fusionforge.org/ * * This file is part of FusionForge. FusionForge 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 Licence, or (at your option) * any later version. * * FusionForge 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 FusionForge; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // export a group's tracker bugs per artifact in RSS 2.0 // Author: Jutta Horstmann, data in transit <jh@dataintransit.com> // Created: 01.10.07 // Based on: export/tracker.php, export/rss20_newreleases.php, tracker/ind.php // Changes: // Date Author Comment // 07.11.07 JH show only public group feeds // //TO DO: Translations for error messages //Notes: // Keep in mind to write "&" in URLs as &amp; in RSS feeds require_once '../env.inc.php'; require_once $gfcommon.'include/pre.php'; require_once $gfwww.'export/rss_utils.inc'; if (isset($_GET['group_id'])&&!empty($_GET['group_id'])&&is_numeric($_GET['group_id'])) { $group_id = $_GET['group_id']; $group =& group_get_object($group_id); //does group exist? do we get an object? if (!$group || !is_object($group)) { beginFeed(); endOnError('Could not get the Group object'); } elseif ($group->isError()) { beginFeed(); endOnError($group->getErrorMessage()); } elseif (!$group->isPublic()){ beginFeed(); endOnError('No RSS feed available as group status is set to private.'); } $groupname = $group->getPublicName(); $link = "/tracker/?group_id=$group_id"; beginFeed($groupname,$link); //does tracker exist? do we get a factory? $atf = new ArtifactTypeFactory($group); if (!$atf || !is_object($atf) || $atf->isError()) { endOnError('Could Not Get ArtifactTypeFactory'); } $at_arr =& $atf->getArtifactTypes(); writeFeed($at_arr,$group_id); endFeed(); }//no group_id in GET else { beginFeed(); displayError('Please supply a Group ID with the request.'); endFeed(); } //**************************************************************++ function beginFeed($groupname = "", $link = "") { header("Content-Type: text/xml"); print '<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0"> '; print " <channel>\n"; print " <title>".forge_get_config('forge_name')." Project \"".$groupname."\" Bug Trackers</title>\n"; print " <link>http://".forge_get_config('web_host').$link."</link>\n"; print " <description>".forge_get_config('forge_name')." Bug Trackers of \"".$groupname."\"</description>\n"; print " <language>en-us</language>\n"; print " <copyright>Copyright 2000-".date("Y")." ".forge_get_config('forge_name')."</copyright>\n"; print " <webMaster>".forge_get_config('admin_email')."</webMaster>\n"; print " <lastBuildDate>".gmdate('D, d M Y G:i:s',time())." GMT</lastBuildDate>\n"; print " <docs>http://blogs.law.harvard.edu/tech/rss</docs>\n"; print " <image>\n"; print " <url>http://".forge_get_config('web_host')."/images/bflogo-88.png</url>\n"; print " <title>".forge_get_config('forge_name')." Developer</title>\n"; print " <link>http://".forge_get_config('web_host')."/</link>\n"; print " <width>124</width>\n"; print " <heigth>32</heigth>\n"; print " </image>\n"; } function writeFeed($at_arr, $group_id){ // ## default limit //if (isset($limit) ||empty($limit)) $limit = 10; //if ($limit > 100) $limit = 100; if (!$at_arr || count($at_arr) < 1) { endOnError(_("Tracker RSS: No trackers found")); } else { // Put the result set (list of trackers for this group) into feed items // ## item outputs //$outputtotal = 0; //loop through the bug trackers for ($j = 0; $j < count($at_arr); $j++) { print " <item>\n"; if (!is_object($at_arr[$j])) { //just skip it } elseif ($at_arr[$j]->isError()) { print " <title>Error</title>". "<description>".rss_description($at_arr[$j]->getErrorMessage())."</decription>"; } else { print " <title>".$at_arr[$j]->getName()."</title>\n"; print " <link>http://".forge_get_config('web_host')."/tracker?atid=".$at_arr[$j]->getID()."&amp;group_id=".$group_id."&amp;func=browse</link>\n"; print " <description>". rss_description($at_arr[$j]->getDescription()). " - Open Bugs: ".(int) $at_arr[$j]->getOpenCount() . ", Total Count: ". (int) $at_arr[$j]->getTotalCount() . "</description>\n"; print " <author></author>\n"; //print " <comment></comment>\n"; //print " <pubDate>".gmdate('D, d M Y G:i:s',time())." GMT</pubDate>\n"; //print " <guid></guid>\n"; }//else (everything ok) print " </item>\n"; //$outputtotal++; //if ($outputtotal >= $limit) break; }//for loop }//else (there are trackers) } function displayError($errorMessage) { print " <title>Error</title>". "<description>".rss_description($errorMessage)."</description>"; } function endFeed() { print '</channel></rss>'; exit(); } function endOnError($errorMessage) { displayError($errorMessage); endFeed(); } ?>
foresthz/fusion5.1
www/export/rss20_tracker.php
PHP
gpl-2.0
5,480
<?php defined('JPATH_PLATFORM') or die; /** * * @package VirtueMart * @subpackage Plugins - Elements * @author Valérie Isaksen * @link http://www.virtuemart.net * @copyright Copyright (c) 2004 - 2011 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * @version $Id$ */ defined('DS') or define('DS', DIRECTORY_SEPARATOR); if (!class_exists( 'VmConfig' )) require(JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'helpers'.DS.'config.php'); /* * This class is used by VirtueMart Payment or Shipment Plugins * So It should be an extension of JFormField * Those plugins cannot be configured through the Plugin Manager anyway. */ JFormHelper::loadFieldClass('list'); jimport('joomla.form.formfield'); class JFormFieldVmAcceptedCurrency extends JFormFieldList { /** * The form field type. * * @var string * @since 11.1 */ var $type = 'vmacceptedcurrency'; protected function getOptions() { VmConfig::loadConfig(); VmConfig::loadJLang('com_virtuemart', false); $cModel = VmModel::getModel('currency'); $values = $cModel->getVendorAcceptedCurrrenciesList(); $options[] = JHtml::_('select.option', 0, vmText::_('COM_VIRTUEMART_DEFAULT_VENDOR_CURRENCY')); foreach ($values as $v) { $options[] = JHtml::_('select.option', $v->virtuemart_currency_id, $v->currency_txt); } return $options; } }
FabianodeLimaAbreu/conectby
administrator/components/com_virtuemart/fields/vmacceptedcurrency.php
PHP
gpl-2.0
1,698
/* * Open-source multi-Physics Phenomena Analyzer (OP2A) ver. 0.1 * * Copyright (c) 2015 MINKWAN KIM * * Initial Developed Date: May 26, 2015 * Author: Minkwan Kim * * OP2A_ProblemCommon.hpp * - * */ #ifndef OP2A_PROBLEMCOMMON_HPP_ #define OP2A_PROBLEMCOMMON_HPP_ #include <string> #include <vector> using namespace std; namespace OP2A{ namespace Setup{ /* * Class for Basic Problem setup * * @author Minkwan Kim * @version 1.0 25/05/2015 */ class ProblemBasic { public: string title; string module; }; } } #endif /* OP2A_PROBLEMCOMMON_HPP_ */
minkwankim/OP2A
OP2A/Setup/include/OP2A_ProblemCommon.hpp
C++
gpl-2.0
593
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ThunarxFileInfo</title> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2"> <link rel="start" href="index.html" title="Thunar Extensions Reference Manual"> <link rel="up" href="thunarx-abstraction-layer.html" title="Part IV. Abstraction Layer"> <link rel="prev" href="thunarx-abstraction-layer.html" title="Part IV. Abstraction Layer"> <link rel="next" href="ThunarxPropertyPage.html" title="ThunarxPropertyPage"> <meta name="generator" content="GTK-Doc V1.10 (XML mode)"> <link rel="stylesheet" href="style.css" type="text/css"> <link rel="part" href="thunarx-overview.html" title="Part I. Overview"> <link rel="part" href="thunarx-writing-extensions.html" title="Part II. Writing Extensions"> <link rel="part" href="thunarx-fundamentals.html" title="Part III. Fundamentals"> <link rel="part" href="thunarx-abstraction-layer.html" title="Part IV. Abstraction Layer"> <link rel="part" href="thunarx-providers.html" title="Part V. Providers"> <link rel="part" href="thunarx-using-extensions.html" title="Part VI. Using Thunar extensions in applications"> <link rel="index" href="ix01.html" title="Index"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table class="navigation" id="top" width="100%" summary="Navigation header" cellpadding="2" cellspacing="2"> <tr valign="middle"> <td><a accesskey="p" href="thunarx-abstraction-layer.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td> <td><a accesskey="u" href="thunarx-abstraction-layer.html"><img src="up.png" width="24" height="24" border="0" alt="Up"></a></td> <td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td> <th width="100%" align="center">Thunar Extensions Reference Manual</th> <td><a accesskey="n" href="ThunarxPropertyPage.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td> </tr> <tr><td colspan="5" class="shortcuts"><nobr><a href="#ThunarxFileInfo.synopsis" class="shortcut">Top</a>  |  <a href="#ThunarxFileInfo.description" class="shortcut">Description</a>  |  <a href="#ThunarxFileInfo.object-hierarchy" class="shortcut">Object Hierarchy</a>  |  <a href="#ThunarxFileInfo.prerequisites" class="shortcut">Prerequisites</a>  |  <a href="#ThunarxFileInfo.signals" class="shortcut">Signals</a></nobr></td></tr> </table> <div class="refentry" lang="en"> <a name="ThunarxFileInfo"></a><div class="titlepage"></div> <div class="refnamediv"><table width="100%"><tr> <td valign="top"> <h2><span class="refentrytitle"><a name="ThunarxFileInfo.top_of_page"></a>ThunarxFileInfo</span></h2> <p>ThunarxFileInfo — Abstraction of a file handled within the file manager</p> </td> <td valign="top" align="right"></td> </tr></table></div> <div class="refsect1" lang="en"> <a name="ThunarxFileInfo.stability-level"></a><h2>Stability Level</h2> Stable, unless otherwise indicated </div> <div class="refsynopsisdiv"> <a name="ThunarxFileInfo.synopsis"></a><h2>Synopsis</h2> <pre class="synopsis"> #include &lt;thunarx/thunarx.h&gt; <a class="link" href="ThunarxFileInfo.html#ThunarxFileInfoIface" title="ThunarxFileInfoIface">ThunarxFileInfoIface</a>; <a class="link" href="ThunarxFileInfo.html#ThunarxFileInfo-struct" title="ThunarxFileInfo">ThunarxFileInfo</a>; <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-name" title="thunarx_file_info_get_name ()">thunarx_file_info_get_name</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info); <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-uri" title="thunarx_file_info_get_uri ()">thunarx_file_info_get_uri</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info); <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-parent-uri" title="thunarx_file_info_get_parent_uri ()">thunarx_file_info_get_parent_uri</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info); <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-uri-scheme" title="thunarx_file_info_get_uri_scheme ()">thunarx_file_info_get_uri_scheme</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info); <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-mime-type" title="thunarx_file_info_get_mime_type ()">thunarx_file_info_get_mime_type</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info); <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gboolean" >gboolean</a> <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-has-mime-type" title="thunarx_file_info_has_mime_type ()">thunarx_file_info_has_mime_type</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info, const <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a> *mime_type); <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gboolean" >gboolean</a> <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-is-directory" title="thunarx_file_info_is_directory ()">thunarx_file_info_is_directory</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info); <a href="../thunar-vfs/thunar-vfs-ThunarVfsInfo.html#ThunarVfsInfo" >ThunarVfsInfo</a>* <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-vfs-info" title="thunarx_file_info_get_vfs_info ()">thunarx_file_info_get_vfs_info</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info); void <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-changed" title="thunarx_file_info_changed ()">thunarx_file_info_changed</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info); void <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-renamed" title="thunarx_file_info_renamed ()">thunarx_file_info_renamed</a> (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info); #define <a class="link" href="ThunarxFileInfo.html#THUNARX-TYPE-FILE-INFO-LIST:CAPS" title="THUNARX_TYPE_FILE_INFO_LIST">THUNARX_TYPE_FILE_INFO_LIST</a> <a href="/usr/share/gtk-doc/html/glib/glib-Doubly-Linked-Lists.html#GList" >GList</a>* <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-list-copy" title="thunarx_file_info_list_copy ()">thunarx_file_info_list_copy</a> (<a href="/usr/share/gtk-doc/html/glib/glib-Doubly-Linked-Lists.html#GList" >GList</a> *file_infos); void <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-list-free" title="thunarx_file_info_list_free ()">thunarx_file_info_list_free</a> (<a href="/usr/share/gtk-doc/html/glib/glib-Doubly-Linked-Lists.html#GList" >GList</a> *file_infos); </pre> </div> <div class="refsect1" lang="en"> <a name="ThunarxFileInfo.object-hierarchy"></a><h2>Object Hierarchy</h2> <pre class="synopsis"> GInterface +----ThunarxFileInfo </pre> </div> <div class="refsect1" lang="en"> <a name="ThunarxFileInfo.prerequisites"></a><h2>Prerequisites</h2> <p> ThunarxFileInfo requires <a href="/usr/share/gtk-doc/html/gobject/gobject-The-Base-Object-Type.html#GObject" >GObject</a>.</p> </div> <div class="refsect1" lang="en"> <a name="ThunarxFileInfo.signals"></a><h2>Signals</h2> <pre class="synopsis"> "<a class="link" href="ThunarxFileInfo.html#ThunarxFileInfo-changed" title='The "changed" signal'>changed</a>" : Run First "<a class="link" href="ThunarxFileInfo.html#ThunarxFileInfo-renamed" title='The "renamed" signal'>renamed</a>" : Run First </pre> </div> <div class="refsect1" lang="en"> <a name="ThunarxFileInfo.description"></a><h2>Description</h2> <p> The <span class="interface">ThunarxFileInfo</span> interface provides extensions with a way to access information about a file handled within the file manager. </p> </div> <div class="refsect1" lang="en"> <a name="ThunarxFileInfo.details"></a><h2>Details</h2> <div class="refsect2" lang="en"> <a name="ThunarxFileInfoIface"></a><h3>ThunarxFileInfoIface</h3> <pre class="programlisting">typedef struct { /* virtual methods */ gchar *(*get_name) (ThunarxFileInfo *file_info); gchar *(*get_uri) (ThunarxFileInfo *file_info); gchar *(*get_parent_uri) (ThunarxFileInfo *file_info); gchar *(*get_uri_scheme) (ThunarxFileInfo *file_info); gchar *(*get_mime_type) (ThunarxFileInfo *file_info); gboolean (*has_mime_type) (ThunarxFileInfo *file_info, const gchar *mime_type); gboolean (*is_directory) (ThunarxFileInfo *file_info); ThunarVfsInfo *(*get_vfs_info) (ThunarxFileInfo *file_info); /* signals */ void (*changed) (ThunarxFileInfo *file_info); void (*renamed) (ThunarxFileInfo *file_info); } ThunarxFileInfoIface; </pre> <p> Interface with virtual methods implemented by the file manager and accessible from the extensions. </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="structfield"><code>get_name</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-name" title="thunarx_file_info_get_name ()"><code class="function">thunarx_file_info_get_name()</code></a>. </td> </tr> <tr> <td><p><span class="term"><em class="structfield"><code>get_uri</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-uri" title="thunarx_file_info_get_uri ()"><code class="function">thunarx_file_info_get_uri()</code></a>. </td> </tr> <tr> <td><p><span class="term"><em class="structfield"><code>get_parent_uri</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-parent-uri" title="thunarx_file_info_get_parent_uri ()"><code class="function">thunarx_file_info_get_parent_uri()</code></a>. </td> </tr> <tr> <td><p><span class="term"><em class="structfield"><code>get_uri_scheme</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-uri-scheme" title="thunarx_file_info_get_uri_scheme ()"><code class="function">thunarx_file_info_get_uri_scheme()</code></a>. </td> </tr> <tr> <td><p><span class="term"><em class="structfield"><code>get_mime_type</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-mime-type" title="thunarx_file_info_get_mime_type ()"><code class="function">thunarx_file_info_get_mime_type()</code></a>. </td> </tr> <tr> <td><p><span class="term"><em class="structfield"><code>has_mime_type</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-has-mime-type" title="thunarx_file_info_has_mime_type ()"><code class="function">thunarx_file_info_has_mime_type()</code></a>. </td> </tr> <tr> <td><p><span class="term"><em class="structfield"><code>is_directory</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-is-directory" title="thunarx_file_info_is_directory ()"><code class="function">thunarx_file_info_is_directory()</code></a>. </td> </tr> <tr> <td><p><span class="term"><em class="structfield"><code>get_vfs_info</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-vfs-info" title="thunarx_file_info_get_vfs_info ()"><code class="function">thunarx_file_info_get_vfs_info()</code></a>. </td> </tr> <tr> <td><p><span class="term"><em class="structfield"><code>changed</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-changed" title="thunarx_file_info_changed ()"><code class="function">thunarx_file_info_changed()</code></a>. </td> </tr> <tr> <td><p><span class="term"><em class="structfield"><code>renamed</code></em> ()</span></p></td> <td>See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-renamed" title="thunarx_file_info_renamed ()"><code class="function">thunarx_file_info_renamed()</code></a>. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="ThunarxFileInfo-struct"></a><h3>ThunarxFileInfo</h3> <pre class="programlisting">typedef struct _ThunarxFileInfo ThunarxFileInfo;</pre> <p> File info type, which is mapped to the real file info implementation within the file manager. </p> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-get-name"></a><h3>thunarx_file_info_get_name ()</h3> <pre class="programlisting"><a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* thunarx_file_info_get_name (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info);</pre> <p> Returns the real name of the file represented by <em class="parameter"><code>file_info</code></em> in the local file system encoding. You can use <a href="/usr/share/gtk-doc/html/glib/glib-Character-Set-Conversion.html#g-filename-display-name" ><code class="function">g_filename_display_name()</code></a> or similar functions to generate an UTF-8 version of the name, which is suitable for use in the user interface. </p> <p> The caller is responsible to free the returned string using <a href="/usr/share/gtk-doc/html/glib/glib-Memory-Allocation.html#g-free" ><code class="function">g_free()</code></a> when no longer needed.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> the real name of the file represented by <em class="parameter"><code>file_info</code></em>. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-get-uri"></a><h3>thunarx_file_info_get_uri ()</h3> <pre class="programlisting"><a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* thunarx_file_info_get_uri (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info);</pre> <p> Returns the escaped, fully qualified URI of the file object represented by <em class="parameter"><code>file_info</code></em>. You may use <a href="/usr/share/gtk-doc/html/glib/glib-Character-Set-Conversion.html#g-filename-from-uri" ><code class="function">g_filename_from_uri()</code></a> and similar functions to work with the returned URI. </p> <p> The caller is responsible to free the returned string using <a href="/usr/share/gtk-doc/html/glib/glib-Memory-Allocation.html#g-free" ><code class="function">g_free()</code></a> when no longer needed.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> the fully qualified URI of <em class="parameter"><code>file_info</code></em>. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-get-parent-uri"></a><h3>thunarx_file_info_get_parent_uri ()</h3> <pre class="programlisting"><a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* thunarx_file_info_get_parent_uri (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info);</pre> <p> Returns the URI to the parent file of <em class="parameter"><code>file_info</code></em> or <a href="/usr/share/gtk-doc/html/glib/glib-Standard-Macros.html#NULL:CAPS" ><code class="literal">NULL</code></a> if <em class="parameter"><code>file_info</code></em> has no parent. Note that the parent URI may be of a different type than the URI of <em class="parameter"><code>file_info</code></em>. For example, the parent of "file:///" is "computer:///". </p> <p> The caller is responsible to free the returned string using <a href="/usr/share/gtk-doc/html/glib/glib-Memory-Allocation.html#g-free" ><code class="function">g_free()</code></a> when no longer needed.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> the parent URI for <em class="parameter"><code>file_info</code></em> or <a href="/usr/share/gtk-doc/html/glib/glib-Standard-Macros.html#NULL:CAPS" ><code class="literal">NULL</code></a>. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-get-uri-scheme"></a><h3>thunarx_file_info_get_uri_scheme ()</h3> <pre class="programlisting"><a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* thunarx_file_info_get_uri_scheme (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info);</pre> <p> Returns the URI scheme of the file represented by <em class="parameter"><code>file_info</code></em>. E.g. if <em class="parameter"><code>file_info</code></em> refers to the file "file:///usr/home", the return value will be "file". </p> <p> The caller is responsible to free the returned string using <a href="/usr/share/gtk-doc/html/glib/glib-Memory-Allocation.html#g-free" ><code class="function">g_free()</code></a> when no longer needed.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> the URI scheme for <em class="parameter"><code>file_info</code></em>. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-get-mime-type"></a><h3>thunarx_file_info_get_mime_type ()</h3> <pre class="programlisting"><a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a>* thunarx_file_info_get_mime_type (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info);</pre> <p> Returns the MIME-type of the file represented by <em class="parameter"><code>file_info</code></em> or <a href="/usr/share/gtk-doc/html/glib/glib-Standard-Macros.html#NULL:CAPS" ><code class="literal">NULL</code></a> if no MIME-type is known for <em class="parameter"><code>file_info</code></em>. </p> <p> The caller is responsible to free the returned string using <a href="/usr/share/gtk-doc/html/glib/glib-Memory-Allocation.html#g-free" ><code class="function">g_free()</code></a> when no longer needed.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> the MIME-type for <em class="parameter"><code>file_info</code></em> or <a href="/usr/share/gtk-doc/html/glib/glib-Standard-Macros.html#NULL:CAPS" ><code class="literal">NULL</code></a>. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-has-mime-type"></a><h3>thunarx_file_info_has_mime_type ()</h3> <pre class="programlisting"><a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gboolean" >gboolean</a> thunarx_file_info_has_mime_type (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info, const <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gchar" >gchar</a> *mime_type);</pre> <p> Checks whether <em class="parameter"><code>file_info</code></em> is of the given <em class="parameter"><code>mime_type</code></em> or whether the MIME-type of <em class="parameter"><code>file_info</code></em> is a subclass of <em class="parameter"><code>mime_type</code></em>. </p> <p> This is the preferred way for most extensions to check whether they support a given file or not, and you should consider using this method rather than <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-get-mime-type" title="thunarx_file_info_get_mime_type ()"><code class="function">thunarx_file_info_get_mime_type()</code></a>. A simple example would be a menu extension that performs a certain action on text files. In this case you want to check whether a given <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a> refers to any kind of text file, not only to "text/plain" (e.g. this also includes "text/xml" and "application/x-desktop"). </p> <p> But you should be aware that this method may take some time to test whether <em class="parameter"><code>mime_type</code></em> is valid for <em class="parameter"><code>file_info</code></em>, so don't call it too often.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>mime_type</code></em> :</span></p></td> <td> a MIME-type (e.g. "text/plain"). </td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> <a href="/usr/share/gtk-doc/html/glib/glib-Standard-Macros.html#TRUE:CAPS" ><code class="literal">TRUE</code></a> if <em class="parameter"><code>mime_type</code></em> is valid for <em class="parameter"><code>file_info</code></em>, else <a href="/usr/share/gtk-doc/html/glib/glib-Standard-Macros.html#FALSE:CAPS" ><code class="literal">FALSE</code></a>. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-is-directory"></a><h3>thunarx_file_info_is_directory ()</h3> <pre class="programlisting"><a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gboolean" >gboolean</a> thunarx_file_info_is_directory (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info);</pre> <p> Checks whether <em class="parameter"><code>file_info</code></em> refers to a directory.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> <a href="/usr/share/gtk-doc/html/glib/glib-Standard-Macros.html#TRUE:CAPS" ><code class="literal">TRUE</code></a> if <em class="parameter"><code>file_info</code></em> is a directory. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-get-vfs-info"></a><h3>thunarx_file_info_get_vfs_info ()</h3> <pre class="programlisting"><a href="../thunar-vfs/thunar-vfs-ThunarVfsInfo.html#ThunarVfsInfo" >ThunarVfsInfo</a>* thunarx_file_info_get_vfs_info (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info);</pre> <p> Returns the <a href="../thunar-vfs/thunar-vfs-ThunarVfsInfo.html#ThunarVfsInfo" ><span class="type">ThunarVfsInfo</span></a> associated with <em class="parameter"><code>file_info</code></em>, which includes additional information about the <em class="parameter"><code>file_info</code></em> as queried from the VFS library earlier. The caller is responsible to free the returned <a href="../thunar-vfs/thunar-vfs-ThunarVfsInfo.html#ThunarVfsInfo" ><span class="type">ThunarVfsInfo</span></a> object using <a href="../thunar-vfs/thunar-vfs-ThunarVfsInfo.html#thunar-vfs-info-unref" ><code class="function">thunar_vfs_info_unref()</code></a> when no longer needed. </p> <p> Note that the <span class="application">thunarx</span> library itself is not linked to the <span class="application">thunar-vfs</span> library, and so, if you need to use this method, you'll need to include <code class="code">&lt;thunar-vfs/thunar-vfs.h&gt;</code> in your code and add <code class="code">`pkg-config --cflags thunar-vfs-1`</code> to your <code class="envar">CFLAGS</code>.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> the <a href="../thunar-vfs/thunar-vfs-ThunarVfsInfo.html#ThunarVfsInfo" ><span class="type">ThunarVfsInfo</span></a> object associated with <em class="parameter"><code>file_info</code></em>, which MUST be freed using <a href="../thunar-vfs/thunar-vfs-ThunarVfsInfo.html#thunar-vfs-info-unref" ><code class="function">thunar_vfs_info_unref()</code></a>. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-changed"></a><h3>thunarx_file_info_changed ()</h3> <pre class="programlisting">void thunarx_file_info_changed (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info);</pre> <p> Emits the ::changed signal on <em class="parameter"><code>file_info</code></em>. This method should not be invoked by Thunar plugins, instead the file manager itself will use this method to emit ::changed whenever it notices a change on <em class="parameter"><code>file_info</code></em>.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody><tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr></tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-renamed"></a><h3>thunarx_file_info_renamed ()</h3> <pre class="programlisting">void thunarx_file_info_renamed (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info);</pre> <p> Emits the ::renamed signal on <em class="parameter"><code>file_info</code></em>. This method should not be invoked by Thunar plugins, instead the file manager will emit this signal whenever the user renamed the <em class="parameter"><code>file_info</code></em>. </p> <p> The plugins should instead connect to the ::renamed signal and update it's internal state and it's user interface after the file manager renamed a file.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody><tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr></tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="THUNARX-TYPE-FILE-INFO-LIST:CAPS"></a><h3>THUNARX_TYPE_FILE_INFO_LIST</h3> <pre class="programlisting">#define THUNARX_TYPE_FILE_INFO_LIST (thunarx_file_info_list_get_type ()) </pre> <p> The <a href="/usr/share/gtk-doc/html/gobject/gobject-Type-Information.html#GType" ><span class="type">GType</span></a> for a boxed type holding a <a href="/usr/share/gtk-doc/html/glib/glib-Doubly-Linked-Lists.html#GList" ><span class="type">GList</span></a> of <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>s. See <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-list-copy" title="thunarx_file_info_list_copy ()"><code class="function">thunarx_file_info_list_copy()</code></a> and <a class="link" href="ThunarxFileInfo.html#thunarx-file-info-list-free" title="thunarx_file_info_list_free ()"><code class="function">thunarx_file_info_list_free()</code></a>. </p> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-list-copy"></a><h3>thunarx_file_info_list_copy ()</h3> <pre class="programlisting"><a href="/usr/share/gtk-doc/html/glib/glib-Doubly-Linked-Lists.html#GList" >GList</a>* thunarx_file_info_list_copy (<a href="/usr/share/gtk-doc/html/glib/glib-Doubly-Linked-Lists.html#GList" >GList</a> *file_infos);</pre> <p> Does a deep copy of <em class="parameter"><code>file_infos</code></em> and returns the new list.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_infos</code></em> :</span></p></td> <td> a <a href="/usr/share/gtk-doc/html/glib/glib-Doubly-Linked-Lists.html#GList" ><span class="type">GList</span></a> of <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>s. </td> </tr> <tr> <td><p><span class="term"><span class="emphasis"><em>Returns</em></span> :</span></p></td> <td> a copy of <em class="parameter"><code>file_infos</code></em>. </td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="thunarx-file-info-list-free"></a><h3>thunarx_file_info_list_free ()</h3> <pre class="programlisting">void thunarx_file_info_list_free (<a href="/usr/share/gtk-doc/html/glib/glib-Doubly-Linked-Lists.html#GList" >GList</a> *file_infos);</pre> <p> Frees the resources allocated for the <em class="parameter"><code>file_infos</code></em> list and decreases the reference count on the <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>s contained within.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody><tr> <td><p><span class="term"><em class="parameter"><code>file_infos</code></em> :</span></p></td> <td> a <a href="/usr/share/gtk-doc/html/glib/glib-Doubly-Linked-Lists.html#GList" ><span class="type">GList</span></a> of <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>s. </td> </tr></tbody> </table></div> </div> </div> <div class="refsect1" lang="en"> <a name="ThunarxFileInfo.signal-details"></a><h2>Signal Details</h2> <div class="refsect2" lang="en"> <a name="ThunarxFileInfo-changed"></a><h3>The <code class="literal">"changed"</code> signal</h3> <pre class="programlisting">void user_function (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info, <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gpointer" >gpointer</a> user_data) : Run First</pre> <p> Emitted whenever the system notices a change to <em class="parameter"><code>file_info</code></em>. </p> <p> Thunar plugins should use this signal to stay informed about changes to a <em class="parameter"><code>file_info</code></em> for which they currently display information (i.e. in a <a class="link" href="ThunarxPropertyPage.html" title="ThunarxPropertyPage"><span class="type">ThunarxPropertyPage</span></a>), and update it's user interface whenever a change is noticed on <em class="parameter"><code>file_info</code></em>.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a>. </td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>user_data</code></em> :</span></p></td> <td>user data set when the signal handler was connected.</td> </tr> </tbody> </table></div> </div> <hr> <div class="refsect2" lang="en"> <a name="ThunarxFileInfo-renamed"></a><h3>The <code class="literal">"renamed"</code> signal</h3> <pre class="programlisting">void user_function (<a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo">ThunarxFileInfo</a> *file_info, <a href="/usr/share/gtk-doc/html/glib/glib-Basic-Types.html#gpointer" >gpointer</a> user_data) : Run First</pre> <p> Emitted when the <em class="parameter"><code>file_info</code></em> is renamed to another name. </p> <p> For example, within Thunar, <span class="type">ThunarFolder</span> uses this signal to reregister it's VFS directory monitor, after the corresponding file was renamed.</p> <p> </p> <div class="variablelist"><table border="0"> <col align="left" valign="top"> <tbody> <tr> <td><p><span class="term"><em class="parameter"><code>file_info</code></em> :</span></p></td> <td> a <a class="link" href="ThunarxFileInfo.html" title="ThunarxFileInfo"><span class="type">ThunarxFileInfo</span></a> </td> </tr> <tr> <td><p><span class="term"><em class="parameter"><code>user_data</code></em> :</span></p></td> <td>user data set when the signal handler was connected.</td> </tr> </tbody> </table></div> </div> </div> </div> <div class="footer"> <hr> Generated by GTK-Doc V1.10</div> </body> </html>
fibernet-us/Thunar_sort_files_by_extension
docs/reference/thunarx/html/ThunarxFileInfo.html
HTML
gpl-2.0
36,033
<?php /* * This file is part of SeAT * * Copyright (C) 2015 to 2020 Leon Jacobs * * 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. */ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** * Class CreateCorporationInfosTestTable. */ class CreateCorporationInfosTestTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('corporation_infos', function (Blueprint $table) { $table->bigInteger('corporation_id')->primary(); $table->string('name'); $table->string('ticker'); $table->integer('member_count'); $table->bigInteger('ceo_id'); $table->bigInteger('alliance_id')->nullable(); $table->text('description')->nullable(); $table->double('tax_rate'); $table->dateTime('date_founded')->nullable(); $table->bigInteger('creator_id'); $table->string('url')->nullable(); $table->integer('faction_id')->nullable(); $table->integer('home_station_id')->nullable(); $table->bigInteger('shares')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('corporation_infos'); } }
eveseat/web
tests/database/migrations/2020_05_08_085856_create_corporation_infos_test_table.php
PHP
gpl-2.0
2,126
/* * This include file is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. */ #ifndef __ASM_ARCH_REGS_USB_OTG_HS_H #define __ASM_ARCH_REGS_USB_OTG_HS_H #define S3C_USBOTG_PHYREG(x) ((x) + S3C_VA_OTGSFR) #define S3C_USBOTG_PHYPWR S3C_USBOTG_PHYREG(0x0) #define S3C_USBOTG_PHYCLK S3C_USBOTG_PHYREG(0x4) #define S3C_USBOTG_RSTCON S3C_USBOTG_PHYREG(0x8) /* USB2.0 OTG Controller register */ #define S3C_USBOTGREG(x) ((x) + S3C_VA_OTG) //============================================================================================== // Core Global Registers #define S3C_UDC_OTG_GOTGCTL S3C_USBOTGREG(0x000) // OTG Control & Status #define S3C_UDC_OTG_GOTGINT S3C_USBOTGREG(0x004) // OTG Interrupt #define S3C_UDC_OTG_GAHBCFG S3C_USBOTGREG(0x008) // Core AHB Configuration #define S3C_UDC_OTG_GUSBCFG S3C_USBOTGREG(0x00C) // Core USB Configuration #define S3C_UDC_OTG_GRSTCTL S3C_USBOTGREG(0x010) // Core Reset #define S3C_UDC_OTG_GINTSTS S3C_USBOTGREG(0x014) // Core Interrupt #define S3C_UDC_OTG_GINTMSK S3C_USBOTGREG(0x018) // Core Interrupt Mask #define S3C_UDC_OTG_GRXSTSR S3C_USBOTGREG(0x01C) // Receive Status Debug Read/Status Read #define S3C_UDC_OTG_GRXSTSP S3C_USBOTGREG(0x020) // Receive Status Debug Pop/Status Pop #define S3C_UDC_OTG_GRXFSIZ S3C_USBOTGREG(0x024) // Receive FIFO Size #define S3C_UDC_OTG_GNPTXFSIZ S3C_USBOTGREG(0x028) // Non-Periodic Transmit FIFO Size #define S3C_UDC_OTG_GNPTXSTS S3C_USBOTGREG(0x02C) // Non-Periodic Transmit FIFO/Queue Status #define S3C_UDC_OTG_HPTXFSIZ S3C_USBOTGREG(0x100) // Host Periodic Transmit FIFO Size #define S3C_UDC_OTG_DPTXFSIZ1 S3C_USBOTGREG(0x104) // Device Periodic Transmit FIFO-1 Size #define S3C_UDC_OTG_DPTXFSIZ2 S3C_USBOTGREG(0x108) // Device Periodic Transmit FIFO-2 Size #define S3C_UDC_OTG_DPTXFSIZ3 S3C_USBOTGREG(0x10C) // Device Periodic Transmit FIFO-3 Size #define S3C_UDC_OTG_DPTXFSIZ4 S3C_USBOTGREG(0x110) // Device Periodic Transmit FIFO-4 Size #define S3C_UDC_OTG_DPTXFSIZ5 S3C_USBOTGREG(0x114) // Device Periodic Transmit FIFO-5 Size #define S3C_UDC_OTG_DPTXFSIZ6 S3C_USBOTGREG(0x118) // Device Periodic Transmit FIFO-6 Size #define S3C_UDC_OTG_DPTXFSIZ7 S3C_USBOTGREG(0x11C) // Device Periodic Transmit FIFO-7 Size #define S3C_UDC_OTG_DPTXFSIZ8 S3C_USBOTGREG(0x120) // Device Periodic Transmit FIFO-8 Size #define S3C_UDC_OTG_DPTXFSIZ9 S3C_USBOTGREG(0x124) // Device Periodic Transmit FIFO-9 Size #define S3C_UDC_OTG_DPTXFSIZ10 S3C_USBOTGREG(0x128) // Device Periodic Transmit FIFO-10 Size #define S3C_UDC_OTG_DPTXFSIZ11 S3C_USBOTGREG(0x12C) // Device Periodic Transmit FIFO-11 Size #define S3C_UDC_OTG_DPTXFSIZ12 S3C_USBOTGREG(0x130) // Device Periodic Transmit FIFO-12 Size #define S3C_UDC_OTG_DPTXFSIZ13 S3C_USBOTGREG(0x134) // Device Periodic Transmit FIFO-13 Size #define S3C_UDC_OTG_DPTXFSIZ14 S3C_USBOTGREG(0x138) // Device Periodic Transmit FIFO-14 Size #define S3C_UDC_OTG_DPTXFSIZ15 S3C_USBOTGREG(0x13C) // Device Periodic Transmit FIFO-15 Size //============================================================================================== // Host Mode Registers //------------------------------------------------ // Host Global Registers #define S3C_UDC_OTG_HCFG S3C_USBOTGREG(0x400) // Host Configuration #define S3C_UDC_OTG_HFIR S3C_USBOTGREG(0x404) // Host Frame Interval #define S3C_UDC_OTG_HFNUM S3C_USBOTGREG(0x408) // Host Frame Number/Frame Time Remaining #define S3C_UDC_OTG_HPTXSTS S3C_USBOTGREG(0x410) // Host Periodic Transmit FIFO/Queue Status #define S3C_UDC_OTG_HAINT S3C_USBOTGREG(0x414) // Host All Channels Interrupt #define S3C_UDC_OTG_HAINTMSK S3C_USBOTGREG(0x418) // Host All Channels Interrupt Mask //------------------------------------------------ // Host Port Control & Status Registers #define S3C_UDC_OTG_HPRT S3C_USBOTGREG(0x440) // Host Port Control & Status //------------------------------------------------ // Host Channel-Specific Registers #define S3C_UDC_OTG_HCCHAR0 S3C_USBOTGREG(0x500) // Host Channel-0 Characteristics #define S3C_UDC_OTG_HCSPLT0 S3C_USBOTGREG(0x504) // Host Channel-0 Split Control #define S3C_UDC_OTG_HCINT0 S3C_USBOTGREG(0x508) // Host Channel-0 Interrupt #define S3C_UDC_OTG_HCINTMSK0 S3C_USBOTGREG(0x50C) // Host Channel-0 Interrupt Mask #define S3C_UDC_OTG_HCTSIZ0 S3C_USBOTGREG(0x510) // Host Channel-0 Transfer Size #define S3C_UDC_OTG_HCDMA0 S3C_USBOTGREG(0x514) // Host Channel-0 DMA Address //============================================================================================== // Device Mode Registers //------------------------------------------------ // Device Global Registers #define S3C_UDC_OTG_DCFG S3C_USBOTGREG(0x800) // Device Configuration #define S3C_UDC_OTG_DCTL S3C_USBOTGREG(0x804) // Device Control #define S3C_UDC_OTG_DSTS S3C_USBOTGREG(0x808) // Device Status #define S3C_UDC_OTG_DIEPMSK S3C_USBOTGREG(0x810) // Device IN Endpoint Common Interrupt Mask #define S3C_UDC_OTG_DOEPMSK S3C_USBOTGREG(0x814) // Device OUT Endpoint Common Interrupt Mask #define S3C_UDC_OTG_DAINT S3C_USBOTGREG(0x818) // Device All Endpoints Interrupt #define S3C_UDC_OTG_DAINTMSK S3C_USBOTGREG(0x81C) // Device All Endpoints Interrupt Mask #define S3C_UDC_OTG_DTKNQR1 S3C_USBOTGREG(0x820) // Device IN Token Sequence Learning Queue Read 1 #define S3C_UDC_OTG_DTKNQR2 S3C_USBOTGREG(0x824) // Device IN Token Sequence Learning Queue Read 2 #define S3C_UDC_OTG_DVBUSDIS S3C_USBOTGREG(0x828) // Device VBUS Discharge Time #define S3C_UDC_OTG_DVBUSPULSE S3C_USBOTGREG(0x82C) // Device VBUS Pulsing Time #define S3C_UDC_OTG_DTKNQR3 S3C_USBOTGREG(0x830) // Device IN Token Sequence Learning Queue Read 3 #define S3C_UDC_OTG_DTKNQR4 S3C_USBOTGREG(0x834) // Device IN Token Sequence Learning Queue Read 4 //------------------------------------------------ // Device Logical IN Endpoint-Specific Registers #define S3C_UDC_OTG_DIEPCTL0 S3C_USBOTGREG(0x900) // Device IN Endpoint 0 Control #define S3C_UDC_OTG_DIEPINT0 S3C_USBOTGREG(0x908) // Device IN Endpoint 0 Interrupt #define S3C_UDC_OTG_DIEPTSIZ0 S3C_USBOTGREG(0x910) // Device IN Endpoint 0 Transfer Size #define S3C_UDC_OTG_DIEPDMA0 S3C_USBOTGREG(0x914) // Device IN Endpoint 0 DMA Address #define S3C_UDC_OTG_DIEPCTL1 S3C_USBOTGREG(0x920) // Device IN Endpoint 2 Control #define S3C_UDC_OTG_DIEPINT1 S3C_USBOTGREG(0x928) // Device IN Endpoint 2 Interrupt #define S3C_UDC_OTG_DIEPTSIZ1 S3C_USBOTGREG(0x930) // Device IN Endpoint 2 Transfer Size #define S3C_UDC_OTG_DIEPDMA1 S3C_USBOTGREG(0x934) // Device IN Endpoint 2 DMA Address #define S3C_UDC_OTG_DIEPCTL2 S3C_USBOTGREG(0x940) // Device IN Endpoint 2 Control #define S3C_UDC_OTG_DIEPINT2 S3C_USBOTGREG(0x948) // Device IN Endpoint 2 Interrupt #define S3C_UDC_OTG_DIEPTSIZ2 S3C_USBOTGREG(0x950) // Device IN Endpoint 2 Transfer Size #define S3C_UDC_OTG_DIEPDMA2 S3C_USBOTGREG(0x954) // Device IN Endpoint 2 DMA Address #define S3C_UDC_OTG_DIEPCTL3 S3C_USBOTGREG(0x960) // Device IN Endpoint 3 Control #define S3C_UDC_OTG_DIEPINT3 S3C_USBOTGREG(0x968) // Device IN Endpoint 3 Interrupt #define S3C_UDC_OTG_DIEPTSIZ3 S3C_USBOTGREG(0x970) // Device IN Endpoint 3 Transfer Size #define S3C_UDC_OTG_DIEPDMA3 S3C_USBOTGREG(0x974) // Device IN Endpoint 3 DMA Address #define S3C_UDC_OTG_DIEPCTL4 S3C_USBOTGREG(0x980) // Device IN Endpoint 4 Control #define S3C_UDC_OTG_DIEPINT4 S3C_USBOTGREG(0x988) // Device IN Endpoint 4 Interrupt #define S3C_UDC_OTG_DIEPTSIZ4 S3C_USBOTGREG(0x990) // Device IN Endpoint 4 Transfer Size #define S3C_UDC_OTG_DIEPDMA4 S3C_USBOTGREG(0x994) // Device IN Endpoint 4 DMA Address #define S3C_UDC_OTG_DIEPCTL5 S3C_USBOTGREG(0x9a0) // Device IN Endpoint 5 Control #define S3C_UDC_OTG_DIEPINT5 S3C_USBOTGREG(0x9a8) // Device IN Endpoint 5 Interrupt #define S3C_UDC_OTG_DIEPTSIZ5 S3C_USBOTGREG(0x9b0) // Device IN Endpoint 5 Transfer Size #define S3C_UDC_OTG_DIEPDMA5 S3C_USBOTGREG(0x9b4) // Device IN Endpoint 5 DMA Address #define S3C_UDC_OTG_DIEPCTL6 S3C_USBOTGREG(0x9c0) // Device IN Endpoint 6 Control #define S3C_UDC_OTG_DIEPINT6 S3C_USBOTGREG(0x9c8) // Device IN Endpoint 6 Interrupt #define S3C_UDC_OTG_DIEPTSIZ6 S3C_USBOTGREG(0x9d0) // Device IN Endpoint 6 Transfer Size #define S3C_UDC_OTG_DIEPDMA6 S3C_USBOTGREG(0x9d4) // Device IN Endpoint 6 DMA Address #define S3C_UDC_OTG_DIEPCTL7 S3C_USBOTGREG(0x9e0) // Device IN Endpoint 7 Control #define S3C_UDC_OTG_DIEPINT7 S3C_USBOTGREG(0x9e8) // Device IN Endpoint 7 Interrupt #define S3C_UDC_OTG_DIEPTSIZ7 S3C_USBOTGREG(0x9f0) // Device IN Endpoint 7 Transfer Size #define S3C_UDC_OTG_DIEPDMA7 S3C_USBOTGREG(0x9f4) // Device IN Endpoint 7 DMA Address #define S3C_UDC_OTG_DIEPCTL8 S3C_USBOTGREG(0xa00) // Device IN Endpoint 8 Control #define S3C_UDC_OTG_DIEPINT8 S3C_USBOTGREG(0xa08) // Device IN Endpoint 8 Interrupt #define S3C_UDC_OTG_DIEPTSIZ8 S3C_USBOTGREG(0xa10) // Device IN Endpoint 8 Transfer Size #define S3C_UDC_OTG_DIEPDMA8 S3C_USBOTGREG(0xa14) // Device IN Endpoint 8 DMA Address #define S3C_UDC_OTG_DIEPCTL9 S3C_USBOTGREG(0xa20) // Device IN Endpoint 9 Control #define S3C_UDC_OTG_DIEPINT9 S3C_USBOTGREG(0xa28) // Device IN Endpoint 9 Interrupt #define S3C_UDC_OTG_DIEPTSIZ9 S3C_USBOTGREG(0xa30) // Device IN Endpoint 9 Transfer Size #define S3C_UDC_OTG_DIEPDMA9 S3C_USBOTGREG(0xa34) // Device IN Endpoint 9 DMA Address //------------------------------------------------ // Device Logical OUT Endpoint-Specific Registers #define S3C_UDC_OTG_DOEPCTL0 S3C_USBOTGREG(0xB00) // Device OUT Endpoint 0 Control #define S3C_UDC_OTG_DOEPINT0 S3C_USBOTGREG(0xB08) // Device OUT Endpoint 0 Interrupt #define S3C_UDC_OTG_DOEPTSIZ0 S3C_USBOTGREG(0xB10) // Device OUT Endpoint 0 Transfer Size #define S3C_UDC_OTG_DOEPDMA0 S3C_USBOTGREG(0xB14) // Device OUT Endpoint 0 DMA Address #define S3C_UDC_OTG_DOEPCTL1 S3C_USBOTGREG(0xB20) // Device OUT Endpoint 1 Control #define S3C_UDC_OTG_DOEPINT1 S3C_USBOTGREG(0xB28) // Device OUT Endpoint 1 Interrupt #define S3C_UDC_OTG_DOEPTSIZ1 S3C_USBOTGREG(0xB30) // Device OUT Endpoint 1 Transfer Size #define S3C_UDC_OTG_DOEPDMA1 S3C_USBOTGREG(0xB34) // Device OUT Endpoint 1 DMA Address #define S3C_UDC_OTG_DOEPCTL2 S3C_USBOTGREG(0xB40) // Device OUT Endpoint 2 Control #define S3C_UDC_OTG_DOEPINT2 S3C_USBOTGREG(0xB48) // Device OUT Endpoint 2 Interrupt #define S3C_UDC_OTG_DOEPTSIZ2 S3C_USBOTGREG(0xB50) // Device OUT Endpoint 2 Transfer Size #define S3C_UDC_OTG_DOEPDMA2 S3C_USBOTGREG(0xB54) // Device OUT Endpoint 2 DMA Address #define S3C_UDC_OTG_DOEPCTL3 S3C_USBOTGREG(0xB60) // Device OUT Endpoint 3 Control #define S3C_UDC_OTG_DOEPINT3 S3C_USBOTGREG(0xB68) // Device OUT Endpoint 3 Interrupt #define S3C_UDC_OTG_DOEPTSIZ3 S3C_USBOTGREG(0xB70) // Device OUT Endpoint 3 Transfer Size #define S3C_UDC_OTG_DOEPDMA3 S3C_USBOTGREG(0xB74) // Device OUT Endpoint 3 DMA Address #define S3C_UDC_OTG_DOEPCTL4 S3C_USBOTGREG(0xB80) // Device OUT Endpoint 4 Control #define S3C_UDC_OTG_DOEPINT4 S3C_USBOTGREG(0xB88) // Device OUT Endpoint 4 Interrupt #define S3C_UDC_OTG_DOEPTSIZ4 S3C_USBOTGREG(0xB90) // Device OUT Endpoint 4 Transfer Size #define S3C_UDC_OTG_DOEPDMA4 S3C_USBOTGREG(0xB94) // Device OUT Endpoint 4 DMA Address #define S3C_UDC_OTG_DOEPCTL5 S3C_USBOTGREG(0xBa0) // Device OUT Endpoint 5 Control #define S3C_UDC_OTG_DOEPINT5 S3C_USBOTGREG(0xBa8) // Device OUT Endpoint 5 Interrupt #define S3C_UDC_OTG_DOEPTSIZ5 S3C_USBOTGREG(0xBb0) // Device OUT Endpoint 5 Transfer Size #define S3C_UDC_OTG_DOEPDMA5 S3C_USBOTGREG(0xBb4) // Device OUT Endpoint 5 DMA Address #define S3C_UDC_OTG_DOEPCTL6 S3C_USBOTGREG(0xBc0) // Device OUT Endpoint 6 Control #define S3C_UDC_OTG_DOEPINT6 S3C_USBOTGREG(0xBc8) // Device OUT Endpoint 6 Interrupt #define S3C_UDC_OTG_DOEPTSIZ6 S3C_USBOTGREG(0xBd0) // Device OUT Endpoint 6 Transfer Size #define S3C_UDC_OTG_DOEPDMA6 S3C_USBOTGREG(0xBd4) // Device OUT Endpoint 6 DMA Address #define S3C_UDC_OTG_DOEPCTL7 S3C_USBOTGREG(0xBe0) // Device OUT Endpoint 7 Control #define S3C_UDC_OTG_DOEPINT7 S3C_USBOTGREG(0xBe8) // Device OUT Endpoint 7 Interrupt #define S3C_UDC_OTG_DOEPTSIZ7 S3C_USBOTGREG(0xBf0) // Device OUT Endpoint 7 Transfer Size #define S3C_UDC_OTG_DOEPDMA7 S3C_USBOTGREG(0xBf4) // Device OUT Endpoint 7 DMA Address #define S3C_UDC_OTG_DOEPCTL8 S3C_USBOTGREG(0xc00) // Device OUT Endpoint 8 Control #define S3C_UDC_OTG_DOEPINT8 S3C_USBOTGREG(0xc08) // Device OUT Endpoint 8 Interrupt #define S3C_UDC_OTG_DOEPTSIZ8 S3C_USBOTGREG(0xc10) // Device OUT Endpoint 8 Transfer Size #define S3C_UDC_OTG_DOEPDMA8 S3C_USBOTGREG(0xc14) // Device OUT Endpoint 8 DMA Address #define S3C_UDC_OTG_DOEPCTL9 S3C_USBOTGREG(0xc20) // Device OUT Endpoint 9 Control #define S3C_UDC_OTG_DOEPINT9 S3C_USBOTGREG(0xc28) // Device OUT Endpoint 9 Interrupt #define S3C_UDC_OTG_DOEPTSIZ9 S3C_USBOTGREG(0xc30) // Device OUT Endpoint 9 Transfer Size #define S3C_UDC_OTG_DOEPDMA9 S3C_USBOTGREG(0xc34) // Device OUT Endpoint 9 DMA Address //------------------------------------------------ // Endpoint FIFO address #define S3C_UDC_OTG_EP0_FIFO S3C_USBOTGREG(0x1000) #define S3C_UDC_OTG_EP1_FIFO S3C_USBOTGREG(0x2000) #define S3C_UDC_OTG_EP2_FIFO S3C_USBOTGREG(0x3000) #define S3C_UDC_OTG_EP3_FIFO S3C_USBOTGREG(0x4000) #define S3C_UDC_OTG_EP4_FIFO S3C_USBOTGREG(0x5000) #define S3C_UDC_OTG_EP5_FIFO S3C_USBOTGREG(0x6000) #define S3C_UDC_OTG_EP6_FIFO S3C_USBOTGREG(0x7000) #define S3C_UDC_OTG_EP7_FIFO S3C_USBOTGREG(0x8000) #define S3C_UDC_OTG_EP8_FIFO S3C_USBOTGREG(0x9000) #define S3C_UDC_OTG_EP9_FIFO S3C_USBOTGREG(0xa000) //============================================================================================== // Power and Clock Gating Registers //------------------------------------------------ #define S3C_UDC_OTG_PCGCCTL S3C_USBOTGREG(0x0E00) //===================================================================== //definitions related to CSR setting // S3C_UDC_OTG_PCGCCTL : Power and Clock Gating Registers #define STOP_PCLK_BIT (0) #define GATE_HCLK_BIT (1) // S3C_UDC_OTG_GOTGCTL #define B_SESSION_VALID (0x1<<19) #define A_SESSION_VALID (0x1<<18) //S3C_UDC_OTG_DSTS: Device Status #define SUSPEND_STS (0) // S3C_UDC_OTG_GAHBCFG #define PTXFE_HALF (0<<8) #define PTXFE_ZERO (1<<8) #define NPTXFE_HALF (0<<7) #define NPTXFE_ZERO (1<<7) #define MODE_SLAVE (0<<5) #define MODE_DMA (1<<5) #define BURST_SINGLE (0<<1) #define BURST_INCR (1<<1) #define BURST_INCR4 (3<<1) #define BURST_INCR8 (5<<1) #define BURST_INCR16 (7<<1) #define GBL_INT_UNMASK (1<<0) #define GBL_INT_MASK (0<<0) // S3C_UDC_OTG_GRSTCTL #define AHB_MASTER_IDLE (0x1<<31) #define CORE_SOFT_RESET (0x1<<0) // S3C_UDC_OTG_GINTSTS/S3C_UDC_OTG_GINTMSK core interrupt register #define INT_RESUME (0x1<<31) #define INT_DISCONN (0x1<<29) #define INT_CONN_ID_STS_CNG (0x1<<28) #define INT_OUT_EP (0x1<<19) #define INT_IN_EP (0x1<<18) #define INT_ENUMDONE (0x1<<13) #define INT_RESET (0x1<<12) #define INT_SUSPEND (0x1<<11) #define INT_EARLY_SUSPEND (0x1<<10) #define INT_GOUTNakEff (0x1<<7) #define INT_GINNakEff (0x1<<6) #define INT_NP_TX_FIFO_EMPTY (0x1<<5) #define INT_RX_FIFO_NOT_EMPTY (0x1<<4) #define INT_SOF (0x1<<3) #define INT_OTG (0x1<<2) #define INT_MODE_MIS (0x1<<1) #define INT_CUR_MOD (0x1<<0) #define FULL_SPEED_CONTROL_PKT_SIZE (8) #define FULL_SPEED_BULK_PKT_SIZE (64) #define HIGH_SPEED_CONTROL_PKT_SIZE (64) #define HIGH_SPEED_BULK_PKT_SIZE (512) #define RX_FIFO_SIZE (2048) #define NPTX_FIFO_START_ADDR RX_FIFO_SIZE #define NPTX_FIFO_SIZE (2048) #define PTX_FIFO_SIZE (2048) #define DEPCTL_TXFNUM_0 (0x0<<22) #define DEPCTL_TXFNUM_1 (0x1<<22) #define DEPCTL_TXFNUM_2 (0x2<<22) #define DEPCTL_TXFNUM_3 (0x3<<22) #define DEPCTL_TXFNUM_4 (0x4<<22) // Enumeration speed #define USB_HIGH_30_60MHZ (0x0<<1) #define USB_FULL_30_60MHZ (0x1<<1) #define USB_LOW_6MHZ (0x2<<1) #define USB_FULL_48MHZ (0x3<<1) // S3C_UDC_OTG_GRXSTSP STATUS #define OUT_PKT_RECEIVED (0x2<<17) #define OUT_TRANSFER_COMPLELTED (0x3<<17) #define SETUP_TRANSACTION_COMPLETED (0x4<<17) #define SETUP_PKT_RECEIVED (0x6<<17) #define GLOBAL_OUT_NAK (0x1<<17) // S3C_UDC_OTG_DCTL device control register #define NORMAL_OPERATION (0x1<<0) #define SOFT_DISCONNECT (0x1<<1) // S3C_UDC_OTG_DAINT device all endpoint interrupt register #define S3C_UDC_INT_IN_EP0 (0x1<<0) #define S3C_UDC_INT_IN_EP2 (0x1<<2) #define S3C_UDC_INT_IN_EP3 (0x1<<3) #define S3C_UDC_INT_OUT_EP0 (0x1<<16) #define S3C_UDC_INT_OUT_EP1 (0x1<<17) #define S3C_UDC_INT_OUT_EP4 (0x1<<20) // S3C_UDC_OTG_DIEPCTL0/DOEPCTL0 device control IN/OUT endpoint 0 control register #define DEPCTL_EPENA (0x1<<31) #define DEPCTL_EPDIS (0x1<<30) #define DEPCTL_SNAK (0x1<<27) #define DEPCTL_CNAK (0x1<<26) #define DEPCTL_CTRL_TYPE (0x0<<18) #define DEPCTL_ISO_TYPE (0x1<<18) #define DEPCTL_BULK_TYPE (0x2<<18) #define DEPCTL_INTR_TYPE (0x3<<18) #define DEPCTL_USBACTEP (0x1<<15) #define DEPCTL0_MPS_64 (0x0<<0) #define DEPCTL0_MPS_32 (0x1<<0) #define DEPCTL0_MPS_16 (0x2<<0) #define DEPCTL0_MPS_8 (0x3<<0) #define DEPCTL_MPS_BULK_512 (512<<0) #define DEPCTL_MPS_INT_MPS_16 (16<<0) #define DIEPCTL_NEXT_EP_BIT (11) // S3C_UDC_OTG_DIEPMSK/DOEPMSK device IN/OUT endpoint common interrupt mask register // S3C_UDC_OTG_DIEPINTn/DOEPINTn device IN/OUT endpoint interrupt register #define BACK2BACK_SETUP_RECEIVED (0x1<<6) #define INTKNEPMIS (0x1<<5) #define INTKN_TXFEMP (0x1<<4) #define NON_ISO_IN_EP_TIMEOUT (0x1<<3) #define CTRL_OUT_EP_SETUP_PHASE_DONE (0x1<<3) #define AHB_ERROR (0x1<<2) #define EPDISBLD (0x1<<1) #define TRANSFER_DONE (0x1<<0) //DIEPTSIZ0 / DOEPTSIZ0 // DEPTSIZ common bit #define DEPTSIZ_PKT_CNT_BIT (19) #define DEPTSIZ_XFER_SIZE_BIT (0) #define DEPTSIZ_SETUP_PKCNT_1 (1<<29) #define DEPTSIZ_SETUP_PKCNT_2 (2<<29) #define DEPTSIZ_SETUP_PKCNT_3 (3<<29) #endif
JesusFreke/nook-linux-kernel
arch/arm/plat-s3c/include/plat/regs-usb-otg-hs.h
C
gpl-2.0
18,219
/* * Copyright (C) 2005 - 2011 MaNGOS <http://www.getmangos.org/> * * Copyright (C) 2008 - 2011 TrinityCore <http://www.trinitycore.org/> * * Copyright (C) 2011 - 2012 TrilliumEMU <http://trilliumx.code-engine.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "InstanceScript.h" #include "DatabaseEnv.h" #include "Map.h" #include "Player.h" #include "GameObject.h" #include "Creature.h" #include "CreatureAI.h" #include "Log.h" #include "LFGMgr.h" void InstanceScript::SaveToDB() { std::string data = GetSaveData(); if (data.empty()) return; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_DATA); stmt->setUInt32(0, GetCompletedEncounterMask()); stmt->setString(1, data); stmt->setUInt32(2, instance->GetInstanceId()); CharacterDatabase.Execute(stmt); } void InstanceScript::HandleGameObject(uint64 GUID, bool open, GameObject *go) { if (!go) go = instance->GetGameObject(GUID); if (go) go->SetGoState(open ? GO_STATE_ACTIVE : GO_STATE_READY); else sLog->outDebug(LOG_FILTER_TSCR, "TSCR: InstanceScript: HandleGameObject failed"); } bool InstanceScript::IsEncounterInProgress() const { for (std::vector<BossInfo>::const_iterator itr = bosses.begin(); itr != bosses.end(); ++itr) if (itr->state == IN_PROGRESS) return true; return false; } void InstanceScript::LoadMinionData(const MinionData *data) { while (data->entry) { if (data->bossId < bosses.size()) minions.insert(std::make_pair(data->entry, MinionInfo(&bosses[data->bossId]))); ++data; } sLog->outDebug(LOG_FILTER_TSCR, "InstanceScript::LoadMinionData: " UI64FMTD " minions loaded.", uint64(minions.size())); } void InstanceScript::LoadDoorData(const DoorData *data) { while (data->entry) { if (data->bossId < bosses.size()) doors.insert(std::make_pair(data->entry, DoorInfo(&bosses[data->bossId], data->type, BoundaryType(data->boundary)))); ++data; } sLog->outDebug(LOG_FILTER_TSCR, "InstanceScript::LoadDoorData: " UI64FMTD " doors loaded.", uint64(doors.size())); } void InstanceScript::UpdateMinionState(Creature *minion, EncounterState state) { switch (state) { case NOT_STARTED: if (!minion->isAlive()) minion->Respawn(); else if (minion->isInCombat()) minion->AI()->EnterEvadeMode(); break; case IN_PROGRESS: if (!minion->isAlive()) minion->Respawn(); else if (!minion->getVictim()) minion->AI()->DoZoneInCombat(); break; default: break; } } void InstanceScript::UpdateDoorState(GameObject *door) { DoorInfoMap::iterator lower = doors.lower_bound(door->GetEntry()); DoorInfoMap::iterator upper = doors.upper_bound(door->GetEntry()); if (lower == upper) return; bool open = true; for (DoorInfoMap::iterator itr = lower; itr != upper && open; ++itr) { switch (itr->second.type) { case DOOR_TYPE_ROOM: open = (itr->second.bossInfo->state != IN_PROGRESS); break; case DOOR_TYPE_PASSAGE: open = (itr->second.bossInfo->state == DONE); break; case DOOR_TYPE_SPAWN_HOLE: open = (itr->second.bossInfo->state == IN_PROGRESS); break; default: break; } } door->SetGoState(open ? GO_STATE_ACTIVE : GO_STATE_READY); } void InstanceScript::AddDoor(GameObject *door, bool add) { DoorInfoMap::iterator lower = doors.lower_bound(door->GetEntry()); DoorInfoMap::iterator upper = doors.upper_bound(door->GetEntry()); if (lower == upper) return; for (DoorInfoMap::iterator itr = lower; itr != upper; ++itr) { if (add) { itr->second.bossInfo->door[itr->second.type].insert(door); switch (itr->second.boundary) { default: case BOUNDARY_NONE: break; case BOUNDARY_N: case BOUNDARY_S: itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionX(); break; case BOUNDARY_E: case BOUNDARY_W: itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionY(); break; case BOUNDARY_NW: case BOUNDARY_SE: itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionX() + door->GetPositionY(); break; case BOUNDARY_NE: case BOUNDARY_SW: itr->second.bossInfo->boundary[itr->second.boundary] = door->GetPositionX() - door->GetPositionY(); break; } } else itr->second.bossInfo->door[itr->second.type].erase(door); } if (add) UpdateDoorState(door); } void InstanceScript::AddMinion(Creature *minion, bool add) { MinionInfoMap::iterator itr = minions.find(minion->GetEntry()); if (itr == minions.end()) return; if (add) itr->second.bossInfo->minion.insert(minion); else itr->second.bossInfo->minion.erase(minion); } bool InstanceScript::SetBossState(uint32 id, EncounterState state) { if (id < bosses.size()) { BossInfo *bossInfo = &bosses[id]; if (bossInfo->state == TO_BE_DECIDED) // loading { bossInfo->state = state; //sLog->outError("Inialize boss %u state as %u.", id, (uint32)state); return false; } else { if (bossInfo->state == state) return false; if (state == DONE) for (MinionSet::iterator i = bossInfo->minion.begin(); i != bossInfo->minion.end(); ++i) if ((*i)->isWorldBoss() && (*i)->isAlive()) return false; bossInfo->state = state; SaveToDB(); } for (uint32 type = 0; type < MAX_DOOR_TYPES; ++type) for (DoorSet::iterator i = bossInfo->door[type].begin(); i != bossInfo->door[type].end(); ++i) UpdateDoorState(*i); for (MinionSet::iterator i = bossInfo->minion.begin(); i != bossInfo->minion.end(); ++i) UpdateMinionState(*i, state); return true; } return false; } std::string InstanceScript::LoadBossState(const char * data) { if (!data) return NULL; std::istringstream loadStream(data); uint32 buff; uint32 bossId = 0; for (std::vector<BossInfo>::iterator i = bosses.begin(); i != bosses.end(); ++i, ++bossId) { loadStream >> buff; if (buff < TO_BE_DECIDED) SetBossState(bossId, (EncounterState)buff); } return loadStream.str(); } std::string InstanceScript::GetBossSaveData() { std::ostringstream saveStream; for (std::vector<BossInfo>::iterator i = bosses.begin(); i != bosses.end(); ++i) saveStream << (uint32)i->state << ' '; return saveStream.str(); } void InstanceScript::DoUseDoorOrButton(uint64 uiGuid, uint32 uiWithRestoreTime, bool bUseAlternativeState) { if (!uiGuid) return; GameObject* pGo = instance->GetGameObject(uiGuid); if (pGo) { if (pGo->GetGoType() == GAMEOBJECT_TYPE_DOOR || pGo->GetGoType() == GAMEOBJECT_TYPE_BUTTON) { if (pGo->getLootState() == GO_READY) pGo->UseDoorOrButton(uiWithRestoreTime, bUseAlternativeState); else if (pGo->getLootState() == GO_ACTIVATED) pGo->ResetDoorOrButton(); } else sLog->outError("SD2: Script call DoUseDoorOrButton, but gameobject entry %u is type %u.", pGo->GetEntry(), pGo->GetGoType()); } } void InstanceScript::DoRespawnGameObject(uint64 uiGuid, uint32 uiTimeToDespawn) { if (GameObject* pGo = instance->GetGameObject(uiGuid)) { //not expect any of these should ever be handled if (pGo->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE || pGo->GetGoType() == GAMEOBJECT_TYPE_DOOR || pGo->GetGoType() == GAMEOBJECT_TYPE_BUTTON || pGo->GetGoType() == GAMEOBJECT_TYPE_TRAP) return; if (pGo->isSpawned()) return; pGo->SetRespawnTime(uiTimeToDespawn); } } void InstanceScript::DoUpdateWorldState(uint32 uiStateId, uint32 uiStateData) { Map::PlayerList const& lPlayers = instance->GetPlayers(); if (!lPlayers.isEmpty()) { for (Map::PlayerList::const_iterator itr = lPlayers.begin(); itr != lPlayers.end(); ++itr) if (Player *pPlayer = itr->getSource()) pPlayer->SendUpdateWorldState(uiStateId, uiStateData); } else sLog->outDebug(LOG_FILTER_TSCR, "TSCR: DoUpdateWorldState attempt send data but no players in map."); } // Send Notify to all players in instance void InstanceScript::DoSendNotifyToInstance(const char *format, ...) { InstanceMap::PlayerList const &PlayerList = instance->GetPlayers(); InstanceMap::PlayerList::const_iterator i; if (!PlayerList.isEmpty()) { va_list ap; va_start(ap, format); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (Player *pPlayer = i->getSource()) if (WorldSession *pSession = pPlayer->GetSession()) pSession->SendNotification(format, ap); } va_end(ap); } } // Update Achievement Criteria for all players in instance void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player *pPlayer = i->getSource()) pPlayer->UpdateAchievementCriteria(type, miscValue1, miscValue2, unit); } // Start timed achievement for all players in instance void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player *pPlayer = i->getSource()) pPlayer->GetAchievementMgr().StartTimedAchievement(type, entry); } // Stop timed achievement for all players in instance void InstanceScript::DoStopTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player *pPlayer = i->getSource()) pPlayer->GetAchievementMgr().RemoveTimedAchievement(type, entry); } // Remove Auras due to Spell on all players in instance void InstanceScript::DoRemoveAurasDueToSpellOnPlayers(uint32 spell) { Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) { if (Player* player = itr->getSource()) { player->RemoveAurasDueToSpell(spell); if (Pet* pet = player->GetPet()) pet->RemoveAurasDueToSpell(spell); } } } } // Cast spell on all players in instance void InstanceScript::DoCastSpellOnPlayers(uint32 spell) { Map::PlayerList const &PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* player = i->getSource()) player->CastSpell(player, spell, true); } bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/ /*= NULL*/, uint32 /*miscvalue1*/ /*= 0*/) { sLog->outError("Achievement system call InstanceScript::CheckAchievementCriteriaMeet but instance script for map %u not have implementation for achievement criteria %u", instance->GetId(), criteria_id); return false; } void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= NULL*/, uint8 param1 /*= 0*/, uint8 param2 /*= 0*/) { // size of this packet is at most 15 (usually less) WorldPacket data(SMSG_UPDATE_INSTANCE_ENCOUNTER_UNIT, 15); data << uint32(type); switch (type) { case ENCOUNTER_FRAME_ADD: case ENCOUNTER_FRAME_REMOVE: case 2: data.append(unit->GetPackGUID()); data << uint8(param1); break; case 3: case 4: case 6: data << uint8(param1); data << uint8(param2); break; case 5: data << uint8(param1); break; case 7: default: break; } instance->SendToPlayers(&data); } void InstanceScript::UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source) { DungeonEncounterList const* encounters = sObjectMgr->GetDungeonEncounterList(instance->GetId(), instance->GetDifficulty()); if (!encounters) return; for (DungeonEncounterList::const_iterator itr = encounters->begin(); itr != encounters->end(); ++itr) { if ((*itr)->creditType == type && (*itr)->creditEntry == creditEntry) { completedEncounters |= 1 << (*itr)->dbcEntry->encounterIndex; sLog->outDebug(LOG_FILTER_TSCR, "Instance %s (instanceId %u) completed encounter %s", instance->GetMapName(), instance->GetInstanceId(), (*itr)->dbcEntry->encounterName[0]); if (uint32 dungeonId = (*itr)->lastEncounterDungeon) { Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) if (Player* player = i->getSource()) if (!source || player->IsAtGroupRewardDistance(source)) sLFGMgr->RewardDungeonDonefor (dungeonId, player); } return; } } }
Kr4v3n5/Core
src/server/game/Instances/InstanceScript.cpp
C++
gpl-2.0
15,351
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPixmap> #include <QPoint> class QLabel; class QLineEdit; class QMouseEvent; class QTextEdit; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = 0); protected: void mousePressEvent(QMouseEvent *event); private: QLabel *iconLabel; QLineEdit *nameEdit; QPixmap iconPixmap; QPoint dragStartPosition; QTextEdit *commentEdit; }; #endif
librelab/qtmoko-test
qtopiacore/qt/doc/src/snippets/dragging/mainwindow.h
C
gpl-2.0
2,424
/* Copyright (c) 2015-2016, 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. */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/of_gpio.h> #include <linux/platform_device.h> #include <linux/device.h> #include <linux/printk.h> #include <linux/ratelimit.h> #include <linux/list.h> #include <linux/bitops.h> #include <linux/delay.h> #include <linux/pm_runtime.h> #include <linux/kernel.h> #include <linux/input.h> #include <linux/firmware.h> #include <linux/completion.h> #include <sound/soc.h> #include <sound/jack.h> #include <sound/sounddebug.h> #include "wcd-mbhc-v2.h" #include "wcdcal-hwdep.h" #define WCD_MBHC_JACK_MASK (SND_JACK_HEADSET | SND_JACK_OC_HPHL | \ SND_JACK_OC_HPHR | SND_JACK_LINEOUT | \ SND_JACK_MECHANICAL | SND_JACK_MICROPHONE2 | \ SND_JACK_UNSUPPORTED) #define WCD_MBHC_JACK_BUTTON_MASK (SND_JACK_BTN_0 | SND_JACK_BTN_1 | \ SND_JACK_BTN_2 | SND_JACK_BTN_3 | \ SND_JACK_BTN_4 | SND_JACK_BTN_5 | \ SND_JACK_BTN_6 | SND_JACK_BTN_7) #define OCP_ATTEMPT 1 #define HS_DETECT_PLUG_TIME_MS (800) #define SPECIAL_HS_DETECT_TIME_MS (2 * 1000) #define MBHC_BUTTON_PRESS_THRESHOLD_MIN 250 #define GND_MIC_SWAP_THRESHOLD 4 #define WCD_FAKE_REMOVAL_MIN_PERIOD_MS 100 #define HS_VREF_MIN_VAL 1400 #define FW_READ_ATTEMPTS 15 #define FW_READ_TIMEOUT 4000000 #define FAKE_REM_RETRY_ATTEMPTS 3 #define MAX_IMPED 60000 #define WCD_MBHC_BTN_PRESS_COMPL_TIMEOUT_MS 50 #define ANC_DETECT_RETRY_CNT 7 #define WCD_MBHC_SPL_HS_CNT 1 static int det_extn_cable_en; module_param(det_extn_cable_en, int, S_IRUGO | S_IWUSR | S_IWGRP); MODULE_PARM_DESC(det_extn_cable_en, "enable/disable extn cable detect"); enum wcd_mbhc_cs_mb_en_flag { WCD_MBHC_EN_CS = 0, WCD_MBHC_EN_MB, WCD_MBHC_EN_PULLUP, WCD_MBHC_EN_NONE, }; static void wcd_mbhc_jack_report(struct wcd_mbhc *mbhc, struct snd_soc_jack *jack, int status, int mask) { snd_soc_jack_report(jack, status, mask); } static void __hphocp_off_report(struct wcd_mbhc *mbhc, u32 jack_status, int irq) { struct snd_soc_codec *codec = mbhc->codec; dev_dbg(codec->dev, "%s: clear ocp status %x\n", __func__, jack_status); if (mbhc->hph_status & jack_status) { mbhc->hph_status &= ~jack_status; wcd_mbhc_jack_report(mbhc, &mbhc->headset_jack, mbhc->hph_status, WCD_MBHC_JACK_MASK); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_OCP_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_OCP_FSM_EN, 1); /* * reset retry counter as PA is turned off signifying * start of new OCP detection session */ if (mbhc->intr_ids->hph_left_ocp) mbhc->hphlocp_cnt = 0; else mbhc->hphrocp_cnt = 0; mbhc->mbhc_cb->irq_control(codec, irq, true); } } static void hphrocp_off_report(struct wcd_mbhc *mbhc, u32 jack_status) { __hphocp_off_report(mbhc, SND_JACK_OC_HPHR, mbhc->intr_ids->hph_right_ocp); } static void hphlocp_off_report(struct wcd_mbhc *mbhc, u32 jack_status) { __hphocp_off_report(mbhc, SND_JACK_OC_HPHL, mbhc->intr_ids->hph_left_ocp); } static void wcd_program_hs_vref(struct wcd_mbhc *mbhc) { struct wcd_mbhc_plug_type_cfg *plug_type_cfg; struct snd_soc_codec *codec = mbhc->codec; u32 reg_val; plug_type_cfg = WCD_MBHC_CAL_PLUG_TYPE_PTR(mbhc->mbhc_cfg->calibration); reg_val = ((plug_type_cfg->v_hs_max - HS_VREF_MIN_VAL) / 100); dev_dbg(codec->dev, "%s: reg_val = %x\n", __func__, reg_val); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_HS_VREF, reg_val); } static void wcd_program_btn_threshold(const struct wcd_mbhc *mbhc, bool micbias) { struct wcd_mbhc_btn_detect_cfg *btn_det; struct snd_soc_codec *codec = mbhc->codec; struct snd_soc_card *card = codec->component.card; s16 *btn_low, *btn_high; if (mbhc->mbhc_cfg->calibration == NULL) { dev_err(card->dev, "%s: calibration data is NULL\n", __func__); return; } btn_det = WCD_MBHC_CAL_BTN_DET_PTR(mbhc->mbhc_cfg->calibration); btn_low = btn_det->_v_btn_low; btn_high = ((void *)&btn_det->_v_btn_low) + (sizeof(btn_det->_v_btn_low[0]) * btn_det->num_btn); mbhc->mbhc_cb->set_btn_thr(codec, btn_low, btn_high, btn_det->num_btn, micbias); } static void wcd_enable_curr_micbias(const struct wcd_mbhc *mbhc, const enum wcd_mbhc_cs_mb_en_flag cs_mb_en) { /* * Some codecs handle micbias/pullup enablement in codec * drivers itself and micbias is not needed for regular * plug type detection. So if micbias_control callback function * is defined, just return. */ if (mbhc->mbhc_cb->mbhc_micbias_control) return; pr_debug("%s: enter, cs_mb_en: %d\n", __func__, cs_mb_en); switch (cs_mb_en) { case WCD_MBHC_EN_CS: WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_MICB_CTRL, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 3); /* Program Button threshold registers as per CS */ wcd_program_btn_threshold(mbhc, false); break; case WCD_MBHC_EN_MB: WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 1); /* Disable PULL_UP_EN & enable MICBIAS */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_MICB_CTRL, 2); /* Program Button threshold registers as per MICBIAS */ wcd_program_btn_threshold(mbhc, true); break; case WCD_MBHC_EN_PULLUP: WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 3); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 1); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_MICB_CTRL, 1); /* Program Button threshold registers as per MICBIAS */ wcd_program_btn_threshold(mbhc, true); break; case WCD_MBHC_EN_NONE: WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 1); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_MICB_CTRL, 0); break; default: pr_debug("%s: Invalid parameter", __func__); break; } pr_debug("%s: exit\n", __func__); } static const char *wcd_mbhc_get_event_string(int event) { switch (event) { case WCD_EVENT_PRE_MICBIAS_2_OFF: return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_MICBIAS_2_OFF); case WCD_EVENT_POST_MICBIAS_2_OFF: return WCD_MBHC_STRINGIFY(WCD_EVENT_POST_MICBIAS_2_OFF); case WCD_EVENT_PRE_MICBIAS_2_ON: return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_MICBIAS_2_ON); case WCD_EVENT_POST_MICBIAS_2_ON: return WCD_MBHC_STRINGIFY(WCD_EVENT_POST_MICBIAS_2_ON); case WCD_EVENT_PRE_HPHL_PA_ON: return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_HPHL_PA_ON); case WCD_EVENT_POST_HPHL_PA_OFF: return WCD_MBHC_STRINGIFY(WCD_EVENT_POST_HPHL_PA_OFF); case WCD_EVENT_PRE_HPHR_PA_ON: return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_HPHR_PA_ON); case WCD_EVENT_POST_HPHR_PA_OFF: return WCD_MBHC_STRINGIFY(WCD_EVENT_POST_HPHR_PA_OFF); case WCD_EVENT_PRE_HPHR_PA_OFF: return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_HPHR_PA_OFF); case WCD_EVENT_PRE_HPHL_PA_OFF: return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_HPHL_PA_OFF); case WCD_EVENT_POST_DAPM_MICBIAS_2_ON: return WCD_MBHC_STRINGIFY(WCD_EVENT_POST_DAPM_MICBIAS_2_ON); case WCD_EVENT_PRE_DAPM_MICBIAS_2_ON: return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_DAPM_MICBIAS_2_ON); case WCD_EVENT_POST_DAPM_MICBIAS_2_OFF: return WCD_MBHC_STRINGIFY(WCD_EVENT_POST_DAPM_MICBIAS_2_OFF); case WCD_EVENT_PRE_DAPM_MICBIAS_2_OFF: return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_DAPM_MICBIAS_2_OFF); case WCD_EVENT_INVALID: default: return WCD_MBHC_STRINGIFY(WCD_EVENT_INVALID); } } static int wcd_event_notify(struct notifier_block *self, unsigned long val, void *data) { struct wcd_mbhc *mbhc = (struct wcd_mbhc *)data; enum wcd_notify_event event = (enum wcd_notify_event)val; struct snd_soc_codec *codec = mbhc->codec; bool micbias2 = false; bool micbias1 = false; u8 fsm_en; pr_debug("%s: event %s (%d)\n", __func__, wcd_mbhc_get_event_string(event), event); if (mbhc->mbhc_cb->micbias_enable_status) { micbias2 = mbhc->mbhc_cb->micbias_enable_status(mbhc, MIC_BIAS_2); micbias1 = mbhc->mbhc_cb->micbias_enable_status(mbhc, MIC_BIAS_1); } switch (event) { /* MICBIAS usage change */ case WCD_EVENT_POST_DAPM_MICBIAS_2_ON: mbhc->is_hs_recording = true; pr_debug("%s: is_capture: %d\n", __func__, mbhc->is_hs_recording); break; case WCD_EVENT_POST_MICBIAS_2_ON: if (!mbhc->micbias_enable) goto out_micb_en; if (mbhc->mbhc_cb->mbhc_common_micb_ctrl) { mbhc->mbhc_cb->mbhc_common_micb_ctrl(codec, MBHC_COMMON_MICB_PRECHARGE, true); mbhc->mbhc_cb->mbhc_common_micb_ctrl(codec, MBHC_COMMON_MICB_SET_VAL, true); /* * Special headset needs MICBIAS as 2.7V so wait for * 50 msec for the MICBIAS to reach 2.7 volts. */ msleep(50); } if (mbhc->mbhc_cb->set_auto_zeroing) mbhc->mbhc_cb->set_auto_zeroing(codec, true); if (mbhc->mbhc_cb->mbhc_common_micb_ctrl) mbhc->mbhc_cb->mbhc_common_micb_ctrl(codec, MBHC_COMMON_MICB_PRECHARGE, false); out_micb_en: /* Disable current source if micbias enabled */ if (mbhc->mbhc_cb->mbhc_micbias_control) { WCD_MBHC_REG_READ(WCD_MBHC_FSM_EN, fsm_en); if (fsm_en) WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 0); } else { mbhc->is_hs_recording = true; wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); } /* configure cap settings properly when micbias is enabled */ if (mbhc->mbhc_cb->set_cap_mode) mbhc->mbhc_cb->set_cap_mode(codec, micbias1, true); break; case WCD_EVENT_PRE_MICBIAS_2_OFF: /* * Before MICBIAS_2 is turned off, if FSM is enabled, * make sure current source is enabled so as to detect * button press/release events */ if (mbhc->mbhc_cb->mbhc_micbias_control && !mbhc->micbias_enable) { WCD_MBHC_REG_READ(WCD_MBHC_FSM_EN, fsm_en); if (fsm_en) WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 3); } break; /* MICBIAS usage change */ case WCD_EVENT_POST_DAPM_MICBIAS_2_OFF: mbhc->is_hs_recording = false; pr_debug("%s: is_capture: %d\n", __func__, mbhc->is_hs_recording); break; case WCD_EVENT_POST_MICBIAS_2_OFF: if (mbhc->mbhc_cb->set_auto_zeroing) mbhc->mbhc_cb->set_auto_zeroing(codec, false); if (mbhc->mbhc_cb->set_micbias_value) mbhc->mbhc_cb->set_micbias_value(codec); if (!mbhc->mbhc_cb->mbhc_micbias_control) mbhc->is_hs_recording = false; /* Enable PULL UP if PA's are enabled */ if ((test_bit(WCD_MBHC_EVENT_PA_HPHL, &mbhc->event_state)) || (test_bit(WCD_MBHC_EVENT_PA_HPHR, &mbhc->event_state))) /* enable pullup and cs, disable mb */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_PULLUP); else /* enable current source and disable mb, pullup*/ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_CS); /* configure cap settings properly when micbias is disabled */ if (mbhc->mbhc_cb->set_cap_mode) mbhc->mbhc_cb->set_cap_mode(codec, micbias1, false); break; case WCD_EVENT_PRE_HPHL_PA_OFF: mutex_lock(&mbhc->hphl_pa_lock); break; case WCD_EVENT_POST_HPHL_PA_OFF: clear_bit(WCD_MBHC_HPHL_PA_OFF_ACK, &mbhc->hph_pa_dac_state); if (mbhc->hph_status & SND_JACK_OC_HPHL) hphlocp_off_report(mbhc, SND_JACK_OC_HPHL); clear_bit(WCD_MBHC_EVENT_PA_HPHL, &mbhc->event_state); /* check if micbias is enabled */ if (micbias2) /* Disable cs, pullup & enable micbias */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); else /* Disable micbias, pullup & enable cs */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_CS); mutex_unlock(&mbhc->hphl_pa_lock); break; case WCD_EVENT_PRE_HPHR_PA_OFF: mutex_lock(&mbhc->hphr_pa_lock); break; case WCD_EVENT_POST_HPHR_PA_OFF: clear_bit(WCD_MBHC_HPHR_PA_OFF_ACK, &mbhc->hph_pa_dac_state); if (mbhc->hph_status & SND_JACK_OC_HPHR) hphrocp_off_report(mbhc, SND_JACK_OC_HPHR); clear_bit(WCD_MBHC_EVENT_PA_HPHR, &mbhc->event_state); /* check if micbias is enabled */ if (micbias2) /* Disable cs, pullup & enable micbias */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); else /* Disable micbias, pullup & enable cs */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_CS); mutex_unlock(&mbhc->hphr_pa_lock); break; case WCD_EVENT_PRE_HPHL_PA_ON: set_bit(WCD_MBHC_EVENT_PA_HPHL, &mbhc->event_state); /* check if micbias is enabled */ if (micbias2) /* Disable cs, pullup & enable micbias */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); else /* Disable micbias, enable pullup & cs */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_PULLUP); break; case WCD_EVENT_PRE_HPHR_PA_ON: set_bit(WCD_MBHC_EVENT_PA_HPHR, &mbhc->event_state); /* check if micbias is enabled */ if (micbias2) /* Disable cs, pullup & enable micbias */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); else /* Disable micbias, enable pullup & cs */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_PULLUP); break; default: break; } return 0; } static int wcd_cancel_btn_work(struct wcd_mbhc *mbhc) { int r; r = cancel_delayed_work_sync(&mbhc->mbhc_btn_dwork); /* * if scheduled mbhc.mbhc_btn_dwork is canceled from here, * we have to unlock from here instead btn_work */ if (r) mbhc->mbhc_cb->lock_sleep(mbhc, false); return r; } static bool wcd_swch_level_remove(struct wcd_mbhc *mbhc) { u16 result2; WCD_MBHC_REG_READ(WCD_MBHC_SWCH_LEVEL_REMOVE, result2); return (result2) ? true : false; } /* should be called under interrupt context that hold suspend */ static void wcd_schedule_hs_detect_plug(struct wcd_mbhc *mbhc, struct work_struct *work) { pr_debug("%s: scheduling correct_swch_plug\n", __func__); WCD_MBHC_RSC_ASSERT_LOCKED(mbhc); mbhc->hs_detect_work_stop = false; mbhc->mbhc_cb->lock_sleep(mbhc, true); schedule_work(work); } /* called under codec_resource_lock acquisition */ static void wcd_cancel_hs_detect_plug(struct wcd_mbhc *mbhc, struct work_struct *work) { pr_debug("%s: Canceling correct_plug_swch\n", __func__); mbhc->hs_detect_work_stop = true; WCD_MBHC_RSC_UNLOCK(mbhc); if (cancel_work_sync(work)) { pr_debug("%s: correct_plug_swch is canceled\n", __func__); mbhc->mbhc_cb->lock_sleep(mbhc, false); } WCD_MBHC_RSC_LOCK(mbhc); } static void wcd_mbhc_clr_and_turnon_hph_padac(struct wcd_mbhc *mbhc) { bool pa_turned_on = false; u8 wg_time; WCD_MBHC_REG_READ(WCD_MBHC_HPH_CNP_WG_TIME, wg_time); wg_time += 1; mutex_lock(&mbhc->hphr_pa_lock); if (test_and_clear_bit(WCD_MBHC_HPHR_PA_OFF_ACK, &mbhc->hph_pa_dac_state)) { pr_debug("%s: HPHR clear flag and enable PA\n", __func__); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_HPHR_PA_EN, 1); pa_turned_on = true; } mutex_unlock(&mbhc->hphr_pa_lock); mutex_lock(&mbhc->hphl_pa_lock); if (test_and_clear_bit(WCD_MBHC_HPHL_PA_OFF_ACK, &mbhc->hph_pa_dac_state)) { pr_debug("%s: HPHL clear flag and enable PA\n", __func__); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_HPHL_PA_EN, 1); pa_turned_on = true; } mutex_unlock(&mbhc->hphl_pa_lock); if (pa_turned_on) { pr_debug("%s: PA was turned on by MBHC and not by DAPM\n", __func__); usleep_range(wg_time * 1000, wg_time * 1000 + 50); } } static bool wcd_mbhc_is_hph_pa_on(struct wcd_mbhc *mbhc) { bool hph_pa_on = false; WCD_MBHC_REG_READ(WCD_MBHC_HPH_PA_EN, hph_pa_on); return (hph_pa_on) ? true : false; } static void wcd_mbhc_set_and_turnoff_hph_padac(struct wcd_mbhc *mbhc) { u8 wg_time; WCD_MBHC_REG_READ(WCD_MBHC_HPH_CNP_WG_TIME, wg_time); wg_time += 1; /* If headphone PA is on, check if userspace receives * removal event to sync-up PA's state */ if (wcd_mbhc_is_hph_pa_on(mbhc)) { pr_debug("%s PA is on, setting PA_OFF_ACK\n", __func__); set_bit(WCD_MBHC_HPHL_PA_OFF_ACK, &mbhc->hph_pa_dac_state); set_bit(WCD_MBHC_HPHR_PA_OFF_ACK, &mbhc->hph_pa_dac_state); } else { pr_debug("%s PA is off\n", __func__); } WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_HPH_PA_EN, 0); usleep_range(wg_time * 1000, wg_time * 1000 + 50); } int wcd_mbhc_get_impedance(struct wcd_mbhc *mbhc, uint32_t *zl, uint32_t *zr) { *zl = mbhc->zl; *zr = mbhc->zr; if (*zl && *zr) return 0; else return -EINVAL; } static void wcd_mbhc_hs_elec_irq(struct wcd_mbhc *mbhc, int irq_type, bool enable) { int irq; WCD_MBHC_RSC_ASSERT_LOCKED(mbhc); if (irq_type == WCD_MBHC_ELEC_HS_INS) irq = mbhc->intr_ids->mbhc_hs_ins_intr; else if (irq_type == WCD_MBHC_ELEC_HS_REM) irq = mbhc->intr_ids->mbhc_hs_rem_intr; else { pr_debug("%s: irq_type: %d, enable: %d\n", __func__, irq_type, enable); return; } pr_debug("%s: irq: %d, enable: %d, intr_status:%lu\n", __func__, irq, enable, mbhc->intr_status); if ((test_bit(irq_type, &mbhc->intr_status)) != enable) { mbhc->mbhc_cb->irq_control(mbhc->codec, irq, enable); if (enable) set_bit(irq_type, &mbhc->intr_status); else clear_bit(irq_type, &mbhc->intr_status); } } static void wcd_mbhc_report_plug(struct wcd_mbhc *mbhc, int insertion, enum snd_jack_types jack_type) { WCD_MBHC_RSC_ASSERT_LOCKED(mbhc); pr_debug("%s: enter insertion %d hph_status %x\n", __func__, insertion, mbhc->hph_status); if (!insertion) { /* Report removal */ mbhc->hph_status &= ~jack_type; /* * cancel possibly scheduled btn work and * report release if we reported button press */ if (wcd_cancel_btn_work(mbhc)) { pr_debug("%s: button press is canceled\n", __func__); } else if (mbhc->buttons_pressed) { pr_debug("%s: release of button press%d\n", __func__, jack_type); wcd_mbhc_jack_report(mbhc, &mbhc->button_jack, 0, mbhc->buttons_pressed); mbhc->buttons_pressed &= ~WCD_MBHC_JACK_BUTTON_MASK; } if (mbhc->micbias_enable) { if (mbhc->mbhc_cb->mbhc_micbias_control) mbhc->mbhc_cb->mbhc_micbias_control( mbhc->codec, MIC_BIAS_2, MICB_DISABLE); if (mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic) mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic( mbhc->codec, MIC_BIAS_2, false); mbhc->micbias_enable = false; } mbhc->hph_type = WCD_MBHC_HPH_NONE; mbhc->zl = mbhc->zr = 0; pr_err("%s: Reporting removal %d(%x)\n", __func__, jack_type, mbhc->hph_status); switch_set_state(&mbhc->wcd9xxx_sdev,0); wcd_mbhc_jack_report(mbhc, &mbhc->headset_jack, mbhc->hph_status, WCD_MBHC_JACK_MASK); wcd_mbhc_set_and_turnoff_hph_padac(mbhc); hphrocp_off_report(mbhc, SND_JACK_OC_HPHR); hphlocp_off_report(mbhc, SND_JACK_OC_HPHL); mbhc->current_plug = MBHC_PLUG_TYPE_NONE; } else { /* * Report removal of current jack type. * Headphone to headset shouldn't report headphone * removal. */ if (mbhc->mbhc_cfg->detect_extn_cable && (mbhc->current_plug == MBHC_PLUG_TYPE_HIGH_HPH || jack_type == SND_JACK_LINEOUT) && (mbhc->hph_status && mbhc->hph_status != jack_type)) { if (mbhc->micbias_enable && mbhc->current_plug == MBHC_PLUG_TYPE_HEADSET) { if (mbhc->mbhc_cb->mbhc_micbias_control) mbhc->mbhc_cb->mbhc_micbias_control( mbhc->codec, MIC_BIAS_2, MICB_DISABLE); if (mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic) mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic( mbhc->codec, MIC_BIAS_2, false); mbhc->micbias_enable = false; } mbhc->hph_type = WCD_MBHC_HPH_NONE; mbhc->zl = mbhc->zr = 0; pr_debug("%s: Reporting removal (%x)\n", __func__, mbhc->hph_status); wcd_mbhc_jack_report(mbhc, &mbhc->headset_jack, 0, WCD_MBHC_JACK_MASK); if (mbhc->hph_status == SND_JACK_LINEOUT) { pr_debug("%s: Enable micbias\n", __func__); /* Disable current source and enable micbias */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); pr_debug("%s: set up elec removal detection\n", __func__); WCD_MBHC_REG_UPDATE_BITS( WCD_MBHC_ELECT_DETECTION_TYPE, 0); usleep_range(200, 210); wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_REM, true); } mbhc->hph_status &= ~(SND_JACK_HEADSET | SND_JACK_LINEOUT | SND_JACK_ANC_HEADPHONE | SND_JACK_UNSUPPORTED); } if (mbhc->current_plug == MBHC_PLUG_TYPE_HEADSET && jack_type == SND_JACK_HEADPHONE) mbhc->hph_status &= ~SND_JACK_HEADSET; /* Report insertion */ if (jack_type == SND_JACK_HEADPHONE) mbhc->current_plug = MBHC_PLUG_TYPE_HEADPHONE; else if (jack_type == SND_JACK_UNSUPPORTED) mbhc->current_plug = MBHC_PLUG_TYPE_GND_MIC_SWAP; else if (jack_type == SND_JACK_HEADSET) { mbhc->current_plug = MBHC_PLUG_TYPE_HEADSET; mbhc->jiffies_atreport = jiffies; } else if (jack_type == SND_JACK_LINEOUT) { mbhc->current_plug = MBHC_PLUG_TYPE_HIGH_HPH; } else if (jack_type == SND_JACK_ANC_HEADPHONE) mbhc->current_plug = MBHC_PLUG_TYPE_ANC_HEADPHONE; if (mbhc->impedance_detect && mbhc->mbhc_cb->compute_impedance && (mbhc->mbhc_cfg->linein_th != 0)) { mbhc->mbhc_cb->compute_impedance(mbhc, &mbhc->zl, &mbhc->zr); if ((mbhc->zl > mbhc->mbhc_cfg->linein_th && mbhc->zl < MAX_IMPED) && (mbhc->zr > mbhc->mbhc_cfg->linein_th && mbhc->zr < MAX_IMPED) && (jack_type == SND_JACK_HEADPHONE)) { jack_type = SND_JACK_LINEOUT; mbhc->current_plug = MBHC_PLUG_TYPE_HIGH_HPH; if (mbhc->hph_status) { mbhc->hph_status &= ~(SND_JACK_HEADSET | SND_JACK_LINEOUT | SND_JACK_UNSUPPORTED); wcd_mbhc_jack_report(mbhc, &mbhc->headset_jack, mbhc->hph_status, WCD_MBHC_JACK_MASK); } pr_debug("%s: Marking jack type as SND_JACK_LINEOUT\n", __func__); } } mbhc->hph_status |= jack_type; switch(mbhc->current_plug){ case MBHC_PLUG_TYPE_HEADPHONE: case MBHC_PLUG_TYPE_HIGH_HPH: mbhc->mbhc_cfg->headset_type = 0; switch_set_state(&mbhc->wcd9xxx_sdev,2); break; case MBHC_PLUG_TYPE_GND_MIC_SWAP: mbhc->mbhc_cfg->headset_type = 0; switch_set_state(&mbhc->wcd9xxx_sdev,1); break; case MBHC_PLUG_TYPE_HEADSET: mbhc->mbhc_cfg->headset_type = 1; switch_set_state(&mbhc->wcd9xxx_sdev,1); break; default: mbhc->mbhc_cfg->headset_type = 0; switch_set_state(&mbhc->wcd9xxx_sdev,0); break; } pr_err("%s: Reporting insertion %d(%x)\n", __func__, jack_type, mbhc->hph_status); pr_debug("%s: Reporting insertion %d(%x)\n", __func__, jack_type, mbhc->hph_status); wcd_mbhc_jack_report(mbhc, &mbhc->headset_jack, (mbhc->hph_status | SND_JACK_MECHANICAL), WCD_MBHC_JACK_MASK); wcd_mbhc_clr_and_turnon_hph_padac(mbhc); } pr_debug("%s: leave hph_status %x\n", __func__, mbhc->hph_status); } static bool wcd_mbhc_detect_anc_plug_type(struct wcd_mbhc *mbhc) { bool anc_mic_found = false; u16 val, hs_comp_res, btn_status = 0; unsigned long retry = 0; int valid_plug_cnt = 0, invalid_plug_cnt = 0; int btn_status_cnt = 0; bool is_check_btn_press = false; if (mbhc->mbhc_cfg->anc_micbias < MIC_BIAS_1 || mbhc->mbhc_cfg->anc_micbias > MIC_BIAS_4) return false; if (!mbhc->mbhc_cb->mbhc_micbias_control) return false; WCD_MBHC_REG_READ(WCD_MBHC_FSM_EN, val); if (val) WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 0); mbhc->mbhc_cb->mbhc_micbias_control(mbhc->codec, mbhc->mbhc_cfg->anc_micbias, MICB_ENABLE); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_MUX_CTL, 0x2); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ANC_DET_EN, 1); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 1); /* * wait for button debounce time 20ms. If 4-pole plug is inserted * into 5-pole jack, then there will be a button press interrupt * during anc plug detection. In that case though Hs_comp_res is 0, * it should not be declared as ANC plug type */ usleep_range(20000, 20100); /* * After enabling FSM, to handle slow insertion scenarios, * check hs_comp_result for few times to see if the IN3 voltage * is below the Vref */ do { if (wcd_swch_level_remove(mbhc)) { pr_debug("%s: Switch level is low\n", __func__); goto exit; } pr_debug("%s: Retry attempt %lu\n", __func__, retry + 1); WCD_MBHC_REG_READ(WCD_MBHC_HS_COMP_RESULT, hs_comp_res); if (!hs_comp_res) { valid_plug_cnt++; is_check_btn_press = true; } else invalid_plug_cnt++; /* Wait 1ms before taking another reading */ usleep_range(1000, 1100); WCD_MBHC_REG_READ(WCD_MBHC_FSM_STATUS, btn_status); if (btn_status) btn_status_cnt++; retry++; } while (retry < ANC_DETECT_RETRY_CNT); pr_debug("%s: valid: %d, invalid: %d, btn_status_cnt: %d\n", __func__, valid_plug_cnt, invalid_plug_cnt, btn_status_cnt); /* decision logic */ if ((valid_plug_cnt > invalid_plug_cnt) && is_check_btn_press && (btn_status_cnt == 0)) anc_mic_found = true; exit: if (!val) WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ANC_DET_EN, 0); mbhc->mbhc_cb->mbhc_micbias_control(mbhc->codec, mbhc->mbhc_cfg->anc_micbias, MICB_DISABLE); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_MUX_CTL, 0x0); pr_debug("%s: anc mic %sfound\n", __func__, anc_mic_found ? "" : "not "); return anc_mic_found; } static void wcd_mbhc_find_plug_and_report(struct wcd_mbhc *mbhc, enum wcd_mbhc_plug_type plug_type) { bool anc_mic_found = false; enum snd_jack_types jack_type; pr_debug("%s: enter current_plug(%d) new_plug(%d)\n", __func__, mbhc->current_plug, plug_type); WCD_MBHC_RSC_ASSERT_LOCKED(mbhc); if (mbhc->current_plug == plug_type) { pr_debug("%s: cable already reported, exit\n", __func__); goto exit; } if (plug_type == MBHC_PLUG_TYPE_HEADPHONE) { /* * Nothing was reported previously * report a headphone or unsupported */ wcd_mbhc_report_plug(mbhc, 1, SND_JACK_HEADPHONE); } else if (plug_type == MBHC_PLUG_TYPE_GND_MIC_SWAP) { if (mbhc->current_plug == MBHC_PLUG_TYPE_HEADPHONE) wcd_mbhc_report_plug(mbhc, 0, SND_JACK_HEADPHONE); if (mbhc->current_plug == MBHC_PLUG_TYPE_HEADSET) wcd_mbhc_report_plug(mbhc, 0, SND_JACK_HEADSET); wcd_mbhc_report_plug(mbhc, 1, SND_JACK_UNSUPPORTED); } else if (plug_type == MBHC_PLUG_TYPE_HEADSET) { if (mbhc->mbhc_cfg->enable_anc_mic_detect) anc_mic_found = wcd_mbhc_detect_anc_plug_type(mbhc); jack_type = SND_JACK_HEADSET; if (anc_mic_found) jack_type = SND_JACK_ANC_HEADPHONE; /* * If Headphone was reported previously, this will * only report the mic line */ wcd_mbhc_report_plug(mbhc, 1, jack_type); } else if (plug_type == MBHC_PLUG_TYPE_HIGH_HPH) { if (mbhc->mbhc_cfg->detect_extn_cable) { /* High impedance device found. Report as LINEOUT */ wcd_mbhc_report_plug(mbhc, 1, SND_JACK_LINEOUT); pr_debug("%s: setup mic trigger for further detection\n", __func__); /* Disable HW FSM and current source */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 0); /* Setup for insertion detection */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_DETECTION_TYPE, 1); /* * Enable HPHL trigger and MIC Schmitt triggers * and request for elec insertion interrupts */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_SCHMT_ISRC, 3); wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_INS, true); } else { wcd_mbhc_report_plug(mbhc, 1, SND_JACK_LINEOUT); } } else { WARN(1, "Unexpected current plug_type %d, plug_type %d\n", mbhc->current_plug, plug_type); } exit: pr_debug("%s: leave\n", __func__); } /* To determine if cross connection occured */ static int wcd_check_cross_conn(struct wcd_mbhc *mbhc) { u16 swap_res; enum wcd_mbhc_plug_type plug_type = MBHC_PLUG_TYPE_NONE; s16 reg1; bool hphl_sch_res, hphr_sch_res; if (wcd_swch_level_remove(mbhc)) { pr_debug("%s: Switch level is low\n", __func__); return -EINVAL; } WCD_MBHC_REG_READ(WCD_MBHC_ELECT_SCHMT_ISRC, reg1); /* * Check if there is any cross connection, * Micbias and schmitt trigger (HPHL-HPHR) * needs to be enabled. For some codecs like wcd9335, * pull-up will already be enabled when this function * is called for cross-connection identification. No * need to enable micbias in that case. */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_SCHMT_ISRC, 2); WCD_MBHC_REG_READ(WCD_MBHC_ELECT_RESULT, swap_res); pr_debug("%s: swap_res%x\n", __func__, swap_res); /* * Read reg hphl and hphr schmitt result with cross connection * bit. These bits will both be "0" in case of cross connection * otherwise, they stay at 1 */ WCD_MBHC_REG_READ(WCD_MBHC_HPHL_SCHMT_RESULT, hphl_sch_res); WCD_MBHC_REG_READ(WCD_MBHC_HPHR_SCHMT_RESULT, hphr_sch_res); if (!(hphl_sch_res || hphr_sch_res)) { plug_type = MBHC_PLUG_TYPE_GND_MIC_SWAP; pr_debug("%s: Cross connection identified\n", __func__); } else { pr_debug("%s: No Cross connection found\n", __func__); } /* Disable schmitt trigger and restore micbias */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_SCHMT_ISRC, reg1); pr_debug("%s: leave, plug type: %d\n", __func__, plug_type); return (plug_type == MBHC_PLUG_TYPE_GND_MIC_SWAP) ? true : false; } static bool wcd_is_special_headset(struct wcd_mbhc *mbhc) { struct snd_soc_codec *codec = mbhc->codec; int delay = 0, rc; bool ret = false; u16 hs_comp_res; bool is_spl_hs = false; /* * Increase micbias to 2.7V to detect headsets with * threshold on microphone */ if (mbhc->mbhc_cb->mbhc_micbias_control && !mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic) { pr_debug("%s: callback fn micb_ctrl_thr_mic not defined\n", __func__); return false; } else if (mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic) { rc = mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic(codec, MIC_BIAS_2, true); if (rc) { pr_err("%s: Micbias control for thr mic failed, rc: %d\n", __func__, rc); return false; } } wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); pr_debug("%s: special headset, start register writes\n", __func__); WCD_MBHC_REG_READ(WCD_MBHC_HS_COMP_RESULT, hs_comp_res); while (hs_comp_res) { if (mbhc->hs_detect_work_stop) { pr_debug("%s: stop requested: %d\n", __func__, mbhc->hs_detect_work_stop); break; } delay = delay + 50; if (mbhc->mbhc_cb->mbhc_common_micb_ctrl) { mbhc->mbhc_cb->mbhc_common_micb_ctrl(codec, MBHC_COMMON_MICB_PRECHARGE, true); mbhc->mbhc_cb->mbhc_common_micb_ctrl(codec, MBHC_COMMON_MICB_SET_VAL, true); } /* Wait for 50msec for MICBIAS to settle down */ msleep(50); if (mbhc->mbhc_cb->set_auto_zeroing) mbhc->mbhc_cb->set_auto_zeroing(codec, true); /* Wait for 50msec for FSM to update result values */ msleep(50); WCD_MBHC_REG_READ(WCD_MBHC_HS_COMP_RESULT, hs_comp_res); if (!(hs_comp_res)) { pr_debug("%s: Special headset detected in %d msecs\n", __func__, (delay * 2)); is_spl_hs = true; } if (delay == SPECIAL_HS_DETECT_TIME_MS) { pr_debug("%s: Spl headset didnt get detect in 4 sec\n", __func__); break; } } if (is_spl_hs) { pr_debug("%s: Headset with threshold found\n", __func__); mbhc->micbias_enable = true; ret = true; } if (mbhc->mbhc_cb->mbhc_common_micb_ctrl) mbhc->mbhc_cb->mbhc_common_micb_ctrl(codec, MBHC_COMMON_MICB_PRECHARGE, false); if (mbhc->mbhc_cb->set_micbias_value) mbhc->mbhc_cb->set_micbias_value(codec); if (mbhc->mbhc_cb->set_auto_zeroing) mbhc->mbhc_cb->set_auto_zeroing(codec, false); if (mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic && !mbhc->micbias_enable) mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic(codec, MIC_BIAS_2, false); pr_debug("%s: leave, micb_enable: %d\n", __func__, mbhc->micbias_enable); return ret; } static void wcd_mbhc_update_fsm_source(struct wcd_mbhc *mbhc, enum wcd_mbhc_plug_type plug_type) { bool micbias2; micbias2 = mbhc->mbhc_cb->micbias_enable_status(mbhc, MIC_BIAS_2); switch (plug_type) { case MBHC_PLUG_TYPE_HEADPHONE: WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 3); break; case MBHC_PLUG_TYPE_HEADSET: case MBHC_PLUG_TYPE_ANC_HEADPHONE: if (!mbhc->is_hs_recording && !micbias2) WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 3); break; default: WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 0); break; }; } static void wcd_enable_mbhc_supply(struct wcd_mbhc *mbhc, enum wcd_mbhc_plug_type plug_type) { struct snd_soc_codec *codec = mbhc->codec; /* * Do not disable micbias if recording is going on or * headset is inserted on the other side of the extn * cable. If headset has been detected current source * needs to be kept enabled for button detection to work. * If the accessory type is invalid or unsupported, we * dont need to enable either of them. */ if (det_extn_cable_en && mbhc->is_extn_cable && mbhc->mbhc_cb && mbhc->mbhc_cb->extn_use_mb && mbhc->mbhc_cb->extn_use_mb(codec)) { if (plug_type == MBHC_PLUG_TYPE_HEADPHONE || plug_type == MBHC_PLUG_TYPE_HEADSET) wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); } else { if (plug_type == MBHC_PLUG_TYPE_HEADSET) { if (mbhc->is_hs_recording) wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); else if ((test_bit(WCD_MBHC_EVENT_PA_HPHL, &mbhc->event_state)) || (test_bit(WCD_MBHC_EVENT_PA_HPHR, &mbhc->event_state))) wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_PULLUP); else wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_CS); } else if (plug_type == MBHC_PLUG_TYPE_HEADPHONE) { wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_CS); } else { wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_NONE); } } } static bool wcd_mbhc_check_for_spl_headset(struct wcd_mbhc *mbhc, int *spl_hs_cnt) { u16 hs_comp_res_1_8v = 0, hs_comp_res_2_7v = 0; bool spl_hs = false; if (!mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic) goto exit; /* Read back hs_comp_res @ 1.8v Micbias */ WCD_MBHC_REG_READ(WCD_MBHC_HS_COMP_RESULT, hs_comp_res_1_8v); if (!hs_comp_res_1_8v) { spl_hs = false; goto exit; } /* Bump up MB2 to 2.7v */ mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic(mbhc->codec, mbhc->mbhc_cfg->mbhc_micbias, true); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 1); usleep_range(10000, 10100); /* Read back HS_COMP_RESULT */ WCD_MBHC_REG_READ(WCD_MBHC_HS_COMP_RESULT, hs_comp_res_2_7v); if (!hs_comp_res_2_7v && hs_comp_res_1_8v) spl_hs = true; if (spl_hs && spl_hs_cnt) *spl_hs_cnt += 1; /* MB2 back to 1.8v */ if (spl_hs_cnt && (*spl_hs_cnt != WCD_MBHC_SPL_HS_CNT)) { mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic(mbhc->codec, mbhc->mbhc_cfg->mbhc_micbias, false); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 1); usleep_range(10000, 10100); } if (spl_hs) pr_debug("%s: Detected special HS (%d)\n", __func__, spl_hs); exit: return spl_hs; } static void wcd_correct_swch_plug(struct work_struct *work) { struct wcd_mbhc *mbhc; struct snd_soc_codec *codec; enum wcd_mbhc_plug_type plug_type = MBHC_PLUG_TYPE_INVALID; unsigned long timeout; u16 hs_comp_res, hphl_sch, mic_sch, btn_result; bool wrk_complete = false; int pt_gnd_mic_swap_cnt = 0; int no_gnd_mic_swap_cnt = 0; bool is_pa_on = false, spl_hs = false; bool micbias2 = false; bool micbias1 = false; int ret = 0; int rc, spl_hs_count = 0; pr_debug("%s: enter\n", __func__); mbhc = container_of(work, struct wcd_mbhc, correct_plug_swch); codec = mbhc->codec; /* * Enable micbias/pullup for detection in correct work. * This work will get scheduled from detect_plug_type which * will already request for pullup/micbias. If the pullup/micbias * is handled with ref-counts by individual codec drivers, there is * no need to enabale micbias/pullup here */ wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); if (mbhc->current_plug == MBHC_PLUG_TYPE_GND_MIC_SWAP) { mbhc->current_plug = MBHC_PLUG_TYPE_NONE; goto correct_plug_type; } /* Enable HW FSM */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 1); /* * Check for any button press interrupts before starting 3-sec * loop. */ rc = wait_for_completion_timeout(&mbhc->btn_press_compl, msecs_to_jiffies(WCD_MBHC_BTN_PRESS_COMPL_TIMEOUT_MS)); WCD_MBHC_REG_READ(WCD_MBHC_BTN_RESULT, btn_result); WCD_MBHC_REG_READ(WCD_MBHC_HS_COMP_RESULT, hs_comp_res); if (!rc) { pr_debug("%s No btn press interrupt\n", __func__); if (!btn_result && !hs_comp_res) plug_type = MBHC_PLUG_TYPE_HEADSET; else if (!btn_result && hs_comp_res) plug_type = MBHC_PLUG_TYPE_HIGH_HPH; else plug_type = MBHC_PLUG_TYPE_INVALID; } else { if (!btn_result && !hs_comp_res) plug_type = MBHC_PLUG_TYPE_HEADPHONE; else plug_type = MBHC_PLUG_TYPE_INVALID; } pr_err("%s: Valid plug found, plug type is %d\n", __func__, plug_type); if ((plug_type == MBHC_PLUG_TYPE_HEADSET ) && (!wcd_swch_level_remove(mbhc))) { WCD_MBHC_RSC_LOCK(mbhc); wcd_mbhc_find_plug_and_report(mbhc, plug_type); WCD_MBHC_RSC_UNLOCK(mbhc); } correct_plug_type: timeout = jiffies + msecs_to_jiffies(HS_DETECT_PLUG_TIME_MS); while (!time_after(jiffies, timeout)) { if (mbhc->hs_detect_work_stop) { pr_err("%s: stop requested: %d\n", __func__, mbhc->hs_detect_work_stop); wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_NONE); if (mbhc->micbias_enable && mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic) { mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic( mbhc->codec, MIC_BIAS_2, false); mbhc->micbias_enable = false; } goto exit; } if (mbhc->btn_press_intr) { wcd_cancel_btn_work(mbhc); mbhc->btn_press_intr = false; } /* Toggle FSM */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 1); /* allow sometime and re-check stop requested again */ msleep(20); if (mbhc->hs_detect_work_stop) { pr_err("%s: stop requested: %d\n", __func__, mbhc->hs_detect_work_stop); wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_NONE); if (mbhc->micbias_enable && mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic) { mbhc->mbhc_cb->mbhc_micb_ctrl_thr_mic( mbhc->codec, MIC_BIAS_2, false); mbhc->micbias_enable = false; } goto exit; } WCD_MBHC_REG_READ(WCD_MBHC_HS_COMP_RESULT, hs_comp_res); pr_debug("%s: hs_comp_res: %x\n", __func__, hs_comp_res); if (mbhc->mbhc_cb->hph_pa_on_status) is_pa_on = mbhc->mbhc_cb->hph_pa_on_status(codec); /* * instead of hogging system by contineous polling, wait for * sometime and re-check stop request again. */ msleep(60); if (hs_comp_res && (spl_hs_count < WCD_MBHC_SPL_HS_CNT)) { spl_hs = wcd_mbhc_check_for_spl_headset(mbhc, &spl_hs_count); if (spl_hs_count == WCD_MBHC_SPL_HS_CNT) { hs_comp_res = 0; spl_hs = true; mbhc->micbias_enable = true; } } if ((!hs_comp_res) && (!is_pa_on)) { /* Check for cross connection*/ ret = wcd_check_cross_conn(mbhc); if (ret < 0) { continue; } else if (ret > 0) { pt_gnd_mic_swap_cnt++; no_gnd_mic_swap_cnt = 0; if (pt_gnd_mic_swap_cnt < GND_MIC_SWAP_THRESHOLD) { msleep(80); continue; } else if (pt_gnd_mic_swap_cnt > GND_MIC_SWAP_THRESHOLD) { /* * This is due to GND/MIC switch didn't * work, Report unsupported plug. */ pr_err("%s: switch didnt work\n", __func__); plug_type = MBHC_PLUG_TYPE_GND_MIC_SWAP; goto report; } else { plug_type = MBHC_PLUG_TYPE_GND_MIC_SWAP; } } else { no_gnd_mic_swap_cnt++; pt_gnd_mic_swap_cnt = 0; plug_type = MBHC_PLUG_TYPE_HEADSET; if ((no_gnd_mic_swap_cnt < GND_MIC_SWAP_THRESHOLD) && (spl_hs_count != WCD_MBHC_SPL_HS_CNT)) { continue; } else { no_gnd_mic_swap_cnt = 0; } } if ((pt_gnd_mic_swap_cnt == GND_MIC_SWAP_THRESHOLD) && (plug_type == MBHC_PLUG_TYPE_GND_MIC_SWAP)) { /* * if switch is toggled, check again, * otherwise report unsupported plug */ if (mbhc->mbhc_cfg->swap_gnd_mic && mbhc->mbhc_cfg->swap_gnd_mic(codec)) { pr_err("%s: US_EU gpio present,flip switch\n" , __func__); continue; } } } WCD_MBHC_REG_READ(WCD_MBHC_HPHL_SCHMT_RESULT, hphl_sch); WCD_MBHC_REG_READ(WCD_MBHC_MIC_SCHMT_RESULT, mic_sch); if (hs_comp_res && !(hphl_sch || mic_sch)) { pr_err("%s: cable is extension cable\n", __func__); plug_type = MBHC_PLUG_TYPE_HIGH_HPH; wrk_complete = true; } else { pr_err("%s: cable might be headset: %d mbhc->current_plug = %d\n", __func__, plug_type,mbhc->current_plug); if (!(plug_type == MBHC_PLUG_TYPE_GND_MIC_SWAP)) { plug_type = MBHC_PLUG_TYPE_HEADSET; /* * Report headset only if not already reported * and if there is not button press without * release */ if (((mbhc->current_plug != MBHC_PLUG_TYPE_HEADSET) && (mbhc->current_plug != MBHC_PLUG_TYPE_ANC_HEADPHONE)) && !mbhc->btn_press_intr) { pr_err("%s: cable is %sheadset\n", __func__, ((spl_hs_count == WCD_MBHC_SPL_HS_CNT) ? "special ":"")); goto report; } } wrk_complete = false; } } if (!wrk_complete && mbhc->btn_press_intr) { pr_err("%s: Can be slow insertion of headphone\n", __func__); wcd_cancel_btn_work(mbhc); plug_type = MBHC_PLUG_TYPE_HEADPHONE; } /* * If plug_tye is headset, we might have already reported either in * detect_plug-type or in above while loop, no need to report again */ if (!wrk_complete && ((plug_type == MBHC_PLUG_TYPE_HEADSET) || (plug_type == MBHC_PLUG_TYPE_ANC_HEADPHONE))) { pr_err("%s: plug_type:0x%x already reported\n", __func__, mbhc->current_plug); goto enable_supply; } if (plug_type == MBHC_PLUG_TYPE_HIGH_HPH && (!det_extn_cable_en)) { if (wcd_is_special_headset(mbhc)) { pr_err("%s: Special headset found %d\n", __func__, plug_type); plug_type = MBHC_PLUG_TYPE_HEADSET; goto report; } } report: if (wcd_swch_level_remove(mbhc)) { pr_err("%s: Switch level is low\n", __func__); goto exit; } pr_err("%s: Valid plug found, plug type %d wrk_cmpt %d btn_intr %d\n", __func__, plug_type, wrk_complete, mbhc->btn_press_intr); WCD_MBHC_RSC_LOCK(mbhc); wcd_mbhc_find_plug_and_report(mbhc, plug_type); WCD_MBHC_RSC_UNLOCK(mbhc); enable_supply: if (mbhc->mbhc_cb->mbhc_micbias_control) wcd_mbhc_update_fsm_source(mbhc, plug_type); else wcd_enable_mbhc_supply(mbhc, plug_type); exit: if (mbhc->mbhc_cb->mbhc_micbias_control && !mbhc->micbias_enable) mbhc->mbhc_cb->mbhc_micbias_control(codec, MIC_BIAS_2, MICB_DISABLE); if (mbhc->mbhc_cb->micbias_enable_status) { micbias1 = mbhc->mbhc_cb->micbias_enable_status(mbhc, MIC_BIAS_1); micbias2 = mbhc->mbhc_cb->micbias_enable_status(mbhc, MIC_BIAS_2); } if (mbhc->mbhc_cfg->detect_extn_cable && ((plug_type == MBHC_PLUG_TYPE_HEADPHONE) || (plug_type == MBHC_PLUG_TYPE_HEADSET)) && !mbhc->hs_detect_work_stop) { WCD_MBHC_RSC_LOCK(mbhc); wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_REM, true); WCD_MBHC_RSC_UNLOCK(mbhc); } if (mbhc->mbhc_cb->set_cap_mode) mbhc->mbhc_cb->set_cap_mode(codec, micbias1, micbias2); if (mbhc->mbhc_cb->hph_pull_down_ctrl) mbhc->mbhc_cb->hph_pull_down_ctrl(codec, true); mbhc->mbhc_cb->lock_sleep(mbhc, false); pr_err("%s: leave\n", __func__); } /* called under codec_resource_lock acquisition */ static void wcd_mbhc_detect_plug_type(struct wcd_mbhc *mbhc) { struct snd_soc_codec *codec = mbhc->codec; enum wcd_mbhc_plug_type plug_type; bool micbias1 = false; int cross_conn; int try = 0; pr_debug("%s: enter\n", __func__); WCD_MBHC_RSC_ASSERT_LOCKED(mbhc); if (mbhc->mbhc_cb->hph_pull_down_ctrl) mbhc->mbhc_cb->hph_pull_down_ctrl(codec, false); if (mbhc->mbhc_cb->micbias_enable_status) micbias1 = mbhc->mbhc_cb->micbias_enable_status(mbhc, MIC_BIAS_1); if (mbhc->mbhc_cb->set_cap_mode) mbhc->mbhc_cb->set_cap_mode(codec, micbias1, true); if (mbhc->mbhc_cb->mbhc_micbias_control) mbhc->mbhc_cb->mbhc_micbias_control(codec, MIC_BIAS_2, MICB_ENABLE); else wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_MB); do { cross_conn = wcd_check_cross_conn(mbhc); try++; } while (try < GND_MIC_SWAP_THRESHOLD); if (cross_conn > 0) { pr_debug("%s: cross con found, start polling\n", __func__); plug_type = MBHC_PLUG_TYPE_GND_MIC_SWAP; if (!mbhc->current_plug) mbhc->current_plug = plug_type; pr_debug("%s: Plug found, plug type is %d\n", __func__, plug_type); } /* Re-initialize button press completion object */ reinit_completion(&mbhc->btn_press_compl); wcd_schedule_hs_detect_plug(mbhc, &mbhc->correct_plug_swch); pr_debug("%s: leave\n", __func__); } static void wcd_mbhc_swch_irq_handler(struct wcd_mbhc *mbhc) { bool detection_type; bool micbias1 = false; struct snd_soc_codec *codec = mbhc->codec; dev_dbg(codec->dev, "%s: enter\n", __func__); WCD_MBHC_RSC_LOCK(mbhc); mbhc->in_swch_irq_handler = true; /* cancel pending button press */ if (wcd_cancel_btn_work(mbhc)) pr_debug("%s: button press is canceled\n", __func__); WCD_MBHC_REG_READ(WCD_MBHC_MECH_DETECTION_TYPE, detection_type); /* Set the detection type appropriately */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_MECH_DETECTION_TYPE, !detection_type); pr_debug("%s: mbhc->current_plug: %d detection_type: %d\n", __func__, mbhc->current_plug, detection_type); wcd_cancel_hs_detect_plug(mbhc, &mbhc->correct_plug_swch); if (mbhc->mbhc_cb->micbias_enable_status) micbias1 = mbhc->mbhc_cb->micbias_enable_status(mbhc, MIC_BIAS_1); if ((mbhc->current_plug == MBHC_PLUG_TYPE_NONE) && detection_type) { /* Make sure MASTER_BIAS_CTL is enabled */ mbhc->mbhc_cb->mbhc_bias(codec, true); if (mbhc->mbhc_cb->mbhc_common_micb_ctrl) mbhc->mbhc_cb->mbhc_common_micb_ctrl(codec, MBHC_COMMON_MICB_TAIL_CURR, true); if (!mbhc->mbhc_cfg->hs_ext_micbias && mbhc->mbhc_cb->micb_internal) /* * Enable Tx2 RBias if the headset * is using internal micbias */ mbhc->mbhc_cb->micb_internal(codec, 1, true); /* Remove micbias pulldown */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_PULLDOWN_CTRL, 0); /* Apply trim if needed on the device */ if (mbhc->mbhc_cb->trim_btn_reg) mbhc->mbhc_cb->trim_btn_reg(codec); /* Enable external voltage source to micbias if present */ if (mbhc->mbhc_cb->enable_mb_source) mbhc->mbhc_cb->enable_mb_source(codec, true); mbhc->btn_press_intr = false; wcd_mbhc_detect_plug_type(mbhc); } else if ((mbhc->current_plug != MBHC_PLUG_TYPE_NONE) && !detection_type) { /* Disable external voltage source to micbias if present */ if (mbhc->mbhc_cb->enable_mb_source) mbhc->mbhc_cb->enable_mb_source(codec, false); /* Disable HW FSM */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 0); if (mbhc->mbhc_cb->mbhc_common_micb_ctrl) mbhc->mbhc_cb->mbhc_common_micb_ctrl(codec, MBHC_COMMON_MICB_TAIL_CURR, false); if (mbhc->mbhc_cb->set_cap_mode) mbhc->mbhc_cb->set_cap_mode(codec, micbias1, false); mbhc->btn_press_intr = false; if (mbhc->current_plug == MBHC_PLUG_TYPE_HEADPHONE) { wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_REM, false); wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_INS, false); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_DETECTION_TYPE, 1); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_SCHMT_ISRC, 0); wcd_mbhc_report_plug(mbhc, 0, SND_JACK_HEADPHONE); } else if (mbhc->current_plug == MBHC_PLUG_TYPE_GND_MIC_SWAP) { wcd_mbhc_report_plug(mbhc, 0, SND_JACK_UNSUPPORTED); } else if (mbhc->current_plug == MBHC_PLUG_TYPE_HEADSET) { /* make sure to turn off Rbias */ if (mbhc->mbhc_cb->micb_internal) mbhc->mbhc_cb->micb_internal(codec, 1, false); /* Pulldown micbias */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_PULLDOWN_CTRL, 1); wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_REM, false); wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_INS, false); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_DETECTION_TYPE, 1); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_SCHMT_ISRC, 0); wcd_mbhc_report_plug(mbhc, 0, SND_JACK_HEADSET); } else if (mbhc->current_plug == MBHC_PLUG_TYPE_HIGH_HPH) { mbhc->is_extn_cable = false; wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_REM, false); wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_INS, false); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_DETECTION_TYPE, 1); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_SCHMT_ISRC, 0); wcd_mbhc_report_plug(mbhc, 0, SND_JACK_LINEOUT); } else if (mbhc->current_plug == MBHC_PLUG_TYPE_ANC_HEADPHONE) { mbhc->mbhc_cb->irq_control(codec, mbhc->intr_ids->mbhc_hs_rem_intr, false); mbhc->mbhc_cb->irq_control(codec, mbhc->intr_ids->mbhc_hs_ins_intr, false); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_DETECTION_TYPE, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_SCHMT_ISRC, 0); wcd_mbhc_report_plug(mbhc, 0, SND_JACK_ANC_HEADPHONE); } } else if (!detection_type) { /* Disable external voltage source to micbias if present */ if (mbhc->mbhc_cb->enable_mb_source) mbhc->mbhc_cb->enable_mb_source(codec, false); /* Disable HW FSM */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_ISRC_CTL, 0); } mbhc->in_swch_irq_handler = false; WCD_MBHC_RSC_UNLOCK(mbhc); pr_debug("%s: leave\n", __func__); } static irqreturn_t wcd_mbhc_mech_plug_detect_irq(int irq, void *data) { int r = IRQ_HANDLED; struct wcd_mbhc *mbhc = data; pr_debug("%s: enter\n", __func__); if (unlikely((mbhc->mbhc_cb->lock_sleep(mbhc, true)) == false)) { pr_warn("%s: failed to hold suspend\n", __func__); r = IRQ_NONE; } else { /* Call handler */ wcd_mbhc_swch_irq_handler(mbhc); mbhc->mbhc_cb->lock_sleep(mbhc, false); } pr_debug("%s: leave %d\n", __func__, r); return r; } static int wcd_mbhc_get_button_mask(struct wcd_mbhc *mbhc) { int mask = 0; int btn; btn = mbhc->mbhc_cb->map_btn_code_to_num(mbhc->codec); switch (btn) { case 0: mask = SND_JACK_BTN_0; break; case 1: mask = SND_JACK_BTN_1; break; case 2: mask = SND_JACK_BTN_2; break; case 3: mask = SND_JACK_BTN_3; break; case 4: mask = SND_JACK_BTN_4; break; case 5: mask = SND_JACK_BTN_5; break; case 6: mask = SND_JACK_BTN_6; break; case 7: mask = SND_JACK_BTN_7; break; default: break; } return mask; } static irqreturn_t wcd_mbhc_hs_ins_irq(int irq, void *data) { struct wcd_mbhc *mbhc = data; bool detection_type, hphl_sch, mic_sch; u16 elect_result; static u16 hphl_trigerred; static u16 mic_trigerred; pr_debug("%s: enter\n", __func__); if (!mbhc->mbhc_cfg->detect_extn_cable) { pr_debug("%s: Returning as Extension cable feature not enabled\n", __func__); return IRQ_HANDLED; } WCD_MBHC_RSC_LOCK(mbhc); WCD_MBHC_REG_READ(WCD_MBHC_ELECT_DETECTION_TYPE, detection_type); WCD_MBHC_REG_READ(WCD_MBHC_ELECT_RESULT, elect_result); pr_debug("%s: detection_type %d, elect_result %x\n", __func__, detection_type, elect_result); if (detection_type) { /* check if both Left and MIC Schmitt triggers are triggered */ WCD_MBHC_REG_READ(WCD_MBHC_HPHL_SCHMT_RESULT, hphl_sch); WCD_MBHC_REG_READ(WCD_MBHC_MIC_SCHMT_RESULT, mic_sch); if (hphl_sch && mic_sch) { /* Go for plug type determination */ pr_debug("%s: Go for plug type determination\n", __func__); goto determine_plug; } else { if (mic_sch) { mic_trigerred++; pr_debug("%s: Insertion MIC trigerred %d\n", __func__, mic_trigerred); WCD_MBHC_REG_UPDATE_BITS( WCD_MBHC_ELECT_SCHMT_ISRC, 0); msleep(20); WCD_MBHC_REG_UPDATE_BITS( WCD_MBHC_ELECT_SCHMT_ISRC, 1); } if (hphl_sch) { hphl_trigerred++; pr_debug("%s: Insertion HPHL trigerred %d\n", __func__, hphl_trigerred); } if (mic_trigerred && hphl_trigerred) { /* Go for plug type determination */ pr_debug("%s: Go for plug type determination\n", __func__); goto determine_plug; } } } WCD_MBHC_RSC_UNLOCK(mbhc); pr_debug("%s: leave\n", __func__); return IRQ_HANDLED; determine_plug: /* * Disable HPHL trigger and MIC Schmitt triggers. * Setup for insertion detection. */ pr_debug("%s: Disable insertion interrupt\n", __func__); wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_INS, false); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_SCHMT_ISRC, 0); hphl_trigerred = 0; mic_trigerred = 0; mbhc->is_extn_cable = true; mbhc->btn_press_intr = false; wcd_mbhc_detect_plug_type(mbhc); WCD_MBHC_RSC_UNLOCK(mbhc); pr_debug("%s: leave\n", __func__); return IRQ_HANDLED; } static irqreturn_t wcd_mbhc_hs_rem_irq(int irq, void *data) { struct wcd_mbhc *mbhc = data; u8 hs_comp_result, hphl_sch, mic_sch; static u16 hphl_trigerred; static u16 mic_trigerred; unsigned long timeout; bool removed = true; int retry = 0; pr_debug("%s: enter\n", __func__); WCD_MBHC_RSC_LOCK(mbhc); timeout = jiffies + msecs_to_jiffies(WCD_FAKE_REMOVAL_MIN_PERIOD_MS); do { retry++; /* * read the result register every 10ms to look for * any change in HS_COMP_RESULT bit */ usleep_range(10000, 10100); WCD_MBHC_REG_READ(WCD_MBHC_HS_COMP_RESULT, hs_comp_result); pr_debug("%s: Check result reg for fake removal: hs_comp_res %x\n", __func__, hs_comp_result); if ((!hs_comp_result) && retry > FAKE_REM_RETRY_ATTEMPTS) { removed = false; break; } } while (!time_after(jiffies, timeout)); if (wcd_swch_level_remove(mbhc)) { pr_debug("%s: Switch level is low ", __func__); goto exit; } pr_debug("%s: headset %s actually removed\n", __func__, removed ? "" : "not "); WCD_MBHC_REG_READ(WCD_MBHC_HPHL_SCHMT_RESULT, hphl_sch); WCD_MBHC_REG_READ(WCD_MBHC_MIC_SCHMT_RESULT, mic_sch); WCD_MBHC_REG_READ(WCD_MBHC_HS_COMP_RESULT, hs_comp_result); if (removed) { if (!(hphl_sch && mic_sch && hs_comp_result)) { /* * extension cable is still plugged in * report it as LINEOUT device */ goto report_unplug; } else { if (!mic_sch) { mic_trigerred++; pr_debug("%s: Removal MIC trigerred %d\n", __func__, mic_trigerred); } if (!hphl_sch) { hphl_trigerred++; pr_debug("%s: Removal HPHL trigerred %d\n", __func__, hphl_trigerred); } if (mic_trigerred && hphl_trigerred) { /* * extension cable is still plugged in * report it as LINEOUT device */ goto report_unplug; } } } exit: WCD_MBHC_RSC_UNLOCK(mbhc); pr_debug("%s: leave\n", __func__); return IRQ_HANDLED; report_unplug: /* cancel pending button press */ if (wcd_cancel_btn_work(mbhc)) pr_debug("%s: button press is canceled\n", __func__); /* cancel correct work function */ wcd_cancel_hs_detect_plug(mbhc, &mbhc->correct_plug_swch); pr_debug("%s: Report extension cable\n", __func__); wcd_mbhc_report_plug(mbhc, 1, SND_JACK_LINEOUT); /* * If PA is enabled HPHL schmitt trigger can * be unreliable, make sure to disable it */ if (test_bit(WCD_MBHC_EVENT_PA_HPHL, &mbhc->event_state)) wcd_mbhc_set_and_turnoff_hph_padac(mbhc); /* * Disable HPHL trigger and MIC Schmitt triggers. * Setup for insertion detection. */ wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_REM, false); wcd_enable_curr_micbias(mbhc, WCD_MBHC_EN_NONE); /* Disable HW FSM */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_SCHMT_ISRC, 3); /* Set the detection type appropriately */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_ELECT_DETECTION_TYPE, 1); wcd_mbhc_hs_elec_irq(mbhc, WCD_MBHC_ELEC_HS_INS, true); hphl_trigerred = 0; mic_trigerred = 0; WCD_MBHC_RSC_UNLOCK(mbhc); pr_debug("%s: leave\n", __func__); return IRQ_HANDLED; } static void wcd_btn_lpress_fn(struct work_struct *work) { struct delayed_work *dwork; struct wcd_mbhc *mbhc; s16 btn_result; pr_debug("%s: Enter\n", __func__); dwork = to_delayed_work(work); mbhc = container_of(dwork, struct wcd_mbhc, mbhc_btn_dwork); WCD_MBHC_REG_READ(WCD_MBHC_BTN_RESULT, btn_result); if (mbhc->current_plug == MBHC_PLUG_TYPE_HEADSET) { pr_debug("%s: Reporting long button press event, btn_result: %d\n", __func__, btn_result); wcd_mbhc_jack_report(mbhc, &mbhc->button_jack, mbhc->buttons_pressed, mbhc->buttons_pressed); } pr_debug("%s: leave\n", __func__); mbhc->mbhc_cb->lock_sleep(mbhc, false); } static bool wcd_mbhc_fw_validate(const void *data, size_t size) { u32 cfg_offset; struct wcd_mbhc_btn_detect_cfg *btn_cfg; struct firmware_cal fw; fw.data = (void *)data; fw.size = size; if (fw.size < WCD_MBHC_CAL_MIN_SIZE) return false; /* * Previous check guarantees that there is enough fw data up * to num_btn */ btn_cfg = WCD_MBHC_CAL_BTN_DET_PTR(fw.data); cfg_offset = (u32) ((void *) btn_cfg - (void *) fw.data); if (fw.size < (cfg_offset + WCD_MBHC_CAL_BTN_SZ(btn_cfg))) return false; return true; } static irqreturn_t wcd_mbhc_btn_press_handler(int irq, void *data) { struct wcd_mbhc *mbhc = data; int mask; unsigned long msec_val; pr_debug("%s: enter\n", __func__); complete(&mbhc->btn_press_compl); WCD_MBHC_RSC_LOCK(mbhc); /* send event to sw intr handler*/ mbhc->is_btn_press = true; wcd_cancel_btn_work(mbhc); if (wcd_swch_level_remove(mbhc)) { pr_debug("%s: Switch level is low ", __func__); goto done; } mbhc->btn_press_intr = true; msec_val = jiffies_to_msecs(jiffies - mbhc->jiffies_atreport); pr_debug("%s: msec_val = %ld\n", __func__, msec_val); if (msec_val < MBHC_BUTTON_PRESS_THRESHOLD_MIN) { pr_debug("%s: Too short, ignore button press\n", __func__); goto done; } /* If switch interrupt already kicked in, ignore button press */ if (mbhc->in_swch_irq_handler) { pr_debug("%s: Swtich level changed, ignore button press\n", __func__); goto done; } if (mbhc->current_plug != MBHC_PLUG_TYPE_HEADSET) { pr_debug("%s: Plug isn't headset, ignore button press\n", __func__); goto done; } mask = wcd_mbhc_get_button_mask(mbhc); mbhc->buttons_pressed |= mask; mbhc->mbhc_cb->lock_sleep(mbhc, true); if (schedule_delayed_work(&mbhc->mbhc_btn_dwork, msecs_to_jiffies(400)) == 0) { WARN(1, "Button pressed twice without release event\n"); mbhc->mbhc_cb->lock_sleep(mbhc, false); } done: pr_debug("%s: leave\n", __func__); WCD_MBHC_RSC_UNLOCK(mbhc); return IRQ_HANDLED; } static irqreturn_t wcd_mbhc_release_handler(int irq, void *data) { struct wcd_mbhc *mbhc = data; int ret; pr_debug("%s: enter\n", __func__); WCD_MBHC_RSC_LOCK(mbhc); if (wcd_swch_level_remove(mbhc)) { pr_debug("%s: Switch level is low ", __func__); goto exit; } if (mbhc->btn_press_intr) { mbhc->btn_press_intr = false; } else { pr_debug("%s: This release is for fake btn press\n", __func__); goto exit; } /* * If current plug is headphone then there is no chance to * get btn release interrupt, so connected cable should be * headset not headphone. */ if (mbhc->current_plug == MBHC_PLUG_TYPE_HEADPHONE) { wcd_mbhc_find_plug_and_report(mbhc, MBHC_PLUG_TYPE_HEADSET); goto exit; } if (mbhc->buttons_pressed & WCD_MBHC_JACK_BUTTON_MASK) { ret = wcd_cancel_btn_work(mbhc); if (ret == 0) { pr_debug("%s: Reporting long button release event\n", __func__); wcd_mbhc_jack_report(mbhc, &mbhc->button_jack, 0, mbhc->buttons_pressed); } else { if (mbhc->in_swch_irq_handler) { pr_debug("%s: Switch irq kicked in, ignore\n", __func__); } else { pr_debug("%s: Reporting btn press\n", __func__); wcd_mbhc_jack_report(mbhc, &mbhc->button_jack, mbhc->buttons_pressed, mbhc->buttons_pressed); pr_debug("%s: Reporting btn release\n", __func__); wcd_mbhc_jack_report(mbhc, &mbhc->button_jack, 0, mbhc->buttons_pressed); } } mbhc->buttons_pressed &= ~WCD_MBHC_JACK_BUTTON_MASK; } exit: pr_debug("%s: leave\n", __func__); WCD_MBHC_RSC_UNLOCK(mbhc); return IRQ_HANDLED; } static irqreturn_t wcd_mbhc_hphl_ocp_irq(int irq, void *data) { struct wcd_mbhc *mbhc = data; pr_debug("%s: received HPHL OCP irq\n", __func__); if (mbhc) { if ((mbhc->hphlocp_cnt < OCP_ATTEMPT) && (!mbhc->hphrocp_cnt)) { pr_debug("%s: retry\n", __func__); mbhc->hphlocp_cnt++; WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_OCP_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_OCP_FSM_EN, 1); } else { mbhc->mbhc_cb->irq_control(mbhc->codec, mbhc->intr_ids->hph_left_ocp, false); mbhc->hph_status |= SND_JACK_OC_HPHL; wcd_mbhc_jack_report(mbhc, &mbhc->headset_jack, mbhc->hph_status, WCD_MBHC_JACK_MASK); } } else { pr_err("%s: Bad wcd9xxx_spmi private data\n", __func__); } return IRQ_HANDLED; } static irqreturn_t wcd_mbhc_hphr_ocp_irq(int irq, void *data) { struct wcd_mbhc *mbhc = data; pr_debug("%s: received HPHR OCP irq\n", __func__); if ((mbhc->hphrocp_cnt < OCP_ATTEMPT) && (!mbhc->hphlocp_cnt)) { pr_debug("%s: retry\n", __func__); mbhc->hphrocp_cnt++; WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_OCP_FSM_EN, 0); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_OCP_FSM_EN, 1); } else { mbhc->mbhc_cb->irq_control(mbhc->codec, mbhc->intr_ids->hph_right_ocp, false); mbhc->hph_status |= SND_JACK_OC_HPHR; wcd_mbhc_jack_report(mbhc, &mbhc->headset_jack, mbhc->hph_status, WCD_MBHC_JACK_MASK); } return IRQ_HANDLED; } static void wcd_mbhc_moisture_config(struct wcd_mbhc *mbhc) { if (mbhc->mbhc_cfg->moist_cfg.m_vref_ctl == V_OFF) return; WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_MOISTURE_VREF, mbhc->mbhc_cfg->moist_cfg.m_vref_ctl); if (mbhc->mbhc_cb->hph_pull_up_control) mbhc->mbhc_cb->hph_pull_up_control(mbhc->codec, mbhc->mbhc_cfg->moist_cfg.m_iref_ctl); } static int wcd_mbhc_initialise(struct wcd_mbhc *mbhc) { int ret = 0; struct snd_soc_codec *codec = mbhc->codec; pr_debug("%s: enter\n", __func__); WCD_MBHC_RSC_LOCK(mbhc); /* enable HS detection */ if (mbhc->mbhc_cb->hph_pull_up_control) mbhc->mbhc_cb->hph_pull_up_control(codec, I_DEFAULT); else WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_HS_L_DET_PULL_UP_CTRL, 3); wcd_mbhc_moisture_config(mbhc); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_HPHL_PLUG_TYPE, mbhc->hphl_swh); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_GND_PLUG_TYPE, mbhc->gnd_swh); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_SW_HPH_LP_100K_TO_GND, 1); if (mbhc->mbhc_cfg->gnd_det_en && mbhc->mbhc_cb->mbhc_gnd_det_ctrl) mbhc->mbhc_cb->mbhc_gnd_det_ctrl(codec, true); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_HS_L_DET_PULL_UP_COMP_CTRL, 1); WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_L_DET_EN, 1); /* Insertion debounce set to 96ms */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_INSREM_DBNC, 6); /* Button Debounce set to 16ms */ WCD_MBHC_REG_UPDATE_BITS(WCD_MBHC_BTN_DBNC, 2); /* Enable micbias ramp */ if (mbhc->mbhc_cb->mbhc_micb_ramp_control) mbhc->mbhc_cb->mbhc_micb_ramp_control(codec, true); /* enable bias */ mbhc->mbhc_cb->mbhc_bias(codec, true); /* enable MBHC clock */ if (mbhc->mbhc_cb->clk_setup) mbhc->mbhc_cb->clk_setup(codec, true); /* program HS_VREF value */ wcd_program_hs_vref(mbhc); wcd_program_btn_threshold(mbhc, false); INIT_WORK(&mbhc->correct_plug_swch, wcd_correct_swch_plug); init_completion(&mbhc->btn_press_compl); WCD_MBHC_RSC_UNLOCK(mbhc); pr_debug("%s: leave\n", __func__); return ret; } static void wcd_mbhc_fw_read(struct work_struct *work) { struct delayed_work *dwork; struct wcd_mbhc *mbhc; struct snd_soc_codec *codec; const struct firmware *fw; struct firmware_cal *fw_data = NULL; int ret = -1, retry = 0; bool use_default_cal = false; dwork = to_delayed_work(work); mbhc = container_of(dwork, struct wcd_mbhc, mbhc_firmware_dwork); codec = mbhc->codec; while (retry < FW_READ_ATTEMPTS) { retry++; pr_debug("%s:Attempt %d to request MBHC firmware\n", __func__, retry); if (mbhc->mbhc_cb->get_hwdep_fw_cal) fw_data = mbhc->mbhc_cb->get_hwdep_fw_cal(codec, WCD9XXX_MBHC_CAL); if (!fw_data) ret = request_firmware(&fw, "wcd9320/wcd9320_mbhc.bin", codec->dev); /* * if request_firmware and hwdep cal both fail then * sleep for 4sec for the userspace to send data to kernel * retry for few times before bailing out */ if ((ret != 0) && !fw_data) { usleep_range(FW_READ_TIMEOUT, FW_READ_TIMEOUT + WCD_MBHC_USLEEP_RANGE_MARGIN_US); } else { pr_debug("%s: MBHC Firmware read succesful\n", __func__); break; } } if (!fw_data) pr_debug("%s: using request_firmware\n", __func__); else pr_debug("%s: using hwdep cal\n", __func__); if (ret != 0 && !fw_data) { pr_err("%s: Cannot load MBHC firmware use default cal\n", __func__); use_default_cal = true; } if (!use_default_cal) { const void *data; size_t size; if (fw_data) { data = fw_data->data; size = fw_data->size; } else { data = fw->data; size = fw->size; } if (wcd_mbhc_fw_validate(data, size) == false) { pr_err("%s: Invalid MBHC cal data size use default cal\n", __func__); if (!fw_data) release_firmware(fw); } else { if (fw_data) { mbhc->mbhc_cfg->calibration = (void *)fw_data->data; mbhc->mbhc_cal = fw_data; } else { mbhc->mbhc_cfg->calibration = (void *)fw->data; mbhc->mbhc_fw = fw; } } } (void) wcd_mbhc_initialise(mbhc); } int wcd_mbhc_set_keycode(struct wcd_mbhc *mbhc) { enum snd_jack_types type; int i, ret, result = 0; int *btn_key_code; btn_key_code = mbhc->mbhc_cfg->key_code; for (i = 0 ; i < WCD_MBHC_KEYCODE_NUM ; i++) { if (btn_key_code[i] != 0) { switch (i) { case 0: type = SND_JACK_BTN_0; break; case 1: type = SND_JACK_BTN_1; break; case 2: type = SND_JACK_BTN_2; break; case 3: type = SND_JACK_BTN_3; break; case 4: type = SND_JACK_BTN_4; break; case 5: type = SND_JACK_BTN_5; break; case 6: type = SND_JACK_BTN_6; break; case 7: type = SND_JACK_BTN_7; break; default: WARN_ONCE(1, "Wrong button number:%d\n", i); result = -1; return result; } ret = snd_jack_set_key(mbhc->button_jack.jack, type, btn_key_code[i]); if (ret) { pr_err("%s: Failed to set code for %d\n", __func__, btn_key_code[i]); result = -1; return result; } input_set_capability( mbhc->button_jack.jack->input_dev, EV_KEY, btn_key_code[i]); pr_debug("%s: set btn%d key code:%d\n", __func__, i, btn_key_code[i]); } } if (btn_key_code[0]) mbhc->is_btn_already_regd = true; return result; } int wcd_mbhc_start(struct wcd_mbhc *mbhc, struct wcd_mbhc_config *mbhc_cfg) { int rc = 0; pr_debug("%s: enter\n", __func__); /* update the mbhc config */ mbhc->mbhc_cfg = mbhc_cfg; /* Set btn key code */ if ((!mbhc->is_btn_already_regd) && wcd_mbhc_set_keycode(mbhc)) pr_err("Set btn key code error!!!\n"); if (!mbhc->mbhc_cfg->read_fw_bin || (mbhc->mbhc_cfg->read_fw_bin && mbhc->mbhc_fw) || (mbhc->mbhc_cfg->read_fw_bin && mbhc->mbhc_cal)) { rc = wcd_mbhc_initialise(mbhc); } else { if (!mbhc->mbhc_fw || !mbhc->mbhc_cal) schedule_delayed_work(&mbhc->mbhc_firmware_dwork, usecs_to_jiffies(FW_READ_TIMEOUT)); else pr_err("%s: Skipping to read mbhc fw, 0x%p %p\n", __func__, mbhc->mbhc_fw, mbhc->mbhc_cal); } pr_debug("%s: leave %d\n", __func__, rc); return rc; } EXPORT_SYMBOL(wcd_mbhc_start); void wcd_mbhc_stop(struct wcd_mbhc *mbhc) { pr_debug("%s: enter\n", __func__); if (mbhc->current_plug != MBHC_PLUG_TYPE_NONE) { if (mbhc->mbhc_cb && mbhc->mbhc_cb->skip_imped_detect) mbhc->mbhc_cb->skip_imped_detect(mbhc->codec); } mbhc->current_plug = MBHC_PLUG_TYPE_NONE; mbhc->hph_status = 0; mbhc->mbhc_cb->irq_control(mbhc->codec, mbhc->intr_ids->hph_left_ocp, false); mbhc->mbhc_cb->irq_control(mbhc->codec, mbhc->intr_ids->hph_right_ocp, false); if (mbhc->mbhc_fw || mbhc->mbhc_cal) { cancel_delayed_work_sync(&mbhc->mbhc_firmware_dwork); if (!mbhc->mbhc_cal) release_firmware(mbhc->mbhc_fw); mbhc->mbhc_fw = NULL; mbhc->mbhc_cal = NULL; } pr_debug("%s: leave\n", __func__); } EXPORT_SYMBOL(wcd_mbhc_stop); /* * wcd_mbhc_init : initialize MBHC internal structures. * * NOTE: mbhc->mbhc_cfg is not YET configure so shouldn't be used */ int wcd_mbhc_init(struct wcd_mbhc *mbhc, struct snd_soc_codec *codec, const struct wcd_mbhc_cb *mbhc_cb, const struct wcd_mbhc_intr *mbhc_cdc_intr_ids, struct wcd_mbhc_register *wcd_mbhc_regs, bool impedance_det_en) { int ret = 0; int hph_swh = 0; int gnd_swh = 0; struct snd_soc_card *card = codec->component.card; const char *hph_switch = "qcom,msm-mbhc-hphl-swh"; const char *gnd_switch = "qcom,msm-mbhc-gnd-swh"; pr_debug("%s: enter\n", __func__); ret = of_property_read_u32(card->dev->of_node, hph_switch, &hph_swh); if (ret) { dev_err(card->dev, "%s: missing %s in dt node\n", __func__, hph_switch); goto err; } ret = of_property_read_u32(card->dev->of_node, gnd_switch, &gnd_swh); if (ret) { dev_err(card->dev, "%s: missing %s in dt node\n", __func__, gnd_switch); goto err; } mbhc->in_swch_irq_handler = false; mbhc->current_plug = MBHC_PLUG_TYPE_NONE; mbhc->is_btn_press = false; mbhc->codec = codec; mbhc->intr_ids = mbhc_cdc_intr_ids; mbhc->impedance_detect = impedance_det_en; mbhc->hphl_swh = hph_swh; mbhc->gnd_swh = gnd_swh; mbhc->micbias_enable = false; mbhc->mbhc_cb = mbhc_cb; mbhc->btn_press_intr = false; mbhc->is_hs_recording = false; mbhc->is_extn_cable = false; mbhc->hph_type = WCD_MBHC_HPH_NONE; mbhc->wcd_mbhc_regs = wcd_mbhc_regs; if (mbhc->intr_ids == NULL) { pr_err("%s: Interrupt mapping not provided\n", __func__); return -EINVAL; } if (!mbhc->wcd_mbhc_regs) { dev_err(codec->dev, "%s: mbhc registers are not defined\n", __func__); return -EINVAL; } /* Check if IRQ and other required callbacks are defined or not */ if (!mbhc_cb || !mbhc_cb->request_irq || !mbhc_cb->irq_control || !mbhc_cb->free_irq || !mbhc_cb->map_btn_code_to_num || !mbhc_cb->lock_sleep || !mbhc_cb->mbhc_bias || !mbhc_cb->set_btn_thr) { dev_err(codec->dev, "%s: required mbhc callbacks are not defined\n", __func__); return -EINVAL; } if (mbhc->headset_jack.jack == NULL) { ret = snd_soc_jack_new(codec, "Headset Jack", WCD_MBHC_JACK_MASK, &mbhc->headset_jack); if (ret) { pr_err("%s: Failed to create new jack\n", __func__); return ret; } ret = snd_soc_jack_new(codec, "Button Jack", WCD_MBHC_JACK_BUTTON_MASK, &mbhc->button_jack); if (ret) { pr_err("Failed to create new jack\n"); return ret; } ret = snd_jack_set_key(mbhc->button_jack.jack, SND_JACK_BTN_0, KEY_MEDIA); if (ret) { pr_err("%s: Failed to set code for btn-0\n", __func__); return ret; } ret = snd_jack_set_key(mbhc->button_jack.jack, SND_JACK_BTN_1, KEY_VOLUMEUP); if (ret) { pr_err("%s: Failed to set code for btn-0\n", __func__); return ret; } ret = snd_jack_set_key(mbhc->button_jack.jack, SND_JACK_BTN_2, KEY_VOLUMEDOWN); if (ret) { pr_err("%s: Failed to set code for btn-0\n", __func__); return ret; } set_bit(INPUT_PROP_NO_DUMMY_RELEASE, mbhc->button_jack.jack->input_dev->propbit); INIT_DELAYED_WORK(&mbhc->mbhc_firmware_dwork, wcd_mbhc_fw_read); INIT_DELAYED_WORK(&mbhc->mbhc_btn_dwork, wcd_btn_lpress_fn); } mutex_init(&mbhc->hphl_pa_lock); mutex_init(&mbhc->hphr_pa_lock); /* Register event notifier */ mbhc->nblock.notifier_call = wcd_event_notify; if (mbhc->mbhc_cb->register_notifier) { ret = mbhc->mbhc_cb->register_notifier(codec, &mbhc->nblock, true); if (ret) { pr_err("%s: Failed to register notifier %d\n", __func__, ret); return ret; } } init_waitqueue_head(&mbhc->wait_btn_press); mutex_init(&mbhc->codec_resource_lock); ret = mbhc->mbhc_cb->request_irq(codec, mbhc->intr_ids->mbhc_sw_intr, wcd_mbhc_mech_plug_detect_irq, "mbhc sw intr", mbhc); if (ret) { pr_err("%s: Failed to request irq %d, ret = %d\n", __func__, mbhc->intr_ids->mbhc_sw_intr, ret); goto err_mbhc_sw_irq; } ret = mbhc->mbhc_cb->request_irq(codec, mbhc->intr_ids->mbhc_btn_press_intr, wcd_mbhc_btn_press_handler, "Button Press detect", mbhc); if (ret) { pr_err("%s: Failed to request irq %d\n", __func__, mbhc->intr_ids->mbhc_btn_press_intr); goto err_btn_press_irq; } ret = mbhc->mbhc_cb->request_irq(codec, mbhc->intr_ids->mbhc_btn_release_intr, wcd_mbhc_release_handler, "Button Release detect", mbhc); if (ret) { pr_err("%s: Failed to request irq %d\n", __func__, mbhc->intr_ids->mbhc_btn_release_intr); goto err_btn_release_irq; } ret = mbhc->mbhc_cb->request_irq(codec, mbhc->intr_ids->mbhc_hs_ins_intr, wcd_mbhc_hs_ins_irq, "Elect Insert", mbhc); if (ret) { pr_err("%s: Failed to request irq %d\n", __func__, mbhc->intr_ids->mbhc_hs_ins_intr); goto err_mbhc_hs_ins_irq; } mbhc->mbhc_cb->irq_control(codec, mbhc->intr_ids->mbhc_hs_ins_intr, false); clear_bit(WCD_MBHC_ELEC_HS_INS, &mbhc->intr_status); ret = mbhc->mbhc_cb->request_irq(codec, mbhc->intr_ids->mbhc_hs_rem_intr, wcd_mbhc_hs_rem_irq, "Elect Remove", mbhc); if (ret) { pr_err("%s: Failed to request irq %d\n", __func__, mbhc->intr_ids->mbhc_hs_rem_intr); goto err_mbhc_hs_rem_irq; } mbhc->mbhc_cb->irq_control(codec, mbhc->intr_ids->mbhc_hs_rem_intr, false); clear_bit(WCD_MBHC_ELEC_HS_REM, &mbhc->intr_status); ret = mbhc->mbhc_cb->request_irq(codec, mbhc->intr_ids->hph_left_ocp, wcd_mbhc_hphl_ocp_irq, "HPH_L OCP detect", mbhc); if (ret) { pr_err("%s: Failed to request irq %d\n", __func__, mbhc->intr_ids->hph_left_ocp); goto err_hphl_ocp_irq; } ret = mbhc->mbhc_cb->request_irq(codec, mbhc->intr_ids->hph_right_ocp, wcd_mbhc_hphr_ocp_irq, "HPH_R OCP detect", mbhc); if (ret) { pr_err("%s: Failed to request irq %d\n", __func__, mbhc->intr_ids->hph_right_ocp); goto err_hphr_ocp_irq; } pr_debug("%s: leave ret %d\n", __func__, ret); return ret; err_hphr_ocp_irq: mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->hph_left_ocp, mbhc); err_hphl_ocp_irq: mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_hs_rem_intr, mbhc); err_mbhc_hs_rem_irq: mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_hs_ins_intr, mbhc); err_mbhc_hs_ins_irq: mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_btn_release_intr, mbhc); err_btn_release_irq: mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_btn_press_intr, mbhc); err_btn_press_irq: mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_sw_intr, mbhc); err_mbhc_sw_irq: if (mbhc->mbhc_cb->register_notifier) mbhc->mbhc_cb->register_notifier(codec, &mbhc->nblock, false); mutex_destroy(&mbhc->codec_resource_lock); err: pr_debug("%s: leave ret %d\n", __func__, ret); return ret; } EXPORT_SYMBOL(wcd_mbhc_init); void wcd_mbhc_deinit(struct wcd_mbhc *mbhc) { struct snd_soc_codec *codec = mbhc->codec; mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_sw_intr, mbhc); mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_btn_press_intr, mbhc); mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_btn_release_intr, mbhc); mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_hs_ins_intr, mbhc); mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->mbhc_hs_rem_intr, mbhc); mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->hph_left_ocp, mbhc); mbhc->mbhc_cb->free_irq(codec, mbhc->intr_ids->hph_right_ocp, mbhc); if (mbhc->mbhc_cb && mbhc->mbhc_cb->register_notifier) mbhc->mbhc_cb->register_notifier(codec, &mbhc->nblock, false); mutex_destroy(&mbhc->codec_resource_lock); } EXPORT_SYMBOL(wcd_mbhc_deinit); MODULE_DESCRIPTION("wcd MBHC v2 module"); MODULE_LICENSE("GPL v2");
F4uzan/mono_oneplus3
sound/soc/codecs/wcd-mbhc-v2.c
C
gpl-2.0
76,095
<?php /** * @file * Customize the display of a complete webform. * * This file may be renamed "webform-form-[nid].tpl.php" to target a specific * webform on your site. Or you can leave it "webform-form.tpl.php" to affect * all webforms on your site. * * Available variables: * - $form: The complete form array. * - $nid: The node ID of the Webform. * * The $form array contains two main pieces: * - $form['submitted']: The main content of the user-created form. * - $form['details']: Internal information stored by Webform. */ ?> <div class="row"> <div class="col-md-4 col-sm-12"></div> <div class="col-md-4 col-sm-12"> <div id="content-contact-form"> <div id="form-contacto"> <h3>Contáctanos</h3> <?php // Print out the main part of the form. // Feel free to break this up and move the pieces within the array. print drupal_render($form['submitted']); // Always print out the entire $form. This renders the remaining pieces of the // form that haven't yet been rendered above. print drupal_render_children($form); ?> </div> </div> </div> <div class="col-md-4 col-sm-12"></div> </div>
eforerop2888/fotografias
sites/all/themes/fotografias/templates/webform-form-33.tpl.php
PHP
gpl-2.0
1,215
#ifndef _ITEM_LIST_H_ #define _ITEM_LIST_H_ #include "base/ObjectList.h" #include "Item.h" #include <string> using std::string; class ItemList : public ObjectList { public: ItemList (const uint64 &max_size = UINT_MAX) ; virtual ~ItemList () ; public: typedef STLObjectList STLItemList ; typedef STLItemList::iterator STLItemList_it ; typedef STLItemList::const_iterator STLItemList_cit ; public: virtual const bool operator< (const Object& rObject) const ; virtual const bool operator> (const Object& rObject) const ; virtual const bool operator<= (const Object& rObject) const ; virtual const bool operator>= (const Object& rObject) const ; virtual const bool operator== (const Object& rObject) const ; public: Item* GetItemByValue (const string &value) const ; void ClearItemProjectionTransactionLists () ; public: virtual const string GetPrintableString () const ; public: void Print () const ; }; #endif
leandrocosta/machado
src/ItemList.h
C
gpl-2.0
968
import mainUi.main mainUi.main.main()
MiiRaGe/cryptanalysis-tools
run.py
Python
gpl-2.0
39
/* * Generated by asn1c-0.9.22 (http://lionet.info/asn1c) * From ASN.1 module "CryptographicMessageSyntax2004" * found in "lpa2.asn1" * `asn1c -S/skeletons` */ #include <asn_internal.h> #include "SignatureAlgorithmIdentifier.h" int SignatureAlgorithmIdentifier_constraint(asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { /* Replace with underlying type checker */ td->check_constraints = asn_DEF_AlgorithmIdentifier.check_constraints; return td->check_constraints(td, sptr, ctfailcb, app_key); } /* * This type is implemented using AlgorithmIdentifier, * so here we adjust the DEF accordingly. */ static void SignatureAlgorithmIdentifier_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { td->free_struct = asn_DEF_AlgorithmIdentifier.free_struct; td->print_struct = asn_DEF_AlgorithmIdentifier.print_struct; td->ber_decoder = asn_DEF_AlgorithmIdentifier.ber_decoder; td->der_encoder = asn_DEF_AlgorithmIdentifier.der_encoder; td->xer_decoder = asn_DEF_AlgorithmIdentifier.xer_decoder; td->xer_encoder = asn_DEF_AlgorithmIdentifier.xer_encoder; td->uper_decoder = asn_DEF_AlgorithmIdentifier.uper_decoder; td->uper_encoder = asn_DEF_AlgorithmIdentifier.uper_encoder; if(!td->per_constraints) td->per_constraints = asn_DEF_AlgorithmIdentifier.per_constraints; td->elements = asn_DEF_AlgorithmIdentifier.elements; td->elements_count = asn_DEF_AlgorithmIdentifier.elements_count; td->specifics = asn_DEF_AlgorithmIdentifier.specifics; } void SignatureAlgorithmIdentifier_free(asn_TYPE_descriptor_t *td, void *struct_ptr, int contents_only) { SignatureAlgorithmIdentifier_1_inherit_TYPE_descriptor(td); td->free_struct(td, struct_ptr, contents_only); } int SignatureAlgorithmIdentifier_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { SignatureAlgorithmIdentifier_1_inherit_TYPE_descriptor(td); return td->print_struct(td, struct_ptr, ilevel, cb, app_key); } asn_dec_rval_t SignatureAlgorithmIdentifier_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const void *bufptr, size_t size, int tag_mode) { SignatureAlgorithmIdentifier_1_inherit_TYPE_descriptor(td); return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); } asn_enc_rval_t SignatureAlgorithmIdentifier_encode_der(asn_TYPE_descriptor_t *td, void *structure, int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb, void *app_key) { SignatureAlgorithmIdentifier_1_inherit_TYPE_descriptor(td); return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); } asn_dec_rval_t SignatureAlgorithmIdentifier_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const char *opt_mname, const void *bufptr, size_t size) { SignatureAlgorithmIdentifier_1_inherit_TYPE_descriptor(td); return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); } asn_enc_rval_t SignatureAlgorithmIdentifier_encode_xer(asn_TYPE_descriptor_t *td, void *structure, int ilevel, enum xer_encoder_flags_e flags, asn_app_consume_bytes_f *cb, void *app_key) { SignatureAlgorithmIdentifier_1_inherit_TYPE_descriptor(td); return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); } static ber_tlv_tag_t asn_DEF_SignatureAlgorithmIdentifier_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; asn_TYPE_descriptor_t asn_DEF_SignatureAlgorithmIdentifier = { "SignatureAlgorithmIdentifier", "SignatureAlgorithmIdentifier", SignatureAlgorithmIdentifier_free, SignatureAlgorithmIdentifier_print, SignatureAlgorithmIdentifier_constraint, SignatureAlgorithmIdentifier_decode_ber, SignatureAlgorithmIdentifier_encode_der, SignatureAlgorithmIdentifier_decode_xer, SignatureAlgorithmIdentifier_encode_xer, 0, 0, /* No PER support, use "-gen-PER" to enable */ 0, /* Use generic outmost tag fetcher */ asn_DEF_SignatureAlgorithmIdentifier_tags_1, sizeof(asn_DEF_SignatureAlgorithmIdentifier_tags_1) /sizeof(asn_DEF_SignatureAlgorithmIdentifier_tags_1[0]), /* 1 */ asn_DEF_SignatureAlgorithmIdentifier_tags_1, /* Same as above */ sizeof(asn_DEF_SignatureAlgorithmIdentifier_tags_1) /sizeof(asn_DEF_SignatureAlgorithmIdentifier_tags_1[0]), /* 1 */ 0, /* No PER visible constraints */ 0, 0, /* Defined elsewhere */ 0 /* No specifics */ };
lades-unb/asn1pas
src/SignatureAlgorithmIdentifier.c
C
gpl-2.0
4,422
/* * functions.c: Implementation of the XSLT extra functions * * Reference: * http://www.w3.org/TR/1999/REC-xslt-19991116 * * See Copyright for the status of this software. * * daniel@veillard.com * Bjorn Reese <breese@users.sourceforge.net> for number formatting */ #define IN_LIBXSLT #include "libxslt.h" #include <string.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_CTYPE_H #include <ctype.h> #endif #include <libxml/xmlmemory.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/valid.h> #include <libxml/hash.h> #include <libxml/xmlerror.h> #include <libxml/xpath.h> #include <libxml/xpathInternals.h> #include <libxml/parserInternals.h> #include <libxml/uri.h> #include <libxml/xpointer.h> #include "xslt.h" #include "xsltInternals.h" #include "xsltutils.h" #include "functions.h" #include "extensions.h" #include "numbersInternals.h" #include "keys.h" #include "documents.h" #ifdef WITH_XSLT_DEBUG #define WITH_XSLT_DEBUG_FUNCTION #endif /* * Some versions of DocBook XSL use the vendor string to detect * supporting chunking, this is a workaround to be considered * in the list of decent XSLT processors <grin/> */ #define DOCBOOK_XSL_HACK /** * xsltXPathFunctionLookup: * @ctxt: a void * but the XSLT transformation context actually * @name: the function name * @ns_uri: the function namespace URI * * This is the entry point when a function is needed by the XPath * interpretor. * * Returns the callback function or NULL if not found */ xmlXPathFunction xsltXPathFunctionLookup (xmlXPathContextPtr ctxt, const xmlChar *name, const xmlChar *ns_uri) { xmlXPathFunction ret; if ((ctxt == NULL) || (name == NULL) || (ns_uri == NULL)) return (NULL); #ifdef WITH_XSLT_DEBUG_FUNCTION xsltGenericDebug(xsltGenericDebugContext, "Lookup function {%s}%s\n", ns_uri, name); #endif /* give priority to context-level functions */ /* ret = (xmlXPathFunction) xmlHashLookup2(ctxt->funcHash, name, ns_uri); */ XML_CAST_FPTR(ret) = xmlHashLookup2(ctxt->funcHash, name, ns_uri); if (ret == NULL) ret = xsltExtModuleFunctionLookup(name, ns_uri); #ifdef WITH_XSLT_DEBUG_FUNCTION if (ret != NULL) xsltGenericDebug(xsltGenericDebugContext, "found function %s\n", name); #endif return(ret); } /************************************************************************ * * * Module interfaces * * * ************************************************************************/ static void xsltDocumentFunctionLoadDocument(xmlXPathParserContextPtr ctxt, xmlChar* URI) { xsltTransformContextPtr tctxt; xmlURIPtr uri; xmlChar *fragment; xsltDocumentPtr idoc; /* document info */ xmlDocPtr doc; xmlXPathContextPtr xptrctxt = NULL; xmlXPathObjectPtr resObj = NULL; tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) { xsltTransformError(NULL, NULL, NULL, "document() : internal error tctxt == NULL\n"); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } uri = xmlParseURI((const char *) URI); if (uri == NULL) { xsltTransformError(tctxt, NULL, NULL, "document() : failed to parse URI\n"); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); return; } /* * check for and remove fragment identifier */ fragment = (xmlChar *)uri->fragment; if (fragment != NULL) { xmlChar *newURI; uri->fragment = NULL; newURI = xmlSaveUri(uri); idoc = xsltLoadDocument(tctxt, newURI); xmlFree(newURI); } else idoc = xsltLoadDocument(tctxt, URI); xmlFreeURI(uri); if (idoc == NULL) { if ((URI == NULL) || (URI[0] == '#') || ((tctxt->style->doc != NULL) && (xmlStrEqual(tctxt->style->doc->URL, URI)))) { /* * This selects the stylesheet's doc itself. */ doc = tctxt->style->doc; } else { valuePush(ctxt, xmlXPathNewNodeSet(NULL)); if (fragment != NULL) xmlFree(fragment); return; } } else doc = idoc->doc; if (fragment == NULL) { valuePush(ctxt, xmlXPathNewNodeSet((xmlNodePtr) doc)); return; } /* use XPointer of HTML location for fragment ID */ #ifdef LIBXML_XPTR_ENABLED xptrctxt = xmlXPtrNewContext(doc, NULL, NULL); if (xptrctxt == NULL) { xsltTransformError(tctxt, NULL, NULL, "document() : internal error xptrctxt == NULL\n"); goto out_fragment; } resObj = xmlXPtrEval(fragment, xptrctxt); xmlXPathFreeContext(xptrctxt); #endif xmlFree(fragment); if (resObj == NULL) goto out_fragment; switch (resObj->type) { case XPATH_NODESET: break; case XPATH_UNDEFINED: case XPATH_BOOLEAN: case XPATH_NUMBER: case XPATH_STRING: case XPATH_POINT: case XPATH_USERS: case XPATH_XSLT_TREE: case XPATH_RANGE: case XPATH_LOCATIONSET: xsltTransformError(tctxt, NULL, NULL, "document() : XPointer does not select a node set: #%s\n", fragment); goto out_object; } valuePush(ctxt, resObj); return; out_object: xmlXPathFreeObject(resObj); out_fragment: valuePush(ctxt, xmlXPathNewNodeSet(NULL)); } /** * xsltDocumentFunction: * @ctxt: the XPath Parser context * @nargs: the number of arguments * * Implement the document() XSLT function * node-set document(object, node-set?) */ void xsltDocumentFunction(xmlXPathParserContextPtr ctxt, int nargs) { xmlXPathObjectPtr obj, obj2 = NULL; xmlChar *base = NULL, *URI; if ((nargs < 1) || (nargs > 2)) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "document() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } if (ctxt->value == NULL) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "document() : invalid arg value\n"); ctxt->error = XPATH_INVALID_TYPE; return; } if (nargs == 2) { if (ctxt->value->type != XPATH_NODESET) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "document() : invalid arg expecting a nodeset\n"); ctxt->error = XPATH_INVALID_TYPE; return; } obj2 = valuePop(ctxt); } if (ctxt->value->type == XPATH_NODESET) { int i; xmlXPathObjectPtr newobj, ret; obj = valuePop(ctxt); ret = xmlXPathNewNodeSet(NULL); if (obj->nodesetval) { for (i = 0; i < obj->nodesetval->nodeNr; i++) { valuePush(ctxt, xmlXPathNewNodeSet(obj->nodesetval->nodeTab[i])); xmlXPathStringFunction(ctxt, 1); if (nargs == 2) { valuePush(ctxt, xmlXPathObjectCopy(obj2)); } else { valuePush(ctxt, xmlXPathNewNodeSet(obj->nodesetval-> nodeTab[i])); } xsltDocumentFunction(ctxt, 2); newobj = valuePop(ctxt); ret->nodesetval = xmlXPathNodeSetMerge(ret->nodesetval, newobj->nodesetval); xmlXPathFreeObject(newobj); } } xmlXPathFreeObject(obj); if (obj2 != NULL) xmlXPathFreeObject(obj2); valuePush(ctxt, ret); return; } /* * Make sure it's converted to a string */ xmlXPathStringFunction(ctxt, 1); if (ctxt->value->type != XPATH_STRING) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "document() : invalid arg expecting a string\n"); ctxt->error = XPATH_INVALID_TYPE; if (obj2 != NULL) xmlXPathFreeObject(obj2); return; } obj = valuePop(ctxt); if (obj->stringval == NULL) { valuePush(ctxt, xmlXPathNewNodeSet(NULL)); } else { xsltTransformContextPtr tctxt; tctxt = xsltXPathGetTransformContext(ctxt); if ((obj2 != NULL) && (obj2->nodesetval != NULL) && (obj2->nodesetval->nodeNr > 0) && IS_XSLT_REAL_NODE(obj2->nodesetval->nodeTab[0])) { xmlNodePtr target; target = obj2->nodesetval->nodeTab[0]; if ((target->type == XML_ATTRIBUTE_NODE) || (target->type == XML_PI_NODE)) { target = ((xmlAttrPtr) target)->parent; } base = xmlNodeGetBase(target->doc, target); } else { if ((tctxt != NULL) && (tctxt->inst != NULL)) { base = xmlNodeGetBase(tctxt->inst->doc, tctxt->inst); } else if ((tctxt != NULL) && (tctxt->style != NULL) && (tctxt->style->doc != NULL)) { base = xmlNodeGetBase(tctxt->style->doc, (xmlNodePtr) tctxt->style->doc); } } URI = xmlBuildURI(obj->stringval, base); if (base != NULL) xmlFree(base); if (URI == NULL) { if ((tctxt != NULL) && (tctxt->style != NULL) && (tctxt->style->doc != NULL) && (xmlStrEqual(URI, tctxt->style->doc->URL))) { /* This selects the stylesheet's doc itself. */ valuePush(ctxt, xmlXPathNewNodeSet((xmlNodePtr) tctxt->style->doc)); } else { valuePush(ctxt, xmlXPathNewNodeSet(NULL)); } } else { xsltDocumentFunctionLoadDocument( ctxt, URI ); xmlFree(URI); } } xmlXPathFreeObject(obj); if (obj2 != NULL) xmlXPathFreeObject(obj2); } /** * xsltKeyFunction: * @ctxt: the XPath Parser context * @nargs: the number of arguments * * Implement the key() XSLT function * node-set key(string, object) */ void xsltKeyFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlXPathObjectPtr obj1, obj2; if (nargs != 2) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "key() : expects two arguments\n"); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Get the key's value. */ obj2 = valuePop(ctxt); xmlXPathStringFunction(ctxt, 1); if ((obj2 == NULL) || (ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "key() : invalid arg expecting a string\n"); ctxt->error = XPATH_INVALID_TYPE; xmlXPathFreeObject(obj2); return; } /* * Get the key's name. */ obj1 = valuePop(ctxt); if ((obj2->type == XPATH_NODESET) || (obj2->type == XPATH_XSLT_TREE)) { int i; xmlXPathObjectPtr newobj, ret; ret = xmlXPathNewNodeSet(NULL); if (obj2->nodesetval != NULL) { for (i = 0; i < obj2->nodesetval->nodeNr; i++) { valuePush(ctxt, xmlXPathObjectCopy(obj1)); valuePush(ctxt, xmlXPathNewNodeSet(obj2->nodesetval->nodeTab[i])); xmlXPathStringFunction(ctxt, 1); xsltKeyFunction(ctxt, 2); newobj = valuePop(ctxt); ret->nodesetval = xmlXPathNodeSetMerge(ret->nodesetval, newobj->nodesetval); xmlXPathFreeObject(newobj); } } valuePush(ctxt, ret); } else { xmlNodeSetPtr nodelist = NULL; xmlChar *key = NULL, *value; const xmlChar *keyURI; xsltTransformContextPtr tctxt; xmlChar *qname, *prefix; xmlXPathContextPtr xpctxt = ctxt->context; xmlNodePtr tmpNode = NULL; xsltDocumentPtr oldDocInfo; tctxt = xsltXPathGetTransformContext(ctxt); oldDocInfo = tctxt->document; if (xpctxt->node == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "Internal error in xsltKeyFunction(): " "The context node is not set on the XPath context.\n"); tctxt->state = XSLT_STATE_STOPPED; goto error; } /* * Get the associated namespace URI if qualified name */ qname = obj1->stringval; key = xmlSplitQName2(qname, &prefix); if (key == NULL) { key = xmlStrdup(obj1->stringval); keyURI = NULL; if (prefix != NULL) xmlFree(prefix); } else { if (prefix != NULL) { keyURI = xmlXPathNsLookup(xpctxt, prefix); if (keyURI == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "key() : prefix %s is not bound\n", prefix); /* * TODO: Shouldn't we stop here? */ } xmlFree(prefix); } else { keyURI = NULL; } } /* * Force conversion of first arg to string */ valuePush(ctxt, obj2); xmlXPathStringFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) { xsltTransformError(tctxt, NULL, tctxt->inst, "key() : invalid arg expecting a string\n"); ctxt->error = XPATH_INVALID_TYPE; goto error; } obj2 = valuePop(ctxt); value = obj2->stringval; /* * We need to ensure that ctxt->document is available for * xsltGetKey(). * First find the relevant doc, which is the context node's * owner doc; using context->doc is not safe, since * the doc could have been acquired via the document() function, * or the doc might be a Result Tree Fragment. * FUTURE INFO: In XSLT 2.0 the key() function takes an additional * argument indicating the doc to use. */ if (xpctxt->node->type == XML_NAMESPACE_DECL) { /* * REVISIT: This is a libxml hack! Check xpath.c for details. * The XPath module sets the owner element of a ns-node on * the ns->next field. */ if ((((xmlNsPtr) xpctxt->node)->next != NULL) && (((xmlNsPtr) xpctxt->node)->next->type == XML_ELEMENT_NODE)) { tmpNode = (xmlNodePtr) ((xmlNsPtr) xpctxt->node)->next; } } else tmpNode = xpctxt->node; if ((tmpNode == NULL) || (tmpNode->doc == NULL)) { xsltTransformError(tctxt, NULL, tctxt->inst, "Internal error in xsltKeyFunction(): " "Couldn't get the doc of the XPath context node.\n"); goto error; } if ((tctxt->document == NULL) || (tctxt->document->doc != tmpNode->doc)) { if (tmpNode->doc->name && (tmpNode->doc->name[0] == ' ')) { /* * This is a Result Tree Fragment. */ if (tmpNode->doc->_private == NULL) { tmpNode->doc->_private = xsltNewDocument(tctxt, tmpNode->doc); if (tmpNode->doc->_private == NULL) goto error; } tctxt->document = (xsltDocumentPtr) tmpNode->doc->_private; } else { /* * May be the initial source doc or a doc acquired via the * document() function. */ tctxt->document = xsltFindDocument(tctxt, tmpNode->doc); } if (tctxt->document == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "Internal error in xsltKeyFunction(): " "Could not get the document info of a context doc.\n"); tctxt->state = XSLT_STATE_STOPPED; goto error; } } /* * Get/compute the key value. */ nodelist = xsltGetKey(tctxt, key, keyURI, value); error: tctxt->document = oldDocInfo; valuePush(ctxt, xmlXPathWrapNodeSet( xmlXPathNodeSetMerge(NULL, nodelist))); if (key != NULL) xmlFree(key); } if (obj1 != NULL) xmlXPathFreeObject(obj1); if (obj2 != NULL) xmlXPathFreeObject(obj2); } /** * xsltUnparsedEntityURIFunction: * @ctxt: the XPath Parser context * @nargs: the number of arguments * * Implement the unparsed-entity-uri() XSLT function * string unparsed-entity-uri(string) */ void xsltUnparsedEntityURIFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlXPathObjectPtr obj; xmlChar *str; if ((nargs != 1) || (ctxt->value == NULL)) { xsltGenericError(xsltGenericErrorContext, "unparsed-entity-uri() : expects one string arg\n"); ctxt->error = XPATH_INVALID_ARITY; return; } obj = valuePop(ctxt); if (obj->type != XPATH_STRING) { obj = xmlXPathConvertString(obj); } str = obj->stringval; if (str == NULL) { valuePush(ctxt, xmlXPathNewString((const xmlChar *)"")); } else { xmlEntityPtr entity; entity = xmlGetDocEntity(ctxt->context->doc, str); if (entity == NULL) { valuePush(ctxt, xmlXPathNewString((const xmlChar *)"")); } else { if (entity->URI != NULL) valuePush(ctxt, xmlXPathNewString(entity->URI)); else valuePush(ctxt, xmlXPathNewString((const xmlChar *)"")); } } xmlXPathFreeObject(obj); } /** * xsltFormatNumberFunction: * @ctxt: the XPath Parser context * @nargs: the number of arguments * * Implement the format-number() XSLT function * string format-number(number, string, string?) */ void xsltFormatNumberFunction(xmlXPathParserContextPtr ctxt, int nargs) { xmlXPathObjectPtr numberObj = NULL; xmlXPathObjectPtr formatObj = NULL; xmlXPathObjectPtr decimalObj = NULL; xsltStylesheetPtr sheet; xsltDecimalFormatPtr formatValues; xmlChar *result; xsltTransformContextPtr tctxt; tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) return; sheet = tctxt->style; if (sheet == NULL) return; formatValues = sheet->decimalFormat; switch (nargs) { case 3: CAST_TO_STRING; decimalObj = valuePop(ctxt); formatValues = xsltDecimalFormatGetByName(sheet, decimalObj->stringval); if (formatValues == NULL) { xsltTransformError(tctxt, NULL, NULL, "format-number() : undeclared decimal format '%s'\n", decimalObj->stringval); } /* Intentional fall-through */ case 2: CAST_TO_STRING; formatObj = valuePop(ctxt); CAST_TO_NUMBER; numberObj = valuePop(ctxt); break; default: XP_ERROR(XPATH_INVALID_ARITY); } if (formatValues != NULL) { if (xsltFormatNumberConversion(formatValues, formatObj->stringval, numberObj->floatval, &result) == XPATH_EXPRESSION_OK) { valuePush(ctxt, xmlXPathNewString(result)); xmlFree(result); } } xmlXPathFreeObject(numberObj); xmlXPathFreeObject(formatObj); xmlXPathFreeObject(decimalObj); } /** * xsltGenerateIdFunction: * @ctxt: the XPath Parser context * @nargs: the number of arguments * * Implement the generate-id() XSLT function * string generate-id(node-set?) */ void xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlNodePtr cur = NULL; xmlXPathObjectPtr obj = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } if (obj) xmlXPathFreeObject(obj); val = (long)((char *)cur - (char *)doc); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); } /** * xsltSystemPropertyFunction: * @ctxt: the XPath Parser context * @nargs: the number of arguments * * Implement the system-property() XSLT function * object system-property(string) */ void xsltSystemPropertyFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlXPathObjectPtr obj; xmlChar *prefix, *name; const xmlChar *nsURI = NULL; if (nargs != 1) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "system-property() : expects one string arg\n"); ctxt->error = XPATH_INVALID_ARITY; return; } if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "system-property() : invalid arg expecting a string\n"); ctxt->error = XPATH_INVALID_TYPE; return; } obj = valuePop(ctxt); if (obj->stringval == NULL) { valuePush(ctxt, xmlXPathNewString((const xmlChar *)"")); } else { name = xmlSplitQName2(obj->stringval, &prefix); if (name == NULL) { name = xmlStrdup(obj->stringval); } else { nsURI = xmlXPathNsLookup(ctxt->context, prefix); if (nsURI == NULL) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "system-property() : prefix %s is not bound\n", prefix); } } if (xmlStrEqual(nsURI, XSLT_NAMESPACE)) { #ifdef DOCBOOK_XSL_HACK if (xmlStrEqual(name, (const xmlChar *)"vendor")) { xsltStylesheetPtr sheet; xsltTransformContextPtr tctxt; tctxt = xsltXPathGetTransformContext(ctxt); if ((tctxt != NULL) && (tctxt->inst != NULL) && (xmlStrEqual(tctxt->inst->name, BAD_CAST "variable")) && (tctxt->inst->parent != NULL) && (xmlStrEqual(tctxt->inst->parent->name, BAD_CAST "template"))) sheet = tctxt->style; else sheet = NULL; if ((sheet != NULL) && (sheet->doc != NULL) && (sheet->doc->URL != NULL) && (xmlStrstr(sheet->doc->URL, (const xmlChar *)"chunk") != NULL)) { valuePush(ctxt, xmlXPathNewString( (const xmlChar *)"libxslt (SAXON 6.2 compatible)")); } else { valuePush(ctxt, xmlXPathNewString( (const xmlChar *)XSLT_DEFAULT_VENDOR)); } } else #else if (xmlStrEqual(name, (const xmlChar *)"vendor")) { valuePush(ctxt, xmlXPathNewString( (const xmlChar *)XSLT_DEFAULT_VENDOR)); } else #endif if (xmlStrEqual(name, (const xmlChar *)"version")) { valuePush(ctxt, xmlXPathNewString( (const xmlChar *)XSLT_DEFAULT_VERSION)); } else if (xmlStrEqual(name, (const xmlChar *)"vendor-url")) { valuePush(ctxt, xmlXPathNewString( (const xmlChar *)XSLT_DEFAULT_URL)); } else { valuePush(ctxt, xmlXPathNewString((const xmlChar *)"")); } } else { valuePush(ctxt, xmlXPathNewString((const xmlChar *)"")); } if (name != NULL) xmlFree(name); if (prefix != NULL) xmlFree(prefix); } xmlXPathFreeObject(obj); } /** * xsltElementAvailableFunction: * @ctxt: the XPath Parser context * @nargs: the number of arguments * * Implement the element-available() XSLT function * boolean element-available(string) */ void xsltElementAvailableFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlXPathObjectPtr obj; xmlChar *prefix, *name; const xmlChar *nsURI = NULL; xsltTransformContextPtr tctxt; if (nargs != 1) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "element-available() : expects one string arg\n"); ctxt->error = XPATH_INVALID_ARITY; return; } xmlXPathStringFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "element-available() : invalid arg expecting a string\n"); ctxt->error = XPATH_INVALID_TYPE; return; } obj = valuePop(ctxt); tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "element-available() : internal error tctxt == NULL\n"); xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewBoolean(0)); return; } name = xmlSplitQName2(obj->stringval, &prefix); if (name == NULL) { xmlNsPtr ns; name = xmlStrdup(obj->stringval); ns = xmlSearchNs(tctxt->inst->doc, tctxt->inst, NULL); if (ns != NULL) nsURI = xmlStrdup(ns->href); } else { nsURI = xmlXPathNsLookup(ctxt->context, prefix); if (nsURI == NULL) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "element-available() : prefix %s is not bound\n", prefix); } } if (xsltExtElementLookup(tctxt, name, nsURI) != NULL) { valuePush(ctxt, xmlXPathNewBoolean(1)); } else { valuePush(ctxt, xmlXPathNewBoolean(0)); } xmlXPathFreeObject(obj); if (name != NULL) xmlFree(name); if (prefix != NULL) xmlFree(prefix); } /** * xsltFunctionAvailableFunction: * @ctxt: the XPath Parser context * @nargs: the number of arguments * * Implement the function-available() XSLT function * boolean function-available(string) */ void xsltFunctionAvailableFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlXPathObjectPtr obj; xmlChar *prefix, *name; const xmlChar *nsURI = NULL; if (nargs != 1) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "function-available() : expects one string arg\n"); ctxt->error = XPATH_INVALID_ARITY; return; } xmlXPathStringFunction(ctxt, 1); if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "function-available() : invalid arg expecting a string\n"); ctxt->error = XPATH_INVALID_TYPE; return; } obj = valuePop(ctxt); name = xmlSplitQName2(obj->stringval, &prefix); if (name == NULL) { name = xmlStrdup(obj->stringval); } else { nsURI = xmlXPathNsLookup(ctxt->context, prefix); if (nsURI == NULL) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "function-available() : prefix %s is not bound\n", prefix); } } if (xmlXPathFunctionLookupNS(ctxt->context, name, nsURI) != NULL) { valuePush(ctxt, xmlXPathNewBoolean(1)); } else { valuePush(ctxt, xmlXPathNewBoolean(0)); } xmlXPathFreeObject(obj); if (name != NULL) xmlFree(name); if (prefix != NULL) xmlFree(prefix); } /** * xsltCurrentFunction: * @ctxt: the XPath Parser context * @nargs: the number of arguments * * Implement the current() XSLT function * node-set current() */ static void xsltCurrentFunction(xmlXPathParserContextPtr ctxt, int nargs){ xsltTransformContextPtr tctxt; if (nargs != 0) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "current() : function uses no argument\n"); ctxt->error = XPATH_INVALID_ARITY; return; } tctxt = xsltXPathGetTransformContext(ctxt); if (tctxt == NULL) { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "current() : internal error tctxt == NULL\n"); valuePush(ctxt, xmlXPathNewNodeSet(NULL)); } else { valuePush(ctxt, xmlXPathNewNodeSet(tctxt->node)); /* current */ } } /************************************************************************ * * * Registration of XSLT and libxslt functions * * * ************************************************************************/ /** * xsltRegisterAllFunctions: * @ctxt: the XPath context * * Registers all default XSLT functions in this context */ void xsltRegisterAllFunctions(xmlXPathContextPtr ctxt) { xmlXPathRegisterFunc(ctxt, (const xmlChar *) "current", xsltCurrentFunction); xmlXPathRegisterFunc(ctxt, (const xmlChar *) "document", xsltDocumentFunction); xmlXPathRegisterFunc(ctxt, (const xmlChar *) "key", xsltKeyFunction); xmlXPathRegisterFunc(ctxt, (const xmlChar *) "unparsed-entity-uri", xsltUnparsedEntityURIFunction); xmlXPathRegisterFunc(ctxt, (const xmlChar *) "format-number", xsltFormatNumberFunction); xmlXPathRegisterFunc(ctxt, (const xmlChar *) "generate-id", xsltGenerateIdFunction); xmlXPathRegisterFunc(ctxt, (const xmlChar *) "system-property", xsltSystemPropertyFunction); xmlXPathRegisterFunc(ctxt, (const xmlChar *) "element-available", xsltElementAvailableFunction); xmlXPathRegisterFunc(ctxt, (const xmlChar *) "function-available", xsltFunctionAvailableFunction); }
twobob/buildroot-kindle
output/build/host-libxslt-1.1.27/libxslt/functions.c
C
gpl-2.0
28,342
#ifndef TAOBAOKEWIDGETSHOPSCONVERTRESPONSE_H #define TAOBAOKEWIDGETSHOPSCONVERTRESPONSE_H #include <TaoApiCpp/TaoResponse.h> #include <QList> #include <TaoApiCpp/domain/TaobaokeShop.h> /** * @brief TOP RESPONSE API: 淘客店铺转换,该接口只支持js方式去调用,具体的调用方式参考文档【http://open.taobao.com/doc/detail.htm?id=101372】 <p>淘宝客应用、网站接入的过程中,难免会遇到问题,这里对从接入到线上运营的各个环节最常碰到的问题,做了汇总,帮助开发者提高接入的效率。 </p> <p>一、淘宝客网站应用创建流程:<a href="http://open.taobao.com/doc/detail.htm?spm=0.0.0.34.b1f9de&id=1028">http://open.taobao.com/doc/detail.htm?spm=0.0.0.34.b1f9de&id=1028</a></p> <p>二、淘宝客API结合实际使用场景的介绍:<a href="http://open.taobao.com/doc/detail.htm?id=1014">http://open.taobao.com/doc/detail.htm?id=1014</a></p> <p>三、淘宝客网站官方推荐的架构:<a href="http://open.taobao.com/doc/detail.htm?id=1011">http://open.taobao.com/doc/detail.htm?id=1011</a></p> <p>四、淘宝客最常见的几个问题以及解决方案汇总:<a href="http://open.taobao.com/doc/detail.htm?id=1005">http://open.taobao.com/doc/detail.htm?id=1005</a></p> * * @author sd44 <sd44sdd44@yeah.net> */ class TaobaokeWidgetShopsConvertResponse : public TaoResponse { public: virtual ~TaobaokeWidgetShopsConvertResponse() { } QList<TaobaokeShop> getTaobaokeShops() const; void setTaobaokeShops (QList<TaobaokeShop> taobaokeShops); virtual void parseNormalResponse(); private: /** * @brief 淘宝客店铺对象列表,不能返回shop_type,seller_credit,auction_coun, total_auction **/ QList<TaobaokeShop> taobaokeShops; }; #endif
sd44/TaobaoCppQtSDK
TaoApiCpp/response/TaobaokeWidgetShopsConvertResponse.h
C
gpl-2.0
1,758
/* * Copyright (C) 2014-2017 StormCore * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "PlayerAI.h" #include "SpellAuras.h" #include "SpellAuraEffects.h" enum Spells { /* Generic */ SPELL_AUTO_SHOT = 75, SPELL_SHOOT = 3018, SPELL_THROW = 2764, SPELL_SHOOT_WAND = 5019, /* Warrior - Generic */ SPELL_BATTLE_STANCE = 2457, SPELL_BERSERKER_STANCE = 2458, SPELL_DEFENSIVE_STANCE = 71, SPELL_CHARGE = 11578, SPELL_INTERCEPT = 20252, SPELL_ENRAGED_REGEN = 55694, SPELL_INTIMIDATING_SHOUT= 5246, SPELL_PUMMEL = 6552, SPELL_SHIELD_BASH = 72, SPELL_BLOODRAGE = 2687, /* Warrior - Arms */ SPELL_SWEEPING_STRIKES = 12328, SPELL_MORTAL_STRIKE = 12294, SPELL_BLADESTORM = 46924, SPELL_REND = 47465, SPELL_RETALIATION = 20230, SPELL_SHATTERING_THROW = 64382, SPELL_THUNDER_CLAP = 47502, /* Warrior - Fury */ SPELL_DEATH_WISH = 12292, SPELL_BLOODTHIRST = 23881, PASSIVE_TITANS_GRIP = 46917, SPELL_DEMO_SHOUT = 47437, SPELL_EXECUTE = 47471, SPELL_HEROIC_FURY = 60970, SPELL_RECKLESSNESS = 1719, SPELL_PIERCING_HOWL = 12323, /* Warrior - Protection */ SPELL_VIGILANCE = 50720, SPELL_DEVASTATE = 20243, SPELL_SHOCKWAVE = 46968, SPELL_CONCUSSION_BLOW = 12809, SPELL_DISARM = 676, SPELL_LAST_STAND = 12975, SPELL_SHIELD_BLOCK = 2565, SPELL_SHIELD_SLAM = 47488, SPELL_SHIELD_WALL = 871, SPELL_SPELL_REFLECTION = 23920, /* Paladin - Generic */ SPELL_PAL_AURA_MASTERY = 31821, SPELL_LAY_ON_HANDS = 48788, SPELL_BLESSING_OF_MIGHT = 48932, SPELL_AVENGING_WRATH = 31884, SPELL_DIVINE_PROTECTION = 498, SPELL_DIVINE_SHIELD = 642, SPELL_HAMMER_OF_JUSTICE = 10308, SPELL_HAND_OF_FREEDOM = 1044, SPELL_HAND_OF_PROTECTION = 10278, SPELL_HAND_OF_SACRIFICE = 6940, /* Paladin - Holy*/ PASSIVE_ILLUMINATION = 20215, SPELL_HOLY_SHOCK = 20473, SPELL_BEACON_OF_LIGHT = 53563, SPELL_CONSECRATION = 48819, SPELL_FLASH_OF_LIGHT = 48785, SPELL_HOLY_LIGHT = 48782, SPELL_DIVINE_FAVOR = 20216, SPELL_DIVINE_ILLUMINATION = 31842, /* Paladin - Protection */ SPELL_BLESS_OF_SANC = 20911, SPELL_HOLY_SHIELD = 20925, SPELL_AVENGERS_SHIELD = 48827, SPELL_DIVINE_SACRIFICE = 64205, SPELL_HAMMER_OF_RIGHTEOUS = 53595, SPELL_RIGHTEOUS_FURY = 25780, SPELL_SHIELD_OF_RIGHTEOUS = 61411, /* Paladin - Retribution */ SPELL_SEAL_OF_COMMAND = 20375, SPELL_CRUSADER_STRIKE = 35395, SPELL_DIVINE_STORM = 53385, SPELL_JUDGEMENT = 20271, SPELL_HAMMER_OF_WRATH = 48806, /* Hunter - Generic */ SPELL_DETERRENCE = 19263, SPELL_EXPLOSIVE_TRAP = 49067, SPELL_FREEZING_ARROW = 60192, SPELL_RAPID_FIRE = 3045, SPELL_KILL_SHOT = 61006, SPELL_MULTI_SHOT = 49048, SPELL_VIPER_STING = 3034, /* Hunter - Beast Mastery */ SPELL_BESTIAL_WRATH = 19574, PASSIVE_BEAST_WITHIN = 34692, PASSIVE_BEAST_MASTERY = 53270, /* Hunter - Marksmanship */ SPELL_AIMED_SHOT = 19434, PASSIVE_TRUESHOT_AURA = 19506, SPELL_CHIMERA_SHOT = 53209, SPELL_ARCANE_SHOT = 49045, SPELL_STEADY_SHOT = 49052, SPELL_READINESS = 23989, SPELL_SILENCING_SHOT = 34490, /* Hunter - Survival */ PASSIVE_LOCK_AND_LOAD = 56344, SPELL_WYVERN_STING = 19386, SPELL_EXPLOSIVE_SHOT = 53301, SPELL_BLACK_ARROW = 3674, /* Rogue - Generic */ SPELL_DISMANTLE = 51722, SPELL_EVASION = 26669, SPELL_KICK = 1766, SPELL_VANISH = 26889, SPELL_BLIND = 2094, SPELL_CLOAK_OF_SHADOWS = 31224, /* Rogue - Assassination */ SPELL_COLD_BLOOD = 14177, SPELL_MUTILATE = 1329, SPELL_HUNGER_FOR_BLOOD = 51662, SPELL_ENVENOM = 57993, /* Rogue - Combat */ SPELL_SINISTER_STRIKE = 48637, SPELL_BLADE_FLURRY = 13877, SPELL_ADRENALINE_RUSH = 13750, SPELL_KILLING_SPREE = 51690, SPELL_EVISCERATE = 48668, /* Rogue - Sublety */ SPELL_HEMORRHAGE = 16511, SPELL_PREMEDITATION = 14183, SPELL_SHADOW_DANCE = 51713, SPELL_PREPARATION = 14185, SPELL_SHADOWSTEP = 36554, /* Priest - Generic */ SPELL_FEAR_WARD = 6346, SPELL_POWER_WORD_FORT = 48161, SPELL_DIVINE_SPIRIT = 48073, SPELL_SHADOW_PROTECTION = 48169, SPELL_DIVINE_HYMN = 64843, SPELL_HYMN_OF_HOPE = 64901, SPELL_SHADOW_WORD_DEATH = 48158, SPELL_PSYCHIC_SCREAM = 10890, /* Priest - Discipline */ PASSIVE_SOUL_WARDING = 63574, SPELL_POWER_INFUSION = 10060, SPELL_PENANCE = 47540, SPELL_PAIN_SUPPRESSION = 33206, SPELL_INNER_FOCUS = 14751, SPELL_POWER_WORD_SHIELD = 48066, /* Priest - Holy */ PASSIVE_SPIRIT_REDEMPTION = 20711, SPELL_DESPERATE_PRAYER = 19236, SPELL_GUARDIAN_SPIRIT = 47788, SPELL_FLASH_HEAL = 48071, SPELL_RENEW = 48068, /* Priest - Shadow */ SPELL_VAMPIRIC_EMBRACE = 15286, SPELL_SHADOWFORM = 15473, SPELL_VAMPIRIC_TOUCH = 34914, SPELL_MIND_FLAY = 15407, SPELL_MIND_BLAST = 48127, SPELL_SHADOW_WORD_PAIN = 48125, SPELL_DEVOURING_PLAGUE = 48300, SPELL_DISPERSION = 47585, /* Death Knight - Generic */ SPELL_DEATH_GRIP = 49576, SPELL_STRANGULATE = 47476, SPELL_EMPOWER_RUNE_WEAP = 47568, SPELL_ICEBORN_FORTITUDE = 48792, SPELL_ANTI_MAGIC_SHELL = 48707, SPELL_DEATH_COIL_DK = 49895, SPELL_MIND_FREEZE = 47528, SPELL_ICY_TOUCH = 49909, AURA_FROST_FEVER = 55095, SPELL_PLAGUE_STRIKE = 49921, AURA_BLOOD_PLAGUE = 55078, SPELL_PESTILENCE = 50842, /* Death Knight - Blood */ SPELL_RUNE_TAP = 48982, SPELL_HYSTERIA = 49016, SPELL_HEART_STRIKE = 55050, SPELL_DEATH_STRIKE = 49924, SPELL_BLOOD_STRIKE = 49930, SPELL_MARK_OF_BLOOD = 49005, SPELL_VAMPIRIC_BLOOD = 55233, /* Death Knight - Frost */ PASSIVE_ICY_TALONS = 50887, SPELL_FROST_STRIKE = 49143, SPELL_HOWLING_BLAST = 49184, SPELL_UNBREAKABLE_ARMOR = 51271, SPELL_OBLITERATE = 51425, SPELL_DEATHCHILL = 49796, /* Death Knight - Unholy */ PASSIVE_UNHOLY_BLIGHT = 49194, PASSIVE_MASTER_OF_GHOUL = 52143, SPELL_SCOURGE_STRIKE = 55090, SPELL_DEATH_AND_DECAY = 49938, SPELL_ANTI_MAGIC_ZONE = 51052, SPELL_SUMMON_GARGOYLE = 49206, /* Shaman - Generic */ SPELL_HEROISM = 32182, SPELL_BLOODLUST = 2825, SPELL_GROUNDING_TOTEM = 8177, /* Shaman - Elemental*/ PASSIVE_ELEMENTAL_FOCUS = 16164, SPELL_TOTEM_OF_WRATH = 30706, SPELL_THUNDERSTORM = 51490, SPELL_LIGHTNING_BOLT = 49238, SPELL_EARTH_SHOCK = 49231, SPELL_FLAME_SHOCK = 49233, SPELL_LAVA_BURST = 60043, SPELL_CHAIN_LIGHTNING = 49271, SPELL_ELEMENTAL_MASTERY = 16166, /* Shaman - Enhancement */ PASSIVE_SPIRIT_WEAPONS = 16268, SPELL_LAVA_LASH = 60103, SPELL_FERAL_SPIRIT = 51533, AURA_MAELSTROM_WEAPON = 53817, SPELL_STORMSTRIKE = 17364, SPELL_SHAMANISTIC_RAGE = 30823, /* Shaman - Restoration*/ SPELL_SHA_NATURE_SWIFT = 591, SPELL_MANA_TIDE_TOTEM = 590, SPELL_EARTH_SHIELD = 49284, SPELL_RIPTIDE = 61295, SPELL_HEALING_WAVE = 49273, SPELL_LESSER_HEAL_WAVE = 49276, SPELL_TIDAL_FORCE = 55198, /* Mage - Generic */ SPELL_DAMPEN_MAGIC = 43015, SPELL_EVOCATION = 12051, SPELL_MANA_SHIELD = 43020, SPELL_MIRROR_IMAGE = 55342, SPELL_SPELLSTEAL = 30449, SPELL_COUNTERSPELL = 2139, SPELL_ICE_BLOCK = 45438, /* Mage - Arcane */ SPELL_FOCUS_MAGIC = 54646, SPELL_ARCANE_POWER = 12042, SPELL_ARCANE_BARRAGE = 44425, SPELL_ARCANE_BLAST = 42897, AURA_ARCANE_BLAST = 36032, SPELL_ARCANE_MISSILES = 42846, SPELL_PRESENCE_OF_MIND = 12043, /* Mage - Fire */ SPELL_PYROBLAST = 11366, SPELL_COMBUSTION = 11129, SPELL_LIVING_BOMB = 44457, SPELL_FIREBALL = 42833, SPELL_FIRE_BLAST = 42873, SPELL_DRAGONS_BREATH = 31661, SPELL_BLAST_WAVE = 11113, /* Mage - Frost */ SPELL_ICY_VEINS = 12472, SPELL_ICE_BARRIER = 11426, SPELL_DEEP_FREEZE = 44572, SPELL_FROST_NOVA = 42917, SPELL_FROSTBOLT = 42842, SPELL_COLD_SNAP = 11958, SPELL_ICE_LANCE = 42914, /* Warlock - Generic */ SPELL_FEAR = 6215, SPELL_HOWL_OF_TERROR = 17928, SPELL_CORRUPTION = 47813, SPELL_DEATH_COIL_W = 47860, SPELL_SHADOW_BOLT = 47809, SPELL_INCINERATE = 47838, SPELL_IMMOLATE = 47811, SPELL_SEED_OF_CORRUPTION = 47836, /* Warlock - Affliction */ PASSIVE_SIPHON_LIFE = 63108, SPELL_UNSTABLE_AFFLICTION = 30108, SPELL_HAUNT = 48181, SPELL_CURSE_OF_AGONY = 47864, SPELL_DRAIN_SOUL = 47855, /* Warlock - Demonology */ SPELL_SOUL_LINK = 19028, SPELL_DEMONIC_EMPOWERMENT = 47193, SPELL_METAMORPHOSIS = 59672, SPELL_IMMOLATION_AURA = 50589, SPELL_DEMON_CHARGE = 54785, AURA_DECIMATION = 63167, AURA_MOLTEN_CORE = 71165, SPELL_SOUL_FIRE = 47825, /* Warlock - Destruction */ SPELL_SHADOWBURN = 17877, SPELL_CONFLAGRATE = 17962, SPELL_CHAOS_BOLT = 50796, SPELL_SHADOWFURY = 47847, /* Druid - Generic */ SPELL_BARKSKIN = 22812, SPELL_INNERVATE = 29166, /* Druid - Balance */ SPELL_INSECT_SWARM = 5570, SPELL_MOONKIN_FORM = 24858, SPELL_STARFALL = 48505, SPELL_TYPHOON = 61384, AURA_ECLIPSE_LUNAR = 48518, SPELL_MOONFIRE = 48463, SPELL_STARFIRE = 48465, SPELL_WRATH = 48461, /* Druid - Feral */ SPELL_CAT_FORM = 768, SPELL_SURVIVAL_INSTINCTS = 61336, SPELL_MANGLE = 33917, SPELL_BERSERK = 50334, SPELL_MANGLE_CAT = 48566, SPELL_FERAL_CHARGE_CAT = 49376, SPELL_RAKE = 48574, SPELL_RIP = 49800, SPELL_SAVAGE_ROAR = 52610, SPELL_TIGER_FURY = 50213, SPELL_CLAW = 48570, SPELL_DASH = 33357, SPELL_MAIM = 49802, /* Druid - Restoration */ SPELL_SWIFTMEND = 18562, SPELL_TREE_OF_LIFE = 33891, SPELL_WILD_GROWTH = 48438, SPELL_NATURE_SWIFTNESS = 17116, SPELL_TRANQUILITY = 48447, SPELL_NOURISH = 50464, SPELL_HEALING_TOUCH = 48378, SPELL_REJUVENATION = 48441, SPELL_REGROWTH = 48443, SPELL_LIFEBLOOM = 48451 }; bool PlayerAI::IsPlayerHealer(Player const* who) { if (!who) return false; switch (who->getClass()) { case CLASS_WARRIOR: case CLASS_HUNTER: case CLASS_ROGUE: case CLASS_DEATH_KNIGHT: case CLASS_MAGE: case CLASS_WARLOCK: case CLASS_DEMON_HUNTER: default: return false; case CLASS_PALADIN: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PALADIN_HOLY; case CLASS_PRIEST: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PRIEST_DISCIPLINE || who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PRIEST_HOLY; case CLASS_SHAMAN: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_SHAMAN_RESTORATION; case CLASS_MONK: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_MONK_MISTWEAVER; case CLASS_DRUID: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_DRUID_RESTORATION; } } bool PlayerAI::IsPlayerRangedAttacker(Player const* who) { if (!who) return false; switch (who->getClass()) { case CLASS_WARRIOR: case CLASS_PALADIN: case CLASS_ROGUE: case CLASS_DEATH_KNIGHT: default: return false; case CLASS_MAGE: case CLASS_WARLOCK: return true; case CLASS_HUNTER: { // check if we have a ranged weapon equipped Item const* rangedSlot = who->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); if (ItemTemplate const* rangedTemplate = rangedSlot ? rangedSlot->GetTemplate() : nullptr) if ((1 << rangedTemplate->GetSubClass()) & ITEM_SUBCLASS_MASK_WEAPON_RANGED) return true; return false; } case CLASS_PRIEST: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_PRIEST_SHADOW; case CLASS_SHAMAN: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_SHAMAN_ELEMENTAL; case CLASS_DRUID: return who->GetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID) == TALENT_SPEC_DRUID_BALANCE; } } PlayerAI::TargetedSpell PlayerAI::VerifySpellCast(uint32 spellId, Unit* target) { // Find highest spell rank that we know uint32 knownRank, nextRank; if (me->HasSpell(spellId)) { // this will save us some lookups if the player has the highest rank (expected case) knownRank = spellId; nextRank = sSpellMgr->GetNextSpellInChain(spellId); } else { knownRank = 0; nextRank = sSpellMgr->GetFirstSpellInChain(spellId); } while (nextRank && me->HasSpell(nextRank)) { knownRank = nextRank; nextRank = sSpellMgr->GetNextSpellInChain(knownRank); } if (!knownRank) return {}; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(knownRank); if (!spellInfo) return {}; if (me->GetSpellHistory()->HasGlobalCooldown(spellInfo)) return {}; Spell* spell = new Spell(me, spellInfo, TRIGGERED_NONE); if (spell->CanAutoCast(target)) return{ spell, target }; delete spell; return {}; } PlayerAI::TargetedSpell PlayerAI::VerifySpellCast(uint32 spellId, SpellTarget target) { Unit* pTarget = nullptr; switch (target) { case TARGET_NONE: break; case TARGET_VICTIM: pTarget = me->GetVictim(); if (!pTarget) return {}; break; case TARGET_CHARMER: pTarget = me->GetCharmer(); if (!pTarget) return {}; break; case TARGET_SELF: pTarget = me; break; } return VerifySpellCast(spellId, pTarget); } PlayerAI::TargetedSpell PlayerAI::SelectSpellCast(PossibleSpellVector& spells) { if (spells.empty()) return{}; uint32 totalWeights = 0; for (PossibleSpell const& wSpell : spells) totalWeights += wSpell.second; TargetedSpell selected; uint32 randNum = urand(0, totalWeights - 1); for (PossibleSpell const& wSpell : spells) { if (selected) { delete wSpell.first.first; continue; } if (randNum < wSpell.second) selected = wSpell.first; else { randNum -= wSpell.second; delete wSpell.first.first; } } spells.clear(); return selected; } void PlayerAI::DoRangedAttackIfReady() { if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (!me->isAttackReady(RANGED_ATTACK)) return; Unit* victim = me->GetVictim(); if (!victim) return; uint32 rangedAttackSpell = 0; Item const* rangedItem = me->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); if (ItemTemplate const* rangedTemplate = rangedItem ? rangedItem->GetTemplate() : nullptr) { switch (rangedTemplate->GetSubClass()) { case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_GUN: case ITEM_SUBCLASS_WEAPON_CROSSBOW: rangedAttackSpell = SPELL_SHOOT; break; case ITEM_SUBCLASS_WEAPON_THROWN: rangedAttackSpell = SPELL_THROW; break; case ITEM_SUBCLASS_WEAPON_WAND: rangedAttackSpell = SPELL_SHOOT_WAND; break; } } if (!rangedAttackSpell) return; me->CastSpell(victim, rangedAttackSpell, TRIGGERED_CAST_DIRECTLY); me->resetAttackTimer(RANGED_ATTACK); } void PlayerAI::DoAutoAttackIfReady() { if (IsRangedAttacker()) DoRangedAttackIfReady(); else DoMeleeAttackIfReady(); } void PlayerAI::CancelAllShapeshifts() { std::list<AuraEffect*> const& shapeshiftAuras = me->GetAuraEffectsByType(SPELL_AURA_MOD_SHAPESHIFT); std::set<Aura*> removableShapeshifts; for (AuraEffect* auraEff : shapeshiftAuras) { Aura* aura = auraEff->GetBase(); if (!aura) continue; SpellInfo const* auraInfo = aura->GetSpellInfo(); if (!auraInfo) continue; if (auraInfo->HasAttribute(SPELL_ATTR0_CANT_CANCEL)) continue; if (!auraInfo->IsPositive() || auraInfo->IsPassive()) continue; removableShapeshifts.insert(aura); } for (Aura* aura : removableShapeshifts) me->RemoveOwnedAura(aura, AURA_REMOVE_BY_CANCEL); } struct UncontrolledTargetSelectPredicate : public std::unary_function<Unit*, bool> { bool operator()(Unit const* target) const { return !target->HasBreakableByDamageCrowdControlAura(); } }; Unit* SimpleCharmedPlayerAI::SelectAttackTarget() const { if (Unit* charmer = me->GetCharmer()) return charmer->IsAIEnabled ? charmer->GetAI()->SelectTarget(SELECT_TARGET_RANDOM, 0, UncontrolledTargetSelectPredicate()) : charmer->GetVictim(); return nullptr; } PlayerAI::TargetedSpell SimpleCharmedPlayerAI::SelectAppropriateCastForSpec() { PossibleSpellVector spells; /* switch (me->getClass()) { case CLASS_WARRIOR: if (!me->IsWithinMeleeRange(me->GetVictim())) { VerifyAndPushSpellCast(spells, SPELL_CHARGE, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_INTERCEPT, TARGET_VICTIM, 10); } VerifyAndPushSpellCast(spells, SPELL_ENRAGED_REGEN, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_INTIMIDATING_SHOUT, TARGET_VICTIM, 4); if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) { VerifyAndPushSpellCast(spells, SPELL_PUMMEL, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_SHIELD_BASH, TARGET_VICTIM, 15); } VerifyAndPushSpellCast(spells, SPELL_BLOODRAGE, TARGET_NONE, 5); switch (GetSpec()) { case TALENT_SPEC_WARRIOR_PROTECTION: VerifyAndPushSpellCast(spells, SPELL_SHOCKWAVE, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_CONCUSSION_BLOW, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_DISARM, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_LAST_STAND, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_SHIELD_BLOCK, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_SHIELD_SLAM, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_SHIELD_WALL, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_SPELL_REFLECTION, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_DEVASTATE, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_REND, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_THUNDER_CLAP, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_DEMO_SHOUT, TARGET_VICTIM, 1); break; case TALENT_SPEC_WARRIOR_ARMS: VerifyAndPushSpellCast(spells, SPELL_SWEEPING_STRIKES, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_MORTAL_STRIKE, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_BLADESTORM, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_REND, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_RETALIATION, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_SHATTERING_THROW, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_SWEEPING_STRIKES, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_THUNDER_CLAP, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_EXECUTE, TARGET_VICTIM, 15); break; case TALENT_SPEC_WARRIOR_FURY: VerifyAndPushSpellCast(spells, SPELL_DEATH_WISH, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_BLOODTHIRST, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_DEMO_SHOUT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_EXECUTE, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_HEROIC_FURY, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_RECKLESSNESS, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_PIERCING_HOWL, TARGET_VICTIM, 2); break; } break; case CLASS_PALADIN: VerifyAndPushSpellCast(spells, SPELL_AURA_MASTERY, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_LAY_ON_HANDS, TARGET_CHARMER, 8); VerifyAndPushSpellCast(spells, SPELL_BLESSING_OF_MIGHT, TARGET_CHARMER, 8); VerifyAndPushSpellCast(spells, SPELL_AVENGING_WRATH, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_DIVINE_PROTECTION, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_DIVINE_SHIELD, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_JUSTICE, TARGET_VICTIM, 6); VerifyAndPushSpellCast(spells, SPELL_HAND_OF_FREEDOM, TARGET_SELF, 3); VerifyAndPushSpellCast(spells, SPELL_HAND_OF_PROTECTION, TARGET_SELF, 1); if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) { if (creatureCharmer->IsDungeonBoss() || creatureCharmer->isWorldBoss()) VerifyAndPushSpellCast(spells, SPELL_HAND_OF_SACRIFICE, creatureCharmer, 10); else VerifyAndPushSpellCast(spells, SPELL_HAND_OF_PROTECTION, creatureCharmer, 3); } switch (GetSpec()) { case TALENT_SPEC_PALADIN_PROTECTION: VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_RIGHTEOUS, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_DIVINE_SACRIFICE, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_SHIELD_OF_RIGHTEOUS, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_JUDGEMENT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_CONSECRATION, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_HOLY_SHIELD, TARGET_NONE, 1); break; case TALENT_SPEC_PALADIN_HOLY: VerifyAndPushSpellCast(spells, SPELL_HOLY_SHOCK, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_HOLY_SHOCK, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_FLASH_OF_LIGHT, TARGET_CHARMER, 4); VerifyAndPushSpellCast(spells, SPELL_HOLY_LIGHT, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_DIVINE_FAVOR, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_DIVINE_ILLUMINATION, TARGET_NONE, 3); break; case TALENT_SPEC_PALADIN_RETRIBUTION: VerifyAndPushSpellCast(spells, SPELL_CRUSADER_STRIKE, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_DIVINE_STORM, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_JUDGEMENT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_HAMMER_OF_WRATH, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_RIGHTEOUS_FURY, TARGET_NONE, 2); break; } break; case CLASS_HUNTER: VerifyAndPushSpellCast(spells, SPELL_DETERRENCE, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_EXPLOSIVE_TRAP, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_FREEZING_ARROW, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_RAPID_FIRE, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_KILL_SHOT, TARGET_VICTIM, 10); if (me->GetVictim() && me->GetVictim()->getPowerType() == POWER_MANA && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_VIPER_STING, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_VIPER_STING, TARGET_VICTIM, 5); switch (GetSpec()) { case TALENT_SPEC_HUNTER_BEASTMASTER: VerifyAndPushSpellCast(spells, SPELL_AIMED_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_ARCANE_SHOT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_MULTI_SHOT, TARGET_VICTIM, 2); break; case TALENT_SPEC_HUNTER_MARKSMAN: VerifyAndPushSpellCast(spells, SPELL_AIMED_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_CHIMERA_SHOT, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_ARCANE_SHOT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_READINESS, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_SILENCING_SHOT, TARGET_VICTIM, 5); break; case TALENT_SPEC_HUNTER_SURVIVAL: VerifyAndPushSpellCast(spells, SPELL_EXPLOSIVE_SHOT, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_BLACK_ARROW, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_MULTI_SHOT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_STEADY_SHOT, TARGET_VICTIM, 1); break; } break; case CLASS_ROGUE: { VerifyAndPushSpellCast(spells, SPELL_DISMANTLE, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_EVASION, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_VANISH, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_BLIND, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_CLOAK_OF_SHADOWS, TARGET_NONE, 2); uint32 builder = 0, finisher = 0; switch (GetSpec()) { case TALENT_SPEC_ROGUE_ASSASSINATION: builder = SPELL_MUTILATE, finisher = SPELL_ENVENOM; VerifyAndPushSpellCast(spells, SPELL_COLD_BLOOD, TARGET_NONE, 20); break; case TALENT_SPEC_ROGUE_COMBAT: builder = SPELL_SINISTER_STRIKE, finisher = SPELL_EVISCERATE; VerifyAndPushSpellCast(spells, SPELL_ADRENALINE_RUSH, TARGET_NONE, 6); VerifyAndPushSpellCast(spells, SPELL_BLADE_FLURRY, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_KILLING_SPREE, TARGET_NONE, 25); break; case TALENT_SPEC_ROGUE_SUBTLETY: builder = SPELL_HEMORRHAGE, finisher = SPELL_EVISCERATE; VerifyAndPushSpellCast(spells, SPELL_PREPARATION, TARGET_NONE, 10); if (!me->IsWithinMeleeRange(me->GetVictim())) VerifyAndPushSpellCast(spells, SPELL_SHADOWSTEP, TARGET_VICTIM, 25); VerifyAndPushSpellCast(spells, SPELL_SHADOW_DANCE, TARGET_NONE, 10); break; } if (Unit* victim = me->GetVictim()) { if (victim->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_KICK, TARGET_VICTIM, 25); uint8 const cp = me->GetPower(POWER_COMBO_POINTS); if (cp >= 4) VerifyAndPushSpellCast(spells, finisher, TARGET_VICTIM, 10); if (cp <= 4) VerifyAndPushSpellCast(spells, builder, TARGET_VICTIM, 5); } break; } case CLASS_PRIEST: VerifyAndPushSpellCast(spells, SPELL_FEAR_WARD, TARGET_SELF, 2); VerifyAndPushSpellCast(spells, SPELL_POWER_WORD_FORT, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_DIVINE_SPIRIT, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_SHADOW_PROTECTION, TARGET_CHARMER, 2); VerifyAndPushSpellCast(spells, SPELL_DIVINE_HYMN, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_HYMN_OF_HOPE, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_SHADOW_WORD_DEATH, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_PSYCHIC_SCREAM, TARGET_VICTIM, 3); switch (GetSpec()) { case TALENT_SPEC_PRIEST_DISCIPLINE: VerifyAndPushSpellCast(spells, SPELL_POWER_WORD_SHIELD, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_INNER_FOCUS, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_PAIN_SUPPRESSION, TARGET_CHARMER, 15); VerifyAndPushSpellCast(spells, SPELL_POWER_INFUSION, TARGET_CHARMER, 10); VerifyAndPushSpellCast(spells, SPELL_PENANCE, TARGET_CHARMER, 3); VerifyAndPushSpellCast(spells, SPELL_FLASH_HEAL, TARGET_CHARMER, 1); break; case TALENT_SPEC_PRIEST_HOLY: VerifyAndPushSpellCast(spells, SPELL_DESPERATE_PRAYER, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_GUARDIAN_SPIRIT, TARGET_CHARMER, 5); VerifyAndPushSpellCast(spells, SPELL_FLASH_HEAL, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_RENEW, TARGET_CHARMER, 3); break; case TALENT_SPEC_PRIEST_SHADOW: if (!me->HasAura(SPELL_SHADOWFORM)) { VerifyAndPushSpellCast(spells, SPELL_SHADOWFORM, TARGET_NONE, 100); break; } if (Unit* victim = me->GetVictim()) { if (!victim->GetAuraApplicationOfRankedSpell(SPELL_VAMPIRIC_TOUCH, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_VAMPIRIC_TOUCH, TARGET_VICTIM, 4); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_SHADOW_WORD_PAIN, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_SHADOW_WORD_PAIN, TARGET_VICTIM, 3); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_DEVOURING_PLAGUE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_DEVOURING_PLAGUE, TARGET_VICTIM, 4); } VerifyAndPushSpellCast(spells, SPELL_MIND_BLAST, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_MIND_FLAY, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_DISPERSION, TARGET_NONE, 10); break; } break; case CLASS_DEATH_KNIGHT: { if (!me->IsWithinMeleeRange(me->GetVictim())) VerifyAndPushSpellCast(spells, SPELL_DEATH_GRIP, TARGET_VICTIM, 25); VerifyAndPushSpellCast(spells, SPELL_STRANGULATE, TARGET_VICTIM, 15); VerifyAndPushSpellCast(spells, SPELL_EMPOWER_RUNE_WEAP, TARGET_NONE, 5); VerifyAndPushSpellCast(spells, SPELL_ICEBORN_FORTITUDE, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_ANTI_MAGIC_SHELL, TARGET_NONE, 10); bool hasFF = false, hasBP = false; if (Unit* victim = me->GetVictim()) { if (victim->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_MIND_FREEZE, TARGET_VICTIM, 25); hasFF = !!victim->GetAuraApplicationOfRankedSpell(AURA_FROST_FEVER, me->GetGUID()), hasBP = !!victim->GetAuraApplicationOfRankedSpell(AURA_BLOOD_PLAGUE, me->GetGUID()); if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_PESTILENCE, TARGET_VICTIM, 3); if (!hasFF) VerifyAndPushSpellCast(spells, SPELL_ICY_TOUCH, TARGET_VICTIM, 4); if (!hasBP) VerifyAndPushSpellCast(spells, SPELL_PLAGUE_STRIKE, TARGET_VICTIM, 4); } switch (GetSpec()) { case TALENT_SPEC_DEATHKNIGHT_BLOOD: VerifyAndPushSpellCast(spells, SPELL_RUNE_TAP, TARGET_NONE, 2); VerifyAndPushSpellCast(spells, SPELL_HYSTERIA, TARGET_SELF, 5); if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) if (!creatureCharmer->IsDungeonBoss() && !creatureCharmer->isWorldBoss()) VerifyAndPushSpellCast(spells, SPELL_HYSTERIA, creatureCharmer, 15); VerifyAndPushSpellCast(spells, SPELL_HEART_STRIKE, TARGET_VICTIM, 2); if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_DEATH_STRIKE, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_DK, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_MARK_OF_BLOOD, TARGET_VICTIM, 20); VerifyAndPushSpellCast(spells, SPELL_VAMPIRIC_BLOOD, TARGET_NONE, 10); break; case TALENT_SPEC_DEATHKNIGHT_FROST: if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_OBLITERATE, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_HOWLING_BLAST, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_UNBREAKABLE_ARMOR, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_DEATHCHILL, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_FROST_STRIKE, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_BLOOD_STRIKE, TARGET_VICTIM, 1); break; case TALENT_SPEC_DEATHKNIGHT_UNHOLY: if (hasFF && hasBP) VerifyAndPushSpellCast(spells, SPELL_SCOURGE_STRIKE, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_DEATH_AND_DECAY, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_ANTI_MAGIC_ZONE, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_SUMMON_GARGOYLE, TARGET_VICTIM, 7); VerifyAndPushSpellCast(spells, SPELL_BLOOD_STRIKE, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_DK, TARGET_VICTIM, 3); break; } break; } case CLASS_SHAMAN: VerifyAndPushSpellCast(spells, SPELL_HEROISM, TARGET_NONE, 25); VerifyAndPushSpellCast(spells, SPELL_BLOODLUST, TARGET_NONE, 25); VerifyAndPushSpellCast(spells, SPELL_GROUNDING_TOTEM, TARGET_NONE, 2); switch (GetSpec()) { case TALENT_SPEC_SHAMAN_RESTORATION: if (Unit* charmer = me->GetCharmer()) if (!charmer->GetAuraApplicationOfRankedSpell(SPELL_EARTH_SHIELD, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_EARTH_SHIELD, charmer, 2); if (me->HasAura(SPELL_SHA_NATURE_SWIFT)) VerifyAndPushSpellCast(spells, SPELL_HEALING_WAVE, TARGET_CHARMER, 20); else VerifyAndPushSpellCast(spells, SPELL_LESSER_HEAL_WAVE, TARGET_CHARMER, 1); VerifyAndPushSpellCast(spells, SPELL_TIDAL_FORCE, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_SHA_NATURE_SWIFT, TARGET_NONE, 4); VerifyAndPushSpellCast(spells, SPELL_MANA_TIDE_TOTEM, TARGET_NONE, 3); break; case TALENT_SPEC_SHAMAN_ELEMENTAL: if (Unit* victim = me->GetVictim()) { if (victim->GetAuraOfRankedSpell(SPELL_FLAME_SHOCK, GetGUID())) VerifyAndPushSpellCast(spells, SPELL_LAVA_BURST, TARGET_VICTIM, 5); else VerifyAndPushSpellCast(spells, SPELL_FLAME_SHOCK, TARGET_VICTIM, 3); } VerifyAndPushSpellCast(spells, SPELL_CHAIN_LIGHTNING, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_LIGHTNING_BOLT, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_ELEMENTAL_MASTERY, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_THUNDERSTORM, TARGET_NONE, 3); break; case TALENT_SPEC_SHAMAN_ENHANCEMENT: if (Aura const* maelstrom = me->GetAura(AURA_MAELSTROM_WEAPON)) if (maelstrom->GetStackAmount() == 5) VerifyAndPushSpellCast(spells, SPELL_LIGHTNING_BOLT, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_STORMSTRIKE, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_EARTH_SHOCK, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_LAVA_LASH, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_SHAMANISTIC_RAGE, TARGET_NONE, 10); break; } break; case CLASS_MAGE: if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_COUNTERSPELL, TARGET_VICTIM, 25); VerifyAndPushSpellCast(spells, SPELL_DAMPEN_MAGIC, TARGET_CHARMER, 2); VerifyAndPushSpellCast(spells, SPELL_EVOCATION, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_MANA_SHIELD, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_MIRROR_IMAGE, TARGET_NONE, 3); VerifyAndPushSpellCast(spells, SPELL_SPELLSTEAL, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_ICE_BLOCK, TARGET_NONE, 1); VerifyAndPushSpellCast(spells, SPELL_ICY_VEINS, TARGET_NONE, 3); switch (GetSpec()) { case TALENT_SPEC_MAGE_ARCANE: if (Aura* abAura = me->GetAura(AURA_ARCANE_BLAST)) if (abAura->GetStackAmount() >= 3) VerifyAndPushSpellCast(spells, SPELL_ARCANE_MISSILES, TARGET_VICTIM, 7); VerifyAndPushSpellCast(spells, SPELL_ARCANE_BLAST, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_ARCANE_BARRAGE, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_ARCANE_POWER, TARGET_NONE, 8); VerifyAndPushSpellCast(spells, SPELL_PRESENCE_OF_MIND, TARGET_NONE, 7); break; case TALENT_SPEC_MAGE_FIRE: if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_LIVING_BOMB)) VerifyAndPushSpellCast(spells, SPELL_LIVING_BOMB, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_COMBUSTION, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_FIREBALL, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_FIRE_BLAST, TARGET_VICTIM, 1); VerifyAndPushSpellCast(spells, SPELL_DRAGONS_BREATH, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_BLAST_WAVE, TARGET_VICTIM, 1); break; case TALENT_SPEC_MAGE_FROST: VerifyAndPushSpellCast(spells, SPELL_DEEP_FREEZE, TARGET_VICTIM, 10); VerifyAndPushSpellCast(spells, SPELL_FROST_NOVA, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_FROSTBOLT, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_COLD_SNAP, TARGET_VICTIM, 5); if (me->GetVictim() && me->GetVictim()->HasAuraState(AURA_STATE_FROZEN, nullptr, me)) VerifyAndPushSpellCast(spells, SPELL_ICE_LANCE, TARGET_VICTIM, 5); break; } break; case CLASS_WARLOCK: VerifyAndPushSpellCast(spells, SPELL_DEATH_COIL_W, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_FEAR, TARGET_VICTIM, 2); VerifyAndPushSpellCast(spells, SPELL_SEED_OF_CORRUPTION, TARGET_VICTIM, 4); VerifyAndPushSpellCast(spells, SPELL_HOWL_OF_TERROR, TARGET_NONE, 2); if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_CORRUPTION, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_CORRUPTION, TARGET_VICTIM, 10); switch (GetSpec()) { case TALENT_SPEC_WARLOCK_AFFLICTION: if (Unit* victim = me->GetVictim()) { VerifyAndPushSpellCast(spells, SPELL_SHADOW_BOLT, TARGET_VICTIM, 7); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_UNSTABLE_AFFLICTION, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_UNSTABLE_AFFLICTION, TARGET_VICTIM, 8); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_HAUNT, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_HAUNT, TARGET_VICTIM, 8); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_CURSE_OF_AGONY, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_CURSE_OF_AGONY, TARGET_VICTIM, 4); if (victim->HealthBelowPct(25)) VerifyAndPushSpellCast(spells, SPELL_DRAIN_SOUL, TARGET_VICTIM, 100); } break; case TALENT_SPEC_WARLOCK_DEMONOLOGY: VerifyAndPushSpellCast(spells, SPELL_METAMORPHOSIS, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_SHADOW_BOLT, TARGET_VICTIM, 7); if (me->HasAura(AURA_DECIMATION)) VerifyAndPushSpellCast(spells, SPELL_SOUL_FIRE, TARGET_VICTIM, 100); if (me->HasAura(SPELL_METAMORPHOSIS)) { VerifyAndPushSpellCast(spells, SPELL_IMMOLATION_AURA, TARGET_NONE, 30); if (!me->IsWithinMeleeRange(me->GetVictim())) VerifyAndPushSpellCast(spells, SPELL_DEMON_CHARGE, TARGET_VICTIM, 20); } if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_IMMOLATE, TARGET_VICTIM, 5); if (me->HasAura(AURA_MOLTEN_CORE)) VerifyAndPushSpellCast(spells, SPELL_INCINERATE, TARGET_VICTIM, 10); break; case TALENT_SPEC_WARLOCK_DESTRUCTION: if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_IMMOLATE, TARGET_VICTIM, 8); if (me->GetVictim() && me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_IMMOLATE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_CONFLAGRATE, TARGET_VICTIM, 8); VerifyAndPushSpellCast(spells, SPELL_SHADOWFURY, TARGET_VICTIM, 5); VerifyAndPushSpellCast(spells, SPELL_CHAOS_BOLT, TARGET_VICTIM, 10); VerifyAndPushSpellCast(spells, SPELL_SHADOWBURN, TARGET_VICTIM, 3); VerifyAndPushSpellCast(spells, SPELL_INCINERATE, TARGET_VICTIM, 7); break; } break; case CLASS_MONK: switch (GetSpec()) { case TALENT_SPEC_MONK_BREWMASTER: case TALENT_SPEC_MONK_BATTLEDANCER: case TALENT_SPEC_MONK_MISTWEAVER: break; } break; case CLASS_DRUID: VerifyAndPushSpellCast(spells, SPELL_INNERVATE, TARGET_CHARMER, 5); VerifyAndPushSpellCast(spells, SPELL_BARKSKIN, TARGET_NONE, 5); switch (GetSpec()) { case TALENT_SPEC_DRUID_RESTORATION: if (!me->HasAura(SPELL_TREE_OF_LIFE)) { CancelAllShapeshifts(); VerifyAndPushSpellCast(spells, SPELL_TREE_OF_LIFE, TARGET_NONE, 100); break; } VerifyAndPushSpellCast(spells, SPELL_TRANQUILITY, TARGET_NONE, 10); VerifyAndPushSpellCast(spells, SPELL_NATURE_SWIFTNESS, TARGET_NONE, 7); if (Creature* creatureCharmer = ObjectAccessor::GetCreature(*me, me->GetCharmerGUID())) { VerifyAndPushSpellCast(spells, SPELL_NOURISH, creatureCharmer, 5); VerifyAndPushSpellCast(spells, SPELL_WILD_GROWTH, creatureCharmer, 5); if (!creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REJUVENATION, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_REJUVENATION, creatureCharmer, 8); if (!creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REGROWTH, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_REGROWTH, creatureCharmer, 8); uint8 lifebloomStacks = 0; if (Aura const* lifebloom = creatureCharmer->GetAura(SPELL_LIFEBLOOM, me->GetGUID())) lifebloomStacks = lifebloom->GetStackAmount(); if (lifebloomStacks < 3) VerifyAndPushSpellCast(spells, SPELL_LIFEBLOOM, creatureCharmer, 5); if (creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REJUVENATION) || creatureCharmer->GetAuraApplicationOfRankedSpell(SPELL_REGROWTH)) VerifyAndPushSpellCast(spells, SPELL_SWIFTMEND, creatureCharmer, 10); if (me->HasAura(SPELL_NATURE_SWIFTNESS)) VerifyAndPushSpellCast(spells, SPELL_HEALING_TOUCH, creatureCharmer, 100); } break; case TALENT_SPEC_DRUID_BALANCE: { if (!me->HasAura(SPELL_MOONKIN_FORM)) { CancelAllShapeshifts(); VerifyAndPushSpellCast(spells, SPELL_MOONKIN_FORM, TARGET_NONE, 100); break; } uint32 const mainAttackSpell = me->HasAura(AURA_ECLIPSE_LUNAR) ? SPELL_STARFIRE : SPELL_WRATH; VerifyAndPushSpellCast(spells, SPELL_STARFALL, TARGET_NONE, 20); VerifyAndPushSpellCast(spells, mainAttackSpell, TARGET_VICTIM, 10); if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_INSECT_SWARM, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_INSECT_SWARM, TARGET_VICTIM, 7); if (me->GetVictim() && !me->GetVictim()->GetAuraApplicationOfRankedSpell(SPELL_MOONFIRE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_MOONFIRE, TARGET_VICTIM, 5); if (me->GetVictim() && me->GetVictim()->HasUnitState(UNIT_STATE_CASTING)) VerifyAndPushSpellCast(spells, SPELL_TYPHOON, TARGET_NONE, 15); break; } case TALENT_SPEC_DRUID_CAT: case TALENT_SPEC_DRUID_BEAR: if (!me->HasAura(SPELL_CAT_FORM)) { CancelAllShapeshifts(); VerifyAndPushSpellCast(spells, SPELL_CAT_FORM, TARGET_NONE, 100); break; } VerifyAndPushSpellCast(spells, SPELL_BERSERK, TARGET_NONE, 20); VerifyAndPushSpellCast(spells, SPELL_SURVIVAL_INSTINCTS, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_TIGER_FURY, TARGET_NONE, 15); VerifyAndPushSpellCast(spells, SPELL_DASH, TARGET_NONE, 5); if (Unit* victim = me->GetVictim()) { uint8 const cp = me->GetPower(POWER_COMBO_POINTS); if (victim->HasUnitState(UNIT_STATE_CASTING) && cp >= 1) VerifyAndPushSpellCast(spells, SPELL_MAIM, TARGET_VICTIM, 25); if (!me->IsWithinMeleeRange(victim)) VerifyAndPushSpellCast(spells, SPELL_FERAL_CHARGE_CAT, TARGET_VICTIM, 25); if (cp >= 4) VerifyAndPushSpellCast(spells, SPELL_RIP, TARGET_VICTIM, 50); if (cp <= 4) { VerifyAndPushSpellCast(spells, SPELL_MANGLE_CAT, TARGET_VICTIM, 10); VerifyAndPushSpellCast(spells, SPELL_CLAW, TARGET_VICTIM, 5); if (!victim->GetAuraApplicationOfRankedSpell(SPELL_RAKE, me->GetGUID())) VerifyAndPushSpellCast(spells, SPELL_RAKE, TARGET_VICTIM, 8); if (!me->HasAura(SPELL_SAVAGE_ROAR)) VerifyAndPushSpellCast(spells, SPELL_SAVAGE_ROAR, TARGET_NONE, 15); } } break; } break; case CLASS_DEMON_HUNTER: switch (GetSpec()) { case TALENT_SPEC_DEMON_HUNTER_HAVOC: case TALENT_SPEC_DEMON_HUNTER_VENGEANCE: break; } break; } */ return SelectSpellCast(spells); } static const float CASTER_CHASE_DISTANCE = 28.0f; void SimpleCharmedPlayerAI::UpdateAI(const uint32 diff) { Creature* charmer = me->GetCharmer() ? me->GetCharmer()->ToCreature() : nullptr; if (!charmer) return; //kill self if charm aura has infinite duration if (charmer->IsInEvadeMode()) { Player::AuraEffectList const& auras = me->GetAuraEffectsByType(SPELL_AURA_MOD_CHARM); for (Player::AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter) if ((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent()) { me->KillSelf(); return; } } if (charmer->IsInCombat()) { Unit* target = me->GetVictim(); if (!target || !charmer->IsValidAttackTarget(target) || target->HasBreakableByDamageCrowdControlAura()) { target = SelectAttackTarget(); if (!target) return; if (IsRangedAttacker()) { _chaseCloser = !me->IsWithinLOSInMap(target); if (_chaseCloser) AttackStart(target); else AttackStartCaster(target, CASTER_CHASE_DISTANCE); } else AttackStart(target); _forceFacing = true; } if (me->IsStopped() && !me->HasUnitState(UNIT_STATE_CANNOT_TURN)) { float targetAngle = me->GetAngle(target); if (_forceFacing || fabs(me->GetOrientation() - targetAngle) > 0.4f) { me->SetFacingTo(targetAngle); _forceFacing = false; } } if (_castCheckTimer <= diff) { if (me->HasUnitState(UNIT_STATE_CASTING)) _castCheckTimer = 0; else { if (IsRangedAttacker()) { // chase to zero if the target isn't in line of sight bool inLOS = me->IsWithinLOSInMap(target); if (_chaseCloser != !inLOS) { _chaseCloser = !inLOS; if (_chaseCloser) AttackStart(target); else AttackStartCaster(target, CASTER_CHASE_DISTANCE); } } if (TargetedSpell shouldCast = SelectAppropriateCastForSpec()) DoCastAtTarget(shouldCast); _castCheckTimer = 500; } } else _castCheckTimer -= diff; DoAutoAttackIfReady(); } else { me->AttackStop(); me->CastStop(); me->StopMoving(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE); } } void SimpleCharmedPlayerAI::OnCharmed(bool apply) { if (apply) { me->CastStop(); me->AttackStop(); me->StopMoving(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MovePoint(0, me->GetPosition(), false); // force re-sync of current position for all clients } else { me->CastStop(); me->AttackStop(); // @todo only voluntary movement (don't cancel stuff like death grip or charge mid-animation) me->GetMotionMaster()->Clear(); me->StopMoving(); } }
Ragebones/StormCore
src/server/game/AI/PlayerAI/PlayerAI.cpp
C++
gpl-2.0
57,029
<?php /* * This file is part of SeAT * * Copyright (C) 2015 to 2022 Leon Jacobs * * 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. */ namespace Seat\Services\Traits; use Composer\InstalledVersions; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use OutOfBoundsException; use Seat\Services\AbstractSeatPlugin; use stdClass; /** * Trait VersionsManagementTrait. * * @package Seat\Services\Traits */ trait VersionsManagementTrait { /** * Compute a list of provider class which are implementing SeAT package structure. * * @return \stdClass */ protected function getPluginsMetadataList(): stdClass { app()->loadDeferredProviders(); $providers = array_keys(app()->getLoadedProviders()); $packages = (object) [ 'core' => collect(), 'plugins' => collect(), ]; foreach ($providers as $class) { // attempt to retrieve the class from booted app $provider = app()->getProvider($class); if (is_null($provider)) continue; // ensure the provider is a valid SeAT package if (! is_a($provider, AbstractSeatPlugin::class)) continue; // seed proper collection according to package vendor $provider->getPackagistVendorName() === 'eveseat' ? $packages->core->push($provider) : $packages->plugins->push($provider); } return $packages; } /** * @param string $vendor * @param string $package * @return string */ protected function getPackageLatestVersion(string $vendor, string $package): string { // construct the packagist uri to its API $packagist_url = sprintf('https://packagist.org/packages/%s/%s.json', $vendor, $package); try { $installed_version = InstalledVersions::getPrettyVersion(sprintf('%s/%s', $vendor, $package)) ?? '0.0.0'; } catch (OutOfBoundsException $e) { $installed_version = '0.0.0'; } // retrieve package meta-data try { $response = (new Client())->request('GET', $packagist_url); if ($response->getStatusCode() !== 200) return '0.0.0'; // convert the body into an array $json_array = json_decode($response->getBody(), true); // in case we miss either versions or package attribute, return an error as those attribute should contains version information if (! array_key_exists('package', $json_array) || ! array_key_exists('versions', $json_array['package'])) return '0.0.0'; // extract published versions from packagist response $versions = $json_array['package']['versions']; foreach ($versions as $available_version => $metadata) { // ignore any unstable versions if (strpos($available_version, 'dev') !== false || strpos($available_version, 'rc') !== false || strpos($available_version, 'alpha') !== false || strpos($available_version, 'beta') !== false) continue; // return outdated on the first package which is greater than installed version if (version_compare($installed_version, $metadata['version']) < 0) return $metadata['version']; } } catch (GuzzleException $e) { logger()->error($e->getMessage()); return 'offline'; } return $installed_version; } }
eveseat/services
src/Traits/VersionsManagementTrait.php
PHP
gpl-2.0
4,287
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ /* rtc not implemented yet */ extern int cma_rtc_not_implemented;
luckasfb/OT_903D-kernel-2.6.35.7
bootable/bootloader/uboot/board/cogent/rtc.h
C
gpl-2.0
2,287
<%include file="header.html" /> <form action="${app.base_url + 'wait'}" method="get"> <div class="action"> You can now run the rectification process. <input type="hidden" name="key" value="${app.key}"> <input type="submit" value="run" /> </div> </form> <h2>Input Images</h2> <div class="gallery" style="height: 1024px;"> <ul class="index"> <li> <a href="#"> first image <span> <img src="${app.work_url + 'input_0.png'}" /> </span> </a> </li> <li> <a href="#"> second image <span> <img src="${app.work_url + 'input_1.png'}" /> </span> </a> </li> </ul> </div> <%include file="footer.html" />
juan-cardelino/matlab_demos
ipol_demo-light-1025b85/app_available/m_quasi_euclidean_epipolar_rectification/template/params.html
HTML
gpl-2.0
666
# # Makefile for the linux kernel. # # Object file lists. obj-y := core.o lm.o time.o obj-$(CONFIG_ARCH_INTEGRATOR_AP) += integrator_ap.o obj-$(CONFIG_LEDS) += leds.o obj-$(CONFIG_PCI) += pci_v3.o pci.o obj-$(CONFIG_CPU_FREQ_INTEGRATOR) += cpu.o obj-$(CONFIG_INTEGRATOR_IMPD1) += impd1.o
sarnobat/knoppix
arch/arm/mach-integrator/Makefile
Makefile
gpl-2.0
300
<?php if (empty($_REQUEST['feeding'])): $feeding = 0; else: $feeding = $_REQUEST['feeding']; endif; if (empty($_REQUEST['transfer'])): $transfer = 0; else: $transfer = $_REQUEST['transfer']; endif; if (empty($_REQUEST['mobility'])): $mobility = 0; else: $mobility = $_REQUEST['mobility']; endif; if (empty($_REQUEST['dressing'])): $dressing = 0; else: $dressing = $_REQUEST['dressing']; endif; if (empty($_REQUEST['bathing'])): $bathing = 0; else: $bathing = $_REQUEST['bathing']; endif; if (empty($_REQUEST['groming'])): $groming = 0; else: $groming = $_REQUEST['groming']; endif; if (empty($_REQUEST['toilet_use'])): $toilet_use = 0; else: $toilet_use = $_REQUEST['toilet_use']; endif; if (empty($_REQUEST['bowels'])): $bowels = 0; else: $bowels = $_REQUEST['bowels']; endif; if (empty($_REQUEST['bladder'])): $bladder = 0; else: $bladder = $_REQUEST['bladder']; endif; if (empty($_REQUEST['stairs'])): $stairs = 0; else: $stairs = $_REQUEST['stairs']; endif; $score = $feeding + $transfer + $mobility + $dressing + $bathing + $groming + $toilet_use + $bowels + $bladder + $stairs; switch ($score) { case 0: $text = "ติดเตียง (เตียง 3)"; break; case ($score > 12): $text = "ติดสังคม (เตียง 1)"; break; case ($score > 5): $text = "ติดบ้าน (เตียง 2)"; break; case ($score < 5): $text = "ติดเตียง (เตียง 3)"; break; } echo "คะแนนที่ได้ " . $score . " คะแนน (เต็ม 20 คะแนน)<br>" . $text; ?>
kukks205/jhhc
page/old_screen/adl_result.php
PHP
gpl-2.0
1,838
package icaro.pruebas; import icaro.infraestructura.entidadesBasicas.NombresPredefinidos; import icaro.infraestructura.patronAgenteReactivo.control.acciones.AccionSincrona; import icaro.infraestructura.entidadesBasicas.descEntidadesOrganizacion.ComprobadorRutasEntidades; import icaro.infraestructura.entidadesBasicas.interfaces.InterfazGestion; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.ItfUsoRecursoTrazas; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.imp.componentes.InfoTraza; import icaro.infraestructura.recursosOrganizacion.recursoTrazas.imp.componentes.InfoTraza.NivelTraza; import icaro.infraestructura.recursosOrganizacion.repositorioInterfaces.ItfUsoRepositorioInterfaces; import java.util.Vector; /* * Implementacion por defecto de las acciones que se ejecutaron por parte del gestor de agentes. * @author */ public class VerificarExistenciaEntidadesDescripcion extends AccionSincrona { /** * Almacn de los nombres de los agentes que este gestor debe gestionar */ protected Vector<String> nombresAgentesGestionados = new Vector<String>(); /** * Depuracion para pruebas */ protected static boolean DEBUG = true; private InterfazGestion ItfGestionRecTrazas; private ItfUsoRecursoTrazas ItfUsoRecTrazas; // private ItfGestionAgenteReactivo ItfgestGestorInicial = null; // private ItfUsoConfiguracion configuracionExterna = null; // private String identGestorNodo = null; // private String msgUsuario = null; private String rutaDescripcionOrganizacion = null; private String nombreAgente; private ItfUsoRepositorioInterfaces itfUsoRepositorio; /** * Hebra para la monitorizacion */ // private HebraMonitorizacion hebra; // private Thread currentthread; /** * Tiempo de monitorizacion */ protected int tiempoParaNuevaMonitorizacion; protected final static String SUBTIPO_COGNITIVO = "Cognitivo"; protected final static String SUBTIPO_REACTIVO = "Reactivo"; private NombresPredefinidos.TipoEntidad tipoEntidad = NombresPredefinidos.TipoEntidad.Reactivo; /** * Constructor */ public VerificarExistenciaEntidadesDescripcion() { super(); this.nombreAgente = NombresPredefinidos.NOMBRE_INICIADOR; try { itfUsoRepositorio = NombresPredefinidos.REPOSITORIO_INTERFACES_OBJ; ItfUsoRecTrazas = NombresPredefinidos.RECURSO_TRAZAS_OBJ; ItfGestionRecTrazas = (InterfazGestion) this.itfUsoRepositorio .obtenerInterfaz(NombresPredefinidos.ITF_GESTION + NombresPredefinidos.RECURSO_TRAZAS); // ItfUsoRecTrazas.trazar(this.nombreAgente, "Fichero Descripcion organizacion : "+ // NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO, NivelTraza.debug); ItfUsoRecTrazas.visualizarIdentFicheroDescrOrganizacion(); ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza(this.nombreAgente, tipoEntidad, "Activacion agente reactivo " + nombreAgente + "\n" + "Fichero Descripcion organizacion : " + NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO, InfoTraza.NivelTraza.debug)); } catch (Exception e2) { e2.printStackTrace(); } /* * ItfUsoConfiguracion config = * (ItfUsoConfiguracion)RepositorioInterfaces.instance().obtenerInterfaz * (NombresPredefinidos.ITF_USO+NombresPredefinidos.CONFIGURACION); * tiempoParaNuevaMonitorizacion = config.getEntornoEjecucionGestor(nombreAgente). * getIntervaloMonitorizacion().intValue(); */ } @Override public void ejecutar(Object... params) { // Se verifican las rutas donde deben encontrarse las entidades de descripcion: // El esquema de descripcion de la organizacion, el fichero de descripcion y el paquete jaxb // nombreAgente= this.getNombreAgente(); ItfUsoRecTrazas.setIdentAgenteAReportar(this.nombreAgente); ComprobadorRutasEntidades comprobadorRutas = new ComprobadorRutasEntidades(); Boolean SeHapodidoLocalizarEsquema = true; Boolean SeHapodidoLocalizarFicheroDescripcion = true; this.trazas.trazar(nombreAgente, "Verificando la existencia de entidadesDescripcion", NivelTraza.debug); if (!comprobadorRutas.existeSchemaDescOrganizacion()) { ItfUsoRecTrazas .aceptaNuevaTraza(new InfoTraza( "Iniciador", "No se pudo encontrar fichero que define el esquema para interpretar la descripcion de la Organizacion", InfoTraza.NivelTraza.error)); SeHapodidoLocalizarEsquema = false; } rutaDescripcionOrganizacion = comprobadorRutas .buscarDescOrganizacion(NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO); if (rutaDescripcionOrganizacion == null) { ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", "No se pudo encontrar fichero de descripcion de la Organizacion", InfoTraza.NivelTraza.error)); SeHapodidoLocalizarFicheroDescripcion = false; } try { if (SeHapodidoLocalizarEsquema && SeHapodidoLocalizarFicheroDescripcion) { this.procesarInput("existenEntidadesDescripcion", null); } else { this.procesarInput("errorLocalizacionFicherosDescripcion", null); } } catch (Exception e2) { e2.printStackTrace(); ItfUsoRecTrazas .aceptaNuevaTraza(new InfoTraza( "Iniciador", tipoEntidad, "No se ha podido enviar un evento a si mismo notificando la validacion de las rutas de las entidades de descripcion . ", InfoTraza.NivelTraza.error)); } } public void getInfoObjectInput(Object obj) { } // public void crearRecursosNucleoOrganizacion () throws Exception { // // // Intento crear los recursos en orden pero si se producen errores se capturan, se visualizan // y // // se pude intentar dialogar con el usuario para que los corrija // // try { // // Se crea el recurso de configuración y posteriormente se debería dar orden al recurso // // de trazas para pintar el proceso. // // ItfUsoRepositorioInterfaces repositorioInterfaces = // RepositorioInterfaces.instance(RepositorioInterfaces.IMP_LOCAL); // trazas.trazar(this.nombreAgente,"Creacion de recursos nucleo Organizacion", NivelTraza.info); // configuracionExterna = ClaseGeneradoraConfiguracion.instance(); // // Se crea una configuracion con el fichero de descripcion de la organizacion // // rutaDescripcionOrganizacion // =NombresPredefinidos.RUTA_DESCRIPCIONES+NombresPredefinidos.DESCRIPCION_XML_POR_DEFECTO+".xml"; // configuracionExterna.interpretarDescripOrganizacion(rutaDescripcionOrganizacion); // if(!configuracionExterna.validarDescripOrganizacion()){ // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza(this.nombreAgente, // "Se produjo un error al interpretar el fichero de descripcion de la organizacion", // InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_InterpretacionDescripcionOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // }else { // // registro la configuracion // itfUsoRepositorio.registrarInterfaz( // NombresPredefinidos.ITF_USO + NombresPredefinidos.CONFIGURACION,configuracionExterna); // // Ahora que la configuracion es correcta , interpreto las propiedades globales // // y pongo la configuracion de trazas definida por el usuario // Boolean ConfiguracionTrazas = false; // if (NombresPredefinidos.ACTIVACION_PANEL_TRAZAS_DEBUG.startsWith("t")){ // ConfiguracionTrazas = true; // } // else // ItfGestionRecTrazas.termina(); // ItfUsoRecTrazas.visualizacionDeTrazas(ConfiguracionTrazas); // // // // Se crea el gestor de Organizacion // // DescInstanciaAgente descGestor = // configuracionExterna.getDescInstanciaGestor(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // // creo el agente gestor de organizacion // // // arranco la organizacion // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "recursosNucleoCreados", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // ItfgestGestorOrg.arranca(); // } catch (IllegalArgumentException ie) { // System.err.println("Error. La organizacion no se ha compilado correctamente. Compruebe que los ficheros xml de los automatas se encuentren en el classpath."); // ie.printStackTrace(); // System.exit(1); // // } // catch (ExcepcionEnComponente ie) { // msgUsuario = // "Se produjo un error al interpretar el fichero de descripcion de la organizacion \n"+ // "La ruta especificada es : " + rutaDescripcionOrganizacion; // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // msgUsuario,InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_InterpretacionDescripcionOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // catch (Exception e) { // msgUsuario = // "Se produjo un error al interpretar el fichero de descripcion de la organizacion \n"+ // "La ruta especificada es : " + rutaDescripcionOrganizacion; // System.err.println(msgUsuario); // e.printStackTrace(); // ItfUsoRecTrazas.aceptaNuevaTraza(new // InfoTraza("Iniciador",msgUsuario,InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_InterpretacionDescripcionOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // } // // public String localizarComportamientoGestorInicial ( String identGestor) throws // ExcepcionEnComponente, RemoteException { // // String locComportamientoGestor = null; // // Se obtiene el gestor inicial de la descripción de la organizacion. Puede ser un gestor de // organizacion o un gestor de nodo // // identGestor = configuracionExterna.getIdentGestorInicial(); // try { // // DescComportamientoAgente desCompGestor = // configuracionExterna.getDescComportamientoAgente(identGestor); // DescInstanciaGestor desCompGestor = configuracionExterna.getDescInstanciaGestor(identGestor); // locComportamientoGestor = // desCompGestor.getDescComportamiento().getLocalizacionComportamiento(); // if ( identGestor.startsWith(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)){ // if (locComportamientoGestor.isEmpty()) // locComportamientoGestor = NombresPredefinidos.PAQUETE_GESTOR_ORGANIZACION; // // } else // if ( identGestorNodo.startsWith(NombresPredefinidos.NOMBRE_GESTOR_NODO)){ // // identGestorACrear = NombresPredefinidos.NOMBRE_GESTOR_NODO; // if (locComportamientoGestor.isEmpty()) // locComportamientoGestor = NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_NODO; // } // else{ // // El gestor inicial debe ser un gestor de organización o un gestor de nodo y no se ha // definido ninguno // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor Inicial porque no hay un Gestor de Organizacion o un Gestor de Nodo definido." // + " Revisar el fichero de Descripcion de la Organizacion", // InfoTraza.NivelTraza.error)); // // } // // } catch (ExcepcionEnComponente ex) { // Logger.getLogger(VerificarExistenciaEntidadesDescripcion.class.getName()).log(Level.SEVERE, // null, ex); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor Inicial porque no se pudo obtener el comportamiento del Gestor de Organizacion o del Gestor de Nodo definido." // + " Revisar el fichero de Descripcion de la Organizacion", // InfoTraza.NivelTraza.error)); // } // return locComportamientoGestor; // } // public void crearGestorInicial () throws Exception { // // String locComportamientoGestor = null; // // Se obtiene el gestor inicial de la descripción de la organizacion. Puede ser un gestor de // organizacion o un gestor de nodo // // identGestorNodo = configuracionExterna.getIdentGestorInicial(); // if (configuracionExterna.despliegueOrgEnUnSoloNodo()) // identGestorNodo = NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION; // else { // Si la organizacion es distribuida el iniciador mira si esta en el nodo del GO o en // otro nodo // String identNodoGO = // configuracionExterna.getHostComponente(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // String thisHost = InetAddress.getLocalHost().getHostName(); // if ( thisHost.equalsIgnoreCase(identNodoGO)) // Esta en el nodo del GO se crea un Gestor de // Organizacion // identGestorNodo = NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION; // else identGestorNodo = NombresPredefinidos.NOMBRE_GESTOR_NODO; // Se crea un Gestor de Nodo // } // // // if ( identGestorNodo.startsWith(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)){ // //// identGestorACrear = NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION; // // // // // //// locComportamientoGestor = // NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_ORGANIZACION; // // locComportamientoGestor = // configuracionExterna.getDescComportamientoAgente(NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_ORGANIZACION).getLocalizacionComportamiento(); // // // // } else // // if ( identGestorNodo.startsWith(NombresPredefinidos.NOMBRE_GESTOR_NODO)){ // //// identGestorACrear = NombresPredefinidos.NOMBRE_GESTOR_NODO; // // locComportamientoGestor = NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_NODO; // // } // // else{ // // // El gestor inicial debe ser un gestor de organización o un gestor de nodo y no se ha // definido ninguno // // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // // // "No se pudo crear el comportamiento del Gestor Inicial porque no hay un Gestor de Organizacion o un Gestor de Nodo definido." // // + " Revisar el fichero de Descripcion de la Organizacion", // // InfoTraza.NivelTraza.error)); // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // // "error_al_crearGestorInicial", // // NombresPredefinidos.NOMBRE_INICIADOR, // // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // locComportamientoGestor = this.localizarComportamientoGestorInicial(identGestorNodo); // // if (!locComportamientoGestor.isEmpty() ) { // // Se crea el gestor y se registra en el registro RMI en el caso en que la organizacion sea // distribuida // try { // // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(identGestorNodo // ,locComportamientoGestor); // DescInstanciaGestor desCompGestor = // configuracionExterna.getDescInstanciaGestor(identGestorNodo); // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(desCompGestor); // ItfgestGestorInicial = (ItfGestionAgenteReactivo) itfUsoRepositorio.obtenerInterfaz( // NombresPredefinidos.ITF_GESTION + identGestorNodo); // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "GestorInicialCreado", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // catch (ExcepcionEnComponente ie) { // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor inicial", // InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_crearGestorInicial", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // catch (Exception e) { // System.err.println("Error. No se ha podido crear o registrar el Gestor Inicial."); // e.printStackTrace(); // } // } // } // // public void crearGestorOrganizacion () throws Exception { // try { // FactoriaAgenteReactivo.instancia().crearAgenteReactivo(NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION // ,NombresPredefinidos.COMPORTAMIENTO_PORDEFECTO_GESTOR_ORGANIZACION); // ItfgestGestorInicial = (ItfGestionAgenteReactivo) itfUsoRepositorio.obtenerInterfaz( // NombresPredefinidos.ITF_GESTION + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "GestorOrganizacionCreado", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // catch (ExcepcionEnComponente ie) { // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se pudo crear el comportamiento del Gestor de Organizacion", // InfoTraza.NivelTraza.error)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_crearGestorInicial", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // // } // catch (Exception e) { // System.err.println("Error. No se ha podido crear o registrar el Gestor de Organizacion."); // e.printStackTrace(); // } // } // // /** // * arranca los agentes que se especifiquen en la config. // */ // public void arrancarGestorInicialyTerminar()throws Exception { // logger.debug("GestorIniciador: Arrancando gestor Inicial."); // // try { // // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Arrancando el Gestor Inicial . ", InfoTraza.NivelTraza.debug)); // // if (ItfgestGestorInicial != null ){ // // arranca el Gestor de Organizacion y Termina el iniciador // this. ItfgestGestorInicial.arranca(); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "GestorInicial_arrancado_ok", // nombreAgente, // nombreAgente)); // // // terminarPorPropiaVoluntad(); // // } // else { // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "La interfaz del GO es nula . ", InfoTraza.NivelTraza.error)); // // genero un evento interno de error // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_arrancarGestorOrganizacion", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // } // } catch (Exception e2) { // e2.printStackTrace(); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_arrancarGestorInicial", // NombresPredefinidos.NOMBRE_INICIADOR, // NombresPredefinidos.NOMBRE_INICIADOR)); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "No se ha podido arrancar el Gestor de Organizacion . ", InfoTraza.NivelTraza.error)); // // } // // } // // /** // * Devuelve cierto si es necesario arrancar el agente // * // * @param nombreAgente // * @return // */ // /* // * private boolean esNecesarioArrancar(String nombreAgente) { Enumeration // * enume = configEspecifica.getListaAgentes().enumerateAgente(); while // * (enume.hasMoreElements()) { Agente item = (Agente)enume.nextElement(); if // * (nombreAgente.equals(item.getNombre())) return // * item.getHayQueArrancarlo(); } logger.error("GestorAgentes: No se encontr� // * ning�n agente con nombre "+nombreAgente+" dentro de la lista de objetos // * gestionados."); throw new NullPointerException(); } // */ // /** // * Decide que hacer en caso de fallos en los agentes. // */ // public void decidirTratamientoErrorIrrecuperable() { // // el tratamiento ser� siempre cerrar todo el chiringuito // logger.debug("GestorAgentes: Se decide cerrar el sistema ante un error critico irrecuperable."); // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // this.nombreAgente, // "Se decide cerrar el sistema ante un error critico irrecuperable.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // nombreAgente, // "Terminado proceso de arranque automatico de agentes.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "tratamiento_terminar_agentes_y_gestor_agentes", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // /** // * intenta arrancar los agentes que especifique la config y hayan dado // * problemas. // */ // public void recuperarErrorArranqueAgentes() { // // por defecto no se implementan pol�ticas de recuperaci�n // //logger.debug("GestorAgentes: Fue imposible recuperar el error en el arranque de los agentes."); // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // nombreAgente, // "Fue imposible recuperar el error en el arranque de los agentes.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "imposible_recuperar_arranque", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } // // /** // * Elabora un informe del estado en el que se encuentran los agentes y lo // * env�a al sistema de trazas. // */ // public void generarInformeErrorIrrecuperable() { // // Producimos traza de un error // logger.error("GestorIniciador: Se ha producido un error irrecuperable."); // try { // trazas.aceptaNuevaTraza(new InfoTraza( // "Iniciador", // " Iniciador a la espera de terminacion por parte del usuario debido a un error irrecuperable.", // InfoTraza.NivelTraza.error)); // this.informaraMiAutomata("informe_generado", null); // } catch (Exception e2) { // e2.printStackTrace(); // } // /* // try { // this.itfUsoGestorAReportar.aceptaEvento(new EventoRecAgte( // "error_en_arranque_gestores", // NombresPredefinidos.NOMBRE_GESTOR_RECURSOS, // NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION)); // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte("informe_generado", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // */ // } // // // /** // * Crea y arranca un agente. Es necesario pasar las caracter�sticas del // * agente a crear por par�metro. // */ // public void crearAgente() { // // esto hay que recuperarlo de los parametros // // logger.debug("GestorAgentes: crearAgente():Este metodo no esta implementado"); // try { // // trazas.aceptaNuevaTraza(new InfoTraza( // nombreAgente, // "crearAgente():Este metodo no esta implementado", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // throw new UnsupportedOperationException(); // } // // /** // * Monitoriza secuencialmente todos los agentes activos que est�n definidos // * como necesarios en la configuraci�n. // */ // public void monitorizarAgentes() { // // if(DEBUG) System.out.println("GestorAgentes:Comienza ciclo // // monitorizaci�n."); // // boolean errorEncontrado = false; // // recuperar todos los interfaces de gesti�n del repositorio que estamos // // gestionando // Enumeration enume = nombresAgentesGestionados.elements(); // while (enume.hasMoreElements() && !errorEncontrado) { // String nombre = (String) enume.nextElement(); // // if(DEBUG) System.out.println("GestorAgentes:Monitorizando agente // // "+nombre+"."); // // recupero el interfaz de gestion del repositorio // try { // InterfazGestion itfGes = (InterfazGestion) // this.itfUsoRepositorio.obtenerInterfaz(NombresPredefinidos.ITF_GESTION + nombre); // int monitoriz = itfGes.obtenerEstado(); // if (monitoriz == InterfazGestion.ESTADO_ERRONEO_IRRECUPERABLE || monitoriz == // InterfazGestion.ESTADO_ERRONEO_RECUPERABLE || monitoriz == InterfazGestion.ESTADO_TERMINADO // || monitoriz == InterfazGestion.ESTADO_TERMINANDO) { // errorEncontrado = true; // logger.debug("GestorAgentes:Agente " + nombre + " est� en estado err�neo o terminado."); // try { // ItfUsoRecursoTrazas trazas = (ItfUsoRecursoTrazas) // ClaseGeneradoraRepositorioInterfaces.instance().obtenerInterfaz( // NombresPredefinidos.ITF_USO + NombresPredefinidos.RECURSO_TRAZAS); // trazas.aceptaNuevaTraza(new InfoTraza( // this.nombreAgente, // "Agente " + nombre + " esta en estado erroneo o terminado.", // InfoTraza.NivelTraza.debug)); // } catch (Exception e2) { // e2.printStackTrace(); // } // } // /* // * else if(DEBUG) System.out.println("GestorAgentes:Agente // * "+nombre+" est� ok."); // */ // } catch (Exception ex) { // errorEncontrado = true; // logger.error("GestorAgentes: No se pudo acceder al repositorio."); // ex.printStackTrace(); // } // } // // if (errorEncontrado) { // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte( // "error_al_monitorizar", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } else { // try { // this.itfUsoPropiadeEsteAgente.aceptaEvento(new EventoRecAgte("agentes_ok", // nombreAgente, // nombreAgente)); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // // /** // * Intenta recuperar los errores detectados en la monitorizaci�n siguiendo // * la pol�tica definida para cada agente. // */ // // // /** // * destruye los recursos que se crearon a lo largo del ciclo de vida de este // * agente. // */ // public void terminarPorPropiaVoluntad() throws Exception, Throwable { // // termina el gestor. // // puede esperarse a que terminen los agentes // //logger.debug("GestorAgentes: Terminando gestor de agentes."); // logger.debug("Iniciador: Terminando gestor de la organizacion y los recursos de la infraestructura."); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Terminando el Iniciador.", // InfoTraza.NivelTraza.debug)); // try { // // se obtiene la propia interfaz de gestion para terminar // // // ItfgestGestorInicial.termina(); // // // ((ItfGestionAgenteReactivo) this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + this.nombreAgente)) // .termina(); // // quitamos las interfaces del repositorio de interfaces // itfUsoRepositorio.eliminarRegistroInterfaz(NombresPredefinidos.ITF_USO+this.nombreAgente); // itfUsoRepositorio.eliminarRegistroInterfaz(NombresPredefinidos.ITF_GESTION+this.nombreAgente); // // definimos el gestor al que debe enviar los eventos el RC // ItfUsoRecTrazas.setIdentAgenteAReportar(this.identGestorNodo); // // // // this.itfUsoPropiadeEsteAgente.aceptaEvento(new // // EventoRecAgte ("termina",this.nombreAgente,this.nombreAgente)); // // } catch (Exception ex) { // ex.printStackTrace(); // } // logger.debug("Iniciador: Terminando."); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Terminando.", // InfoTraza.NivelTraza.debug)); // if (this.hebra != null) // this.hebra.finalizar(); // // this.currentthread.join(); // } // public void procesarPeticionTerminacion() { // logger.debug("Iniciador: Procesando la peticion de terminacion"); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Procesando la peticion de terminacion", // InfoTraza.NivelTraza.debug)); // // ItfUsoRecTrazas.pedirConfirmacionTerminacionAlUsuario(); // // /*try { // // this.itfUsoAgente.aceptaEvento(new // // EventoRecAgte("termina",null,null)); // // // ItfGestionAgenteReactivo gestion = (ItfGestionAgenteReactivo) this.itfUsoRepositorio // .obtenerInterfaz(NombresPredefinidos.ITF_GESTION // + NombresPredefinidos.NOMBRE_GESTOR_ORGANIZACION); // gestion.termina(); // } catch (Exception e) { // e.printStackTrace(); // } // */ // } // // public void comenzarTerminacionConfirmada() { // logger.debug("Iniciador: Terminando recursos..."); // ItfUsoRecTrazas.aceptaNuevaTraza(new InfoTraza("Iniciador", // "Comenzando la terminacion de los recursos...", // InfoTraza.NivelTraza.info)); // // // try { // // ItfGestionRecTrazas.termina(); // // y a continuacion se termina el gestor // // terminarPorPropiaVoluntad();if (this.hebra != null) // if (this.hebra != null) // this.hebra.finalizar(); // System.exit(0); // } catch (Exception ex) { // Logger.getLogger(VerificarExistenciaEntidadesDescripcion.class.getName()).log(Level.SEVERE, // null, ex); // } catch (Throwable ex) { // Logger.getLogger(VerificarExistenciaEntidadesDescripcion.class.getName()).log(Level.SEVERE, // null, ex); // } // // // } // // public void clasificaError() { // } }
palomagc/MovieChatter
src/icaro/pruebas/VerificarExistenciaEntidadesDescripcion.java
Java
gpl-2.0
27,852
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest00550") public class BenchmarkTest00550 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = ""; boolean flag = true; java.util.Enumeration<String> names = request.getParameterNames(); while (names.hasMoreElements() && flag) { String name = (String) names.nextElement(); String[] values = request.getParameterValues(name); if (values != null) { for(int i=0;i<values.length && flag; i++){ String value = values[i]; if (value.equals("vector")) { param = name; flag = false; } } } } // Chain a bunch of propagators in sequence String a26930 = param; //assign StringBuilder b26930 = new StringBuilder(a26930); // stick in stringbuilder b26930.append(" SafeStuff"); // append some safe content b26930.replace(b26930.length()-"Chars".length(),b26930.length(),"Chars"); //replace some of the end content java.util.HashMap<String,Object> map26930 = new java.util.HashMap<String,Object>(); map26930.put("key26930", b26930.toString()); // put in a collection String c26930 = (String)map26930.get("key26930"); // get it back out String d26930 = c26930.substring(0,c26930.length()-1); // extract most of it String e26930 = new String( new sun.misc.BASE64Decoder().decodeBuffer( new sun.misc.BASE64Encoder().encode( d26930.getBytes() ) )); // B64 encode and decode it String f26930 = e26930.split(" ")[0]; // split it on a space org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String g26930 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe' String bar = thing.doSomething(g26930); // reflection double value = java.lang.Math.random(); String rememberMeKey = Double.toString(value).substring(2); // Trim off the 0. at the front. String user = "Doug"; String fullClassName = this.getClass().getName(); String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length()); user+= testCaseNumber; String cookieName = "rememberMe" + testCaseNumber; boolean foundUser = false; javax.servlet.http.Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) { javax.servlet.http.Cookie cookie = cookies[i]; if (cookieName.equals(cookie.getName())) { if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) { foundUser = true; } } } if (foundUser) { response.getWriter().println("Welcome back: " + user + "<br/>"); } else { javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey); rememberMe.setSecure(true); request.getSession().setAttribute(cookieName, rememberMeKey); response.addCookie(rememberMe); response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName() + " whose value is: " + rememberMe.getValue() + "<br/>"); } response.getWriter().println("Weak Randomness Test java.lang.Math.random() executed"); } }
andresriancho/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00550.java
Java
gpl-2.0
4,565
<?php require 'head.php';?> <div class="container-fluid main-container"> <div class="col-md-2 sidebar"> <div class="row"> <!-- uncomment code for absolute positioning tweek see top comment in css --> <div class="absolute-wrapper"> </div> <!-- Menu --> <div class="side-menu"> <nav class="navbar navbar-default" role="navigation"> <!-- Main Menu --> <div class="side-menu-container"> <ul class="nav navbar-nav"> <li class="active"><a href="#" target="_self"><span class="glyphicon glyphicon-dashboard"></span> Dashboard</a></li> <li><a href="grafik.php"><span class="glyphicon glyphicon-signal"></span> Link</a></li> </ul> </div><!-- /.navbar-collapse --> </nav> </div> </div> </div> <div class="col-md-10 content"> <div class="panel panel-default"> <div class="panel-heading"> Dashboard </div> <div class="panel-body"> <?php require 'addcalon.php'; ?> </div> </div> </div> <?php require'foot.php';?>
zona284/evotemipa
admin/admin.php
PHP
gpl-2.0
998
/* This file is part of Work in Texas (WIT) Search Helper. WIT Search Helper 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. WIT Search Helper 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 WIT Search Helper. If not, see <http://www.gnu.org/licenses/>. */ /* functions for getting and setting correct value from local storage local storage key: WITStorage array structure: see function getNewLocStorArray below */ function getLocalStorage(loc) { arr = testLocalStorageIntegrity(); if(loc == 'maxDist') return arr[0].maxDist; else if(loc == 'myZip') return arr[0].myZip; else if(loc == 'resultHandling') return arr[0].resultHandling; else if(loc == 'myDistances') return arr[0].myDistances; else window.console.log('Nothing returned for ' + loc); } //arrAdd array structure: [value to add, key to add to] function setLocalStorage(arrAdd) { arr = testLocalStorageIntegrity(); for (i = 0; i < arrAdd.length; i++) { var val = arrAdd[i][0]; var loc = arrAdd[i][1]; if(loc == 'maxDist') arr[0].maxDist = val; else if(loc == 'myZip') arr[0].myZip = val; else if(loc == 'resultHandling') arr[0].resultHandling = val; else if(loc == 'myDistances') arr[0].myDistances = val; } localStorage['WITStorage'] = JSON.stringify(arr); return; } function testLocalStorageIntegrity() { var arr = localStorage['WITStorage']; if(arr == 'undefined' || arr == null) { //empty or error, redo storage // lOut('Redoing Array'); return getNewLocStorArray(); } arr = JSON.parse(arr); if(arr.length != 4) { //empty or error, redo storage // lOut('Redoing Array'); return getNewLocStorArray(); } //no problems, return good local storage values return arr; } //SET DEFAULT VALUES HERE, ALL VALUES ARE PRELOADED FROM THIS ARRAY function getNewLocStorArray() { var myArray = [ {"maxDist":"20"}, {"myZip":"76010"}, {"resultHandling":""}, {"myDistances":""} ] return myArray; } //shortened script for printing to console log function lOut(str) { window.console.log(str); } //functions for testing time to execute scripts function myTime(a) { i = performance.now(); lOut(a[0] + ". " + (i-a[1])); a[0]++; a[1] = i; return a; }
Soscan2062/wit-search-helper
utils.js
JavaScript
gpl-2.0
2,653
# $Id: BLASTPGP.pm 14 2007-07-26 19:51:53Z malay $ # Perl module for SeqToolBox::BLAST::BLASTPGP # Author: Malay <malay@bioinformatics.org> # Copyright (c) 2007 by Malay. All rights reserved. # You may distribute this module under the same terms as perl itself ##-------------------------------------------------------------------------## ## POD documentation - main docs before the code ##-------------------------------------------------------------------------## =head1 NAME SeqToolBox::BLAST::BLASTPGP - DESCRIPTION of Object =head1 SYNOPSIS Give standard usage here =head1 DESCRIPTION Describe the object here =cut ##-------------------------------------------------------------------------## ## Let the code begin... ##-------------------------------------------------------------------------## package SeqToolBox::BLAST::BLASTPGP; use SeqToolBox::Root; use SeqToolBox::BLASTParser; use vars qw(@ISA); @ISA = qw(SeqToolBox::Root SeqToolBox::BLASTParser); use strict; ##-------------------------------------------------------------------------## ## Constructors ##-------------------------------------------------------------------------## =head1 CONSTRUCTOR =head2 new() =cut sub new { my $class = shift; my $self = {}; bless $self, ref($class) || $class; $self->_init(@_); return $self; } # _init is where the heavy stuff will happen when new is called sub _init { my($self,@args) = @_; } ##-------------------------------------------------------------------------## ## METHODS ##-------------------------------------------------------------------------## =head1 PUBLIC METHODS =cut =head2 get_gi_list() Describe your function here Usage : Args : Returns : =cut sub get_gi_list { my ($self,@args) = @_; if (exists $self->{gi_list}) { my @temp = @{$self->{gi_list}}; return @temp; }else{ return; } } =head1 PRIVATE METHODS =cut =head2 set_fh() Describe your function here Usage : Args : Returns : =cut sub set_fh { my ($self,@args) = @_; $self->{fh} = $args[0]; } =head2 parse_file() Describe your function here Usage : Args : Returns : =cut sub _parse_file { my $self = shift; my $fh = $self->{fh}; while (my $line = <$fh>) { last if ($line =~ /Sequences producing significant alignments\:/); } while (my $line = <$fh>){ last if $line =~ /Sequences with E-value WORSE than threshold/; if ($line =~ /gi\|(\d+)\|/) { $self->_add_to_gi_list($1); }else { } } } =head2 _add_to_gi_list() Describe your function here Usage : Args : Returns : =cut sub _add_to_gi_list { my ($self,$gi) = @_; if (exists $self->{gi_list}) { my @temp = @{$self->{gi_list}}; push @temp , $gi; $self->{gi_list} = \@temp; }else{ my @temp; push @temp , $gi; $self->{gi_list} = \@temp; } } =head1 SEE ALSO =head1 CONTACT Malay <malay@bioinformatics.org> =head1 COPYRIGHTS Copyright (c) 2007 by Malay <malay@bioinformatics.org>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut =head1 APPENDIX =cut 1;
malaybasu/ProPhylo
lib/SeqToolBox/BLAST/BLASTPGP.pm
Perl
gpl-2.0
3,162
/* Copyright (C) 2005-2015 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #ifndef _TLS_H # define _TLS_H 1 # include <dl-sysdep.h> #ifndef __ASSEMBLER__ # include <stdbool.h> # include <stddef.h> # include <stdint.h> /* Type for the dtv. */ typedef union dtv { size_t counter; struct { void *val; bool is_static; } pointer; } dtv_t; #else /* __ASSEMBLER__ */ # include <tcb-offsets.h> #endif /* __ASSEMBLER__ */ #ifndef __ASSEMBLER__ /* Get system call information. */ # include <sysdep.h> /* The TP points to the start of the thread blocks. */ # define TLS_DTV_AT_TP 1 # define TLS_TCB_AT_TP 0 /* Get the thread descriptor definition. */ # include <nptl/descr.h> typedef struct { dtv_t *dtv; void *private; } tcbhead_t; #define READ_THREAD_POINTER() \ ({ register void *__microblaze_thread_area asm ("r21"); \ __microblaze_thread_area; }) /* This is the size of the initial TCB. */ # define TLS_INIT_TCB_SIZE sizeof (tcbhead_t) /* Alignment requirements for the initial TCB. */ # define TLS_INIT_TCB_ALIGN __alignof__ (tcbhead_t) /* This is the size of the TCB. */ # define TLS_TCB_SIZE sizeof (tcbhead_t) /* This is the size we need before TCB. */ # define TLS_PRE_TCB_SIZE sizeof (struct pthread) /* Alignment requirements for the TCB. */ # define TLS_TCB_ALIGN __alignof__ (struct pthread) /* Install the dtv pointer. The pointer passed is to the element with index -1 which contain the length. */ # define INSTALL_DTV(tcbp, dtvp) \ (((tcbhead_t *) (tcbp))->dtv = (dtvp) + 1) /* Install new dtv for current thread. */ # define INSTALL_NEW_DTV(dtv) \ (THREAD_DTV() = (dtv)) /* Return dtv of given thread descriptor. */ # define GET_DTV(tcbp) \ (((tcbhead_t *) (tcbp))->dtv) /* Code to initially initialize the thread pointer. r21 is reserved for thread pointer. */ # define TLS_INIT_TP(tcbp) \ ({ __asm __volatile ("or r21,r0,%0" : : "r" ((void *)tcbp)); NULL; }) # define TLS_DEFINE_INIT_TP(tp, pd) void *tp = (pd) + 1 /* Return the address of the dtv for the current thread. */ # define THREAD_DTV() \ (((tcbhead_t *) READ_THREAD_POINTER())->dtv) /* Return the thread descriptor for the current thread. */ # define THREAD_SELF \ (((struct pthread *) READ_THREAD_POINTER()) - 1) /* Magic for libthread_db to know how to do THREAD_SELF. */ # define DB_THREAD_SELF \ CONST_THREAD_AREA (32, sizeof (struct pthread)) /* Magic for Infinity to know how to do THREAD_SELF. */ # define I8_THREAD_SELF I8_TS_CONST_THREAD_AREA # define I8_TS_CTA_VALUE sizeof (struct pthread) /* Read member of the thread descriptor directly. */ # define THREAD_GETMEM(descr, member) (descr->member) /* Same as THREAD_GETMEM, but the member offset can be non-constant. */ # define THREAD_GETMEM_NC(descr, member, idx) \ (descr->member[idx]) /* Set member of the thread descriptor directly. */ # define THREAD_SETMEM(descr, member, value) \ (descr->member = (value)) /* Same as THREAD_SETMEM, but the member offset can be non-constant. */ # define THREAD_SETMEM_NC(descr, member, idx, value) \ (descr->member[idx] = (value)) /* Get and set the global scope generation counter in struct pthread. */ # define THREAD_GSCOPE_FLAG_UNUSED 0 # define THREAD_GSCOPE_FLAG_USED 1 # define THREAD_GSCOPE_FLAG_WAIT 2 # define THREAD_GSCOPE_RESET_FLAG() \ do \ { int __res \ = atomic_exchange_rel (&THREAD_SELF->header.gscope_flag, \ THREAD_GSCOPE_FLAG_UNUSED); \ if (__res == THREAD_GSCOPE_FLAG_WAIT) \ lll_futex_wake (&THREAD_SELF->header.gscope_flag, 1, LLL_PRIVATE); \ } \ while (0) # define THREAD_GSCOPE_SET_FLAG() \ do \ { \ THREAD_SELF->header.gscope_flag = THREAD_GSCOPE_FLAG_USED; \ atomic_write_barrier (); \ } \ while (0) # define THREAD_GSCOPE_WAIT() \ GL (dl_wait_lookup_done) () #endif /* __ASSEMBLER__ */ #endif /* tls.h. */
gbenson/glibc
sysdeps/microblaze/nptl/tls.h
C
gpl-2.0
5,250
<?php /* * index.home.php * Created on 21.03.2007 by Tobias Bieniek */ // Startseiten-Template laden und mit Variablen füllen $temp = new Template("templates/".$competition['lang']."/home.tpl"); // Heimatflugplatz einfügen $base = (explode("|", $competition['config']['homebase'])); $base = $base[0]; $temp->addVariable("homebase", $base); // Heimatbonus einfügen $temp->addVariable("awayfactor", $competition['config']['homefactor']); $hf = "1.0"; while (strlen($hf) < strlen($competition['config']['homefactor'])) { $hf = $hf . "0"; } $temp->addVariable("homefactor", $hf); // Meilenstein-Faktoren einfügen $factors = explode("|", $competition['config']['factors']); for ($i = 0; $i < count($factors); $i++) { $temp->addVariable("factor_".($i+1), $factors[$i]); } // OLC Jahr berechnen $year = date("Y"); if (time() >= mktime(0,0,0,11,1,$year)) $year++; // kleine Rankingtabellen der letzten <3> Jahre einfuegen include_once("index.smallranking.php"); $sr_perpage = 3; if (isset($competition['config']['sr_per_page']) && $competition['config']['sr_per_page'] > 0) $sr_perpage = $competition['config']['sr_per_page']; $small_rankings = ""; $i = 0; for ($j = 0; $j < 100 && $i < $sr_perpage; $j++) { $xtemp = getSmallRanking($competition, $db, $year - $j); if ($xtemp != "") { $small_rankings .= $xtemp; $i++; } } $temp->addVariable("small_rankings", $small_rankings); // News-System hinzufügen $page = 1; if (array_key_exists("page", $_GET)) $page = $_GET['page']; $i = 0; $s_news = ""; $next = 0; $prev = 0; $perpage = 5; if (isset($competition['config']['news_per_page']) && $competition['config']['news_per_page'] > 0) $perpage = $competition['config']['news_per_page']; $res_news = db_query("SELECT * FROM %pre%news ORDER BY time DESC, id DESC", $db, $competition['id']); while($news = db_fetch_array($res_news)) { if ($i >= ($page - 1) * $perpage && $i < $page * $perpage) { $news_temp = new Template("templates/".$competition['lang']."/home.news.row.tpl"); $news_temp->addVariable("id", $news['id']); $news_temp->addVariable("author", $news['author']); $news_temp->addVariable("header", $news['header']); $news_temp->addVariable("text", str_replace("\r\n", "<br />\r\n", $news['text'])); $news_temp->addVariable("ldate", date("d.m.Y", $news['time'])); $news_temp->addVariable("sdate", date("d.m.", $news['time'])); $news_temp->addVariable("ltime", date("H:i:s", $news['time'])); $news_temp->addVariable("stime", date("H:i", $news['time'])); $s_news .= $news_temp->getOutput(); } if ($i >= $page * $perpage) { $next = 1; } if ($i < ($page - 1) * $perpage) { $prev = 1; } $i++; } if ($i == 0) { $news_temp = new Template("templates/".$competition['lang']."/home.news.row.empty.tpl"); $news_temp->fillStandard($competition); $s_news .= $news_temp->getOutput(); } // Links einfügen (Vor/Zurück) if ($next == 1) { $next = new Template("templates/".$competition['lang']."/home.news.next.tpl"); $next->fillStandard($competition); $next->addVariable("page", ($page+1)); $next = $next->getOutput(); } else $next = "&nbsp;"; if ($prev == 1) { $prev = new Template("templates/".$competition['lang']."/home.news.prev.tpl"); $prev->fillStandard($competition); $prev->addVariable("page", ($page-1)); $prev = $prev->getOutput(); } else $prev = "&nbsp;"; $temp->addVariable("news", $s_news); $temp->addVariable("news_page", $page); $temp->addVariable("news_next", $next); $temp->addVariable("news_prev", $prev); ?>
Turbo87/destination
index.home.php
PHP
gpl-2.0
3,541
/* Cabal - Legacy Game Implementations * * Cabal is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ // Based on the ScummVM (GPLv2+) file of the same name #ifndef ACCESS_VIDEO_MOVIE_DECODER_H #define ACCESS_VIDEO_MOVIE_DECODER_H #include "common/rect.h" #include "video/video_decoder.h" namespace Audio { class QueuingAudioStream; } namespace Common { class SeekableReadStream; } namespace Image { class Codec; } namespace Access { enum kDebugLevels { kVIDMovieChunkId_FullFrame = 0x00, kVIDMovieChunkId_FullFrameCompressed = 0x01, kVIDMovieChunkId_Palette = 0x02, kVIDMovieChunkId_FullFrameCompressedFill = 0x03, kVIDMovieChunkId_PartialFrameCompressed = 0x04, kVIDMovieChunkId_EndOfFile = 0x14, kVIDMovieChunkId_AudioFirstChunk = 0x7C, kVIDMovieChunkId_Audio = 0x7D }; // This video format is used in at least the following Access engine games: // - Noctropolis // - Synnergist class AccessVIDMovieDecoder : public Video::VideoDecoder { public: AccessVIDMovieDecoder(); ~AccessVIDMovieDecoder(); bool loadStream(Common::SeekableReadStream *stream); void close(); protected: void readNextPacket(); private: bool streamSkipFullFrameCompressedFill(); private: int32 _streamSeekOffset; /* current stream offset, pointing to not-yet-indexed stream position */ uint32 _streamVideoIndex; /* current stream index for video decoding */ uint32 _streamAudioIndex; /* current stream index for audio decoding */ struct IndexCacheEntry { byte chunkId; int32 offset; }; Common::Array<IndexCacheEntry> _indexCacheTable; private: class StreamVideoTrack : public VideoTrack { public: StreamVideoTrack(uint32 width, uint32 height, uint16 regularFrameDelay); ~StreamVideoTrack(); bool endOfTrack() const; uint16 getWidth() const { return _width; } uint16 getHeight() const { return _height; } Graphics::PixelFormat getPixelFormat() const; int getCurFrame() const { return _curFrame; } void setNextFrameStartTime(uint32 nextFrameStartTime) { _nextFrameStartTime = nextFrameStartTime; } uint32 getNextFrameStartTime() const { return _nextFrameStartTime; } const Graphics::Surface *decodeNextFrame() { return _surface; } const byte *getPalette() const; bool hasDirtyPalette() const; void decodePalette(Common::SeekableReadStream *stream); void decodeFrame(Common::SeekableReadStream *stream, byte chunkId); bool skipOverFrame(Common::SeekableReadStream *stream, byte chunkId); bool skipOverPalette(Common::SeekableReadStream *stream); void setEndOfTrack() { _endOfTrack = true; } private: Graphics::Surface *_surface; int _curFrame; uint32 _nextFrameStartTime; byte _palette[3 * 256]; mutable bool _dirtyPalette; uint16 _width, _height; uint16 _regularFrameDelay; // delay between frames (1 = 1/60 of a second) bool _endOfTrack; }; class StreamAudioTrack : public AudioTrack { public: StreamAudioTrack(uint32 sampleRate); ~StreamAudioTrack(); void queueAudio(Common::SeekableReadStream *stream, byte chunkId); bool skipOverAudio(Common::SeekableReadStream *stream, byte chunkId); protected: Audio::AudioStream *getAudioStream() const; private: Audio::QueuingAudioStream *_audioStream; uint32 _totalAudioQueued; /* total amount of milliseconds of audio, that we queued up already */ public: uint32 getTotalAudioQueued() const { return _totalAudioQueued; } private: int16 decodeSample(uint8 dataNibble); uint16 _sampleRate; bool _stereo; }; Common::SeekableReadStream *_stream; StreamVideoTrack *_videoTrack; StreamAudioTrack *_audioTrack; }; } // End of namespace Access #endif
clone2727/cabal
engines/access/video/movie_decoder.h
C
gpl-2.0
4,457
# -*- coding: utf-8 -*- import sys sys.path.append(sys.argv[1]) from scriptlib import * """Файлы пакета""" FILES = ( '7z920-x64.msi', '7z920.msi' ) """Имена исполняемых файлов""" if ARCH == '64': INSTALLER = os.path.join('', DIR, FILES[0]) else: INSTALLER = os.path.join('', DIR, FILES[1]) def install(): run_msi('/i', INSTALLER) def remove(): run_msi('/x', INSTALLER) check_files(FILES) if ACTION == 'install': install() elif ACTION == 'remove': remove()
kuchiman/wpm-pkg
7zip/script.py
Python
gpl-2.0
529
/* ============================================================ * * This file is a part of kipi-plugins project * http://www.kipi-plugins.org * * Date : 2003-10-14 * Description : batch image rotation * * Copyright (C) 2003-2005 by Renchi Raju <renchi@pooh.tam.uiuc.edu> * Copyright (C) 2004-2009 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de> * Copyright (C) 2006-2009 by Gilles Caulier <caulier dot gilles at gmail dot com> * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation; * either version 2, 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. * * ============================================================ */ #define XMD_H // C++ includes. #include <cstdio> // C ANSI includes. extern "C" { #include <sys/types.h> #include <unistd.h> #include <jpeglib.h> } // Qt includes. #include <QFile> #include <QFileInfo> // KDE includes. #include <kprocess.h> #include <kdebug.h> #include <klocale.h> // Local includes. #include "utils.h" #include "transupp.h" #include "jpegtransform.h" #include "imagerotate.h" #include "imagerotate.moc" namespace KIPIJPEGLossLessPlugin { ImageRotate::ImageRotate() : QObject() { m_tmpFile.setSuffix("kipiplugin-rotate"); m_tmpFile.setAutoRemove(true); } ImageRotate::~ImageRotate() { } bool ImageRotate::rotate(const QString& src, RotateAction angle, QString& err, bool updateFileTimeStamp) { QFileInfo fi(src); if (!fi.exists() || !fi.isReadable() || !fi.isWritable()) { err = i18n("Error in opening input file"); return false; } if ( !m_tmpFile.open() ) { err = i18n("Error in opening temporary file"); return false; } QString tmp = m_tmpFile.fileName(); if (Utils::isRAW(src)) { err = i18n("Cannot rotate RAW file"); return false; } else if (Utils::isJPEG(src)) { if (!rotateJPEG(src, tmp, angle, err, updateFileTimeStamp)) { if (err == "nothing to do") { err=QString::null; return true; } return false; } } else { // B.K.O #123499 : we using Image Magick API here instead QT API // else TIFF/PNG 16 bits image are broken! if (!rotateImageMagick(src, tmp, angle, err)) return false; // We update metadata on new image. Utils tools(this); if (!tools.updateMetadataImageMagick(tmp, err)) return false; } // Move back to original file if (!Utils::MoveFile(tmp, src)) { err = i18n("Cannot update source image"); return false; } return true; } bool ImageRotate::rotateJPEG(const QString& src, const QString& dest, RotateAction angle, QString& err, bool updateFileTimeStamp) { Matrix transform=Matrix::none; switch(angle) { case (Rot90): { transform = Matrix::rotate90; break; } case (Rot180): { transform = Matrix::rotate180; break; } case (Rot270): { transform = Matrix::rotate270; break; } case (Rot0): { transform = Matrix::none; break; } default: { kError( 51000 ) << "ImageRotate: Nonstandard rotation angle" << endl; err = i18n("Nonstandard rotation angle"); return false; } } return transformJPEG(src, dest, transform, err, updateFileTimeStamp); } bool ImageRotate::rotateImageMagick(const QString& src, const QString& dest, RotateAction angle, QString& err) { KProcess process; process.clearProgram(); process << "convert"; process << "-rotate"; switch(angle) { case (Rot90): { process << "90"; break; } case (Rot180): { process << "180"; break; } case (Rot270): { process << "270"; break; } case (Rot0): { break; } default: { kError( 51000 ) << "ImageRotate: Nonstandard rotation angle" << endl; err = i18n("Nonstandard rotation angle"); return false; } } process << src + QString("[0]") << dest; kDebug( 51000 ) << "ImageMagick Command line: " << process.program() << endl; process.start(); if (!process.waitForFinished()) return false; if (process.exitStatus() != QProcess::NormalExit) return false; switch (process.exitCode()) { case 0: // Process finished successfully ! { return true; break; } case 15: // process aborted ! { return false; break; } } // Processing error ! m_stdErr = process.readAllStandardError(); err = i18n("Cannot rotate: %1", m_stdErr.replace('\n', ' ')); return false; } } // namespace KIPIJPEGLossLessPlugin
ruphy/kipi-plugins
jpeglossless/imagerotate.cpp
C++
gpl-2.0
5,473
/* Includes ------------------------------------------------------------------*/ #include "indication.h" #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private constaints --------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ uint8_t adcEnd = 4; volatile uint16_t adcA, adcB, adcC, adcX; volatile uint8_t cX = 0; /* Extern variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************* * Function Name : ResetIO * Description : Reset all input/output data * Input : pointer to IO structure *******************************************************************************/ void ResetIO(struct IOtype *IO) { for(uint8_t i=0; i<5; i++) IO->buttons[i] = 0; for(uint8_t i=0; i<20; i++) IO->light[i] = 0; for(uint8_t i=0; i<8; i++) IO->RGB[i].R = IO->RGB[i].G = IO->RGB[i].B = 0; for(uint8_t i=0; i<7; i++) IO->lightIN[i] = IO->lightFL[i] = 0; } /******************************************************************************* * Function Name : SetIO * Description : Set all input/output data * Input : pointer to IO structure *******************************************************************************/ void SetIO(struct IOtype *IO) { for(uint8_t i=0; i<20; i++) IO->light[i] = 0xFF; for(uint8_t i=0; i<8; i++) IO->RGB[i].R = IO->RGB[i].G = IO->RGB[i].B = 0xFF; for(uint8_t i=0; i<7; i++) IO->lightIN[i] = IO->lightFL[i] = 0xFF; } /******************************************************************************* * Function Name : ProcessIO * Description : HAL: indication and buttons scan * Input : pointer to IO structure *******************************************************************************/ void ProcessIO(struct IOtype *IO) { //8 quant operations static uint8_t number5 = 0, number8 = 0; if(adcEnd == 0) { if(++number8 >= 8) number8 = 0; //DC BitWrite((number8 & 1),PORTC,1); BitWrite((number8 & 2),PORTC,5); BitWrite((number8 & 4),PORTC,7); //RGB backlight OCR1B = IO->RGB[number8].R; OCR2 = IO->RGB[number8].G; OCR1A = IO->RGB[number8].B; //ADC if(cX == 16) { IO->currFader[24] = adcX >> 4; cX = 0; adcX = 0; } //IO->currFader[24] = adcX; IO->currFader[number8] = adcA; IO->currFader[number8+8] = adcB; IO->currFader[number8+16]= adcC; adcA = adcB = adcC = 0; adcEnd = 4; ADCSRA |= (1<<ADSC); } //end 8 //5 quant operations //Shift registers BitReset(PORTB, 3); //çàäâèíåì èíôîðìàöèþ ñî æìÿêàëîê â 165å asm("nop"); asm("nop"); BitSet(PORTB, 3); PORTC &= ~((1<<PC0)|(1<<PC2)|(1<<PC3)|(1<<PC4)|(1<<6)); IO->buttons[number5] = 0; SPDR = ~(IO->light[number5+10]); while( !( SPSR & (1<<SPIF) ) ); // æäåì ïîêà ïåðåêèíåòñÿ "787878787" ******** ******** ******** IO->buttons[number5] |= SPDR; SPDR = (IO->light[number5+15]); //7seg [15-18] while( !( SPSR & (1<<SPIF) ) ); // æäåì ïîêà ïåðåêèíåòñÿ ******** "787878787" ******** ******** uint16_t A = SPDR << 8; IO->buttons[number5] |= A; SPDR = ~(IO->light[number5+5]); //bar while( !( SPSR & (1<<SPIF) ) ); // æäåì ïîêà ïåðåêèíåòñÿ ******** ******** "787878787" ******** SPDR = ~(IO->light[number5]); //beginning while( !( SPSR & (1<<SPIF) ) ); // æäåì ïîêà ïåðåêèíåòñÿ ******** ******** ******** "787878787" if(++number5 >= 5) number5 = 0; //_delay_us(200); BitSet(PORTB, 4); //çàäâèíåì èëëþìèíàöèþ â 595å asm("nop"); asm("nop"); BitReset(PORTB, 4); if(number5 == 0) BitSet(PORTC, 0); //äåøèôðàöèÿ îäíîé èç 5 ëèíèé if(number5 == 1) BitSet(PORTC, 2); if(number5 == 2) BitSet(PORTC, 3); if(number5 == 3) BitSet(PORTC, 4); if(number5 == 4) BitSet(PORTC, 6); //end 5 } /******************************************************************************* * Function Name : ADC_vect * Description : ADC Interrupt Handler *******************************************************************************/ ISR(ADC_vect) { if(adcEnd == 0) return; else { switch(adcEnd) { /* case 4: adcX = ADCL; adcX |= (uint8_t)(ADCH<<8); ADMUX = 5; break; //10bit case 3: adcA = ADCL; adcA |= (uint8_t)(ADCH<<8); ADMUX = 3; break; case 2: adcB = ADCL; adcB |= (uint8_t)(ADCH<<8); ADMUX = 1; break; case 1: adcC = ADCL; adcC |= (uint8_t)(ADCH<<8); ADMUX = 0; break;*/ case 4: adcX += ADCH >> 1; ADMUX = 5 | 0b01100000; cX++; break; //8bit case 3: adcA = ADCH >> 1; ADMUX = 1 | 0b01100000; break; case 2: adcC = ADCH >> 1; ADMUX = 3 | 0b01100000; break; case 1: adcB = ADCH >> 1; ADMUX = 0 | 0b01100000; break; } adcEnd--; ADCSRA |= (1<<ADSC); } }
EvgenyDD/DJ_Controller
SOFT/indication.c
C
gpl-2.0
5,144
package org.mo.game.editor.core.entity.common; import org.mo.game.editor.core.entity.base.XBaseEntityItemTemplate; public class XEntityItemTemplate extends XBaseEntityItemTemplate{ private static final long serialVersionUID = 1L; }
favedit/MoPlatform
mo-gm-develop/src/editor-java/org/mo/game/editor/core/entity/common/XEntityItemTemplate.java
Java
gpl-2.0
245
package data; import java.io.File; import java.io.FileReader; import java.util.HashMap; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * This class contains all different types of incidents that can arrive. * * @author Alexandre Fourgs * */ public class IncidentDatabase { private static IncidentDatabase INSTANCE = new IncidentDatabase(); private HashMap<Integer, IncidentData> incidentDatabase = new HashMap<Integer, IncidentData>(); private IncidentDatabase(){ incidentDatabase = incidentParsing(); } /** * Parses the .json file of incident and create a HashMap containing parsed data. * * @return a HashMap object that contains all types of incident & informations about it. * */ private HashMap<Integer, IncidentData> incidentParsing(){ HashMap<Integer, IncidentData> incidentDatabase = new HashMap<Integer, IncidentData>(); File json = new File("data/incident.json"); JSONParser fileParser = new JSONParser(); try { Object obj = fileParser.parse(new FileReader(json)); JSONObject jsonObject = (JSONObject) obj ; JSONArray schedulesArray = (JSONArray) jsonObject.get("Incident"); Iterator it = schedulesArray.iterator(); while (it.hasNext()) { JSONObject innerObj = (JSONObject) it.next(); int id = Integer.parseInt((String) innerObj.get("Id")); IncidentData actual = new IncidentData(id, (String)innerObj.get("Type"), Integer.parseInt((String) innerObj.get("Min_Time")), Integer.parseInt((String) innerObj.get("Max_Time"))); incidentDatabase.put(id, actual); } } catch (Exception e){ e.printStackTrace(); } return incidentDatabase ; } /** * Getter of the current initialized instance of IncidentDatabase * @return the initialized instance of IncidentDatabase */ public static IncidentDatabase getInstance(){ return INSTANCE ; } public HashMap<Integer, IncidentData> getIncidentDatabase(){ return incidentDatabase ; } }
Uinelj/logirail
src/data/IncidentDatabase.java
Java
gpl-2.0
2,182
/* A useful and efficient way to use compile-time recursion, partial template specialization and variadic template parameter pack by rangerprice, alias absorbement. */ template <typename Val, typename Type, typename...Args> inline void push(const std::pair<const Val, Type> var, const Args&...args) noexcept { const void* const valueptr = &var.first; operations[var.second](valueptr); nb_param++; push(args...); }; void push() const noexcept { }; template <typename...Args> void call(const std::string & fname, const Args&...args) noexcept { lua_settop(context, 0); lua_getglobal(context, fname.c_str()); push(args...); lua_call(context, nb_param, LUA_MULTRET); };
rangerprice/simplified-lua-api
source/template/slacore.tpl.cpp
C++
gpl-2.0
697
/* * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. */ package org.retest.swingset3.demos.spinner; import javax.swing.*; import java.awt.*; /** * Arranges labels and spinners into two vertical columns. Labels at the left, spinners at the right. * * @author Mikhail Lapshin */ //<snip>Helpful component for layout of labeled spinners public class JSpinnerPanel extends JPanel { private final JPanel labelPanel; private final JPanel spinnerPanel; public JSpinnerPanel() { setLayout( new BoxLayout( this, BoxLayout.X_AXIS ) ); labelPanel = new JPanel(); labelPanel.setLayout( new GridLayout( 0, 1 ) ); spinnerPanel = new JPanel(); spinnerPanel.setLayout( new GridLayout( 0, 1 ) ); add( labelPanel ); add( Box.createHorizontalStrut( 5 ) ); add( spinnerPanel ); } public void addSpinner( String labelText, JSpinner spinner ) { JLabel label = new JLabel( labelText ); label.setHorizontalAlignment( SwingConstants.TRAILING ); labelPanel.add( label ); JPanel flowPanel = new JPanel(); flowPanel.setLayout( new FlowLayout( FlowLayout.LEADING, 5, 1 ) ); flowPanel.add( spinner ); spinnerPanel.add( flowPanel ); } } //</snip>
retest/swingset3
src/org/retest/swingset3/demos/spinner/JSpinnerPanel.java
Java
gpl-2.0
2,708
/*************************************************************************** qgsvariableeditorwidget.h ------------------------- Date : April 2015 Copyright : (C) 2015 by Nyall Dawson Email : nyall dot dawson at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef QGSVARIABLEEDITORWIDGET_H #define QGSVARIABLEEDITORWIDGET_H #include "qgis.h" #include <QWidget> #include <QTreeWidget> #include <QItemDelegate> #include "qgis_gui.h" #include <memory> class QTableWidget; class QgsExpressionContextScope; class QPushButton; class QgsExpressionContext; class QgsVariableEditorTree; class VariableEditorDelegate; /** \ingroup gui * \class QgsVariableEditorWidget * A tree based widget for editing expression context scope variables. The widget allows editing * variables from a QgsExpressionContextScope, and can optionally also show inherited * variables from a QgsExpressionContext. * \since QGIS 2.12 */ class GUI_EXPORT QgsVariableEditorWidget : public QWidget { Q_OBJECT Q_PROPERTY( QString settingGroup READ settingGroup WRITE setSettingGroup ) public: /** Constructor for QgsVariableEditorWidget. * \param parent parent widget */ QgsVariableEditorWidget( QWidget *parent SIP_TRANSFERTHIS = 0 ); ~QgsVariableEditorWidget(); /** Overwrites the QgsExpressionContext for the widget. Setting a context * allows the widget to show all inherited variables for the context, * and highlight any overridden variables within scopes. * \param context expression context * \see context() */ void setContext( QgsExpressionContext *context ); /** Returns the current expression context for the widget. QgsVariableEditorWidget widgets * are created with an empty context by default. * \see setContext() */ QgsExpressionContext *context() const { return mContext.get(); } /** Sets the editable scope for the widget. Only variables from the editable scope can * be modified by users. * \param scopeIndex index of current editable scope. Set to -1 to disable * editing and make the widget read-only. * \see editableScope() */ void setEditableScopeIndex( int scopeIndex ); /** Returns the current editable scope for the widget. * \returns editable scope, or 0 if no editable scope is set * \see setEditableScopeIndex() */ QgsExpressionContextScope *editableScope() const; /** Sets the setting group for the widget. QgsVariableEditorWidget widgets with * the same setting group will synchronise their settings, e.g., the size * of columns in the tree widget. * \param group setting group * \see settingGroup() */ void setSettingGroup( const QString &group ) { mSettingGroup = group; } /** Returns the setting group for the widget. QgsVariableEditorWidget widgets with * the same setting group will synchronise their settings, e.g., the size * of columns in the tree widget. * \returns setting group name * \see setSettingGroup() */ QString settingGroup() const { return mSettingGroup; } /** Returns a map variables set within the editable scope. Read only variables are not * returned. This method can be used to retrieve the variables edited an added by * users via the widget. */ QVariantMap variablesInActiveScope() const; public slots: /** Reloads all scopes from the editor's current context. This method should be called * after adding or removing scopes from the attached context. * \see context() */ void reloadContext(); signals: /** Emitted when the user has modified a scope using the widget. */ void scopeChanged(); protected: void showEvent( QShowEvent *event ) override; private: std::unique_ptr<QgsExpressionContext> mContext; int mEditableScopeIndex = -1; QgsVariableEditorTree *mTreeWidget = nullptr; QPushButton *mAddButton = nullptr; QPushButton *mRemoveButton = nullptr; QString mSettingGroup; bool mShown = false; QString saveKey() const; private slots: void on_mAddButton_clicked(); void on_mRemoveButton_clicked(); void selectionChanged(); }; #ifndef SIP_RUN /// @cond PRIVATE /* QgsVariableEditorTree is NOT part of the public QGIS api. It's only * public here as Qt meta objects can't be nested classes */ class QgsVariableEditorTree : public QTreeWidget { Q_OBJECT public: enum VaribleRoles { ContextIndex = Qt::UserRole, RowBaseColor }; explicit QgsVariableEditorTree( QWidget *parent = nullptr ); QTreeWidgetItem *indexToItem( const QModelIndex &index ) const { return itemFromIndex( index ); } QModelIndex itemToIndex( QTreeWidgetItem *item ) const { return indexFromItem( item ); } QString variableNameFromItem( QTreeWidgetItem *item ) const { return item ? item->text( 0 ) : QString(); } QString variableNameFromIndex( const QModelIndex &index ) const { return variableNameFromItem( itemFromIndex( index ) ); } QgsExpressionContextScope *scopeFromItem( QTreeWidgetItem *item ) const; QTreeWidgetItem *itemFromVariable( QgsExpressionContextScope *scope, const QString &name ) const; void setEditableScopeIndex( int scopeIndex ) { mEditableScopeIndex = scopeIndex; } QgsExpressionContextScope *editableScope(); void setContext( QgsExpressionContext *context ) { mContext = context; } void refreshTree(); void removeItem( QTreeWidgetItem *item ); void renameItem( QTreeWidgetItem *item, const QString &name ); void resetTree(); void emitChanged(); signals: void scopeChanged(); protected: void keyPressEvent( QKeyEvent *event ) override; void mousePressEvent( QMouseEvent *event ) override; void drawRow( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const override; QColor rowColor( int index ) const; void toggleContextExpanded( QTreeWidgetItem *item ); void editNext( const QModelIndex &index ); QModelIndex moveCursor( CursorAction cursorAction, Qt::KeyboardModifiers modifiers ) override; QIcon mExpandIcon; private: VariableEditorDelegate *mEditorDelegate = nullptr; int mEditableScopeIndex = -1; QgsExpressionContext *mContext = nullptr; QMap< QPair<int, QString>, QTreeWidgetItem * > mVariableToItem; QMap< int, QTreeWidgetItem * > mScopeToItem; void refreshScopeItems( QgsExpressionContextScope *scope, int scopeIndex ); void refreshScopeVariables( QgsExpressionContextScope *scope, int scopeIndex ); }; class VariableEditorDelegate : public QItemDelegate { Q_OBJECT public: VariableEditorDelegate( QObject *parent = nullptr, QgsVariableEditorTree *tree = nullptr ) : QItemDelegate( parent ) , mParentTree( tree ) {} QWidget *createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const override; void updateEditorGeometry( QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index ) const override; QSize sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const override; void setModelData( QWidget *widget, QAbstractItemModel *model, const QModelIndex &index ) const override; void setEditorData( QWidget *, const QModelIndex & ) const override {} private: QgsVariableEditorTree *mParentTree = nullptr; }; /// @endcond #endif #endif //QGSVARIABLEEDITORWIDGET_H
GeoCat/QGIS
src/gui/qgsvariableeditorwidget.h
C
gpl-2.0
8,230
from unittest import mock from flask import request from routersploit.modules.exploits.routers.tplink.wdr740nd_wdr740n_backdoor import Exploit def apply_response(*args, **kwargs): cmd = request.args["cmd"] data = 'TEST; var cmdResult = new Array(\n"' + cmd + '",\n0,0 ); TEST' return data, 200 @mock.patch("routersploit.modules.exploits.routers.tplink.wdr740nd_wdr740n_backdoor.shell") def test_check_success(mocked_shell, target): """ Test scenario - successful check """ route_mock = target.get_route_mock("/userRpm/DebugResultRpm.htm", methods=["GET"]) route_mock.side_effect = apply_response exploit = Exploit() assert exploit.target == "" assert exploit.port == 80 assert exploit.username == "admin" assert exploit.password == "admin" exploit.target = target.host exploit.port = target.port assert exploit.check() assert exploit.run() is None
dasseclab/dasseclab
clones/routersploit/tests/exploits/routers/tplink/test_wdr740nd_wdr740n_backdoor.py
Python
gpl-2.0
917
<?php /*download sample.csv*/ $csvfilepath = get_option( 'home' ) ."/wp-content/themes/".get_option( 'template' )."/sample_csv.csv"; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header("Content-Type: image/png"); header("Content-type: application/force-download"); header('Content-Disposition: inline; filename="sample_csv.csv"'); header('Content-Transfer-Encoding: binary'); readfile($csvfilepath); exit; ?>
epgmedia/thunderpress-calendar
wp-content/themes/Events/library/includes/csvdl.php
PHP
gpl-2.0
488
/* 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. xrdp: A Remote Desktop Protocol server. Copyright (C) Jay Sorg 2005-2008 */ /** * * @file libscp_v1s.h * @brief libscp version 1 server api declarations * @author Simone Fedele * */ #ifndef LIBSCP_V1S_H #define LIBSCP_V1S_H #include "libscp.h" /* server API */ /** * * @brief processes the stream using scp version 1 * @param c connection descriptor * @param s pointer to session descriptor pointer * @param skipVchk if set to !0 skips the version control (to be used after * scp_vXs_accept() ) * * this function places in *s the address of a newely allocated SCP_SESSION structure * that should be free()d */ enum SCP_SERVER_STATES_E scp_v1s_accept(struct SCP_CONNECTION* c, struct SCP_SESSION** s, int skipVchk); /** * * @brief denies connection to sesman * @param c connection descriptor * @param reason pointer to a string containinge the reason for denying connection * */ /* 002 */ enum SCP_SERVER_STATES_E scp_v1s_deny_connection(struct SCP_CONNECTION* c, char* reason); enum SCP_SERVER_STATES_E scp_v1s_request_password(struct SCP_CONNECTION* c, struct SCP_SESSION* s, char* reason); /* 020 */ enum SCP_SERVER_STATES_E scp_v1s_request_pwd_change(struct SCP_CONNECTION* c, char* reason, char* npw); /* 023 */ enum SCP_SERVER_STATES_E scp_v1s_pwd_change_error(struct SCP_CONNECTION* c, char* error, int retry, char* npw); /* 030 */ enum SCP_SERVER_STATES_E scp_v1s_connect_new_session(struct SCP_CONNECTION* c, SCP_DISPLAY d); /* 032 */ enum SCP_SERVER_STATES_E scp_v1s_connection_error(struct SCP_CONNECTION* c, char* error); /* 040 */ enum SCP_SERVER_STATES_E scp_v1s_list_sessions(struct SCP_CONNECTION* c, int sescnt, struct SCP_DISCONNECTED_SESSION* ds, SCP_SID* sid); /* 046 was: 031 struct SCP_DISCONNECTED_SESSION* ds, */ enum SCP_SERVER_STATES_E scp_v1s_reconnect_session(struct SCP_CONNECTION* c, SCP_DISPLAY d); #endif
zeha/xrdp-suse-fork
sesman/libscp/libscp_v1s.h
C
gpl-2.0
2,612
# HowTo create a new container For all following examples it is assumed that you changed to the root directory of the git repository, which is most likely "~/M3_Container". ## The comfortable way (for beginners) There already are a few recipes for complete containers in "./scripts/create_container_XYZ.sh". These scripts will try to get the sources, configure and compile them and pack a complete container without interaction with the user. They always build the complete content of a container in the correct order, so all dependencies of the projects to build are satisfied. This scripts can be used as a template for own containers. ## In short (for advanced) 1. Use ./oss_sources/scripts/*.sh build scripts to cross compile open source projects 2. Optionally compile your own applications in ./closed_sources/* 3. Create a list ./scripts/rootfs_list/*.txt defining all files to be copied into the container 3. Create the update packet with the container with ./scripts/mk_container.sh ## Detailed instructions for creating containers (for experts) The build scripts located in ./oss_sources/scripts/*.sh are used to download, configure and compile the open source projects. A build script needs one of the parameters "all", "download", "check_source", "unpack", "configure", "compile", "install_staging" or "uninstall_staging". This parameters are functions that optionally can exist in a build script, they are not mandatory. If a build script lacks one of the functions, a generic function will do its default action. The build script are named after the package they will try to compile. They should be very specific and contain something like a version, so that build scripts for newer/older versions of the same project can be built. If building an open source project using one of these scripts fails, a missing dependency might be the reason. This is often the case when an open source package needs external libraries like openssl. That is the reason it might be important to compile the packages within the right order. 1. "all"<br> This parameter of a build script will try all steps from getting the sources up to installing the binaries 2. "download"<br> This parameter is used to get the sources of the open source project. In the beginning of the build script the variable "PKG_DOWNLOAD" contains the location of the open source packet archive. The packet will be stored in "oss_sources/dl" with the file name that is set to the variable "PKG_ARCHIVE_FILE" in the beginning of the build script. If there already is a file with that name the download will not happen. 3. "check_sources"<br> The MD5 checksum of the downloaded sources are checked. The variable "PKG_CHECKSUM" in the beginning of a build script must contain the expected MD5 sum. The variable "PKG_ARCHIVE_FILE" contains the file name that must be located in "./oss_sources/dl/". This check is highly recommended to avoid using defective or incomplete source archives. If you do not want to check the sources, you will have to set PKG_CHECKSUM="none" 4. "unpack"<br> The archive must get unpacked to "./working" for the following steps. In the beginning of the build script the variable "PKG_DIR" defines the directory within "./working" where the sources will be extracted to. This directory name should be named similar to the build script and the open source project. 5. "configure"<br> This function prepares the sources for the next step - compilation. If the directory named after $PKG_DIR in the directory "./oss_packages/src/" exists, and the function "copy_overlay" is called, all files in that directory are copied into the working directory. This will replace the files of the original project if there already are files with the same name. This way the sources can be modified. Important: Never change files in the working directory manually as long as you are not perfectly aware of this mechanism! When there is no such directory the source stay unmodified. Most of the time the "configure" function of a build script will call ".configure" in the working directory and prepare the sources for compilation. This is the chance to modify compile options or the feature set for the packet. Depending on the packet the configure function will contain different lines. Use the existing build scripts to get inspired. 6. "compile"<br> This function also can start with the function "copy_overlay" as described in the paragraph above. This can modify the sources after "configuring" them. Most of the time the compile function will result binaries in a new directory called "./working/PKG_DIR/install". The binaries are still unstripped. 7. "install_staging"<br> This function will copy files to the directory "./rootfs_staging". This directory is a collection of unmodified files, to offer them to other build scripts which need a link to these files within their "configure" step. A example for such a dependency are open source libraries. Build scripts of a library (e.g. openssl) install the header files and the binary library to "./rootfs_staging". Build scripts (e.g.) stunnel) need these header files to get configured. All files copied to "./rootfs_staging" are still unstripped. 8. "uninstall_staging"<br> This function reverts "install_staging". It removes all files copied to "./rootfs_staging". This would be necessary if a newer version of a library had no longer a certain header file. After compiling all needed open source binaries the own closed sources should be compiled. As this is an optional step and every closed source project can have different requirements for their compilation this is all left in the hand of the developer. It is recommended to have Makefiles or scripts similar to build scripts above. The final files should be copied to rootfs_staging. The final step is packaging everything to an update packet that can be stored and installed on a router. This is done by "./scripts/mk_container.sh": <pre> $ ./scripts/mk_container.sh -l scripts/rootfs_lists/default.txt -n "My_first_container" -v 1.0 </pre> The script packs all files and stores the resulting update packet in "./images". To be able to do that the script will create the directory "./working/rootfs_target/rootfs". A list with copy instructions is used to define the files that should be copied into the final container. This list is located in ./scripts/rootfs_lists/. Every line contains a file, directory or symlink to be copied or created. Each entry must be given the read/write/execute permissions and the ownership. This way a container can be created by a normal user, no root permission are necessary. To get more information about the the script use: "./scripts/mk_container.sh -h": -n name of the update packet with container to be packed -l use this file in the directory "./scripts/rootfs_lists/" to fill the root file system of container -k use this RSA key in the directory "./scripts/keys/" to encrypt the container -d use that description within MANIFEST -v use that version string within MANIFEST Optionally the root file system can be encrypted. In that case a random key is generated and the root file system gets encrypted with AES 256. The randomly generated key gets encrypted with a RSA key pair. The public part of the RSA key pair must exist on the router in order to be able to decrypt the update packet. The RSA key pairs to be used have to be stored in "./scripts/keys/". If there is no key pair, the script will create a new one and store it there.
mi-schindler/M3_Container
doc/HowTo_create_a_container.md
Markdown
gpl-2.0
7,595
class BadgeGrouping < ActiveRecord::Base GettingStarted = 1 Community = 2 Posting = 3 TrustLevel = 4 Other = 5 has_many :badges end # == Schema Information # # Table name: badge_groupings # # id :integer not null, primary key # name :string(255) not null # description :string(255) not null # position :integer not null # created_at :datetime # updated_at :datetime #
zoubeiri/discourse-snowboard
app/models/badge_grouping.rb
Ruby
gpl-2.0
438
module AllTests(main) where import AnalysisTests import ParserTests main = do allAnalysisTests allParserTests
dillonhuff/GitVisualizer
test/AllTests.hs
Haskell
gpl-2.0
116
#include <float.h> const float flt_epsilon_sse[4] __attribute__((aligned(16))) = { FLT_EPSILON, FLT_EPSILON, FLT_EPSILON, FLT_EPSILON }; void extract_m8_i16_SSE2(const unsigned char *srcp, const int stride, const int xdia, const int ydia, float *mstd, float *inputf) { __asm__ { mov rax,srcp mov ebx,stride mov edi,xdia mov edx,ydia mov rsp,inputf lea rsi,[rax+rbx*2] pxor xmm4,xmm4 // sum pxor xmm5,xmm5 // sumsq pxor xmm6,xmm6 yloop: xor rcx,rcx xloop: movq xmm0,QWORD PTR[rax+rcx] movq xmm1,QWORD PTR[rsi+rcx] movdqa xmm2,xmm0 movdqa xmm3,xmm1 punpcklbw xmm0,xmm6 punpcklbw xmm1,xmm6 psadbw xmm2,xmm6 psadbw xmm3,xmm6 movdqa [rsp],xmm0 movdqa [rsp+rdi*2],xmm1 pmaddwd xmm0,xmm0 pmaddwd xmm1,xmm1 paddd xmm4,xmm2 paddd xmm5,xmm0 paddd xmm4,xmm3 paddd xmm5,xmm1 add rcx,8 add rsp,16 cmp rcx,rdi jl xloop lea rax,[rax+rbx*4] lea rsi,[rsi+rbx*4] lea rsp,[rsp+rdi*2] sub edx,2 jnz yloop movhlps xmm1,xmm5 mov eax,ydia paddd xmm5,xmm1 mul rdi pshuflw xmm1,xmm5,14 cvtsi2ss xmm7,rax paddd xmm5,xmm1 rcpss xmm7,xmm7 // scale cvtdq2ps xmm4,xmm4 cvtdq2ps xmm5,xmm5 mov rax,mstd mulss xmm4,xmm7 // mean mulss xmm5,xmm7 movss [rax],xmm4 mulss xmm4,xmm4 subss xmm5,xmm4 // var comiss xmm5,flt_epsilon_sse jbe novarjmp rsqrtss xmm5,xmm5 // 1.0/std rcpss xmm4,xmm5 // std movss [rax+4],xmm4 movss [rax+8],xmm5 jmp finish novarjmp: movss [rax+4],xmm6 movss [rax+8],xmm6 finish: movss [rax+12],xmm6 } }
darealshinji/yua
src/nnedi3/nnedi3_extract_m8_i16_SSE2.c
C
gpl-2.0
1,699
/* This file is part of CBF. CBF 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. CBF 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 CBF. If not, see <http://www.gnu.org/licenses/>. Copyright 2011 Viktor Richter */ #ifndef CBF_RUN_CONTROLLER_HH #define CBF_RUN_CONTROLLER_HH #include <cbf/config.h> #include <cbf/controller.h> #include <cbf/control_basis.h> #include <cbf/debug_macros.h> #include <cbf/namespace.h> #ifdef CBF_HAVE_QT #include <QtGui/QApplication> #endif #include <IceUtil/Monitor.h> #include <IceUtil/RecMutex.h> #include <boost/shared_ptr.hpp> #include <stdexcept> namespace CBF { /** @brief An exception that will be thrown, when an action is called, which can not be done while the controller is running. */ struct ControllerRunningException : std::runtime_error { public: ControllerRunningException() : std::runtime_error ("action impossible while controller is running") { } }; /** @brief An exception that will be thrown, when an action is called, which needs the namespace to be set first. */ struct ObjectNamespaceNotSetException : std::runtime_error { public: ObjectNamespaceNotSetException() : std::runtime_error ("action impossible while the object namespace is not sets") { } }; /** @brief An exception that will be thrown, when start_controller() is called with a conntroller_name, that does not exist in the namespace */ struct ControllerNotFoundExcepption : std::runtime_error { public: ControllerNotFoundExcepption() : std::runtime_error ("could not find the controller in the object namespace") { } }; /** @brief A struct that runs a controller from a controller name and a ObjectNamespacePtr. The execution of the controller and all functions are (meant to be) threadsafe. */ struct CBFRunController { public: /** @brief Creates a CBFRunController struct, does not start to run the controller. Execution can be started with start_controller() after an ObjectNamespace was set. @param sleep_time The sleep time after each step of execution in milliseconds. @param steps The count of steps to execute. Setting steps to 0 lets the controller run until convergence. @param verbosity_level Sets the verbosity level.s */ CBFRunController( unsigned int sleep_time = 0, unsigned int steps = 0, unsigned int verbosity_level = 0 #ifdef CBF_HAVE_QT ,bool qt_support = false #endif ); /** A virtual destructor, so polymorphic cleanup works nicely */ virtual ~CBFRunController() {} /** @brief Sets the ObjectNamespace when the controller is not running (thread safe). */ void setObjectNamespace(CBF::ObjectNamespacePtr object_namespace) throw(ControllerRunningException); /** @brief Returns an ObjectNamespacePtr with a copy of the object namespace. */ const CBF::ObjectNamespacePtr getObjectNamespace() throw(ObjectNamespaceNotSetException); /** @brief Changes the sleep-time (thread-save). */ void setSleepTime(unsigned int time); /** @brief Returns the sleep-time (thread-save). */ unsigned int sleepTime(); /** @brief Changes the amount of steps (thread-save). If at start_controller() the amount of steps was greater then 0 a value less or equal 0 will stop the execution. */ void setStepCount(unsigned int steps); /** @brief Returns the step count (thread-save). */ unsigned int stepCount(); /** @brief Decreases the step count by 1 (thread-save). */ void decStepCount(); /** @brief Changes the verbosity level (thread-save). */ void setVerbosityLevel(unsigned int verbosity_level); /** @brief Returns the verbosity level (thread-save). */ unsigned int verbosityLevel(); #ifdef CBF_HAVE_QT /** @brief Switches the Qt-support (thread-save). Only works before start_controller() was called. qt_support must not be set to true without an initialized QApplication. */ void setQTSupport(bool qt_support); /** @brief Returns whether Qt-support is on (thread-save). */ bool qtSupport(); #endif /** @brief Starts to run the controller 'controller_name' from the m_ObjectNamespace. m_ObjectNamespace must be set before. Waits for m_SleepTime milliseconds after each step of execution. Execution can be stopped through stop_controller(). If m_Steps == 0 the controller runs until convergence. If m_Steps > 0 this amount of steps will be performed. */ void start_controller(std::string controller_name) throw(ObjectNamespaceNotSetException, ControllerNotFoundExcepption, ControllerRunningException); /** @brief Stops the controller from execution before the next step is performed. */ void stop_controller(); /** @brief a thread safe way to check whether the controller is running. @return Whether the controller is running. */ bool checkControllerRuns(); /** @brief a thread safe way to check whether the ObjectNamespace is already set. @return Whether the ObjectNamespace is set. */ bool checkObjectNamespaceSet(); /** @brief a thread safe way to check whether a controller is in the ObjectNamespace. @return Whether the controller exists. */ bool checkControllerExists(std::string controller_name) throw(ObjectNamespaceNotSetException, ControllerNotFoundExcepption); /** @brief a thread safe way to check whether the controller converged. @return Whether the controller converged in the last step(). */ bool checkConverged(); private: /** @brief Holds the ObjectnamespacePtr. */ ObjectNamespacePtr m_ObjectNamespace; /** @brief Holds the sleep-time in milliseconds. */ unsigned int m_SleepTime; /** @brief Holds the amount of steps to perform. */ unsigned int m_Steps; /** @brief Switches the verbosity level. */ unsigned int m_VerbosityLevel; #ifdef CBF_HAVE_QT /** @brief Switches the Qt-support. */ bool m_QtSupport; #endif /** @brief Tells whether the controller is running. */ bool m_ControllerRunning; /** @brief Tells whether the ObjectNamespace is set. */ bool m_ObjectNamespaceSet; /** @brief Tells whether the controller converged. */ bool m_Converged; /** @brief The mutex-lock that is used for the thread syncronization of the sleep-time resource. */ IceUtil::Monitor<IceUtil::RecMutex> m_SleepTimeMonitor; /** @brief The mutex-lock that is used for the thread syncronization of the steps resource. */ IceUtil::Monitor<IceUtil::RecMutex> m_StepsMonitor; /** @brief The mutex-lock that is used for the thread syncronization of the verbosity-level resource. */ IceUtil::Monitor<IceUtil::RecMutex> m_VerbosityLevelMonitor; /** @brief The mutex-lock that is used for the thread syncronization of the controllerRunning resource. */ IceUtil::Monitor<IceUtil::RecMutex> m_ControllerRunningMonitor; /** @brief The mutex-lock that is used for the thread syncronization of the converged resource. */ IceUtil::Monitor<IceUtil::RecMutex> m_ConvergedMonitor; #ifdef CBF_HAVE_QT /** @brief The mutex-lock that is used for the thread syncronization of the qt-support resource. */ IceUtil::Monitor<IceUtil::RecMutex> m_QtSupportMonitor; #endif /** @brief a thread safe way to check whether the controller is already running and set it. @param running A boolean to set the controller to. @return Whether the controller was running before. */ bool checkControllerRuns(bool running); /** @brief a thread safe way to set whether the controller converged. @param converged A boolean whether the controller converged. @return Returns the same boolean that is passed. */ bool setConverged(bool converged); }; /** @brief A shared pointer to a CBFRunController. */ typedef boost::shared_ptr<CBFRunController> CBFRunControllerPtr; } //namespace #endif
manuelbonilla/CBF
apps/cbf_run_controller.h
C
gpl-2.0
8,281