code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* This file was generated by SableCC (http://www.sablecc.org/). */ package org.sablecc.portugol.node; import org.sablecc.portugol.analysis.*; @SuppressWarnings("nls") public final class TColon extends Token { public TColon() { super.setText(":"); } public TColon(int line, int pos) { super.setText(":"); setLine(line); setPos(pos); } @Override public Object clone() { return new TColon(getLine(), getPos()); } @Override public void apply(Switch sw) { ((Analysis) sw).caseTColon(this); } @Override public void setText(@SuppressWarnings("unused") String text) { throw new RuntimeException("Cannot change TColon text."); } }
ericmguimaraes/compilador
Compilador/src/org/sablecc/portugol/node/TColon.java
Java
gpl-2.0
756
/* drivers/android/pmem.c * * Copyright (C) 2007 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/miscdevice.h> #include <linux/platform_device.h> #include <linux/fs.h> #include <linux/file.h> #include <linux/mm.h> #include <linux/list.h> #include <linux/debugfs.h> #include <linux/android_pmem.h> #include <linux/mempolicy.h> #include <linux/sched.h> #include <linux/slab.h> #include <asm/io.h> #include <asm/uaccess.h> #include <asm/cacheflush.h> #define PMEM_MAX_DEVICES 10 #define PMEM_MAX_ORDER 128 #define PMEM_MIN_ALLOC PAGE_SIZE #define PMEM_DEBUG 1 /* indicates that a refernce to this file has been taken via get_pmem_file, * the file should not be released until put_pmem_file is called */ #define PMEM_FLAGS_BUSY 0x1 /* indicates that this is a suballocation of a larger master range */ #define PMEM_FLAGS_CONNECTED (0x1 << 1) /* indicates this is a master and not a sub allocation and that it is mmaped */ #define PMEM_FLAGS_MASTERMAP (0x1 << 2) /* submap and unsubmap flags indicate: * 00: subregion has never been mmaped * 10: subregion has been mmaped, reference to the mm was taken * 11: subretion has ben released, refernece to the mm still held * 01: subretion has been released, reference to the mm has been released */ #define PMEM_FLAGS_SUBMAP (0x1 << 3) #define PMEM_FLAGS_UNSUBMAP (0x1 << 4) struct pmem_data { /* in alloc mode: an index into the bitmap * in no_alloc mode: the size of the allocation */ int index; /* see flags above for descriptions */ unsigned int flags; /* protects this data field, if the mm_mmap sem will be held at the * same time as this sem, the mm sem must be taken first (as this is * the order for vma_open and vma_close ops */ struct rw_semaphore sem; /* info about the mmaping process */ struct vm_area_struct *vma; /* task struct of the mapping process */ struct task_struct *task; /* process id of teh mapping process */ pid_t pid; /* file descriptor of the master */ int master_fd; /* file struct of the master */ struct file *master_file; /* a list of currently available regions if this is a suballocation */ struct list_head region_list; /* a linked list of data so we can access them for debugging */ struct list_head list; #if PMEM_DEBUG int ref; #endif }; struct pmem_bits { unsigned allocated:1; /* 1 if allocated, 0 if free */ unsigned order:7; /* size of the region in pmem space */ }; struct pmem_region_node { struct pmem_region region; struct list_head list; }; #define PMEM_DEBUG_MSGS 0 #if PMEM_DEBUG_MSGS #define DLOG(fmt, args...) \ do { printk(KERN_INFO "[%s:%s:%d] "fmt, __FILE__, __func__, __LINE__, \ ##args); } \ while (0) #else #define DLOG(x...) do {} while (0) #endif struct pmem_info { struct miscdevice dev; /* physical start address of the remaped pmem space */ unsigned long base; /* vitual start address of the remaped pmem space */ unsigned char __iomem *vbase; /* total size of the pmem space */ unsigned long size; /* number of entries in the pmem space */ unsigned long num_entries; /* pfn of the garbage page in memory */ unsigned long garbage_pfn; /* index of the garbage page in the pmem space */ int garbage_index; /* the bitmap for the region indicating which entries are allocated * and which are free */ struct pmem_bits *bitmap; /* indicates the region should not be managed with an allocator */ unsigned no_allocator; /* indicates maps of this region should be cached, if a mix of * cached and uncached is desired, set this and open the device with * O_SYNC to get an uncached region */ unsigned cached; unsigned buffered; /* in no_allocator mode the first mapper gets the whole space and sets * this flag */ unsigned allocated; /* for debugging, creates a list of pmem file structs, the * data_list_sem should be taken before pmem_data->sem if both are * needed */ struct semaphore data_list_sem; struct list_head data_list; /* pmem_sem protects the bitmap array * a write lock should be held when modifying entries in bitmap * a read lock should be held when reading data from bits or * dereferencing a pointer into bitmap * * pmem_data->sem protects the pmem data of a particular file * Many of the function that require the pmem_data->sem have a non- * locking version for when the caller is already holding that sem. * * IF YOU TAKE BOTH LOCKS TAKE THEM IN THIS ORDER: * down(pmem_data->sem) => down(bitmap_sem) */ struct rw_semaphore bitmap_sem; long (*ioctl)(struct file *, unsigned int, unsigned long); int (*release)(struct inode *, struct file *); }; static struct pmem_info pmem[PMEM_MAX_DEVICES]; static int id_count; #define PMEM_IS_FREE(id, index) (!(pmem[id].bitmap[index].allocated)) #define PMEM_ORDER(id, index) pmem[id].bitmap[index].order #define PMEM_BUDDY_INDEX(id, index) (index ^ (1 << PMEM_ORDER(id, index))) #define PMEM_NEXT_INDEX(id, index) (index + (1 << PMEM_ORDER(id, index))) #define PMEM_OFFSET(index) (index * PMEM_MIN_ALLOC) #define PMEM_START_ADDR(id, index) (PMEM_OFFSET(index) + pmem[id].base) #define PMEM_LEN(id, index) ((1 << PMEM_ORDER(id, index)) * PMEM_MIN_ALLOC) #define PMEM_END_ADDR(id, index) (PMEM_START_ADDR(id, index) + \ PMEM_LEN(id, index)) #define PMEM_START_VADDR(id, index) (PMEM_OFFSET(id, index) + pmem[id].vbase) #define PMEM_END_VADDR(id, index) (PMEM_START_VADDR(id, index) + \ PMEM_LEN(id, index)) #define PMEM_REVOKED(data) (data->flags & PMEM_FLAGS_REVOKED) #define PMEM_IS_PAGE_ALIGNED(addr) (!((addr) & (~PAGE_MASK))) #define PMEM_IS_SUBMAP(data) ((data->flags & PMEM_FLAGS_SUBMAP) && \ (!(data->flags & PMEM_FLAGS_UNSUBMAP))) static int pmem_release(struct inode *, struct file *); static int pmem_mmap(struct file *, struct vm_area_struct *); static int pmem_open(struct inode *, struct file *); static long pmem_ioctl(struct file *, unsigned int, unsigned long); struct file_operations pmem_fops = { .release = pmem_release, .mmap = pmem_mmap, .open = pmem_open, .unlocked_ioctl = pmem_ioctl, .llseek = noop_llseek, }; static int get_id(struct file *file) { return MINOR(file->f_dentry->d_inode->i_rdev); } static int is_pmem_file(struct file *file) { int id; if (unlikely(!file || !file->f_dentry || !file->f_dentry->d_inode)) return 0; id = get_id(file); if (unlikely(id >= PMEM_MAX_DEVICES)) return 0; if (unlikely(file->f_dentry->d_inode->i_rdev != MKDEV(MISC_MAJOR, pmem[id].dev.minor))) return 0; return 1; } static int has_allocation(struct file *file) { struct pmem_data *data; /* check is_pmem_file first if not accessed via pmem_file_ops */ if (unlikely(!file->private_data)) return 0; data = (struct pmem_data *)file->private_data; if (unlikely(data->index < 0)) return 0; return 1; } static int is_master_owner(struct file *file) { struct file *master_file; struct pmem_data *data; int put_needed, ret = 0; if (!is_pmem_file(file) || !has_allocation(file)) return 0; data = (struct pmem_data *)file->private_data; if (PMEM_FLAGS_MASTERMAP & data->flags) return 1; master_file = fget_light(data->master_fd, &put_needed); if (master_file && data->master_file == master_file) ret = 1; fput_light(master_file, put_needed); return ret; } static int pmem_free(int id, int index) { /* caller should hold the write lock on pmem_sem! */ int buddy, curr = index; DLOG("index %d\n", index); if (pmem[id].no_allocator) { pmem[id].allocated = 0; return 0; } /* clean up the bitmap, merging any buddies */ pmem[id].bitmap[curr].allocated = 0; /* find a slots buddy Buddy# = Slot# ^ (1 << order) * if the buddy is also free merge them * repeat until the buddy is not free or end of the bitmap is reached */ do { buddy = PMEM_BUDDY_INDEX(id, curr); if (PMEM_IS_FREE(id, buddy) && PMEM_ORDER(id, buddy) == PMEM_ORDER(id, curr)) { PMEM_ORDER(id, buddy)++; PMEM_ORDER(id, curr)++; curr = min(buddy, curr); } else { break; } } while (curr < pmem[id].num_entries); return 0; } static void pmem_revoke(struct file *file, struct pmem_data *data); static int pmem_release(struct inode *inode, struct file *file) { struct pmem_data *data = (struct pmem_data *)file->private_data; struct pmem_region_node *region_node; struct list_head *elt, *elt2; int id = get_id(file), ret = 0; down(&pmem[id].data_list_sem); /* if this file is a master, revoke all the memory in the connected * files */ if (PMEM_FLAGS_MASTERMAP & data->flags) { struct pmem_data *sub_data; list_for_each(elt, &pmem[id].data_list) { sub_data = list_entry(elt, struct pmem_data, list); down_read(&sub_data->sem); if (PMEM_IS_SUBMAP(sub_data) && file == sub_data->master_file) { up_read(&sub_data->sem); pmem_revoke(file, sub_data); } else up_read(&sub_data->sem); } } list_del(&data->list); up(&pmem[id].data_list_sem); down_write(&data->sem); /* if its not a conencted file and it has an allocation, free it */ if (!(PMEM_FLAGS_CONNECTED & data->flags) && has_allocation(file)) { down_write(&pmem[id].bitmap_sem); ret = pmem_free(id, data->index); up_write(&pmem[id].bitmap_sem); } /* if this file is a submap (mapped, connected file), downref the * task struct */ if (PMEM_FLAGS_SUBMAP & data->flags) if (data->task) { put_task_struct(data->task); data->task = NULL; } file->private_data = NULL; list_for_each_safe(elt, elt2, &data->region_list) { region_node = list_entry(elt, struct pmem_region_node, list); list_del(elt); kfree(region_node); } BUG_ON(!list_empty(&data->region_list)); up_write(&data->sem); kfree(data); if (pmem[id].release) ret = pmem[id].release(inode, file); return ret; } static int pmem_open(struct inode *inode, struct file *file) { struct pmem_data *data; int id = get_id(file); int ret = 0; DLOG("current %u file %p(%d)\n", current->pid, file, file_count(file)); /* setup file->private_data to indicate its unmapped */ /* you can only open a pmem device one time */ if (file->private_data != NULL) return -1; data = kmalloc(sizeof(struct pmem_data), GFP_KERNEL); if (!data) { printk("pmem: unable to allocate memory for pmem metadata."); return -1; } data->flags = 0; data->index = -1; data->task = NULL; data->vma = NULL; data->pid = 0; data->master_file = NULL; #if PMEM_DEBUG data->ref = 0; #endif INIT_LIST_HEAD(&data->region_list); init_rwsem(&data->sem); file->private_data = data; INIT_LIST_HEAD(&data->list); down(&pmem[id].data_list_sem); list_add(&data->list, &pmem[id].data_list); up(&pmem[id].data_list_sem); return ret; } static unsigned long pmem_order(unsigned long len) { int i; len = (len + PMEM_MIN_ALLOC - 1)/PMEM_MIN_ALLOC; len--; for (i = 0; i < sizeof(len)*8; i++) if (len >> i == 0) break; return i; } static int pmem_allocate(int id, unsigned long len) { /* caller should hold the write lock on pmem_sem! */ /* return the corresponding pdata[] entry */ int curr = 0; int end = pmem[id].num_entries; int best_fit = -1; unsigned long order = pmem_order(len); if (pmem[id].no_allocator) { DLOG("no allocator"); if ((len > pmem[id].size) || pmem[id].allocated) return -1; pmem[id].allocated = 1; return len; } if (order > PMEM_MAX_ORDER) return -1; DLOG("order %lx\n", order); /* look through the bitmap: * if you find a free slot of the correct order use it * otherwise, use the best fit (smallest with size > order) slot */ while (curr < end) { if (PMEM_IS_FREE(id, curr)) { if (PMEM_ORDER(id, curr) == (unsigned char)order) { /* set the not free bit and clear others */ best_fit = curr; break; } if (PMEM_ORDER(id, curr) > (unsigned char)order && (best_fit < 0 || PMEM_ORDER(id, curr) < PMEM_ORDER(id, best_fit))) best_fit = curr; } curr = PMEM_NEXT_INDEX(id, curr); } /* if best_fit < 0, there are no suitable slots, * return an error */ if (best_fit < 0) { printk("pmem: no space left to allocate!\n"); return -1; } /* now partition the best fit: * split the slot into 2 buddies of order - 1 * repeat until the slot is of the correct order */ while (PMEM_ORDER(id, best_fit) > (unsigned char)order) { int buddy; PMEM_ORDER(id, best_fit) -= 1; buddy = PMEM_BUDDY_INDEX(id, best_fit); PMEM_ORDER(id, buddy) = PMEM_ORDER(id, best_fit); } pmem[id].bitmap[best_fit].allocated = 1; return best_fit; } static pgprot_t phys_mem_access_prot(struct file *file, pgprot_t vma_prot) { int id = get_id(file); #ifdef pgprot_noncached if (pmem[id].cached == 0 || file->f_flags & O_SYNC) return pgprot_noncached(vma_prot); #endif #ifdef pgprot_ext_buffered else if (pmem[id].buffered) return pgprot_ext_buffered(vma_prot); #endif return vma_prot; } static unsigned long pmem_start_addr(int id, struct pmem_data *data) { if (pmem[id].no_allocator) return PMEM_START_ADDR(id, 0); else return PMEM_START_ADDR(id, data->index); } static void *pmem_start_vaddr(int id, struct pmem_data *data) { return pmem_start_addr(id, data) - pmem[id].base + pmem[id].vbase; } static unsigned long pmem_len(int id, struct pmem_data *data) { if (pmem[id].no_allocator) return data->index; else return PMEM_LEN(id, data->index); } static int pmem_map_garbage(int id, struct vm_area_struct *vma, struct pmem_data *data, unsigned long offset, unsigned long len) { int i, garbage_pages = len >> PAGE_SHIFT; vma->vm_flags |= VM_IO | VM_RESERVED | VM_PFNMAP | VM_SHARED | VM_WRITE; for (i = 0; i < garbage_pages; i++) { if (vm_insert_pfn(vma, vma->vm_start + offset + (i * PAGE_SIZE), pmem[id].garbage_pfn)) return -EAGAIN; } return 0; } static int pmem_unmap_pfn_range(int id, struct vm_area_struct *vma, struct pmem_data *data, unsigned long offset, unsigned long len) { int garbage_pages; DLOG("unmap offset %lx len %lx\n", offset, len); BUG_ON(!PMEM_IS_PAGE_ALIGNED(len)); garbage_pages = len >> PAGE_SHIFT; zap_page_range(vma, vma->vm_start + offset, len, NULL); pmem_map_garbage(id, vma, data, offset, len); return 0; } static int pmem_map_pfn_range(int id, struct vm_area_struct *vma, struct pmem_data *data, unsigned long offset, unsigned long len) { DLOG("map offset %lx len %lx\n", offset, len); BUG_ON(!PMEM_IS_PAGE_ALIGNED(vma->vm_start)); BUG_ON(!PMEM_IS_PAGE_ALIGNED(vma->vm_end)); BUG_ON(!PMEM_IS_PAGE_ALIGNED(len)); BUG_ON(!PMEM_IS_PAGE_ALIGNED(offset)); if (io_remap_pfn_range(vma, vma->vm_start + offset, (pmem_start_addr(id, data) + offset) >> PAGE_SHIFT, len, vma->vm_page_prot)) { return -EAGAIN; } return 0; } static int pmem_remap_pfn_range(int id, struct vm_area_struct *vma, struct pmem_data *data, unsigned long offset, unsigned long len) { /* hold the mm semp for the vma you are modifying when you call this */ BUG_ON(!vma); zap_page_range(vma, vma->vm_start + offset, len, NULL); return pmem_map_pfn_range(id, vma, data, offset, len); } static void pmem_vma_open(struct vm_area_struct *vma) { struct file *file = vma->vm_file; struct pmem_data *data = file->private_data; int id = get_id(file); /* this should never be called as we don't support copying pmem * ranges via fork */ BUG_ON(!has_allocation(file)); down_write(&data->sem); /* remap the garbage pages, forkers don't get access to the data */ pmem_unmap_pfn_range(id, vma, data, 0, vma->vm_start - vma->vm_end); up_write(&data->sem); } static void pmem_vma_close(struct vm_area_struct *vma) { struct file *file = vma->vm_file; struct pmem_data *data = file->private_data; DLOG("current %u ppid %u file %p count %d\n", current->pid, current->parent->pid, file, file_count(file)); if (unlikely(!is_pmem_file(file) || !has_allocation(file))) { printk(KERN_WARNING "pmem: something is very wrong, you are " "closing a vm backing an allocation that doesn't " "exist!\n"); return; } down_write(&data->sem); if (data->vma == vma) { data->vma = NULL; if ((data->flags & PMEM_FLAGS_CONNECTED) && (data->flags & PMEM_FLAGS_SUBMAP)) data->flags |= PMEM_FLAGS_UNSUBMAP; } /* the kernel is going to free this vma now anyway */ up_write(&data->sem); } static struct vm_operations_struct vm_ops = { .open = pmem_vma_open, .close = pmem_vma_close, }; static int pmem_mmap(struct file *file, struct vm_area_struct *vma) { struct pmem_data *data; int index; unsigned long vma_size = vma->vm_end - vma->vm_start; int ret = 0, id = get_id(file); if (vma->vm_pgoff || !PMEM_IS_PAGE_ALIGNED(vma_size)) { #if PMEM_DEBUG printk(KERN_ERR "pmem: mmaps must be at offset zero, aligned" " and a multiple of pages_size.\n"); #endif return -EINVAL; } data = (struct pmem_data *)file->private_data; down_write(&data->sem); /* check this file isn't already mmaped, for submaps check this file * has never been mmaped */ if ((data->flags & PMEM_FLAGS_MASTERMAP) || (data->flags & PMEM_FLAGS_SUBMAP) || (data->flags & PMEM_FLAGS_UNSUBMAP)) { #if PMEM_DEBUG printk(KERN_ERR "pmem: you can only mmap a pmem file once, " "this file is already mmaped. %x\n", data->flags); #endif ret = -EINVAL; goto error; } /* if file->private_data == unalloced, alloc*/ if (data && data->index == -1) { down_write(&pmem[id].bitmap_sem); index = pmem_allocate(id, vma->vm_end - vma->vm_start); up_write(&pmem[id].bitmap_sem); data->index = index; } /* either no space was available or an error occured */ if (!has_allocation(file)) { ret = -EINVAL; printk("pmem: could not find allocation for map.\n"); goto error; } if (pmem_len(id, data) < vma_size) { #if PMEM_DEBUG printk(KERN_WARNING "pmem: mmap size [%lu] does not match" "size of backing region [%lu].\n", vma_size, pmem_len(id, data)); #endif ret = -EINVAL; goto error; } vma->vm_pgoff = pmem_start_addr(id, data) >> PAGE_SHIFT; vma->vm_page_prot = phys_mem_access_prot(file, vma->vm_page_prot); if (data->flags & PMEM_FLAGS_CONNECTED) { struct pmem_region_node *region_node; struct list_head *elt; if (pmem_map_garbage(id, vma, data, 0, vma_size)) { printk("pmem: mmap failed in kernel!\n"); ret = -EAGAIN; goto error; } list_for_each(elt, &data->region_list) { region_node = list_entry(elt, struct pmem_region_node, list); DLOG("remapping file: %p %lx %lx\n", file, region_node->region.offset, region_node->region.len); if (pmem_remap_pfn_range(id, vma, data, region_node->region.offset, region_node->region.len)) { ret = -EAGAIN; goto error; } } data->flags |= PMEM_FLAGS_SUBMAP; get_task_struct(current->group_leader); data->task = current->group_leader; data->vma = vma; #if PMEM_DEBUG data->pid = current->pid; #endif DLOG("submmapped file %p vma %p pid %u\n", file, vma, current->pid); } else { if (pmem_map_pfn_range(id, vma, data, 0, vma_size)) { printk(KERN_INFO "pmem: mmap failed in kernel!\n"); ret = -EAGAIN; goto error; } data->flags |= PMEM_FLAGS_MASTERMAP; data->pid = current->pid; } vma->vm_ops = &vm_ops; error: up_write(&data->sem); return ret; } /* the following are the api for accessing pmem regions by other drivers * from inside the kernel */ int get_pmem_user_addr(struct file *file, unsigned long *start, unsigned long *len) { struct pmem_data *data; if (!is_pmem_file(file) || !has_allocation(file)) { #if PMEM_DEBUG printk(KERN_INFO "pmem: requested pmem data from invalid" "file.\n"); #endif return -1; } data = (struct pmem_data *)file->private_data; down_read(&data->sem); if (data->vma) { *start = data->vma->vm_start; *len = data->vma->vm_end - data->vma->vm_start; } else { *start = 0; *len = 0; } up_read(&data->sem); return 0; } int get_pmem_addr(struct file *file, unsigned long *start, unsigned long *vstart, unsigned long *len) { struct pmem_data *data; int id; if (!is_pmem_file(file) || !has_allocation(file)) return -1; data = (struct pmem_data *)file->private_data; if (data->index == -1) { #if PMEM_DEBUG printk(KERN_INFO "pmem: requested pmem data from file with no " "allocation.\n"); return -1; #endif } id = get_id(file); down_read(&data->sem); *start = pmem_start_addr(id, data); *len = pmem_len(id, data); *vstart = (unsigned long)pmem_start_vaddr(id, data); up_read(&data->sem); #if PMEM_DEBUG down_write(&data->sem); data->ref++; up_write(&data->sem); #endif return 0; } int get_pmem_file(int fd, unsigned long *start, unsigned long *vstart, unsigned long *len, struct file **filp) { struct file *file; file = fget(fd); if (unlikely(file == NULL)) { printk(KERN_INFO "pmem: requested data from file descriptor " "that doesn't exist."); return -1; } if (get_pmem_addr(file, start, vstart, len)) goto end; if (filp) *filp = file; return 0; end: fput(file); return -1; } void put_pmem_file(struct file *file) { struct pmem_data *data; int id; if (!is_pmem_file(file)) return; id = get_id(file); data = (struct pmem_data *)file->private_data; #if PMEM_DEBUG down_write(&data->sem); if (data->ref == 0) { printk("pmem: pmem_put > pmem_get %s (pid %d)\n", pmem[id].dev.name, data->pid); BUG(); } data->ref--; up_write(&data->sem); #endif fput(file); } void flush_pmem_file(struct file *file, unsigned long offset, unsigned long len) { struct pmem_data *data; int id; void *vaddr; struct pmem_region_node *region_node; struct list_head *elt; void *flush_start, *flush_end; if (!is_pmem_file(file) || !has_allocation(file)) return; id = get_id(file); data = (struct pmem_data *)file->private_data; if (!pmem[id].cached) return; down_read(&data->sem); vaddr = pmem_start_vaddr(id, data); /* if this isn't a submmapped file, flush the whole thing */ if (unlikely(!(data->flags & PMEM_FLAGS_CONNECTED))) { dmac_flush_range(vaddr, vaddr + pmem_len(id, data)); goto end; } /* otherwise, flush the region of the file we are drawing */ list_for_each(elt, &data->region_list) { region_node = list_entry(elt, struct pmem_region_node, list); if ((offset >= region_node->region.offset) && ((offset + len) <= (region_node->region.offset + region_node->region.len))) { flush_start = vaddr + region_node->region.offset; flush_end = flush_start + region_node->region.len; dmac_flush_range(flush_start, flush_end); break; } } end: up_read(&data->sem); } static int pmem_connect(unsigned long connect, struct file *file) { struct pmem_data *data = (struct pmem_data *)file->private_data; struct pmem_data *src_data; struct file *src_file; int ret = 0, put_needed; down_write(&data->sem); /* retrieve the src file and check it is a pmem file with an alloc */ src_file = fget_light(connect, &put_needed); DLOG("connect %p to %p\n", file, src_file); if (!src_file) { printk(KERN_INFO "pmem: src file not found!\n"); ret = -EINVAL; goto err_no_file; } if (unlikely(!is_pmem_file(src_file) || !has_allocation(src_file))) { printk(KERN_INFO "pmem: src file is not a pmem file or has no " "alloc!\n"); ret = -EINVAL; goto err_bad_file; } src_data = (struct pmem_data *)src_file->private_data; if (has_allocation(file) && (data->index != src_data->index)) { printk(KERN_INFO "pmem: file is already mapped but doesn't " "match this src_file!\n"); ret = -EINVAL; goto err_bad_file; } data->index = src_data->index; data->flags |= PMEM_FLAGS_CONNECTED; data->master_fd = connect; data->master_file = src_file; err_bad_file: fput_light(src_file, put_needed); err_no_file: up_write(&data->sem); return ret; } static void pmem_unlock_data_and_mm(struct pmem_data *data, struct mm_struct *mm) { up_write(&data->sem); if (mm != NULL) { up_write(&mm->mmap_sem); mmput(mm); } } static int pmem_lock_data_and_mm(struct file *file, struct pmem_data *data, struct mm_struct **locked_mm) { int ret = 0; struct mm_struct *mm = NULL; *locked_mm = NULL; lock_mm: down_read(&data->sem); if (PMEM_IS_SUBMAP(data)) { mm = get_task_mm(data->task); if (!mm) { #if PMEM_DEBUG printk(KERN_DEBUG "pmem: can't remap task is gone!\n"); #endif up_read(&data->sem); return -1; } } up_read(&data->sem); if (mm) down_write(&mm->mmap_sem); down_write(&data->sem); /* check that the file didn't get mmaped before we could take the * data sem, this should be safe b/c you can only submap each file * once */ if (PMEM_IS_SUBMAP(data) && !mm) { pmem_unlock_data_and_mm(data, mm); up_write(&data->sem); goto lock_mm; } /* now check that vma.mm is still there, it could have been * deleted by vma_close before we could get the data->sem */ if ((data->flags & PMEM_FLAGS_UNSUBMAP) && (mm != NULL)) { /* might as well release this */ if (data->flags & PMEM_FLAGS_SUBMAP) { put_task_struct(data->task); data->task = NULL; /* lower the submap flag to show the mm is gone */ data->flags &= ~(PMEM_FLAGS_SUBMAP); } pmem_unlock_data_and_mm(data, mm); return -1; } *locked_mm = mm; return ret; } int pmem_remap(struct pmem_region *region, struct file *file, unsigned operation) { int ret; struct pmem_region_node *region_node; struct mm_struct *mm = NULL; struct list_head *elt, *elt2; int id = get_id(file); struct pmem_data *data = (struct pmem_data *)file->private_data; /* pmem region must be aligned on a page boundry */ if (unlikely(!PMEM_IS_PAGE_ALIGNED(region->offset) || !PMEM_IS_PAGE_ALIGNED(region->len))) { #if PMEM_DEBUG printk(KERN_DEBUG "pmem: request for unaligned pmem " "suballocation %lx %lx\n", region->offset, region->len); #endif return -EINVAL; } /* if userspace requests a region of len 0, there's nothing to do */ if (region->len == 0) return 0; /* lock the mm and data */ ret = pmem_lock_data_and_mm(file, data, &mm); if (ret) return 0; /* only the owner of the master file can remap the client fds * that back in it */ if (!is_master_owner(file)) { #if PMEM_DEBUG printk("pmem: remap requested from non-master process\n"); #endif ret = -EINVAL; goto err; } /* check that the requested range is within the src allocation */ if (unlikely((region->offset > pmem_len(id, data)) || (region->len > pmem_len(id, data)) || (region->offset + region->len > pmem_len(id, data)))) { #if PMEM_DEBUG printk(KERN_INFO "pmem: suballoc doesn't fit in src_file!\n"); #endif ret = -EINVAL; goto err; } if (operation == PMEM_MAP) { region_node = kmalloc(sizeof(struct pmem_region_node), GFP_KERNEL); if (!region_node) { ret = -ENOMEM; #if PMEM_DEBUG printk(KERN_INFO "No space to allocate metadata!"); #endif goto err; } region_node->region = *region; list_add(&region_node->list, &data->region_list); } else if (operation == PMEM_UNMAP) { int found = 0; list_for_each_safe(elt, elt2, &data->region_list) { region_node = list_entry(elt, struct pmem_region_node, list); if (region->len == 0 || (region_node->region.offset == region->offset && region_node->region.len == region->len)) { list_del(elt); kfree(region_node); found = 1; } } if (!found) { #if PMEM_DEBUG printk("pmem: Unmap region does not map any mapped " "region!"); #endif ret = -EINVAL; goto err; } } if (data->vma && PMEM_IS_SUBMAP(data)) { if (operation == PMEM_MAP) ret = pmem_remap_pfn_range(id, data->vma, data, region->offset, region->len); else if (operation == PMEM_UNMAP) ret = pmem_unmap_pfn_range(id, data->vma, data, region->offset, region->len); } err: pmem_unlock_data_and_mm(data, mm); return ret; } static void pmem_revoke(struct file *file, struct pmem_data *data) { struct pmem_region_node *region_node; struct list_head *elt, *elt2; struct mm_struct *mm = NULL; int id = get_id(file); int ret = 0; data->master_file = NULL; ret = pmem_lock_data_and_mm(file, data, &mm); /* if lock_data_and_mm fails either the task that mapped the fd, or * the vma that mapped it have already gone away, nothing more * needs to be done */ if (ret) return; /* unmap everything */ /* delete the regions and region list nothing is mapped any more */ if (data->vma) list_for_each_safe(elt, elt2, &data->region_list) { region_node = list_entry(elt, struct pmem_region_node, list); pmem_unmap_pfn_range(id, data->vma, data, region_node->region.offset, region_node->region.len); list_del(elt); kfree(region_node); } /* delete the master file */ pmem_unlock_data_and_mm(data, mm); } static void pmem_get_size(struct pmem_region *region, struct file *file) { struct pmem_data *data = (struct pmem_data *)file->private_data; int id = get_id(file); if (!has_allocation(file)) { region->offset = 0; region->len = 0; return; } else { region->offset = pmem_start_addr(id, data); region->len = pmem_len(id, data); } DLOG("offset %lx len %lx\n", region->offset, region->len); } static long pmem_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct pmem_data *data; int id = get_id(file); switch (cmd) { case PMEM_GET_PHYS: { struct pmem_region region; DLOG("get_phys\n"); if (!has_allocation(file)) { region.offset = 0; region.len = 0; } else { data = (struct pmem_data *)file->private_data; region.offset = pmem_start_addr(id, data); region.len = pmem_len(id, data); } printk(KERN_INFO "pmem: request for physical address " "of pmem region from process %d.\n", current->pid); if (copy_to_user((void __user *)arg, &region, sizeof(struct pmem_region))) return -EFAULT; break; } case PMEM_MAP: { struct pmem_region region; if (copy_from_user(&region, (void __user *)arg, sizeof(struct pmem_region))) return -EFAULT; data = (struct pmem_data *)file->private_data; return pmem_remap(&region, file, PMEM_MAP); } break; case PMEM_UNMAP: { struct pmem_region region; if (copy_from_user(&region, (void __user *)arg, sizeof(struct pmem_region))) return -EFAULT; data = (struct pmem_data *)file->private_data; return pmem_remap(&region, file, PMEM_UNMAP); break; } case PMEM_GET_SIZE: { struct pmem_region region; DLOG("get_size\n"); pmem_get_size(&region, file); if (copy_to_user((void __user *)arg, &region, sizeof(struct pmem_region))) return -EFAULT; break; } case PMEM_GET_TOTAL_SIZE: { struct pmem_region region; DLOG("get total size\n"); region.offset = 0; get_id(file); region.len = pmem[id].size; if (copy_to_user((void __user *)arg, &region, sizeof(struct pmem_region))) return -EFAULT; break; } case PMEM_ALLOCATE: { if (has_allocation(file)) return -EINVAL; data = (struct pmem_data *)file->private_data; data->index = pmem_allocate(id, arg); break; } case PMEM_CONNECT: DLOG("connect\n"); return pmem_connect(arg, file); break; default: if (pmem[id].ioctl) return pmem[id].ioctl(file, cmd, arg); return -EINVAL; } return 0; } #if PMEM_DEBUG static ssize_t debug_open(struct inode *inode, struct file *file) { file->private_data = inode->i_private; return 0; } static ssize_t debug_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct list_head *elt, *elt2; struct pmem_data *data; struct pmem_region_node *region_node; int id = (int)file->private_data; const int debug_bufmax = 4096; static char buffer[4096]; int n = 0; DLOG("debug open\n"); n = scnprintf(buffer, debug_bufmax, "pid #: mapped regions (offset, len) (offset,len)...\n"); down(&pmem[id].data_list_sem); list_for_each(elt, &pmem[id].data_list) { data = list_entry(elt, struct pmem_data, list); down_read(&data->sem); n += scnprintf(buffer + n, debug_bufmax - n, "pid %u:", data->pid); list_for_each(elt2, &data->region_list) { region_node = list_entry(elt2, struct pmem_region_node, list); n += scnprintf(buffer + n, debug_bufmax - n, "(%lx,%lx) ", region_node->region.offset, region_node->region.len); } n += scnprintf(buffer + n, debug_bufmax - n, "\n"); up_read(&data->sem); } up(&pmem[id].data_list_sem); n++; buffer[n] = 0; return simple_read_from_buffer(buf, count, ppos, buffer, n); } static struct file_operations debug_fops = { .read = debug_read, .open = debug_open, .llseek = default_llseek, }; #endif #if 0 static struct miscdevice pmem_dev = { .name = "pmem", .fops = &pmem_fops, }; #endif int pmem_setup(struct android_pmem_platform_data *pdata, long (*ioctl)(struct file *, unsigned int, unsigned long), int (*release)(struct inode *, struct file *)) { int err = 0; int i, index = 0; int id = id_count; id_count++; pmem[id].no_allocator = pdata->no_allocator; pmem[id].cached = pdata->cached; pmem[id].buffered = pdata->buffered; pmem[id].base = pdata->start; pmem[id].size = pdata->size; pmem[id].ioctl = ioctl; pmem[id].release = release; init_rwsem(&pmem[id].bitmap_sem); init_MUTEX(&pmem[id].data_list_sem); INIT_LIST_HEAD(&pmem[id].data_list); pmem[id].dev.name = pdata->name; pmem[id].dev.minor = id; pmem[id].dev.fops = &pmem_fops; printk(KERN_INFO "%s: %d init\n", pdata->name, pdata->cached); err = misc_register(&pmem[id].dev); if (err) { printk(KERN_ALERT "Unable to register pmem driver!\n"); goto err_cant_register_device; } pmem[id].num_entries = pmem[id].size / PMEM_MIN_ALLOC; pmem[id].bitmap = kcalloc(pmem[id].num_entries, sizeof(struct pmem_bits), GFP_KERNEL); if (!pmem[id].bitmap) goto err_no_mem_for_metadata; for (i = sizeof(pmem[id].num_entries) * 8 - 1; i >= 0; i--) { if ((pmem[id].num_entries) & 1<<i) { PMEM_ORDER(id, index) = i; index = PMEM_NEXT_INDEX(id, index); } } if (pmem[id].cached) pmem[id].vbase = ioremap_cached(pmem[id].base, pmem[id].size); #ifdef ioremap_ext_buffered else if (pmem[id].buffered) pmem[id].vbase = ioremap_ext_buffered(pmem[id].base, pmem[id].size); #endif else pmem[id].vbase = ioremap(pmem[id].base, pmem[id].size); if (pmem[id].vbase == 0) goto error_cant_remap; pmem[id].garbage_pfn = page_to_pfn(alloc_page(GFP_KERNEL)); if (pmem[id].no_allocator) pmem[id].allocated = 0; #if PMEM_DEBUG debugfs_create_file(pdata->name, S_IFREG | S_IRUGO, NULL, (void *)id, &debug_fops); #endif return 0; error_cant_remap: kfree(pmem[id].bitmap); err_no_mem_for_metadata: misc_deregister(&pmem[id].dev); err_cant_register_device: return -1; } static int pmem_probe(struct platform_device *pdev) { struct android_pmem_platform_data *pdata; if (!pdev || !pdev->dev.platform_data) { printk(KERN_ALERT "Unable to probe pmem!\n"); return -1; } pdata = pdev->dev.platform_data; return pmem_setup(pdata, NULL, NULL); } static int pmem_remove(struct platform_device *pdev) { int id = pdev->id; __free_page(pfn_to_page(pmem[id].garbage_pfn)); misc_deregister(&pmem[id].dev); return 0; } static struct platform_driver pmem_driver = { .probe = pmem_probe, .remove = pmem_remove, .driver = { .name = "android_pmem" } }; static int __init pmem_init(void) { return platform_driver_register(&pmem_driver); } static void __exit pmem_exit(void) { platform_driver_unregister(&pmem_driver); } module_init(pmem_init); module_exit(pmem_exit);
nushor/samsung_aries_ics_OLD
drivers/staging/dream/pmem.c
C
gpl-2.0
35,828
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen //Copyright 2006-2011 Jeroen van Menen // // 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. #endregion Copyright using System; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using WatiN.Core.UnitTests.TestUtils; namespace WatiN.Core.UnitTests { [TestFixture] public class BaseElementCollectionTest : BaseWithBrowserTests { public override Uri TestPageUri { get { return MainURI; } } [Test] public void FirstWithAttributeConstraint() { ExecuteTest(browser => { var elements = browser.Elements; var element = elements.First(Find.ById("popupid")); Assert.That(element.Exists, Is.True); Assert.That(element, Is.TypeOf(typeof(Button))); }); } [Test] public void First() { ExecuteTest(browser => { var buttons = browser.Buttons; Element element = buttons.First(); Assert.That(element.Exists, Is.True); Assert.That(element.Id, Is.EqualTo("popupid")); Assert.That(element, Is.TypeOf(typeof(Button))); }); } [Test] public void ExistUsingPredicateT() { ExecuteTest(browser => Assert.That(browser.Buttons.Exists(b => b.Id == "helloid"))); } } }
sixsixdean/watin_test
src/UnitTests/BaseElementCollectionTest.cs
C#
gpl-2.0
2,044
define(["three"], /** * Extend THREE namespace with ConvolutionShader */ function(THREE) { /** * @author alteredq / http://alteredqualia.com/ * * Convolution shader * ported from o3d sample to WebGL / GLSL * http://o3d.googlecode.com/svn/trunk/samples/convolution.html */ THREE.ConvolutionShader = { defines: { "KERNEL_SIZE_FLOAT": "25.0", "KERNEL_SIZE_INT": "25", }, uniforms: { "tDiffuse": { type: "t", value: null }, "uImageIncrement": { type: "v2", value: new THREE.Vector2( 0.001953125, 0.0 ) }, "cKernel": { type: "fv1", value: [] } }, vertexShader: [ "uniform vec2 uImageIncrement;", "varying vec2 vUv;", "void main() {", "vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}" ].join("\n"), fragmentShader: [ "uniform float cKernel[ KERNEL_SIZE_INT ];", "uniform sampler2D tDiffuse;", "uniform vec2 uImageIncrement;", "varying vec2 vUv;", "void main() {", "vec2 imageCoord = vUv;", "vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );", "for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) {", "sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ];", "imageCoord += uImageIncrement;", "}", "gl_FragColor = sum;", "}" ].join("\n"), buildKernel: function ( sigma ) { // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway. function gauss( x, sigma ) { return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) ); } var i, values, sum, halfWidth, kMaxKernelSize = 25, kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1; if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize; halfWidth = ( kernelSize - 1 ) * 0.5; values = new Array( kernelSize ); sum = 0.0; for ( i = 0; i < kernelSize; ++i ) { values[ i ] = gauss( i - halfWidth, sigma ); sum += values[ i ]; } // normalize the kernel for ( i = 0; i < kernelSize; ++i ) values[ i ] /= sum; return values; } }; } );
emkatsom/virtual-atom-smasher
src/modules/extern/three-extras/js/shader-convolution.js
JavaScript
gpl-2.0
2,177
/** * 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("/BenchmarkTest00758") public class BenchmarkTest00758 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[] values = request.getParameterValues("vector"); String param; if (values != null && values.length > 0) param = values[0]; else param = ""; org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String bar = thing.doSomething(param); String cmd = ""; String a1 = ""; String a2 = ""; String[] args = null; String osName = System.getProperty("os.name"); if (osName.indexOf("Windows") != -1) { a1 = "cmd.exe"; a2 = "/c"; cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("echo"); args = new String[]{a1, a2, cmd, bar}; } else { a1 = "sh"; a2 = "-c"; cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("ping -c1"); args = new String[]{a1, a2,cmd + bar}; } Runtime r = Runtime.getRuntime(); try { Process p = r.exec(args); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p, response); } catch (IOException e) { System.out.println("Problem executing cmdi - TestCase"); throw new ServletException(e); } } }
andresriancho/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00758.java
Java
gpl-2.0
2,713
<?php $name='DejaVuSerifCondensed'; $type='TTF'; $desc=array ( 'CapHeight' => 729, 'XHeight' => 519, 'FontBBox' => '[-693 -347 1512 1109]', 'Flags' => 4, 'Ascent' => 928, 'Descent' => -236, 'Leading' => 0, 'ItalicAngle' => 0, 'StemV' => 87, 'MissingWidth' => 540, ); $unitsPerEm=2048; $up=-63; $ut=44; $strp=259; $strs=50; $ttffile='/opt/lampp/htdocs/projeto/application/third_party/mpdf/ttfonts/DejaVuSerifCondensed.ttf'; $TTCfontID='0'; $originalsize=334040; $sip=false; $smp=false; $BMPselected=true; $fontkey='dejavuserifcondensed'; $panose=' 0 0 2 6 6 6 5 6 5 2 2 4'; $haskerninfo=true; $haskernGPOS=false; $hassmallcapsGSUB=false; $fontmetrics='win'; // TypoAscender/TypoDescender/TypoLineGap = 760, -240, 200 // usWinAscent/usWinDescent = 928, -236 // hhea Ascent/Descent/LineGap = 928, -236, 0 $useOTL=0x0000; $rtlPUAstr=''; $kerninfo=array ( 45 => array ( 84 => -35, 86 => -72, 87 => -54, 88 => -35, 89 => -109, 221 => -109, 356 => -35, 376 => -109, ), 65 => array ( 84 => -54, 86 => -49, 87 => -40, 89 => -40, 102 => -17, 116 => -17, 118 => -40, 119 => -44, 121 => -40, 221 => -40, 253 => -40, 255 => -40, 354 => -54, 355 => -17, 356 => -54, 357 => -17, 372 => -40, 373 => -44, 374 => -40, 375 => -40, 376 => -40, 538 => -54, 539 => -17, 562 => -40, 7808 => -40, 7809 => -44, 7810 => -40, 7811 => -44, 7812 => -40, 7813 => -44, 7922 => -40, 7923 => -40, 8217 => -146, 8221 => -146, 64256 => -17, 64257 => -17, 64258 => -17, ), 66 => array ( 45 => 18, 67 => 18, 71 => 18, 79 => 18, 89 => -17, 199 => 18, 210 => 18, 211 => 18, 212 => 18, 213 => 18, 214 => 18, 216 => 18, 221 => -17, 262 => 18, 264 => 18, 266 => 18, 268 => 18, 284 => 18, 286 => 18, 288 => 18, 290 => 18, 332 => 18, 334 => 18, 336 => 18, 338 => 18, 374 => -17, 376 => -17, 490 => 18, 492 => 18, 558 => 18, 562 => -17, ), 67 => array ( 44 => -35, 46 => -35, ), 68 => array ( 44 => -35, 45 => 18, 46 => -35, 86 => -17, ), 69 => array ( 45 => 18, ), 70 => array ( 44 => -155, 45 => -44, 46 => -155, 58 => -35, 59 => -35, 65 => -86, 97 => -67, 101 => -54, 111 => -54, 192 => -86, 193 => -86, 194 => -86, 195 => -86, 196 => -86, 224 => -67, 225 => -67, 226 => -67, 227 => -67, 228 => -67, 229 => -67, 230 => -67, 232 => -54, 233 => -54, 234 => -54, 235 => -54, 242 => -54, 243 => -54, 244 => -54, 245 => -54, 246 => -54, 248 => -54, 256 => -86, 257 => -67, 258 => -86, 259 => -67, 260 => -86, 261 => -67, 275 => -54, 277 => -54, 279 => -54, 281 => -54, 283 => -54, 333 => -54, 335 => -54, 337 => -54, 339 => -54, 483 => -67, 491 => -54, 493 => -54, 559 => -54, ), 71 => array ( 44 => -35, 45 => 18, 46 => -35, 89 => -17, 221 => -17, 376 => -17, ), 74 => array ( 44 => -58, 46 => -77, 58 => -40, 59 => -40, ), 75 => array ( 45 => -72, 65 => -40, 67 => -26, 79 => -26, 85 => -35, 87 => -35, 89 => -26, 101 => -26, 111 => -26, 117 => -21, 121 => -63, 192 => -40, 193 => -40, 194 => -40, 195 => -40, 196 => -40, 199 => -26, 210 => -26, 211 => -26, 212 => -26, 213 => -26, 214 => -26, 216 => -26, 217 => -35, 218 => -35, 219 => -35, 220 => -35, 221 => -26, 232 => -26, 233 => -26, 234 => -26, 235 => -26, 242 => -26, 243 => -26, 244 => -26, 245 => -26, 246 => -26, 248 => -17, 249 => -21, 250 => -21, 251 => -21, 252 => -21, 253 => -63, 255 => -63, 262 => -26, 268 => -26, 283 => -26, 338 => -26, 339 => -26, 366 => -35, 367 => -21, 376 => -26, ), 76 => array ( 84 => -81, 85 => -54, 86 => -118, 87 => -86, 89 => -63, 121 => -17, 217 => -54, 218 => -54, 219 => -54, 220 => -54, 221 => -63, 253 => -17, 255 => -17, 356 => -81, 366 => -54, 376 => -63, 8217 => -239, 8221 => -239, ), 78 => array ( 44 => -63, 46 => -63, 58 => -35, 59 => -35, ), 79 => array ( 44 => -58, 45 => 36, 46 => -58, 86 => -17, 88 => -17, ), 80 => array ( 44 => -202, 45 => -54, 46 => -202, 58 => -35, 59 => -35, 65 => -91, 85 => -17, 97 => -44, 101 => -44, 111 => -40, 115 => -26, 192 => -91, 193 => -91, 194 => -91, 195 => -91, 196 => -91, 217 => -17, 218 => -17, 219 => -17, 220 => -17, 224 => -44, 225 => -44, 226 => -44, 227 => -44, 228 => -44, 229 => -44, 230 => -44, 232 => -44, 233 => -44, 234 => -44, 235 => -44, 242 => -40, 243 => -40, 244 => -40, 245 => -40, 246 => -40, 248 => -40, 283 => -44, 339 => -40, 351 => -26, 353 => -26, 366 => -17, ), 81 => array ( 44 => -49, 45 => 36, 46 => -49, 8217 => 18, 8221 => 18, ), 82 => array ( 84 => -17, 86 => -35, 87 => -21, 89 => -30, 97 => 22, 121 => -17, 221 => -30, 224 => 22, 225 => 22, 226 => 22, 227 => 22, 228 => 22, 229 => 22, 230 => 22, 248 => 18, 253 => -17, 255 => -17, 356 => -17, 376 => -30, 8217 => -54, 8221 => -54, ), 83 => array ( 44 => -35, 45 => 36, 46 => -35, 83 => -17, 350 => -17, 352 => -17, ), 84 => array ( 44 => -146, 45 => -128, 46 => -146, 58 => -35, 59 => -35, 65 => -54, 84 => 18, 97 => -77, 99 => -77, 101 => -77, 111 => -77, 115 => -72, 119 => -35, 192 => -54, 193 => -54, 194 => -54, 195 => -54, 196 => -54, 224 => -28, 225 => -77, 226 => -28, 227 => -28, 228 => -28, 229 => -28, 230 => -77, 231 => -77, 232 => -48, 233 => -77, 234 => -48, 235 => -48, 242 => -38, 243 => -77, 244 => -38, 245 => -38, 246 => -38, 248 => -77, 263 => -77, 269 => -77, 283 => -77, 339 => -77, 351 => -72, 353 => -72, 356 => 18, ), 85 => array ( 44 => -91, 45 => -17, 46 => -91, 58 => -35, 59 => -35, 65 => -30, 74 => -26, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 86 => array ( 44 => -174, 45 => -91, 46 => -174, 58 => -100, 59 => -100, 65 => -67, 79 => -17, 97 => -91, 101 => -91, 105 => -17, 111 => -91, 117 => -63, 121 => -40, 192 => -67, 193 => -67, 194 => -67, 195 => -67, 196 => -67, 210 => -17, 211 => -17, 212 => -17, 213 => -17, 214 => -17, 216 => -17, 224 => -91, 225 => -91, 226 => -91, 227 => -91, 228 => -91, 229 => -91, 230 => -91, 232 => -91, 233 => -91, 234 => -91, 235 => -91, 242 => -91, 243 => -91, 244 => -91, 245 => -91, 246 => -91, 248 => -91, 249 => -63, 250 => -63, 251 => -63, 252 => -63, 253 => -40, 255 => -40, 283 => -91, 338 => -17, 339 => -91, 367 => -63, 8217 => 36, 8221 => 36, ), 87 => array ( 44 => -174, 45 => -72, 46 => -174, 58 => -86, 59 => -86, 65 => -49, 97 => -86, 101 => -81, 105 => -17, 111 => -67, 114 => -44, 117 => -40, 121 => -21, 192 => -49, 193 => -49, 194 => -49, 195 => -49, 196 => -49, 224 => -86, 225 => -86, 226 => -86, 227 => -86, 228 => -86, 229 => -86, 230 => -67, 232 => -81, 233 => -81, 234 => -81, 235 => -81, 242 => -67, 243 => -67, 244 => -67, 245 => -67, 246 => -67, 248 => -67, 249 => -40, 250 => -40, 251 => -40, 252 => -40, 253 => -21, 255 => -21, 283 => -81, 339 => -67, 341 => -44, 345 => -44, 367 => -40, 8217 => 18, 8221 => 18, ), 88 => array ( 45 => -35, 65 => -35, 67 => -17, 79 => -17, 192 => -35, 193 => -35, 194 => -35, 195 => -35, 196 => -35, 199 => -17, 210 => -17, 211 => -17, 212 => -17, 213 => -17, 214 => -17, 216 => -17, 262 => -17, 268 => -17, 338 => -17, ), 89 => array ( 44 => -128, 45 => -109, 46 => -128, 58 => -123, 59 => -123, 65 => -77, 67 => -17, 97 => -77, 101 => -86, 105 => -17, 111 => -86, 117 => -86, 192 => -77, 193 => -77, 194 => -77, 195 => -77, 196 => -77, 199 => -17, 224 => -77, 225 => -77, 226 => -77, 227 => -77, 228 => -77, 229 => -77, 230 => -95, 232 => -86, 233 => -86, 234 => -86, 235 => -86, 242 => -86, 243 => -86, 244 => -86, 245 => -86, 246 => -86, 248 => -86, 249 => -86, 250 => -86, 251 => -86, 252 => -86, 262 => -17, 268 => -17, 283 => -86, 339 => -104, 367 => -86, ), 90 => array ( 44 => -17, 46 => -17, ), 102 => array ( 44 => -35, 45 => -35, 46 => -35, 8217 => 73, 8220 => 18, 8221 => 73, ), 107 => array ( 45 => -17, ), 111 => array ( 46 => -17, ), 114 => array ( 44 => -109, 46 => -109, ), 118 => array ( 44 => -118, 46 => -118, ), 119 => array ( 44 => -118, 46 => -118, ), 120 => array ( 45 => -17, ), 121 => array ( 44 => -132, 46 => -132, ), 192 => array ( 84 => -54, 86 => -49, 87 => -40, 89 => -40, 102 => -17, 116 => -17, 118 => -40, 119 => -44, 121 => -40, 221 => -40, 253 => -40, 255 => -40, 354 => -54, 355 => -17, 356 => -54, 357 => -17, 372 => -40, 373 => -44, 374 => -40, 375 => -40, 376 => -40, 538 => -54, 539 => -17, 562 => -40, 7808 => -40, 7809 => -44, 7810 => -40, 7811 => -44, 7812 => -40, 7813 => -44, 7922 => -40, 7923 => -40, 8217 => -146, 8221 => -146, 64256 => -17, 64257 => -17, 64258 => -17, ), 193 => array ( 84 => -54, 86 => -49, 87 => -40, 89 => -40, 102 => -17, 116 => -17, 118 => -40, 119 => -44, 121 => -40, 221 => -40, 253 => -40, 255 => -40, 354 => -54, 355 => -17, 356 => -54, 357 => -17, 372 => -40, 373 => -44, 374 => -40, 375 => -40, 376 => -40, 538 => -54, 539 => -17, 562 => -40, 7808 => -40, 7809 => -44, 7810 => -40, 7811 => -44, 7812 => -40, 7813 => -44, 7922 => -40, 7923 => -40, 8217 => -146, 8221 => -146, 64256 => -17, 64257 => -17, 64258 => -17, ), 194 => array ( 84 => -54, 86 => -49, 87 => -40, 89 => -40, 102 => -17, 116 => -17, 118 => -40, 119 => -44, 121 => -40, 221 => -40, 253 => -40, 255 => -40, 354 => -54, 355 => -17, 356 => -54, 357 => -17, 372 => -40, 373 => -44, 374 => -40, 375 => -40, 376 => -40, 538 => -54, 539 => -17, 562 => -40, 7808 => -40, 7809 => -44, 7810 => -40, 7811 => -44, 7812 => -40, 7813 => -44, 7922 => -40, 7923 => -40, 8217 => -146, 8221 => -146, 64256 => -17, 64257 => -17, 64258 => -17, ), 195 => array ( 84 => -54, 86 => -49, 87 => -40, 89 => -40, 102 => -17, 116 => -17, 118 => -40, 119 => -44, 121 => -40, 221 => -40, 253 => -40, 255 => -40, 354 => -54, 355 => -17, 356 => -54, 357 => -17, 372 => -40, 373 => -44, 374 => -40, 375 => -40, 376 => -40, 538 => -54, 539 => -17, 562 => -40, 7808 => -40, 7809 => -44, 7810 => -40, 7811 => -44, 7812 => -40, 7813 => -44, 7922 => -40, 7923 => -40, 8217 => -146, 8221 => -146, 64256 => -17, 64257 => -17, 64258 => -17, ), 196 => array ( 84 => -54, 86 => -49, 87 => -40, 89 => -40, 102 => -17, 116 => -17, 118 => -40, 119 => -44, 121 => -40, 221 => -40, 253 => -40, 255 => -40, 354 => -54, 355 => -17, 356 => -54, 357 => -17, 372 => -40, 373 => -44, 374 => -40, 375 => -40, 376 => -40, 538 => -54, 539 => -17, 562 => -40, 7808 => -40, 7809 => -44, 7810 => -40, 7811 => -44, 7812 => -40, 7813 => -44, 7922 => -40, 7923 => -40, 8217 => -146, 8221 => -146, 64256 => -17, 64257 => -17, 64258 => -17, ), 198 => array ( 45 => 18, ), 199 => array ( 44 => -35, 46 => -35, ), 200 => array ( 45 => 18, ), 201 => array ( 45 => 18, ), 202 => array ( 45 => 18, ), 203 => array ( 45 => 18, ), 208 => array ( 44 => -35, 45 => 36, 46 => -35, 65 => -17, 86 => -17, 89 => -17, 192 => -17, 193 => -17, 194 => -17, 195 => -17, 196 => -17, 221 => -17, 376 => -17, ), 209 => array ( 44 => -63, 46 => -63, 58 => -35, 59 => -35, ), 210 => array ( 44 => -58, 45 => 36, 46 => -58, 86 => -17, 88 => -17, ), 211 => array ( 44 => -58, 45 => 36, 46 => -58, 86 => -17, 88 => -17, ), 212 => array ( 44 => -58, 45 => 36, 46 => -58, 86 => -17, 88 => -17, ), 213 => array ( 44 => -58, 45 => 36, 46 => -58, 86 => -17, 88 => -17, ), 214 => array ( 44 => -58, 45 => 36, 46 => -58, 86 => -17, 88 => -17, ), 216 => array ( 44 => -58, 45 => 36, 46 => -58, 86 => -17, 88 => -17, ), 217 => array ( 44 => -91, 45 => -17, 46 => -91, 58 => -35, 59 => -35, 65 => -30, 74 => -26, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 218 => array ( 44 => -91, 45 => -17, 46 => -91, 58 => -35, 59 => -35, 65 => -30, 74 => -26, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 219 => array ( 44 => -91, 45 => -17, 46 => -91, 58 => -35, 59 => -35, 65 => -30, 74 => -26, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 220 => array ( 44 => -91, 45 => -17, 46 => -91, 58 => -35, 59 => -35, 65 => -30, 74 => -26, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 221 => array ( 44 => -128, 45 => -109, 46 => -128, 58 => -123, 59 => -123, 65 => -77, 67 => -17, 97 => -77, 101 => -86, 105 => -17, 111 => -86, 117 => -86, 192 => -77, 193 => -77, 194 => -77, 195 => -77, 196 => -77, 199 => -17, 224 => -77, 225 => -77, 226 => -77, 227 => -77, 228 => -77, 229 => -77, 230 => -95, 232 => -86, 233 => -86, 234 => -86, 235 => -86, 242 => -86, 243 => -86, 244 => -86, 245 => -86, 246 => -86, 248 => -86, 249 => -86, 250 => -86, 251 => -86, 252 => -86, 262 => -17, 268 => -17, 283 => -86, 339 => -104, 367 => -86, ), 222 => array ( 44 => -165, 45 => 18, 46 => -165, ), 240 => array ( 46 => -17, ), 242 => array ( 46 => -17, ), 243 => array ( 46 => -17, ), 244 => array ( 46 => -17, ), 245 => array ( 46 => -17, ), 246 => array ( 46 => -17, ), 248 => array ( 46 => -17, ), 253 => array ( 44 => -132, 46 => -132, ), 254 => array ( 44 => -17, 46 => -49, ), 255 => array ( 44 => -132, 46 => -132, ), 256 => array ( 84 => -54, 86 => -49, 87 => -40, 89 => -40, 102 => -17, 116 => -17, 118 => -40, 119 => -44, 121 => -40, 221 => -40, 253 => -40, 255 => -40, 354 => -54, 355 => -17, 356 => -54, 357 => -17, 372 => -40, 373 => -44, 374 => -40, 375 => -40, 376 => -40, 538 => -54, 539 => -17, 562 => -40, 7808 => -40, 7809 => -44, 7810 => -40, 7811 => -44, 7812 => -40, 7813 => -44, 7922 => -40, 7923 => -40, 8217 => -146, 8221 => -146, 64256 => -17, 64257 => -17, 64258 => -17, ), 258 => array ( 84 => -54, 86 => -49, 87 => -40, 89 => -40, 102 => -17, 116 => -17, 118 => -40, 119 => -44, 121 => -40, 221 => -40, 253 => -40, 255 => -40, 354 => -54, 355 => -17, 356 => -54, 357 => -17, 372 => -40, 373 => -44, 374 => -40, 375 => -40, 376 => -40, 538 => -54, 539 => -17, 562 => -40, 7808 => -40, 7809 => -44, 7810 => -40, 7811 => -44, 7812 => -40, 7813 => -44, 7922 => -40, 7923 => -40, 8217 => -146, 8221 => -146, 64256 => -17, 64257 => -17, 64258 => -17, ), 260 => array ( 84 => -54, 86 => -49, 87 => -40, 89 => -40, 102 => -17, 116 => -17, 118 => -40, 119 => -44, 121 => -40, 221 => -40, 253 => -40, 255 => -40, 354 => -54, 355 => -17, 356 => -54, 357 => -17, 372 => -40, 373 => -44, 374 => -40, 375 => -40, 376 => -40, 538 => -54, 539 => -17, 562 => -40, 7808 => -40, 7809 => -44, 7810 => -40, 7811 => -44, 7812 => -40, 7813 => -44, 7922 => -40, 7923 => -40, 8217 => -146, 8221 => -146, 64256 => -17, 64257 => -17, 64258 => -17, ), 262 => array ( 44 => -35, 46 => -35, ), 264 => array ( 44 => -35, 46 => -35, ), 266 => array ( 44 => -35, 46 => -35, ), 268 => array ( 44 => -35, 46 => -35, ), 270 => array ( 44 => -35, 45 => 18, 46 => -35, 86 => -17, ), 272 => array ( 44 => -35, 45 => 18, 46 => -35, 86 => -17, ), 282 => array ( 45 => 18, ), 286 => array ( 44 => -35, 45 => 18, 46 => -35, 89 => -17, 221 => -17, 376 => -17, ), 313 => array ( 84 => -81, 85 => -54, 86 => -118, 87 => -86, 89 => -63, 121 => -17, 217 => -54, 218 => -54, 219 => -54, 220 => -54, 221 => -63, 253 => -17, 255 => -17, 356 => -81, 366 => -54, 376 => -63, 8217 => -239, 8221 => -239, ), 317 => array ( 84 => -81, 85 => -54, 86 => -118, 87 => -86, 89 => -63, 121 => -17, 217 => -54, 218 => -54, 219 => -54, 220 => -54, 221 => -63, 253 => -17, 255 => -17, 356 => -81, 366 => -54, 376 => -63, 8217 => -239, 8221 => -239, ), 320 => array ( 108 => -110, ), 321 => array ( 84 => -81, 85 => -17, 86 => -118, 87 => -86, 89 => -100, 121 => -17, 217 => -17, 218 => -17, 219 => -17, 220 => -17, 221 => -100, 253 => -17, 255 => -17, 356 => -81, 366 => -17, 376 => -100, 8217 => -239, 8221 => -239, ), 327 => array ( 44 => -63, 46 => -63, 58 => -35, 59 => -35, ), 338 => array ( 45 => 18, ), 340 => array ( 84 => -17, 86 => -35, 87 => -21, 89 => -30, 97 => 22, 121 => -17, 221 => -30, 224 => 22, 225 => 22, 226 => 22, 227 => 22, 228 => 22, 229 => 22, 230 => 22, 248 => 18, 253 => -17, 255 => -17, 356 => -17, 376 => -30, 8217 => -54, 8221 => -54, ), 341 => array ( 44 => -109, 46 => -109, ), 344 => array ( 84 => -17, 86 => -35, 87 => -21, 89 => -30, 97 => 22, 121 => -17, 221 => -30, 224 => 22, 225 => 22, 226 => 22, 227 => 22, 228 => 22, 229 => 22, 230 => 22, 248 => 18, 253 => -17, 255 => -17, 356 => -17, 376 => -30, 8217 => -54, 8221 => -54, ), 345 => array ( 44 => -109, 46 => -109, ), 350 => array ( 44 => -35, 45 => 36, 46 => -35, 83 => -17, 350 => -17, 352 => -17, ), 352 => array ( 44 => -35, 45 => 36, 46 => -35, 83 => -17, 350 => -17, 352 => -17, ), 356 => array ( 44 => -146, 45 => -128, 46 => -146, 58 => -35, 59 => -35, 65 => -54, 84 => 18, 97 => -77, 99 => -77, 101 => -77, 111 => -77, 115 => -72, 119 => -35, 192 => -54, 193 => -54, 194 => -54, 195 => -54, 196 => -54, 224 => -77, 225 => -77, 226 => -77, 227 => -77, 228 => -77, 229 => -77, 230 => -77, 231 => -77, 232 => -77, 233 => -77, 234 => -77, 235 => -77, 242 => -77, 243 => -77, 244 => -77, 245 => -77, 246 => -77, 248 => -77, 263 => -77, 269 => -77, 283 => -77, 339 => -77, 351 => -72, 353 => -72, 356 => 18, ), 366 => array ( 44 => -91, 45 => -17, 46 => -91, 58 => -35, 59 => -35, 65 => -30, 74 => -26, 192 => -30, 193 => -30, 194 => -30, 195 => -30, 196 => -30, ), 373 => array ( 44 => -149, 46 => -133, 97 => 53, 99 => 41, 100 => 47, 101 => 41, 102 => 107, 103 => 47, 105 => 107, 106 => 106, 109 => 61, 110 => 61, 111 => 41, 112 => 68, 113 => 47, 114 => 61, 115 => 75, 116 => 114, 117 => 70, 118 => 100, 119 => 81, 120 => 84, 121 => 100, 122 => 87, 373 => 127, 64256 => 107, ), 376 => array ( 44 => -128, 45 => -109, 46 => -128, 58 => -123, 59 => -123, 65 => -77, 67 => -17, 97 => -77, 101 => -86, 105 => -17, 111 => -86, 117 => -86, 192 => -77, 193 => -77, 194 => -77, 195 => -77, 196 => -77, 199 => -17, 224 => -77, 225 => -77, 226 => -77, 227 => -77, 228 => -77, 229 => -77, 230 => -95, 232 => -86, 233 => -86, 234 => -86, 235 => -86, 242 => -86, 243 => -86, 244 => -86, 245 => -86, 246 => -86, 248 => -86, 249 => -86, 250 => -86, 251 => -86, 252 => -86, 262 => -17, 268 => -17, 283 => -86, 339 => -104, 367 => -86, ), 381 => array ( 44 => -17, 46 => -17, ), 699 => array ( 65 => -128, 74 => 22, 192 => -128, 193 => -128, 194 => -128, 195 => -128, 196 => -128, 198 => -109, ), 8208 => array ( 84 => -35, 86 => -72, 87 => -54, 88 => -35, 89 => -109, 221 => -109, 356 => -35, 376 => -109, ), 8216 => array ( 65 => -128, 74 => 22, 192 => -128, 193 => -128, 194 => -128, 195 => -128, 196 => -128, 198 => -109, ), 8220 => array ( 65 => -128, 74 => 22, 86 => 27, 87 => 27, 88 => 27, 89 => 27, 192 => -128, 193 => -128, 194 => -128, 195 => -128, 196 => -128, 198 => -146, 221 => 27, 376 => 27, ), 8222 => array ( 84 => -35, 86 => -54, 87 => -35, 88 => 27, 89 => -35, 118 => -17, 119 => -17, 221 => -35, 356 => -35, 376 => -35, ), 42816 => array ( 45 => -72, 65 => -40, 67 => -26, 79 => -26, 85 => -35, 87 => -35, 89 => -26, 101 => -26, 111 => -26, 117 => -21, 121 => -63, 192 => -40, 193 => -40, 194 => -40, 195 => -40, 196 => -40, 199 => -26, 210 => -26, 211 => -26, 212 => -26, 213 => -26, 214 => -26, 216 => -26, 217 => -35, 218 => -35, 219 => -35, 220 => -35, 221 => -26, 232 => -26, 233 => -26, 234 => -26, 235 => -26, 242 => -26, 243 => -26, 244 => -26, 245 => -26, 246 => -26, 248 => -17, 249 => -21, 250 => -21, 251 => -21, 252 => -21, 253 => -63, 255 => -63, 262 => -26, 268 => -26, 283 => -26, 338 => -26, 339 => -26, 366 => -35, 367 => -21, 376 => -26, ), 42817 => array ( 45 => -17, ), 64256 => array ( 44 => -35, 45 => -35, 46 => -35, 8217 => 73, 8220 => 18, 8221 => 73, ), ); ?>
ArleyOliveira/SistemaEstacionamento
application/third_party/mpdf/ttfontdata/dejavuserifcondensed.mtx.php
PHP
gpl-2.0
25,084
/* Defines the LTC_ARGCHK macro used within the library */ /* ARGTYPE is defined in mycrypt_cfg.h */ #if ARGTYPE == 0 #include <signal.h> /* this is the default LibTomCrypt macro */ void crypt_argchk(char *v, char *s, int d); #define LTC_ARGCHK(x) if (!(x)) { crypt_argchk(#x, __FILE__, __LINE__); } #elif ARGTYPE == 1 /* fatal type of error */ #define LTC_ARGCHK(x) assert((x)) #elif ARGTYPE == 2 #define LTC_ARGCHK(x) #endif /* $Source$ */ /* $Revision$ */ /* $Date$ */
ipwndev/DSLinux-Mirror
user/dropbear/libtomcrypt/src/headers/tomcrypt_argchk.h
C
gpl-2.0
483
/** * OWASP Benchmark Project v1.1 * * 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 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 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("/BenchmarkTest19759") public class BenchmarkTest19759 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 { String[] values = request.getParameterValues("foo"); String param; if (values.length != 0) param = request.getParameterValues("foo")[0]; else param = null; String bar = doSomething(param); String sql = "UPDATE USERS SET PASSWORD='" + bar + "' WHERE USERNAME='foo'"; try { java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement(); int count = statement.executeUpdate( sql ); } catch (java.sql.SQLException e) { throw new ServletException(e); } } // end doPost private static String doSomething(String param) throws ServletException, IOException { String bar; // Simple ? condition that assigns constant to bar on true condition int i = 106; bar = (7*18) + i > 200 ? "This_should_always_happen" : param; return bar; } }
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest19759.java
Java
gpl-2.0
2,328
/* Theme Name: Twenty Twelve Theme URI: http://wordpress.org/themes/twentytwelve Author: the WordPress team Author URI: http://wordpress.org/ Description: The 2012 theme for WordPress is a fully responsive theme that looks great on any device. Features include a front page template with its own widgets, an optional display font, styling for post formats on both index and single views, and an optional no-sidebar page template. Make it yours with a custom menu, header image, and background. Version: 1.4 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: light, gray, white, one-column, two-columns, right-sidebar, fluid-layout, responsive-layout, custom-background, custom-header, custom-menu, editor-style, featured-images, flexible-header, full-width-template, microformats, post-formats, rtl-language-support, sticky-post, theme-options, translation-ready Text Domain: twentytwelve This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others. */ /* =Notes -------------------------------------------------------------- This stylesheet uses rem values with a pixel fallback. The rem values (and line heights) are calculated using two variables: $rembase: 14; $line-height: 24; ---------- Examples * Use a pixel value with a rem fallback for font-size, padding, margins, etc. padding: 5px 0; padding: 0.357142857rem 0; (5 / $rembase) * Set a font-size and then set a line-height based on the font-size font-size: 16px font-size: 1.142857143rem; (16 / $rembase) line-height: 1.5; ($line-height / 16) ---------- Vertical spacing Vertical spacing between most elements should use 24px or 48px to maintain vertical rhythm: .my-new-div { margin: 24px 0; margin: 1.714285714rem 0; ( 24 / $rembase ) } ---------- Further reading http://snook.ca/archives/html_and_css/font-size-with-rem http://blog.typekit.com/2011/11/09/type-study-sizing-the-legible-letter/ /* =Reset -------------------------------------------------------------- */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; vertical-align: baseline; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } caption, th, td { font-weight: normal; text-align: left; } h1, h2, h3, h4, h5, h6 { clear: both; } html { overflow-y: scroll; font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } a:focus { outline: thin dotted; } article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; } audio, canvas, video { display: inline-block; } audio:not([controls]) { display: none; } del { color: #333; } ins { background: #fff9c0; text-decoration: none; } hr { background-color: #ccc; border: 0; height: 1px; margin: 24px; margin-bottom: 1.714285714rem; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } small { font-size: smaller; } img { border: 0; -ms-interpolation-mode: bicubic; } /* Clearing floats */ .clear:after, .wrapper:after, .format-status .entry-header:after { clear: both; } .clear:before, .clear:after, .wrapper:before, .wrapper:after, .format-status .entry-header:before, .format-status .entry-header:after { display: table; content: ""; } /* =Repeatable patterns -------------------------------------------------------------- */ /* Small headers */ .archive-title, .page-title, .widget-title, .entry-content th, .comment-content th { font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; font-weight: bold; text-transform: uppercase; color: #636363; } /* Shared Post Format styling */ article.format-quote footer.entry-meta, article.format-link footer.entry-meta, article.format-status footer.entry-meta { font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; } /* Form fields, general styles first */ button, input, select, textarea { border: 1px solid #ccc; border-radius: 3px; font-family: inherit; padding: 6px; padding: 0.428571429rem; } button, input { line-height: normal; } textarea { font-size: 100%; overflow: auto; vertical-align: top; } /* Reset non-text input types */ input[type="checkbox"], input[type="radio"], input[type="file"], input[type="hidden"], input[type="image"], input[type="color"] { border: 0; border-radius: 0; padding: 0; } /* Buttons */ .menu-toggle, input[type="submit"], input[type="button"], input[type="reset"], article.post-password-required input[type=submit], .bypostauthor cite span { padding: 6px 10px; padding: 0.428571429rem 0.714285714rem; font-size: 11px; font-size: 0.785714286rem; line-height: 1.428571429; font-weight: normal; color: #7c7c7c; background-color: #e6e6e6; background-repeat: repeat-x; background-image: -moz-linear-gradient(top, #f4f4f4, #e6e6e6); background-image: -ms-linear-gradient(top, #f4f4f4, #e6e6e6); background-image: -webkit-linear-gradient(top, #f4f4f4, #e6e6e6); background-image: -o-linear-gradient(top, #f4f4f4, #e6e6e6); background-image: linear-gradient(top, #f4f4f4, #e6e6e6); border: 1px solid #d2d2d2; border-radius: 3px; box-shadow: 0 1px 2px rgba(64, 64, 64, 0.1); } .menu-toggle, button, input[type="submit"], input[type="button"], input[type="reset"] { cursor: pointer; } button[disabled], input[disabled] { cursor: default; } .menu-toggle:hover, button:hover, input[type="submit"]:hover, input[type="button"]:hover, input[type="reset"]:hover, article.post-password-required input[type=submit]:hover { color: #5e5e5e; background-color: #ebebeb; background-repeat: repeat-x; background-image: -moz-linear-gradient(top, #f9f9f9, #ebebeb); background-image: -ms-linear-gradient(top, #f9f9f9, #ebebeb); background-image: -webkit-linear-gradient(top, #f9f9f9, #ebebeb); background-image: -o-linear-gradient(top, #f9f9f9, #ebebeb); background-image: linear-gradient(top, #f9f9f9, #ebebeb); } .menu-toggle:active, .menu-toggle.toggled-on, button:active, input[type="submit"]:active, input[type="button"]:active, input[type="reset"]:active { color: #757575; background-color: #e1e1e1; background-repeat: repeat-x; background-image: -moz-linear-gradient(top, #ebebeb, #e1e1e1); background-image: -ms-linear-gradient(top, #ebebeb, #e1e1e1); background-image: -webkit-linear-gradient(top, #ebebeb, #e1e1e1); background-image: -o-linear-gradient(top, #ebebeb, #e1e1e1); background-image: linear-gradient(top, #ebebeb, #e1e1e1); box-shadow: inset 0 0 8px 2px #c6c6c6, 0 1px 0 0 #f4f4f4; border-color: transparent; } .bypostauthor cite span { color: #fff; background-color: #21759b; background-image: none; border: 1px solid #1f6f93; border-radius: 2px; box-shadow: none; padding: 0; } /* Responsive images */ .entry-content img, .comment-content img, .widget img { max-width: 100%; /* Fluid images for posts, comments, and widgets */ } img[class*="align"], img[class*="wp-image-"], img[class*="attachment-"] { height: auto; /* Make sure images with WordPress-added height and width attributes are scaled correctly */ } img.size-full, img.size-large, img.header-image, img.wp-post-image { max-width: 100%; height: auto; /* Make sure images with WordPress-added height and width attributes are scaled correctly */ } /* Make sure videos and embeds fit their containers */ embed, iframe, object, video { max-width: 100%; } .entry-content .twitter-tweet-rendered { max-width: 100% !important; /* Override the Twitter embed fixed width */ } /* Images */ .alignleft { float: left; } .alignright { float: right; } .aligncenter { display: block; margin-left: auto; margin-right: auto; } .entry-content img, .comment-content img, .widget img, img.header-image, .author-avatar img, img.wp-post-image { /* Add fancy borders to all WordPress-added images but not things like badges and icons and the like */ border-radius: 3px; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); } .wp-caption { max-width: 100%; /* Keep wide captions from overflowing their container. */ padding: 4px; } .wp-caption .wp-caption-text, .gallery-caption, .entry-caption { font-style: italic; font-size: 12px; font-size: 0.857142857rem; line-height: 2; color: #757575; } img.wp-smiley, .rsswidget img { border: 0; border-radius: 0; box-shadow: none; margin-bottom: 0; margin-top: 0; padding: 0; } .entry-content dl.gallery-item { margin: 0; } .gallery-item a, .gallery-caption { width: 90%; } .gallery-item a { display: block; } .gallery-caption a { display: inline; } .gallery-columns-1 .gallery-item a { max-width: 100%; width: auto; } .gallery .gallery-icon img { height: auto; max-width: 90%; padding: 5%; } .gallery-columns-1 .gallery-icon img { padding: 3%; } /* Navigation */ .site-content nav { clear: both; line-height: 2; overflow: hidden; } #nav-above { padding: 24px 0; padding: 1.714285714rem 0; } #nav-above { display: none; } .paged #nav-above { display: block; } .nav-previous, .previous-image { float: left; width: 50%; } .nav-next, .next-image { float: right; text-align: right; width: 50%; } .nav-single + .comments-area, #comment-nav-above { margin: 48px 0; margin: 3.428571429rem 0; } /* Author profiles */ .author .archive-header { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .author-info { border-top: 1px solid #ededed; margin: 24px 0; margin: 1.714285714rem 0; padding-top: 24px; padding-top: 1.714285714rem; overflow: hidden; } .author-description p { color: #757575; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } .author.archive .author-info { border-top: 0; margin: 0 0 48px; margin: 0 0 3.428571429rem; } .author.archive .author-avatar { margin-top: 0; } /* =Basic structure -------------------------------------------------------------- */ /* Body, links, basics */ html { font-size: 87.5%; } body { font-size: 14px; font-size: 1rem; font-family: Helvetica, Arial, sans-serif; text-rendering: optimizeLegibility; color: #444; } body.custom-font-enabled { font-family: "Open Sans", Helvetica, Arial, sans-serif; } a { outline: none; color: #21759b; } a:hover { color: #0f3647; } /* Assistive text */ .assistive-text, .site .screen-reader-text { position: absolute !important; clip: rect(1px, 1px, 1px, 1px); } .main-navigation .assistive-text:focus { background: #fff; border: 2px solid #333; border-radius: 3px; clip: auto !important; color: #000; display: block; font-size: 12px; padding: 12px; position: absolute; top: 5px; left: 5px; z-index: 100000; /* Above WP toolbar */ } /* Page structure */ .site { padding: 0 24px; padding: 0 1.714285714rem; background-color: #fff; } .site-content { margin: 24px 0 0; margin: 1.714285714rem 0 0; } .widget-area { margin: 24px 0 0; margin: 1.714285714rem 0 0; } /* Header */ .site-header { padding: 24px 0; padding: 1.714285714rem 0; } .site-header h1, .site-header h2 { text-align: center; } .site-header h1 a, .site-header h2 a { color: #515151; display: inline-block; text-decoration: none; } .site-header h1 a:hover, .site-header h2 a:hover { color: #21759b; } .site-header h1 { font-size: 24px; font-size: 1.714285714rem; line-height: 1.285714286; margin-bottom: 14px; margin-bottom: 1rem; } .site-header h2 { font-weight: normal; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #757575; } .header-image { margin-top: 24px; margin-top: 1.714285714rem; } /* Navigation Menu */ .main-navigation { margin-top: 24px; margin-top: 1.714285714rem; text-align: center; } .main-navigation li { margin-top: 24px; margin-top: 1.714285714rem; font-size: 12px; font-size: 0.857142857rem; line-height: 1.42857143; } .main-navigation a { color: #5e5e5e; } .main-navigation a:hover, .main-navigation a:focus { color: #21759b; } .main-navigation ul.nav-menu, .main-navigation div.nav-menu > ul { display: none; } .main-navigation ul.nav-menu.toggled-on, .menu-toggle { display: inline-block; } /* Banner */ section[role="banner"] { margin-bottom: 48px; margin-bottom: 3.428571429rem; } /* Sidebar */ .widget-area .widget { -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; margin-bottom: 48px; margin-bottom: 3.428571429rem; word-wrap: break-word; } .widget-area .widget h3 { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .widget-area .widget p, .widget-area .widget li, .widget-area .widget .textwidget { font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } .widget-area .widget p { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .widget-area .textwidget ul { list-style: disc outside; margin: 0 0 24px; margin: 0 0 1.714285714rem; } .widget-area .textwidget li { margin-left: 36px; margin-left: 2.571428571rem; } .widget-area .widget a { color: #757575; } .widget-area .widget a:hover { color: #21759b; } .widget-area .widget a:visited { color: #9f9f9f; } .widget-area #s { width: 53.66666666666%; /* define a width to avoid dropping a wider submit button */ } /* Footer */ footer[role="contentinfo"] { border-top: 1px solid #ededed; clear: both; font-size: 12px; font-size: 0.857142857rem; line-height: 2; max-width: 960px; max-width: 68.571428571rem; margin-top: 24px; margin-top: 1.714285714rem; margin-left: auto; margin-right: auto; padding: 24px 0; padding: 1.714285714rem 0; } footer[role="contentinfo"] a { color: #686868; } footer[role="contentinfo"] a:hover { color: #21759b; } /* =Main content and comment content -------------------------------------------------------------- */ .entry-meta { clear: both; } .entry-header { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .entry-header img.wp-post-image { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .entry-header .entry-title { font-size: 20px; font-size: 1.428571429rem; line-height: 1.2; font-weight: normal; } .entry-header .entry-title a { text-decoration: none; } .entry-header .entry-format { margin-top: 24px; margin-top: 1.714285714rem; font-weight: normal; } .entry-header .comments-link { margin-top: 24px; margin-top: 1.714285714rem; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #757575; } .comments-link a, .entry-meta a { color: #757575; } .comments-link a:hover, .entry-meta a:hover { color: #21759b; } article.sticky .featured-post { border-top: 4px double #ededed; border-bottom: 4px double #ededed; color: #757575; font-size: 13px; font-size: 0.928571429rem; line-height: 3.692307692; margin-bottom: 24px; margin-bottom: 1.714285714rem; text-align: center; } .entry-content, .entry-summary, .mu_register { line-height: 1.714285714; } .entry-content h1, .comment-content h1, .entry-content h2, .comment-content h2, .entry-content h3, .comment-content h3, .entry-content h4, .comment-content h4, .entry-content h5, .comment-content h5, .entry-content h6, .comment-content h6 { margin: 24px 0; margin: 1.714285714rem 0; line-height: 1.714285714; } .entry-content h1, .comment-content h1 { font-size: 21px; font-size: 1.5rem; line-height: 1.5; } .entry-content h2, .comment-content h2, .mu_register h2 { font-size: 18px; font-size: 1.285714286rem; line-height: 1.6; } .entry-content h3, .comment-content h3 { font-size: 16px; font-size: 1.142857143rem; line-height: 1.846153846; } .entry-content h4, .comment-content h4 { font-size: 14px; font-size: 1rem; line-height: 1.846153846; } .entry-content h5, .comment-content h5 { font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } .entry-content h6, .comment-content h6 { font-size: 12px; font-size: 0.857142857rem; line-height: 1.846153846; } .entry-content p, .entry-summary p, .comment-content p, .mu_register p { margin: 0 0 24px; margin: 0 0 1.714285714rem; line-height: 1.714285714; } .entry-content a:visited, .comment-content a:visited { color: #9f9f9f; } .entry-content ol, .comment-content ol, .entry-content ul, .comment-content ul, .mu_register ul { margin: 0 0 24px; margin: 0 0 1.714285714rem; line-height: 1.714285714; } .entry-content ul ul, .comment-content ul ul, .entry-content ol ol, .comment-content ol ol, .entry-content ul ol, .comment-content ul ol, .entry-content ol ul, .comment-content ol ul { margin-bottom: 0; } .entry-content ul, .comment-content ul, .mu_register ul { list-style: disc outside; } .entry-content ol, .comment-content ol { list-style: decimal outside; } .entry-content li, .comment-content li, .mu_register li { margin: 0 0 0 36px; margin: 0 0 0 2.571428571rem; } .entry-content blockquote, .comment-content blockquote { margin-bottom: 24px; margin-bottom: 1.714285714rem; padding: 24px; padding: 1.714285714rem; font-style: italic; } .entry-content blockquote p:last-child, .comment-content blockquote p:last-child { margin-bottom: 0; } .entry-content code, .comment-content code { font-family: Consolas, Monaco, Lucida Console, monospace; font-size: 12px; font-size: 0.857142857rem; line-height: 2; } .entry-content pre, .comment-content pre { border: 1px solid #ededed; color: #666; font-family: Consolas, Monaco, Lucida Console, monospace; font-size: 12px; font-size: 0.857142857rem; line-height: 1.714285714; margin: 24px 0; margin: 1.714285714rem 0; overflow: auto; padding: 24px; padding: 1.714285714rem; } .entry-content pre code, .comment-content pre code { display: block; } .entry-content abbr, .comment-content abbr, .entry-content dfn, .comment-content dfn, .entry-content acronym, .comment-content acronym { border-bottom: 1px dotted #666; cursor: help; } .entry-content address, .comment-content address { display: block; line-height: 1.714285714; margin: 0 0 24px; margin: 0 0 1.714285714rem; } img.alignleft, .wp-caption.alignleft { margin: 12px 24px 12px 0; margin: 0.857142857rem 1.714285714rem 0.857142857rem 0; } img.alignright, .wp-caption.alignright { margin: 12px 0 12px 24px; margin: 0.857142857rem 0 0.857142857rem 1.714285714rem; } img.aligncenter, .wp-caption.aligncenter { clear: both; margin-top: 12px; margin-top: 0.857142857rem; margin-bottom: 12px; margin-bottom: 0.857142857rem; } .entry-content embed, .entry-content iframe, .entry-content object, .entry-content video { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .entry-content dl, .comment-content dl { margin: 0 24px; margin: 0 1.714285714rem; } .entry-content dt, .comment-content dt { font-weight: bold; line-height: 1.714285714; } .entry-content dd, .comment-content dd { line-height: 1.714285714; margin-bottom: 24px; margin-bottom: 1.714285714rem; } .entry-content table, .comment-content table { border-bottom: 1px solid #ededed; color: #757575; font-size: 12px; font-size: 0.857142857rem; line-height: 2; margin: 0 0 24px; margin: 0 0 1.714285714rem; width: 100%; } .entry-content table caption, .comment-content table caption { font-size: 16px; font-size: 1.142857143rem; margin: 24px 0; margin: 1.714285714rem 0; } .entry-content td, .comment-content td { border-top: 1px solid #ededed; padding: 6px 10px 6px 0; } .site-content article { border-bottom: 4px double #ededed; margin-bottom: 72px; margin-bottom: 5.142857143rem; padding-bottom: 24px; padding-bottom: 1.714285714rem; word-wrap: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; } .page-links { clear: both; line-height: 1.714285714; } footer.entry-meta { margin-top: 24px; margin-top: 1.714285714rem; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #757575; } .single-author .entry-meta .by-author { display: none; } .mu_register h2 { color: #757575; font-weight: normal; } /* =Archives -------------------------------------------------------------- */ .archive-header, .page-header { margin-bottom: 48px; margin-bottom: 3.428571429rem; padding-bottom: 22px; padding-bottom: 1.571428571rem; border-bottom: 1px solid #ededed; } .archive-meta { color: #757575; font-size: 12px; font-size: 0.857142857rem; line-height: 2; margin-top: 22px; margin-top: 1.571428571rem; } /* =Single audio/video attachment view -------------------------------------------------------------- */ .attachment .entry-content .mejs-audio { max-width: 400px; } .attachment .entry-content .mejs-container { margin-bottom: 24px; } /* =Single image attachment view -------------------------------------------------------------- */ .article.attachment { overflow: hidden; } .image-attachment div.attachment { text-align: center; } .image-attachment div.attachment p { text-align: center; } .image-attachment div.attachment img { display: block; height: auto; margin: 0 auto; max-width: 100%; } .image-attachment .entry-caption { margin-top: 8px; margin-top: 0.571428571rem; } /* =Aside post format -------------------------------------------------------------- */ article.format-aside h1 { margin-bottom: 24px; margin-bottom: 1.714285714rem; } article.format-aside h1 a { text-decoration: none; color: #4d525a; } article.format-aside h1 a:hover { color: #2e3542; } article.format-aside .aside { padding: 24px 24px 0; padding: 1.714285714rem; background: #d2e0f9; border-left: 22px solid #a8bfe8; } article.format-aside p { font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #4a5466; } article.format-aside blockquote:last-child, article.format-aside p:last-child { margin-bottom: 0; } /* =Post formats -------------------------------------------------------------- */ /* Image posts */ article.format-image footer h1 { font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; font-weight: normal; } article.format-image footer h2 { font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; } article.format-image footer a h2 { font-weight: normal; } /* Link posts */ article.format-link header { padding: 0 10px; padding: 0 0.714285714rem; float: right; font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; font-weight: bold; font-style: italic; text-transform: uppercase; color: #848484; background-color: #ebebeb; border-radius: 3px; } article.format-link .entry-content { max-width: 80%; float: left; } article.format-link .entry-content a { font-size: 22px; font-size: 1.571428571rem; line-height: 1.090909091; text-decoration: none; } /* Quote posts */ article.format-quote .entry-content p { margin: 0; padding-bottom: 24px; padding-bottom: 1.714285714rem; } article.format-quote .entry-content blockquote { display: block; padding: 24px 24px 0; padding: 1.714285714rem 1.714285714rem 0; font-size: 15px; font-size: 1.071428571rem; line-height: 1.6; font-style: normal; color: #6a6a6a; background: #efefef; } /* Status posts */ .format-status .entry-header { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .format-status .entry-header header { display: inline-block; } .format-status .entry-header h1 { font-size: 15px; font-size: 1.071428571rem; font-weight: normal; line-height: 1.6; margin: 0; } .format-status .entry-header h2 { font-size: 12px; font-size: 0.857142857rem; font-weight: normal; line-height: 2; margin: 0; } .format-status .entry-header header a { color: #757575; } .format-status .entry-header header a:hover { color: #21759b; } .format-status .entry-header img { float: left; margin-right: 21px; margin-right: 1.5rem; } /* =Comments -------------------------------------------------------------- */ .comments-title { margin-bottom: 48px; margin-bottom: 3.428571429rem; font-size: 16px; font-size: 1.142857143rem; line-height: 1.5; font-weight: normal; } .comments-area article { margin: 24px 0; margin: 1.714285714rem 0; } .comments-area article header { margin: 0 0 48px; margin: 0 0 3.428571429rem; overflow: hidden; position: relative; } .comments-area article header img { float: left; padding: 0; line-height: 0; } .comments-area article header cite, .comments-area article header time { display: block; margin-left: 85px; margin-left: 6.071428571rem; } .comments-area article header cite { font-style: normal; font-size: 15px; font-size: 1.071428571rem; line-height: 1.42857143; } .comments-area cite b { font-weight: normal; } .comments-area article header time { line-height: 1.714285714; text-decoration: none; font-size: 12px; font-size: 0.857142857rem; color: #5e5e5e; } .comments-area article header a { text-decoration: none; color: #5e5e5e; } .comments-area article header a:hover { color: #21759b; } .comments-area article header cite a { color: #444; } .comments-area article header cite a:hover { text-decoration: underline; } .comments-area article header h4 { position: absolute; top: 0; right: 0; padding: 6px 12px; padding: 0.428571429rem 0.857142857rem; font-size: 12px; font-size: 0.857142857rem; font-weight: normal; color: #fff; background-color: #0088d0; background-repeat: repeat-x; background-image: -moz-linear-gradient(top, #009cee, #0088d0); background-image: -ms-linear-gradient(top, #009cee, #0088d0); background-image: -webkit-linear-gradient(top, #009cee, #0088d0); background-image: -o-linear-gradient(top, #009cee, #0088d0); background-image: linear-gradient(top, #009cee, #0088d0); border-radius: 3px; border: 1px solid #007cbd; } .comments-area .bypostauthor cite span { position: absolute; margin-left: 5px; margin-left: 0.357142857rem; padding: 2px 5px; padding: 0.142857143rem 0.357142857rem; font-size: 10px; font-size: 0.714285714rem; } .comments-area .bypostauthor cite b { font-weight: bold; } a.comment-reply-link, a.comment-edit-link { color: #686868; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } a.comment-reply-link:hover, a.comment-edit-link:hover { color: #21759b; } .commentlist .pingback { line-height: 1.714285714; margin-bottom: 24px; margin-bottom: 1.714285714rem; } /* Comment form */ #respond { margin-top: 48px; margin-top: 3.428571429rem; } #respond h3#reply-title { font-size: 16px; font-size: 1.142857143rem; line-height: 1.5; } #respond h3#reply-title #cancel-comment-reply-link { margin-left: 10px; margin-left: 0.714285714rem; font-weight: normal; font-size: 12px; font-size: 0.857142857rem; } #respond form { margin: 24px 0; margin: 1.714285714rem 0; } #respond form p { margin: 11px 0; margin: 0.785714286rem 0; } #respond form p.logged-in-as { margin-bottom: 24px; margin-bottom: 1.714285714rem; } #respond form label { display: block; line-height: 1.714285714; } #respond form input[type="text"], #respond form textarea { -moz-box-sizing: border-box; box-sizing: border-box; font-size: 12px; font-size: 0.857142857rem; line-height: 1.714285714; padding: 10px; padding: 0.714285714rem; width: 100%; } #respond form p.form-allowed-tags { margin: 0; font-size: 12px; font-size: 0.857142857rem; line-height: 2; color: #5e5e5e; } .required { color: red; } /* =Front page template -------------------------------------------------------------- */ .entry-page-image { margin-bottom: 14px; margin-bottom: 1rem; } .template-front-page .site-content article { border: 0; margin-bottom: 0; } .template-front-page .widget-area { clear: both; float: none; width: auto; padding-top: 24px; padding-top: 1.714285714rem; border-top: 1px solid #ededed; } .template-front-page .widget-area .widget li { margin: 8px 0 0; margin: 0.571428571rem 0 0; font-size: 13px; font-size: 0.928571429rem; line-height: 1.714285714; list-style-type: square; list-style-position: inside; } .template-front-page .widget-area .widget li a { color: #757575; } .template-front-page .widget-area .widget li a:hover { color: #21759b; } .template-front-page .widget-area .widget_text img { float: left; margin: 8px 24px 8px 0; margin: 0.571428571rem 1.714285714rem 0.571428571rem 0; } /* =Widgets -------------------------------------------------------------- */ .widget-area .widget ul ul { margin-left: 12px; margin-left: 0.857142857rem; } .widget_rss li { margin: 12px 0; margin: 0.857142857rem 0; } .widget_recent_entries .post-date, .widget_rss .rss-date { color: #aaa; font-size: 11px; font-size: 0.785714286rem; margin-left: 12px; margin-left: 0.857142857rem; } #wp-calendar { margin: 0; width: 100%; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #686868; } #wp-calendar th, #wp-calendar td, #wp-calendar caption { text-align: left; } #wp-calendar #next { padding-right: 24px; padding-right: 1.714285714rem; text-align: right; } .widget_search label { display: block; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } .widget_twitter li { list-style-type: none; } .widget_twitter .timesince { display: block; text-align: right; } /* =Plugins ----------------------------------------------- */ img#wpstats { display: block; margin: 0 auto 24px; margin: 0 auto 1.714285714rem; } /* =Media queries -------------------------------------------------------------- */ /* Does the same thing as <meta name="viewport" content="width=device-width">, * but in the future W3C standard way. -ms- prefix is required for IE10+ to * render responsive styling in Windows 8 "snapped" views; IE10+ does not honor * the meta tag. See http://core.trac.wordpress.org/ticket/25888. */ @-ms-viewport { width: device-width; } @viewport { width: device-width; } /* Minimum width of 600 pixels. */ @media screen and (min-width: 600px) { .author-avatar { float: left; margin-top: 8px; margin-top: 0.571428571rem; } .author-description { float: right; width: 80%; } .site { margin: 0 auto; max-width: 960px; max-width: 68.571428571rem; overflow: hidden; } .site-content { float: left; width: 65.104166667%; } body.template-front-page .site-content, body.attachment .site-content, body.full-width .site-content { width: 100%; } .widget-area { float: right; width: 26.041666667%; } .site-header h1, .site-header h2 { text-align: left; } .site-header h1 { font-size: 26px; font-size: 1.857142857rem; line-height: 1.846153846; margin-bottom: 0; } .main-navigation ul.nav-menu, .main-navigation div.nav-menu > ul { border-bottom: 1px solid #ededed; border-top: 1px solid #ededed; display: inline-block !important; text-align: left; width: 100%; } .main-navigation ul { margin: 0; text-indent: 0; } .main-navigation li a, .main-navigation li { display: inline-block; text-decoration: none; } .main-navigation li a { border-bottom: 0; color: #6a6a6a; line-height: 3.692307692; text-transform: uppercase; white-space: nowrap; } .main-navigation li a:hover, .main-navigation li a:focus { color: #000; } .main-navigation li { margin: 0 40px 0 0; margin: 0 2.857142857rem 0 0; position: relative; } .main-navigation li ul { margin: 0; padding: 0; position: absolute; top: 100%; z-index: 1; height: 1px; width: 1px; overflow: hidden; clip: rect(1px, 1px, 1px, 1px); } .main-navigation li ul ul { top: 0; left: 100%; } .main-navigation ul li:hover > ul, .main-navigation ul li:focus > ul, .main-navigation .focus > ul { border-left: 0; clip: inherit; overflow: inherit; height: inherit; width: inherit; } .main-navigation li ul li a { background: #efefef; border-bottom: 1px solid #ededed; display: block; font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; padding: 8px 10px; padding: 0.571428571rem 0.714285714rem; width: 180px; width: 12.85714286rem; white-space: normal; } .main-navigation li ul li a:hover, .main-navigation li ul li a:focus { background: #e3e3e3; color: #444; } .main-navigation .current-menu-item > a, .main-navigation .current-menu-ancestor > a, .main-navigation .current_page_item > a, .main-navigation .current_page_ancestor > a { color: #636363; font-weight: bold; } .menu-toggle { display: none; } .entry-header .entry-title { font-size: 22px; font-size: 1.571428571rem; } #respond form input[type="text"] { width: 46.333333333%; } #respond form textarea.blog-textarea { width: 79.666666667%; } .template-front-page .site-content, .template-front-page article { overflow: hidden; } .template-front-page.has-post-thumbnail article { float: left; width: 47.916666667%; } .entry-page-image { float: right; margin-bottom: 0; width: 47.916666667%; } .template-front-page .widget-area .widget, .template-front-page.two-sidebars .widget-area .front-widgets { float: left; width: 51.875%; margin-bottom: 24px; margin-bottom: 1.714285714rem; } .template-front-page .widget-area .widget:nth-child(odd) { clear: right; } .template-front-page .widget-area .widget:nth-child(even), .template-front-page.two-sidebars .widget-area .front-widgets + .front-widgets { float: right; width: 39.0625%; margin: 0 0 24px; margin: 0 0 1.714285714rem; } .template-front-page.two-sidebars .widget, .template-front-page.two-sidebars .widget:nth-child(even) { float: none; width: auto; } .commentlist .children { margin-left: 48px; margin-left: 3.428571429rem; } } /* Minimum width of 960 pixels. */ @media screen and (min-width: 960px) { body { background-color: #e6e6e6; } body .site { padding: 0 40px; padding: 0 2.857142857rem; margin-top: 48px; margin-top: 3.428571429rem; margin-bottom: 48px; margin-bottom: 3.428571429rem; box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3); } body.custom-background-empty { background-color: #fff; } body.custom-background-empty .site, body.custom-background-white .site { padding: 0; margin-top: 0; margin-bottom: 0; box-shadow: none; } } /* =Print ----------------------------------------------- */ @media print { body { background: none !important; color: #000; font-size: 10pt; } footer a[rel=bookmark]:link:after, footer a[rel=bookmark]:visited:after { content: " [" attr(href) "] "; /* Show URLs */ } a { text-decoration: none; } .entry-content img, .comment-content img, .author-avatar img, img.wp-post-image { border-radius: 0; box-shadow: none; } .site { clear: both !important; display: block !important; float: none !important; max-width: 100%; position: relative !important; } .site-header { margin-bottom: 72px; margin-bottom: 5.142857143rem; text-align: left; } .site-header h1 { font-size: 21pt; line-height: 1; text-align: left; } .site-header h2 { color: #000; font-size: 10pt; text-align: left; } .site-header h1 a, .site-header h2 a { color: #000; } .author-avatar, #colophon, #respond, .commentlist .comment-edit-link, .commentlist .reply, .entry-header .comments-link, .entry-meta .edit-link a, .page-link, .site-content nav, .widget-area, img.header-image, .main-navigation { display: none; } .wrapper { border-top: none; box-shadow: none; } .site-content { margin: 0; width: auto; } .entry-header .entry-title, .entry-title { font-size: 21pt; } footer.entry-meta, footer.entry-meta a { color: #444; font-size: 10pt; } .author-description { float: none; width: auto; } /* Comments */ .commentlist > li.comment { background: none; position: relative; width: auto; } .commentlist .avatar { height: 39px; left: 2.2em; top: 2.2em; width: 39px; } .comments-area article header cite, .comments-area article header time { margin-left: 50px; margin-left: 3.57142857rem; } }
suzybates/LeeWebsiteRedesign
wp-content/themes/twentytwelve/style.css
CSS
gpl-2.0
36,192
<?php /** * @package AkeebaBackup * @copyright Copyright (c)2009-2016 Nicholas K. Dionysopoulos * @license GNU General Public License version 3, or later * * @since 1.3 * * The main page of the Akeeba Backup component is where all the fun takes place :) */ /** @var $this AkeebaViewCpanel */ // Protect from unauthorized access defined('_JEXEC') or die(); use Akeeba\Engine\Platform; use Akeeba\Engine\Factory; use Akeeba\Engine\Util\Comconfig; Platform::getInstance()->load_version_defines(); $lang = JFactory::getLanguage(); $icons_root = JUri::base().'components/com_akeeba/assets/images/'; JHtml::_('behavior.modal'); JHtml::_('formbehavior.chosen'); $script = <<<JS ;// This comment is intentionally put here to prevent badly written plugins from causing a Javascript error // due to missing trailing semicolon and/or newline in their code. (function($){ if ({$this->desktop_notifications}) { akeeba.System.notification.askPermission(); } $(document).ready(function(){ $('#btnchangelog').click(showChangelog); }); function showChangelog() { var akeebaChangelogElement = $('#akeeba-changelog').clone().appendTo('body').attr('id', 'akeeba-changelog-clone'); SqueezeBox.fromElement( document.getElementById('akeeba-changelog-clone'), { handler: 'adopt', size: { x: 550, y: 500 } } ); } })(akeeba.jQuery); JS; JFactory::getDocument()->addScriptDeclaration($script,'text/javascript'); ?> <?php // Configuration Wizard prompt if (!\Akeeba\Engine\Factory::getConfiguration()->get('akeeba.flag.confwiz', 0)) { echo $this->loadAnyTemplate('admin:com_akeeba/config/confwiz_modal'); } ?> <?php if(!$this->checkMbstring):?> <div class="alert alert-danger"> <?php echo JText::sprintf('COM_AKEEBA_CPANL_ERR_MBSTRING', PHP_VERSION)?> </div> <?php endif;?> <?php if (!empty($this->frontEndSecretWordIssue)): ?> <div class="alert alert-danger"> <h3><?php echo JText::_('COM_AKEEBA_CPANEL_ERR_FESECRETWORD_HEADER'); ?></h3> <p><?php echo JText::_('COM_AKEEBA_CPANEL_ERR_FESECRETWORD_INTRO'); ?></p> <p><?php echo $this->frontEndSecretWordIssue ?></p> <p> <?php echo JText::_('COM_AKEEBA_CPANEL_ERR_FESECRETWORD_WHATTODO_JOOMLA'); ?> <?php echo JText::sprintf('COM_AKEEBA_CPANEL_ERR_FESECRETWORD_WHATTODO_COMMON', $this->newSecretWord); ?> </p> <p> <a class="btn btn-success btn-large" href="index.php?option=com_akeeba&view=cpanel&task=resetSecretWord&<?php echo JFactory::getSession()->getToken() ?>=1"> <span class="icon icon-white icon-refresh"></span> <?php echo JText::_('COM_AKEEBA_CPANEL_BTN_FESECRETWORD_RESET'); ?> </a> </p> </div> <?php endif; ?> <?php // Obsolete PHP version check if (version_compare(PHP_VERSION, '5.3.3', 'lt')): JLoader::import('joomla.utilities.date'); $akeebaCommonDatePHP = new JDate('2014-08-14 00:00:00', 'GMT'); $akeebaCommonDateObsolescence = new JDate('2015-05-14 00:00:00', 'GMT'); ?> <div id="phpVersionCheck" class="alert alert-warning"> <h3><?php echo JText::_('AKEEBA_COMMON_PHPVERSIONTOOOLD_WARNING_TITLE'); ?></h3> <p> <?php echo JText::sprintf( 'AKEEBA_COMMON_PHPVERSIONTOOOLD_WARNING_BODY', PHP_VERSION, $akeebaCommonDatePHP->format(JText::_('DATE_FORMAT_LC1')), $akeebaCommonDateObsolescence->format(JText::_('DATE_FORMAT_LC1')), '5.5' ); ?> </p> </div> <?php endif; ?> <?php if (!$this->fixedpermissions): ?> <div id="notfixedperms" class="alert alert-error"> <h3><?php echo JText::_('AKEEBA_CPANEL_WARN_WARNING') ?></h3> <p><?php echo JText::_('AKEEBA_CPANEL_WARN_PERMS_L1') ?></p> <p><?php echo JText::_('AKEEBA_CPANEL_WARN_PERMS_L2') ?></p> <ol> <li><?php echo JText::_('AKEEBA_CPANEL_WARN_PERMS_L3A') ?></li> <li><?php echo JText::_('AKEEBA_CPANEL_WARN_PERMS_L3B') ?></li> </ol> <p><?php echo JText::_('AKEEBA_CPANEL_WARN_PERMS_L4') ?></p> </div> <?php endif; ?> <?php if(!version_compare(PHP_VERSION, '5.3.0', 'ge') && Comconfig::getValue('displayphpwarning', 1)): ?> <div class="alert"> <a class="close" data-dismiss="alert" href="#">×</a> <p><strong><?php echo JText::_('COM_AKEEBA_CONFIG_LBL_OUTDATEDPHP_HEADER') ?></strong><br/> <?php echo JText::sprintf('COM_AKEEBA_CONFIG_LBL_OUTDATEDPHP_BODY', PHP_VERSION) ?> </p> <p> <a class="btn btn-small btn-primary" href="index.php?option=com_akeeba&view=cpanel&task=disablephpwarning&<?php echo JFactory::getSession()->getFormToken() ?>=1"> <?php echo JText::_('COM_AKEEBA_CONFIG_LBL_OUTDATEDPHP_BUTTON'); ?> </a> </p> </div> <?php endif; ?> <?php if($this->needsdlid): ?> <div class="alert alert-success"> <h3> <?php echo JText::_('COM_AKEEBA_CPANEL_MSG_MUSTENTERDLID') ?> </h3> <p> <?php echo JText::sprintf('COM_AKEEBA_LBL_CPANEL_NEEDSDLID','https://www.akeebabackup.com/instructions/1435-akeeba-backup-download-id.html'); ?> </p> <form name="dlidform" action="index.php" method="post" class="form-inline"> <input type="hidden" name="option" value="com_akeeba" /> <input type="hidden" name="view" value="cpanel" /> <input type="hidden" name="task" value="applydlid" /> <input type="hidden" name="<?php echo JFactory::getSession()->getFormToken()?>" value="1" /> <span> <?php echo JText::_('COM_AKEEBA_CPANEL_MSG_PASTEDLID') ?> </span> <input type="text" name="dlid" placeholder="<?php echo JText::_('CONFIG_DOWNLOADID_LABEL')?>" class="input-xlarge"> <button type="submit" class="btn btn-success"> <span class="icon icon-<?php echo version_compare(JVERSION, '3.0.0', 'ge') ? 'checkbox' : 'ok icon-white' ?>"></span> <?php echo JText::_('COM_AKEEBA_CPANEL_MSG_APPLYDLID') ?> </button> </form> </div> <?php elseif ($this->needscoredlidwarning): ?> <div class="alert alert-danger"> <?php echo JText::sprintf('COM_AKEEBA_LBL_CPANEL_NEEDSUPGRADE','https://www.akeebabackup.com/videos/1212-akeeba-backup-core/1617-abtc03-upgrade-core-professional.html'); ?> </div> <?php endif; ?> <div id="updateNotice"></div> <div id="cpanel" class="row-fluid"> <div class="span8"> <form action="index.php" method="post" name="adminForm" id="adminForm" class="akeeba-formstyle-reset form-inline"> <input type="hidden" name="option" value="com_akeeba" /> <input type="hidden" name="view" value="cpanel" /> <input type="hidden" name="task" value="switchprofile" /> <input type="hidden" name="<?php echo JFactory::getSession()->getFormToken()?>" value="1" /> <label> <?php echo JText::_('CPANEL_PROFILE_TITLE'); ?>: #<?php echo $this->profileid; ?> </label> <?php echo JHTML::_('select.genericlist', $this->profilelist, 'profileid', 'onchange="document.forms.adminForm.submit()" class="advancedSelect"', 'value', 'text', $this->profileid); ?> <button class="btn hidden-phone" onclick="this.form.submit(); return false;"> <span class="icon-retweet"></span> <?php echo JText::_('CPANEL_PROFILE_BUTTON'); ?> </button> </form> <?php if(!empty($this->quickIconProfiles)): $token = JFactory::getSession()->getToken(); ?> <h3><?php echo JText::_('COM_AKEEBA_CPANEL_HEADER_QUICKBACKUP'); ?></h3> <?php foreach($this->quickIconProfiles as $qiProfile): ?> <div class="icon"> <a href="index.php?option=com_akeeba&view=backup&autostart=1&profileid=<?php echo (int) $qiProfile->id ?>&<?php echo $token ?>=1"> <div class="ak-icon ak-icon-backup">&nbsp;</div> <span> <?php echo htmlentities($qiProfile->description) ?> </span> </a> </div> <?php endforeach; ?> <div class="ak_clr"></div> <?php endif; ?> <h3><?php echo JText::_('CPANEL_HEADER_BASICOPS'); ?></h3> <div class="icon"> <a href="index.php?option=com_akeeba&view=backup"> <div class="ak-icon ak-icon-backup">&nbsp;</div> <span><?php echo JText::_('BACKUP'); ?></span> </a> </div> <div class="icon"> <a href="index.php?option=com_akeeba&view=transfer"> <div class="ak-icon ak-icon-stw">&nbsp;</div> <span><?php echo JText::_('COM_AKEEBA_TRANSFER');?></span> </a> </div> <div class="icon"> <a href="index.php?option=com_akeeba&view=buadmin"> <div class="ak-icon ak-icon-manage">&nbsp;</div> <span><?php echo JText::_('BUADMIN'); ?></span> </a> </div> <div class="icon"> <a href="index.php?option=com_akeeba&view=config"> <div class="ak-icon ak-icon-configuration">&nbsp;</div> <span><?php echo JText::_('CONFIGURATION'); ?></span> </a> </div> <div class="icon"> <a href="index.php?option=com_akeeba&view=profiles"> <div class="ak-icon ak-icon-profiles">&nbsp;</div> <span><?php echo JText::_('PROFILES'); ?></span> </a> </div> <div class="ak_clr"></div> <h3><?php echo JText::_('COM_AKEEBA_CPANEL_HEADER_TROUBLESHOOTING'); ?></h3> <div class="icon"> <a href="index.php?option=com_akeeba&view=log"> <div class="ak-icon ak-icon-viewlog">&nbsp;</div> <span><?php echo JText::_('VIEWLOG'); ?></span> </a> </div> <?php if (AKEEBA_PRO): ?> <div class="icon"> <a href="index.php?option=com_akeeba&view=alices"> <div class="ak-icon ak-icon-viewlog">&nbsp;</div> <span><?php echo JText::_('AKEEBA_ALICE'); ?></span> </a> </div> <?php endif; ?> <div class="ak_clr"></div> <h3><?php echo JText::_('COM_AKEEBA_CPANEL_HEADER_ADVANCED'); ?></h3> <div class="icon"> <a href="index.php?option=com_akeeba&view=schedule"> <div class="ak-icon ak-icon-scheduling">&nbsp;</div> <span><?php echo JText::_('AKEEBA_SCHEDULE'); ?></span> </a> </div> <?php if (AKEEBA_PRO): ?> <div class="icon"> <a href="index.php?option=com_akeeba&view=discover"> <div class="ak-icon ak-icon-import">&nbsp;</div> <span><?php echo JText::_('DISCOVER'); ?></span> </a> </div> <div class="icon"> <a href="index.php?option=com_akeeba&view=s3import"> <div class="ak-icon ak-icon-s3import">&nbsp;</div> <span><?php echo JText::_('S3IMPORT'); ?></span> </a> </div> <?php endif; ?> <div class="ak_clr"></div> <h3><?php echo JText::_('COM_AKEEBA_CPANEL_HEADER_INCLUDEEXCLUDE'); ?></h3> <?php if (AKEEBA_PRO): ?> <div class="icon"> <a href="index.php?option=com_akeeba&view=multidb"> <div class="ak-icon ak-icon-multidb">&nbsp;</div> <span><?php echo JText::_('MULTIDB'); ?></span> </a> </div> <div class="icon"> <a href="index.php?option=com_akeeba&view=eff"> <div class="ak-icon ak-icon-extradirs">&nbsp;</div> <span><?php echo JText::_('EXTRADIRS'); ?></span> </a> </div> <?php endif; ?> <div class="icon"> <a href="index.php?option=com_akeeba&view=fsfilter"> <div class="ak-icon ak-icon-fsfilter">&nbsp;</div> <span><?php echo JText::_('FSFILTERS'); ?></span> </a> </div> <div class="icon"> <a href="index.php?option=com_akeeba&view=dbef"> <div class="ak-icon ak-icon-dbfilter">&nbsp;</div> <span><?php echo JText::_('DBEF'); ?></span> </a> </div> <?php if (AKEEBA_PRO): ?> <div class="icon"> <a href="index.php?option=com_akeeba&view=regexfsfilter"> <div class="ak-icon ak-icon-regexfiles">&nbsp;</div> <span><?php echo JText::_('REGEXFSFILTERS'); ?></span> </a> </div> <div class="icon"> <a href="index.php?option=com_akeeba&view=regexdbfilter"> <div class="ak-icon ak-icon-regexdb">&nbsp;</div> <span><?php echo JText::_('REGEXDBFILTERS'); ?></span> </a> </div> <?php endif; ?> <div class="ak_clr"></div> </div> <div class="span4"> <h3><?php echo JText::_('CPANEL_LABEL_STATUSSUMMARY')?></h3> <div> <?php echo $this->statuscell ?> <?php $quirks = Factory::getConfigurationChecks()->getDetailedStatus(); ?> <?php if(!empty($quirks)): ?> <div> <?php echo $this->detailscell ?> </div> <hr/> <?php endif; ?> <?php if(!defined('AKEEBA_PRO')) { $show_donation = 1; } else { $show_donation = (AKEEBA_PRO != 1); } ?> <p class="ak_version"> <?php echo JText::_('AKEEBA').' '.($show_donation?'Core':'Professional ').' '.AKEEBA_VERSION.' ('.AKEEBA_DATE.')' ?> </p> <!-- CHANGELOG :: BEGIN --> <?php if($show_donation): ?> <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_s-xclick" /> <input type="hidden" name="hosted_button_id" value="10903325" /> <a href="#" id="btnchangelog" class="btn btn-info btn-small">CHANGELOG</a> <input type="submit" class="btn btn-inverse btn-small" value="Donate via PayPal" /> <!--<input class="btn" type="image" src="https://www.paypal.com/en_GB/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online." style="border: none !important; width: 92px; height 26px;" />--> <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form> <?php else: ?> <a href="#" id="btnchangelog" class="btn btn-info btn-small">CHANGELOG</a> <?php endif; ?> <div style="display:none;"> <div id="akeeba-changelog"> <?php require_once dirname(__FILE__).'/coloriser.php'; echo AkeebaChangelogColoriser::colorise(JPATH_COMPONENT_ADMINISTRATOR.'/CHANGELOG.php'); ?> </div> </div> <!-- CHANGELOG :: END --> <a href="index.php?option=com_akeeba&view=update&task=force" class="btn btn-inverse btn-small"> <?php echo JText::_('COM_AKEEBA_CPANEL_MSG_RELOADUPDATE'); ?> </a> </div> <h3><?php echo JText::_('BACKUP_STATS') ?></h3> <div><?php echo $this->statscell ?></div> </div> </div> <div class="row-fluid footer"> <div class="span12"> <p style="height: 6em"> <?php echo JText::sprintf('Copyright &copy;2006-%s <a href="http://www.akeebabackup.com">Akeeba Ltd</a>. All Rights Reserved.', date('Y')); ?><br/> Akeeba Backup is Free Software and is distributed under the terms of the <a href="http://www.gnu.org/licenses/gpl-3.0.html">GNU General Public License</a>, version 3 or - at your option - any later version. <?php if(AKEEBA_PRO != 1): ?> <br/>If you use Akeeba Backup Core, please post a rating and a review at the <a href="http://extensions.joomla.org/extensions/extension/access-a-security/site-security/akeeba-backup">Joomla! Extensions Directory</a>. <?php endif; ?> <br/><br/> <strong><?php echo JText::_('TRANSLATION_CREDITS')?></strong>: <em><?php echo JText::_('TRANSLATION_LANGUAGE') ?></em> &bull; <a href="<?php echo JText::_('TRANSLATION_AUTHOR_URL') ?>"><?php echo JText::_('TRANSLATION_AUTHOR') ?></a> </p> </div> </div> <?php if($this->statsIframe) { echo $this->statsIframe; } ?> <script type="text/javascript"> (function($) { $(document).ready(function(){ <?php if (!$this->needsdlid): ?> $.ajax('index.php?option=com_akeeba&view=cpanel&task=updateinfo&tmpl=component', { success: function(msg, textStatus, jqXHR) { // Get rid of junk before and after data var match = msg.match(/###([\s\S]*?)###/); data = match[1]; if (data.length) { $('#updateNotice').html(data); } } }); <?php endif; ?> }); })(akeeba.jQuery); </script>
felix47/gruz
administrator/components/com_akeeba/views/cpanel/tmpl/default.php
PHP
gpl-2.0
14,965
<?php @ini_set("display_errors","1"); @ini_set("display_startup_errors","1"); session_cache_limiter("none"); include("include/dbcommon.php"); header("Expires: Thu, 01 Jan 1970 00:00:01 GMT"); set_time_limit(600); include("include/me_dead_variables.php"); include("include/import_functions.php"); $strOriginalTableName="`me-dead`"; if(!isLogged()) { $_SESSION["MyURL"]=$_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"]; header("Location: login.php?message=expired"); return; } if(CheckPermissionsEvent($strTableName, 'I') && !CheckSecurity(@$_SESSION["_".$strTableName."_OwnerID"],"Import")) { echo "<p>"."You don't have permissions to access this table"."<a href=\"login.php\">"."Back to login page"."</a></p>"; return; } $cipherer = new RunnerCipherer($strTableName); // keys array $keys_present=1; $total_records=0; $goodlines = 0; // Create audit object $auditObj = GetAuditObject($strTableName); function getFieldNamesByHeaders($fields) { global $strTableName, $conn, $strOriginalTableName, $ext, $gSettings; // check fields in column headers // check that we have labes in column headers $fieldsNotFoundArr = array(); $fNamesArr = array(); $fNamesFromQuery = $gSettings->getFieldsList(); $fieldLabelError = false; $labelFieldsNotFoundArr = array(); for ($j=0;$j<count($fields);$j++) { $labelNotFound = true; for($i=0;$i<count($fNamesFromQuery);$i++) { if($ext==".CSV") $label = GoodFieldName($fNamesFromQuery[$i]); else $label = GetFieldLabel(GoodFieldName($strTableName), GoodFieldName($fNamesFromQuery[$i])); if($fields[$j] == $label) { $fNamesArr[$j] = $fNamesFromQuery[$i]; $labelNotFound = false; break; } } if ($labelNotFound) { $fieldLabelError = true; $labelFieldsNotFoundArr[] = $fields[$j]; } } // if field names are not labels, than compare them with fields from query $fieldsListError = false; $queryFieldsNotFoundArr = array(); if ($fieldLabelError) { $fieldFromListNotFound = true; $fNamesArr = array(); for ($j=0;$j<count($fields);$j++) { $fieldNotFound = true; for($i=0;$i<count($fNamesFromQuery);$i++) { if($fields[$j] == $fNamesFromQuery[$i]) { $fNamesArr[$j] = $fNamesFromQuery[$i]; $fieldNotFound = false; $fieldFromListNotFound = false; break; } } if ($fieldNotFound) { $fieldsListError = true; $queryFieldsNotFoundArr[] = $fields[$j]; } } } // if field list not lables or fields from query, than compare fields from DB $fieldsDbError = false; $dbFieldsNotFoundArr = array(); if ($fieldLabelError && $fieldsListError) { $fNamesArr = array(); $strSQL = "select * from ".AddTableWrappers($strOriginalTableName); $rs = db_query($strSQL,$conn); $dbFieldNum = db_numfields($rs); for ($j=0;$j<count($fields);$j++) { $fieldFromDBNotFound = true; for($i=0;$i<$dbFieldNum;$i++) { $fNameFromDB = db_fieldname($rs,$i); if($fields[$j] == $fNameFromDB) { $fNamesArr[$j] = $fNameFromDB; $fieldFromDBNotFound = false; break; } } if ($fieldFromDBNotFound) { $fieldsDbError = true; $dbFieldsNotFoundArr[] = $fields[$j]; } } } // if fields are not labels, fields from list and fields from table if ($fieldLabelError && $fieldsListError && $fieldsDbError) { if (count($labelFieldsNotFoundArr) < count($dbFieldsNotFoundArr) && count($labelFieldsNotFoundArr) < count($queryFieldsNotFoundArr) ){ $fieldsNotFoundArr = $labelFieldsNotFoundArr; }elseif (count($dbFieldsNotFoundArr) < count($labelFieldsNotFoundArr) && count($dbFieldsNotFoundArr) < count($queryFieldsNotFoundArr) ){ $fieldsNotFoundArr = $dbFieldsNotFoundArr; }elseif (count($queryFieldsNotFoundArr) < count($labelFieldsNotFoundArr) && count($queryFieldsNotFoundArr) < count($dbFieldsNotFoundArr)){ $fieldsNotFoundArr = $queryFieldsNotFoundArr; }elseif(count($queryFieldsNotFoundArr) == count($labelFieldsNotFoundArr) && count($queryFieldsNotFoundArr) == count($dbFieldsNotFoundArr)){ $fieldsNotFoundArr = $dbFieldsNotFoundArr; } echo "Import didn't succeed, couldn't find followind fields: ".implode(", ", $fieldsNotFoundArr); exit(); } // if found any type of fields, than use them as fields array else { return $fNamesArr; } } ////////////////////// // import from Excel ////////////////////// function ImportFromExcel($uploadfile) { $autoinc=false; $ret = 1; global $error_message, $keys, $goodlines, $total_records, $conn, $strOriginalTableName, $strTableName, $keys_present; $data=openImportExcelFile($uploadfile); // populate field names array $fields=array(); $fields=getImportExcelFields($data); $fields = getFieldNamesByHeaders($fields); $keys_present=1; for($k=0; $k<count($keys); $k++) { if (!in_array(RemoveFieldWrappers($keys[$k]),$fields)) { $keys_present=0; break; } } if(in_array("ID",$fields)) $autoinc=true; $ret=getImportExcelData($data,$fields); return $ret; } ///////////////////////// // import from CSV ///////////////////////// function ImportFromCSV($uploadfile) { $ret = 1; global $error_message, $keys, $goodlines, $total_records, $conn, $strOriginalTableName , $keys_present, $auditObj, $gSettings; $fields = array(); $fields = getImportCVSFields($uploadfile); // populate field names array for ($j=0;$j<count($fields);$j++) { $fields[$j] = trim($fields[$j]); if(substr($fields[$j],0,1)=="\"" && substr($fields[$j],-1)=="\"") $fields[$j]=substr($fields[$j],1,-1); } $fields = getFieldNamesByHeaders($fields); $keys_present=1; for($k=0; $k<count($keys); $k++) { if (!in_array(RemoveFieldWrappers($keys[$k]),$fields)) { $keys_present=0; break; } } $autoinc = false; if(in_array("ID",$fields)) $autoinc=true; $total_records = 0; $line = ""; $row = 0; // parse records from file if (($handle = fopen($uploadfile, "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000000, ",")) !== FALSE) { // first rec contain only fields names if ($row === 0) { $row++; continue; } $arr = array(); foreach($data as $key=>$val) { $type= $gSettings->getFieldType($fields[$key]); if(IsDateFieldType($type)) { $value = localdatetime2db($val); if ($value !== -1 && $value !== FALSE && strlen($value)) $arr[$fields[$key]]=$value; else $arr[$fields[$key]] = NULL; } elseif(IsTimeType($type)) { $value = localtime2db($val); if ($value !== -1 && $value !== FALSE && strlen($value) && strlen($val) && !is_null($val)) $arr[$fields[$key]]=$value; else $arr[$fields[$key]] = NULL; } else $arr[$fields[$key]]=$val; } $ret = InsertRecord($arr, $row); $row++; } fclose($handle); } $total_records = $row-1; return $ret; } function import_error_handler($errno, $errstr, $errfile, $errline) { global $error_happened; // echo $errstr ."<br>"; $error_happened=1; } function ParseCSVLine($line) { $arr = array(); $inword=0; $hasquotes=0; $start=0; for ($i=0;$i<strlen($line);$i++) { $c = $line[$i]; switch ($c) { case "\"": if (!$inword) { $inword=1; $hasquotes=1; $start=$i+1; } else { if ($line[$i+1]=="\"") { $i++; continue; } else { $inword=0; $hasquotes=0; $arr[] = substr($line, $start, $i-$start); $start=$i+1; } } break; case ",": if (!$inword) { if ($line[$i+1]==",") $inword=1; $hasquotes=0; $start=$i+1; } else { if (!$hasquotes) { $inword=0; if ($line[$i+1]==",") $inword=1; $hasquotes=0; $arr[] = substr($line, $start, $i-$start); $start=$i+1; } } break; case " ": break; default: $inword=1; break; } } if ($start<strlen($line)) $arr[] = substr($line, $start); return $arr; } function InsertRecord($arr, $recInd) { global $goodlines, $conn, $error_message, $keys_present, $keys, $strOriginalTableName, $strTableName , $eventObj, $locale_info, $auditObj, $cipherer, $gSettings, $pageObject; $ret=1; $rawvalues = array(); foreach($arr as $key=>$val) { $rawvalues[$key] = $val; $type= $gSettings->getFieldType($key); if(!NeedQuotes($type)) { $value = (string)$val; $value = str_replace(",",".",$value); if(strlen($value)>0) { $value=str_replace($locale_info["LOCALE_SCURRENCY"],"",$value); $arr[$key]=0+$value; } else $arr[$key]=NULL; } } $retval=true; if ($eventObj->exists('BeforeInsert')) $retval=$eventObj->BeforeInsert($rawvalues,$arr, $pageObject); if($retval) { $fields = array_keys($arr); foreach($fields as $key=>$val) $fields_list[$key]=GetFullFieldNameForInsert($gSettings, $val); $values_list=""; foreach($arr as $key=>$val) { if(!is_null($arr[$key])) $values_list .= $cipherer->AddDBQuotes($key, $val).", "; else $values_list .= "NULL, "; } if(strlen($values_list)>0) $values_list=substr($values_list,0,strlen($values_list)-2); $sql = "insert into ".AddTableWrappers($strOriginalTableName)." (".implode(",", $fields_list).") values (".$values_list.")"; if (db_exec_import($sql,$conn)) { $goodlines++; if($auditObj) { $aKeys = GetKeysArray($arr, true); $auditObj->LogAdd($strTableName, $arr, $aKeys); } } else { $temp_error_message="<b>Error:</b> in the line: ".implode(",",$arr).'&nbsp;&nbsp;<a linkType="debugOpener" recId="'.$recInd.'" href="" onclick="importMore('.$recInd.');">More info</a><br>'; $temp_error_message .= '<div id="importDebugInfoTable'.$recInd.'" cellpadding="3" cellspacing="1" align="center" style="display: none;"><p class="error">SQL query: '.$sql.'; </p><p class="error">DB error: '.db_error($conn).';</p></div>'; $temp_error_message .= "<br><br>"; // we'll try to update the record if ($keys_present) { $sql = "update ".AddTableWrappers($strOriginalTableName)." set "; $sqlset=""; $where = " where "; foreach($fields as $k=>$val) { if (!in_array(AddFieldWrappers($fields[$k]), $keys)) { if(!is_null($arr[$val])) $sqlset .= $fields_list[$k] . "=" .$cipherer->AddDBQuotes($val,$arr[$val]).", "; else $sqlset .= $fields_list[$k] . "=NULL, "; } else { $where.= $fields_list[$k] . "=".$cipherer->AddDBQuotes($val,$arr[$val]). " and "; } } if(strlen($sqlset)>0) $sql.= substr($sqlset, 0, strlen($sqlset)-2); $where = substr($where, 0, strlen ($where)-5); $sql.= " " . $where; $rstmp=db_query("select * from " .AddTableWrappers($strOriginalTableName). " " . $where,$conn); $data=db_fetch_array($rstmp); if ($data) { if($auditObj) foreach ($data as $key => $val) $auditOldValues[$key] = $val; if (db_exec_import($sql,$conn)) { // update successfull $goodlines++; if($auditObj) { $aKeys = GetKeysArray($arr); $auditObj->LogEdit($strTableName, $arr, $auditOldValues, $aKeys); } } else { // update not successfull $error_message .= $temp_error_message; $ret = 0; } } else // nothing to update { $error_message .= $temp_error_message; $ret = 0; } } else $error_message .= $temp_error_message; } return $ret; } } /** * GetKeysArray * Form aray of primary keys and their values for audit * @param {array} $arr array of inserting values * @param {bool} $searchId - find last inserted id or not * @return {array} array of keys and their values */ function GetKeysArray($arr, $searchId = false) { global $conn, $pageObject; $keyfields = $pageObject->pSet->GetTableKeys(); $aKeys = array(); if(count($keyfields)) { foreach ($keyfields as $kfield) if(array_key_exists($kfield, $arr)) $aKeys[$kfield] = $arr[$kfield]; if(count($aKeys) == 0 && searchId) { $lastId = db_insertid($conn); if($lastId > 0) $aKeys[$keyfields[0]] = $lastId; } } return $aKeys; } $id = postvalue("id") != "" ? postvalue("id") : 1; $error_message = ""; include('include/xtempl.php'); include('classes/runnerpage.php'); $xt = new Xtempl(); $layout = new TLayout("import","BoldWhite_label2","MobileWhite_label2"); $layout->blocks["top"] = array(); $layout->containers["import"] = array(); $layout->containers["import"][] = array("name"=>"importheader","block"=>"","substyle"=>2); $layout->containers["import"][] = array("name"=>"importheader_text","block"=>"","substyle"=>3); $layout->containers["import"][] = array("name"=>"errormessage","block"=>"","substyle"=>1); $layout->containers["import"][] = array("name"=>"importfields","block"=>"","substyle"=>1); $layout->containers["import"][] = array("name"=>"importbuttons","block"=>"","substyle"=>2); $layout->skins["import"] = "fields"; $layout->blocks["top"][] = "import";$page_layouts["me_dead_import"] = $layout; //array of params for classes $params = array("pageType" => PAGE_IMPORT, "id" =>$id, "tName"=>$strTableName); $params["xt"] = &$xt; $params["needSearchClauseObj"] = false; $pageObject = new RunnerPage($params); // if is postback (form sent) and import needed if(@$_POST["a"]=="added") { $value = postvalue("value_ImportFileName".$id); $type = postvalue("type_ImportFileName".$id); $importfile = getImportTableName("file_ImportFileName".$id); //check the file extension $pos = strrpos($value,"."); $ext = strtoupper(substr($value,$pos)); if ($eventObj->exists('BeforeImport')) { if ($eventObj->BeforeImport($pageObject) === false) { exit(0); } } if($ext==".XLS" || $ext==".XLSX") { ImportFromExcel($importfile); } else { ImportFromCSV($importfile); } if ($eventObj->exists('AfterImport')) { $eventObj->AfterImport($goodlines, $total_records-$goodlines, $pageObject); } if ($goodlines==$total_records) { $error_message = "<font size=2>" . $goodlines . " records were imported</font><br>"; $error_message .= "<font size=2>To back to your list click on the <b>Back to list</b> button.</font>"; } else { $error_message .= "Number of records: ". $total_records ."<br>"; $error_message .= "Imported: ".$goodlines."<br>"; $error_message .= "Not imported: "; $error_message .= $total_records-$goodlines ."<br>"; } } // add button events if exist $pageObject->addButtonHandlers(); $pageObject->body["begin"] .="<script type=\"text/javascript\" src=\"include/loadfirst.js\"></script>\r\n"; $pageObject->body["begin"].="<script>\r\n"; $pageObject->body["begin"].="function importMore(id)\r\n"; $pageObject->body["begin"].="{\r\n"; $pageObject->body["begin"].=" if($('#importDebugInfoTable'+id).css('display')=='none')\r\n"; $pageObject->body["begin"].=" $('#importDebugInfoTable'+id).show();\r\n"; $pageObject->body["begin"].=" else\r\n"; $pageObject->body["begin"].=" $('#importDebugInfoTable'+id).hide();\r\n"; $pageObject->body["begin"].="}\r\n"; $pageObject->body["begin"].="</script>\r\n"; $pageObject->body["begin"] .= "<script type=\"text/javascript\" src=\"include/lang/".getLangFileName(mlang_getcurrentlang()).".js\"></script>"; $pageObject->fillSetCntrlMaps(); $pageObject->body['end'] .= '<script>'; $pageObject->body['end'] .= "window.controlsMap = ".my_json_encode($pageObject->controlsHTMLMap).";"; $pageObject->body['end'] .= "window.viewControlsMap = ".my_json_encode($pageObject->viewControlsHTMLMap).";"; $pageObject->body['end'] .= "window.settings = ".my_json_encode($pageObject->jsSettings).";"; $pageObject->body['end'] .= '</script>'; $pageObject->body["end"] .= "<script language=\"JavaScript\" src=\"include/runnerJS/RunnerAll.js\"></script>\r\n"; $pageObject->addCommonJs(); $pageObject->body["end"] .= "<script>".$pageObject->PrepareJS()."</script>"; $xt->assignbyref("body",$pageObject->body); $xt->assign("importfile_attrs", "id=\"file_ImportFileName".$pageObject->id."\" name=\"file_ImportFileName".$pageObject->id."\""); $xt->assign("backtolist_attrs", "id=\"backButton".$pageObject->id."\""); $xt->assign("importlink_attrs", "id=\"saveButton".$pageObject->id."\""); $xt->assign("error_message", $error_message); $xt->display("me_dead_import.htm"); ?>
LewisSoftwareDevelopment/Headwaters
output/me_dead_import.php
PHP
gpl-2.0
17,742
select assertEmpty('select * from get_db_columns_LogicExpression() where logicExpression is not null and logicExpression ilike ''%^%'' '); select assertEmpty('select * from get_db_columns_LogicExpression() where logicExpression is not null and logicExpression ilike ''%~%'' ');
klst-com/metasfresh
de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5449762_sys_FRESH-112_assert_NoLogicExpressionWithLegacyNotOperators.sql
SQL
gpl-2.0
282
{namespace theme=KayStrobach\Themes\ViewHelpers} <div xmlns="http://www.w3.org/1999/xhtml" lang="en" xmlns:f="http://typo3.org/ns/fluid/ViewHelpers"> <f:section name="Default"> <!-- theme_t3kit: Partials/Header/Header.html [begin] --> <header class="header"> <div class="header-top-wrp"> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderTop')}"> <div class="header-top"> <div class="header-top__main-navigation-toggle-btn"> <button type="button" class="main-navigation__toggle-btn js__main-navigation__toggle-btn" > <span>toggle menu</span> </button> </div> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderTopContacts')}"> <div class="header-top__contact"> <div class="header-top__contact-tel"> <span class="icons icon-t3-mobile" aria-hidden="true"></span> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderTopContactsLabels')}"> <span class="header-top__contact-tel-title" aria-hidden="true"><f:translate key="callUs_label" /></span> </f:if> <a class="header-top__contact-tel-link" href="tel:{f:cObject(typoscriptObjectPath: 'lib.contacts.phone')}">{theme:constant(constant: 'themes.configuration.contacts.phone')}</a> </div> <div class="header-top__contact-email"> <span class="icons icon-t3-mail" aria-hidden="true"></span> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderTopContactsLabels')}"> <span class="header-top__contact-email-title" aria-hidden="true"><f:translate key="emailUs_label" /></span> </f:if> <f:link.email class="header-top__contact-email-link" title="{f:translate(key: 'emailUs_label')}" additionalAttributes="{aria-label: '{f:translate(key: \'emailUs_label\')}'}" email="{theme:constant(constant: 'themes.configuration.contacts.email')}" /> </div> </div> </f:if> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderTopLangMenu')}"> <f:cObject typoscriptObjectPath="lib.menu.language.standard" /> </f:if> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderTopSearch')}"> <f:cObject typoscriptObjectPath="lib.header.top.search" /> </f:if> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderTopNavigation')}"> <f:cObject typoscriptObjectPath="lib.menu.top" /> </f:if> </div> </f:if> </div> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderMiddle')}"> <div class="header-middle-wrp"> <div class="header-middle"> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderMiddleLogo')}"> <div class="header-middle__logo"> <f:cObject typoscriptObjectPath="lib.header.logo.main" /> </div> </f:if> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderMiddleSocIcons')}"> <div class="header-middle__social-icon"> <f:cObject typoscriptObjectPath="lib.header.middle.socialmedia" /> </div> </f:if> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderMiddleSearch')}"> <f:cObject typoscriptObjectPath="lib.header.middle.search" /> </f:if> </div> </div> </f:if> <!-- theme_t3kit: Main menu [begin] --> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderTop')}==0"> <button type="button" class="main-navigation__toggle-btn js__main-navigation__toggle-btn" > <span>toggle menu</span> </button> <f:if condition="{theme:constant(constant:'themes.configuration.menu.main.enableLangMenuInNavigation')}"> <div class="main-navigation-mobile__language-menu"> <f:cObject typoscriptObjectPath="lib.menu.language.standard" /> </div> </f:if> </f:if> <nav id="main-navigation" class="main-navigation js__main-navigation{f:if(condition: '{theme:constant(constant:\'themes.configuration.menu.main.dropdownColumns\')} == 1', then: ' _dropdown-menu-with-columns js__dropdown-menu-with-columns')}"> <div class="main-navigation__items-wrp js__navigation__items-wrp"> <f:if condition="{theme:constant(constant:'themes.configuration.menu.main.enableLogoInNavigation')}"> <div class="main-navigation__logo"> <f:cObject typoscriptObjectPath="lib.header.logo.main" /> </div> </f:if> <f:if condition="{theme:constant(constant:'themes.configuration.menu.main.enableLangMenuInNavigation')}"> <f:cObject typoscriptObjectPath="lib.menu.language.standard" /> </f:if> <ul class="main-navigation__items-list js__main-navigation__items-list {f:if(condition: '{theme:constant(constant:\'themes.configuration.menu.main.navbarPos\')} == right', then: '_right-pos')}"> <f:cObject typoscriptObjectPath="lib.menu.main" /> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.headerTopNavigationVisibleInMobileMenu')}"> <f:cObject typoscriptObjectPath="lib.menu.topMobile" /> </f:if> <f:if condition="{theme:constant(constant:'themes.configuration.elem.status.showHeaderMainMenuSearch')}"> <f:cObject typoscriptObjectPath="lib.menu.main.search" /> </f:if> </ul> </div> </nav> <!-- theme_t3kit: Main menu [end] --> <div class="main-navigation__search-box-overlay js__main-navigation__search-box-overlay"></div> <div class="header-top__language-menu-overlay js__header-top__language-menu-overlay"></div> </header> <!-- theme_t3kit: Partials/Header/Header.html [end] --> </f:section> </div>
dkd/theme_t3kit
Resources/Private/Partials/Header/Header.html
HTML
gpl-2.0
5,680
# Copyright 2011 Google Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; 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. """Unit tests for nss_cache/util/timestamps.py.""" __author__ = 'jaq@google.com (Jamie Wilkinson)' import os import shutil import tempfile import time import unittest import mox from nss_cache.util import timestamps class TestTimestamps(mox.MoxTestBase): def setUp(self): super(TestTimestamps, self).setUp() self.workdir = tempfile.mkdtemp() def tearDown(self): super(TestTimestamps, self).tearDown() shutil.rmtree(self.workdir) def testReadTimestamp(self): ts_filename = os.path.join(self.workdir, 'tsr') ts_file = open(ts_filename, 'w') ts_file.write('1970-01-01T00:00:01Z\n') ts_file.close() ts = timestamps.ReadTimestamp(ts_filename) self.assertEqual(time.gmtime(1), ts) def testReadTimestamp(self): # TZ=UTC date -d @1306428781 # Thu May 26 16:53:01 UTC 2011 ts_filename = os.path.join(self.workdir, 'tsr') ts_file = open(ts_filename, 'w') ts_file.write('2011-05-26T16:53:01Z\n') ts_file.close() ts = timestamps.ReadTimestamp(ts_filename) self.assertEqual(time.gmtime(1306428781), ts) def testReadTimestampInFuture(self): ts_filename = os.path.join(self.workdir, 'tsr') ts_file = open(ts_filename, 'w') ts_file.write('2011-05-26T16:02:00Z') ts_file.close() now = time.gmtime(1) self.mox.StubOutWithMock(time, 'gmtime') time.gmtime().AndReturn(now) self.mox.ReplayAll() ts = timestamps.ReadTimestamp(ts_filename) self.assertEqual(now, ts) def testWriteTimestamp(self): ts_filename = os.path.join(self.workdir, 'tsw') good_ts = time.gmtime(1) timestamps.WriteTimestamp(good_ts, ts_filename) self.assertEqual(good_ts, timestamps.ReadTimestamp(ts_filename)) ts_file = open(ts_filename, 'r') self.assertEqual('1970-01-01T00:00:01Z\n', ts_file.read()) if __name__ == '__main__': unittest.main()
UPPMAX/nsscache
nss_cache/util/timestamps_test.py
Python
gpl-2.0
2,605
<?php /** * New sidebar widgets * */ class JR_FX_mini_gmaps extends WP_Widget { function JR_FX_mini_gmaps() { $widget_ops = array( 'description' => __( 'FXtender Mini Google Maps Location', JR_FX_i18N_DOMAIN) ); $this->WP_Widget('jr_fx_mini_gmaps', __('FXtender Mini Google Maps Location', JR_FX_i18N_DOMAIN), $widget_ops); } function widget( $args, $instance ) { global $wp_query; extract($args); $title = apply_filters('widget_title', empty($instance['title']) ? '' : $instance['title']); $coord = (isset($instance['coord'])?$instance['coord']:0); $zoom = (isset($instance['zoom'])?$instance['zoom']:10); if ( $wp_query->post && is_singular(JR_FX_JR_POST_TYPE) ) : echo $before_widget; if ( $title ) echo $before_title . $title . $after_title; jr_fx_display_location_meta_box( $wp_query->post, $coord, ($zoom?$zoom:1) ); echo $after_widget; endif; } function update( $new_instance, $old_instance ) { $instance = $old_instance; /* Strip tags (if needed) and update the widget settings. */ $instance['title'] = strip_tags( $new_instance['title'] ); $instance['zoom'] = strip_tags( $new_instance['zoom'] ); $instance['coord'] = strip_tags( $new_instance['coord'] ); return $new_instance; } function form( $instance ) { $defaults = array( 'title' => __('Location', JR_FX_i18N_DOMAIN), 'coord' => 0, 'zoom' => 10 ); $instance = wp_parse_args( (array) $instance, $defaults ); ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', JR_FX_i18N_DOMAIN ); ?> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $instance['title']; ?>" /> </label> </p> <p> <?php _e( 'Show Latitude/Longitude?', JR_FX_i18N_DOMAIN ); ?> <input type="checkbox" id="<?php echo $this->get_field_id( 'coord' ); ?>" name="<?php echo $this->get_field_name( 'coord' ); ?>" <?php echo ($instance['coord']?'checked':''); ?>> </p> <p> <label for="<?php echo $this->get_field_id( 'zoom' ); ?>"><?php _e( 'Zoom Level:' ); ?> <input size=2 id="<?php echo $this->get_field_id( 'zoom' ); ?>" name="<?php echo $this->get_field_name( 'zoom' ); ?>" type="text" value="<?php echo $instance['zoom']; ?>" /> </label> <p> <p> <?php _e('<strong>Note</strong>: This widget will only work within the Job page.', JR_FX_i18N_DOMAIN ); ?> </p> <?php } } class JR_FX_company_logo extends WP_Widget { function JR_FX_company_logo() { $widget_ops = array( 'description' => __( 'FXtender Company Logo', JR_FX_i18N_DOMAIN) ); $this->WP_Widget('jr_fx_company_logo', __('FXtender Company Logo', JR_FX_i18N_DOMAIN), $widget_ops); } function widget( $args, $instance ) { global $wp_query; $post_id = $wp_query->post->ID; $post_title = $wp_query->post->post_title; extract($args); $title = apply_filters('widget_title', empty($instance['title']) ? '' : $instance['title']); $size = $instance['size']; $width = $instance['width']; $height = $instance['height']; # if width and height are passed, ignore the fixed sizes if ( $width && $height && $instance['size']=='custom' ) $size = array($width, $height); if ( $wp_query->post && is_singular(JR_FX_JR_POST_TYPE) && has_post_thumbnail($post_id) ) : echo $before_widget; if ( $title ) echo $before_title . $title . $after_title; if ( has_post_thumbnail($post_id) ) { $logo = '<div class="jr_fx_side_logo">'; $author = get_user_by('id', $wp_query->post->post_author); $logo_link = '<a href="' . get_author_posts_url( $author->ID, $author->user_nicename ) . '" title="' . esc_attr( $post_title ) . '">'; if ($instance['link']) $logo .= $logo_link; $logo .= get_the_post_thumbnail( $post_id, $size, array( 'title' => esc_attr( $post_title ) ) ); if ($instance['link']) $logo .= '</a>'; $logo .= '</div>'; echo $logo; } echo $after_widget; endif; } function update( $new_instance, $old_instance ) { $instance = $old_instance; /* Strip tags (if needed) and update the widget settings. */ $instance['title'] = strip_tags( $new_instance['title'] ); $instance['size'] = strip_tags( $new_instance['size'] ); $instance['width'] = strip_tags($new_instance['width']); $instance['height'] = strip_tags($new_instance['height']); $instance['link'] = strip_tags( $new_instance['link'] ); return $instance; } function form( $instance ) { $defaults = array( 'title' => __('Company Logo', JR_FX_i18N_DOMAIN), 'size' =>'thumbnail', 'width' => '', 'height' => '', 'link' => ''); $instance = wp_parse_args( (array) $instance, $defaults ); ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $instance['title']; ?>" /> </label> </p> <p> <label><?php _e('Size',JR_FX_i18N_DOMAIN) ?>:</label><br/> <select id="<?php echo $this->get_field_id( 'size' ); ?>" name="<?php echo $this->get_field_name( 'size' ); ?>" > <option value="thumbnail" <?php echo ($instance['size']=='thumbnail'?'selected':''); ?>><?php _e( 'Thumbnail',JR_FX_i18N_DOMAIN); ?></option> <option value="medium" <?php echo ($instance['size']=='medium'?'selected':''); ?>><?php _e( 'Medium',JR_FX_i18N_DOMAIN); ?></option> <option value="large" <?php echo ($instance['size']=='large'?'selected':''); ?>><?php _e( 'Large',JR_FX_i18N_DOMAIN); ?></option> <option value="custom" <?php echo ($instance['size']=='custom'?'selected':''); ?>><?php _e( 'Custom Size',JR_FX_i18N_DOMAIN); ?></option> </select > </p> <p> <?php _e( 'Link to Author Jobs?', JR_FX_i18N_DOMAIN ); ?> <input type="checkbox" id="<?php echo $this->get_field_id( 'link' ); ?>" name="<?php echo $this->get_field_name( 'link' ); ?>" <?php echo ($instance['link']?'checked':''); ?>> </p> <p> W: <input type="text" id="<?php echo $this->get_field_id( 'width' ); ?>" name="<?php echo $this->get_field_name( 'width' ); ?>" size=3 value="<?php echo $instance['width']; ?>"> x H: <input id="<?php echo $this->get_field_id( 'height' ); ?>" name="<?php echo $this->get_field_name( 'height' ); ?>" size=3 value="<?php echo $instance['height']; ?>"> </p> <p> <?php _e('<strong>Note</strong>: This widget will only work on a job page.', JR_FX_i18N_DOMAIN ); ?> </p> <?php } } add_action( 'widgets_init', 'jr_fx_widgets_init' ); function jr_fx_widgets_init() { if ( jr_fx_has_perms_to( '_widget_mini_gmaps' ) ) register_widget( 'JR_FX_mini_gmaps' ); if ( jr_fx_has_perms_to ( '_widget_company_logo' ) ) register_widget ( 'JR_FX_company_logo' ); }
tamtranvn2012/jobroller
wp-content_old backup/plugins/fxtender-pro-jobroller/includes/widgetz.php
PHP
gpl-2.0
6,962
/** * $Id: jquery.multiupload.gears.js 616 2008-11-27 15:43:52Z spocke $ * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ (function($) { if (!$.multiUpload.initialized && window.google && google.gears) { $.multiUpload.initialized = 1; $.multiUpload.runtime = 'gears'; // Override init function $.extend($.multiUpload.prototype, { init : function() { var up = this; $(up).trigger('multiUpload:init'); $(up).bind('multiUpload:selectFiles', function(e) { var up = this, desk = google.gears.factory.create('beta.desktop'), s = {}; if (up.settings.filter[0] != '*') s.filter = $.map(up.settings.filter, function(v) {return '.' + v}); desk.openFiles(function(f) { var sf = []; if (f.length) { up._fireEvent('multiUpload:beforeFilesSelected'); $(f).each(function() { var fo = { id : up.generateID(), name : this.name, blob : this.blob, size : this.blob.length, loaded : 0 }; up.files.push(fo); sf.push(fo); }); up._fireEvent('multiUpload:filesSelected', [{files : sf}]); up._fireEvent('multiUpload:filesChanged'); } else up._fireEvent('multiUpload:filesSelectionCancelled'); }, s); }); $(up).bind('multiUpload:uploadFile', function(e, fo) { var req, up = this, chunkSize, chunk = 0, chunks, i, start, loaded = 0, curChunkSize; chunkSize = up.settings.chunk_size || 1024 * 1024; chunks = Math.ceil(fo.blob.length / chunkSize); uploadNextChunk(); function uploadNextChunk() { var url = up.settings.upload_url; if (fo.status) return; curChunkSize = Math.min(chunkSize, fo.blob.length - (chunk * chunkSize)); req = google.gears.factory.create('beta.httprequest'); req.open('POST', url + (url.indexOf('?') == -1 ? '?' : '&') + 'name=' + escape(fo.name) + '&chunk=' + chunk + '&chunks=' + chunks + '&path=' + escape(up.settings.path)); req.setRequestHeader('Content-Disposition', 'attachment; filename="' + fo.name + '"'); req.setRequestHeader('Content-Type', 'application/octet-stream'); req.setRequestHeader('Content-Range', 'bytes ' + chunk * chunkSize); req.upload.onprogress = function(pr) { fo.loaded = loaded + pr.loaded; up._fireEvent('multiUpload:fileUploadProgress', [{file : fo, loaded : fo.loaded, total : fo.size}]); }; req.onreadystatechange = function() { var ar; if (req.readyState == 4) { if (req.status == 200) { ar = {file : fo, chunk : chunk, chunks : chunks, response : req.responseText}; up._fireEvent('multiUpload:chunkUploaded', [ar]); if (ar.cancel) { fo.status = 'failed'; up._fireEvent('multiUpload:filesChanged'); up.uploadNext(); return; } loaded += curChunkSize; if (++chunk >= chunks) { fo.status = 'completed'; up._fireEvent('multiUpload:fileUploaded', [{file : fo, response : req.responseText}]); up._fireEvent('multiUpload:filesChanged'); up.uploadNext(); } else uploadNextChunk(); } else up._fireEvent('multiUpload:uploadChunkError', [{file : fo, chunk : chunk, chunks : chunks, error : 'Status: ' + req.status}]); } }; if (chunk < chunks) req.send(fo.blob.slice(chunk * chunkSize, curChunkSize)); }; }); }, _fireEvent : function(ev, ar) { $(this).trigger(ev, ar); } }); } })(jQuery);
masterit92/c-par
public_html/public/tinymce/script/plugins/imagemanager/pages/im/js/jquery/jquery.multiupload.gears.js
JavaScript
gpl-2.0
3,768
<?php /* * Template Name: Page Fullwidth */ get_header(); ?> <div id="content" class="container clearfix"> <!-- page header --> <div class="container clearfix "> <?php if(of_get_option('sc_showpageheader') == '1' && get_post_meta($post->ID, 'snbpd_ph_disabled', true) != 'on' ) : ?> <?php if(get_post_meta($post->ID, 'snbpd_phitemlink', true) != '' ) : ?> <?php $thumbId = get_image_id_by_link ( get_post_meta($post->ID, 'snbpd_phitemlink', true) ); $thumb = wp_get_attachment_image_src($thumbId, 'page-header', false); ?> <img class="intro-img" alt=" " src="<?php echo $thumb[0] ?>" alt="<?php the_title(); ?>" /> <?php elseif (of_get_option('sc_pageheaderurl') !='' ): ?> <?php $thumbId = get_image_id_by_link ( of_get_option('sc_pageheaderurl') ); $thumb = wp_get_attachment_image_src($thumbId, 'page-header', false); ?> <img class="intro-img" alt=" " src="<?php echo $thumb[0] ?>" alt="<?php the_title(); ?>" /> <?php else: ?> <img class="intro-img" alt=" " src="<?php echo get_template_directory_uri(); ?>/library/images/inner-page-bg.jpg" /> <?php endif ?> <?php endif ?> </div> <!-- end page header --> <!-- content --> <div class="container"> <h1><?php the_title(); ?> <?php if ( !get_post_meta($post->ID, 'snbpd_pagedesc', true)== '') { ?>/<?php }?> <span><?php echo get_post_meta($post->ID, 'snbpd_pagedesc', true); ?></span></h1> <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?> role="article"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="page-body clearfix"> <?php the_content(); ?> </div> <!-- end article section --> <?php endwhile; ?> </article> <?php else : ?> <article id="post-not-found"> <header> <h1><?php _e("Not Found", "site5framework"); ?></h1> </header> <section class="post_content"> <p><?php _e("Sorry, but the requested resource was not found on this site.", "site5framework"); ?></p> </section> <footer> </footer> </article> <?php endif; ?> </div> </div> <!-- end content --> <?php get_footer(); ?>
jperkin/simplecorp
template.page.fullwidth.php
PHP
gpl-2.0
2,424
#include <linux/input.h> #include <linux/i2c.h> #include <linux/ctp.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <asm/io.h> #include <asm/uaccess.h> #include <mach/gpio.h> #include <mach/sys_config.h> #include <linux/gpio.h> struct ctp_config_info config_info; EXPORT_SYMBOL_GPL(config_info); #define CTP_IRQ_NUMBER (config_info.irq_gpio_number) static u32 debug_mask = 0; #define dprintk(level_mask, fmt, arg...) if(unlikely(debug_mask & level_mask)) \ printk("***CTP***"fmt, ## arg) int ctp_i2c_write_bytes(struct i2c_client *client, uint8_t *data, uint16_t len) { struct i2c_msg msg; int ret=-1; msg.flags = !I2C_M_RD; msg.addr = client->addr; msg.len = len; msg.buf = data; ret=i2c_transfer(client->adapter, &msg,1); return ret; } EXPORT_SYMBOL(ctp_i2c_write_bytes); int ctp_i2c_read_bytes_addr16(struct i2c_client *client, uint8_t *buf, uint16_t len) { struct i2c_msg msgs[2]; int ret=-1; msgs[0].flags = !I2C_M_RD; msgs[0].addr = client->addr; msgs[0].len = 2; //data address msgs[0].buf = buf; msgs[1].flags = I2C_M_RD; msgs[1].addr = client->addr; msgs[1].len = len-2; msgs[1].buf = buf+2; ret=i2c_transfer(client->adapter, msgs, 2); return ret; } EXPORT_SYMBOL(ctp_i2c_read_bytes_addr16); bool ctp_i2c_test(struct i2c_client * client) { int ret,retry; uint8_t test_data[1] = { 0 }; //only write a data address. for(retry=0; retry < 2; retry++) { ret =ctp_i2c_write_bytes(client, test_data, 1); //Test i2c. if (ret == 1) break; msleep(10); } return ret==1 ? true : false; } EXPORT_SYMBOL(ctp_i2c_test); bool ctp_get_int_enable(u32 *enable) { int ret = -1; ret = sw_gpio_eint_get_enable(CTP_IRQ_NUMBER,enable); if(ret != 0){ return false; } return true; } EXPORT_SYMBOL(ctp_get_int_enable); bool ctp_set_int_enable(u32 enable) { u32 sta_enable; int ret = -1; if((enable != 0) || (enable != 1)){ return false; } ret = ctp_get_int_enable(&sta_enable); if(ret == true){ if(sta_enable == enable) return true; } ret = sw_gpio_eint_set_enable(CTP_IRQ_NUMBER,enable); if(ret != 0){ return false; } return true; } EXPORT_SYMBOL(ctp_set_int_enable); bool ctp_get_int_port_rate(u32 *clk) { struct gpio_eint_debounce pdbc = {0,0}; int ret = -1; ret = sw_gpio_eint_get_debounce(CTP_IRQ_NUMBER,&pdbc); if(ret != 0){ return false; } *clk = pdbc.clk_sel; return true; } EXPORT_SYMBOL(ctp_get_int_port_rate); bool ctp_set_int_port_rate(u32 clk) { struct gpio_eint_debounce pdbc; int ret = -1; if((clk != 0) && (clk != 1)){ return false; } ret = sw_gpio_eint_get_debounce(CTP_IRQ_NUMBER,&pdbc); if(ret == 0){ if(pdbc.clk_sel == clk){ return true; } } pdbc.clk_sel = clk; ret = sw_gpio_eint_set_debounce(CTP_IRQ_NUMBER,pdbc); if(ret != 0){ return false; } return true; } EXPORT_SYMBOL(ctp_set_int_port_rate); bool ctp_get_int_port_deb(u32 *clk_pre_scl) { struct gpio_eint_debounce pdbc = {0,0}; int ret = -1; ret = sw_gpio_eint_get_debounce(CTP_IRQ_NUMBER,&pdbc); if(ret !=0){ return false; } *clk_pre_scl = pdbc.clk_pre_scl; return true; } EXPORT_SYMBOL(ctp_get_int_port_deb); bool ctp_set_int_port_deb(u32 clk_pre_scl) { struct gpio_eint_debounce pdbc; int ret = -1; ret = sw_gpio_eint_get_debounce(CTP_IRQ_NUMBER,&pdbc); if(ret ==0){ if(pdbc.clk_pre_scl == clk_pre_scl){ return true; } } pdbc.clk_pre_scl = clk_pre_scl; ret = sw_gpio_eint_set_debounce(CTP_IRQ_NUMBER,pdbc); if(ret != 0){ return false; } return true; } EXPORT_SYMBOL(ctp_set_int_port_deb); void ctp_free_platform_resource(void) { gpio_free(config_info.wakeup_gpio_number); #ifdef TOUCH_KEY_LIGHT_SUPPORT gpio_free(config_info.key_light_gpio_number); #endif return; } EXPORT_SYMBOL(ctp_free_platform_resource); /** * ctp_init_platform_resource - initialize platform related resource * return value: 0 : success * -EIO : i/o err. * */ int ctp_init_platform_resource(void) { int ret = -1; script_item_u item; script_item_value_type_e type; type = script_get_item("ctp_para", "ctp_wakeup", &item); if(SCIRPT_ITEM_VALUE_TYPE_PIO != type) { printk("script_get_item ctp_wakeup err\n"); return -1; } config_info.wakeup_gpio_number = item.gpio.gpio; type = script_get_item("ctp_para", "ctp_int_port", &item); if(SCIRPT_ITEM_VALUE_TYPE_PIO != type) { printk("script_get_item ctp_int_port type err\n"); return -1; } config_info.irq_gpio_number = item.gpio.gpio; #ifdef TOUCH_KEY_LIGHT_SUPPORT type = script_get_item("ctp_para", "ctp_light", &item); if(SCIRPT_ITEM_VALUE_TYPE_PIO != type) { printk("script_get_item ctp_light err\n"); return -1; } config_info.key_light_gpio_number = item.gpio.gpio; ret = gpio_request_one(config_info.key_light_gpio_number,GPIOF_OUT_INIT_HIGH,NULL); if(ret != 0){ printk("key_light pin set to output function failure!\n"); } #endif ret = gpio_request_one(config_info.wakeup_gpio_number,GPIOF_OUT_INIT_HIGH,NULL); if(ret != 0){ printk("wakeup pin set to output function failure!\n"); } return 0; } EXPORT_SYMBOL(ctp_init_platform_resource); void ctp_print_info(struct ctp_config_info info,int debug_level) { if(debug_level == DEBUG_INIT) { dprintk(DEBUG_INIT,"info.ctp_used:%d\n",info.ctp_used); dprintk(DEBUG_INIT,"info.twi_id:%d\n",info.twi_id); dprintk(DEBUG_INIT,"info.screen_max_x:%d\n",info.screen_max_x); dprintk(DEBUG_INIT,"info.screen_max_y:%d\n",info.screen_max_y); dprintk(DEBUG_INIT,"info.revert_x_flag:%d\n",info.revert_x_flag); dprintk(DEBUG_INIT,"info.revert_y_flag:%d\n",info.revert_y_flag); dprintk(DEBUG_INIT,"info.exchange_x_y_flag:%d\n",info.exchange_x_y_flag); dprintk(DEBUG_INIT,"info.irq_gpio_number:%d\n",info.irq_gpio_number); dprintk(DEBUG_INIT,"info.wakeup_gpio_number:%d\n",info.wakeup_gpio_number); } } EXPORT_SYMBOL(ctp_print_info); /** * ctp_fetch_sysconfig_para - get config info from sysconfig.fex file. * return value: * = 0; success; * < 0; err */ static int ctp_fetch_sysconfig_para(void) { int ret = -1; script_item_u val; if(debug_mask == DEBUG_OTHERS_INFO){ script_dump_mainkey("ctp_para"); } pr_info("=====%s=====. \n", __func__); if(SCIRPT_ITEM_VALUE_TYPE_INT != script_get_item("ctp_para", "ctp_used", &val)){ pr_err("%s: ctp_used script_get_item err. \n", __func__); goto script_get_item_err; } config_info.ctp_used = val.val; if(1 != config_info.ctp_used){ pr_err("%s: ctp_unused. \n", __func__); return ret; } if(SCIRPT_ITEM_VALUE_TYPE_INT != script_get_item("ctp_para", "ctp_twi_id", &val)){ pr_err("%s: ctp_twi_id script_get_item err. \n",__func__ ); goto script_get_item_err; } config_info.twi_id = val.val; if(SCIRPT_ITEM_VALUE_TYPE_INT != script_get_item("ctp_para", "ctp_screen_max_x", &val)){ pr_err("%s: ctp_screen_max_x script_get_item err. \n",__func__ ); goto script_get_item_err; } config_info.screen_max_x = val.val; if(SCIRPT_ITEM_VALUE_TYPE_INT != script_get_item("ctp_para", "ctp_screen_max_y", &val)){ pr_err("%s: ctp_screen_max_y script_get_item err. \n",__func__ ); goto script_get_item_err; } config_info.screen_max_y = val.val; if(SCIRPT_ITEM_VALUE_TYPE_INT != script_get_item("ctp_para", "ctp_revert_x_flag", &val)){ pr_err("%s: ctp_revert_x_flag script_get_item err. \n",__func__ ); goto script_get_item_err; } config_info.revert_x_flag = val.val; if(SCIRPT_ITEM_VALUE_TYPE_INT != script_get_item("ctp_para", "ctp_revert_y_flag", &val)){ pr_err("%s: ctp_revert_y_flag script_get_item err. \n",__func__ ); goto script_get_item_err; } config_info.revert_y_flag = val.val; if(SCIRPT_ITEM_VALUE_TYPE_INT != script_get_item("ctp_para", "ctp_exchange_x_y_flag", &val)){ pr_err("%s: ctp_exchange_x_y_flag script_get_item err. \n",__func__ ); goto script_get_item_err; } config_info.exchange_x_y_flag = val.val; return 0; script_get_item_err: pr_notice("=========script_get_item_err============\n"); return ret; } /** * ctp_wakeup - function * */ int ctp_wakeup(int status,int ms) { u32 gpio_status; dprintk(DEBUG_INIT,"***CTP*** %s:status:%d,ms = %d\n",__func__,status,ms); gpio_status = sw_gpio_getcfg(config_info.wakeup_gpio_number); if(gpio_status != 1){ sw_gpio_setcfg(config_info.wakeup_gpio_number,1); } if(status == 0){ if(ms == 0) { __gpio_set_value(config_info.wakeup_gpio_number, 0); }else { __gpio_set_value(config_info.wakeup_gpio_number, 0); msleep(ms); __gpio_set_value(config_info.wakeup_gpio_number, 1); } } if(status == 1){ if(ms == 0) { __gpio_set_value(config_info.wakeup_gpio_number, 1); }else { __gpio_set_value(config_info.wakeup_gpio_number, 1); msleep(ms); __gpio_set_value(config_info.wakeup_gpio_number, 0); } } msleep(5); if(gpio_status != 1){ sw_gpio_setcfg(config_info.wakeup_gpio_number,gpio_status); } return 0; } EXPORT_SYMBOL(ctp_wakeup); /** * ctp_key_light - function * */ #ifdef TOUCH_KEY_LIGHT_SUPPORT int ctp_key_light(int status,int ms) { u32 gpio_status; dprintk(DEBUG_INIT,"***CTP*** %s:status:%d,ms = %d\n",__func__,status,ms); gpio_status = sw_gpio_getcfg(config_info.key_light_gpio_number); if(gpio_status != 1){ sw_gpio_setcfg(config_info.key_light_gpio_number,1); } if(status == 0){ if(ms == 0) { __gpio_set_value(config_info.key_light_gpio_number, 0); }else { __gpio_set_value(config_info.key_light_gpio_number, 0); msleep(ms); __gpio_set_value(config_info.key_light_gpio_number, 1); } } if(status == 1){ if(ms == 0) { __gpio_set_value(config_info.key_light_gpio_number, 1); }else{ __gpio_set_value(config_info.key_light_gpio_number, 1); msleep(ms); __gpio_set_value(config_info.key_light_gpio_number, 0); } } msleep(10); if(gpio_status != 1){ sw_gpio_setcfg(config_info.key_light_gpio_number,gpio_status); } return 0; } EXPORT_SYMBOL(ctp_key_light); #endif static int __init ctp_init(void) { int err = -1; if (ctp_fetch_sysconfig_para()){ printk("%s: ctp_fetch_sysconfig_para err.\n", __func__); return 0; }else{ err = ctp_init_platform_resource(); if(0 != err){ printk("%s:ctp_ops.init_platform_resource err. \n", __func__); } } ctp_print_info(config_info,DEBUG_INIT); return 0; } static void __exit ctp_exit(void) { ctp_free_platform_resource(); return; } module_init(ctp_init); module_exit(ctp_exit); module_param_named(debug_mask,debug_mask,int,S_IRUGO | S_IWUSR | S_IWGRP); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("ctp init"); MODULE_AUTHOR("Olina yin"); MODULE_ALIAS("platform:AW");
mozilla-b2g/kernel_flatfish
drivers/input/init_ctp.c
C
gpl-2.0
12,535
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "DatabaseEnv.h" #include "WorldPacket.h" #include "WorldSession.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Opcodes.h" #include "Log.h" #include "UpdateMask.h" #include "World.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Player.h" #include "Pet.h" #include "Unit.h" #include "Totem.h" #include "Spell.h" #include "DynamicObject.h" #include "Group.h" #include "UpdateData.h" #include "MapManager.h" #include "ObjectAccessor.h" #include "CellImpl.h" #include "SharedDefines.h" #include "LootMgr.h" #include "VMapFactory.h" #include "Battleground.h" #include "Util.h" #include "TemporarySummon.h" #include "Vehicle.h" #include "SpellAuraEffects.h" #include "ScriptMgr.h" #include "ConditionMgr.h" #include "DisableMgr.h" #include "SpellScript.h" #define SPELL_CHANNEL_UPDATE_INTERVAL (1 * IN_MILLISECONDS) extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS]; bool IsQuestTameSpell(uint32 spellId) { SpellEntry const *spellproto = sSpellStore.LookupEntry(spellId); if (!spellproto) return false; return spellproto->Effect[0] == SPELL_EFFECT_THREAT && spellproto->Effect[1] == SPELL_EFFECT_APPLY_AURA && spellproto->EffectApplyAuraName[1] == SPELL_AURA_DUMMY; } SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0) { m_unitTarget = NULL; m_itemTarget = NULL; m_GOTarget = NULL; m_unitTargetGUID = 0; m_GOTargetGUID = 0; m_CorpseTargetGUID = 0; m_itemTargetGUID = 0; m_itemTargetEntry = 0; m_srcTransGUID = 0; m_srcTransOffset.Relocate(0, 0, 0, 0); m_srcPos.Relocate(0, 0, 0, 0); m_dstTransGUID = 0; m_dstTransOffset.Relocate(0, 0, 0, 0); m_dstPos.Relocate(0, 0, 0, 0); m_strTarget = ""; m_targetMask = 0; } SpellCastTargets::~SpellCastTargets() { } void SpellCastTargets::setUnitTarget(Unit *target) { if (!target) return; m_unitTarget = target; m_unitTargetGUID = target->GetGUID(); m_targetMask |= TARGET_FLAG_UNIT; } void SpellCastTargets::setSrc(float x, float y, float z) { m_srcPos.Relocate(x, y, z); m_srcTransGUID = 0; m_targetMask |= TARGET_FLAG_SOURCE_LOCATION; } void SpellCastTargets::setSrc(Position &pos) { m_srcPos.Relocate(pos); m_srcTransGUID = 0; m_targetMask |= TARGET_FLAG_SOURCE_LOCATION; } void SpellCastTargets::setSrc(WorldObject &wObj) { uint64 guid = wObj.GetTransGUID(); m_srcTransGUID = guid; m_srcTransOffset.Relocate(wObj.GetTransOffsetX(), wObj.GetTransOffsetY(), wObj.GetTransOffsetZ(), wObj.GetTransOffsetO()); m_srcPos.Relocate(wObj); m_targetMask |= TARGET_FLAG_SOURCE_LOCATION; } void SpellCastTargets::modSrc(Position &pos) { ASSERT(m_targetMask & TARGET_FLAG_SOURCE_LOCATION); if (m_srcTransGUID) { Position offset; m_srcPos.GetPositionOffsetTo(pos, offset); m_srcTransOffset.RelocateOffset(offset); } m_srcPos.Relocate(pos); } void SpellCastTargets::setDst(float x, float y, float z, float orientation, uint32 mapId) { m_dstPos.Relocate(x, y, z, orientation); m_dstTransGUID = 0; m_targetMask |= TARGET_FLAG_DEST_LOCATION; if (mapId != MAPID_INVALID) m_dstPos.m_mapId = mapId; } void SpellCastTargets::setDst(Position &pos) { m_dstPos.Relocate(pos); m_dstTransGUID = 0; m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::setDst(WorldObject &wObj) { uint64 guid = wObj.GetTransGUID(); m_dstTransGUID = guid; m_dstTransOffset.Relocate(wObj.GetTransOffsetX(), wObj.GetTransOffsetY(), wObj.GetTransOffsetZ(), wObj.GetTransOffsetO()); m_dstPos.Relocate(wObj); m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::setDst(SpellCastTargets &spellTargets) { m_dstTransGUID = spellTargets.m_dstTransGUID; m_dstTransOffset.Relocate(spellTargets.m_dstTransOffset); m_dstPos.Relocate(spellTargets.m_dstPos); m_targetMask |= TARGET_FLAG_DEST_LOCATION; } void SpellCastTargets::modDst(Position &pos) { ASSERT(m_targetMask & TARGET_FLAG_DEST_LOCATION); if (m_dstTransGUID) { Position offset; m_dstPos.GetPositionOffsetTo(pos, offset); m_dstTransOffset.RelocateOffset(offset); } m_dstPos.Relocate(pos); } void SpellCastTargets::setGOTarget(GameObject *target) { m_GOTarget = target; m_GOTargetGUID = target->GetGUID(); m_targetMask |= TARGET_FLAG_OBJECT; } void SpellCastTargets::setItemTarget(Item* item) { if (!item) return; m_itemTarget = item; m_itemTargetGUID = item->GetGUID(); m_itemTargetEntry = item->GetEntry(); m_targetMask |= TARGET_FLAG_ITEM; } void SpellCastTargets::setTradeItemTarget(Player* caster) { m_itemTargetGUID = uint64(TRADE_SLOT_NONTRADED); m_itemTargetEntry = 0; m_targetMask |= TARGET_FLAG_TRADE_ITEM; Update(caster); } void SpellCastTargets::setCorpseTarget(Corpse* corpse) { m_CorpseTargetGUID = corpse->GetGUID(); } void SpellCastTargets::Update(Unit* caster) { m_GOTarget = m_GOTargetGUID ? caster->GetMap()->GetGameObject(m_GOTargetGUID) : NULL; m_unitTarget = m_unitTargetGUID ? (m_unitTargetGUID == caster->GetGUID() ? caster : ObjectAccessor::GetUnit(*caster, m_unitTargetGUID)) : NULL; m_itemTarget = NULL; if (caster->GetTypeId() == TYPEID_PLAYER) { Player *player = caster->ToPlayer(); if (m_targetMask & TARGET_FLAG_ITEM) m_itemTarget = player->GetItemByGuid(m_itemTargetGUID); else if (m_targetMask & TARGET_FLAG_TRADE_ITEM) if (m_itemTargetGUID == TRADE_SLOT_NONTRADED) // here it is not guid but slot. Also prevents hacking slots if (TradeData* pTrade = player->GetTradeData()) m_itemTarget = pTrade->GetTraderData()->GetItem(TRADE_SLOT_NONTRADED); if (m_itemTarget) m_itemTargetEntry = m_itemTarget->GetEntry(); } // update positions by transport move if (HasSrc() && m_srcTransGUID) { if (WorldObject * transport = ObjectAccessor::GetWorldObject(*caster, m_srcTransGUID)) { m_srcPos.Relocate(transport); m_srcPos.RelocateOffset(m_srcTransOffset); } } if (HasDst() && m_dstTransGUID) { if (WorldObject * transport = ObjectAccessor::GetWorldObject(*caster, m_dstTransGUID)) { m_dstPos.Relocate(transport); m_dstPos.RelocateOffset(m_dstTransOffset); } } } void SpellCastTargets::OutDebug() { if (!m_targetMask) sLog->outString("TARGET_FLAG_SELF"); if (m_targetMask & TARGET_FLAG_UNIT) { sLog->outString("TARGET_FLAG_UNIT: " UI64FMTD, m_unitTargetGUID); } if (m_targetMask & TARGET_FLAG_UNK17) { sLog->outString("TARGET_FLAG_UNK17: " UI64FMTD, m_unitTargetGUID); } if (m_targetMask & TARGET_FLAG_OBJECT) { sLog->outString("TARGET_FLAG_OBJECT: " UI64FMTD, m_GOTargetGUID); } if (m_targetMask & TARGET_FLAG_CORPSE) { sLog->outString("TARGET_FLAG_CORPSE: " UI64FMTD, m_CorpseTargetGUID); } if (m_targetMask & TARGET_FLAG_PVP_CORPSE) { sLog->outString("TARGET_FLAG_PVP_CORPSE: " UI64FMTD, m_CorpseTargetGUID); } if (m_targetMask & TARGET_FLAG_ITEM) { sLog->outString("TARGET_FLAG_ITEM: " UI64FMTD, m_itemTargetGUID); } if (m_targetMask & TARGET_FLAG_TRADE_ITEM) { sLog->outString("TARGET_FLAG_TRADE_ITEM: " UI64FMTD, m_itemTargetGUID); } if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) { sLog->outString("TARGET_FLAG_SOURCE_LOCATION: transport guid:" UI64FMTD " trans offset: %s position: %s", m_srcTransGUID, m_srcTransOffset.ToString().c_str(), m_srcPos.ToString().c_str()); } if (m_targetMask & TARGET_FLAG_DEST_LOCATION) { sLog->outString("TARGET_FLAG_DEST_LOCATION: transport guid:" UI64FMTD " trans offset: %s position: %s", m_dstTransGUID, m_dstTransOffset.ToString().c_str(), m_dstPos.ToString().c_str()); } if (m_targetMask & TARGET_FLAG_STRING) { sLog->outString("TARGET_FLAG_STRING: %s", m_strTarget.c_str()); } sLog->outString("speed: %f", m_speed); sLog->outString("elevation: %f", m_elevation); } void SpellCastTargets::read (ByteBuffer & data, Unit * caster) { data >> m_targetMask; if (m_targetMask == TARGET_FLAG_SELF) return; if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_UNK17)) data.readPackGUID(m_unitTargetGUID); if (m_targetMask & (TARGET_FLAG_OBJECT)) data.readPackGUID(m_GOTargetGUID); if(m_targetMask & (TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM)) data.readPackGUID(m_itemTargetGUID); if(m_targetMask & (TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE)) data.readPackGUID(m_CorpseTargetGUID); if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) { data.readPackGUID(m_srcTransGUID); if (m_srcTransGUID) data >> m_srcTransOffset.PositionXYZStream(); else data >> m_srcPos.PositionXYZStream(); } else { m_srcTransGUID = caster->GetTransGUID(); if (m_srcTransGUID) m_srcTransOffset.Relocate(caster->GetTransOffsetX(), caster->GetTransOffsetY(), caster->GetTransOffsetZ(), caster->GetTransOffsetO()); else m_srcPos.Relocate(caster); } if (m_targetMask & TARGET_FLAG_DEST_LOCATION) { data.readPackGUID(m_dstTransGUID); if (m_dstTransGUID) data >> m_dstTransOffset.PositionXYZStream(); else data >> m_dstPos.PositionXYZStream(); } else { m_dstTransGUID = caster->GetTransGUID(); if (m_dstTransGUID) m_dstTransOffset.Relocate(caster->GetTransOffsetX(), caster->GetTransOffsetY(), caster->GetTransOffsetZ(), caster->GetTransOffsetO()); else m_dstPos.Relocate(caster); } if(m_targetMask & TARGET_FLAG_STRING) data >> m_strTarget; Update(caster); } void SpellCastTargets::write (ByteBuffer & data) { data << uint32(m_targetMask); if (m_targetMask & (TARGET_FLAG_UNIT | TARGET_FLAG_PVP_CORPSE | TARGET_FLAG_OBJECT | TARGET_FLAG_CORPSE | TARGET_FLAG_UNK17)) { if (m_targetMask & TARGET_FLAG_UNIT) { if (m_unitTarget) data.append(m_unitTarget->GetPackGUID()); else data << uint8(0); } else if (m_targetMask & TARGET_FLAG_OBJECT) { if(m_GOTarget) data.append(m_GOTarget->GetPackGUID()); else data << uint8(0); } else if (m_targetMask & ( TARGET_FLAG_CORPSE | TARGET_FLAG_PVP_CORPSE)) data.appendPackGUID(m_CorpseTargetGUID); else data << uint8(0); } if (m_targetMask & ( TARGET_FLAG_ITEM | TARGET_FLAG_TRADE_ITEM)) { if(m_itemTarget) data.append(m_itemTarget->GetPackGUID()); else data << uint8(0); } if (m_targetMask & TARGET_FLAG_SOURCE_LOCATION) { data.appendPackGUID(m_srcTransGUID); // relative position guid here - transport for example if (m_srcTransGUID) data << m_srcTransOffset.PositionXYZStream(); else data << m_srcPos.PositionXYZStream(); } if (m_targetMask & TARGET_FLAG_DEST_LOCATION) { data.appendPackGUID(m_dstTransGUID); // relative position guid here - transport for example if (m_dstTransGUID) data << m_dstTransOffset.PositionXYZStream(); else data << m_dstPos.PositionXYZStream(); } if (m_targetMask & TARGET_FLAG_STRING) data << m_strTarget; } Spell::Spell(Unit* Caster, SpellEntry const *info, bool triggered, uint64 originalCasterGUID, bool skipCheck): m_spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(info, Caster)), m_caster(Caster), m_spellValue(new SpellValue(m_spellInfo)) { m_customAttr = sSpellMgr->GetSpellCustomAttr(m_spellInfo->Id); m_skipCheck = skipCheck; m_selfContainer = NULL; m_referencedFromCurrentSpell = false; m_executedCurrently = false; m_needComboPoints = NeedsComboPoints(m_spellInfo); m_comboPointGain = 0; m_delayStart = 0; m_delayAtDamageCount = 0; m_applyMultiplierMask = 0; m_effectMask = 0; m_auraScaleMask = 0; // Get data for type of attack switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MELEE: if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQ_OFFHAND) m_attackType = OFF_ATTACK; else m_attackType = BASE_ATTACK; break; case SPELL_DAMAGE_CLASS_RANGED: m_attackType = IsRangedWeaponSpell(m_spellInfo) ? RANGED_ATTACK : BASE_ATTACK; break; default: // Wands if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) m_attackType = RANGED_ATTACK; else m_attackType = BASE_ATTACK; break; } m_spellSchoolMask = GetSpellSchoolMask(info); // Can be override for some spell (wand shoot for example) if (m_attackType == RANGED_ATTACK) { // wand case if ((m_caster->getClassMask() & CLASSMASK_WAND_USERS) != 0 && m_caster->GetTypeId() == TYPEID_PLAYER) { if (Item* pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK)) m_spellSchoolMask = SpellSchoolMask(1 << pItem->GetProto()->Damage[0].DamageType); } } if (originalCasterGUID) m_originalCasterGUID = originalCasterGUID; else m_originalCasterGUID = m_caster->GetGUID(); if (m_originalCasterGUID == m_caster->GetGUID()) m_originalCaster = m_caster; else { m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL; } m_spellState = SPELL_STATE_NULL; m_IsTriggeredSpell = bool(triggered || (info->AttributesEx4 & SPELL_ATTR4_TRIGGERED)); m_CastItem = NULL; unitTarget = NULL; itemTarget = NULL; gameObjTarget = NULL; focusObject = NULL; m_cast_count = 0; m_glyphIndex = 0; m_preCastSpell = 0; m_triggeredByAuraSpell = NULL; m_spellAura = NULL; //Auto Shot & Shoot (wand) m_autoRepeat = IsAutoRepeatRangedSpell(m_spellInfo); m_runesState = 0; m_powerCost = 0; // setup to correct value in Spell::prepare, don't must be used before. m_casttime = 0; // setup to correct value in Spell::prepare, don't must be used before. m_timer = 0; // will set to castime in prepare m_channelTargetEffectMask = 0; // determine reflection m_canReflect = false; if (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC && !IsAreaOfEffectSpell(m_spellInfo) && !(m_spellInfo->AttributesEx2 & SPELL_ATTR2_CANT_REFLECTED)) { for (int j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (m_spellInfo->Effect[j] == 0) continue; if (!IsPositiveTarget(m_spellInfo->EffectImplicitTargetA[j], m_spellInfo->EffectImplicitTargetB[j])) m_canReflect = true; else m_canReflect = (m_spellInfo->AttributesEx & SPELL_ATTR1_NEGATIVE) ? true : false; if (m_canReflect) continue; else break; } } CleanupTargetList(); CleanupEffectExecuteData(); } Spell::~Spell() { // unload scripts while(!m_loadedScripts.empty()) { std::list<SpellScript *>::iterator itr = m_loadedScripts.begin(); (*itr)->_Unload(); delete (*itr); m_loadedScripts.erase(itr); } if (m_referencedFromCurrentSpell && m_selfContainer && *m_selfContainer == this) { // Clean the reference to avoid later crash. // If this error is repeating, we may have to add an ASSERT to better track down how we get into this case. sLog->outError("SPELL: deleting spell for spell ID %u. However, spell still referenced.", m_spellInfo->Id); *m_selfContainer = NULL; } if (m_caster && m_caster->GetTypeId() == TYPEID_PLAYER) ASSERT(m_caster->ToPlayer()->m_spellModTakingSpell != this); delete m_spellValue; CheckEffectExecuteData(); } template<typename T> WorldObject* Spell::FindCorpseUsing() { // non-standard target selection float max_range = GetSpellMaxRange(m_spellInfo, false); CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY())); Cell cell(p); cell.data.Part.reserved = ALL_DISTRICT; cell.SetNoCreate(); WorldObject* result = NULL; T u_check(m_caster, max_range); Trinity::WorldObjectSearcher<T> searcher(m_caster, result, u_check); TypeContainerVisitor<Trinity::WorldObjectSearcher<T>, GridTypeMapContainer > grid_searcher(searcher); cell.Visit(p, grid_searcher, *m_caster->GetMap(), *m_caster, max_range); if (!result) { TypeContainerVisitor<Trinity::WorldObjectSearcher<T>, WorldTypeMapContainer > world_searcher(searcher); cell.Visit(p, world_searcher, *m_caster->GetMap(), *m_caster, max_range); } return result; } void Spell::SelectSpellTargets() { for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { // not call for empty effect. // Also some spells use not used effect targets for store targets for dummy effect in triggered spells if (!m_spellInfo->Effect[i]) continue; uint32 effectTargetType = EffectTargetType[m_spellInfo->Effect[i]]; // is it possible that areaaura is not applied to caster? if (effectTargetType == SPELL_REQUIRE_NONE) continue; uint32 targetA = m_spellInfo->EffectImplicitTargetA[i]; uint32 targetB = m_spellInfo->EffectImplicitTargetB[i]; if (targetA) SelectEffectTargets(i, targetA); if (targetB) // In very rare case !A && B SelectEffectTargets(i, targetB); if (effectTargetType != SPELL_REQUIRE_UNIT) { if (effectTargetType == SPELL_REQUIRE_CASTER) AddUnitTarget(m_caster, i); else if (effectTargetType == SPELL_REQUIRE_ITEM) { if (m_targets.getItemTarget()) AddItemTarget(m_targets.getItemTarget(), i); } continue; } if (!targetA && !targetB) { if (!GetSpellMaxRangeForFriend(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex))) { AddUnitTarget(m_caster, i); continue; } // add here custom effects that need default target. // FOR EVERY TARGET TYPE THERE IS A DIFFERENT FILL!! switch(m_spellInfo->Effect[i]) { case SPELL_EFFECT_DUMMY: { switch(m_spellInfo->Id) { case 20577: // Cannibalize case 54044: // Carrion Feeder { WorldObject* result = NULL; if (m_spellInfo->Id == 20577) result = FindCorpseUsing<Trinity::CannibalizeObjectCheck>(); else result = FindCorpseUsing<Trinity::CarrionFeederObjectCheck>(); if (result) { switch(result->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: AddUnitTarget((Unit*)result, i); break; case TYPEID_CORPSE: m_targets.setCorpseTarget((Corpse*)result); if (Player* owner = ObjectAccessor::FindPlayer(((Corpse*)result)->GetOwnerGUID())) AddUnitTarget(owner, i); break; default: break; } } else { // clear cooldown at fail if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true); SendCastResult(SPELL_FAILED_NO_EDIBLE_CORPSES); finish(false); } break; } default: if (m_targets.getUnitTarget()) AddUnitTarget(m_targets.getUnitTarget(), i); else AddUnitTarget(m_caster, i); break; } break; } case SPELL_EFFECT_BIND: case SPELL_EFFECT_RESURRECT: case SPELL_EFFECT_CREATE_ITEM: case SPELL_EFFECT_TRIGGER_SPELL: case SPELL_EFFECT_SKILL_STEP: case SPELL_EFFECT_PROFICIENCY: case SPELL_EFFECT_SUMMON_OBJECT_WILD: case SPELL_EFFECT_SELF_RESURRECT: case SPELL_EFFECT_REPUTATION: case SPELL_EFFECT_LEARN_SPELL: case SPELL_EFFECT_SEND_TAXI: if (m_targets.getUnitTarget()) AddUnitTarget(m_targets.getUnitTarget(), i); // Triggered spells have additional spell targets - cast them even if no explicit unit target is given (required for spell 50516 for example) else if (m_spellInfo->Effect[i] == SPELL_EFFECT_TRIGGER_SPELL) AddUnitTarget(m_caster, i); break; case SPELL_EFFECT_SUMMON_PLAYER: if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->GetSelection()) { Player* target = sObjectMgr->GetPlayer(m_caster->ToPlayer()->GetSelection()); if (target) AddUnitTarget(target, i); } break; case SPELL_EFFECT_RESURRECT_NEW: if (m_targets.getUnitTarget()) AddUnitTarget(m_targets.getUnitTarget(), i); if (m_targets.getCorpseTargetGUID()) { Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID()); if (corpse) { Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID()); if (owner) AddUnitTarget(owner, i); } } break; case SPELL_EFFECT_SUMMON_CHANGE_ITEM: case SPELL_EFFECT_ADD_FARSIGHT: case SPELL_EFFECT_APPLY_GLYPH: case SPELL_EFFECT_STUCK: case SPELL_EFFECT_FEED_PET: case SPELL_EFFECT_DESTROY_ALL_TOTEMS: case SPELL_EFFECT_KILL_CREDIT2: // only one spell: 42793 AddUnitTarget(m_caster, i); break; case SPELL_EFFECT_LEARN_PET_SPELL: if (Guardian* pet = m_caster->GetGuardianPet()) AddUnitTarget(pet, i); break; /*case SPELL_EFFECT_ENCHANT_ITEM: case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY: case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC: case SPELL_EFFECT_DISENCHANT: case SPELL_EFFECT_PROSPECTING: case SPELL_EFFECT_MILLING: if (m_targets.getItemTarget()) AddItemTarget(m_targets.getItemTarget(), i); break;*/ case SPELL_EFFECT_APPLY_AURA: switch(m_spellInfo->EffectApplyAuraName[i]) { case SPELL_AURA_ADD_FLAT_MODIFIER: // some spell mods auras have 0 target modes instead expected TARGET_UNIT_CASTER(1) (and present for other ranks for same spell for example) case SPELL_AURA_ADD_PCT_MODIFIER: AddUnitTarget(m_caster, i); break; default: // apply to target in other case break; } break; case SPELL_EFFECT_APPLY_AREA_AURA_PARTY: // AreaAura if (m_spellInfo->Attributes & (SPELL_ATTR0_CASTABLE_WHILE_SITTING | SPELL_ATTR0_CASTABLE_WHILE_MOUNTED | SPELL_ATTR0_UNK18 | SPELL_ATTR0_NOT_SHAPESHIFT) || m_spellInfo->Attributes == SPELL_ATTR0_NOT_SHAPESHIFT) SelectEffectTargets(i, TARGET_UNIT_PARTY_TARGET); break; case SPELL_EFFECT_SKIN_PLAYER_CORPSE: if (m_targets.getUnitTarget()) { AddUnitTarget(m_targets.getUnitTarget(), i); } else if (m_targets.getCorpseTargetGUID()) { Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster,m_targets.getCorpseTargetGUID()); if (corpse) { Player* owner = ObjectAccessor::FindPlayer(corpse->GetOwnerGUID()); if (owner) AddUnitTarget(owner, i); } } break; default: AddUnitTarget(m_caster, i); break; } } if (IsChanneledSpell(m_spellInfo)) { uint8 mask = (1<<i); for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->effectMask & mask) { m_channelTargetEffectMask |= mask; break; } } } else if (m_auraScaleMask) { bool checkLvl = !m_UniqueTargetInfo.empty(); for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end();) { // remove targets which did not pass min level check if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask) { // Do not check for selfcast if (!ihit->scaleAura && ihit->targetGUID != m_caster->GetGUID()) { m_UniqueTargetInfo.erase(ihit++); continue; } } ++ihit; } if (checkLvl && m_UniqueTargetInfo.empty()) { SendCastResult(SPELL_FAILED_LOWLEVEL); finish(false); } } } if (m_targets.HasDst()) { if (m_targets.HasTraj()) { float speed = m_targets.GetSpeedXY(); if (speed > 0.0f) m_delayMoment = (uint64)floor(m_targets.GetDist2d() / speed * 1000.0f); } else if (m_spellInfo->speed > 0.0f) { float dist = m_caster->GetDistance(m_targets.m_dstPos); m_delayMoment = (uint64) floor(dist / m_spellInfo->speed * 1000.0f); } } } void Spell::prepareDataForTriggerSystem(AuraEffect const * /*triggeredByAura*/) { //========================================================================================== // Now fill data for trigger system, need know: // can spell trigger another or not (m_canTrigger) // Create base triggers flags for Attacker and Victim (m_procAttacker, m_procVictim and m_procEx) //========================================================================================== m_procVictim = m_procAttacker = 0; // Get data for type of attack and fill base info for trigger switch (m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MELEE: m_procAttacker = PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS; if (m_attackType == OFF_ATTACK) m_procAttacker |= PROC_FLAG_DONE_OFFHAND_ATTACK; else m_procAttacker |= PROC_FLAG_DONE_MAINHAND_ATTACK; m_procVictim = PROC_FLAG_TAKEN_MELEE_AUTO_ATTACK; break; case SPELL_DAMAGE_CLASS_RANGED: // Auto attack if (m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) { m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; } else // Ranged spell attack { m_procAttacker = PROC_FLAG_DONE_SPELL_RANGED_DMG_CLASS; m_procVictim = PROC_FLAG_TAKEN_SPELL_RANGED_DMG_CLASS; } break; default: if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && m_spellInfo->EquippedItemSubClassMask & (1<<ITEM_SUBCLASS_WEAPON_WAND) && m_spellInfo->AttributesEx2 & SPELL_ATTR2_AUTOREPEAT_FLAG) // Wands auto attack { m_procAttacker = PROC_FLAG_DONE_RANGED_AUTO_ATTACK; m_procVictim = PROC_FLAG_TAKEN_RANGED_AUTO_ATTACK; } // For other spells trigger procflags are set in Spell::DoAllEffectOnTarget // Because spell positivity is dependant on target } m_procEx= PROC_EX_NONE; // Hunter trap spells - activation proc for Lock and Load, Entrapment and Misdirection if (m_spellInfo->SpellFamilyName == SPELLFAMILY_HUNTER && (m_spellInfo->SpellFamilyFlags[0] & 0x18 || // Freezing and Frost Trap, Freezing Arrow m_spellInfo->Id == 57879 || // Snake Trap - done this way to avoid double proc m_spellInfo->SpellFamilyFlags[2] & 0x00024000)) // Explosive and Immolation Trap m_procAttacker |= PROC_FLAG_DONE_TRAP_ACTIVATION; /* Effects which are result of aura proc from triggered spell cannot proc to prevent chain proc of these spells */ // Hellfire Effect - trigger as DOT if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[0] & 0x00000040) { m_procAttacker = PROC_FLAG_DONE_PERIODIC; m_procVictim = PROC_FLAG_TAKEN_PERIODIC; } // Ranged autorepeat attack is set as triggered spell - ignore it if (!(m_procAttacker & PROC_FLAG_DONE_RANGED_AUTO_ATTACK)) { if (m_IsTriggeredSpell && (m_spellInfo->AttributesEx2 & SPELL_ATTR2_TRIGGERED_CAN_TRIGGER || m_spellInfo->AttributesEx3 & SPELL_ATTR3_TRIGGERED_CAN_TRIGGER_2)) m_procEx |= PROC_EX_INTERNAL_CANT_PROC; else if (m_IsTriggeredSpell) m_procEx |= PROC_EX_INTERNAL_TRIGGERED; } // Totem casts require spellfamilymask defined in spell_proc_event to proc if (m_originalCaster && m_caster != m_originalCaster && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isTotem() && m_caster->IsControlledByPlayer()) { m_procEx |= PROC_EX_INTERNAL_REQ_FAMILY; } } void Spell::CleanupTargetList() { m_UniqueTargetInfo.clear(); m_UniqueGOTargetInfo.clear(); m_UniqueItemInfo.clear(); m_delayMoment = 0; } void Spell::AddUnitTarget(Unit* pVictim, uint32 effIndex) { if (m_spellInfo->Effect[effIndex] == 0) return; if (!CheckTarget(pVictim, effIndex)) return; // Check for effect immune skip if immuned bool immuned = pVictim->IsImmunedToSpellEffect(m_spellInfo, effIndex); uint64 targetGUID = pVictim->GetGUID(); // Lookup target in already in list for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (targetGUID == ihit->targetGUID) // Found in list { if (!immuned) ihit->effectMask |= 1 << effIndex; // Add only effect mask if not immuned ihit->scaleAura = false; if (m_auraScaleMask && ihit->effectMask == m_auraScaleMask && m_caster != pVictim) { SpellEntry const * auraSpell = sSpellStore.LookupEntry(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id)); if (uint32(pVictim->getLevel() + 10) >= auraSpell->spellLevel) ihit->scaleAura = true; } return; } } // This is new target calculate data for him // Get spell hit result on target TargetInfo target; target.targetGUID = targetGUID; // Store target GUID target.effectMask = immuned ? 0 : 1 << effIndex; // Store index of effect if not immuned target.processed = false; // Effects not apply on target target.alive = pVictim->isAlive(); target.damage = 0; target.crit = false; target.scaleAura = false; if (m_auraScaleMask && target.effectMask == m_auraScaleMask && m_caster != pVictim) { SpellEntry const * auraSpell = sSpellStore.LookupEntry(sSpellMgr->GetFirstSpellInChain(m_spellInfo->Id)); if (uint32(pVictim->getLevel() + 10) >= auraSpell->spellLevel) target.scaleAura = true; } // Calculate hit result if (m_originalCaster) { target.missCondition = m_originalCaster->SpellHitResult(pVictim, m_spellInfo, m_canReflect); if (m_skipCheck && target.missCondition != SPELL_MISS_IMMUNE) target.missCondition = SPELL_MISS_NONE; } else target.missCondition = SPELL_MISS_EVADE; //SPELL_MISS_NONE; // Spell have speed - need calculate incoming time // Incoming time is zero for self casts. At least I think so. if (m_spellInfo->speed > 0.0f && m_caster != pVictim) { // calculate spell incoming interval // TODO: this is a hack float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ()); if (dist < 5.0f) dist = 5.0f; target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f); // Calculate minimum incoming time if (m_delayMoment == 0 || m_delayMoment>target.timeDelay) m_delayMoment = target.timeDelay; } else target.timeDelay = 0LL; // If target reflect spell back to caster if (target.missCondition == SPELL_MISS_REFLECT) { // Calculate reflected spell result on caster target.reflectResult = m_caster->SpellHitResult(m_caster, m_spellInfo, m_canReflect); if (target.reflectResult == SPELL_MISS_REFLECT) // Impossible reflect again, so simply deflect spell target.reflectResult = SPELL_MISS_PARRY; // Increase time interval for reflected spells by 1.5 target.timeDelay += target.timeDelay >> 1; } else target.reflectResult = SPELL_MISS_NONE; // Add target to list m_UniqueTargetInfo.push_back(target); } void Spell::AddUnitTarget(uint64 unitGUID, uint32 effIndex) { if (Unit* unit = m_caster->GetGUID() == unitGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, unitGUID)) AddUnitTarget(unit, effIndex); } void Spell::AddGOTarget(GameObject* pVictim, uint32 effIndex) { if (m_spellInfo->Effect[effIndex] == 0) return; uint64 targetGUID = pVictim->GetGUID(); // Lookup target in already in list for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) { if (targetGUID == ihit->targetGUID) // Found in list { ihit->effectMask |= 1 << effIndex; // Add only effect mask return; } } // This is new target calculate data for him GOTargetInfo target; target.targetGUID = targetGUID; target.effectMask = 1 << effIndex; target.processed = false; // Effects not apply on target // Spell have speed - need calculate incoming time if (m_spellInfo->speed > 0.0f) { // calculate spell incoming interval float dist = m_caster->GetDistance(pVictim->GetPositionX(), pVictim->GetPositionY(), pVictim->GetPositionZ()); if (dist < 5.0f) dist = 5.0f; target.timeDelay = (uint64) floor(dist / m_spellInfo->speed * 1000.0f); if (m_delayMoment == 0 || m_delayMoment>target.timeDelay) m_delayMoment = target.timeDelay; } else target.timeDelay = 0LL; // Add target to list m_UniqueGOTargetInfo.push_back(target); } void Spell::AddGOTarget(uint64 goGUID, uint32 effIndex) { GameObject* go = m_caster->GetMap()->GetGameObject(goGUID); if (go) AddGOTarget(go, effIndex); } void Spell::AddItemTarget(Item* pitem, uint32 effIndex) { if (m_spellInfo->Effect[effIndex] == 0) return; // Lookup target in already in list for (std::list<ItemTargetInfo>::iterator ihit = m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) { if (pitem == ihit->item) // Found in list { ihit->effectMask |= 1<<effIndex; // Add only effect mask return; } } // This is new target add data ItemTargetInfo target; target.item = pitem; target.effectMask = 1 << effIndex; m_UniqueItemInfo.push_back(target); } void Spell::DoAllEffectOnTarget(TargetInfo *target) { if (!target || target->processed) return; target->processed = true; // Target checked in apply effects procedure // Get mask of effects for target uint8 mask = target->effectMask; Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster,target->targetGUID); if (!unit) { uint8 farMask = 0; // create far target mask for(uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (IsFarUnitTargetEffect(m_spellInfo->Effect[i])) if ((1<<i) & mask) farMask |= (1<<i); } if (!farMask) return; // find unit in world unit = ObjectAccessor::FindUnit(target->targetGUID); if (!unit) return; // do far effects on the unit // can't use default call because of threading, do stuff as fast as possible for(uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (farMask & (1<<i)) HandleEffects(unit,NULL,NULL,i); } return; } if (unit->isAlive() != target->alive) return; if (getState() == SPELL_STATE_DELAYED && !IsPositiveSpell(m_spellInfo->Id) && (getMSTime() - target->timeDelay) <= unit->m_lastSanctuaryTime) return; // No missinfo in that case // Get original caster (if exist) and calculate damage/healing from him data Unit *caster = m_originalCaster ? m_originalCaster : m_caster; // Skip if m_originalCaster not avaiable if (!caster) return; SpellMissInfo missInfo = target->missCondition; // Need init unitTarget by default unit (can changed in code on reflect) // Or on missInfo != SPELL_MISS_NONE unitTarget undefined (but need in trigger subsystem) unitTarget = unit; // Reset damage/healing counter m_damage = target->damage; m_healing = -target->damage; // Fill base trigger info uint32 procAttacker = m_procAttacker; uint32 procVictim = m_procVictim; uint32 procEx = m_procEx; m_spellAura = NULL; // Set aura to null for every target-make sure that pointer is not used for unit without aura applied //Spells with this flag cannot trigger if effect is casted on self // Slice and Dice, relentless strikes, eviscerate bool canEffectTrigger = unitTarget->CanProc() && (m_spellInfo->AttributesEx4 & (SPELL_ATTR4_CANT_PROC_FROM_SELFCAST) ? m_caster != unitTarget : true); Unit * spellHitTarget = NULL; if (missInfo == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target spellHitTarget = unit; else if (missInfo == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit) { if (target->reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him { spellHitTarget = m_caster; if (m_caster->GetTypeId() == TYPEID_UNIT) m_caster->ToCreature()->LowerPlayerDamageReq(target->damage); } } if (spellHitTarget) { SpellMissInfo missInfo = DoSpellHitOnUnit(spellHitTarget, mask, target->scaleAura); if (missInfo != SPELL_MISS_NONE) { if (missInfo != SPELL_MISS_MISS) m_caster->SendSpellMiss(unit, m_spellInfo->Id, missInfo); m_damage = 0; spellHitTarget = NULL; } } // Do not take combo points on dodge and miss if (m_needComboPoints && m_targets.getUnitTargetGUID() == target->targetGUID) if (missInfo != SPELL_MISS_NONE) { m_needComboPoints = false; // Restore spell mods for a miss/dodge/parry Cold Blood // TODO: check how broad this rule should be if (m_caster->GetTypeId() == TYPEID_PLAYER) if ((missInfo == SPELL_MISS_MISS) || (missInfo == SPELL_MISS_DODGE) || (missInfo == SPELL_MISS_PARRY)) m_caster->ToPlayer()->RestoreSpellMods(this, 14177); } // Trigger info was not filled in spell::preparedatafortriggersystem - we do it now if (canEffectTrigger && !procAttacker && !procVictim) { bool positive = true; if (m_damage > 0) positive = false; else if (!m_healing) { for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) // If at least one effect negative spell is negative hit if (mask & (1<<i) && !IsPositiveEffect(m_spellInfo->Id, i)) { positive = false; break; } } switch(m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MAGIC: if (positive) { procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS; procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS; } else { procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; procVictim |= PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG; } break; case SPELL_DAMAGE_CLASS_NONE: if (positive) { procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS; procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_POS; } else { procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; procVictim |= PROC_FLAG_TAKEN_SPELL_NONE_DMG_CLASS_NEG; } break; } } CallScriptOnHitHandlers(); // All calculated do it! // Do healing and triggers if (m_healing > 0) { bool crit = caster->isSpellCrit(unitTarget, m_spellInfo, m_spellSchoolMask); uint32 addhealth = m_healing; if (crit) { procEx |= PROC_EX_CRITICAL_HIT; addhealth = caster->SpellCriticalHealingBonus(m_spellInfo, addhealth, NULL); } else procEx |= PROC_EX_NORMAL_HIT; // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, addhealth, m_attackType, m_spellInfo, m_triggeredByAuraSpell); int32 gain = caster->HealBySpell(unitTarget, m_spellInfo, addhealth, crit); unitTarget->getHostileRefManager().threatAssist(caster, float(gain) * 0.5f, m_spellInfo); } // Do damage and triggers else if (m_damage > 0) { // Fill base damage struct (unitTarget - is real spell target) SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask); // Add bonuses and fill damageInfo struct caster->CalculateSpellDamageTaken(&damageInfo, m_damage, m_spellInfo, m_attackType, target->crit); caster->DealDamageMods(damageInfo.target,damageInfo.damage,&damageInfo.absorb); // Send log damage message to client caster->SendSpellNonMeleeDamageLog(&damageInfo); procEx |= createProcExtendMask(&damageInfo, missInfo); procVictim |= PROC_FLAG_TAKEN_DAMAGE; // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) { caster->ProcDamageAndSpell(unitTarget, procAttacker, procVictim, procEx, damageInfo.damage, m_attackType, m_spellInfo, m_triggeredByAuraSpell); if (caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET) == 0 && (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED)) caster->ToPlayer()->CastItemCombatSpell(unitTarget, m_attackType, procVictim, procEx); } caster->DealSpellDamage(&damageInfo, true); // Haunt if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[1] & 0x40000 && m_spellAura && m_spellAura->GetEffect(1)) { AuraEffect * aurEff = m_spellAura->GetEffect(1); aurEff->SetAmount(CalculatePctU(aurEff->GetAmount(), damageInfo.damage)); } } // Passive spell hits/misses or active spells only misses (only triggers) else { // Fill base damage struct (unitTarget - is real spell target) SpellNonMeleeDamage damageInfo(caster, unitTarget, m_spellInfo->Id, m_spellSchoolMask); procEx |= createProcExtendMask(&damageInfo, missInfo); // Do triggers for unit (reflect triggers passed on hit phase for correct drop charge) if (canEffectTrigger && missInfo != SPELL_MISS_REFLECT) caster->ProcDamageAndSpell(unit, procAttacker, procVictim, procEx, 0, m_attackType, m_spellInfo, m_triggeredByAuraSpell); // Failed Pickpocket, reveal rogue if (missInfo == SPELL_MISS_RESIST && m_customAttr & SPELL_ATTR0_CU_PICKPOCKET && unitTarget->GetTypeId() == TYPEID_UNIT) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK); if (unitTarget->ToCreature()->IsAIEnabled) unitTarget->ToCreature()->AI()->AttackStart(m_caster); } } if (missInfo != SPELL_MISS_EVADE && m_caster && !m_caster->IsFriendlyTo(unit) && !IsPositiveSpell(m_spellInfo->Id)) { m_caster->CombatStart(unit, !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)); if (m_customAttr & SPELL_ATTR0_CU_AURA_CC) if (!unit->IsStandState()) unit->SetStandState(UNIT_STAND_STATE_STAND); } if (spellHitTarget) { //AI functions if (spellHitTarget->GetTypeId() == TYPEID_UNIT) { if (spellHitTarget->ToCreature()->IsAIEnabled) spellHitTarget->ToCreature()->AI()->SpellHit(m_caster, m_spellInfo); // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished) // ignore pets or autorepeat/melee casts for speed (not exist quest for spells (hm...) if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !spellHitTarget->ToCreature()->isPet() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) p->CastedCreatureOrGO(spellHitTarget->GetEntry(),spellHitTarget->GetGUID(),m_spellInfo->Id); } if (m_caster && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsAIEnabled) m_caster->ToCreature()->AI()->SpellHitTarget(spellHitTarget, m_spellInfo); // Needs to be called after dealing damage/healing to not remove breaking on damage auras DoTriggersOnSpellHit(spellHitTarget); // if target is fallged for pvp also flag caster if a player if (unit->IsPvP()) { if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->UpdatePvP(true); } CallScriptAfterHitHandlers(); } } SpellMissInfo Spell::DoSpellHitOnUnit(Unit *unit, const uint32 effectMask, bool scaleAura) { if (!unit || !effectMask) return SPELL_MISS_EVADE; // Recheck immune (only for delayed spells) if (m_spellInfo->speed && (unit->IsImmunedToDamage(m_spellInfo) || unit->IsImmunedToSpell(m_spellInfo))) return SPELL_MISS_IMMUNE; PrepareScriptHitHandlers(); CallScriptBeforeHitHandlers(); if (unit->GetTypeId() == TYPEID_PLAYER) { unit->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_TARGET, m_spellInfo->Id); unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, m_spellInfo->Id, 0, m_caster); unit->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2, m_spellInfo->Id); } if (m_caster->GetTypeId() == TYPEID_PLAYER) { m_caster->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_SPELL_CASTER, m_spellInfo->Id); m_caster->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2, m_spellInfo->Id, 0, unit); } if (m_caster != unit) { // Recheck UNIT_FLAG_NON_ATTACKABLE for delayed spells if (m_spellInfo->speed > 0.0f && unit->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE) && unit->GetCharmerOrOwnerGUID() != m_caster->GetGUID()) { return SPELL_MISS_EVADE; } if (!m_caster->IsFriendlyTo(unit)) { unit->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_HITBYSPELL); //TODO: This is a hack. But we do not know what types of stealth should be interrupted by CC if ((m_customAttr & SPELL_ATTR0_CU_AURA_CC) && unit->IsControlledByPlayer()) unit->RemoveAurasByType(SPELL_AURA_MOD_STEALTH); } else { // for delayed spells ignore negative spells (after duel end) for friendly targets // TODO: this cause soul transfer bugged if (m_spellInfo->speed > 0.0f && unit->GetTypeId() == TYPEID_PLAYER && !IsPositiveSpell(m_spellInfo->Id)) { return SPELL_MISS_EVADE; } // assisting case, healing and resurrection if (unit->HasUnitState(UNIT_STAT_ATTACK_PLAYER)) { m_caster->SetContestedPvP(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->UpdatePvP(true); } if (unit->isInCombat() && !(m_spellInfo->AttributesEx3 & SPELL_ATTR3_NO_INITIAL_AGGRO)) { m_caster->SetInCombatState(unit->GetCombatTimer() > 0, unit); unit->getHostileRefManager().threatAssist(m_caster, 0.0f); } } } // Get Data Needed for Diminishing Returns, some effects may have multiple auras, so this must be done on spell hit, not aura add m_diminishGroup = GetDiminishingReturnsGroupForSpell(m_spellInfo,m_triggeredByAuraSpell); if (m_diminishGroup) { m_diminishLevel = unit->GetDiminishing(m_diminishGroup); DiminishingReturnsType type = GetDiminishingReturnsGroupType(m_diminishGroup); // Increase Diminishing on unit, current informations for actually casts will use values above if ((type == DRTYPE_PLAYER && (unit->GetTypeId() == TYPEID_PLAYER || unit->ToCreature()->isPet() || unit->ToCreature()->isPossessedByPlayer())) || type == DRTYPE_ALL) unit->IncrDiminishing(m_diminishGroup); } uint8 aura_effmask = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (effectMask & (1<<i) && IsUnitOwnedAuraEffect(m_spellInfo->Effect[i])) aura_effmask |= 1<<i; if (aura_effmask) { // Select rank for aura with level requirements only in specific cases // Unit has to be target only of aura effect, both caster and target have to be players, target has to be other than unit target SpellEntry const * aurSpellInfo = m_spellInfo; int32 basePoints[3]; if (scaleAura) { aurSpellInfo = sSpellMgr->SelectAuraRankForPlayerLevel(m_spellInfo,unitTarget->getLevel()); ASSERT(aurSpellInfo); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { basePoints[i] = aurSpellInfo->EffectBasePoints[i]; if (m_spellInfo->Effect[i] != aurSpellInfo->Effect[i]) { aurSpellInfo = m_spellInfo; break; } } } if (m_originalCaster) { m_spellAura = Aura::TryCreate(aurSpellInfo, effectMask, unit, m_originalCaster,(aurSpellInfo == m_spellInfo)? &m_spellValue->EffectBasePoints[0] : &basePoints[0], m_CastItem); if (m_spellAura) { // Now Reduce spell duration using data received at spell hit int32 duration = m_spellAura->GetMaxDuration(); int32 limitduration = GetDiminishingReturnsLimitDuration(m_diminishGroup,aurSpellInfo); float diminishMod = unit->ApplyDiminishingToDuration(m_diminishGroup, duration, m_originalCaster, m_diminishLevel,limitduration); // unit is immune to aura if it was diminished to 0 duration if (diminishMod == 0.0f) { m_spellAura->Remove(); return SPELL_MISS_IMMUNE; } ((UnitAura*)m_spellAura)->SetDiminishGroup(m_diminishGroup); bool positive = IsPositiveSpell(m_spellAura->GetId()); AuraApplication * aurApp = m_spellAura->GetApplicationOfTarget(m_originalCaster->GetGUID()); if (aurApp) positive = aurApp->IsPositive(); duration = m_originalCaster->ModSpellDuration(aurSpellInfo, unit, duration, positive); // Haste modifies duration of channeled spells if (IsChanneledSpell(m_spellInfo)) m_originalCaster->ModSpellCastTime(aurSpellInfo, duration, this); // and duration of auras affected by SPELL_AURA_PERIODIC_HASTE if (m_originalCaster->HasAuraTypeWithAffectMask(SPELL_AURA_PERIODIC_HASTE, aurSpellInfo)) duration = int32(duration * m_originalCaster->GetFloatValue(UNIT_MOD_CAST_SPEED)); if (duration != m_spellAura->GetMaxDuration()) { m_spellAura->SetMaxDuration(duration); m_spellAura->SetDuration(duration); } m_spellAura->_RegisterForTargets(); } } } for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) { if (effectMask & (1<<effectNumber)) HandleEffects(unit,NULL,NULL,effectNumber); } return SPELL_MISS_NONE; } void Spell::DoTriggersOnSpellHit(Unit *unit) { // Apply additional spell effects to target if (m_preCastSpell) { // Paladin immunity shields if (m_preCastSpell == 61988) { // Cast Forbearance m_caster->CastSpell(unit, 25771, true); // Cast Avenging Wrath Marker unit->CastSpell(unit, 61987, true); } // Avenging Wrath if (m_preCastSpell == 61987) // Cast the serverside immunity shield marker m_caster->CastSpell(unit, 61988, true); if (sSpellStore.LookupEntry(m_preCastSpell)) // Blizz seems to just apply aura without bothering to cast m_caster->AddAura(m_preCastSpell, unit); } // spells with this flag can trigger only if not selfcast (eviscerate for example) if (m_ChanceTriggerSpells.size() && (!((m_spellInfo->AttributesEx4 & SPELL_ATTR4_CANT_PROC_FROM_SELFCAST) && unit == m_caster))) { int _duration=0; for (ChanceTriggerSpells::const_iterator i = m_ChanceTriggerSpells.begin(); i != m_ChanceTriggerSpells.end(); ++i) { // SPELL_AURA_ADD_TARGET_TRIGGER auras shouldn't trigger auras without duration // set duration equal to triggering spell if (roll_chance_i(i->second)) { m_caster->CastSpell(unit, i->first, true); sLog->outDebug("Spell %d triggered spell %d by SPELL_AURA_ADD_TARGET_TRIGGER aura", m_spellInfo->Id, i->first->Id); } if (GetSpellDuration(i->first) == -1) { if (Aura * triggeredAur = unit->GetAura(i->first->Id, m_caster->GetGUID())) { // get duration from aura-only once if (!_duration) { Aura * aur = unit->GetAura(m_spellInfo->Id, m_caster->GetGUID()); _duration = aur ? aur->GetDuration() : -1; } triggeredAur->SetDuration(_duration); } } } } if (m_customAttr & SPELL_ATTR0_CU_LINK_HIT) { if (const std::vector<int32> *spell_triggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id + SPELL_LINK_HIT)) for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i) if (*i < 0) unit->RemoveAurasDueToSpell(-(*i)); else unit->CastSpell(unit, *i, true, 0, 0, m_caster->GetGUID()); } } void Spell::DoAllEffectOnTarget(GOTargetInfo *target) { if (target->processed) // Check target return; target->processed = true; // Target checked in apply effects procedure uint32 effectMask = target->effectMask; if (!effectMask) return; GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID); if (!go) return; PrepareScriptHitHandlers(); CallScriptBeforeHitHandlers(); for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) HandleEffects(NULL, NULL, go, effectNumber); CallScriptOnHitHandlers(); // cast at creature (or GO) quest objectives update at successful cast finished (+channel finished) // ignore autorepeat/melee casts for speed (not exist quest for spells (hm...) if (m_originalCaster && m_originalCaster->IsControlledByPlayer() && !IsAutoRepeat() && !IsNextMeleeSwingSpell() && !IsChannelActive()) { if (Player* p = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself()) p->CastedCreatureOrGO(go->GetEntry(),go->GetGUID(),m_spellInfo->Id); } CallScriptAfterHitHandlers(); } void Spell::DoAllEffectOnTarget(ItemTargetInfo *target) { uint32 effectMask = target->effectMask; if (!target->item || !effectMask) return; PrepareScriptHitHandlers(); CallScriptBeforeHitHandlers(); for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) HandleEffects(NULL, target->item, NULL, effectNumber); CallScriptOnHitHandlers(); CallScriptAfterHitHandlers(); } bool Spell::UpdateChanneledTargetList() { // Not need check return true if (m_channelTargetEffectMask == 0) return true; uint8 channelTargetEffectMask = m_channelTargetEffectMask; uint8 channelAuraMask = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA) channelAuraMask |= 1<<i; channelAuraMask &= channelTargetEffectMask; float range = 0; if (channelAuraMask) { range = GetSpellMaxRange(m_spellInfo, IsPositiveSpell(m_spellInfo->Id)); if (Player * modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); } for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->missCondition == SPELL_MISS_NONE && (channelTargetEffectMask & ihit->effectMask)) { Unit *unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID); if (!unit) continue; if (IsValidDeadOrAliveTarget(unit)) { if (channelAuraMask & ihit->effectMask) { if (AuraApplication * aurApp = unit->GetAuraApplication(m_spellInfo->Id, m_originalCasterGUID)) { if (m_caster != unit && !m_caster->IsWithinDistInMap(unit,range)) { ihit->effectMask &= ~aurApp->GetEffectMask(); unit->RemoveAura(aurApp); continue; } } else // aura is dispelled continue; } channelTargetEffectMask &= ~ihit->effectMask; // remove from need alive mask effect that have alive target } } } // is all effects from m_needAliveTargetMask have alive targets return channelTargetEffectMask == 0; } // Helper for Chain Healing // Spell target first // Raidmates then descending by injury suffered (MaxHealth - Health) // Other players/mobs then descending by injury suffered (MaxHealth - Health) struct ChainHealingOrder : public std::binary_function<const Unit*, const Unit*, bool> { const Unit* MainTarget; ChainHealingOrder(Unit const* Target) : MainTarget(Target) {}; // functor for operator ">" bool operator()(Unit const* _Left, Unit const* _Right) const { return (ChainHealingHash(_Left) < ChainHealingHash(_Right)); } int32 ChainHealingHash(Unit const* Target) const { /*if (Target == MainTarget) return 0; else*/ if (Target->GetTypeId() == TYPEID_PLAYER && MainTarget->GetTypeId() == TYPEID_PLAYER && Target->ToPlayer()->IsInSameRaidWith(MainTarget->ToPlayer())) { if (Target->IsFullHealth()) return 40000; else return 20000 - Target->GetMaxHealth() + Target->GetHealth(); } else return 40000 - Target->GetMaxHealth() + Target->GetHealth(); } }; void Spell::SearchChainTarget(std::list<Unit*> &TagUnitMap, float max_range, uint32 num, SpellTargets TargetType) { Unit *cur = m_targets.getUnitTarget(); if (!cur) return; // Get spell max affected targets /*uint32 unMaxTargets = m_spellInfo->MaxAffectedTargets; Unit::AuraList const& mod = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); for (Unit::AuraList::const_iterator m = mod.begin(); m != mod.end(); ++m) { if (!(*m)->IsAffectedOnSpell(m_spellInfo)) continue; unMaxTargets+=(*m)->GetAmount(); }*/ //FIXME: This very like horrible hack and wrong for most spells if (m_spellInfo->DmgClass != SPELL_DAMAGE_CLASS_MELEE) max_range += num * CHAIN_SPELL_JUMP_RADIUS; std::list<Unit*> tempUnitMap; if (TargetType == SPELL_TARGETS_CHAINHEAL) { SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, SPELL_TARGETS_ALLY); tempUnitMap.sort(ChainHealingOrder(m_caster)); //if (cur->IsFullHealth() && tempUnitMap.size()) // cur = tempUnitMap.front(); } else SearchAreaTarget(tempUnitMap, max_range, PUSH_CHAIN, TargetType); tempUnitMap.remove(cur); while (num) { TagUnitMap.push_back(cur); --num; if (tempUnitMap.empty()) break; std::list<Unit*>::iterator next; if (TargetType == SPELL_TARGETS_CHAINHEAL) { next = tempUnitMap.begin(); while (cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS || !cur->IsWithinLOSInMap(*next)) { ++next; if (next == tempUnitMap.end()) return; } } else { tempUnitMap.sort(Trinity::ObjectDistanceOrderPred(cur)); next = tempUnitMap.begin(); if (cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS) break; while ((m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE && !m_caster->isInFrontInMap(*next, max_range)) || !m_caster->canSeeOrDetect(*next) || !cur->IsWithinLOSInMap(*next)) { ++next; if (next == tempUnitMap.end() || cur->GetDistance(*next) > CHAIN_SPELL_JUMP_RADIUS) return; } } cur = *next; tempUnitMap.erase(next); } } void Spell::SearchAreaTarget(std::list<Unit*> &TagUnitMap, float radius, SpellNotifyPushType type, SpellTargets TargetType, uint32 entry) { if (TargetType == SPELL_TARGETS_GO) return; Position *pos; switch(type) { case PUSH_DST_CENTER: CheckDst(); pos = &m_targets.m_dstPos; break; case PUSH_SRC_CENTER: CheckSrc(); pos = &m_targets.m_srcPos; break; case PUSH_CHAIN: { Unit *target = m_targets.getUnitTarget(); if (!target) { sLog->outError("SPELL: cannot find unit target for spell ID %u\n", m_spellInfo->Id); return; } pos = target; break; } default: pos = m_caster; break; } bool requireDeadTarget = bool(m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQUIRE_DEAD_TARGET); Trinity::SpellNotifierCreatureAndPlayer notifier(m_caster, TagUnitMap, radius, type, TargetType, pos, entry, requireDeadTarget); if ((m_spellInfo->AttributesEx3 & SPELL_ATTR3_PLAYERS_ONLY) || (TargetType == SPELL_TARGETS_ENTRY && !entry)) m_caster->GetMap()->VisitWorld(pos->m_positionX, pos->m_positionY, radius, notifier); else m_caster->GetMap()->VisitAll(pos->m_positionX, pos->m_positionY, radius, notifier); if (m_customAttr & SPELL_ATTR0_CU_EXCLUDE_SELF) TagUnitMap.remove(m_caster); } void Spell::SearchGOAreaTarget(std::list<GameObject*> &TagGOMap, float radius, SpellNotifyPushType type, SpellTargets TargetType, uint32 entry) { if (TargetType != SPELL_TARGETS_GO) return; Position *pos; switch (type) { case PUSH_DST_CENTER: CheckDst(); pos = &m_targets.m_dstPos; break; case PUSH_SRC_CENTER: CheckSrc(); pos = &m_targets.m_srcPos; break; default: pos = m_caster; break; } Trinity::GameObjectInRangeCheck check(pos->m_positionX, pos->m_positionY, pos->m_positionZ, radius, entry); Trinity::GameObjectListSearcher<Trinity::GameObjectInRangeCheck> searcher(m_caster, TagGOMap, check); m_caster->GetMap()->VisitGrid(pos->m_positionX, pos->m_positionY, radius, searcher); } WorldObject* Spell::SearchNearbyTarget(float range, SpellTargets TargetType, SpellEffIndex effIndex) { switch(TargetType) { case SPELL_TARGETS_ENTRY: { ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET, m_spellInfo->Id); if (conditions.empty()) { sLog->outDebug("Spell (ID: %u) (caster Entry: %u) does not have record in `conditions` for spell script target (ConditionSourceType 13)", m_spellInfo->Id, m_caster->GetEntry()); if (IsPositiveSpell(m_spellInfo->Id)) return SearchNearbyTarget(range, SPELL_TARGETS_ALLY, effIndex); else return SearchNearbyTarget(range, SPELL_TARGETS_ENEMY, effIndex); } Creature* creatureScriptTarget = NULL; GameObject* goScriptTarget = NULL; for (ConditionList::const_iterator i_spellST = conditions.begin(); i_spellST != conditions.end(); ++i_spellST) { if ((*i_spellST)->mConditionType != CONDITION_SPELL_SCRIPT_TARGET) continue; if ((*i_spellST)->mConditionValue3 && !((*i_spellST)->mConditionValue3 & (1 << uint32(effIndex)))) continue; switch((*i_spellST)->mConditionValue1) { case SPELL_TARGET_TYPE_CONTROLLED: for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr) if ((*itr)->GetEntry() == (*i_spellST)->mConditionValue2 && (*itr)->IsWithinDistInMap(m_caster, range)) { goScriptTarget = NULL; creatureScriptTarget = (*itr)->ToCreature(); range = m_caster->GetDistance(creatureScriptTarget); } break; case SPELL_TARGET_TYPE_GAMEOBJECT: if ((*i_spellST)->mConditionValue2) { if (GameObject *go = m_caster->FindNearestGameObject((*i_spellST)->mConditionValue2, range)) { // remember found target and range, next attempt will find more near target with another entry goScriptTarget = go; creatureScriptTarget = NULL; range = m_caster->GetDistance(goScriptTarget); } } else if (focusObject) //Focus Object { float frange = m_caster->GetDistance(focusObject); if (range >= frange) { creatureScriptTarget = NULL; goScriptTarget = focusObject; range = frange; } } break; case SPELL_TARGET_TYPE_CREATURE: if (m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetEntry() == (*i_spellST)->mConditionValue2) return m_targets.getUnitTarget(); case SPELL_TARGET_TYPE_DEAD: default: if (Creature *cre = m_caster->FindNearestCreature((*i_spellST)->mConditionValue2, range, (*i_spellST)->mConditionValue1 != SPELL_TARGET_TYPE_DEAD)) { creatureScriptTarget = cre; goScriptTarget = NULL; range = m_caster->GetDistance(creatureScriptTarget); } break; } } if (creatureScriptTarget) return creatureScriptTarget; else return goScriptTarget; } default: case SPELL_TARGETS_ENEMY: { Unit *target = NULL; Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range); Trinity::UnitLastSearcher<Trinity::AnyUnfriendlyUnitInObjectRangeCheck> searcher(m_caster, target, u_check); m_caster->VisitNearbyObject(range, searcher); return target; } case SPELL_TARGETS_ALLY: { Unit *target = NULL; Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(m_caster, m_caster, range); Trinity::UnitLastSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(m_caster, target, u_check); m_caster->VisitNearbyObject(range, searcher); return target; } } } void Spell::SelectEffectTargets(uint32 i, uint32 cur) { SpellNotifyPushType pushType = PUSH_NONE; Player *modOwner = NULL; if (m_originalCaster) modOwner = m_originalCaster->GetSpellModOwner(); switch(SpellTargetType[cur]) { case TARGET_TYPE_UNIT_CASTER: { switch(cur) { case TARGET_UNIT_CASTER: AddUnitTarget(m_caster, i); break; case TARGET_UNIT_CASTER_FISHING: { float min_dis = GetSpellMinRange(m_spellInfo, true); float max_dis = GetSpellMaxRange(m_spellInfo, true); float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis; float x, y, z; m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE, dis); m_targets.setDst(x, y, z, m_caster->GetOrientation()); break; } case TARGET_UNIT_MASTER: if (Unit* owner = m_caster->GetCharmerOrOwner()) AddUnitTarget(owner, i); break; case TARGET_UNIT_PET: if (Guardian* pet = m_caster->GetGuardianPet()) AddUnitTarget(pet, i); break; case TARGET_UNIT_SUMMONER: if (m_caster->isSummon()) if (Unit* unit = m_caster->ToTempSummon()->GetSummoner()) AddUnitTarget(unit, i); break; case TARGET_UNIT_PARTY_CASTER: case TARGET_UNIT_RAID_CASTER: pushType = PUSH_CASTER_CENTER; break; case TARGET_UNIT_VEHICLE: if (Unit *vehicle = m_caster->GetVehicleBase()) AddUnitTarget(vehicle, i); break; case TARGET_UNIT_PASSENGER_0: case TARGET_UNIT_PASSENGER_1: case TARGET_UNIT_PASSENGER_2: case TARGET_UNIT_PASSENGER_3: case TARGET_UNIT_PASSENGER_4: case TARGET_UNIT_PASSENGER_5: case TARGET_UNIT_PASSENGER_6: case TARGET_UNIT_PASSENGER_7: if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->IsVehicle()) if (Unit *unit = m_caster->GetVehicleKit()->GetPassenger(cur - TARGET_UNIT_PASSENGER_0)) AddUnitTarget(unit, i); break; } break; } case TARGET_TYPE_UNIT_TARGET: { Unit *target = m_targets.getUnitTarget(); if (!target) { sLog->outError("SPELL: no unit target for spell ID %u", m_spellInfo->Id); break; } switch(cur) { case TARGET_UNIT_TARGET_ENEMY: if (Unit *magnet = m_caster->SelectMagnetTarget(target, m_spellInfo)) if (magnet != target) m_targets.setUnitTarget(magnet); pushType = PUSH_CHAIN; break; case TARGET_UNIT_TARGET_ANY: if (!IsPositiveSpell(m_spellInfo->Id)) if (Unit *magnet = m_caster->SelectMagnetTarget(target, m_spellInfo)) if (magnet != target) m_targets.setUnitTarget(magnet); pushType = PUSH_CHAIN; break; case TARGET_UNIT_CHAINHEAL: pushType = PUSH_CHAIN; break; case TARGET_UNIT_TARGET_ALLY: case TARGET_UNIT_TARGET_RAID: case TARGET_UNIT_TARGET_PARTY: case TARGET_UNIT_TARGET_PUPPET: AddUnitTarget(target, i); break; case TARGET_UNIT_PARTY_TARGET: case TARGET_UNIT_CLASS_TARGET: pushType = PUSH_CASTER_CENTER; // not real break; } break; } case TARGET_TYPE_UNIT_NEARBY: { WorldObject *target = NULL; float range; switch(cur) { case TARGET_UNIT_NEARBY_ENEMY: range = GetSpellMaxRange(m_spellInfo, false); if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); target = SearchNearbyTarget(range, SPELL_TARGETS_ENEMY, SpellEffIndex(i)); break; case TARGET_UNIT_NEARBY_ALLY: case TARGET_UNIT_NEARBY_ALLY_UNK: case TARGET_UNIT_NEARBY_RAID: range = GetSpellMaxRange(m_spellInfo, true); if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); target = SearchNearbyTarget(range, SPELL_TARGETS_ALLY, SpellEffIndex(i)); break; case TARGET_UNIT_NEARBY_ENTRY: case TARGET_GAMEOBJECT_NEARBY_ENTRY: range = GetSpellMaxRange(m_spellInfo, IsPositiveSpell(m_spellInfo->Id)); if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY, SpellEffIndex(i)); break; } if (!target) return; else if (target->GetTypeId() == TYPEID_GAMEOBJECT) AddGOTarget((GameObject*)target, i); else { pushType = PUSH_CHAIN; if (m_targets.getUnitTarget() != target) m_targets.setUnitTarget((Unit*)target); } break; } case TARGET_TYPE_AREA_SRC: pushType = PUSH_SRC_CENTER; break; case TARGET_TYPE_AREA_DST: pushType = PUSH_DST_CENTER; break; case TARGET_TYPE_AREA_CONE: if (m_customAttr & SPELL_ATTR0_CU_CONE_BACK) pushType = PUSH_IN_BACK; else if (m_customAttr & SPELL_ATTR0_CU_CONE_LINE) pushType = PUSH_IN_LINE; else pushType = PUSH_IN_FRONT; break; case TARGET_TYPE_DEST_CASTER: //4+8+2 { if (cur == TARGET_SRC_CASTER) { m_targets.setSrc(*m_caster); break; } else if (cur == TARGET_DST_CASTER) { m_targets.setDst(*m_caster); break; } float angle, dist; float objSize = m_caster->GetObjectSize(); if (m_spellInfo->AttributesEx & SPELL_ATTR1_USE_RADIUS_AS_MAX_DISTANCE) dist = 0.0f; else dist = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i])); if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, dist, this); if (dist < objSize) dist = objSize; else if (cur == TARGET_DEST_CASTER_RANDOM) dist = objSize + (dist - objSize) * (float)rand_norm(); switch(cur) { case TARGET_DEST_CASTER_FRONT_LEFT: angle = static_cast<float>(-M_PI/4); break; case TARGET_DEST_CASTER_BACK_LEFT: angle = static_cast<float>(-3*M_PI/4); break; case TARGET_DEST_CASTER_BACK_RIGHT: angle = static_cast<float>(3*M_PI/4); break; case TARGET_DEST_CASTER_FRONT_RIGHT:angle = static_cast<float>(M_PI/4); break; case TARGET_MINION: case TARGET_DEST_CASTER_FRONT_LEAP: case TARGET_DEST_CASTER_FRONT: angle = 0.0f; break; case TARGET_DEST_CASTER_BACK: angle = static_cast<float>(M_PI); break; case TARGET_DEST_CASTER_RIGHT: angle = static_cast<float>(M_PI/2); break; case TARGET_DEST_CASTER_LEFT: angle = static_cast<float>(-M_PI/2); break; default: angle = (float)rand_norm()*static_cast<float>(2*M_PI); break; } Position pos; if (cur == TARGET_DEST_CASTER_FRONT_LEAP) m_caster->GetFirstCollisionPosition(pos, dist, angle); else m_caster->GetNearPosition(pos, dist, angle); m_targets.setDst(*m_caster); m_targets.modDst(pos); break; } case TARGET_TYPE_DEST_TARGET: //2+8+2 { Unit *target = m_targets.getUnitTarget(); if (!target) { sLog->outError("SPELL: no unit target for spell ID %u", m_spellInfo->Id); break; } if (cur == TARGET_DST_TARGET_ENEMY || cur == TARGET_DEST_TARGET_ANY) { m_targets.setDst(*target); break; } float angle, dist; float objSize = target->GetObjectSize(); dist = (float)target->GetSpellRadiusForTarget(target, sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i])); if (dist < objSize) dist = objSize; else if (cur == TARGET_DEST_TARGET_RANDOM) dist = objSize + (dist - objSize) * (float)rand_norm(); switch(cur) { case TARGET_DEST_TARGET_FRONT: angle = 0.0f; break; case TARGET_DEST_TARGET_BACK: angle = static_cast<float>(M_PI); break; case TARGET_DEST_TARGET_RIGHT: angle = static_cast<float>(M_PI/2); break; case TARGET_DEST_TARGET_LEFT: angle = static_cast<float>(-M_PI/2); break; case TARGET_DEST_TARGET_FRONT_LEFT: angle = static_cast<float>(-M_PI/4); break; case TARGET_DEST_TARGET_BACK_LEFT: angle = static_cast<float>(-3*M_PI/4); break; case TARGET_DEST_TARGET_BACK_RIGHT: angle = static_cast<float>(3*M_PI/4); break; case TARGET_DEST_TARGET_FRONT_RIGHT:angle = static_cast<float>(M_PI/4); break; default: angle = (float)rand_norm()*static_cast<float>(2*M_PI); break; } Position pos; target->GetNearPosition(pos, dist, angle); m_targets.setDst(*target); m_targets.modDst(pos); break; } case TARGET_TYPE_DEST_DEST: //5+8+1 { if (!m_targets.HasDst()) { sLog->outError("SPELL: no destination for spell ID %u", m_spellInfo->Id); break; } float angle; switch(cur) { case TARGET_DEST_DYNOBJ_ENEMY: case TARGET_DEST_DYNOBJ_ALLY: case TARGET_DEST_DYNOBJ_NONE: case TARGET_DEST_DEST: return; case TARGET_DEST_TRAJ: SelectTrajTargets(); return; case TARGET_DEST_DEST_FRONT: angle = 0.0f; break; case TARGET_DEST_DEST_BACK: angle = static_cast<float>(M_PI); break; case TARGET_DEST_DEST_RIGHT: angle = static_cast<float>(M_PI/2); break; case TARGET_DEST_DEST_LEFT: angle = static_cast<float>(-M_PI/2); break; case TARGET_DEST_DEST_FRONT_LEFT: angle = static_cast<float>(-M_PI/4); break; case TARGET_DEST_DEST_BACK_LEFT: angle = static_cast<float>(-3*M_PI/4); break; case TARGET_DEST_DEST_BACK_RIGHT: angle = static_cast<float>(3*M_PI/4); break; case TARGET_DEST_DEST_FRONT_RIGHT:angle = static_cast<float>(M_PI/4); break; default: angle = (float)rand_norm()*static_cast<float>(2*M_PI); break; } float dist; dist = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i])); if (cur == TARGET_DEST_DEST_RANDOM || cur == TARGET_DEST_DEST_RANDOM_DIR_DIST) dist *= (float)rand_norm(); // must has dst, no need to set flag Position pos = m_targets.m_dstPos; m_caster->MovePosition(pos, dist, angle); m_targets.modDst(pos); break; } case TARGET_TYPE_DEST_SPECIAL: { switch(cur) { case TARGET_DST_DB: if (SpellTargetPosition const* st = sSpellMgr->GetSpellTargetPosition(m_spellInfo->Id)) { //TODO: fix this check if (m_spellInfo->Effect[0] == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effect[1] == SPELL_EFFECT_TELEPORT_UNITS || m_spellInfo->Effect[2] == SPELL_EFFECT_TELEPORT_UNITS) m_targets.setDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation, (int32)st->target_mapId); else if (st->target_mapId == m_caster->GetMapId()) m_targets.setDst(st->target_X, st->target_Y, st->target_Z, st->target_Orientation); } else { sLog->outDebug("SPELL: unknown target coordinates for spell ID %u", m_spellInfo->Id); Unit *target = NULL; if (uint64 guid = m_caster->GetUInt64Value(UNIT_FIELD_TARGET)) target = ObjectAccessor::GetUnit(*m_caster, guid); m_targets.setDst(target ? *target : *m_caster); } break; case TARGET_DST_HOME: if (m_caster->GetTypeId() == TYPEID_PLAYER) m_targets.setDst(m_caster->ToPlayer()->m_homebindX,m_caster->ToPlayer()->m_homebindY,m_caster->ToPlayer()->m_homebindZ, m_caster->ToPlayer()->GetOrientation(), m_caster->ToPlayer()->m_homebindMapId); break; case TARGET_DST_NEARBY_ENTRY: { float range = GetSpellMaxRange(m_spellInfo, IsPositiveSpell(m_spellInfo->Id)); if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); if (WorldObject *target = SearchNearbyTarget(range, SPELL_TARGETS_ENTRY, SpellEffIndex(i))) m_targets.setDst(*target); break; } } break; } case TARGET_TYPE_CHANNEL: { if (!m_originalCaster || !m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) { sLog->outError("SPELL: no current channeled spell for spell ID %u", m_spellInfo->Id); break; } switch (cur) { case TARGET_UNIT_CHANNEL_TARGET: // unit target may be no longer avalible - teleported out of map for example if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.getUnitTargetGUID())) AddUnitTarget(target, i); else sLog->outError("SPELL: cannot find channel spell target for spell ID %u", m_spellInfo->Id); break; case TARGET_DEST_CHANNEL_TARGET: if (m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.HasDst()) m_targets.setDst(m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets); else if (Unit* target = Unit::GetUnit(*m_caster, m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->m_targets.getUnitTargetGUID())) m_targets.setDst(*target); else sLog->outError("SPELL: cannot find channel spell destination for spell ID %u", m_spellInfo->Id); break; case TARGET_DEST_CHANNEL_CASTER: m_targets.setDst(*m_originalCaster->GetCurrentSpell(CURRENT_CHANNELED_SPELL)->GetCaster()); break; } break; } default: { switch (cur) { case TARGET_GAMEOBJECT: if (m_targets.getGOTarget()) AddGOTarget(m_targets.getGOTarget(), i); break; case TARGET_GAMEOBJECT_ITEM: if (m_targets.getGOTargetGUID()) AddGOTarget(m_targets.getGOTarget(), i); else if (m_targets.getItemTarget()) AddItemTarget(m_targets.getItemTarget(), i); break; case TARGET_UNIT_DRIVER: if (Unit * driver = m_targets.getUnitTarget()) if (driver->IsOnVehicle(driver)) AddUnitTarget(driver, i); break; default: sLog->outError("Unhandled spell target %u", cur); break; } break; } } if (pushType == PUSH_CHAIN) // Chain { Unit *target = m_targets.getUnitTarget(); if (!target) { sLog->outError("SPELL: no chain unit target for spell ID %u", m_spellInfo->Id); return; } //Chain: 2, 6, 22, 25, 45, 77 uint32 maxTargets = m_spellInfo->EffectChainTarget[i]; if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this); if (maxTargets > 1) { //otherwise, this multiplier is used for something else m_damageMultipliers[i] = 1.0f; m_applyMultiplierMask |= 1 << i; float range; std::list<Unit*> unitList; switch (cur) { case TARGET_UNIT_NEARBY_ENEMY: case TARGET_UNIT_TARGET_ENEMY: case TARGET_UNIT_NEARBY_ENTRY: // fix me range = GetSpellMaxRange(m_spellInfo, false); if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_ENEMY); break; case TARGET_UNIT_CHAINHEAL: case TARGET_UNIT_NEARBY_ALLY: // fix me case TARGET_UNIT_NEARBY_ALLY_UNK: case TARGET_UNIT_NEARBY_RAID: range = GetSpellMaxRange(m_spellInfo, true); if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); SearchChainTarget(unitList, range, maxTargets, SPELL_TARGETS_CHAINHEAL); break; } for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr) AddUnitTarget(*itr, i); } else AddUnitTarget(target, i); } else if (pushType) { // Dummy, just for client if (EffectTargetType[m_spellInfo->Effect[i]] != SPELL_REQUIRE_UNIT) return; float radius; SpellTargets targetType; switch(cur) { case TARGET_UNIT_AREA_ENEMY_SRC: case TARGET_UNIT_AREA_ENEMY_DST: case TARGET_UNIT_CONE_ENEMY: case TARGET_UNIT_CONE_ENEMY_UNKNOWN: case TARGET_UNIT_AREA_PATH: radius = GetSpellRadius(m_spellInfo, i, false); targetType = SPELL_TARGETS_ENEMY; break; case TARGET_UNIT_AREA_ALLY_SRC: case TARGET_UNIT_AREA_ALLY_DST: case TARGET_UNIT_CONE_ALLY: radius = GetSpellRadius(m_spellInfo, i, true); targetType = SPELL_TARGETS_ALLY; break; case TARGET_UNIT_AREA_ENTRY_DST: case TARGET_UNIT_AREA_ENTRY_SRC: case TARGET_UNIT_CONE_ENTRY: // fix me radius = GetSpellRadius(m_spellInfo, i, IsPositiveSpell(m_spellInfo->Id)); targetType = SPELL_TARGETS_ENTRY; break; case TARGET_GAMEOBJECT_AREA_SRC: case TARGET_GAMEOBJECT_AREA_DST: case TARGET_GAMEOBJECT_AREA_PATH: radius = GetSpellRadius(m_spellInfo, i, true); targetType = SPELL_TARGETS_GO; break; default: radius = GetSpellRadius(m_spellInfo, i, true); targetType = SPELL_TARGETS_NONE; break; } if (modOwner) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius, this); radius *= m_spellValue->RadiusMod; std::list<Unit*> unitList; std::list<GameObject*> gobjectList; switch (targetType) { case SPELL_TARGETS_ENTRY: { ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET, m_spellInfo->Id); if (!conditions.empty()) { for (ConditionList::const_iterator i_spellST = conditions.begin(); i_spellST != conditions.end(); ++i_spellST) { if ((*i_spellST)->mConditionType != CONDITION_SPELL_SCRIPT_TARGET) continue; if ((*i_spellST)->mConditionValue3 && !((*i_spellST)->mConditionValue3 & (1<<i))) continue; if ((*i_spellST)->mConditionValue1 == SPELL_TARGET_TYPE_CREATURE) SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, (*i_spellST)->mConditionValue2); else if ((*i_spellST)->mConditionValue1 == SPELL_TARGET_TYPE_CONTROLLED) { for (Unit::ControlList::iterator itr = m_caster->m_Controlled.begin(); itr != m_caster->m_Controlled.end(); ++itr) if ((*itr)->GetEntry() == (*i_spellST)->mConditionValue2 && /*(*itr)->IsWithinDistInMap(m_caster, radius)*/ (*itr)->IsInMap(m_caster)) // For 60243 and 52173 need skip radius check or use range (no radius entry for effect) unitList.push_back(*itr); } } } else { // Custom entries // TODO: move these to sql switch (m_spellInfo->Id) { case 46584: // Raise Dead { if (WorldObject* result = FindCorpseUsing<Trinity::RaiseDeadObjectCheck> ()) { switch(result->GetTypeId()) { case TYPEID_UNIT: m_targets.setDst(*result); break; default: break; } } break; } // Corpse Explosion case 49158: case 51325: case 51326: case 51327: case 51328: // Search for ghoul if our ghoul or dead body not valid unit target if (!(m_targets.getUnitTarget() && ((m_targets.getUnitTarget()->GetEntry() == 26125 && m_targets.getUnitTarget()->GetOwnerGUID() == m_caster->GetGUID()) || (m_targets.getUnitTarget()->getDeathState() == CORPSE && m_targets.getUnitTarget()->GetDisplayId() == m_targets.getUnitTarget()->GetNativeDisplayId() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_UNIT && !m_targets.getUnitTarget()->ToCreature()->isDeadByDefault() && !(m_targets.getUnitTarget()->GetCreatureTypeMask() & CREATURE_TYPEMASK_MECHANICAL_OR_ELEMENTAL) && m_targets.getUnitTarget()->GetDisplayId() == m_targets.getUnitTarget()->GetNativeDisplayId())))) { CleanupTargetList(); WorldObject* result = FindCorpseUsing <Trinity::ExplodeCorpseObjectCheck> (); if (result) { switch (result->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: m_targets.setUnitTarget((Unit*)result); break; default: break; } } else { if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id,true); SendCastResult(SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW); finish(false); } } break; default: sLog->outDebug("Spell (ID: %u) (caster Entry: %u) does not have type CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET record in `conditions` table.", m_spellInfo->Id, m_caster->GetEntry()); if (m_spellInfo->Effect[i] == SPELL_EFFECT_TELEPORT_UNITS) SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENTRY, 0); else if (IsPositiveEffect(m_spellInfo->Id, i)) SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ALLY); else SearchAreaTarget(unitList, radius, pushType, SPELL_TARGETS_ENEMY); } } break; } case SPELL_TARGETS_GO: { ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET, m_spellInfo->Id); if (!conditions.empty()) { for (ConditionList::const_iterator i_spellST = conditions.begin(); i_spellST != conditions.end(); ++i_spellST) { if ((*i_spellST)->mConditionType != CONDITION_SPELL_SCRIPT_TARGET) continue; if ((*i_spellST)->mConditionValue3 && !((*i_spellST)->mConditionValue3 & (1<<i))) continue; if ((*i_spellST)->mConditionValue1 == SPELL_TARGET_TYPE_GAMEOBJECT) SearchGOAreaTarget(gobjectList, radius, pushType, SPELL_TARGETS_GO, (*i_spellST)->mConditionValue2); } } else { if (m_spellInfo->Effect[i] == SPELL_EFFECT_ACTIVATE_OBJECT) sLog->outDebug("Spell (ID: %u) (caster Entry: %u) with SPELL_EFFECT_ACTIVATE_OBJECT does not have type CONDITION_SOURCE_TYPE_SPELL_SCRIPT_TARGET record in `conditions` table.", m_spellInfo->Id, m_caster->GetEntry()); SearchGOAreaTarget(gobjectList, radius, pushType, SPELL_TARGETS_GO); } break; } case SPELL_TARGETS_ALLY: case SPELL_TARGETS_ENEMY: case SPELL_TARGETS_CHAINHEAL: case SPELL_TARGETS_ANY: SearchAreaTarget(unitList, radius, pushType, targetType); break; default: switch (cur) { case TARGET_UNIT_AREA_PARTY_SRC: case TARGET_UNIT_AREA_PARTY_DST: m_caster->GetPartyMemberInDist(unitList, radius); //fix me break; case TARGET_UNIT_PARTY_TARGET: m_targets.getUnitTarget()->GetPartyMemberInDist(unitList, radius); break; case TARGET_UNIT_PARTY_CASTER: m_caster->GetPartyMemberInDist(unitList, radius); break; case TARGET_UNIT_RAID_CASTER: m_caster->GetRaidMember(unitList, radius); break; case TARGET_UNIT_CLASS_TARGET: { Player* targetPlayer = m_targets.getUnitTarget() && m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER ? (Player*)m_targets.getUnitTarget() : NULL; Group* pGroup = targetPlayer ? targetPlayer->GetGroup() : NULL; if (pGroup) { for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* Target = itr->getSource(); // IsHostileTo check duel and controlled by enemy if (Target && targetPlayer->IsWithinDistInMap(Target, radius) && targetPlayer->getClass() == Target->getClass() && !m_caster->IsHostileTo(Target)) { AddUnitTarget(Target, i); } } } else if (m_targets.getUnitTarget()) AddUnitTarget(m_targets.getUnitTarget(), i); break; } } break; } if (!unitList.empty()) { // Special target selection for smart heals and energizes uint32 maxSize = 0; int32 power = -1; switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: switch (m_spellInfo->Id) { case 52759: // Ancestral Awakening case 71610: // Echoes of Light (Althor's Abacus normal version) case 71641: // Echoes of Light (Althor's Abacus heroic version) maxSize = 1; power = POWER_HEALTH; break; case 54968: // Glyph of Holy Light maxSize = m_spellInfo->MaxAffectedTargets; power = POWER_HEALTH; break; case 57669: // Replenishment // In arenas Replenishment may only affect the caster if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->InArena()) { unitList.clear(); unitList.push_back(m_caster); break; } maxSize = 10; power = POWER_MANA; break; default: break; } break; case SPELLFAMILY_PRIEST: if (m_spellInfo->SpellFamilyFlags[0] == 0x10000000) // Circle of Healing { maxSize = m_caster->HasAura(55675) ? 6 : 5; // Glyph of Circle of Healing power = POWER_HEALTH; } else if (m_spellInfo->Id == 64844) // Divine Hymn { maxSize = 3; power = POWER_HEALTH; } else if (m_spellInfo->Id == 64904) // Hymn of Hope { maxSize = 3; power = POWER_MANA; } else break; // Remove targets outside caster's raid for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end();) { if (!(*itr)->IsInRaidWith(m_caster)) itr = unitList.erase(itr); else ++itr; } break; case SPELLFAMILY_DRUID: if (m_spellInfo->SpellFamilyFlags[1] == 0x04000000) // Wild Growth { maxSize = m_caster->HasAura(62970) ? 6 : 5; // Glyph of Wild Growth power = POWER_HEALTH; } else if (m_spellInfo->SpellFamilyFlags[2] == 0x0100) // Starfall { // Remove targets not in LoS or in stealth for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end();) { if ((*itr)->HasStealthAura() || (*itr)->HasInvisibilityAura() || !(*itr)->IsWithinLOSInMap(m_caster)) itr = unitList.erase(itr); else ++itr; } break; } else break; // Remove targets outside caster's raid for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end();) { if (!(*itr)->IsInRaidWith(m_caster)) itr = unitList.erase(itr); else ++itr; } break; default: break; } if (maxSize && power != -1) { if (Powers(power) == POWER_HEALTH) { if (unitList.size() > maxSize) { unitList.sort(Trinity::HealthPctOrderPred()); unitList.resize(maxSize); } } else { for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end();) { if ((*itr)->getPowerType() != (Powers)power) itr = unitList.erase(itr); else ++itr; } if (unitList.size() > maxSize) { unitList.sort(Trinity::PowerPctOrderPred((Powers)power)); unitList.resize(maxSize); } } } // Other special target selection goes here if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) { Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) if ((*j)->IsAffectedOnSpell(m_spellInfo)) maxTargets += (*j)->GetAmount(); if (m_spellInfo->Id == 5246) //Intimidating Shout unitList.remove(m_targets.getUnitTarget()); Trinity::RandomResizeList(unitList, maxTargets); } else { switch (m_spellInfo->Id) { case 27285: // Seed of Corruption proc spell case 49821: // Mind Sear proc spell Rank 1 case 53022: // Mind Sear proc spell Rank 2 unitList.remove(m_targets.getUnitTarget()); break; case 55789: // Improved Icy Talons case 59725: // Improved Spell Reflection - aoe aura unitList.remove(m_caster); break; case 72255: // Mark of the Fallen Champion (Deathbringer Saurfang) case 72444: case 72445: case 72446: for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end();) { if (!(*itr)->HasAura(72293)) itr = unitList.erase(itr); else ++itr; } break; case 69782: case 69796: // Ooze Flood case 69798: case 69801: // Ooze Flood // get 2 targets except 2 nearest unitList.sort(Trinity::ObjectDistanceOrderPred(m_caster)); unitList.resize(4); while (unitList.size() > 2) unitList.pop_front(); // crashfix if (unitList.empty()) return; break; case 68921: case 69049: // Soulstorm for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end();) { Position pos; (*itr)->GetPosition(&pos); if (m_caster->GetExactDist2d(&pos) <= 10.0f) itr = unitList.erase(itr); else ++itr; } break; case 70402: case 72511: case 72512: case 72513: if (Unit* owner = ObjectAccessor::GetUnit(*m_caster, m_caster->GetCreatorGUID())) unitList.remove(owner); break; case 71390: // Pact of the Darkfallen { for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end();) { if (!(*itr)->HasAura(71340)) itr = unitList.erase(itr); else ++itr; } bool remove = true; // we can do this, unitList is MAX 4 in size for (std::list<Unit*>::const_iterator itr = unitList.begin(); itr != unitList.end() && remove; ++itr) { if (!m_caster->IsWithinDist(*itr, 5.0f, false)) remove = false; for (std::list<Unit*>::const_iterator itr2 = unitList.begin(); itr2 != unitList.end() && remove; ++itr2) if (itr != itr2 && !(*itr2)->IsWithinDist(*itr, 5.0f, false)) remove = false; } if (remove) for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr) (*itr)->RemoveAura(71340); break; } } // Death Pact if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] & 0x00080000) { Unit * unit_to_add = NULL; for (std::list<Unit*>::iterator itr = unitList.begin() ; itr != unitList.end(); ++itr) { if ((*itr)->GetTypeId() == TYPEID_UNIT && (*itr)->GetOwnerGUID() == m_caster->GetGUID() && (*itr)->ToCreature()->GetCreatureInfo()->type == CREATURE_TYPE_UNDEAD) { unit_to_add = (*itr); break; } } if (unit_to_add) { unitList.clear(); unitList.push_back(unit_to_add); } // Pet not found - remove cooldown else { if (modOwner->GetTypeId() == TYPEID_PLAYER) modOwner->RemoveSpellCooldown(m_spellInfo->Id,true); SendCastResult(SPELL_FAILED_NO_PET); finish(false); } } } for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr) AddUnitTarget(*itr, i); } if (!gobjectList.empty()) { if (uint32 maxTargets = m_spellValue->MaxAffectedTargets) { Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_MAX_AFFECTED_TARGETS); for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) if ((*j)->IsAffectedOnSpell(m_spellInfo)) maxTargets += (*j)->GetAmount(); Trinity::RandomResizeList(gobjectList, maxTargets); } for (std::list<GameObject*>::iterator itr = gobjectList.begin(); itr != gobjectList.end(); ++itr) AddGOTarget(*itr, i); } } } void Spell::prepare(SpellCastTargets const* targets, AuraEffect const * triggeredByAura) { if (m_CastItem) m_castItemGUID = m_CastItem->GetGUID(); else m_castItemGUID = 0; m_targets = *targets; if (!m_targets.getUnitTargetGUID() && m_spellInfo->Targets & TARGET_FLAG_UNIT) { Unit *target = NULL; if (m_caster->GetTypeId() == TYPEID_UNIT) target = m_caster->getVictim(); else target = ObjectAccessor::GetUnit(*m_caster, m_caster->ToPlayer()->GetSelection()); if (target && IsValidSingleTargetSpell(target)) m_targets.setUnitTarget(target); else { SendCastResult(SPELL_FAILED_BAD_TARGETS); finish(false); return; } } if (Player* plrCaster = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself()) { //check for special spell conditions ConditionList conditions = sConditionMgr->GetConditionsForNotGroupedEntry(CONDITION_SOURCE_TYPE_SPELL, m_spellInfo->Id); if (!conditions.empty()) { if (!sConditionMgr->IsPlayerMeetToConditions(plrCaster, conditions)) { //SendCastResult(SPELL_FAILED_DONT_REPORT); SendCastResult(plrCaster, m_spellInfo, m_cast_count, SPELL_FAILED_DONT_REPORT); finish(false); return; } } } if (!m_targets.HasSrc() && m_spellInfo->Targets & TARGET_FLAG_SOURCE_LOCATION) m_targets.setSrc(*m_caster); if (!m_targets.HasDst() && m_spellInfo->Targets & TARGET_FLAG_DEST_LOCATION) { Unit *target = m_targets.getUnitTarget(); if (!target) { if (m_caster->GetTypeId() == TYPEID_UNIT) target = m_caster->getVictim(); else target = ObjectAccessor::GetUnit(*m_caster, m_caster->ToPlayer()->GetSelection()); } if (target) m_targets.setDst(*target); else { SendCastResult(SPELL_FAILED_BAD_TARGETS); finish(false); return; } } // Fill aura scaling information if (m_caster->IsControlledByPlayer() && !IsPassiveSpell(m_spellInfo->Id) && m_spellInfo->spellLevel && !IsChanneledSpell(m_spellInfo) && !m_IsTriggeredSpell) { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (m_spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA) { // Change aura with ranks only if basepoints are taken from spellInfo and aura is positive if (IsPositiveEffect(m_spellInfo->Id, i)) { m_auraScaleMask |= (1<<i); if (m_spellValue->EffectBasePoints[i] != m_spellInfo->EffectBasePoints[i]) { m_auraScaleMask = 0; break; } } } } } m_spellState = SPELL_STATE_PREPARING; if (triggeredByAura) m_triggeredByAuraSpell = triggeredByAura->GetSpellProto(); // create and add update event for this spell SpellEvent* Event = new SpellEvent(this); m_caster->m_Events.AddEvent(Event, m_caster->m_Events.CalculateTime(1)); //Prevent casting at cast another spell (ServerSide check) if (!m_IsTriggeredSpell && m_caster->IsNonMeleeSpellCasted(false, true, true) && m_cast_count) { SendCastResult(SPELL_FAILED_SPELL_IN_PROGRESS); finish(false); return; } if (sDisableMgr->IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, m_caster)) { SendCastResult(SPELL_FAILED_SPELL_UNAVAILABLE); finish(false); return; } LoadScripts(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); // Fill cost data (not use power for item casts m_powerCost = m_CastItem ? 0 : CalculatePowerCost(m_spellInfo, m_caster, m_spellSchoolMask); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); // Set combo point requirement if (m_IsTriggeredSpell || m_CastItem || !m_caster->m_movedPlayer) m_needComboPoints = false; SpellCastResult result = CheckCast(true); if (result != SPELL_CAST_OK && !IsAutoRepeat()) //always cast autorepeat dummy for triggering { if (triggeredByAura && !triggeredByAura->GetBase()->IsPassive()) { SendChannelUpdate(0); triggeredByAura->GetBase()->SetDuration(0); } SendCastResult(result); finish(false); return; } // Prepare data for triggers prepareDataForTriggerSystem(triggeredByAura); // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail) m_casttime = GetSpellCastTime(m_spellInfo, this); //m_caster->ModSpellCastTime(m_spellInfo, m_casttime, this); // don't allow channeled spells / spells with cast time to be casted while moving // (even if they are interrupted on moving, spells with almost immediate effect get to have their effect processed before movement interrupter kicks in) if ((IsChanneledSpell(m_spellInfo) || m_casttime) && m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->isMoving() && m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) { SendCastResult(SPELL_FAILED_MOVING); finish(false); return; } // set timer base at cast time ReSetTimer(); sLog->outDebug("Spell::prepare: spell id %u source %u caster %d triggered %u mask %u", m_spellInfo->Id, m_caster->GetEntry(), m_originalCaster ? m_originalCaster->GetEntry() : -1, m_IsTriggeredSpell ? 1 : 0, m_targets.getTargetMask()); //if (m_targets.getUnitTarget()) // sLog->outError("Spell::prepare: unit target %u", m_targets.getUnitTarget()->GetEntry()); //if (m_targets.HasDst()) // sLog->outError("Spell::prepare: pos target %f %f %f", m_targets.m_dstPos.m_positionX, m_targets.m_dstPos.m_positionY, m_targets.m_dstPos.m_positionZ); //Containers for channeled spells have to be set //TODO:Apply this to all casted spells if needed // Why check duration? 29350: channelled triggers channelled if (m_IsTriggeredSpell && (!IsChanneledSpell(m_spellInfo) || !GetSpellMaxDuration(m_spellInfo))) cast(true); else { // stealth must be removed at cast starting (at show channel bar) // skip triggered spell (item equip spell casting and other not explicit character casts/item uses) if (!m_IsTriggeredSpell && isSpellBreakStealth(m_spellInfo)) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CAST); for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (EffectTargetType[m_spellInfo->Effect[i]] == SPELL_REQUIRE_UNIT) { m_caster->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_SPELL_ATTACK); break; } } } m_caster->SetCurrentCastedSpell(this); SendSpellStart(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->AddGlobalCooldown(m_spellInfo,this); if (!m_casttime && !m_spellInfo->StartRecoveryTime && !m_castItemGUID //item: first cast may destroy item and second cast causes crash && GetCurrentContainer() == CURRENT_GENERIC_SPELL) cast(true); } } void Spell::cancel() { if (m_spellState == SPELL_STATE_FINISHED) return; SetReferencedFromCurrent(false); if (m_selfContainer && *m_selfContainer == this) *m_selfContainer = NULL; uint32 oldState = m_spellState; m_spellState = SPELL_STATE_FINISHED; m_autoRepeat = false; switch (oldState) { case SPELL_STATE_PREPARING: case SPELL_STATE_DELAYED: SendInterrupted(0); SendCastResult(SPELL_FAILED_INTERRUPTED); break; case SPELL_STATE_CASTING: for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if ((*ihit).missCondition == SPELL_MISS_NONE) if (Unit* unit = m_caster->GetGUID() == ihit->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID)) unit->RemoveOwnedAura(m_spellInfo->Id, m_originalCasterGUID, 0, AURA_REMOVE_BY_CANCEL); SendChannelUpdate(0); SendInterrupted(0); SendCastResult(SPELL_FAILED_INTERRUPTED); // spell is canceled-take mods and clear list if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->RemoveSpellMods(this); m_appliedMods.clear(); break; default: break; } if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->RemoveGlobalCooldown(m_spellInfo); m_caster->RemoveDynObject(m_spellInfo->Id); m_caster->RemoveGameObject(m_spellInfo->Id,true); //set state back so finish will be processed m_spellState = oldState; finish(false); } void Spell::cast(bool skipCheck) { // update pointers base at GUIDs to prevent access to non-existed already object UpdatePointers(); if (Unit *target = m_targets.getUnitTarget()) { // three check: prepare, cast (m_casttime > 0), hit (delayed) if (m_casttime && target->isAlive() && !target->IsFriendlyTo(m_caster) && !m_caster->canSeeOrDetect(target)) { SendCastResult(SPELL_FAILED_BAD_TARGETS); SendInterrupted(0); finish(false); return; } } else { // cancel at lost main target unit if (m_targets.getUnitTargetGUID() && m_targets.getUnitTargetGUID() != m_caster->GetGUID()) { cancel(); return; } } // now that we've done the basic check, now run the scripts // should be done before the spell is actually executed if (Player *playerCaster = m_caster->ToPlayer()) sScriptMgr->OnPlayerSpellCast(playerCaster, this, skipCheck); SetExecutedCurrently(true); if (m_caster->GetTypeId() != TYPEID_PLAYER && m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster) m_caster->SetInFront(m_targets.getUnitTarget()); // Should this be done for original caster? if (m_caster->GetTypeId() == TYPEID_PLAYER) { // Set spell which will drop charges for triggered cast spells // if not successfully casted, will be remove in finish(false) m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); } // triggered cast called from Spell::prepare where it was already checked if (!m_IsTriggeredSpell || !skipCheck) { SpellCastResult castResult = CheckCast(false); if (castResult != SPELL_CAST_OK) { SendCastResult(castResult); SendInterrupted(0); //restore spell mods if (m_caster->GetTypeId() == TYPEID_PLAYER) { m_caster->ToPlayer()->RestoreSpellMods(this); // cleanup after mod system // triggered spell pointer can be not removed in some cases m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); } finish(false); SetExecutedCurrently(false); return; } // additional check after cast bar completes (must not be in CheckCast) // if trade not complete then remember it in trade data if (m_targets.getTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (TradeData* my_trade = m_caster->ToPlayer()->GetTradeData()) { if (!my_trade->IsInAcceptProcess()) { // Spell will be casted at completing the trade. Silently ignore at this place my_trade->SetSpell(m_spellInfo->Id, m_CastItem); SendCastResult(SPELL_FAILED_DONT_REPORT); SendInterrupted(0); m_caster->ToPlayer()->RestoreSpellMods(this); // cleanup after mod system // triggered spell pointer can be not removed in some cases m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); finish(false); SetExecutedCurrently(false); return; } } } } } SelectSpellTargets(); // Spell may be finished after target map check if (m_spellState == SPELL_STATE_FINISHED) { SendInterrupted(0); //restore spell mods if (m_caster->GetTypeId() == TYPEID_PLAYER) { m_caster->ToPlayer()->RestoreSpellMods(this); // cleanup after mod system // triggered spell pointer can be not removed in some cases m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); } finish(false); SetExecutedCurrently(false); return; } if (m_spellInfo->SpellFamilyName) { if (m_spellInfo->excludeCasterAuraSpell && !IsPositiveSpell(m_spellInfo->excludeCasterAuraSpell)) m_preCastSpell = m_spellInfo->excludeCasterAuraSpell; else if (m_spellInfo->excludeTargetAuraSpell && !IsPositiveSpell(m_spellInfo->excludeTargetAuraSpell)) m_preCastSpell = m_spellInfo->excludeTargetAuraSpell; } switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { if (m_spellInfo->Mechanic == MECHANIC_BANDAGE) // Bandages m_preCastSpell = 11196; // Recently Bandaged break; } case SPELLFAMILY_MAGE: { // Permafrost if (m_spellInfo->SpellFamilyFlags[1] & 0x00001000 || m_spellInfo->SpellFamilyFlags[0] & 0x00100220) m_preCastSpell = 68391; break; } } // traded items have trade slot instead of guid in m_itemTargetGUID // set to real guid to be sent later to the client m_targets.updateTradeSlotItem(); if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (!m_IsTriggeredSpell && m_CastItem) { m_caster->ToPlayer()->GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_ITEM, m_CastItem->GetEntry()); m_caster->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM, m_CastItem->GetEntry()); } m_caster->ToPlayer()->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL, m_spellInfo->Id); } if (!m_IsTriggeredSpell) { // Powers have to be taken before SendSpellGo TakePower(); TakeReagents(); // we must remove reagents before HandleEffects to allow place crafted item in same slot } else if (Item* targetItem = m_targets.getItemTarget()) { /// Not own traded item (in trader trade slot) req. reagents including triggered spell case if (targetItem->GetOwnerGUID() != m_caster->GetGUID()) TakeReagents(); } // are there any spells need to be triggered after hit? // handle SPELL_AURA_ADD_TARGET_TRIGGER auras Unit::AuraEffectList const& targetTriggers = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_TARGET_TRIGGER); for (Unit::AuraEffectList::const_iterator i = targetTriggers.begin(); i != targetTriggers.end(); ++i) { if (!(*i)->IsAffectedOnSpell(m_spellInfo)) continue; SpellEntry const *auraSpellInfo = (*i)->GetSpellProto(); uint32 auraSpellIdx = (*i)->GetEffIndex(); if (SpellEntry const *spellInfo = sSpellStore.LookupEntry(auraSpellInfo->EffectTriggerSpell[auraSpellIdx])) { int32 auraBaseAmount = (*i)->GetBaseAmount(); int32 chance = m_caster->CalculateSpellDamage(NULL, auraSpellInfo, auraSpellIdx, &auraBaseAmount); m_ChanceTriggerSpells.push_back(std::make_pair(spellInfo, chance * (*i)->GetBase()->GetStackAmount())); } } if (m_customAttr & SPELL_ATTR0_CU_DIRECT_DAMAGE) CalculateDamageDoneForAllTargets(); // CAST SPELL SendSpellCooldown(); PrepareScriptHitHandlers(); for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { switch(m_spellInfo->Effect[i]) { case SPELL_EFFECT_CHARGE: case SPELL_EFFECT_CHARGE_DEST: case SPELL_EFFECT_JUMP: case SPELL_EFFECT_JUMP_DEST: case SPELL_EFFECT_LEAP_BACK: case SPELL_EFFECT_ACTIVATE_RUNE: HandleEffects(NULL,NULL,NULL,i); m_effectMask |= (1<<i); break; } } // we must send smsg_spell_go packet before m_castItem delete in TakeCastItem()... SendSpellGo(); // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells if ((m_spellInfo->speed > 0.0f && !IsChanneledSpell(m_spellInfo)) || m_spellInfo->Id == 14157) { // Remove used for cast item if need (it can be already NULL after TakeReagents call // in case delayed spell remove item at cast delay start TakeCastItem(); // Okay, maps created, now prepare flags m_immediateHandled = false; m_spellState = SPELL_STATE_DELAYED; SetDelayStart(0); if (m_caster->HasUnitState(UNIT_STAT_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true)) m_caster->ClearUnitState(UNIT_STAT_CASTING); } else { // Immediate spell, no big deal handle_immediate(); } if (m_customAttr & SPELL_ATTR0_CU_LINK_CAST) { if (const std::vector<int32> *spell_triggered = sSpellMgr->GetSpellLinked(m_spellInfo->Id)) { for (std::vector<int32>::const_iterator i = spell_triggered->begin(); i != spell_triggered->end(); ++i) if (*i < 0) m_caster->RemoveAurasDueToSpell(-(*i)); else m_caster->CastSpell(m_targets.getUnitTarget() ? m_targets.getUnitTarget() : m_caster, *i, true); } } if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); SetExecutedCurrently(false); } void Spell::handle_immediate() { // start channeling if applicable if (IsChanneledSpell(m_spellInfo)) { int32 duration = GetSpellDuration(m_spellInfo); if (duration) { // First mod_duration then haste - see Missile Barrage // Apply duration mod if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); // Apply haste mods m_caster->ModSpellCastTime(m_spellInfo, duration, this); m_spellState = SPELL_STATE_CASTING; m_caster->AddInterruptMask(m_spellInfo->ChannelInterruptFlags); SendChannelStart(duration); } } PrepareTargetProcessing(); // process immediate effects (items, ground, etc.) also initialize some variables _handle_immediate_phase(); for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); for (std::list<GOTargetInfo>::iterator ihit= m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); FinishTargetProcessing(); // spell is finished, perform some last features of the spell here _handle_finish_phase(); // Remove used for cast item if need (it can be already NULL after TakeReagents call TakeCastItem(); if (m_spellState != SPELL_STATE_CASTING) finish(true); // successfully finish spell cast (not last in case autorepeat or channel spell) } uint64 Spell::handle_delayed(uint64 t_offset) { UpdatePointers(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); uint64 next_time = 0; PrepareTargetProcessing(); if (!m_immediateHandled) { _handle_immediate_phase(); m_immediateHandled = true; } bool single_missile = (m_targets.HasDst()); // now recheck units targeting correctness (need before any effects apply to prevent adding immunity at first effect not allow apply second spell effect and similar cases) for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->processed == false) { if (single_missile || ihit->timeDelay <= t_offset) { ihit->timeDelay = t_offset; DoAllEffectOnTarget(&(*ihit)); } else if (next_time == 0 || ihit->timeDelay < next_time) next_time = ihit->timeDelay; } } // now recheck gameobject targeting correctness for (std::list<GOTargetInfo>::iterator ighit= m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit) { if (ighit->processed == false) { if (single_missile || ighit->timeDelay <= t_offset) DoAllEffectOnTarget(&(*ighit)); else if (next_time == 0 || ighit->timeDelay < next_time) next_time = ighit->timeDelay; } } FinishTargetProcessing(); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); // All targets passed - need finish phase if (next_time == 0) { // spell is finished, perform some last features of the spell here _handle_finish_phase(); finish(true); // successfully finish spell cast // return zero, spell is finished now return 0; } else { // spell is unfinished, return next execution time return next_time; } } void Spell::_handle_immediate_phase() { m_spellAura = NULL; // handle some immediate features of the spell here HandleThreatSpells(m_spellInfo->Id); PrepareScriptHitHandlers(); for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (m_spellInfo->Effect[j] == 0) continue; // apply Send Event effect to ground in case empty target lists if (m_spellInfo->Effect[j] == SPELL_EFFECT_SEND_EVENT && !HaveTargetsForEffect(j)) { HandleEffects(NULL, NULL, NULL, j); continue; } } // initialize Diminishing Returns Data m_diminishLevel = DIMINISHING_LEVEL_1; m_diminishGroup = DIMINISHING_NONE; // process items for (std::list<ItemTargetInfo>::iterator ihit= m_UniqueItemInfo.begin(); ihit != m_UniqueItemInfo.end(); ++ihit) DoAllEffectOnTarget(&(*ihit)); if (!m_originalCaster) return; uint8 oldEffMask = m_effectMask; // process ground for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (m_spellInfo->Effect[j] == 0) continue; if (EffectTargetType[m_spellInfo->Effect[j]] == SPELL_REQUIRE_DEST) { if (!m_targets.HasDst()) // FIXME: this will ignore dest set in effect m_targets.setDst(*m_caster); HandleEffects(m_originalCaster, NULL, NULL, j); m_effectMask |= (1<<j); } else if (EffectTargetType[m_spellInfo->Effect[j]] == SPELL_REQUIRE_NONE) { HandleEffects(m_originalCaster, NULL, NULL, j); m_effectMask |= (1<<j); } } if (oldEffMask != m_effectMask && m_UniqueTargetInfo.empty()) { uint32 procAttacker = m_procAttacker; if (!procAttacker) { bool positive = true; for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) // If at least one effect negative spell is negative hit if (m_effectMask & (1<<i) && !IsPositiveEffect(m_spellInfo->Id, i)) { positive = false; break; } switch(m_spellInfo->DmgClass) { case SPELL_DAMAGE_CLASS_MAGIC: if (positive) procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_POS; else procAttacker |= PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG; break; case SPELL_DAMAGE_CLASS_NONE: if (positive) procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_POS; else procAttacker |= PROC_FLAG_DONE_SPELL_NONE_DMG_CLASS_NEG; break; } } // Proc damage for spells which have only dest targets (2484 should proc 51486 for example) m_originalCaster->ProcDamageAndSpell(0, procAttacker, 0, m_procEx | PROC_EX_NORMAL_HIT, 0, BASE_ATTACK, m_spellInfo, m_triggeredByAuraSpell); } } void Spell::_handle_finish_phase() { if (m_caster->m_movedPlayer) { // Take for real after all targets are processed if (m_needComboPoints) m_caster->m_movedPlayer->ClearComboPoints(); // Real add combo points from effects if (m_comboPointGain) m_caster->m_movedPlayer->GainSpellComboPoints(m_comboPointGain); } } void Spell::SendSpellCooldown() { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* _player = (Player*)m_caster; // mana/health/etc potions, disabled by client (until combat out as declarate) if (m_CastItem && m_CastItem->IsPotion()) { // need in some way provided data for Spell::finish SendCooldownEvent _player->SetLastPotionId(m_CastItem->GetEntry()); return; } // have infinity cooldown but set at aura apply // do not set cooldown for triggered spells (needed by reincarnation) if (m_spellInfo->Attributes & (SPELL_ATTR0_DISABLED_WHILE_ACTIVE | SPELL_ATTR0_PASSIVE) || m_IsTriggeredSpell) return; _player->AddSpellAndCategoryCooldowns(m_spellInfo,m_CastItem ? m_CastItem->GetEntry() : 0, this); } void Spell::update(uint32 difftime) { // update pointers based at it's GUIDs UpdatePointers(); if (m_targets.getUnitTargetGUID() && !m_targets.getUnitTarget()) { sLog->outDebug("Spell %u is cancelled due to removal of target.", m_spellInfo->Id); cancel(); return; } // check if the player caster has moved before the spell finished if ((m_caster->GetTypeId() == TYPEID_PLAYER && m_timer != 0) && m_caster->isMoving() && (m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_MOVEMENT) && (m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK || !m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING))) { // don't cancel for melee, autorepeat, triggered and instant spells if (!IsNextMeleeSwingSpell() && !IsAutoRepeat() && !m_IsTriggeredSpell) cancel(); } switch(m_spellState) { case SPELL_STATE_PREPARING: { if (m_timer) { if (difftime >= m_timer) m_timer = 0; else m_timer -= difftime; } if (m_timer == 0 && !IsNextMeleeSwingSpell() && !IsAutoRepeat()) cast(m_spellInfo->CastingTimeIndex == 1); } break; case SPELL_STATE_CASTING: { if (m_timer > 0) { // check if there are alive targets left if (!UpdateChanneledTargetList()) { sLog->outDebug("Channeled spell %d is removed due to lack of targets", m_spellInfo->Id); SendChannelUpdate(0); finish(); } if (difftime >= m_timer) m_timer = 0; else m_timer -= difftime; } if (m_timer == 0) { SendChannelUpdate(0); // channeled spell processed independently for quest targeting // cast at creature (or GO) quest objectives update at successful cast channel finished // ignore autorepeat/melee casts for speed (not exist quest for spells (hm...) if (!IsAutoRepeat() && !IsNextMeleeSwingSpell()) { if (Player* p = m_caster->GetCharmerOrOwnerPlayerOrPlayerItself()) { for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { TargetInfo* target = &*ihit; if (!IS_CRE_OR_VEH_GUID(target->targetGUID)) continue; Unit* unit = m_caster->GetGUID() == target->targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target->targetGUID); if (unit == NULL) continue; p->CastedCreatureOrGO(unit->GetEntry(), unit->GetGUID(), m_spellInfo->Id); } for (std::list<GOTargetInfo>::iterator ihit = m_UniqueGOTargetInfo.begin(); ihit != m_UniqueGOTargetInfo.end(); ++ihit) { GOTargetInfo* target = &*ihit; GameObject* go = m_caster->GetMap()->GetGameObject(target->targetGUID); if (!go) continue; p->CastedCreatureOrGO(go->GetEntry(), go->GetGUID(), m_spellInfo->Id); } } } finish(); } } break; default: { }break; } } void Spell::finish(bool ok) { if (!m_caster) return; if (m_spellState == SPELL_STATE_FINISHED) return; m_spellState = SPELL_STATE_FINISHED; if (IsChanneledSpell(m_spellInfo)) m_caster->UpdateInterruptMask(); if (m_caster->HasUnitState(UNIT_STAT_CASTING) && !m_caster->IsNonMeleeSpellCasted(false, false, true)) m_caster->ClearUnitState(UNIT_STAT_CASTING); // Unsummon summon as possessed creatures on spell cancel if (IsChanneledSpell(m_spellInfo) && m_caster->GetTypeId() == TYPEID_PLAYER) { if (Unit *charm = m_caster->GetCharm()) if (charm->GetTypeId() == TYPEID_UNIT && charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET) && charm->GetUInt32Value(UNIT_CREATED_BY_SPELL) == m_spellInfo->Id) ((Puppet*)charm)->UnSummon(); } if (!ok) return; if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isSummon()) { // Unsummon statue uint32 spell = m_caster->GetUInt32Value(UNIT_CREATED_BY_SPELL); SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell); if (spellInfo && spellInfo->SpellIconID == 2056) { sLog->outDebug("Statue %d is unsummoned in spell %d finish", m_caster->GetGUIDLow(), m_spellInfo->Id); m_caster->setDeathState(JUST_DIED); return; } } if (IsAutoActionResetSpell()) { bool found = false; Unit::AuraEffectList const& vIgnoreReset = m_caster->GetAuraEffectsByType(SPELL_AURA_IGNORE_MELEE_RESET); for (Unit::AuraEffectList::const_iterator i = vIgnoreReset.begin(); i != vIgnoreReset.end(); ++i) { if ((*i)->IsAffectedOnSpell(m_spellInfo)) { found = true; break; } } if (!found && !(m_spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_RESET_AUTO_ACTIONS)) { m_caster->resetAttackTimer(BASE_ATTACK); if (m_caster->haveOffhandWeapon()) m_caster->resetAttackTimer(OFF_ATTACK); m_caster->resetAttackTimer(RANGED_ATTACK); } } // potions disabled by client, send event "not in combat" if need if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (!m_triggeredByAuraSpell) m_caster->ToPlayer()->UpdatePotionCooldown(this); // triggered spell pointer can be not set in some cases // this is needed for proper apply of triggered spell mods m_caster->ToPlayer()->SetSpellModTakingSpell(this, true); } // Take mods after trigger spell (needed for 14177 to affect 48664) // mods are taken only on succesfull cast and independantly from targets of the spell if (m_caster->GetTypeId() == TYPEID_PLAYER) { m_caster->ToPlayer()->RemoveSpellMods(this); m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); } // Stop Attack for some spells if (m_spellInfo->Attributes & SPELL_ATTR0_STOP_ATTACK_TARGET) m_caster->AttackStop(); } void Spell::SendCastResult(SpellCastResult result) { if (result == SPELL_CAST_OK) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (m_caster->ToPlayer()->GetSession()->PlayerLoading()) // don't send cast results at loading time return; SendCastResult((Player*)m_caster,m_spellInfo,m_cast_count,result); } void Spell::SendCastResult(Player* caster, SpellEntry const* spellInfo, uint8 cast_count, SpellCastResult result) { if (result == SPELL_CAST_OK) return; WorldPacket data(SMSG_CAST_FAILED, (4+1+1)); data << uint8(cast_count); // single cast or multi 2.3 (0/1) data << uint32(spellInfo->Id); data << uint8(result); // problem switch (result) { case SPELL_FAILED_REQUIRES_SPELL_FOCUS: data << uint32(spellInfo->RequiresSpellFocus); break; case SPELL_FAILED_REQUIRES_AREA: // hardcode areas limitation case switch(spellInfo->Id) { case 41617: // Cenarion Mana Salve case 41619: // Cenarion Healing Salve data << uint32(3905); break; case 41618: // Bottled Nethergon Energy case 41620: // Bottled Nethergon Vapor data << uint32(3842); break; case 45373: // Bloodberry Elixir data << uint32(4075); break; default: // default case (don't must be) data << uint32(0); break; } break; case SPELL_FAILED_TOTEMS: if (spellInfo->Totem[0]) data << uint32(spellInfo->Totem[0]); if (spellInfo->Totem[1]) data << uint32(spellInfo->Totem[1]); break; case SPELL_FAILED_TOTEM_CATEGORY: if (spellInfo->TotemCategory[0]) data << uint32(spellInfo->TotemCategory[0]); if (spellInfo->TotemCategory[1]) data << uint32(spellInfo->TotemCategory[1]); break; case SPELL_FAILED_EQUIPPED_ITEM_CLASS: data << uint32(spellInfo->EquippedItemClass); data << uint32(spellInfo->EquippedItemSubClassMask); //data << uint32(spellInfo->EquippedItemInventoryTypeMask); break; case SPELL_FAILED_TOO_MANY_OF_ITEM: { uint32 item = 0; for (int8 x=0;x < 3;x++) if (spellInfo->EffectItemType[x]) item = spellInfo->EffectItemType[x]; ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item); if (pProto && pProto->ItemLimitCategory) data << uint32(pProto->ItemLimitCategory); break; } default: break; } caster->GetSession()->SendPacket(&data); } void Spell::SendSpellStart() { if (!IsNeedSendToClient()) return; //sLog->outDebug("Sending SMSG_SPELL_START id=%u", m_spellInfo->Id); uint32 castFlags = CAST_FLAG_UNKNOWN_2; if (m_spellInfo->Attributes & SPELL_ATTR0_REQ_AMMO) castFlags |= CAST_FLAG_AMMO; if ((m_caster->GetTypeId() == TYPEID_PLAYER || (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isPet())) && m_spellInfo->powerType != POWER_HEALTH) castFlags |= CAST_FLAG_POWER_LEFT_SELF; if (m_spellInfo->runeCostID && m_spellInfo->powerType == POWER_RUNE) castFlags |= CAST_FLAG_UNKNOWN_19; WorldPacket data(SMSG_SPELL_START, (8+8+4+4+2)); if (m_CastItem) data.append(m_CastItem->GetPackGUID()); else data.append(m_caster->GetPackGUID()); data.append(m_caster->GetPackGUID()); data << uint8(m_cast_count); // pending spell cast? data << uint32(m_spellInfo->Id); // spellId data << uint32(castFlags); // cast flags data << uint32(m_timer); // delay? m_targets.write(data); if (castFlags & CAST_FLAG_POWER_LEFT_SELF) data << uint32(m_caster->GetPower((Powers)m_spellInfo->powerType)); if (castFlags & CAST_FLAG_AMMO) WriteAmmoToPacket(&data); if (castFlags & CAST_FLAG_UNKNOWN_23) { data << uint32(0); data << uint32(0); } m_caster->SendMessageToSet(&data, true); } void Spell::SendSpellGo() { // not send invisible spell casting if (!IsNeedSendToClient()) return; //sLog->outDebug("Sending SMSG_SPELL_GO id=%u", m_spellInfo->Id); uint32 castFlags = CAST_FLAG_UNKNOWN_9; // triggered spells with spell visual != 0 if ((m_IsTriggeredSpell && !IsAutoRepeatRangedSpell(m_spellInfo)) || m_triggeredByAuraSpell) castFlags |= CAST_FLAG_PENDING; if (m_spellInfo->Attributes & SPELL_ATTR0_REQ_AMMO) castFlags |= CAST_FLAG_AMMO; // arrows/bullets visual if ((m_caster->GetTypeId() == TYPEID_PLAYER || (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isPet())) && m_spellInfo->powerType != POWER_HEALTH) castFlags |= CAST_FLAG_POWER_LEFT_SELF; // should only be sent to self, but the current messaging doesn't make that possible if ((m_caster->GetTypeId() == TYPEID_PLAYER) && (m_caster->getClass() == CLASS_DEATH_KNIGHT) && m_spellInfo->runeCostID && m_spellInfo->powerType == POWER_RUNE) { castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list castFlags |= CAST_FLAG_UNKNOWN_9; // ?? } if (IsSpellHaveEffect(m_spellInfo, SPELL_EFFECT_ACTIVATE_RUNE)) { castFlags |= CAST_FLAG_RUNE_LIST; // rune cooldowns list castFlags |= CAST_FLAG_UNKNOWN_19; // same as in SMSG_SPELL_START } WorldPacket data(SMSG_SPELL_GO, 50); // guess size if (m_CastItem) data.append(m_CastItem->GetPackGUID()); else data.append(m_caster->GetPackGUID()); data.append(m_caster->GetPackGUID()); data << uint8(m_cast_count); // pending spell cast? data << uint32(m_spellInfo->Id); // spellId data << uint32(castFlags); // cast flags data << uint32(getMSTime()); // timestamp /* // statement below seems to be wrong - i've seen spells with both unit and dest target // Can't have TARGET_FLAG_UNIT when *_LOCATION is present - it breaks missile visuals if (m_targets.getTargetMask() & (TARGET_FLAG_SOURCE_LOCATION | TARGET_FLAG_DEST_LOCATION)) m_targets.setTargetMask(m_targets.getTargetMask() & ~TARGET_FLAG_UNIT); else if (m_targets.getIntTargetFlags() & FLAG_INT_UNIT) m_targets.setTargetMask(m_targets.getTargetMask() | TARGET_FLAG_UNIT); */ WriteSpellGoTargets(&data); m_targets.write(data); if (castFlags & CAST_FLAG_POWER_LEFT_SELF) data << uint32(m_caster->GetPower((Powers)m_spellInfo->powerType)); if (castFlags & CAST_FLAG_RUNE_LIST) // rune cooldowns list { uint8 v1 = m_runesState; uint8 v2 = m_caster->ToPlayer()->GetRunesState(); data << uint8(v1); // runes state before data << uint8(v2); // runes state after for (uint8 i = 0; i < MAX_RUNES; ++i) { uint8 m = (1 << i); if (m & v1) // usable before... if (!(m & v2)) // ...but on cooldown now... data << uint8(0); // some unknown byte (time?) } } if (castFlags & CAST_FLAG_UNKNOWN_18) // unknown wotlk { data << float(0); data << uint32(0); } if (castFlags & CAST_FLAG_AMMO) WriteAmmoToPacket(&data); if (castFlags & CAST_FLAG_UNKNOWN_20) // unknown wotlk { data << uint32(0); data << uint32(0); } if (m_targets.getTargetMask() & TARGET_FLAG_DEST_LOCATION) { data << uint8(0); } m_caster->SendMessageToSet(&data, true); } void Spell::WriteAmmoToPacket(WorldPacket * data) { uint32 ammoInventoryType = 0; uint32 ammoDisplayID = 0; if (m_caster->GetTypeId() == TYPEID_PLAYER) { Item *pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK); if (pItem) { ammoInventoryType = pItem->GetProto()->InventoryType; if (ammoInventoryType == INVTYPE_THROWN) ammoDisplayID = pItem->GetProto()->DisplayInfoID; else { uint32 ammoID = m_caster->ToPlayer()->GetUInt32Value(PLAYER_AMMO_ID); if (ammoID) { ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(ammoID); if (pProto) { ammoDisplayID = pProto->DisplayInfoID; ammoInventoryType = pProto->InventoryType; } } else if (m_caster->HasAura(46699)) // Requires No Ammo { ammoDisplayID = 5996; // normal arrow ammoInventoryType = INVTYPE_AMMO; } } } } else { for (uint8 i = 0; i < 3; ++i) { if (uint32 item_id = m_caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + i)) { if (ItemEntry const * itemEntry = sItemStore.LookupEntry(item_id)) { if (itemEntry->Class == ITEM_CLASS_WEAPON) { switch(itemEntry->SubClass) { case ITEM_SUBCLASS_WEAPON_THROWN: ammoDisplayID = itemEntry->DisplayId; ammoInventoryType = itemEntry->InventoryType; break; case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_CROSSBOW: ammoDisplayID = 5996; // is this need fixing? ammoInventoryType = INVTYPE_AMMO; break; case ITEM_SUBCLASS_WEAPON_GUN: ammoDisplayID = 5998; // is this need fixing? ammoInventoryType = INVTYPE_AMMO; break; } if (ammoDisplayID) break; } } } } } *data << uint32(ammoDisplayID); *data << uint32(ammoInventoryType); } void Spell::WriteSpellGoTargets(WorldPacket * data) { // This function also fill data for channeled spells: // m_needAliveTargetMask req for stop channelig if one target die uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO uint32 miss = 0; for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if ((*ihit).effectMask == 0) // No effect apply - all immuned add state { // possibly SPELL_MISS_IMMUNE2 for this?? ihit->missCondition = SPELL_MISS_IMMUNE2; ++miss; } else if ((*ihit).missCondition == SPELL_MISS_NONE) ++hit; else ++miss; } *data << (uint8)hit; for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits { *data << uint64(ihit->targetGUID); m_channelTargetEffectMask |=ihit->effectMask; } } for (std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit) *data << uint64(ighit->targetGUID); // Always hits *data << (uint8)miss; for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->missCondition != SPELL_MISS_NONE) // Add only miss { *data << uint64(ihit->targetGUID); *data << uint8(ihit->missCondition); if (ihit->missCondition == SPELL_MISS_REFLECT) *data << uint8(ihit->reflectResult); } } // Reset m_needAliveTargetMask for non channeled spell if (!IsChanneledSpell(m_spellInfo)) m_channelTargetEffectMask = 0; } void Spell::SendLogExecute() { WorldPacket data(SMSG_SPELLLOGEXECUTE, (8+4+4+4+4+8)); data.append(m_caster->GetPackGUID()); data << uint32(m_spellInfo->Id); uint8 effCount = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (m_effectExecuteData[i]) ++effCount; } if (!effCount) return; data << uint32(effCount); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (!m_effectExecuteData[i]) continue; data << uint32(m_spellInfo->Effect[i]); // spell effect data.append(*m_effectExecuteData[i]); delete m_effectExecuteData[i]; m_effectExecuteData[i] = NULL; } m_caster->SendMessageToSet(&data, true); } void Spell::ExecuteLogEffectTakeTargetPower(uint8 effIndex, Unit * target, uint32 powerType, uint32 powerTaken, float gainMultiplier) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(target->GetPackGUID()); *m_effectExecuteData[effIndex] << uint32(powerTaken); *m_effectExecuteData[effIndex] << uint32(powerType); *m_effectExecuteData[effIndex] << float(gainMultiplier); } void Spell::ExecuteLogEffectExtraAttacks(uint8 effIndex, Unit * victim, uint32 attCount) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(victim->GetPackGUID()); *m_effectExecuteData[effIndex] << uint32(attCount); } void Spell::ExecuteLogEffectInterruptCast(uint8 effIndex, Unit * victim, uint32 spellId) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(victim->GetPackGUID()); *m_effectExecuteData[effIndex] << uint32(spellId); } void Spell::ExecuteLogEffectDurabilityDamage(uint8 effIndex, Unit * victim, uint32 /*itemslot*/, uint32 damage) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(victim->GetPackGUID()); *m_effectExecuteData[effIndex] << uint32(m_spellInfo->Id); *m_effectExecuteData[effIndex] << uint32(damage); } void Spell::ExecuteLogEffectOpenLock(uint8 effIndex, Object * obj) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(obj->GetPackGUID()); } void Spell::ExecuteLogEffectCreateItem(uint8 effIndex, uint32 entry) { InitEffectExecuteData(effIndex); *m_effectExecuteData[effIndex] << uint32(entry); } void Spell::ExecuteLogEffectDestroyItem(uint8 effIndex, uint32 entry) { InitEffectExecuteData(effIndex); *m_effectExecuteData[effIndex] << uint32(entry); } void Spell::ExecuteLogEffectSummonObject(uint8 effIndex, WorldObject * obj) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(obj->GetPackGUID()); } void Spell::ExecuteLogEffectUnsummonObject(uint8 effIndex, WorldObject * obj) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(obj->GetPackGUID()); } void Spell::ExecuteLogEffectResurrect(uint8 effIndex, Unit * target) { InitEffectExecuteData(effIndex); m_effectExecuteData[effIndex]->append(target->GetPackGUID()); } void Spell::SendInterrupted(uint8 result) { WorldPacket data(SMSG_SPELL_FAILURE, (8+4+1)); data.append(m_caster->GetPackGUID()); data << uint8(m_cast_count); data << uint32(m_spellInfo->Id); data << uint8(result); m_caster->SendMessageToSet(&data, true); data.Initialize(SMSG_SPELL_FAILED_OTHER, (8+4)); data.append(m_caster->GetPackGUID()); data << uint8(m_cast_count); data << uint32(m_spellInfo->Id); data << uint8(result); m_caster->SendMessageToSet(&data, true); } void Spell::SendChannelUpdate(uint32 time) { if (time == 0) { m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0); m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, 0); } if (m_caster->GetTypeId() != TYPEID_PLAYER) return; WorldPacket data(MSG_CHANNEL_UPDATE, 8+4); data.append(m_caster->GetPackGUID()); data << uint32(time); m_caster->SendMessageToSet(&data, true); } void Spell::SendChannelStart(uint32 duration) { WorldObject* target = NULL; // select first not resisted target from target list for _0_ effect if (!m_UniqueTargetInfo.empty()) { for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr) { if ((itr->effectMask & (1 << 0)) && itr->reflectResult == SPELL_MISS_NONE && itr->targetGUID != m_caster->GetGUID()) { target = ObjectAccessor::GetUnit(*m_caster, itr->targetGUID); break; } } } else if (!m_UniqueGOTargetInfo.empty()) { for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr) { if (itr->effectMask & (1 << 0)) { target = m_caster->GetMap()->GetGameObject(itr->targetGUID); break; } } } WorldPacket data(MSG_CHANNEL_START, (8+4+4)); data.append(m_caster->GetPackGUID()); data << uint32(m_spellInfo->Id); data << uint32(duration); m_caster->SendMessageToSet(&data, true); m_timer = duration; if (target) m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, target->GetGUID()); m_caster->SetUInt32Value(UNIT_CHANNEL_SPELL, m_spellInfo->Id); } void Spell::SendResurrectRequest(Player* target) { // Both players and NPCs can resurrect using spells - have a look at creature 28487 for example // However, the packet structure differs slightly const char* sentName = m_caster->GetTypeId() == TYPEID_PLAYER ? "" : m_caster->GetNameForLocaleIdx(target->GetSession()->GetSessionDbLocaleIndex()); WorldPacket data(SMSG_RESURRECT_REQUEST, (8+4+strlen(sentName)+1+1+1)); data << uint64(m_caster->GetGUID()); data << uint32(strlen(sentName) + 1); data << sentName; data << uint8(0); data << uint8(m_caster->GetTypeId() == TYPEID_PLAYER ? 0 : 1); target->GetSession()->SendPacket(&data); } void Spell::SendPlaySpellVisual(uint32 SpellID) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 8 + 4); data << uint64(m_caster->GetGUID()); data << uint32(SpellID); // spell visual id? m_caster->ToPlayer()->GetSession()->SendPacket(&data); } void Spell::TakeCastItem() { if (!m_CastItem || m_caster->GetTypeId() != TYPEID_PLAYER) return; // not remove cast item at triggered spell (equipping, weapon damage, etc) if (m_IsTriggeredSpell) return; ItemPrototype const *proto = m_CastItem->GetProto(); if (!proto) { // This code is to avoid a crash // I'm not sure, if this is really an error, but I guess every item needs a prototype sLog->outError("Cast item has no item prototype highId=%d, lowId=%d",m_CastItem->GetGUIDHigh(), m_CastItem->GetGUIDLow()); return; } bool expendable = false; bool withoutCharges = false; for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) { if (proto->Spells[i].SpellId) { // item has limited charges if (proto->Spells[i].SpellCharges) { if (proto->Spells[i].SpellCharges < 0) expendable = true; int32 charges = m_CastItem->GetSpellCharges(i); // item has charges left if (charges) { (charges > 0) ? --charges : ++charges; // abs(charges) less at 1 after use if (proto->Stackable == 1) m_CastItem->SetSpellCharges(i, charges); m_CastItem->SetState(ITEM_CHANGED, (Player*)m_caster); } // all charges used withoutCharges = (charges == 0); } } } if (expendable && withoutCharges) { uint32 count = 1; m_caster->ToPlayer()->DestroyItemCount(m_CastItem, count, true); // prevent crash at access to deleted m_targets.getItemTarget if (m_CastItem == m_targets.getItemTarget()) m_targets.setItemTarget(NULL); m_CastItem = NULL; } } void Spell::TakePower() { if (m_CastItem || m_triggeredByAuraSpell) return; bool hit = true; if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (m_spellInfo->powerType == POWER_RAGE || m_spellInfo->powerType == POWER_ENERGY) if (uint64 targetGUID = m_targets.getUnitTargetGUID()) for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->targetGUID == targetGUID) { if (ihit->missCondition != SPELL_MISS_NONE && ihit->missCondition != SPELL_MISS_MISS/* && ihit->targetGUID != m_caster->GetGUID()*/) hit = false; if (ihit->missCondition != SPELL_MISS_NONE) { //lower spell cost on fail (by talent aura) if (Player *modOwner = m_caster->ToPlayer()->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, m_powerCost); } break; } } Powers powerType = Powers(m_spellInfo->powerType); if (hit && powerType == POWER_RUNE) { TakeRunePower(); return; } if (!m_powerCost) return; // health as power used if (m_spellInfo->powerType == POWER_HEALTH) { m_caster->ModifyHealth(-(int32)m_powerCost); return; } if (m_spellInfo->powerType >= MAX_POWERS) { sLog->outError("Spell::TakePower: Unknown power type '%d'", m_spellInfo->powerType); return; } if (hit) m_caster->ModifyPower(powerType, -m_powerCost); else m_caster->ModifyPower(powerType, -irand(0, m_powerCost/4)); // Set the five second timer if (powerType == POWER_MANA && m_powerCost > 0) m_caster->SetLastManaUse(getMSTime()); } void Spell::TakeAmmo() { if (m_attackType == RANGED_ATTACK && m_caster->GetTypeId() == TYPEID_PLAYER) { Item *pItem = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK); // wands don't have ammo if (!pItem || pItem->IsBroken() || pItem->GetProto()->SubClass == ITEM_SUBCLASS_WEAPON_WAND) return; if (pItem->GetProto()->InventoryType == INVTYPE_THROWN) { if (pItem->GetMaxStackCount() == 1) { // decrease durability for non-stackable throw weapon m_caster->ToPlayer()->DurabilityPointLossForEquipSlot(EQUIPMENT_SLOT_RANGED); } else { // decrease items amount for stackable throw weapon uint32 count = 1; m_caster->ToPlayer()->DestroyItemCount(pItem, count, true); } } else if (uint32 ammo = m_caster->ToPlayer()->GetUInt32Value(PLAYER_AMMO_ID)) m_caster->ToPlayer()->DestroyItemCount(ammo, 1, true); } } SpellCastResult Spell::CheckRuneCost(uint32 runeCostID) { if (m_spellInfo->powerType != POWER_RUNE || !runeCostID) return SPELL_CAST_OK; if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_CAST_OK; Player *plr = (Player*)m_caster; if (plr->getClass() != CLASS_DEATH_KNIGHT) return SPELL_CAST_OK; SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(runeCostID); if (!src) return SPELL_CAST_OK; if (src->NoRuneCost()) return SPELL_CAST_OK; int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death for (uint32 i = 0; i < RUNE_DEATH; ++i) { runeCost[i] = src->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this); } runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later for (uint32 i = 0; i < MAX_RUNES; ++i) { RuneType rune = plr->GetCurrentRune(i); if ((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0)) runeCost[rune]--; } for (uint32 i = 0; i < RUNE_DEATH; ++i) if (runeCost[i] > 0) runeCost[RUNE_DEATH] += runeCost[i]; if (runeCost[RUNE_DEATH] > MAX_RUNES) return SPELL_FAILED_NO_POWER; // not sure if result code is correct return SPELL_CAST_OK; } void Spell::TakeRunePower() { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player *plr = (Player*)m_caster; if (plr->getClass() != CLASS_DEATH_KNIGHT) return; SpellRuneCostEntry const *src = sSpellRuneCostStore.LookupEntry(m_spellInfo->runeCostID); if (!src || (src->NoRuneCost() && src->NoRunicPowerGain())) return; m_runesState = plr->GetRunesState(); // store previous state int32 runeCost[NUM_RUNE_TYPES]; // blood, frost, unholy, death for (uint32 i = 0; i < RUNE_DEATH; ++i) { runeCost[i] = src->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this); } runeCost[RUNE_DEATH] = 0; // calculated later for (uint32 i = 0; i < MAX_RUNES; ++i) { RuneType rune = plr->GetCurrentRune(i); if ((plr->GetRuneCooldown(i) == 0) && (runeCost[rune] > 0)) { plr->SetRuneCooldown(i, plr->GetRuneBaseCooldown(i)); plr->SetLastUsedRune(RuneType(rune)); runeCost[rune]--; } } runeCost[RUNE_DEATH] = runeCost[RUNE_BLOOD] + runeCost[RUNE_UNHOLY] + runeCost[RUNE_FROST]; if (runeCost[RUNE_DEATH] > 0) { for (uint32 i = 0; i < MAX_RUNES; ++i) { RuneType rune = plr->GetCurrentRune(i); if ((plr->GetRuneCooldown(i) == 0) && (rune == RUNE_DEATH)) { plr->SetRuneCooldown(i, plr->GetRuneBaseCooldown(i)); plr->SetLastUsedRune(RuneType(rune)); runeCost[rune]--; plr->RestoreBaseRune(i); if (runeCost[RUNE_DEATH] == 0) break; } } } // you can gain some runic power when use runes float rp = (float)src->runePowerGain; rp *= sWorld->getRate(RATE_POWER_RUNICPOWER_INCOME); plr->ModifyPower(POWER_RUNIC_POWER, (int32)rp); } void Spell::TakeReagents() { if (m_IsTriggeredSpell) // reagents used in triggered spell removed by original spell or don't must be removed. { Item* targetItem = m_targets.getItemTarget(); /// Not own traded item (in trader trade slot) req. reagents including triggered spell case if (!(targetItem && targetItem->GetOwnerGUID() != m_caster->GetGUID())) return; } if (m_caster->GetTypeId() != TYPEID_PLAYER) return; // do not take reagents for these item casts if (m_CastItem && m_CastItem->GetProto()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST) return; Player* p_caster = (Player*)m_caster; if (p_caster->CanNoReagentCast(m_spellInfo)) return; for (uint32 x = 0; x < MAX_SPELL_REAGENTS; ++x) { if (m_spellInfo->Reagent[x] <= 0) continue; uint32 itemid = m_spellInfo->Reagent[x]; uint32 itemcount = m_spellInfo->ReagentCount[x]; // if CastItem is also spell reagent if (m_CastItem) { ItemPrototype const *proto = m_CastItem->GetProto(); if (proto && proto->ItemId == itemid) { for (int s = 0; s < MAX_ITEM_PROTO_SPELLS; ++s) { // CastItem will be used up and does not count as reagent int32 charges = m_CastItem->GetSpellCharges(s); if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2) { ++itemcount; break; } } m_CastItem = NULL; } } // if getItemTarget is also spell reagent if (m_targets.getItemTargetEntry() == itemid) m_targets.setItemTarget(NULL); p_caster->DestroyItemCount(itemid, itemcount, true); } } void Spell::HandleThreatSpells(uint32 spellId) { if (!m_targets.getUnitTarget() || !spellId) return; if (!m_targets.getUnitTarget()->CanHaveThreatList()) return; uint16 threat = sSpellMgr->GetSpellThreat(spellId); if (!threat) return; m_targets.getUnitTarget()->AddThreat(m_caster, float(threat)); sLog->outStaticDebug("Spell %u, rank %u, added an additional %i threat", spellId, sSpellMgr->GetSpellRank(spellId), threat); } void Spell::HandleEffects(Unit *pUnitTarget,Item *pItemTarget,GameObject *pGOTarget,uint32 i) { //effect has been handled, skip it if (m_effectMask & (1<<i)) return; unitTarget = pUnitTarget; itemTarget = pItemTarget; gameObjTarget = pGOTarget; uint8 eff = m_spellInfo->Effect[i]; sLog->outDebug("Spell: %u Effect : %u", m_spellInfo->Id, eff); //we do not need DamageMultiplier here. damage = CalculateDamage(i, NULL); bool preventDefault = CallScriptEffectHandlers((SpellEffIndex)i); if (!preventDefault && eff < TOTAL_SPELL_EFFECTS) { (this->*SpellEffects[eff])((SpellEffIndex)i); } } SpellCastResult Spell::CheckCast(bool strict) { // check death state if (!m_IsTriggeredSpell && !m_caster->isAlive() && !(m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE) && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD)) return SPELL_FAILED_CASTER_DEAD; // check cooldowns to prevent cheating if (m_caster->GetTypeId() == TYPEID_PLAYER && !(m_spellInfo->Attributes & SPELL_ATTR0_PASSIVE)) { //can cast triggered (by aura only?) spells while have this flag if (!m_IsTriggeredSpell && m_caster->ToPlayer()->HasFlag(PLAYER_FLAGS, PLAYER_ALLOW_ONLY_ABILITY)) return SPELL_FAILED_SPELL_IN_PROGRESS; if (m_caster->ToPlayer()->HasSpellCooldown(m_spellInfo->Id) || (strict && !m_IsTriggeredSpell && m_caster->ToPlayer()->HasGlobalCooldown(m_spellInfo))) { if (m_triggeredByAuraSpell) return SPELL_FAILED_DONT_REPORT; else return SPELL_FAILED_NOT_READY; } } // only allow triggered spells if at an ended battleground if (!m_IsTriggeredSpell && m_caster->GetTypeId() == TYPEID_PLAYER) if (Battleground * bg = m_caster->ToPlayer()->GetBattleground()) if (bg->GetStatus() == STATUS_WAIT_LEAVE) return SPELL_FAILED_DONT_REPORT; if(m_caster->GetTypeId() == TYPEID_PLAYER && VMAP::VMapFactory::createOrGetVMapManager()->isLineOfSightCalcEnabled()) { if(m_spellInfo->Attributes & SPELL_ATTR0_OUTDOORS_ONLY && !m_caster->GetMap()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ())) return SPELL_FAILED_ONLY_OUTDOORS; if(m_spellInfo->Attributes & SPELL_ATTR0_INDOORS_ONLY && m_caster->GetMap()->IsOutdoors(m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ())) return SPELL_FAILED_ONLY_INDOORS; } // only check at first call, Stealth auras are already removed at second call // for now, ignore triggered spells if (strict && !m_IsTriggeredSpell) { bool checkForm = true; // Ignore form req aura Unit::AuraEffectList const& ignore = m_caster->GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_SHAPESHIFT); for (Unit::AuraEffectList::const_iterator i = ignore.begin(); i != ignore.end(); ++i) { if (!(*i)->IsAffectedOnSpell(m_spellInfo)) continue; checkForm = false; break; } if (checkForm) { // Cannot be used in this stance/form SpellCastResult shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->GetShapeshiftForm()); if (shapeError != SPELL_CAST_OK) return shapeError; if ((m_spellInfo->Attributes & SPELL_ATTR0_ONLY_STEALTHED) && !(m_caster->HasStealthAura())) return SPELL_FAILED_ONLY_STEALTHED; } } bool reqCombat=true; Unit::AuraEffectList const& stateAuras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_IGNORE_AURASTATE); for (Unit::AuraEffectList::const_iterator j = stateAuras.begin(); j != stateAuras.end(); ++j) { if ((*j)->IsAffectedOnSpell(m_spellInfo)) { m_needComboPoints = false; if ((*j)->GetMiscValue() == 1) { reqCombat=false; break; } } } // caster state requirements // not for triggered spells (needed by execute) if (!m_IsTriggeredSpell) { if (m_spellInfo->CasterAuraState && !m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraState), m_spellInfo, m_caster)) return SPELL_FAILED_CASTER_AURASTATE; if (m_spellInfo->CasterAuraStateNot && m_caster->HasAuraState(AuraState(m_spellInfo->CasterAuraStateNot), m_spellInfo, m_caster)) return SPELL_FAILED_CASTER_AURASTATE; // Note: spell 62473 requres casterAuraSpell = triggering spell if (m_spellInfo->casterAuraSpell && !m_caster->HasAura(m_spellInfo->casterAuraSpell)) return SPELL_FAILED_CASTER_AURASTATE; if (m_spellInfo->excludeCasterAuraSpell && m_caster->HasAura(m_spellInfo->excludeCasterAuraSpell)) return SPELL_FAILED_CASTER_AURASTATE; if (reqCombat && m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo)) return SPELL_FAILED_AFFECTING_COMBAT; } // cancel autorepeat spells if cast start when moving // (not wand currently autorepeat cast delayed to moving stop anyway in spell update code) if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->ToPlayer()->isMoving()) { // skip stuck spell to allow use it in falling case and apply spell limitations at movement if ((!m_caster->HasUnitMovementFlag(MOVEMENTFLAG_FALLING) || m_spellInfo->Effect[0] != SPELL_EFFECT_STUCK) && (IsAutoRepeat() || (m_spellInfo->AuraInterruptFlags & AURA_INTERRUPT_FLAG_NOT_SEATED) != 0)) return SPELL_FAILED_MOVING; } Unit *target = m_targets.getUnitTarget(); // In pure self-cast spells, the client won't send any unit target if (!target && (m_targets.getTargetMask() == TARGET_FLAG_SELF || m_targets.getTargetMask() & TARGET_FLAG_UNIT_CASTER)) // TARGET_FLAG_SELF == 0, remember! target = m_caster; if (target) { // target state requirements (not allowed state), apply to self also if (!m_IsTriggeredSpell && m_spellInfo->TargetAuraStateNot && target->HasAuraState(AuraState(m_spellInfo->TargetAuraStateNot), m_spellInfo, m_caster)) return SPELL_FAILED_TARGET_AURASTATE; if (m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell)) return SPELL_FAILED_TARGET_AURASTATE; if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell)) return SPELL_FAILED_TARGET_AURASTATE; if (!m_IsTriggeredSpell && target == m_caster && m_spellInfo->AttributesEx & SPELL_ATTR1_CANT_TARGET_SELF) return SPELL_FAILED_BAD_TARGETS; bool non_caster_target = target != m_caster && !sSpellMgr->IsSpellWithCasterSourceTargetsOnly(m_spellInfo); if (non_caster_target) { // target state requirements (apply to non-self only), to allow cast affects to self like Dirty Deeds if (!m_IsTriggeredSpell && m_spellInfo->TargetAuraState && !target->HasAuraState(AuraState(m_spellInfo->TargetAuraState), m_spellInfo, m_caster)) return SPELL_FAILED_TARGET_AURASTATE; // Not allow casting on flying player or on vehicle player (if caster isnt vehicle) if (target->HasUnitState(UNIT_STAT_IN_FLIGHT) || (target->HasUnitState(UNIT_STAT_ONVEHICLE) && target->GetVehicleBase() != m_caster)) return SPELL_FAILED_BAD_TARGETS; if (!m_IsTriggeredSpell && !m_caster->canSeeOrDetect(target)) return SPELL_FAILED_BAD_TARGETS; if (m_caster->GetTypeId() == TYPEID_PLAYER) { // Do not allow to banish target tapped by someone not in caster's group if (m_spellInfo->Mechanic == MECHANIC_BANISH) if (Creature *targetCreature = target->ToCreature()) if (targetCreature->hasLootRecipient() && !targetCreature->isTappedBy(m_caster->ToPlayer())) return SPELL_FAILED_CANT_CAST_ON_TAPPED; if (m_customAttr & SPELL_ATTR0_CU_PICKPOCKET) { if (target->GetTypeId() == TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; else if ((target->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0) return SPELL_FAILED_TARGET_NO_POCKETS; } // Not allow disarm unarmed player if (m_spellInfo->Mechanic == MECHANIC_DISARM) { if (target->GetTypeId() == TYPEID_PLAYER) { Player *player = target->ToPlayer(); if (!player->GetWeaponForAttack(BASE_ATTACK) || !player->IsUseEquipedWeapon(true)) return SPELL_FAILED_TARGET_NO_WEAPONS; } else if (!target->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID)) return SPELL_FAILED_TARGET_NO_WEAPONS; } } if (!m_IsTriggeredSpell && VMAP::VMapFactory::checkSpellForLoS(m_spellInfo->Id) && !m_caster->IsWithinLOSInMap(target)) return SPELL_FAILED_LINE_OF_SIGHT; } else if (m_caster == target) { if (m_caster->GetTypeId() == TYPEID_PLAYER) // Target - is player caster { // Additional check for some spells // If 0 spell effect empty - client not send target data (need use selection) // TODO: check it on next client version if (m_targets.getTargetMask() == TARGET_FLAG_SELF && m_spellInfo->EffectImplicitTargetA[1] == TARGET_UNIT_TARGET_ENEMY) { target = m_caster->GetUnit(*m_caster, m_caster->ToPlayer()->GetSelection()); if (target) m_targets.setUnitTarget(target); else return SPELL_FAILED_BAD_TARGETS; } // Lay on Hands - cannot be self-cast on paladin with Forbearance or after using Avenging Wrath if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN && m_spellInfo->SpellFamilyFlags[0] & 0x0008000) if (target->HasAura(61988)) // Immunity shield marker return SPELL_FAILED_TARGET_AURASTATE; } } // check pet presents for (int j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (m_spellInfo->EffectImplicitTargetA[j] == TARGET_UNIT_PET) { target = m_caster->GetGuardianPet(); if (!target) { if (m_triggeredByAuraSpell) // not report pet not existence for triggered spells return SPELL_FAILED_DONT_REPORT; else return SPELL_FAILED_NO_PET; } break; } } //check creature type //ignore self casts (including area casts when caster selected as target) if (non_caster_target) { if (!CheckTargetCreatureType(target)) { if (target->GetTypeId() == TYPEID_PLAYER) return SPELL_FAILED_TARGET_IS_PLAYER; else return SPELL_FAILED_BAD_TARGETS; } } // who can give me an example to show what is the use of this // even if we need check, check by effect rather than whole spell, otherwise 57108,57143 are broken /* // TODO: this check can be applied and for player to prevent cheating when IsPositiveSpell will return always correct result. // check target for pet/charmed casts (not self targeted), self targeted cast used for area effects and etc if (non_caster_target && m_caster->GetTypeId() == TYPEID_UNIT && m_caster->GetCharmerOrOwnerGUID()) { // check correctness positive/negative cast target (pet cast real check and cheating check) if (IsPositiveSpell(m_spellInfo->Id)) { //dispel positivity is dependant on target, don't check it if (m_caster->IsHostileTo(target) && !IsDispel(m_spellInfo)) return SPELL_FAILED_BAD_TARGETS; } else { if (m_caster->IsFriendlyTo(target)) return SPELL_FAILED_BAD_TARGETS; } } */ if (target) if (IsPositiveSpell(m_spellInfo->Id)) if (target->IsImmunedToSpell(m_spellInfo)) return SPELL_FAILED_TARGET_AURASTATE; //Must be behind the target. if (m_spellInfo->AttributesEx2 == SPELL_ATTR2_UNK20 && m_spellInfo->AttributesEx & SPELL_ATTR1_UNK9 && target->HasInArc(static_cast<float>(M_PI), m_caster) //Exclusion for Pounce: Facing Limitation was removed in 2.0.1, but it still uses the same, old Ex-Flags && (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_DRUID && m_spellInfo->SpellFamilyFlags.IsEqual(0x20000,0,0))) //Mutilate no longer requires you be behind the target as of patch 3.0.3 && (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE && m_spellInfo->SpellFamilyFlags[1] & 0x200000)) //Exclusion for Throw: Facing limitation was added in 3.2.x, but that shouldn't be && (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE && m_spellInfo->SpellFamilyFlags[0] & 0x00000001))) { SendInterrupted(2); return SPELL_FAILED_NOT_BEHIND; } //Target must be facing you. if ((m_spellInfo->Attributes == (SPELL_ATTR0_UNK4 | SPELL_ATTR0_NOT_SHAPESHIFT | SPELL_ATTR0_UNK18 | SPELL_ATTR0_STOP_ATTACK_TARGET)) && !target->HasInArc(static_cast<float>(M_PI), m_caster)) { SendInterrupted(2); return SPELL_FAILED_NOT_INFRONT; } // check if target is in combat if (non_caster_target && (m_spellInfo->AttributesEx & SPELL_ATTR1_NOT_IN_COMBAT_TARGET) && target->isInCombat()) return SPELL_FAILED_TARGET_AFFECTING_COMBAT; } // Spell casted only on battleground if ((m_spellInfo->AttributesEx3 & SPELL_ATTR3_BATTLEGROUND) && m_caster->GetTypeId() == TYPEID_PLAYER) if (!m_caster->ToPlayer()->InBattleground()) return SPELL_FAILED_ONLY_BATTLEGROUNDS; // do not allow spells to be cast in arenas // - with greater than 10 min CD without SPELL_ATTR4_USABLE_IN_ARENA flag // - with SPELL_ATTR4_NOT_USABLE_IN_ARENA flag if ((m_spellInfo->AttributesEx4 & SPELL_ATTR4_NOT_USABLE_IN_ARENA) || (GetSpellRecoveryTime(m_spellInfo) > 10 * MINUTE * IN_MILLISECONDS && !(m_spellInfo->AttributesEx4 & SPELL_ATTR4_USABLE_IN_ARENA))) if (MapEntry const* mapEntry = sMapStore.LookupEntry(m_caster->GetMapId())) if (mapEntry->IsBattleArena()) return SPELL_FAILED_NOT_IN_ARENA; // zone check if (m_caster->GetTypeId() == TYPEID_UNIT || !m_caster->ToPlayer()->isGameMaster()) { uint32 zone, area; m_caster->GetZoneAndAreaId(zone,area); SpellCastResult locRes= sSpellMgr->GetSpellAllowedInLocationError(m_spellInfo,m_caster->GetMapId(),zone,area, m_caster->GetTypeId() == TYPEID_PLAYER ? m_caster->ToPlayer() : NULL); if (locRes != SPELL_CAST_OK) return locRes; } // not let players cast spells at mount (and let do it to creatures) if (m_caster->IsMounted() && m_caster->GetTypeId() == TYPEID_PLAYER && !m_IsTriggeredSpell && !IsPassiveSpell(m_spellInfo->Id) && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_MOUNTED)) { if (m_caster->isInFlight()) return SPELL_FAILED_NOT_ON_TAXI; else return SPELL_FAILED_NOT_MOUNTED; } SpellCastResult castResult = SPELL_CAST_OK; // always (except passive spells) check items (focus object can be required for any type casts) if (!IsPassiveSpell(m_spellInfo->Id)) { castResult = CheckItems(); if (castResult != SPELL_CAST_OK) return castResult; } // Triggered spells also have range check // TODO: determine if there is some flag to enable/disable the check castResult = CheckRange(strict); if (castResult != SPELL_CAST_OK) return castResult; if (!m_IsTriggeredSpell) { castResult = CheckPower(); if (castResult != SPELL_CAST_OK) return castResult; castResult = CheckCasterAuras(); if (castResult != SPELL_CAST_OK) return castResult; } for (int i = 0; i < MAX_SPELL_EFFECTS; i++) { // for effects of spells that have only one target switch(m_spellInfo->Effect[i]) { case SPELL_EFFECT_DUMMY: { if (m_spellInfo->Id == 51582) // Rocket Boots Engaged { if (m_caster->IsInWater()) return SPELL_FAILED_ONLY_ABOVEWATER; } else if (m_spellInfo->SpellIconID == 156) // Holy Shock { // spell different for friends and enemies // hurt version required facing if (m_targets.getUnitTarget() && !m_caster->IsFriendlyTo(m_targets.getUnitTarget()) && !m_caster->HasInArc(static_cast<float>(M_PI), m_targets.getUnitTarget())) return SPELL_FAILED_UNIT_NOT_INFRONT; } else if (m_spellInfo->SpellIconID == 33 && m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN && m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_SHAMAN_FIRE_NOVA) { if (!m_caster->m_SummonSlot[1]) return SPELL_FAILED_SUCCESS; } else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] == 0x2000) // Death Coil (DeathKnight) { Unit* target = m_targets.getUnitTarget(); if (!target || (target->IsFriendlyTo(m_caster) && target->GetCreatureType() != CREATURE_TYPE_UNDEAD)) return SPELL_FAILED_BAD_TARGETS; } else if (m_spellInfo->Id == 19938) // Awaken Peon { Unit *unit = m_targets.getUnitTarget(); if (!unit || !unit->HasAura(17743)) return SPELL_FAILED_BAD_TARGETS; } else if (m_spellInfo->Id == 52264) // Deliver Stolen Horse { if (!m_caster->FindNearestCreature(28653,5)) return SPELL_FAILED_OUT_OF_RANGE; } else if (m_spellInfo->Id == 31789) // Righteous Defense { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_DONT_REPORT; Unit* target = m_targets.getUnitTarget(); if (!target || !target->IsFriendlyTo(m_caster) || target->getAttackers().empty()) return SPELL_FAILED_BAD_TARGETS; } break; } case SPELL_EFFECT_LEARN_SPELL: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (m_spellInfo->EffectImplicitTargetA[i] != TARGET_UNIT_PET) break; Pet* pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]); if (!learn_spellproto) return SPELL_FAILED_NOT_KNOWN; if (m_spellInfo->spellLevel > pet->getLevel()) return SPELL_FAILED_LOWLEVEL; break; } case SPELL_EFFECT_LEARN_PET_SPELL: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; Pet* pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[i]); if (!learn_spellproto) return SPELL_FAILED_NOT_KNOWN; if (m_spellInfo->spellLevel > pet->getLevel()) return SPELL_FAILED_LOWLEVEL; break; } case SPELL_EFFECT_APPLY_GLYPH: { uint32 glyphId = m_spellInfo->EffectMiscValue[i]; if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyphId)) if (m_caster->HasAura(gp->SpellId)) return SPELL_FAILED_UNIQUE_GLYPH; break; } case SPELL_EFFECT_FEED_PET: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; Item* foodItem = m_targets.getItemTarget(); if (!foodItem) return SPELL_FAILED_BAD_TARGETS; Pet* pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; if (!pet->HaveInDiet(foodItem->GetProto())) return SPELL_FAILED_WRONG_PET_FOOD; if (!pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel)) return SPELL_FAILED_FOOD_LOWLEVEL; if (m_caster->isInCombat() || pet->isInCombat()) return SPELL_FAILED_AFFECTING_COMBAT; break; } case SPELL_EFFECT_POWER_BURN: case SPELL_EFFECT_POWER_DRAIN: { // Can be area effect, Check only for players and not check if target - caster (spell can have multiply drain/burn effects) if (m_caster->GetTypeId() == TYPEID_PLAYER) if (Unit* target = m_targets.getUnitTarget()) if (target != m_caster && target->getPowerType() != Powers(m_spellInfo->EffectMiscValue[i])) return SPELL_FAILED_BAD_TARGETS; break; } case SPELL_EFFECT_CHARGE: { if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARRIOR) { // Warbringer - can't be handled in proc system - should be done before checkcast root check and charge effect process if (strict && m_caster->IsScriptOverriden(m_spellInfo, 6953)) m_caster->RemoveMovementImpairingAuras(); } if (m_caster->HasUnitState(UNIT_STAT_ROOT)) return SPELL_FAILED_ROOTED; break; } case SPELL_EFFECT_SKINNING: { if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() != TYPEID_UNIT) return SPELL_FAILED_BAD_TARGETS; if (!(m_targets.getUnitTarget()->GetUInt32Value(UNIT_FIELD_FLAGS) & UNIT_FLAG_SKINNABLE)) return SPELL_FAILED_TARGET_UNSKINNABLE; Creature* creature = m_targets.getUnitTarget()->ToCreature(); if (creature->GetCreatureType() != CREATURE_TYPE_CRITTER && !creature->loot.isLooted()) return SPELL_FAILED_TARGET_NOT_LOOTED; uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill(); int32 skillValue = m_caster->ToPlayer()->GetSkillValue(skill); int32 TargetLevel = m_targets.getUnitTarget()->getLevel(); int32 ReqValue = (skillValue < 100 ? (TargetLevel-10) * 10 : TargetLevel * 5); if (ReqValue > skillValue) return SPELL_FAILED_LOW_CASTLEVEL; // chance for fail at orange skinning attempt if ((m_selfContainer && (*m_selfContainer) == this) && skillValue < sWorld->GetConfigMaxSkillValue() && (ReqValue < 0 ? 0 : ReqValue) > irand(skillValue - 25, skillValue + 37)) return SPELL_FAILED_TRY_AGAIN; break; } case SPELL_EFFECT_OPEN_LOCK: { if (m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT && m_spellInfo->EffectImplicitTargetA[i] != TARGET_GAMEOBJECT_ITEM) break; if (m_caster->GetTypeId() != TYPEID_PLAYER // only players can open locks, gather etc. // we need a go target in case of TARGET_GAMEOBJECT || (m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT && !m_targets.getGOTarget())) return SPELL_FAILED_BAD_TARGETS; Item *pTempItem = NULL; if (m_targets.getTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData()) pTempItem = pTrade->GetTraderData()->GetItem(TradeSlots(m_targets.getItemTargetGUID())); } else if (m_targets.getTargetMask() & TARGET_FLAG_ITEM) pTempItem = m_caster->ToPlayer()->GetItemByGuid(m_targets.getItemTargetGUID()); // we need a go target, or an openable item target in case of TARGET_GAMEOBJECT_ITEM if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_GAMEOBJECT_ITEM && !m_targets.getGOTarget() && (!pTempItem || !pTempItem->GetProto()->LockID || !pTempItem->IsLocked())) return SPELL_FAILED_BAD_TARGETS; if (m_spellInfo->Id != 1842 || (m_targets.getGOTarget() && m_targets.getGOTarget()->GetGOInfo()->type != GAMEOBJECT_TYPE_TRAP)) if (m_caster->ToPlayer()->InBattleground() && // In Battleground players can use only flags and banners !m_caster->ToPlayer()->CanUseBattlegroundObject()) return SPELL_FAILED_TRY_AGAIN; // get the lock entry uint32 lockId = 0; if (GameObject* go = m_targets.getGOTarget()) { lockId = go->GetGOInfo()->GetLockId(); if (!lockId) return SPELL_FAILED_BAD_TARGETS; } else if (Item* itm = m_targets.getItemTarget()) lockId = itm->GetProto()->LockID; SkillType skillId = SKILL_NONE; int32 reqSkillValue = 0; int32 skillValue = 0; // check lock compatibility SpellCastResult res = CanOpenLock(i, lockId, skillId, reqSkillValue, skillValue); if (res != SPELL_CAST_OK) return res; // chance for fail at orange mining/herb/LockPicking gathering attempt // second check prevent fail at rechecks if (skillId != SKILL_NONE && (!m_selfContainer || ((*m_selfContainer) != this))) { bool canFailAtMax = skillId != SKILL_HERBALISM && skillId != SKILL_MINING; // chance for failure in orange gather / lockpick (gathering skill can't fail at maxskill) if ((canFailAtMax || skillValue < sWorld->GetConfigMaxSkillValue()) && reqSkillValue > irand(skillValue - 25, skillValue + 37)) return SPELL_FAILED_TRY_AGAIN; } break; } case SPELL_EFFECT_SUMMON_DEAD_PET: { Creature *pet = m_caster->GetGuardianPet(); if (!pet) return SPELL_FAILED_NO_PET; if (pet->isAlive()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; break; } // This is generic summon effect case SPELL_EFFECT_SUMMON: { SummonPropertiesEntry const *SummonProperties = sSummonPropertiesStore.LookupEntry(m_spellInfo->EffectMiscValueB[i]); if (!SummonProperties) break; switch(SummonProperties->Category) { case SUMMON_CATEGORY_PET: if (m_caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; case SUMMON_CATEGORY_PUPPET: if (m_caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; break; } break; } case SPELL_EFFECT_CREATE_TAMED_PET: { if (m_targets.getUnitTarget()) { if (m_targets.getUnitTarget()->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (m_targets.getUnitTarget()->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; } break; } case SPELL_EFFECT_SUMMON_PET: { if (m_caster->GetPetGUID()) //let warlock do a replacement summon { if (m_caster->GetTypeId() == TYPEID_PLAYER && m_caster->getClass() == CLASS_WARLOCK) { if (strict) //starting cast, trigger pet stun (cast by pet so it doesn't attack player) if (Pet* pet = m_caster->ToPlayer()->GetPet()) pet->CastSpell(pet, 32752, true, NULL, NULL, pet->GetGUID()); } else return SPELL_FAILED_ALREADY_HAVE_SUMMON; } if (m_caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; break; } case SPELL_EFFECT_SUMMON_PLAYER: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (!m_caster->ToPlayer()->GetSelection()) return SPELL_FAILED_BAD_TARGETS; Player* target = sObjectMgr->GetPlayer(m_caster->ToPlayer()->GetSelection()); if (!target || m_caster->ToPlayer() == target || !target->IsInSameRaidWith(m_caster->ToPlayer())) return SPELL_FAILED_BAD_TARGETS; // check if our map is dungeon if (sMapStore.LookupEntry(m_caster->GetMapId())->IsDungeon()) { Map const* pMap = m_caster->GetMap(); InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(pMap->GetId()); if (!instance) return SPELL_FAILED_TARGET_NOT_IN_INSTANCE; if (!target->Satisfy(sObjectMgr->GetAccessRequirement(pMap->GetId(), pMap->GetDifficulty()), pMap->GetId())) return SPELL_FAILED_BAD_TARGETS; } break; } case SPELL_EFFECT_LEAP: case SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER: { //Do not allow to cast it before BG starts. if (m_caster->GetTypeId() == TYPEID_PLAYER) if (Battleground const *bg = m_caster->ToPlayer()->GetBattleground()) if (bg->GetStatus() != STATUS_IN_PROGRESS) return SPELL_FAILED_TRY_AGAIN; break; } case SPELL_EFFECT_STEAL_BENEFICIAL_BUFF: { if (m_targets.getUnitTarget() == m_caster) return SPELL_FAILED_BAD_TARGETS; break; } case SPELL_EFFECT_LEAP_BACK: { // Spell 781 (Disengage) requires player to be in combat if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->Id == 781 && !m_caster->isInCombat()) return SPELL_FAILED_CANT_DO_THAT_RIGHT_NOW; Unit* target = m_targets.getUnitTarget(); if (m_caster == target && m_caster->HasUnitState(UNIT_STAT_ROOT)) { if (m_caster->GetTypeId() == TYPEID_PLAYER) return SPELL_FAILED_ROOTED; else return SPELL_FAILED_DONT_REPORT; } break; } case SPELL_EFFECT_TALENT_SPEC_SELECT: // can't change during already started arena/battleground if (Battleground const* bg = m_caster->ToPlayer()->GetBattleground()) if (bg->GetStatus() == STATUS_IN_PROGRESS) return SPELL_FAILED_NOT_IN_BATTLEGROUND; break; default: break; } } for (int i = 0; i < MAX_SPELL_EFFECTS; i++) { switch(m_spellInfo->EffectApplyAuraName[i]) { case SPELL_AURA_DUMMY: { //custom check switch(m_spellInfo->Id) { // Tag Murloc case 30877: { Unit* target = m_targets.getUnitTarget(); if (!target || target->GetEntry() != 17326) return SPELL_FAILED_BAD_TARGETS; break; } case 61336: if (m_caster->GetTypeId() != TYPEID_PLAYER || !m_caster->ToPlayer()->IsInFeralForm()) return SPELL_FAILED_ONLY_SHAPESHIFT; break; case 1515: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (!m_targets.getUnitTarget() || m_targets.getUnitTarget()->GetTypeId() == TYPEID_PLAYER) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; Creature* target = m_targets.getUnitTarget()->ToCreature(); if (target->getLevel() > m_caster->getLevel()) return SPELL_FAILED_HIGHLEVEL; // use SMSG_PET_TAME_FAILURE? if (!target->GetCreatureInfo()->isTameable (m_caster->ToPlayer()->CanTameExoticPets())) return SPELL_FAILED_BAD_TARGETS; if (m_caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; if (m_caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; break; } case 44795: // Parachute { float x, y, z; m_caster->GetPosition(x, y, z); float ground_Z = m_caster->GetMap()->GetHeight(x, y, z); if (fabs(ground_Z - z) < 0.1f) return SPELL_FAILED_DONT_REPORT; break; } default: break; } break; } case SPELL_AURA_MOD_POSSESS_PET: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_NO_PET; Pet *pet = m_caster->ToPlayer()->GetPet(); if (!pet) return SPELL_FAILED_NO_PET; if (pet->GetCharmerGUID()) return SPELL_FAILED_CHARMED; break; } case SPELL_AURA_MOD_POSSESS: case SPELL_AURA_MOD_CHARM: case SPELL_AURA_AOE_CHARM: { if (m_caster->GetCharmerGUID()) return SPELL_FAILED_CHARMED; if (m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_CHARM || m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_POSSESS) { if (m_caster->GetPetGUID()) return SPELL_FAILED_ALREADY_HAVE_SUMMON; if (m_caster->GetCharmGUID()) return SPELL_FAILED_ALREADY_HAVE_CHARM; } if (Unit *target = m_targets.getUnitTarget()) { if (target->GetTypeId() == TYPEID_UNIT && target->ToCreature()->IsVehicle()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; if (target->IsMounted()) return SPELL_FAILED_CANT_BE_CHARMED; if (target->GetCharmerGUID()) return SPELL_FAILED_CHARMED; int32 damage = CalculateDamage(i, target); if (damage && int32(target->getLevel()) > damage) return SPELL_FAILED_HIGHLEVEL; } break; } case SPELL_AURA_MOUNTED: { if (m_caster->IsInWater()) return SPELL_FAILED_ONLY_ABOVEWATER; // Ignore map check if spell have AreaId. AreaId already checked and this prevent special mount spells bool AllowMount = !m_caster->GetMap()->IsDungeon() || m_caster->GetMap()->IsBattlegroundOrArena(); InstanceTemplate const *it = ObjectMgr::GetInstanceTemplate(m_caster->GetMapId()); if (it) AllowMount = it->allowMount; if (m_caster->GetTypeId() == TYPEID_PLAYER && !AllowMount && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId) return SPELL_FAILED_NO_MOUNTS_ALLOWED; if (m_caster->IsInDisallowedMountForm()) return SPELL_FAILED_NOT_SHAPESHIFT; break; } case SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS: { if (!m_targets.getUnitTarget()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; // can be casted at non-friendly unit or own pet/charm if (m_caster->IsFriendlyTo(m_targets.getUnitTarget())) return SPELL_FAILED_TARGET_FRIENDLY; break; } case SPELL_AURA_FLY: case SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED: { // not allow cast fly spells if not have req. skills (all spells is self target) // allow always ghost flight spells if (m_originalCaster && m_originalCaster->GetTypeId() == TYPEID_PLAYER && m_originalCaster->isAlive()) { if (AreaTableEntry const* pArea = GetAreaEntryByAreaID(m_originalCaster->GetAreaId())) if (pArea->flags & AREA_FLAG_NO_FLY_ZONE) return m_IsTriggeredSpell ? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_NOT_HERE; } break; } case SPELL_AURA_PERIODIC_MANA_LEECH: { if (!m_targets.getUnitTarget()) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; if (m_caster->GetTypeId() != TYPEID_PLAYER || m_CastItem) break; if (m_targets.getUnitTarget()->getPowerType() != POWER_MANA) return SPELL_FAILED_BAD_TARGETS; break; } default: break; } } // check trade slot case (last, for allow catch any another cast problems) if (m_targets.getTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (m_CastItem) return SPELL_FAILED_ITEM_ENCHANT_TRADE_WINDOW; if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_NOT_TRADING; TradeData* my_trade = m_caster->ToPlayer()->GetTradeData(); if (!my_trade) return SPELL_FAILED_NOT_TRADING; TradeSlots slot = TradeSlots(m_targets.getItemTargetGUID()); if (slot != TRADE_SLOT_NONTRADED) return SPELL_FAILED_BAD_TARGETS; if (!m_IsTriggeredSpell) if (my_trade->GetSpell()) return SPELL_FAILED_ITEM_ALREADY_ENCHANTED; } // check if caster has at least 1 combo point for spells that require combo points if (m_needComboPoints) if (Player* plrCaster = m_caster->ToPlayer()) if (!plrCaster->GetComboPoints()) return SPELL_FAILED_NO_COMBO_POINTS; // all ok return SPELL_CAST_OK; } SpellCastResult Spell::CheckPetCast(Unit* target) { if (!m_caster->isAlive() && !(m_spellInfo->Attributes & SPELL_ATTR0_CASTABLE_WHILE_DEAD)) return SPELL_FAILED_CASTER_DEAD; if (m_caster->HasUnitState(UNIT_STAT_CASTING) && !m_IsTriggeredSpell) //prevent spellcast interruption by another spellcast return SPELL_FAILED_SPELL_IN_PROGRESS; if (m_caster->isInCombat() && IsNonCombatSpell(m_spellInfo)) return SPELL_FAILED_AFFECTING_COMBAT; //dead owner (pets still alive when owners ressed?) if (Unit *owner = m_caster->GetCharmerOrOwner()) if (!owner->isAlive()) return SPELL_FAILED_CASTER_DEAD; if (!target && m_targets.getUnitTarget()) target = m_targets.getUnitTarget(); for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (SpellTargetType[m_spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_UNIT_TARGET || SpellTargetType[m_spellInfo->EffectImplicitTargetA[i]] == TARGET_TYPE_DEST_TARGET) { if (!target) return SPELL_FAILED_BAD_IMPLICIT_TARGETS; m_targets.setUnitTarget(target); break; } } Unit* _target = m_targets.getUnitTarget(); if (_target) //for target dead/target not valid { if (!_target->isAlive()) return SPELL_FAILED_BAD_TARGETS; if (!IsValidSingleTargetSpell(_target)) return SPELL_FAILED_BAD_TARGETS; } //cooldown if (m_caster->ToCreature()->HasSpellCooldown(m_spellInfo->Id)) return SPELL_FAILED_NOT_READY; return CheckCast(true); } SpellCastResult Spell::CheckCasterAuras() const { // spells totally immuned to caster auras (wsg flag drop, give marks etc) if (m_spellInfo->AttributesEx6& SPELL_ATTR6_IGNORE_CASTER_AURAS) return SPELL_CAST_OK; uint8 school_immune = 0; uint32 mechanic_immune = 0; uint32 dispel_immune = 0; // Check if the spell grants school or mechanic immunity. // We use bitmasks so the loop is done only once and not on every aura check below. if (m_spellInfo->AttributesEx & SPELL_ATTR1_DISPEL_AURAS_ON_IMMUNITY) { for (int i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_SCHOOL_IMMUNITY) school_immune |= uint32(m_spellInfo->EffectMiscValue[i]); else if (m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MECHANIC_IMMUNITY) mechanic_immune |= 1 << uint32(m_spellInfo->EffectMiscValue[i]); else if (m_spellInfo->EffectApplyAuraName[i] == SPELL_AURA_DISPEL_IMMUNITY) dispel_immune |= GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[i])); } // immune movement impairment and loss of control if (m_spellInfo->Id == 42292 || m_spellInfo->Id == 59752) mechanic_immune = IMMUNE_TO_MOVEMENT_IMPAIRMENT_AND_LOSS_CONTROL_MASK; } // Check whether the cast should be prevented by any state you might have. SpellCastResult prevented_reason = SPELL_CAST_OK; // Have to check if there is a stun aura. Otherwise will have problems with ghost aura apply while logging out uint32 unitflag = m_caster->GetUInt32Value(UNIT_FIELD_FLAGS); // Get unit state if (unitflag & UNIT_FLAG_STUNNED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_STUNNED)) prevented_reason = SPELL_FAILED_STUNNED; else if (unitflag & UNIT_FLAG_CONFUSED && !(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_CONFUSED)) prevented_reason = SPELL_FAILED_CONFUSED; else if (unitflag & UNIT_FLAG_FLEEING && !(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_FEARED)) prevented_reason = SPELL_FAILED_FLEEING; else if (unitflag & UNIT_FLAG_SILENCED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE) prevented_reason = SPELL_FAILED_SILENCED; else if (unitflag & UNIT_FLAG_PACIFIED && m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY) prevented_reason = SPELL_FAILED_PACIFIED; // Attr must make flag drop spell totally immune from all effects if (prevented_reason != SPELL_CAST_OK) { if (school_immune || mechanic_immune || dispel_immune) { //Checking auras is needed now, because you are prevented by some state but the spell grants immunity. Unit::AuraApplicationMap const& auras = m_caster->GetAppliedAuras(); for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { Aura const * aura = itr->second->GetBase(); if (GetAllSpellMechanicMask(aura->GetSpellProto()) & mechanic_immune) continue; if (GetSpellSchoolMask(aura->GetSpellProto()) & school_immune) continue; if ((1<<(aura->GetSpellProto()->Dispel)) & dispel_immune) continue; //Make a second check for spell failed so the right SPELL_FAILED message is returned. //That is needed when your casting is prevented by multiple states and you are only immune to some of them. for (uint8 i=0; i<MAX_SPELL_EFFECTS; ++i) { if (AuraEffect * part = aura->GetEffect(i)) { switch(part->GetAuraType()) { case SPELL_AURA_MOD_STUN: if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_STUNNED)) return SPELL_FAILED_STUNNED; break; case SPELL_AURA_MOD_CONFUSE: if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_CONFUSED)) return SPELL_FAILED_CONFUSED; break; case SPELL_AURA_MOD_FEAR: if (!(m_spellInfo->AttributesEx5 & SPELL_ATTR5_USABLE_WHILE_FEARED)) return SPELL_FAILED_FLEEING; break; case SPELL_AURA_MOD_SILENCE: case SPELL_AURA_MOD_PACIFY: case SPELL_AURA_MOD_PACIFY_SILENCE: if (m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_PACIFY) return SPELL_FAILED_PACIFIED; else if (m_spellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE) return SPELL_FAILED_SILENCED; break; default: break; } } } } } // You are prevented from casting and the spell casted does not grant immunity. Return a failed error. else return prevented_reason; } return SPELL_CAST_OK; } bool Spell::CanAutoCast(Unit* target) { uint64 targetguid = target->GetGUID(); for (uint32 j = 0; j < MAX_SPELL_EFFECTS; ++j) { if (m_spellInfo->Effect[j] == SPELL_EFFECT_APPLY_AURA) { if (m_spellInfo->StackAmount <= 1) { if (target->HasAuraEffect(m_spellInfo->Id, j)) return false; } else { if (AuraEffect * aureff = target->GetAuraEffect(m_spellInfo->Id, j)) if (aureff->GetBase()->GetStackAmount() >= m_spellInfo->StackAmount) return false; } } else if (IsAreaAuraEffect(m_spellInfo->Effect[j])) { if (target->HasAuraEffect(m_spellInfo->Id, j)) return false; } } SpellCastResult result = CheckPetCast(target); if (result == SPELL_CAST_OK || result == SPELL_FAILED_UNIT_NOT_INFRONT) { SelectSpellTargets(); //check if among target units, our WANTED target is as well (->only self cast spells return false) for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->targetGUID == targetguid) return true; } return false; //target invalid } SpellCastResult Spell::CheckRange(bool strict) { // self cast doesn't need range checking -- also for Starshards fix if (m_spellInfo->rangeIndex == 1) return SPELL_CAST_OK; // Don't check for instant cast spells if (!strict && m_casttime == 0) return SPELL_CAST_OK; SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex); Unit *target = m_targets.getUnitTarget(); float max_range = (float)m_caster->GetSpellMaxRangeForTarget(target, srange); float min_range = (float)m_caster->GetSpellMinRangeForTarget(target, srange); uint32 range_type = GetSpellRangeType(srange); if (Player* modOwner = m_caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, max_range, this); if (target && target != m_caster) { if (range_type == SPELL_RANGE_MELEE) { // Because of lag, we can not check too strictly here. if (!m_caster->IsWithinMeleeRange(target, max_range)) return !m_IsTriggeredSpell ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; } else if (!m_caster->IsWithinCombatRange(target, max_range)) return !m_IsTriggeredSpell ? SPELL_FAILED_OUT_OF_RANGE : SPELL_FAILED_DONT_REPORT; //0x5A; if (range_type == SPELL_RANGE_RANGED) { if (m_caster->IsWithinMeleeRange(target)) return !m_IsTriggeredSpell ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT; } else if (min_range && m_caster->IsWithinCombatRange(target, min_range)) // skip this check if min_range = 0 return !m_IsTriggeredSpell ? SPELL_FAILED_TOO_CLOSE : SPELL_FAILED_DONT_REPORT; if (m_caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->FacingCasterFlags & SPELL_FACING_FLAG_INFRONT) && !m_caster->HasInArc(static_cast<float>(M_PI), target)) return !m_IsTriggeredSpell ? SPELL_FAILED_UNIT_NOT_INFRONT : SPELL_FAILED_DONT_REPORT; } if (m_targets.HasDst() && !m_targets.HasTraj()) { if (!m_caster->IsWithinDist3d(&m_targets.m_dstPos, max_range)) return SPELL_FAILED_OUT_OF_RANGE; if (min_range && m_caster->IsWithinDist3d(&m_targets.m_dstPos, min_range)) return SPELL_FAILED_TOO_CLOSE; } return SPELL_CAST_OK; } SpellCastResult Spell::CheckPower() { // item cast not used power if (m_CastItem) return SPELL_CAST_OK; // health as power used - need check health amount if (m_spellInfo->powerType == POWER_HEALTH) { if (int32(m_caster->GetHealth()) <= m_powerCost) return SPELL_FAILED_CASTER_AURASTATE; return SPELL_CAST_OK; } // Check valid power type if (m_spellInfo->powerType >= MAX_POWERS) { sLog->outError("Spell::CheckPower: Unknown power type '%d'", m_spellInfo->powerType); return SPELL_FAILED_UNKNOWN; } //check rune cost only if a spell has PowerType == POWER_RUNE if (m_spellInfo->powerType == POWER_RUNE) { SpellCastResult failReason = CheckRuneCost(m_spellInfo->runeCostID); if (failReason != SPELL_CAST_OK) return failReason; } // Check power amount Powers powerType = Powers(m_spellInfo->powerType); if (int32(m_caster->GetPower(powerType)) < m_powerCost) return SPELL_FAILED_NO_POWER; else return SPELL_CAST_OK; } SpellCastResult Spell::CheckItems() { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_CAST_OK; Player* p_caster = (Player*)m_caster; if (!m_CastItem) { if (m_castItemGUID) return SPELL_FAILED_ITEM_NOT_READY; } else { uint32 itemid = m_CastItem->GetEntry(); if (!p_caster->HasItemCount(itemid, 1)) return SPELL_FAILED_ITEM_NOT_READY; ItemPrototype const *proto = m_CastItem->GetProto(); if (!proto) return SPELL_FAILED_ITEM_NOT_READY; for (int i = 0; i < MAX_ITEM_SPELLS; ++i) if (proto->Spells[i].SpellCharges) if (m_CastItem->GetSpellCharges(i) == 0) return SPELL_FAILED_NO_CHARGES_REMAIN; // consumable cast item checks if (proto->Class == ITEM_CLASS_CONSUMABLE && m_targets.getUnitTarget()) { // such items should only fail if there is no suitable effect at all - see Rejuvenation Potions for example SpellCastResult failReason = SPELL_CAST_OK; for (int i = 0; i < MAX_SPELL_EFFECTS; i++) { // skip check, pet not required like checks, and for TARGET_UNIT_PET m_targets.getUnitTarget() is not the real target but the caster if (m_spellInfo->EffectImplicitTargetA[i] == TARGET_UNIT_PET) continue; if (m_spellInfo->Effect[i] == SPELL_EFFECT_HEAL) { if (m_targets.getUnitTarget()->IsFullHealth()) { failReason = SPELL_FAILED_ALREADY_AT_FULL_HEALTH; continue; } else { failReason = SPELL_CAST_OK; break; } } // Mana Potion, Rage Potion, Thistle Tea(Rogue), ... if (m_spellInfo->Effect[i] == SPELL_EFFECT_ENERGIZE) { if (m_spellInfo->EffectMiscValue[i] < 0 || m_spellInfo->EffectMiscValue[i] >= int8(MAX_POWERS)) { failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER; continue; } Powers power = Powers(m_spellInfo->EffectMiscValue[i]); if (m_targets.getUnitTarget()->GetPower(power) == m_targets.getUnitTarget()->GetMaxPower(power)) { failReason = SPELL_FAILED_ALREADY_AT_FULL_POWER; continue; } else { failReason = SPELL_CAST_OK; break; } } } if (failReason != SPELL_CAST_OK) return failReason; } } // check target item if (m_targets.getItemTargetGUID()) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_BAD_TARGETS; if (!m_targets.getItemTarget()) return SPELL_FAILED_ITEM_GONE; if (!m_targets.getItemTarget()->IsFitToSpellRequirements(m_spellInfo)) return SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // if not item target then required item must be equipped else { if (m_caster->GetTypeId() == TYPEID_PLAYER && !m_caster->ToPlayer()->HasItemFitToSpellRequirements(m_spellInfo)) return SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // check spell focus object if (m_spellInfo->RequiresSpellFocus) { CellPair p(Trinity::ComputeCellPair(m_caster->GetPositionX(), m_caster->GetPositionY())); Cell cell(p); cell.data.Part.reserved = ALL_DISTRICT; GameObject* ok = NULL; Trinity::GameObjectFocusCheck go_check(m_caster,m_spellInfo->RequiresSpellFocus); Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck> checker(m_caster, ok, go_check); TypeContainerVisitor<Trinity::GameObjectSearcher<Trinity::GameObjectFocusCheck>, GridTypeMapContainer > object_checker(checker); Map& map = *m_caster->GetMap(); cell.Visit(p, object_checker, map, *m_caster, m_caster->GetVisibilityRange()); if (!ok) return SPELL_FAILED_REQUIRES_SPELL_FOCUS; focusObject = ok; // game object found in range } // do not take reagents for these item casts if (!(m_CastItem && m_CastItem->GetProto()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST)) { // check reagents (ignore triggered spells with reagents processed by original spell) and special reagent ignore case. if (!m_IsTriggeredSpell && !p_caster->CanNoReagentCast(m_spellInfo)) { for (uint32 i = 0; i < MAX_SPELL_REAGENTS; i++) { if (m_spellInfo->Reagent[i] <= 0) continue; uint32 itemid = m_spellInfo->Reagent[i]; uint32 itemcount = m_spellInfo->ReagentCount[i]; // if CastItem is also spell reagent if (m_CastItem && m_CastItem->GetEntry() == itemid) { ItemPrototype const *proto = m_CastItem->GetProto(); if (!proto) return SPELL_FAILED_ITEM_NOT_READY; for (int s=0; s < MAX_ITEM_PROTO_SPELLS; ++s) { // CastItem will be used up and does not count as reagent int32 charges = m_CastItem->GetSpellCharges(s); if (proto->Spells[s].SpellCharges < 0 && abs(charges) < 2) { ++itemcount; break; } } } if (!p_caster->HasItemCount(itemid,itemcount)) return SPELL_FAILED_ITEM_NOT_READY; //0x54 } } // check totem-item requirements (items presence in inventory) uint32 totems = 2; for (int i = 0; i < 2 ; ++i) { if (m_spellInfo->Totem[i] != 0) { if (p_caster->HasItemCount(m_spellInfo->Totem[i],1)) { totems -= 1; continue; } }else totems -= 1; } if (totems != 0) return SPELL_FAILED_TOTEMS; //0x7C // Check items for TotemCategory (items presence in inventory) uint32 TotemCategory = 2; for (int i= 0; i < 2; ++i) { if (m_spellInfo->TotemCategory[i] != 0) { if (p_caster->HasItemTotemCategory(m_spellInfo->TotemCategory[i])) { TotemCategory -= 1; continue; } } else TotemCategory -= 1; } if (TotemCategory != 0) return SPELL_FAILED_TOTEM_CATEGORY; //0x7B } // special checks for spell effects for (int i = 0; i < MAX_SPELL_EFFECTS; i++) { switch (m_spellInfo->Effect[i]) { case SPELL_EFFECT_CREATE_ITEM: case SPELL_EFFECT_CREATE_ITEM_2: { if (!m_IsTriggeredSpell && m_spellInfo->EffectItemType[i]) { ItemPosCountVec dest; uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1); if (msg != EQUIP_ERR_OK) { ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(m_spellInfo->EffectItemType[i]); // TODO: Needs review if (pProto && !(pProto->ItemLimitCategory)) { p_caster->SendEquipError(msg, NULL, NULL, m_spellInfo->EffectItemType[i]); return SPELL_FAILED_DONT_REPORT; } else { if (!(m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x40000000))) return SPELL_FAILED_TOO_MANY_OF_ITEM; else if (!(p_caster->HasItemCount(m_spellInfo->EffectItemType[i],1))) return SPELL_FAILED_TOO_MANY_OF_ITEM; else p_caster->CastSpell(m_caster,SpellMgr::CalculateSpellEffectAmount(m_spellInfo, 1),false); // move this to anywhere return SPELL_FAILED_DONT_REPORT; } } } break; } case SPELL_EFFECT_ENCHANT_ITEM: if (m_spellInfo->EffectItemType[i] && m_targets.getItemTarget() && (m_targets.getItemTarget()->IsWeaponVellum() || m_targets.getItemTarget()->IsArmorVellum())) { // cannot enchant vellum for other player if (m_targets.getItemTarget()->GetOwner() != m_caster) return SPELL_FAILED_NOT_TRADEABLE; // do not allow to enchant vellum from scroll made by vellum-prevent exploit if (m_CastItem && m_CastItem->GetProto()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST) return SPELL_FAILED_TOTEM_CATEGORY; ItemPosCountVec dest; uint8 msg = p_caster->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, m_spellInfo->EffectItemType[i], 1); if (msg != EQUIP_ERR_OK) { p_caster->SendEquipError(msg, NULL, NULL, m_spellInfo->EffectItemType[i]); return SPELL_FAILED_DONT_REPORT; } } case SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC: { Item* targetItem = m_targets.getItemTarget(); if (!targetItem) return SPELL_FAILED_ITEM_NOT_FOUND; if (targetItem->GetProto()->ItemLevel < m_spellInfo->baseLevel) return SPELL_FAILED_LOWLEVEL; bool isItemUsable = false; for (uint8 e = 0; e < MAX_ITEM_PROTO_SPELLS; ++e) { ItemPrototype const *proto = targetItem->GetProto(); if (proto->Spells[e].SpellId && ( proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE || proto->Spells[e].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)) { isItemUsable = true; break; } } SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(m_spellInfo->EffectMiscValue[i]); // do not allow adding usable enchantments to items that have use effect already if (pEnchant && isItemUsable) for (uint8 s = 0; s < MAX_ITEM_ENCHANTMENT_EFFECTS; ++s) if (pEnchant->type[s] == ITEM_ENCHANTMENT_TYPE_USE_SPELL) return SPELL_FAILED_ON_USE_ENCHANT; // Not allow enchant in trade slot for some enchant type if (targetItem->GetOwner() != m_caster) { if (!pEnchant) return SPELL_FAILED_ERROR; if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND) return SPELL_FAILED_NOT_TRADEABLE; } break; } case SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY: { Item *item = m_targets.getItemTarget(); if (!item) return SPELL_FAILED_ITEM_NOT_FOUND; // Not allow enchant in trade slot for some enchant type if (item->GetOwner() != m_caster) { uint32 enchant_id = m_spellInfo->EffectMiscValue[i]; SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return SPELL_FAILED_ERROR; if (pEnchant->slot & ENCHANTMENT_CAN_SOULBOUND) return SPELL_FAILED_NOT_TRADEABLE; } break; } case SPELL_EFFECT_ENCHANT_HELD_ITEM: // check item existence in effect code (not output errors at offhand hold item effect to main hand for example break; case SPELL_EFFECT_DISENCHANT: { if (!m_targets.getItemTarget()) return SPELL_FAILED_CANT_BE_DISENCHANTED; // prevent disenchanting in trade slot if (m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_CANT_BE_DISENCHANTED; ItemPrototype const* itemProto = m_targets.getItemTarget()->GetProto(); if (!itemProto) return SPELL_FAILED_CANT_BE_DISENCHANTED; uint32 item_quality = itemProto->Quality; // 2.0.x addon: Check player enchanting level against the item disenchanting requirements uint32 item_disenchantskilllevel = itemProto->RequiredDisenchantSkill; if (item_disenchantskilllevel == uint32(-1)) return SPELL_FAILED_CANT_BE_DISENCHANTED; if (item_disenchantskilllevel > p_caster->GetSkillValue(SKILL_ENCHANTING)) return SPELL_FAILED_LOW_CASTLEVEL; if (item_quality > 4 || item_quality < 2) return SPELL_FAILED_CANT_BE_DISENCHANTED; if (itemProto->Class != ITEM_CLASS_WEAPON && itemProto->Class != ITEM_CLASS_ARMOR) return SPELL_FAILED_CANT_BE_DISENCHANTED; if (!itemProto->DisenchantID) return SPELL_FAILED_CANT_BE_DISENCHANTED; break; } case SPELL_EFFECT_PROSPECTING: { if (!m_targets.getItemTarget()) return SPELL_FAILED_CANT_BE_PROSPECTED; //ensure item is a prospectable ore if (!(m_targets.getItemTarget()->GetProto()->Flags & ITEM_PROTO_FLAG_PROSPECTABLE)) return SPELL_FAILED_CANT_BE_PROSPECTED; //prevent prospecting in trade slot if (m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_CANT_BE_PROSPECTED; //Check for enough skill in jewelcrafting uint32 item_prospectingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank; if (item_prospectingskilllevel >p_caster->GetSkillValue(SKILL_JEWELCRAFTING)) return SPELL_FAILED_LOW_CASTLEVEL; //make sure the player has the required ores in inventory if (m_targets.getItemTarget()->GetCount() < 5) return SPELL_FAILED_NEED_MORE_ITEMS; if (!LootTemplates_Prospecting.HaveLootFor(m_targets.getItemTargetEntry())) return SPELL_FAILED_CANT_BE_PROSPECTED; break; } case SPELL_EFFECT_MILLING: { if (!m_targets.getItemTarget()) return SPELL_FAILED_CANT_BE_MILLED; //ensure item is a millable herb if (!(m_targets.getItemTarget()->GetProto()->Flags & ITEM_PROTO_FLAG_MILLABLE)) return SPELL_FAILED_CANT_BE_MILLED; //prevent milling in trade slot if (m_targets.getItemTarget()->GetOwnerGUID() != m_caster->GetGUID()) return SPELL_FAILED_CANT_BE_MILLED; //Check for enough skill in inscription uint32 item_millingskilllevel = m_targets.getItemTarget()->GetProto()->RequiredSkillRank; if (item_millingskilllevel >p_caster->GetSkillValue(SKILL_INSCRIPTION)) return SPELL_FAILED_LOW_CASTLEVEL; //make sure the player has the required herbs in inventory if (m_targets.getItemTarget()->GetCount() < 5) return SPELL_FAILED_NEED_MORE_ITEMS; if (!LootTemplates_Milling.HaveLootFor(m_targets.getItemTargetEntry())) return SPELL_FAILED_CANT_BE_MILLED; break; } case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return SPELL_FAILED_TARGET_NOT_PLAYER; if (m_attackType != RANGED_ATTACK) break; Item *pItem = m_caster->ToPlayer()->GetWeaponForAttack(m_attackType); if (!pItem || pItem->IsBroken()) return SPELL_FAILED_EQUIPPED_ITEM; switch(pItem->GetProto()->SubClass) { case ITEM_SUBCLASS_WEAPON_THROWN: { uint32 ammo = pItem->GetEntry(); if (!m_caster->ToPlayer()->HasItemCount(ammo, 1)) return SPELL_FAILED_NO_AMMO; }; break; case ITEM_SUBCLASS_WEAPON_GUN: case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_CROSSBOW: { uint32 ammo = m_caster->ToPlayer()->GetUInt32Value(PLAYER_AMMO_ID); if (!ammo) { // Requires No Ammo if (m_caster->HasAura(46699)) break; // skip other checks return SPELL_FAILED_NO_AMMO; } ItemPrototype const *ammoProto = ObjectMgr::GetItemPrototype(ammo); if (!ammoProto) return SPELL_FAILED_NO_AMMO; if (ammoProto->Class != ITEM_CLASS_PROJECTILE) return SPELL_FAILED_NO_AMMO; // check ammo ws. weapon compatibility switch(pItem->GetProto()->SubClass) { case ITEM_SUBCLASS_WEAPON_BOW: case ITEM_SUBCLASS_WEAPON_CROSSBOW: if (ammoProto->SubClass != ITEM_SUBCLASS_ARROW) return SPELL_FAILED_NO_AMMO; break; case ITEM_SUBCLASS_WEAPON_GUN: if (ammoProto->SubClass != ITEM_SUBCLASS_BULLET) return SPELL_FAILED_NO_AMMO; break; default: return SPELL_FAILED_NO_AMMO; } if (!m_caster->ToPlayer()->HasItemCount(ammo, 1)) { m_caster->ToPlayer()->SetUInt32Value(PLAYER_AMMO_ID, 0); return SPELL_FAILED_NO_AMMO; } }; break; case ITEM_SUBCLASS_WEAPON_WAND: break; default: break; } break; } case SPELL_EFFECT_CREATE_MANA_GEM: { uint32 item_id = m_spellInfo->EffectItemType[i]; ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item_id); if (!pProto) return SPELL_FAILED_ITEM_AT_MAX_CHARGES; if (Item* pitem = p_caster->GetItemByEntry(item_id)) { for (int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) if (pProto->Spells[x].SpellCharges != 0 && pitem->GetSpellCharges(x) == pProto->Spells[x].SpellCharges) return SPELL_FAILED_ITEM_AT_MAX_CHARGES; } break; } default: break; } } // check weapon presence in slots for main/offhand weapons if (m_spellInfo->EquippedItemClass >=0) { // main hand weapon required if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_MAIN_HAND) { Item* item = m_caster->ToPlayer()->GetWeaponForAttack(BASE_ATTACK); // skip spell if no weapon in slot or broken if (!item || item->IsBroken()) return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; // skip spell if weapon not fit to triggered spell if (!item->IsFitToSpellRequirements(m_spellInfo)) return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; } // offhand hand weapon required if (m_spellInfo->AttributesEx3 & SPELL_ATTR3_REQ_OFFHAND) { Item* item = m_caster->ToPlayer()->GetWeaponForAttack(OFF_ATTACK); // skip spell if no weapon in slot or broken if (!item || item->IsBroken()) return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; // skip spell if weapon not fit to triggered spell if (!item->IsFitToSpellRequirements(m_spellInfo)) return m_IsTriggeredSpell? SPELL_FAILED_DONT_REPORT : SPELL_FAILED_EQUIPPED_ITEM_CLASS; } } return SPELL_CAST_OK; } void Spell::Delayed() // only called in DealDamage() { if (!m_caster)// || m_caster->GetTypeId() != TYPEID_PLAYER) return; //if (m_spellState == SPELL_STATE_DELAYED) // return; // spell is active and can't be time-backed if (isDelayableNoMore()) // Spells may only be delayed twice return; // spells not loosing casting time (slam, dynamites, bombs..) //if (!(m_spellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_DAMAGE)) // return; //check pushback reduce int32 delaytime = 500; // spellcasting delay is normally 500ms int32 delayReduce = 100; // must be initialized to 100 for percent modifiers m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; AddPctN(delaytime, -delayReduce); if (int32(m_timer) + delaytime > m_casttime) { delaytime = m_casttime - m_timer; m_timer = m_casttime; } else m_timer += delaytime; sLog->outDetail("Spell %u partially interrupted for (%d) ms at damage", m_spellInfo->Id, delaytime); WorldPacket data(SMSG_SPELL_DELAYED, 8+4); data.append(m_caster->GetPackGUID()); data << uint32(delaytime); m_caster->SendMessageToSet(&data, true); } void Spell::DelayedChannel() { if (!m_caster || m_caster->GetTypeId() != TYPEID_PLAYER || getState() != SPELL_STATE_CASTING) return; if (isDelayableNoMore()) // Spells may only be delayed twice return; //check pushback reduce int32 delaytime = CalculatePctN(GetSpellDuration(m_spellInfo), 25); // channeling delay is normally 25% of its time per hit int32 delayReduce = 100; // must be initialized to 100 for percent modifiers m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; AddPctN(delaytime, -delayReduce); if (int32(m_timer) <= delaytime) { delaytime = m_timer; m_timer = 0; } else m_timer -= delaytime; sLog->outDebug("Spell %u partially interrupted for %i ms, new duration: %u ms", m_spellInfo->Id, delaytime, m_timer); for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if ((*ihit).missCondition == SPELL_MISS_NONE) if (Unit* unit = (m_caster->GetGUID() == ihit->targetGUID) ? m_caster : ObjectAccessor::GetUnit(*m_caster, ihit->targetGUID)) unit->DelayOwnedAuras(m_spellInfo->Id, m_originalCasterGUID, delaytime); // partially interrupt persistent area auras if (DynamicObject* dynObj = m_caster->GetDynObject(m_spellInfo->Id)) dynObj->Delay(delaytime); SendChannelUpdate(m_timer); } void Spell::UpdatePointers() { if (m_originalCasterGUID == m_caster->GetGUID()) m_originalCaster = m_caster; else { m_originalCaster = ObjectAccessor::GetUnit(*m_caster,m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) m_originalCaster = NULL; } if (m_castItemGUID && m_caster->GetTypeId() == TYPEID_PLAYER) m_CastItem = m_caster->ToPlayer()->GetItemByGuid(m_castItemGUID); m_targets.Update(m_caster); } bool Spell::CheckTargetCreatureType(Unit* target) const { uint32 spellCreatureTargetMask = m_spellInfo->TargetCreatureType; // Curse of Doom & Exorcism: not find another way to fix spell target check :/ if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->Category == 1179) { // not allow cast at player if (target->GetTypeId() == TYPEID_PLAYER) return false; spellCreatureTargetMask = 0x7FF; } // Dismiss Pet and Taming Lesson skipped if (m_spellInfo->Id == 2641 || m_spellInfo->Id == 23356) spellCreatureTargetMask = 0; // Polymorph and Grounding Totem if (target->GetEntry() == 5925 && m_spellInfo->SpellFamilyName == SPELLFAMILY_MAGE && (m_spellInfo->SpellFamilyFlags[0] & 0x1000000) && m_spellInfo->EffectApplyAuraName[0] == SPELL_AURA_MOD_CONFUSE) return true; if (spellCreatureTargetMask) { uint32 TargetCreatureType = target->GetCreatureTypeMask(); return !TargetCreatureType || (spellCreatureTargetMask & TargetCreatureType); } return true; } CurrentSpellTypes Spell::GetCurrentContainer() { if (IsNextMeleeSwingSpell()) return(CURRENT_MELEE_SPELL); else if (IsAutoRepeat()) return(CURRENT_AUTOREPEAT_SPELL); else if (IsChanneledSpell(m_spellInfo)) return(CURRENT_CHANNELED_SPELL); else return(CURRENT_GENERIC_SPELL); } bool Spell::CheckTarget(Unit* target, uint32 eff) { // Check targets for creature type mask and remove not appropriate (skip explicit self target case, maybe need other explicit targets) if (m_spellInfo->EffectImplicitTargetA[eff] != TARGET_UNIT_CASTER) { if (!CheckTargetCreatureType(target)) return false; } // Check Aura spell req (need for AoE spells) if (m_spellInfo->targetAuraSpell && !target->HasAura(m_spellInfo->targetAuraSpell)) return false; if (m_spellInfo->excludeTargetAuraSpell && target->HasAura(m_spellInfo->excludeTargetAuraSpell)) return false; // Check targets for not_selectable unit flag and remove // A player can cast spells on his pet (or other controlled unit) though in any state if (target != m_caster && target->GetCharmerOrOwnerGUID() != m_caster->GetGUID()) { // any unattackable target skipped if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) return false; // unselectable targets skipped in all cases except TARGET_UNIT_NEARBY_ENTRY targeting // in case TARGET_UNIT_NEARBY_ENTRY target selected by server always and can't be cheated /*if (target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE) && m_spellInfo->EffectImplicitTargetA[eff] != TARGET_UNIT_NEARBY_ENTRY && m_spellInfo->EffectImplicitTargetB[eff] != TARGET_UNIT_NEARBY_ENTRY) return false;*/ } //Check player targets and remove if in GM mode or GM invisibility (for not self casting case) if (target != m_caster && target->GetTypeId() == TYPEID_PLAYER) { if (!target->ToPlayer()->IsVisible()) return false; if (target->ToPlayer()->isGameMaster() && !IsPositiveSpell(m_spellInfo->Id)) return false; } switch(m_spellInfo->EffectApplyAuraName[eff]) { case SPELL_AURA_NONE: default: break; case SPELL_AURA_MOD_POSSESS: case SPELL_AURA_MOD_CHARM: case SPELL_AURA_MOD_POSSESS_PET: case SPELL_AURA_AOE_CHARM: if (target->GetTypeId() == TYPEID_UNIT && target->IsVehicle()) return false; if (target->IsMounted()) return false; if (target->GetCharmerGUID()) return false; if (int32 damage = CalculateDamage(eff, target)) if ((int32)target->getLevel() > damage) return false; break; } //Do not do further checks for triggered spells if (m_IsTriggeredSpell) return true; //Check targets for LOS visibility (except spells without range limitations) switch(m_spellInfo->Effect[eff]) { case SPELL_EFFECT_SUMMON_PLAYER: // from anywhere break; case SPELL_EFFECT_DUMMY: if (m_spellInfo->Id != 20577) // Cannibalize break; //fall through case SPELL_EFFECT_RESURRECT_NEW: // player far away, maybe his corpse near? if (target != m_caster && !target->IsWithinLOSInMap(m_caster)) { if (!m_targets.getCorpseTargetGUID()) return false; Corpse *corpse = ObjectAccessor::GetCorpse(*m_caster, m_targets.getCorpseTargetGUID()); if (!corpse) return false; if (target->GetGUID() != corpse->GetOwnerGUID()) return false; if (!corpse->IsWithinLOSInMap(m_caster)) return false; } // all ok by some way or another, skip normal check break; default: // normal case // Get GO cast coordinates if original caster -> GO WorldObject *caster = NULL; if (IS_GAMEOBJECT_GUID(m_originalCasterGUID)) caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID); if (!caster) caster = m_caster; if (target->GetEntry() == 5925) return true; if (target != m_caster && !target->IsWithinLOSInMap(caster)) return false; break; } return true; } bool Spell::IsNeedSendToClient() const { return m_spellInfo->SpellVisual[0] || m_spellInfo->SpellVisual[1] || IsChanneledSpell(m_spellInfo) || m_spellInfo->speed > 0.0f || (!m_triggeredByAuraSpell && !m_IsTriggeredSpell); } bool Spell::HaveTargetsForEffect(uint8 effect) const { for (std::list<TargetInfo>::const_iterator itr = m_UniqueTargetInfo.begin(); itr != m_UniqueTargetInfo.end(); ++itr) if (itr->effectMask & (1 << effect)) return true; for (std::list<GOTargetInfo>::const_iterator itr = m_UniqueGOTargetInfo.begin(); itr != m_UniqueGOTargetInfo.end(); ++itr) if (itr->effectMask & (1 << effect)) return true; for (std::list<ItemTargetInfo>::const_iterator itr = m_UniqueItemInfo.begin(); itr != m_UniqueItemInfo.end(); ++itr) if (itr->effectMask & (1 << effect)) return true; return false; } SpellEvent::SpellEvent(Spell* spell) : BasicEvent() { m_Spell = spell; } SpellEvent::~SpellEvent() { if (m_Spell->getState() != SPELL_STATE_FINISHED) m_Spell->cancel(); if (m_Spell->IsDeletable()) { delete m_Spell; } else { sLog->outError("~SpellEvent: %s %u tried to delete non-deletable spell %u. Was not deleted, causes memory leak.", (m_Spell->GetCaster()->GetTypeId() == TYPEID_PLAYER ? "Player" : "Creature"), m_Spell->GetCaster()->GetGUIDLow(), m_Spell->m_spellInfo->Id); ASSERT(false); } } bool SpellEvent::Execute(uint64 e_time, uint32 p_time) { // update spell if it is not finished if (m_Spell->getState() != SPELL_STATE_FINISHED) m_Spell->update(p_time); // check spell state to process switch (m_Spell->getState()) { case SPELL_STATE_FINISHED: { // spell was finished, check deletable state if (m_Spell->IsDeletable()) { // check, if we do have unfinished triggered spells return true; // spell is deletable, finish event } // event will be re-added automatically at the end of routine) } break; case SPELL_STATE_DELAYED: { // first, check, if we have just started if (m_Spell->GetDelayStart() != 0) { // no, we aren't, do the typical update // check, if we have channeled spell on our hands /* if (IsChanneledSpell(m_Spell->m_spellInfo)) { // evented channeled spell is processed separately, casted once after delay, and not destroyed till finish // check, if we have casting anything else except this channeled spell and autorepeat if (m_Spell->GetCaster()->IsNonMeleeSpellCasted(false, true, true)) { // another non-melee non-delayed spell is casted now, abort m_Spell->cancel(); } else { // Set last not triggered spell for apply spellmods ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, true); // do the action (pass spell to channeling state) m_Spell->handle_immediate(); // And remove after effect handling ((Player*)m_Spell->GetCaster())->SetSpellModTakingSpell(m_Spell, false); } // event will be re-added automatically at the end of routine) } else */ { // run the spell handler and think about what we can do next uint64 t_offset = e_time - m_Spell->GetDelayStart(); uint64 n_offset = m_Spell->handle_delayed(t_offset); if (n_offset) { // re-add us to the queue m_Spell->GetCaster()->m_Events.AddEvent(this, m_Spell->GetDelayStart() + n_offset, false); return false; // event not complete } // event complete // finish update event will be re-added automatically at the end of routine) } } else { // delaying had just started, record the moment m_Spell->SetDelayStart(e_time); // re-plan the event for the delay moment m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + m_Spell->GetDelayMoment(), false); return false; // event not complete } } break; default: { // all other states // event will be re-added automatically at the end of routine) } break; } // spell processing not complete, plan event on the next update interval m_Spell->GetCaster()->m_Events.AddEvent(this, e_time + 1, false); return false; // event not complete } void SpellEvent::Abort(uint64 /*e_time*/) { // oops, the spell we try to do is aborted if (m_Spell->getState() != SPELL_STATE_FINISHED) m_Spell->cancel(); } bool SpellEvent::IsDeletable() const { return m_Spell->IsDeletable(); } bool Spell::IsValidSingleTargetEffect(Unit const* target, Targets type) const { switch (type) { case TARGET_UNIT_TARGET_ENEMY: return !m_caster->IsFriendlyTo(target); case TARGET_UNIT_TARGET_ALLY: case TARGET_UNIT_PARTY_TARGET: return m_caster->IsFriendlyTo(target); case TARGET_UNIT_TARGET_PARTY: return m_caster != target && m_caster->IsInPartyWith(target); case TARGET_UNIT_TARGET_RAID: return m_caster->IsInRaidWith(target); case TARGET_UNIT_TARGET_PUPPET: return target->HasUnitTypeMask(UNIT_MASK_PUPPET) && m_caster == target->GetOwner(); default: break; } return true; } bool Spell::IsValidSingleTargetSpell(Unit const* target) const { if (target->GetMapId() == MAPID_INVALID) { sLog->outDebug("Spell::IsValidSingleTargetSpell - a spell was cast on '%s' (GUIDLow: %u), but they have an invalid map id!", target->GetName(), target->GetGUIDLow()); return false; } for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (!IsValidSingleTargetEffect(target, Targets(m_spellInfo->EffectImplicitTargetA[i]))) return false; // Need to check B? //if (!IsValidSingleTargetEffect(m_spellInfo->EffectImplicitTargetB[i], target) // return false; } return true; } bool Spell::IsValidDeadOrAliveTarget(Unit const* target) const { if (target->isAlive()) return !IsRequiringDeadTargetSpell(m_spellInfo); if (IsAllowingDeadTargetSpell(m_spellInfo)) return true; return false; } void Spell::CalculateDamageDoneForAllTargets() { float multiplier[MAX_SPELL_EFFECTS]; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_applyMultiplierMask & (1 << i)) multiplier[i] = SpellMgr::CalculateSpellEffectDamageMultiplier(m_spellInfo, i, m_originalCaster, this); bool usesAmmo = true; Unit::AuraEffectList const& Auras = m_caster->GetAuraEffectsByType(SPELL_AURA_ABILITY_CONSUME_NO_AMMO); for (Unit::AuraEffectList::const_iterator j = Auras.begin(); j != Auras.end(); ++j) { if ((*j)->IsAffectedOnSpell(m_spellInfo)) usesAmmo=false; } for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { TargetInfo &target = *ihit; uint32 mask = target.effectMask; if (!mask) continue; Unit* unit = m_caster->GetGUID() == target.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, target.targetGUID); if (!unit) // || !unit->isAlive()) do we need to check alive here? continue; if (usesAmmo) { bool ammoTaken = false; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; i++) { if (!(mask & 1<<i)) continue; switch (m_spellInfo->Effect[i]) { case SPELL_EFFECT_SCHOOL_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: ammoTaken=true; TakeAmmo(); } if (ammoTaken) break; } } if (target.missCondition == SPELL_MISS_NONE) // In case spell hit target, do all effect on that target { target.damage += CalculateDamageDone(unit, mask, multiplier); target.crit = m_caster->isSpellCrit(unit, m_spellInfo, m_spellSchoolMask, m_attackType); } else if (target.missCondition == SPELL_MISS_REFLECT) // In case spell reflect from target, do all effect on caster (if hit) { if (target.reflectResult == SPELL_MISS_NONE) // If reflected spell hit caster -> do all effect on him { target.damage += CalculateDamageDone(m_caster, mask, multiplier); target.crit = m_caster->isSpellCrit(m_caster, m_spellInfo, m_spellSchoolMask, m_attackType); } } } } int32 Spell::CalculateDamageDone(Unit *unit, const uint32 effectMask, float * multiplier) { int32 damageDone = 0; unitTarget = unit; for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (effectMask & (1<<i)) { m_damage = 0; damage = CalculateDamage(i, NULL); switch(m_spellInfo->Effect[i]) { case SPELL_EFFECT_SCHOOL_DAMAGE: SpellDamageSchoolDmg((SpellEffIndex)i); break; case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: SpellDamageWeaponDmg((SpellEffIndex)i); break; case SPELL_EFFECT_HEAL: SpellDamageHeal((SpellEffIndex)i); break; } if (m_damage > 0) { if (IsAreaEffectTarget[m_spellInfo->EffectImplicitTargetA[i]] || IsAreaEffectTarget[m_spellInfo->EffectImplicitTargetB[i]]) { m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask)); if (m_caster->GetTypeId() == TYPEID_UNIT) m_damage = int32(float(m_damage) * unit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CREATURE_AOE_DAMAGE_AVOIDANCE, m_spellInfo->SchoolMask)); if (m_caster->GetTypeId() == TYPEID_PLAYER) { uint32 targetAmount = m_UniqueTargetInfo.size(); if (targetAmount > 10) m_damage = m_damage * 10/targetAmount; } } } if (m_applyMultiplierMask & (1 << i)) { m_damage = int32(m_damage * m_damageMultipliers[i]); m_damageMultipliers[i] *= multiplier[i]; } damageDone += m_damage; } } return damageDone; } SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& skillId, int32& reqSkillValue, int32& skillValue) { if (!lockId) // possible case for GO and maybe for items. return SPELL_CAST_OK; // Get LockInfo LockEntry const *lockInfo = sLockStore.LookupEntry(lockId); if (!lockInfo) return SPELL_FAILED_BAD_TARGETS; bool reqKey = false; // some locks not have reqs for (int j = 0; j < MAX_LOCK_CASE; ++j) { switch(lockInfo->Type[j]) { // check key item (many fit cases can be) case LOCK_KEY_ITEM: if (lockInfo->Index[j] && m_CastItem && m_CastItem->GetEntry() == lockInfo->Index[j]) return SPELL_CAST_OK; reqKey = true; break; // check key skill (only single first fit case can be) case LOCK_KEY_SKILL: { reqKey = true; // wrong locktype, skip if (uint32(m_spellInfo->EffectMiscValue[effIndex]) != lockInfo->Index[j]) continue; skillId = SkillByLockType(LockType(lockInfo->Index[j])); if (skillId != SKILL_NONE) { // skill bonus provided by casting spell (mostly item spells) // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) uint32 spellSkillBonus = uint32(CalculateDamage(effIndex, NULL)); reqSkillValue = lockInfo->Skill[j]; // castitem check: rogue using skeleton keys. the skill values should not be added in this case. skillValue = m_CastItem || m_caster->GetTypeId()!= TYPEID_PLAYER ? 0 : m_caster->ToPlayer()->GetSkillValue(skillId); skillValue += spellSkillBonus; if (skillValue < reqSkillValue) return SPELL_FAILED_LOW_CASTLEVEL; } return SPELL_CAST_OK; } } } if (reqKey) return SPELL_FAILED_BAD_TARGETS; return SPELL_CAST_OK; } void Spell::SetSpellValue(SpellValueMod mod, int32 value) { switch(mod) { case SPELLVALUE_BASE_POINT0: m_spellValue->EffectBasePoints[0] = SpellMgr::CalculateSpellEffectBaseAmount(value, m_spellInfo, 0); break; case SPELLVALUE_BASE_POINT1: m_spellValue->EffectBasePoints[1] = SpellMgr::CalculateSpellEffectBaseAmount(value, m_spellInfo, 1); break; case SPELLVALUE_BASE_POINT2: m_spellValue->EffectBasePoints[2] = SpellMgr::CalculateSpellEffectBaseAmount(value, m_spellInfo, 2); break; case SPELLVALUE_RADIUS_MOD: m_spellValue->RadiusMod = (float)value / 10000; break; case SPELLVALUE_MAX_TARGETS: m_spellValue->MaxAffectedTargets = (uint32)value; break; } } float tangent(float x) { x = tan(x); //if (x < std::numeric_limits<float>::max() && x > -std::numeric_limits<float>::max()) return x; //if (x >= std::numeric_limits<float>::max()) return std::numeric_limits<float>::max(); //if (x <= -std::numeric_limits<float>::max()) return -std::numeric_limits<float>::max(); if (x < 100000.0f && x > -100000.0f) return x; if (x >= 100000.0f) return 100000.0f; if (x <= 100000.0f) return -100000.0f; return 0.0f; } #define DEBUG_TRAJ(a) //a void Spell::SelectTrajTargets() { if (!m_targets.HasTraj()) return; float dist2d = m_targets.GetDist2d(); if (!dist2d) return; float dz = m_targets.m_dstPos.m_positionZ - m_targets.m_srcPos.m_positionZ; UnitList unitList; SearchAreaTarget(unitList, dist2d, PUSH_IN_THIN_LINE, SPELL_TARGETS_ANY); if (unitList.empty()) return; unitList.sort(Trinity::ObjectDistanceOrderPred(m_caster)); float b = tangent(m_targets.m_elevation); float a = (dz - dist2d * b) / (dist2d * dist2d); if (a > -0.0001f) a = 0; DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: a %f b %f", a, b);) float bestDist = GetSpellMaxRange(m_spellInfo, false); UnitList::const_iterator itr = unitList.begin(); for (; itr != unitList.end(); ++itr) { if (m_caster == *itr || m_caster->IsOnVehicle(*itr) || (*itr)->GetVehicle())//(*itr)->IsOnVehicle(m_caster)) continue; const float size = std::max((*itr)->GetObjectSize() * 0.7f, 1.0f); // 1/sqrt(3) // TODO: all calculation should be based on src instead of m_caster const float objDist2d = m_targets.m_srcPos.GetExactDist2d(*itr) * cos(m_targets.m_srcPos.GetRelativeAngle(*itr)); const float dz = (*itr)->GetPositionZ() - m_targets.m_srcPos.m_positionZ; DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: check %u, dist between %f %f, height between %f %f.", (*itr)->GetEntry(), objDist2d - size, objDist2d + size, dz - size, dz + size);) float dist = objDist2d - size; float height = dist * (a * dist + b); DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);) if (dist < bestDist && height < dz + size && height > dz - size) { bestDist = dist > 0 ? dist : 0; break; } #define CHECK_DIST {\ DEBUG_TRAJ(sLog->outError("Spell::SelectTrajTargets: dist %f, height %f.", dist, height);)\ if (dist > bestDist) continue;\ if (dist < objDist2d + size && dist > objDist2d - size) { bestDist = dist; break; }\ } if (!a) { height = dz - size; dist = height / b; CHECK_DIST; height = dz + size; dist = height / b; CHECK_DIST; continue; } height = dz - size; float sqrt1 = b * b + 4 * a * height; if (sqrt1 > 0) { sqrt1 = sqrt(sqrt1); dist = (sqrt1 - b) / (2 * a); CHECK_DIST; } height = dz + size; float sqrt2 = b * b + 4 * a * height; if (sqrt2 > 0) { sqrt2 = sqrt(sqrt2); dist = (sqrt2 - b) / (2 * a); CHECK_DIST; dist = (-sqrt2 - b) / (2 * a); CHECK_DIST; } if (sqrt1 > 0) { dist = (-sqrt1 - b) / (2 * a); CHECK_DIST; } } if (m_targets.m_srcPos.GetExactDist2d(&m_targets.m_dstPos) > bestDist) { float x = m_targets.m_srcPos.m_positionX + cos(m_caster->GetOrientation()) * bestDist; float y = m_targets.m_srcPos.m_positionY + sin(m_caster->GetOrientation()) * bestDist; float z = m_targets.m_srcPos.m_positionZ + bestDist * (a * bestDist + b); if (itr != unitList.end()) { float distSq = (*itr)->GetExactDistSq(x, y, z); float sizeSq = (*itr)->GetObjectSize(); sizeSq *= sizeSq; DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);) if (distSq > sizeSq) { float factor = 1 - sqrt(sizeSq / distSq); x += factor * ((*itr)->GetPositionX() - x); y += factor * ((*itr)->GetPositionY() - y); z += factor * ((*itr)->GetPositionZ() - z); distSq = (*itr)->GetExactDistSq(x, y, z); DEBUG_TRAJ(sLog->outError("Initial %f %f %f %f %f", x, y, z, distSq, sizeSq);) } } Position trajDst; trajDst.Relocate(x, y, z, m_caster->GetOrientation()); m_targets.modDst(trajDst); } } void Spell::PrepareTargetProcessing() { CheckEffectExecuteData(); } void Spell::FinishTargetProcessing() { SendLogExecute(); } void Spell::InitEffectExecuteData(uint8 effIndex) { ASSERT(effIndex < MAX_SPELL_EFFECTS); if (!m_effectExecuteData[effIndex]) { m_effectExecuteData[effIndex] = new ByteBuffer(0x20); // first dword - target counter *m_effectExecuteData[effIndex] << uint32(1); } else { // increase target counter by one uint32 count = (*m_effectExecuteData[effIndex]).read<uint32>(0); (*m_effectExecuteData[effIndex]).put<uint32>(0, ++count); } } void Spell::CleanupEffectExecuteData() { for(uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) m_effectExecuteData[i] = NULL; } void Spell::CheckEffectExecuteData() { for(uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) ASSERT(!m_effectExecuteData[i]); } void Spell::LoadScripts() { sLog->outDebug("Spell::LoadScripts"); sScriptMgr->CreateSpellScripts(m_spellInfo->Id, m_loadedScripts); for(std::list<SpellScript *>::iterator itr = m_loadedScripts.begin(); itr != m_loadedScripts.end() ;) { if (!(*itr)->_Load(this)) { std::list<SpellScript *>::iterator bitr = itr; ++itr; m_loadedScripts.erase(bitr); continue; } (*itr)->Register(); ++itr; } } void Spell::PrepareScriptHitHandlers() { for(std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr) { (*scritr)->_InitHit(); } } bool Spell::CallScriptEffectHandlers(SpellEffIndex effIndex) { // execute script effect handler hooks and check if effects was prevented bool preventDefault = false; for(std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_EFFECT); std::list<SpellScript::EffectHandler>::iterator effEndItr = (*scritr)->OnEffect.end(), effItr = (*scritr)->OnEffect.begin(); for(; effItr != effEndItr ; ++effItr) { // effect execution can be prevented if (!(*scritr)->_IsEffectPrevented(effIndex) && (*effItr).IsEffectAffected(m_spellInfo, effIndex)) (*effItr).Call(*scritr, effIndex); } if (!preventDefault) preventDefault = (*scritr)->_IsDefaultEffectPrevented(effIndex); (*scritr)->_FinishScriptCall(); } return preventDefault; } void Spell::CallScriptBeforeHitHandlers() { for(std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_BEFORE_HIT); std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->BeforeHit.end(), hookItr = (*scritr)->BeforeHit.begin(); for(; hookItr != hookItrEnd ; ++hookItr) { (*hookItr).Call(*scritr); } (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptOnHitHandlers() { for(std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_HIT); std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->OnHit.end(), hookItr = (*scritr)->OnHit.begin(); for(; hookItr != hookItrEnd ; ++hookItr) { (*hookItr).Call(*scritr); } (*scritr)->_FinishScriptCall(); } } void Spell::CallScriptAfterHitHandlers() { for(std::list<SpellScript *>::iterator scritr = m_loadedScripts.begin(); scritr != m_loadedScripts.end() ; ++scritr) { (*scritr)->_PrepareScriptCall(SPELL_SCRIPT_HOOK_AFTER_HIT); std::list<SpellScript::HitHandler>::iterator hookItrEnd = (*scritr)->AfterHit.end(), hookItr = (*scritr)->AfterHit.begin(); for(; hookItr != hookItrEnd ; ++hookItr) { (*hookItr).Call(*scritr); } (*scritr)->_FinishScriptCall(); } }
maanuel/Isle-of-Conquest
src/server/game/Spells/Spell.cpp
C++
gpl-2.0
293,632
<?php /* * Copyright (C) Vulcan Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program.If not, see <http://www.gnu.org/licenses/>. * */ /** * @file * @ingroup SMWHaloTriplestore * * SMWRuleStore is an abstraction for a rule store. This dummy implementation * does nothing. It has to be implemented by other extensions. * * $smwgDefaultRuleStore must be set to the implementator class name * This class should be loaded by autoload mechanism. * * @author: Kai K�hn * */ class SMWRuleStore { private static $INSTANCE = NULL; public static function getInstance() { if (self::$INSTANCE == NULL) { global $smwgDefaultRuleStore; self::$INSTANCE = !isset($smwgDefaultRuleStore) ? new SMWRuleStore() : new $smwgDefaultRuleStore(); } return self::$INSTANCE; } /** * Returns rule from local rule store for a given page id. * * @param int $page_id * @return array of rule_id */ public function getRules($page_id) { $results = array(); //dummy impl return $results; } /** * Returns all rules * * @return int[] $pageID */ public function getAllRulePages() { $results = array(); //dummy impl return $results; } /** * Adds new rules to the local rule store. * * @param int $article_id * @param array $new_rules (ruleID => ruleText) */ public function addRules($article_id, $new_rules) { // no impl } /** * Removes rule from given article * * @param int $article_id */ public function clearRules($article_id) { // no impl } /** * Updates article IDs. In case of a renaming operation. * * @param int $new_article_id * @param int $old_article_id * @param Title $newTitle * * @return tuple(old rule URI, new rule URI) */ public function updateRules($new_article_id, $old_article_id, $newTitle) { // no impl return array(); } /** * Setups database tables for semantic rules extension. * * @param boolean $verbose */ public function setup($verbose) { // noimpl } /** * Drops database tables for semantic rules extension. * * @param boolean $verbose */ public function drop($verbose) { // noimpl } }
jheizmann/SMWHalo
smwtsc/includes/triplestore_client/TSC_RuleStore.php
PHP
gpl-2.0
2,849
/* * LZO1X Decompressor from LZO * * Copyright (C) 1996-2012 Markus F.X.J. Oberhumer <markus@oberhumer.com> * * The full LZO package can be found at: * http://www.oberhumer.com/opensource/lzo/ * * Changed for Linux kernel use by: * Nitin Gupta <nitingupta910@gmail.com> * Richard Purdie <rpurdie@openedhand.com> */ #ifndef STATIC #include <linux/module.h> #include <linux/kernel.h> #endif #include <asm/unaligned.h> #include <linux/lzo.h> #include "lzodefs.h" #define HAVE_IP(x) ((size_t)(ip_end - ip) >= (size_t)(x)) #define HAVE_OP(x) ((size_t)(op_end - op) >= (size_t)(x)) #define NEED_IP(x) if (!HAVE_IP(x)) goto input_overrun #define NEED_OP(x) if (!HAVE_OP(x)) goto output_overrun #define TEST_LB(m_pos) if ((m_pos) < out) goto lookbehind_overrun /* This MAX_255_COUNT is the maximum number of times we can add 255 to a base * count without overflowing an integer. The multiply will overflow when * multiplying 255 by more than MAXINT/255. The sum will overflow earlier * depending on the base count. Since the base count is taken from a u8 * and a few bits, it is safe to assume that it will always be lower than * or equal to 2*255, thus we can always prevent any overflow by accepting * two less 255 steps. See Documentation/lzo.txt for more information. */ #define MAX_255_COUNT ((((size_t)~0) / 255) - 2) int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len) { unsigned char *op; const unsigned char *ip; size_t t, next; size_t state = 0; const unsigned char *m_pos; const unsigned char * const ip_end = in + in_len; unsigned char * const op_end = out + *out_len; op = out; ip = in; if (unlikely(in_len < 3)) goto input_overrun; if (*ip > 17) { t = *ip++ - 17; if (t < 4) { next = t; goto match_next; } goto copy_literal_run; } for (;;) { t = *ip++; if (t < 16) { if (likely(state == 0)) { if (unlikely(t == 0)) { size_t offset; const unsigned char *ip_last = ip; while (unlikely(*ip == 0)) { ip++; NEED_IP(1); } offset = ip - ip_last; if (unlikely(offset > MAX_255_COUNT)) return LZO_E_ERROR; offset = (offset << 8) - offset; t += offset + 15 + *ip++; } t += 3; copy_literal_run: #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) if (likely(HAVE_IP(t + 15) && HAVE_OP(t + 15))) { const unsigned char *ie = ip + t; unsigned char *oe = op + t; do { COPY8(op, ip); op += 8; ip += 8; # if !defined(__arm__) COPY8(op, ip); op += 8; ip += 8; #endif } while (ip < ie); ip = ie; op = oe; } else #endif { NEED_OP(t); NEED_IP(t + 3); do { *op++ = *ip++; } while (--t > 0); } state = 4; continue; } else if (state != 4) { next = t & 3; m_pos = op - 1; m_pos -= t >> 2; m_pos -= *ip++ << 2; TEST_LB(m_pos); NEED_OP(2); op[0] = m_pos[0]; op[1] = m_pos[1]; op += 2; goto match_next; } else { next = t & 3; m_pos = op - (1 + M2_MAX_OFFSET); m_pos -= t >> 2; m_pos -= *ip++ << 2; t = 3; } } else if (t >= 64) { next = t & 3; m_pos = op - 1; m_pos -= (t >> 2) & 7; m_pos -= *ip++ << 3; t = (t >> 5) - 1 + (3 - 1); } else if (t >= 32) { t = (t & 31) + (3 - 1); if (unlikely(t == 2)) { size_t offset; const unsigned char *ip_last = ip; while (unlikely(*ip == 0)) { ip++; NEED_IP(1); } offset = ip - ip_last; if (unlikely(offset > MAX_255_COUNT)) return LZO_E_ERROR; offset = (offset << 8) - offset; t += offset + 31 + *ip++; NEED_IP(2); } m_pos = op - 1; next = get_unaligned_le16(ip); ip += 2; m_pos -= next >> 2; next &= 3; } else { m_pos = op; m_pos -= (t & 8) << 11; t = (t & 7) + (3 - 1); if (unlikely(t == 2)) { size_t offset; const unsigned char *ip_last = ip; while (unlikely(*ip == 0)) { ip++; NEED_IP(1); } offset = ip - ip_last; if (unlikely(offset > MAX_255_COUNT)) return LZO_E_ERROR; offset = (offset << 8) - offset; t += offset + 7 + *ip++; NEED_IP(2); } next = get_unaligned_le16(ip); ip += 2; m_pos -= next >> 2; next &= 3; if (m_pos == op) goto eof_found; m_pos -= 0x4000; } TEST_LB(m_pos); #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) if (op - m_pos >= 8) { unsigned char *oe = op + t; if (likely(HAVE_OP(t + 15))) { do { COPY8(op, m_pos); op += 8; m_pos += 8; # if !defined(__arm__) COPY8(op, m_pos); op += 8; m_pos += 8; #endif } while (op < oe); op = oe; if (HAVE_IP(6)) { state = next; COPY4(op, ip); op += next; ip += next; continue; } } else { NEED_OP(t); do { *op++ = *m_pos++; } while (op < oe); } } else #endif { unsigned char *oe = op + t; NEED_OP(t); op[0] = m_pos[0]; op[1] = m_pos[1]; op += 2; m_pos += 2; do { *op++ = *m_pos++; } while (op < oe); } match_next: state = next; t = next; #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) if (likely(HAVE_IP(6) && HAVE_OP(4))) { COPY4(op, ip); op += t; ip += t; } else #endif { NEED_IP(t + 3); NEED_OP(t); while (t > 0) { *op++ = *ip++; t--; } } } eof_found: *out_len = op - out; return (t != 3 ? LZO_E_ERROR : ip == ip_end ? LZO_E_OK : ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN); input_overrun: *out_len = op - out; return LZO_E_INPUT_OVERRUN; output_overrun: *out_len = op - out; return LZO_E_OUTPUT_OVERRUN; lookbehind_overrun: *out_len = op - out; return LZO_E_LOOKBEHIND_OVERRUN; } #ifndef STATIC EXPORT_SYMBOL_GPL(lzo1x_decompress_safe); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("LZO1X Decompressor"); #endif
goutamniwas/android_kernel_motorola_msm8610
lib/lzo/lzo1x_decompress_safe.c
C
gpl-2.0
5,923
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "halls_of_reflection.h" #include "Creature.h" #include "EventProcessor.h" #include "InstanceScript.h" #include "MotionMaster.h" #include "MoveSplineInit.h" #include "ObjectAccessor.h" #include "ObjectGuid.h" #include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "ScriptMgr.h" #include "SpellInfo.h" #include "SpellScript.h" #include "TemporarySummon.h" #include "Transport.h" #include "Unit.h" enum Text { SAY_JAINA_INTRO_1 = 0, SAY_JAINA_INTRO_2 = 1, SAY_JAINA_INTRO_3 = 2, SAY_JAINA_INTRO_4 = 3, SAY_JAINA_INTRO_5 = 4, SAY_JAINA_INTRO_6 = 5, SAY_JAINA_INTRO_7 = 6, SAY_JAINA_INTRO_8 = 7, SAY_JAINA_INTRO_9 = 8, SAY_JAINA_INTRO_10 = 9, SAY_JAINA_INTRO_11 = 10, SAY_JAINA_INTRO_END = 11, SAY_SYLVANAS_INTRO_1 = 0, SAY_SYLVANAS_INTRO_2 = 1, SAY_SYLVANAS_INTRO_3 = 2, SAY_SYLVANAS_INTRO_4 = 3, SAY_SYLVANAS_INTRO_5 = 4, SAY_SYLVANAS_INTRO_6 = 5, SAY_SYLVANAS_INTRO_7 = 6, SAY_SYLVANAS_INTRO_8 = 7, SAY_SYLVANAS_INTRO_END = 8, SAY_UTHER_INTRO_A2_1 = 0, SAY_UTHER_INTRO_A2_2 = 1, SAY_UTHER_INTRO_A2_3 = 2, SAY_UTHER_INTRO_A2_4 = 3, SAY_UTHER_INTRO_A2_5 = 4, SAY_UTHER_INTRO_A2_6 = 5, SAY_UTHER_INTRO_A2_7 = 6, SAY_UTHER_INTRO_A2_8 = 7, SAY_UTHER_INTRO_A2_9 = 8, SAY_UTHER_INTRO_H2_1 = 9, SAY_UTHER_INTRO_H2_2 = 10, SAY_UTHER_INTRO_H2_3 = 11, SAY_UTHER_INTRO_H2_4 = 12, SAY_UTHER_INTRO_H2_5 = 13, SAY_UTHER_INTRO_H2_6 = 14, SAY_UTHER_INTRO_H2_7 = 15, SAY_LK_INTRO_1 = 0, SAY_LK_INTRO_2 = 1, SAY_LK_INTRO_3 = 2, SAY_LK_JAINA_INTRO_END = 3, SAY_LK_SYLVANAS_INTRO_END = 4, SAY_JAINA_SYLVANAS_ESCAPE_1 = 0, SAY_JAINA_SYLVANAS_ESCAPE_2 = 1, SAY_JAINA_SYLVANAS_ESCAPE_3 = 2, SAY_JAINA_SYLVANAS_ESCAPE_4 = 3, SAY_JAINA_SYLVANAS_ESCAPE_5 = 4, SAY_JAINA_SYLVANAS_ESCAPE_6 = 5, SAY_JAINA_SYLVANAS_ESCAPE_7 = 6, // unused SAY_JAINA_SYLVANAS_ESCAPE_8 = 7, SAY_JAINA_ESCAPE_9 = 8, SAY_JAINA_ESCAPE_10 = 9, SAY_SYLVANAS_ESCAPE_9 = 8, SAY_LK_ESCAPE_1 = 0, SAY_LK_ESCAPE_2 = 1, SAY_LK_ESCAPE_ICEWALL_SUMMONED_1 = 2, SAY_LK_ESCAPE_ICEWALL_SUMMONED_2 = 3, SAY_LK_ESCAPE_ICEWALL_SUMMONED_3 = 4, SAY_LK_ESCAPE_ICEWALL_SUMMONED_4 = 5, SAY_LK_ESCAPE_GHOULS = 6, SAY_LK_ESCAPE_ABOMINATION = 7, SAY_LK_ESCAPE_WINTER = 8, SAY_LK_ESCAPE_HARVEST_SOUL = 9, SAY_FALRIC_INTRO_1 = 5, SAY_FALRIC_INTRO_2 = 6, SAY_MARWYN_INTRO_1 = 4 }; enum Events { EVENT_WALK_INTRO1 = 1, EVENT_WALK_INTRO2, EVENT_START_INTRO, EVENT_SKIP_INTRO, EVENT_INTRO_A2_1, EVENT_INTRO_A2_2, EVENT_INTRO_A2_3, EVENT_INTRO_A2_4, EVENT_INTRO_A2_5, EVENT_INTRO_A2_6, EVENT_INTRO_A2_7, EVENT_INTRO_A2_8, EVENT_INTRO_A2_9, EVENT_INTRO_A2_10, EVENT_INTRO_A2_11, EVENT_INTRO_A2_12, EVENT_INTRO_A2_13, EVENT_INTRO_A2_14, EVENT_INTRO_A2_15, EVENT_INTRO_A2_16, EVENT_INTRO_A2_17, EVENT_INTRO_A2_18, EVENT_INTRO_A2_19, EVENT_INTRO_H2_1, EVENT_INTRO_H2_2, EVENT_INTRO_H2_3, EVENT_INTRO_H2_4, EVENT_INTRO_H2_5, EVENT_INTRO_H2_6, EVENT_INTRO_H2_7, EVENT_INTRO_H2_8, EVENT_INTRO_H2_9, EVENT_INTRO_H2_10, EVENT_INTRO_H2_11, EVENT_INTRO_H2_12, EVENT_INTRO_H2_13, EVENT_INTRO_H2_14, EVENT_INTRO_H2_15, EVENT_INTRO_LK_1, EVENT_INTRO_LK_2, EVENT_INTRO_LK_3, EVENT_INTRO_LK_4, EVENT_INTRO_LK_5, EVENT_INTRO_LK_6, EVENT_INTRO_LK_7, EVENT_INTRO_LK_8, EVENT_INTRO_LK_9, EVENT_INTRO_LK_10, EVENT_INTRO_LK_11, EVENT_INTRO_END, EVENT_ESCAPE, EVENT_ESCAPE_1, EVENT_ESCAPE_2, EVENT_ESCAPE_3, EVENT_ESCAPE_4, EVENT_ESCAPE_5, EVENT_ESCAPE_6, EVENT_ESCAPE_7, EVENT_ESCAPE_8, EVENT_ESCAPE_9, EVENT_ESCAPE_10, EVENT_ESCAPE_11, EVENT_ESCAPE_12, EVENT_ESCAPE_13, EVENT_ESCAPE_14, EVENT_ESCAPE_15, EVENT_ESCAPE_16, EVENT_ESCAPE_17, EVENT_REMORSELESS_WINTER, EVENT_ESCAPE_SUMMON_GHOULS, EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, EVENT_ESCAPE_SUMMON_LUMBERING_ABOMINATION, EVENT_OPEN_IMPENETRABLE_DOOR, EVENT_CLOSE_IMPENETRABLE_DOOR, EVENT_KORELN_LORALEN_DEATH }; enum Misc { ACTION_START_INTRO, ACTION_SKIP_INTRO, JAINA_SYLVANAS_MAX_HEALTH = 252000, POINT_SHADOW_THRONE_DOOR = 1, POINT_ATTACK_ICEWALL = 2, POINT_TRAP = 3, SOUND_LK_SLAY_1 = 17214, SOUND_LK_SLAY_2 = 17215, SOUND_LK_FURY_OF_FROSTMOURNE = 17224 }; enum Spells { // Misc SPELL_TAKE_FROSTMOURNE = 72729, SPELL_FROSTMOURNE_DESPAWN = 72726, SPELL_FROSTMOURNE_VISUAL = 73220, SPELL_FROSTMOURNE_SOUNDS = 70667, SPELL_BOSS_SPAWN_AURA = 72712, // Falric and Marwyn SPELL_UTHER_DESPAWN = 70693, // Jaina, Sylvanas SPELL_CAST_VISUAL = 65633, // wrong SPELL_SUMMON_SOULS = 72711, SPELL_TAUNT_ARTHAS = 69857, SPELL_JAINA_ICE_BARRIER = 69787, // Jaina Ice Barrier SPELL_JAINA_ICE_PRISON = 69708, // Jaina Ice Prison SPELL_JAINA_DESTROY_ICE_WALL = 69784, // Jaina SPELL_SYLVANAS_CLOAK_OF_DARKNESS = 70188, // Sylvanas Cloak of Darkness SPELL_SYLVANAS_DARK_BINDING = 70194, // Sylvanas Dark Binding SPELL_SYLVANAS_DESTROY_ICE_WALL = 70224, // Sylvanas SPELL_SYLVANAS_BLINDING_RETREAT = 70199, // Sylvanas Blinding Retreat // Lich King SPELL_REMORSELESS_WINTER = 69780, // Lich King Remorseless Winter SPELL_SOUL_REAPER = 69409, // Lich King Soul Reaper SPELL_FURY_OF_FROSTMOURNE = 70063, // Lich King Fury of Frostmourne SPELL_RAISE_DEAD = 69818, SPELL_SUMMON_RISEN_WITCH_DOCTOR = 69836, SPELL_SUMMON_LUMBERING_ABOMINATION = 69835, SPELL_SUMMON_ICE_WALL = 69768, // Visual effect and icewall summoning SPELL_PAIN_AND_SUFFERING = 74115, // Lich King Pain and Suffering SPELL_STUN_BREAK_JAINA = 69764, // Lich King visual spell, another Stun Break is 69763, should remove the stun effect SPELL_STUN_BREAK_SYLVANAS = 70200, SPELL_HARVEST_SOUL = 69866, // Lich King Harvest Soul // Koreln, Loralen SPELL_FEIGN_DEATH = 29266, // Raging Ghoul SPELL_GHOUL_JUMP = 70150, SPELL_RAGING_GHOUL_SPAWN = 69636, // Risen Witch Doctor SPELL_CURSE_OF_DOOM = 70144, SPELL_SHADOW_BOLT_VOLLEY = 70145, SPELL_SHADOW_BOLT = 70080, SPELL_RISEN_WITCH_DOCTOR_SPAWN = 69639, // Lumbering Abomination SPELL_CLEAVE = 40505, SPELL_VOMIT_SPRAY = 70176 }; enum HorGossipMenu { GOSSIP_MENU_JAINA_FINAL = 10930, GOSSIP_MENU_SYLVANAS_FINAL = 10931 }; Position const NpcJainaOrSylvanasEscapeRoute[] = { { 5601.217285f, 2207.652832f, 731.541931f, 5.223304f }, // leave the throne room { 5607.224375f, 2173.913330f, 731.126038f, 2.608723f }, // adjust route { 5583.427246f, 2138.784180f, 731.150391f, 4.260901f }, // stop for talking { 5560.281738f, 2104.025635f, 731.410889f, 4.058383f }, // attack the first icewall { 5510.990723f, 2000.772217f, 734.716064f, 3.973213f }, // attack the second icewall { 5452.641113f, 1905.762329f, 746.530579f, 4.118834f }, // attack the third icewall { 5338.126953f, 1768.429810f, 767.237244f, 3.855189f }, // attack the fourth icewall { 5259.06f, 1669.27f, 784.3008f, 0.0f }, // trap (sniffed) { 5265.53f, 1681.6f, 784.2947f, 4.13643f } // final position (sniffed) }; Position const LichKingMoveAwayPos = { 5400.069824f, 2102.7131689f, 707.69525f, 0.843803f }; // Lich King walks away Position const LichKingFirstSummon = { 5600.076172f, 2192.270996f, 731.750488f, 4.330935f }; // Lich King First summons Position const JainaSylvanasShadowThroneDoor = { 5577.243f, 2235.852f, 733.0128f, 2.209562f }; // Jaina/Sylvanas move to door Position const LichKingFinalPos = { 5283.742188f, 1706.335693f, 783.293518f, 4.138510f }; // Lich King Final Pos // sniffed Position const KorelnOrLoralenPos[] = { { 5253.061f, 1953.616f, 707.6948f, 0.8377581f }, { 5283.226f, 1992.300f, 707.7445f, 0.8377581f }, { 5360.711f, 2064.797f, 707.6948f, 0.0f } }; Position const SylvanasIntroPosition[] = { { 0.0f, 0.0f, 0.0f, 0.0f }, // 0 - Spawn { 5263.2f, 1950.96f, 707.6948f, 0.8028514f }, // 1 - Move to Door { 5306.82f, 1998.17f, 709.341f, 1.239184f }, // 2 - Move to Frostmourne }; Position const JainaIntroPosition[] = { { 0.0f, 0.0f, 0.0f, 0.0f }, // 0 - Spawn { 5265.89f, 1952.98f, 707.6978f, 0.0f }, // 1 - Move to Door { 5306.95f, 1998.49f, 709.3414f, 1.277278f } // 2 - Move to Frostmourne }; Position const UtherSpawnPos = { 5307.814f, 2003.168f, 709.4244f, 4.537856f }; Position const LichKingIntroPosition[] = { { 5362.463f, 2062.693f, 707.7781f, 3.944444f }, // 0 - Spawn { 5332.83f, 2031.24f, 707.6948f, 0.0f }, // 1 - Door { 5312.93f, 2010.24f, 709.34f, 0.0f }, // 2 - Move to Frostmourne { 5319.028f, 2016.662f, 707.6948f, 0.0f }, // 3 - Move back { 5332.285f, 2030.832f, 707.6948f, 0.0f }, // 4 - Move back 2 { 5355.488f, 2055.149f, 707.6907f, 0.0f } // 5 - Move back 3 }; Position const FalricPosition[] = { { 5276.583f, 2037.45f, 709.4025f, 5.532694f }, // 0 - Spawn { 5283.95f, 2030.53f, 709.3191f, 0.0f } // 1 - Intro }; Position const MarwynPosition[] = { { 5342.232f, 1975.696f, 709.4025f, 2.391101f }, // 0 - Spawn { 5335.01f, 1982.37f, 709.3191f, 0.0f } // 1 - Intro }; Position const SylvanasShadowThroneDoorPosition = { 5576.79f, 2235.73f, 733.0029f, 2.687807f }; Position const IceWallTargetPosition[] = { { 5547.833f, 2083.701f, 731.4332f, 1.029744f }, // 1st Icewall { 5503.213f, 1969.547f, 737.0245f, 1.27409f }, // 2nd Icewall { 5439.976f, 1879.005f, 752.7048f, 1.064651f }, // 3rd Icewall { 5318.289f, 1749.184f, 771.9423f, 0.8726646f } // 4th Icewall }; class npc_jaina_or_sylvanas_intro_hor : public CreatureScript { public: npc_jaina_or_sylvanas_intro_hor() : CreatureScript("npc_jaina_or_sylvanas_intro_hor") { } struct npc_jaina_or_sylvanas_intro_horAI : public ScriptedAI { npc_jaina_or_sylvanas_intro_horAI(Creature* creature) : ScriptedAI(creature) { _instance = me->GetInstanceScript(); } bool OnGossipHello(Player* player) override { // override default gossip if (_instance->GetData(DATA_QUEL_DELAR_EVENT) == IN_PROGRESS || _instance->GetData(DATA_QUEL_DELAR_EVENT) == SPECIAL) { ClearGossipMenuFor(player); return true; } // load default gossip return false; } bool OnGossipSelect(Player* player, uint32 /*menuId*/, uint32 gossipListId) override { ClearGossipMenuFor(player); switch (gossipListId) { case 0: CloseGossipMenuFor(player); _events.ScheduleEvent(EVENT_START_INTRO, 1s); me->RemoveNpcFlag(NPCFlags(UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER)); break; case 1: CloseGossipMenuFor(player); _events.ScheduleEvent(EVENT_SKIP_INTRO, 1s); me->RemoveNpcFlag(NPCFlags(UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER)); break; default: break; } return false; } void Reset() override { _events.Reset(); _utherGUID.Clear(); _lichkingGUID.Clear(); me->RemoveNpcFlag(NPCFlags(UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER)); me->SetStandState(UNIT_STAND_STATE_STAND); _events.ScheduleEvent(EVENT_WALK_INTRO1, 3s); } void UpdateAI(uint32 diff) override { _events.Update(diff); switch (_events.ExecuteEvent()) { case EVENT_WALK_INTRO1: if (Creature* korelnOrLoralen = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_KORELN_LORALEN))) korelnOrLoralen->GetMotionMaster()->MovePoint(0, KorelnOrLoralenPos[0]); if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) { me->GetMotionMaster()->MovePoint(0, JainaIntroPosition[1]); Talk(SAY_JAINA_INTRO_1); _events.ScheduleEvent(EVENT_WALK_INTRO2, 7s); } else { me->GetMotionMaster()->MovePoint(0, SylvanasIntroPosition[1]); Talk(SAY_SYLVANAS_INTRO_1); _events.ScheduleEvent(EVENT_WALK_INTRO2, 9s); } break; case EVENT_WALK_INTRO2: if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) Talk(SAY_JAINA_INTRO_2); else Talk(SAY_SYLVANAS_INTRO_2); me->AddNpcFlag(NPCFlags(UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER)); break; case EVENT_START_INTRO: if (Creature* korelnOrLoralen = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_KORELN_LORALEN))) korelnOrLoralen->GetMotionMaster()->MovePoint(0, KorelnOrLoralenPos[1]); // Begining of intro is differents between factions as the speech sequence and timers are differents. if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) { me->GetMotionMaster()->MovePoint(0, JainaIntroPosition[2]); _events.ScheduleEvent(EVENT_INTRO_A2_1, 0s); } else { me->GetMotionMaster()->MovePoint(0, SylvanasIntroPosition[2]); _events.ScheduleEvent(EVENT_INTRO_H2_1, 0s); } break; // A2 Intro Events case EVENT_INTRO_A2_1: Talk(SAY_JAINA_INTRO_3); _events.ScheduleEvent(EVENT_INTRO_A2_2, 7s); break; case EVENT_INTRO_A2_2: Talk(SAY_JAINA_INTRO_4); _events.ScheduleEvent(EVENT_INTRO_A2_3, 10s); break; case EVENT_INTRO_A2_3: me->CastSpell(me, SPELL_CAST_VISUAL, false); me->CastSpell(me, SPELL_FROSTMOURNE_SOUNDS, true); _instance->HandleGameObject(_instance->GetGuidData(DATA_FROSTMOURNE), true); _events.ScheduleEvent(EVENT_INTRO_A2_4, 10s); break; case EVENT_INTRO_A2_4: if (Creature* uther = me->SummonCreature(NPC_UTHER, UtherSpawnPos, TEMPSUMMON_MANUAL_DESPAWN)) _utherGUID = uther->GetGUID(); _events.ScheduleEvent(EVENT_INTRO_A2_5, 2s); break; case EVENT_INTRO_A2_5: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_1); _events.ScheduleEvent(EVENT_INTRO_A2_6, 3s); break; case EVENT_INTRO_A2_6: Talk(SAY_JAINA_INTRO_5); _events.ScheduleEvent(EVENT_INTRO_A2_7, 7s); break; case EVENT_INTRO_A2_7: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_2); _events.ScheduleEvent(EVENT_INTRO_A2_8, 7s); break; case EVENT_INTRO_A2_8: Talk(SAY_JAINA_INTRO_6); _events.ScheduleEvent(EVENT_INTRO_A2_9, 1200ms); break; case EVENT_INTRO_A2_9: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_3); _events.ScheduleEvent(EVENT_INTRO_A2_10, 11s); break; case EVENT_INTRO_A2_10: Talk(SAY_JAINA_INTRO_7); _events.ScheduleEvent(EVENT_INTRO_A2_11, 6s); break; case EVENT_INTRO_A2_11: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_4); _events.ScheduleEvent(EVENT_INTRO_A2_12, 12s); break; case EVENT_INTRO_A2_12: Talk(SAY_JAINA_INTRO_8); _events.ScheduleEvent(EVENT_INTRO_A2_13, 6s); break; case EVENT_INTRO_A2_13: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_5); _events.ScheduleEvent(EVENT_INTRO_A2_14, 13s); break; case EVENT_INTRO_A2_14: Talk(SAY_JAINA_INTRO_9); _events.ScheduleEvent(EVENT_INTRO_A2_15, 12s); break; case EVENT_INTRO_A2_15: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_6); _events.ScheduleEvent(EVENT_INTRO_A2_16, 25s); break; case EVENT_INTRO_A2_16: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_A2_7); _events.ScheduleEvent(EVENT_INTRO_A2_17, 6s); break; case EVENT_INTRO_A2_17: Talk(SAY_JAINA_INTRO_10); _events.ScheduleEvent(EVENT_INTRO_A2_18, 5s); break; case EVENT_INTRO_A2_18: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) { uther->HandleEmoteCommand(EMOTE_ONESHOT_NO); uther->AI()->Talk(SAY_UTHER_INTRO_A2_8); } _events.ScheduleEvent(EVENT_INTRO_A2_19, 12s); break; case EVENT_INTRO_A2_19: Talk(SAY_JAINA_INTRO_11); _events.ScheduleEvent(EVENT_INTRO_LK_1, 3s); break; // H2 Intro Events case EVENT_INTRO_H2_1: Talk(SAY_SYLVANAS_INTRO_1); _events.ScheduleEvent(EVENT_INTRO_H2_2, 8s); break; case EVENT_INTRO_H2_2: Talk(SAY_SYLVANAS_INTRO_2); _events.ScheduleEvent(EVENT_INTRO_H2_3, 6s); break; case EVENT_INTRO_H2_3: Talk(SAY_SYLVANAS_INTRO_3); me->CastSpell(me, SPELL_CAST_VISUAL, false); me->CastSpell(me, SPELL_FROSTMOURNE_SOUNDS, true); _instance->HandleGameObject(_instance->GetGuidData(DATA_FROSTMOURNE), true); _events.ScheduleEvent(EVENT_INTRO_H2_4, 6s); break; case EVENT_INTRO_H2_4: // spawn UTHER during speach 2 if (Creature* uther = me->SummonCreature(NPC_UTHER, UtherSpawnPos, TEMPSUMMON_MANUAL_DESPAWN)) _utherGUID = uther->GetGUID(); _events.ScheduleEvent(EVENT_INTRO_H2_5, 2s); break; case EVENT_INTRO_H2_5: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_1); _events.ScheduleEvent(EVENT_INTRO_H2_6, 11s); break; case EVENT_INTRO_H2_6: Talk(SAY_SYLVANAS_INTRO_4); _events.ScheduleEvent(EVENT_INTRO_H2_7, 3s); break; case EVENT_INTRO_H2_7: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_2); _events.ScheduleEvent(EVENT_INTRO_H2_8, 6s); break; case EVENT_INTRO_H2_8: Talk(SAY_SYLVANAS_INTRO_5); _events.ScheduleEvent(EVENT_INTRO_H2_9, 5s); break; case EVENT_INTRO_H2_9: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_3); _events.ScheduleEvent(EVENT_INTRO_H2_10, 19s); break; case EVENT_INTRO_H2_10: Talk(SAY_SYLVANAS_INTRO_6); _events.ScheduleEvent(EVENT_INTRO_H2_11, 1500ms); break; case EVENT_INTRO_H2_11: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_4); _events.ScheduleEvent(EVENT_INTRO_H2_12, 19500ms); break; case EVENT_INTRO_H2_12: Talk(SAY_SYLVANAS_INTRO_7); _events.ScheduleEvent(EVENT_INTRO_H2_13, 2s); break; case EVENT_INTRO_H2_13: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) { uther->HandleEmoteCommand(EMOTE_ONESHOT_NO); uther->AI()->Talk(SAY_UTHER_INTRO_H2_5); } _events.ScheduleEvent(EVENT_INTRO_H2_14, 12s); break; case EVENT_INTRO_H2_14: if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) uther->AI()->Talk(SAY_UTHER_INTRO_H2_6); _events.ScheduleEvent(EVENT_INTRO_H2_15, 8s); break; case EVENT_INTRO_H2_15: Talk(SAY_SYLVANAS_INTRO_8); _events.ScheduleEvent(EVENT_INTRO_LK_1, 2s); break; // Remaining Intro Events common for both faction case EVENT_INTRO_LK_1: // Spawn LK in front of door, and make him move to the sword. if (Creature* lichking = me->SummonCreature(NPC_THE_LICH_KING_INTRO, LichKingIntroPosition[0], TEMPSUMMON_MANUAL_DESPAWN)) { lichking->SetWalk(true); lichking->GetMotionMaster()->MovePoint(0, LichKingIntroPosition[2]); _lichkingGUID = lichking->GetGUID(); _events.ScheduleEvent(EVENT_OPEN_IMPENETRABLE_DOOR, 0s); _events.ScheduleEvent(EVENT_CLOSE_IMPENETRABLE_DOOR, 4s); } if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) { uther->SetEmoteState(EMOTE_STATE_COWER); if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) uther->AI()->Talk(SAY_UTHER_INTRO_A2_9); else uther->AI()->Talk(SAY_UTHER_INTRO_H2_7); } _events.ScheduleEvent(EVENT_INTRO_LK_2, 10s); break; case EVENT_INTRO_LK_2: if (Creature* lichking = ObjectAccessor::GetCreature(*me, _lichkingGUID)) lichking->AI()->Talk(SAY_LK_INTRO_1); _events.ScheduleEvent(EVENT_INTRO_LK_3, 1s); break; case EVENT_INTRO_LK_3: // The Lich King banishes Uther to the abyss. if (Creature* uther = ObjectAccessor::GetCreature(*me, _utherGUID)) { uther->CastSpell(uther, SPELL_UTHER_DESPAWN, true); uther->DespawnOrUnsummon(5s); _utherGUID.Clear(); } _events.ScheduleEvent(EVENT_INTRO_LK_4, 9s); break; case EVENT_INTRO_LK_4: // He steps forward and removes the runeblade from the heap of skulls. if (Creature* lichking = ObjectAccessor::GetCreature(*me, _lichkingGUID)) { if (GameObject* frostmourne = ObjectAccessor::GetGameObject(*me, _instance->GetGuidData(DATA_FROSTMOURNE))) frostmourne->SetLootState(GO_JUST_DEACTIVATED); lichking->CastSpell(lichking, SPELL_TAKE_FROSTMOURNE, true); lichking->CastSpell(lichking, SPELL_FROSTMOURNE_VISUAL, true); } _events.ScheduleEvent(EVENT_INTRO_LK_5, 8s); break; case EVENT_INTRO_LK_5: if (Creature* lichking = ObjectAccessor::GetCreature(*me, _lichkingGUID)) lichking->AI()->Talk(SAY_LK_INTRO_2); _events.ScheduleEvent(EVENT_INTRO_LK_6, 10s); break; case EVENT_INTRO_LK_6: // summon Falric and Marwyn. then go back to the door if (Creature* falric = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FALRIC))) { falric->CastSpell(falric, SPELL_BOSS_SPAWN_AURA, true); falric->SetVisible(true); } if (Creature* marwyn = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_MARWYN))) { marwyn->CastSpell(marwyn, SPELL_BOSS_SPAWN_AURA, true); marwyn->SetVisible(true); } if (Creature* lichking = ObjectAccessor::GetCreature(*me, _lichkingGUID)) { lichking->AI()->Talk(SAY_LK_INTRO_3); lichking->SetWalk(true); lichking->GetMotionMaster()->MovePoint(0, LichKingMoveAwayPos); } _events.ScheduleEvent(EVENT_INTRO_LK_7, 10s); _events.ScheduleEvent(EVENT_OPEN_IMPENETRABLE_DOOR, 5s); break; case EVENT_INTRO_LK_7: if (Creature* marwyn = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_MARWYN))) { marwyn->AI()->Talk(SAY_MARWYN_INTRO_1); marwyn->SetWalk(true); marwyn->GetMotionMaster()->MovePoint(0, MarwynPosition[1]); } _events.ScheduleEvent(EVENT_INTRO_LK_8, 1s); break; case EVENT_INTRO_LK_8: if (Creature* falric = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FALRIC))) { falric->AI()->Talk(SAY_FALRIC_INTRO_1); falric->SetWalk(true); falric->GetMotionMaster()->MovePoint(0, FalricPosition[1]); } _events.ScheduleEvent(EVENT_INTRO_LK_9, 5s); break; case EVENT_INTRO_LK_9: if (Creature* falric = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FALRIC))) falric->AI()->Talk(SAY_FALRIC_INTRO_2); _instance->ProcessEvent(nullptr, EVENT_SPAWN_WAVES, nullptr); _events.ScheduleEvent(EVENT_INTRO_LK_10, 4s); break; case EVENT_INTRO_LK_10: if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) Talk(SAY_JAINA_INTRO_END); else Talk(SAY_SYLVANAS_INTRO_END); me->GetMotionMaster()->MovePoint(0, LichKingMoveAwayPos); /// @todo: needs some improvements if (Creature* korelnOrLoralen = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_KORELN_LORALEN))) korelnOrLoralen->GetMotionMaster()->MovePoint(1, KorelnOrLoralenPos[2]); _events.ScheduleEvent(EVENT_INTRO_LK_11, 5s); break; case EVENT_INTRO_LK_11: if (Creature* lichking = ObjectAccessor::GetCreature(*me, _lichkingGUID)) { if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) lichking->AI()->Talk(SAY_LK_JAINA_INTRO_END); else lichking->AI()->Talk(SAY_LK_SYLVANAS_INTRO_END); } _events.ScheduleEvent(EVENT_INTRO_END, 5s); break; case EVENT_INTRO_END: _instance->SetData(DATA_INTRO_EVENT, DONE); _events.ScheduleEvent(EVENT_KORELN_LORALEN_DEATH, 8s); if (Creature* lichking = ObjectAccessor::GetCreature(*me, _lichkingGUID)) { lichking->DespawnOrUnsummon(5s); _lichkingGUID.Clear(); } me->DespawnOrUnsummon(10s); _events.ScheduleEvent(EVENT_CLOSE_IMPENETRABLE_DOOR, 7s); break; case EVENT_SKIP_INTRO: if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) me->GetMotionMaster()->MovePoint(0, JainaIntroPosition[2]); else me->GetMotionMaster()->MovePoint(0, SylvanasIntroPosition[2]); if (Creature* korelnOrLoralen = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_KORELN_LORALEN))) korelnOrLoralen->GetMotionMaster()->MovePoint(0, KorelnOrLoralenPos[1]); if (Creature* lichking = me->SummonCreature(NPC_THE_LICH_KING_INTRO, LichKingIntroPosition[0], TEMPSUMMON_MANUAL_DESPAWN)) { lichking->SetWalk(true); lichking->GetMotionMaster()->MovePoint(0, LichKingIntroPosition[2]); lichking->SetReactState(REACT_PASSIVE); _lichkingGUID = lichking->GetGUID(); _events.ScheduleEvent(EVENT_OPEN_IMPENETRABLE_DOOR, 0s); _events.ScheduleEvent(EVENT_CLOSE_IMPENETRABLE_DOOR, 4s); } _events.ScheduleEvent(EVENT_INTRO_LK_4, 15s); break; case EVENT_OPEN_IMPENETRABLE_DOOR: _instance->HandleGameObject(_instance->GetGuidData(DATA_IMPENETRABLE_DOOR), true); break; case EVENT_CLOSE_IMPENETRABLE_DOOR: _instance->HandleGameObject(_instance->GetGuidData(DATA_IMPENETRABLE_DOOR), false); break; case EVENT_KORELN_LORALEN_DEATH: if (Creature* korelnOrLoralen = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_KORELN_LORALEN))) korelnOrLoralen->CastSpell(korelnOrLoralen, SPELL_FEIGN_DEATH); break; default: break; } } private: InstanceScript* _instance; EventMap _events; ObjectGuid _utherGUID; ObjectGuid _lichkingGUID; }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_jaina_or_sylvanas_intro_horAI>(creature); } }; class HoRGameObjectDeleteDelayEvent : public BasicEvent { public: explicit HoRGameObjectDeleteDelayEvent(Unit* owner, ObjectGuid gameObjectGUID) : _owner(owner), _gameObjectGUID(gameObjectGUID) { } void DeleteGameObject() { if (GameObject* go = ObjectAccessor::GetGameObject(*_owner, _gameObjectGUID)) go->Delete(); } bool Execute(uint64 /*execTime*/, uint32 /*diff*/) override { DeleteGameObject(); return true; } void Abort(uint64 /*execTime*/) override { DeleteGameObject(); } private: Unit* _owner; ObjectGuid _gameObjectGUID; }; class npc_jaina_or_sylvanas_escape_hor : public CreatureScript { public: npc_jaina_or_sylvanas_escape_hor() : CreatureScript("npc_jaina_or_sylvanas_escape_hor") { } struct npc_jaina_or_sylvanas_escape_horAI : public ScriptedAI { npc_jaina_or_sylvanas_escape_horAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()), _icewall(0), _prefight(false), _invincibility(true) { } void Reset() override { _events.Reset(); _icewall = 0; _events.ScheduleEvent(EVENT_ESCAPE, 1s); _instance->DoStopCriteriaTimer(CriteriaStartEvent::SendEvent, ACHIEV_NOT_RETREATING_EVENT); } void JustDied(Unit* /*killer*/) override { if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) lichking->AI()->EnterEvadeMode(); // event failed } void DamageTaken(Unit* /*attacker*/, uint32& damage) override { if (damage >= me->GetHealth() && _invincibility) damage = me->GetHealth() - 1; } void DoAction(int32 actionId) override { switch (actionId) { case ACTION_START_PREFIGHT: if (_prefight) return; _prefight = true; _events.ScheduleEvent(EVENT_ESCAPE_1, 1s); break; case ACTION_WALL_BROKEN: ++_icewall; if (_icewall < 4) _events.ScheduleEvent(EVENT_ESCAPE_13, 3s); else _events.ScheduleEvent(EVENT_ESCAPE_15, 3s); break; case ACTION_GUNSHIP_ARRIVAL: _events.ScheduleEvent(EVENT_ESCAPE_16, 5s); break; case ACTION_GUNSHIP_ARRIVAL_2: _events.ScheduleEvent(EVENT_ESCAPE_17, 5s); break; default: break; } } bool OnGossipHello(Player* player) override { // override default gossip if (_instance->GetBossState(DATA_THE_LICH_KING_ESCAPE) == DONE) { player->PrepareGossipMenu(me, me->GetEntry() == NPC_JAINA_ESCAPE ? GOSSIP_MENU_JAINA_FINAL : GOSSIP_MENU_SYLVANAS_FINAL, true); player->SendPreparedGossip(me); return true; } // load default gossip return false; } bool OnGossipSelect(Player* player, uint32 /*menuId*/, uint32 gossipListId) override { ClearGossipMenuFor(player); switch (gossipListId) { case 0: CloseGossipMenuFor(player); me->RemoveNpcFlag(UNIT_NPC_FLAG_GOSSIP); _events.ScheduleEvent(EVENT_ESCAPE_6, 0s); break; default: break; } return false; } void DestroyIceWall() { if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) me->RemoveAurasDueToSpell(SPELL_JAINA_DESTROY_ICE_WALL); else me->RemoveAurasDueToSpell(SPELL_SYLVANAS_DESTROY_ICE_WALL); _instance->HandleGameObject(_instance->GetGuidData(DATA_ICEWALL), true); me->m_Events.AddEvent(new HoRGameObjectDeleteDelayEvent(me, _instance->GetGuidData(DATA_ICEWALL)), me->m_Events.CalculateTime(5s)); if (Creature* wallTarget = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_ICEWALL_TARGET))) wallTarget->DespawnOrUnsummon(); } void SummonIceWall() { if (_icewall < 4) { if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) { lichking->StopMoving(); if (Creature* wallTarget = me->SummonCreature(NPC_ICE_WALL_TARGET, IceWallTargetPosition[_icewall], TEMPSUMMON_MANUAL_DESPAWN, 12min)) lichking->CastSpell(wallTarget, SPELL_SUMMON_ICE_WALL); lichking->AI()->SetData(DATA_ICEWALL, _icewall); } } } void AttackIceWall() { if (_icewall < 4) Talk(SAY_JAINA_SYLVANAS_ESCAPE_2 + _icewall); if (Creature* wallTarget = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_ICEWALL_TARGET))) me->SetFacingToObject(wallTarget); if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) DoCast(me, SPELL_JAINA_DESTROY_ICE_WALL, true); else DoCast(me, SPELL_SYLVANAS_DESTROY_ICE_WALL, true); } void MovementInform(uint32 type, uint32 pointId) override { if (type != POINT_MOTION_TYPE) return; switch (pointId) { case POINT_SHADOW_THRONE_DOOR: if (me->GetEntry() == NPC_JAINA_ESCAPE) me->RemoveAurasDueToSpell(SPELL_JAINA_ICE_BARRIER); else me->RemoveAurasDueToSpell(SPELL_SYLVANAS_CLOAK_OF_DARKNESS); me->AddNpcFlag(UNIT_NPC_FLAG_GOSSIP); me->SetHealth(JAINA_SYLVANAS_MAX_HEALTH); me->SetFacingTo(SylvanasShadowThroneDoorPosition.GetOrientation()); break; case POINT_ATTACK_ICEWALL: AttackIceWall(); break; case POINT_TRAP: Talk(SAY_JAINA_SYLVANAS_ESCAPE_8); if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) me->SetFacingToObject(lichking); break; default: break; } } void DeleteAllFromThreatList(Unit* target, ObjectGuid except) { for (ThreatReference* ref : target->GetThreatManager().GetModifiableThreatList()) if (ref->GetVictim()->GetGUID() != except) ref->ClearThreat(); } void UpdateAI(uint32 diff) override { _events.Update(diff); while (uint32 event = _events.ExecuteEvent()) { switch (event) { case EVENT_ESCAPE: if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) DoCast(me, SPELL_JAINA_ICE_BARRIER); else DoCast(me, SPELL_SYLVANAS_CLOAK_OF_DARKNESS); if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) { me->CastSpell(lichking, SPELL_TAUNT_ARTHAS, true); lichking->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); lichking->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_ATTACK_ME, true); AttackStart(lichking); lichking->AI()->AttackStart(me); } me->SetHealth(JAINA_SYLVANAS_MAX_HEALTH); me->RemoveNpcFlag(NPCFlags(UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER)); break; case EVENT_ESCAPE_1: if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) { if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) lichking->AI()->Talk(SAY_LK_ESCAPE_1); else lichking->AI()->Talk(SAY_LK_ESCAPE_2); _events.ScheduleEvent(EVENT_ESCAPE_2, 8s); } break; case EVENT_ESCAPE_2: me->AttackStop(); me->StopMoving(); me->SetReactState(REACT_PASSIVE); if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) DoCast(me, SPELL_JAINA_ICE_PRISON, false); else DoCast(me, SPELL_SYLVANAS_BLINDING_RETREAT, true); if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) { lichking->SetReactState(REACT_PASSIVE); lichking->AddUnitFlag(UNIT_FLAG_PACIFIED); } _events.ScheduleEvent(EVENT_ESCAPE_3, 1500ms); break; case EVENT_ESCAPE_3: if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == HORDE) DoCastAOE(SPELL_SYLVANAS_DARK_BINDING, true); _events.ScheduleEvent(EVENT_ESCAPE_4, 1s); break; case EVENT_ESCAPE_4: if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) DoCast(me, SPELL_CREDIT_FINDING_JAINA); else DoCast(me, SPELL_CREDIT_FINDING_SYLVANAS); Talk(SAY_JAINA_SYLVANAS_ESCAPE_1); if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) { lichking->SetImmuneToPC(true); lichking->RemoveAllAttackers(); DeleteAllFromThreatList(lichking, me->GetGUID()); } _events.ScheduleEvent(EVENT_ESCAPE_5, 2s); break; case EVENT_ESCAPE_5: me->GetMotionMaster()->MovePoint(POINT_SHADOW_THRONE_DOOR, SylvanasShadowThroneDoorPosition); break; case EVENT_ESCAPE_6: if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) { lichking->RemoveUnitFlag(UNIT_FLAG_PACIFIED); lichking->SetImmuneToPC(false); if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) { lichking->CastSpell(lichking, SPELL_STUN_BREAK_JAINA); lichking->RemoveAurasDueToSpell(SPELL_JAINA_ICE_PRISON); } else { lichking->CastSpell(lichking, SPELL_STUN_BREAK_SYLVANAS); lichking->RemoveAurasDueToSpell(SPELL_SYLVANAS_DARK_BINDING); } } _invincibility = false; _instance->DoStartCriteriaTimer(CriteriaStartEvent::SendEvent, ACHIEV_NOT_RETREATING_EVENT); _events.ScheduleEvent(EVENT_ESCAPE_7, 1s); break; case EVENT_ESCAPE_7: if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) lichking->HandleEmoteCommand(EMOTE_ONESHOT_ROAR); me->GetMotionMaster()->MovePoint(0, NpcJainaOrSylvanasEscapeRoute[0]); _events.ScheduleEvent(EVENT_ESCAPE_8, 3s); break; case EVENT_ESCAPE_8: if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) lichking->GetMotionMaster()->MovePoint(0, NpcJainaOrSylvanasEscapeRoute[0]); _events.ScheduleEvent(EVENT_ESCAPE_9, 1s); break; case EVENT_ESCAPE_9: me->GetMotionMaster()->MovePoint(0, NpcJainaOrSylvanasEscapeRoute[1]); _events.ScheduleEvent(EVENT_ESCAPE_10, 5s); break; case EVENT_ESCAPE_10: me->GetMotionMaster()->MovePoint(0, NpcJainaOrSylvanasEscapeRoute[2]); if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) lichking->GetMotionMaster()->MovePoint(1, LichKingFirstSummon); _events.ScheduleEvent(EVENT_ESCAPE_11, 6s); break; case EVENT_ESCAPE_11: SummonIceWall(); _events.ScheduleEvent(EVENT_ESCAPE_12, 4s); break; case EVENT_ESCAPE_12: if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) lichking->CastSpell(lichking, SPELL_PAIN_AND_SUFFERING, true); me->GetMotionMaster()->MovePoint(POINT_ATTACK_ICEWALL, NpcJainaOrSylvanasEscapeRoute[3]); break; case EVENT_ESCAPE_13: // ICEWALL BROKEN DestroyIceWall(); if (_icewall && _icewall < 4) me->GetMotionMaster()->MovePoint(POINT_ATTACK_ICEWALL, NpcJainaOrSylvanasEscapeRoute[_icewall + 3]); _events.ScheduleEvent(EVENT_ESCAPE_14, 8s); break; case EVENT_ESCAPE_14: SummonIceWall(); break; case EVENT_ESCAPE_15: // FINAL PART DestroyIceWall(); Talk(SAY_JAINA_SYLVANAS_ESCAPE_6); if (Creature* lichking = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_THE_LICH_KING_ESCAPE))) { lichking->GetMotionMaster()->MovePoint(2, LichKingFinalPos); lichking->RemoveAurasDueToSpell(SPELL_REMORSELESS_WINTER); } me->GetMotionMaster()->MovePoint(POINT_TRAP, NpcJainaOrSylvanasEscapeRoute[7]); break; case EVENT_ESCAPE_16: me->RemoveAurasDueToSpell(SPELL_HARVEST_SOUL); if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) Talk(SAY_JAINA_ESCAPE_9); if (Transport* gunship = ObjectAccessor::GetTransportOnMap(*me, _instance->GetGuidData(DATA_GUNSHIP))) gunship->EnableMovement(true); _instance->SetBossState(DATA_THE_LICH_KING_ESCAPE, DONE); break; case EVENT_ESCAPE_17: if (_instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) Talk(SAY_JAINA_ESCAPE_10); else Talk(SAY_SYLVANAS_ESCAPE_9); DoCast(me, SPELL_CREDIT_ESCAPING_ARTHAS); me->AddNpcFlag(NPCFlags(UNIT_NPC_FLAG_GOSSIP | UNIT_NPC_FLAG_QUESTGIVER)); break; default: break; } } DoMeleeAttackIfReady(); } private: InstanceScript* _instance; EventMap _events; uint32 _icewall; // icewall number bool _prefight; bool _invincibility; }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_jaina_or_sylvanas_escape_horAI>(creature); } }; class npc_the_lich_king_escape_hor : public CreatureScript { public: npc_the_lich_king_escape_hor() : CreatureScript("npc_the_lich_king_escape_hor") { } struct npc_the_lich_king_escape_horAI : public ScriptedAI { npc_the_lich_king_escape_horAI(Creature* creature) : ScriptedAI(creature) { _instance = me->GetInstanceScript(); _instance->SetBossState(DATA_THE_LICH_KING_ESCAPE, NOT_STARTED); _summonsCount = 0; _icewall = 0; _despawn = false; } void DamageTaken(Unit* /*attacker*/, uint32& damage) override { if (damage >= me->GetHealth()) damage = me->GetHealth() - 1; } void MovementInform(uint32 type, uint32 pointId) override { if (type == POINT_MOTION_TYPE) { switch (pointId) { case 1: if (Creature* target = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_ESCAPE_LEADER))) me->GetMotionMaster()->MoveChase(target); break; case 2: Talk(SAY_LK_ESCAPE_HARVEST_SOUL); if (Creature* target = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_ESCAPE_LEADER))) DoCast(target, SPELL_HARVEST_SOUL); if (Transport* gunship = ObjectAccessor::GetTransportOnMap(*me, _instance->GetGuidData(DATA_GUNSHIP))) gunship->EnableMovement(true); break; default: break; } } } void JustSummoned(Creature* /*summon*/) override { ++_summonsCount; } void SummonedCreatureDies(Creature* /*summon*/, Unit* /*killer*/) override { // should never happen if (!_summonsCount) return; --_summonsCount; // All summons dead and no summon events scheduled if (!_summonsCount && _events.Empty()) { if (Creature* jainaOrSylvanas = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_ESCAPE_LEADER))) jainaOrSylvanas->AI()->DoAction(ACTION_WALL_BROKEN); } } void KilledUnit(Unit* who) override { if (who->GetTypeId() == TYPEID_PLAYER) DoPlaySoundToSet(me, RAND(SOUND_LK_SLAY_1, SOUND_LK_SLAY_2)); } void SetData(uint32 type, uint32 data) override { if (type != DATA_ICEWALL) return; _icewall = data; switch (_icewall) { case 0: // 6 Ghouls, 1 Witch Doctor DoZoneInCombat(); _events.ScheduleEvent(EVENT_REMORSELESS_WINTER, 0s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_GHOULS, 8s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, 14s); Talk(SAY_LK_ESCAPE_ICEWALL_SUMMONED_1); break; case 1: // 6 Ghouls, 2 Witch Doctor, 1 Lumbering Abomination _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_GHOULS, 8s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_LUMBERING_ABOMINATION, 13s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, 15s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, 18s); Talk(SAY_LK_ESCAPE_ICEWALL_SUMMONED_2); break; case 2: // 6 Ghouls, 2 Witch Doctor, 2 Lumbering Abomination _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_GHOULS, 9s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_LUMBERING_ABOMINATION, 14s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, 15s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_LUMBERING_ABOMINATION, 19s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, 39s); Talk(SAY_LK_ESCAPE_ICEWALL_SUMMONED_3); break; case 3: // 12 Ghouls, 4 Witch Doctor, 3 Lumbering Abomination _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_GHOULS, 9s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, 15s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, 19s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_LUMBERING_ABOMINATION, 40s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_LUMBERING_ABOMINATION, 45s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_GHOULS, 55s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, 62s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_WITCH_DOCTOR, 65s); _events.ScheduleEvent(EVENT_ESCAPE_SUMMON_LUMBERING_ABOMINATION, 14s); Talk(SAY_LK_ESCAPE_ICEWALL_SUMMONED_4); break; default: break; } } void EnterEvadeMode(EvadeReason /*why*/) override { if (_despawn) return; _instance->SetBossState(DATA_THE_LICH_KING_ESCAPE, FAIL); me->StopMoving(); DoPlaySoundToSet(me, SOUND_LK_FURY_OF_FROSTMOURNE); DoCastAOE(SPELL_FURY_OF_FROSTMOURNE); me->DespawnOrUnsummon(12s); _despawn = true; } void UpdateAI(uint32 diff) override { if (!SelectVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 event = _events.ExecuteEvent()) { switch (event) { case EVENT_REMORSELESS_WINTER: me->StopMoving(); Talk(SAY_LK_ESCAPE_WINTER); DoCast(me, SPELL_REMORSELESS_WINTER); break; case EVENT_ESCAPE_SUMMON_GHOULS: me->StopMoving(); Talk(SAY_LK_ESCAPE_GHOULS); DoCast(me, SPELL_RAISE_DEAD); break; case EVENT_ESCAPE_SUMMON_WITCH_DOCTOR: DoCast(me, SPELL_SUMMON_RISEN_WITCH_DOCTOR); break; case EVENT_ESCAPE_SUMMON_LUMBERING_ABOMINATION: Talk(SAY_LK_ESCAPE_ABOMINATION); DoCast(me, SPELL_SUMMON_LUMBERING_ABOMINATION); break; default: break; } } DoMeleeAttackIfReady(); } private: bool SelectVictim() { if (!me->IsInCombat()) return false; if (!me->HasReactState(REACT_PASSIVE)) { if (Unit* victim = me->SelectVictim()) if (!me->HasSpellFocus() && victim != me->GetVictim()) AttackStart(victim); return me->GetVictim() != nullptr; } else if (me->GetCombatManager().GetPvECombatRefs().size() < 2 && me->HasAura(SPELL_REMORSELESS_WINTER)) { EnterEvadeMode(EVADE_REASON_OTHER); return false; } return true; } InstanceScript* _instance; EventMap _events; uint8 _icewall; uint32 _summonsCount; bool _despawn; }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_the_lich_king_escape_horAI>(creature); } }; enum TrashSpells { // Ghostly Priest SPELL_SHADOW_WORD_PAIN = 72318, SPELL_CIRCLE_OF_DESTRUCTION = 72320, SPELL_COWER_IN_FEAR = 72321, SPELL_DARK_MENDING = 72322, // Phantom Mage SPELL_FIREBALL = 72163, SPELL_FLAMESTRIKE = 72169, SPELL_FROSTBOLT = 72166, SPELL_CHAINS_OF_ICE = 72121, SPELL_HALLUCINATION = 72342, AURA_HALLUCINATION = 72343, // Phantom Hallucination (same as phantom mage + HALLUCINATION_2 when dies) SPELL_HALLUCINATION_2 = 72344, // Shadowy Mercenary SPELL_SHADOW_STEP = 72326, SPELL_DEADLY_POISON = 72329, SPELL_ENVENOMED_DAGGER_THROW = 72333, SPELL_KIDNEY_SHOT = 72335, // Spectral Footman SPELL_SPECTRAL_STRIKE = 72198, SPELL_SHIELD_BASH = 72194, SPELL_TORTURED_ENRAGE = 72203, // Tortured Rifleman SPELL_SHOOT = 72208, SPELL_CURSED_ARROW = 72222, SPELL_FROST_TRAP = 72215, SPELL_ICE_SHOT = 72268 }; enum TrashEvents { EVENT_TRASH_NONE, // Ghostly Priest EVENT_SHADOW_WORD_PAIN, EVENT_CIRCLE_OF_DESTRUCTION, EVENT_COWER_IN_FEAR, EVENT_DARK_MENDING, // Phantom Mage EVENT_FIREBALL, EVENT_FLAMESTRIKE, EVENT_FROSTBOLT, EVENT_CHAINS_OF_ICE, EVENT_HALLUCINATION, // Shadowy Mercenary EVENT_SHADOW_STEP, EVENT_DEADLY_POISON, EVENT_ENVENOMED_DAGGER_THROW, EVENT_KIDNEY_SHOT, // Spectral Footman EVENT_SPECTRAL_STRIKE, EVENT_SHIELD_BASH, EVENT_TORTURED_ENRAGE, // Tortured Rifleman EVENT_SHOOT, EVENT_CURSED_ARROW, EVENT_FROST_TRAP, EVENT_ICE_SHOT }; struct npc_gauntlet_trash : public ScriptedAI { npc_gauntlet_trash(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()), InternalWaveId(0) { } void Reset() override { me->CastSpell(me, SPELL_WELL_OF_SOULS, true); _events.Reset(); } void EnterEvadeMode(EvadeReason /*why*/) override { if (_instance->GetData(DATA_WAVE_COUNT) != NOT_STARTED) _instance->SetData(DATA_WAVE_COUNT, NOT_STARTED); } void SetData(uint32 type, uint32 value) override { if (type) return; InternalWaveId = value; } uint32 GetData(uint32 type) const override { if (type) return 0; return InternalWaveId; } protected: EventMap _events; InstanceScript* _instance; uint32 InternalWaveId; }; class npc_ghostly_priest : public CreatureScript { public: npc_ghostly_priest() : CreatureScript("npc_ghostly_priest") { } struct npc_ghostly_priestAI : public npc_gauntlet_trash { npc_ghostly_priestAI(Creature* creature) : npc_gauntlet_trash(creature) { } void JustEngagedWith(Unit* /*who*/) override { _events.ScheduleEvent(EVENT_SHADOW_WORD_PAIN, 6s, 15s); _events.ScheduleEvent(EVENT_CIRCLE_OF_DESTRUCTION, 12s); _events.ScheduleEvent(EVENT_COWER_IN_FEAR, 10s); _events.ScheduleEvent(EVENT_DARK_MENDING, 20s); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_events.ExecuteEvent()) { case EVENT_SHADOW_WORD_PAIN: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 40.0f, true)) DoCast(target, SPELL_SHADOW_WORD_PAIN); _events.ScheduleEvent(EVENT_SHADOW_WORD_PAIN, 6s, 15s); break; case EVENT_CIRCLE_OF_DESTRUCTION: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 10.0f, true)) DoCast(target, SPELL_CIRCLE_OF_DESTRUCTION); _events.ScheduleEvent(EVENT_CIRCLE_OF_DESTRUCTION, 12s); break; case EVENT_COWER_IN_FEAR: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 20.0f, true)) DoCast(target, SPELL_COWER_IN_FEAR); _events.ScheduleEvent(EVENT_COWER_IN_FEAR, 10s); break; case EVENT_DARK_MENDING: // find an ally with missing HP if (Unit* target = DoSelectLowestHpFriendly(40, DUNGEON_MODE(30000, 50000))) { DoCast(target, SPELL_DARK_MENDING); _events.ScheduleEvent(EVENT_DARK_MENDING, 20s); } else { // no friendly unit with missing hp. re-check in just 5 sec. _events.ScheduleEvent(EVENT_DARK_MENDING, 5s); } break; default: break; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_ghostly_priestAI>(creature); } }; class npc_phantom_mage : public CreatureScript { public: npc_phantom_mage() : CreatureScript("npc_phantom_mage") { } struct npc_phantom_mageAI : public npc_gauntlet_trash { npc_phantom_mageAI(Creature* creature) : npc_gauntlet_trash(creature) { } void EnterEvadeMode(EvadeReason why) override { if (!me->HasAura(AURA_HALLUCINATION)) npc_gauntlet_trash::EnterEvadeMode(why); } void JustEngagedWith(Unit* /*who*/) override { _events.ScheduleEvent(EVENT_FIREBALL, 3s); _events.ScheduleEvent(EVENT_FLAMESTRIKE, 6s); _events.ScheduleEvent(EVENT_FROSTBOLT, 9s); _events.ScheduleEvent(EVENT_CHAINS_OF_ICE, 12s); _events.ScheduleEvent(EVENT_HALLUCINATION, 40s); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_events.ExecuteEvent()) { case EVENT_FIREBALL: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 40.0f, true)) DoCast(target, SPELL_FIREBALL); _events.ScheduleEvent(EVENT_FIREBALL, 15s); break; case EVENT_FLAMESTRIKE: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 40.0f, true)) DoCast(target, SPELL_FLAMESTRIKE); _events.ScheduleEvent(EVENT_FLAMESTRIKE, 15s); break; case EVENT_FROSTBOLT: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 40.0f, true)) DoCast(target, SPELL_FROSTBOLT); _events.ScheduleEvent(EVENT_FROSTBOLT, 15s); break; case EVENT_CHAINS_OF_ICE: if (Unit* target = SelectTarget(SelectTargetMethod::Random)) DoCast(target, SPELL_CHAINS_OF_ICE); _events.ScheduleEvent(EVENT_CHAINS_OF_ICE, 15s); break; case EVENT_HALLUCINATION: // removing any dots on mage or else the invisibility spell will break duration me->RemoveAllAuras(); DoCast(me, SPELL_HALLUCINATION); break; default: break; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_phantom_mageAI>(creature); } }; class npc_phantom_hallucination : public CreatureScript { public: npc_phantom_hallucination() : CreatureScript("npc_phantom_hallucination") { } struct npc_phantom_hallucinationAI : public npc_phantom_mage::npc_phantom_mageAI { npc_phantom_hallucinationAI(Creature* creature) : npc_phantom_mage::npc_phantom_mageAI(creature) { } void Reset() override { DoZoneInCombat(me); } void EnterEvadeMode(EvadeReason why) override { if (me->GetOwner() && !me->GetOwner()->HasAura(AURA_HALLUCINATION)) npc_phantom_mage::npc_phantom_mageAI::EnterEvadeMode(why); } void JustDied(Unit* /*killer*/) override { DoCastAOE(SPELL_HALLUCINATION_2); } }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_phantom_hallucinationAI>(creature); } }; class npc_shadowy_mercenary : public CreatureScript { public: npc_shadowy_mercenary() : CreatureScript("npc_shadowy_mercenary") { } struct npc_shadowy_mercenaryAI : public npc_gauntlet_trash { npc_shadowy_mercenaryAI(Creature* creature) : npc_gauntlet_trash(creature) { } void JustEngagedWith(Unit* /*who*/) override { _events.ScheduleEvent(EVENT_SHADOW_STEP, 23s); _events.ScheduleEvent(EVENT_DEADLY_POISON, 5s); _events.ScheduleEvent(EVENT_ENVENOMED_DAGGER_THROW, 10s); _events.ScheduleEvent(EVENT_KIDNEY_SHOT, 12s); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_events.ExecuteEvent()) { case EVENT_SHADOW_STEP: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 100.0f, true)) DoCast(target, SPELL_SHADOW_STEP); _events.ScheduleEvent(EVENT_SHADOW_STEP, 8s); break; case EVENT_DEADLY_POISON: DoCastVictim(SPELL_DEADLY_POISON); _events.ScheduleEvent(EVENT_DEADLY_POISON, 10s); break; case EVENT_ENVENOMED_DAGGER_THROW: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 40.0f, true)) DoCast(target, SPELL_ENVENOMED_DAGGER_THROW); _events.ScheduleEvent(EVENT_ENVENOMED_DAGGER_THROW, 10s); break; case EVENT_KIDNEY_SHOT: DoCastVictim(SPELL_KIDNEY_SHOT); _events.ScheduleEvent(EVENT_KIDNEY_SHOT, 10s); break; default: break; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_shadowy_mercenaryAI>(creature); } }; class npc_spectral_footman : public CreatureScript { public: npc_spectral_footman() : CreatureScript("npc_spectral_footman") { } struct npc_spectral_footmanAI : public npc_gauntlet_trash { npc_spectral_footmanAI(Creature* creature) : npc_gauntlet_trash(creature) { } void JustEngagedWith(Unit* /*who*/) override { _events.ScheduleEvent(EVENT_SPECTRAL_STRIKE, 14s); _events.ScheduleEvent(EVENT_SHIELD_BASH, 10s); _events.ScheduleEvent(EVENT_TORTURED_ENRAGE, 15s); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_events.ExecuteEvent()) { case EVENT_SPECTRAL_STRIKE: DoCastVictim(SPELL_SPECTRAL_STRIKE); _events.ScheduleEvent(EVENT_SPECTRAL_STRIKE, 5s); break; case EVENT_SHIELD_BASH: DoCastVictim(SPELL_SHIELD_BASH); _events.ScheduleEvent(EVENT_SHIELD_BASH, 5s); break; case EVENT_TORTURED_ENRAGE: DoCast(me, SPELL_TORTURED_ENRAGE); _events.ScheduleEvent(EVENT_TORTURED_ENRAGE, 15s); break; default: break; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_spectral_footmanAI>(creature); } }; class npc_tortured_rifleman : public CreatureScript { public: npc_tortured_rifleman() : CreatureScript("npc_tortured_rifleman") { } struct npc_tortured_riflemanAI : public npc_gauntlet_trash { npc_tortured_riflemanAI(Creature* creature) : npc_gauntlet_trash(creature) { } void JustEngagedWith(Unit* /*who*/) override { _events.ScheduleEvent(EVENT_SHOOT, 1ms); _events.ScheduleEvent(EVENT_CURSED_ARROW, 7s); _events.ScheduleEvent(EVENT_FROST_TRAP, 10s); _events.ScheduleEvent(EVENT_ICE_SHOT, 15s); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_events.ExecuteEvent()) { case EVENT_SHOOT: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 40.0f, true)) DoCast(target, SPELL_SHOOT); _events.ScheduleEvent(EVENT_SHOOT, 2s); break; case EVENT_CURSED_ARROW: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 40.0f, true)) DoCast(target, SPELL_CURSED_ARROW); _events.ScheduleEvent(EVENT_CURSED_ARROW, 10s); break; case EVENT_FROST_TRAP: DoCast(me, SPELL_FROST_TRAP); _events.ScheduleEvent(EVENT_FROST_TRAP, 30s); break; case EVENT_ICE_SHOT: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 40.0f, true)) DoCast(target, SPELL_ICE_SHOT); _events.ScheduleEvent(EVENT_ICE_SHOT, 15s); break; default: break; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_tortured_riflemanAI>(creature); } }; enum FrostswornGeneral { // General EVENT_SHIELD = 1, EVENT_SPIKE = 2, EVENT_CLONE = 3, SAY_AGGRO = 0, SAY_DEATH = 1, SPELL_SHIELD_THROWN = 69222, SPELL_SPIKE = 69184, SPELL_CLONE = 69828, SPELL_GHOST_VISUAL = 69861, // Reflection EVENT_BALEFUL_STRIKE = 1, SPELL_BALEFUL_STRIKE = 69933, SPELL_SPIRIT_BURST = 69900 }; class npc_frostsworn_general : public CreatureScript { public: npc_frostsworn_general() : CreatureScript("npc_frostsworn_general") { } struct npc_frostsworn_generalAI : public ScriptedAI { npc_frostsworn_generalAI(Creature* creature) : ScriptedAI(creature) { _instance = creature->GetInstanceScript(); } void Reset() override { _events.Reset(); _instance->SetData(DATA_FROSTSWORN_GENERAL, NOT_STARTED); } void JustDied(Unit* /*killer*/) override { Talk(SAY_DEATH); _events.Reset(); _instance->SetData(DATA_FROSTSWORN_GENERAL, DONE); } void JustEngagedWith(Unit* /*victim*/) override { Talk(SAY_AGGRO); DoZoneInCombat(); _events.ScheduleEvent(EVENT_SHIELD, 5s); _events.ScheduleEvent(EVENT_SPIKE, 14s); _events.ScheduleEvent(EVENT_CLONE, 22s); _instance->SetData(DATA_FROSTSWORN_GENERAL, IN_PROGRESS); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 event = _events.ExecuteEvent()) { switch (event) { case EVENT_SHIELD: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 45.0f, true)) DoCast(target, SPELL_SHIELD_THROWN); _events.ScheduleEvent(EVENT_SHIELD, 8s, 12s); break; case EVENT_SPIKE: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 45.0f, true)) DoCast(target, SPELL_SPIKE); _events.ScheduleEvent(EVENT_SPIKE, 15s, 20s); break; case EVENT_CLONE: SummonClones(); _events.ScheduleEvent(EVENT_CLONE, 1min); break; default: break; } } DoMeleeAttackIfReady(); } void SummonClones() { std::list<Unit*> playerList; SelectTargetList(playerList, 5, SelectTargetMethod::MaxThreat, 0, 0.0f, true); for (Unit* target : playerList) { if (Creature* reflection = me->SummonCreature(NPC_REFLECTION, *target, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 3s)) { reflection->SetImmuneToPC(false); target->CastSpell(reflection, SPELL_CLONE, true); target->CastSpell(reflection, SPELL_GHOST_VISUAL, true); reflection->AI()->AttackStart(target); } } } private: InstanceScript* _instance; EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_frostsworn_generalAI>(creature); } }; class npc_spiritual_reflection : public CreatureScript { public: npc_spiritual_reflection() : CreatureScript("npc_spiritual_reflection") { } struct npc_spiritual_reflectionAI : public ScriptedAI { npc_spiritual_reflectionAI(Creature *creature) : ScriptedAI(creature) { } void Reset() override { _events.Reset(); } void JustEngagedWith(Unit* /*victim*/) override { _events.ScheduleEvent(EVENT_BALEFUL_STRIKE, 3s); } void JustDied(Unit* /*killer*/) override { DoCastAOE(SPELL_SPIRIT_BURST); } void UpdateAI(uint32 diff) override { if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_events.ExecuteEvent()) { case EVENT_BALEFUL_STRIKE: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 8.0f, true)) DoCast(target, SPELL_BALEFUL_STRIKE); _events.ScheduleEvent(EVENT_BALEFUL_STRIKE, 3s, 8s); break; default: break; } DoMeleeAttackIfReady(); } private: EventMap _events; }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_spiritual_reflectionAI>(creature); } }; // 5689 class at_hor_intro_start : public AreaTriggerScript { public: at_hor_intro_start() : AreaTriggerScript("at_hor_intro_start") { } bool OnTrigger(Player* player, AreaTriggerEntry const* /*areaTrigger*/) override { if (player->IsGameMaster()) return true; InstanceScript* _instance = player->GetInstanceScript(); if (_instance->GetData(DATA_INTRO_EVENT) == NOT_STARTED) _instance->SetData(DATA_INTRO_EVENT, IN_PROGRESS); if (player->HasAura(SPELL_QUEL_DELAR_COMPULSION) && (player->GetQuestStatus(QUEST_HALLS_OF_REFLECTION_ALLIANCE) == QUEST_STATUS_INCOMPLETE || player->GetQuestStatus(QUEST_HALLS_OF_REFLECTION_HORDE) == QUEST_STATUS_INCOMPLETE) && _instance->GetData(DATA_QUEL_DELAR_EVENT) == NOT_STARTED) { _instance->SetData(DATA_QUEL_DELAR_EVENT, IN_PROGRESS); _instance->SetGuidData(DATA_QUEL_DELAR_INVOKER, player->GetGUID()); } return true; } }; class at_hor_waves_restarter : public AreaTriggerScript { public: at_hor_waves_restarter() : AreaTriggerScript("at_hor_waves_restarter") { } bool OnTrigger(Player* player, AreaTriggerEntry const* /*areaTrigger*/) override { if (player->IsGameMaster()) return true; InstanceScript* _instance = player->GetInstanceScript(); if (_instance->GetData(DATA_WAVE_COUNT)) return true; if (_instance->GetData(DATA_INTRO_EVENT) == DONE && _instance->GetBossState(DATA_MARWYN) != DONE) { _instance->ProcessEvent(nullptr, EVENT_SPAWN_WAVES, nullptr); if (Creature* falric = ObjectAccessor::GetCreature(*player, _instance->GetGuidData(DATA_FALRIC))) { falric->CastSpell(falric, SPELL_BOSS_SPAWN_AURA, true); falric->SetVisible(true); } if (Creature* marwyn = ObjectAccessor::GetCreature(*player, _instance->GetGuidData(DATA_MARWYN))) { marwyn->CastSpell(marwyn, SPELL_BOSS_SPAWN_AURA, true); marwyn->SetVisible(true); } } return true; } }; // 5740 class at_hor_impenetrable_door : public AreaTriggerScript { public: at_hor_impenetrable_door() : AreaTriggerScript("at_hor_impenetrable_door") { } bool OnTrigger(Player* player, AreaTriggerEntry const* /*areaTrigger*/) override { if (player->IsGameMaster()) return true; InstanceScript* _instance = player->GetInstanceScript(); if (_instance->GetBossState(DATA_MARWYN) == DONE) return true; /// return false to handle teleport by db return false; } }; // 5605 class at_hor_shadow_throne : public AreaTriggerScript { public: at_hor_shadow_throne() : AreaTriggerScript("at_hor_shadow_throne") { } bool OnTrigger(Player* player, AreaTriggerEntry const* /*areaTrigger*/) override { if (player->IsGameMaster()) return true; InstanceScript* _instance = player->GetInstanceScript(); if (_instance->GetBossState(DATA_THE_LICH_KING_ESCAPE) == NOT_STARTED) _instance->SetBossState(DATA_THE_LICH_KING_ESCAPE, IN_PROGRESS); return true; } }; enum EscapeEvents { // Raging Ghoul EVENT_RAGING_GHOUL_JUMP = 1, // Risen Witch Doctor EVENT_RISEN_WITCH_DOCTOR_CURSE, EVENT_RISEN_WITCH_DOCTOR_SHADOW_BOLT, EVENT_RISEN_WITCH_DOCTOR_SHADOW_BOLT_VOLLEY, // Lumbering Abomination EVENT_LUMBERING_ABOMINATION_VOMIT_SPRAY, EVENT_LUMBERING_ABOMINATION_CLEAVE }; class HoRStartMovementEvent : public BasicEvent { public: explicit HoRStartMovementEvent(Creature* owner) : _owner(owner) { } bool Execute(uint64 /*execTime*/, uint32 /*diff*/) override { _owner->SetReactState(REACT_AGGRESSIVE); if (Unit* target = _owner->AI()->SelectTarget(SelectTargetMethod::Random, 0, 0.0f, true)) _owner->AI()->AttackStart(target); return true; } private: Creature* _owner; }; struct npc_escape_event_trash : public ScriptedAI { npc_escape_event_trash(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()) { } void Reset() override { _events.Reset(); } void UpdateAI(uint32 /*diff*/) override { if (_instance->GetBossState(DATA_THE_LICH_KING_ESCAPE) == FAIL || _instance->GetBossState(DATA_THE_LICH_KING_ESCAPE) == NOT_STARTED) me->DespawnOrUnsummon(); } void IsSummonedBy(WorldObject* /*summoner*/) override { DoZoneInCombat(me); if (Creature* leader = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_ESCAPE_LEADER))) { me->SetImmuneToPC(false); me->SetInCombatWith(leader); leader->SetInCombatWith(me); AddThreat(leader, 0.0f); } } protected: EventMap _events; InstanceScript* _instance; }; class npc_raging_ghoul : public CreatureScript { public: npc_raging_ghoul() : CreatureScript("npc_raging_ghoul") { } struct npc_raging_ghoulAI : public npc_escape_event_trash { npc_raging_ghoulAI(Creature* creature) : npc_escape_event_trash(creature) { } void Reset() override { npc_escape_event_trash::Reset(); _events.ScheduleEvent(EVENT_RAGING_GHOUL_JUMP, 5s); } void IsSummonedBy(WorldObject* summoner) override { me->CastSpell(me, SPELL_RAGING_GHOUL_SPAWN, true); me->SetReactState(REACT_PASSIVE); me->HandleEmoteCommand(EMOTE_ONESHOT_EMERGE); me->m_Events.AddEvent(new HoRStartMovementEvent(me), me->m_Events.CalculateTime(5s)); npc_escape_event_trash::IsSummonedBy(summoner); } void UpdateAI(uint32 diff) override { npc_escape_event_trash::UpdateAI(diff); if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_events.ExecuteEvent()) { case EVENT_RAGING_GHOUL_JUMP: if (Unit* victim = me->GetVictim()) { if (me->IsInRange(victim, 5.0f, 30.0f)) { DoCast(victim, SPELL_GHOUL_JUMP); return; } } _events.ScheduleEvent(EVENT_RAGING_GHOUL_JUMP, 500ms); break; default: break; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_raging_ghoulAI>(creature); } }; class npc_risen_witch_doctor : public CreatureScript { public: npc_risen_witch_doctor() : CreatureScript("npc_risen_witch_doctor") { } struct npc_risen_witch_doctorAI : public npc_escape_event_trash { npc_risen_witch_doctorAI(Creature* creature) : npc_escape_event_trash(creature) { } void Reset() override { npc_escape_event_trash::Reset(); _events.ScheduleEvent(EVENT_RISEN_WITCH_DOCTOR_SHADOW_BOLT, 6s); _events.ScheduleEvent(EVENT_RISEN_WITCH_DOCTOR_SHADOW_BOLT_VOLLEY, 15s); _events.ScheduleEvent(EVENT_RISEN_WITCH_DOCTOR_CURSE, 7s); } void IsSummonedBy(WorldObject* summoner) override { me->CastSpell(me, SPELL_RISEN_WITCH_DOCTOR_SPAWN, true); me->SetReactState(REACT_PASSIVE); me->HandleEmoteCommand(EMOTE_ONESHOT_EMERGE); me->m_Events.AddEvent(new HoRStartMovementEvent(me), me->m_Events.CalculateTime(5s)); npc_escape_event_trash::IsSummonedBy(summoner); } void UpdateAI(uint32 diff) override { npc_escape_event_trash::UpdateAI(diff); if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_events.ExecuteEvent()) { case EVENT_RISEN_WITCH_DOCTOR_CURSE: if (Unit* target = SelectTarget(SelectTargetMethod::Random, 0, 30.0f, true)) DoCast(target, SPELL_CURSE_OF_DOOM); _events.ScheduleEvent(EVENT_RISEN_WITCH_DOCTOR_CURSE, 10s, 15s); break; case EVENT_RISEN_WITCH_DOCTOR_SHADOW_BOLT: if (Unit* target = SelectTarget(SelectTargetMethod::MaxThreat, 0, 20.0f, true)) DoCast(target, SPELL_SHADOW_BOLT); _events.ScheduleEvent(EVENT_RISEN_WITCH_DOCTOR_SHADOW_BOLT, 2s, 3s); break; case EVENT_RISEN_WITCH_DOCTOR_SHADOW_BOLT_VOLLEY: if (SelectTarget(SelectTargetMethod::Random, 0, 30.0f, true)) DoCastAOE(SPELL_SHADOW_BOLT_VOLLEY); _events.ScheduleEvent(EVENT_RISEN_WITCH_DOCTOR_SHADOW_BOLT_VOLLEY, 15s, 22s); break; default: break; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_risen_witch_doctorAI>(creature); } }; class npc_lumbering_abomination : public CreatureScript { public: npc_lumbering_abomination() : CreatureScript("npc_lumbering_abomination") { } struct npc_lumbering_abominationAI : public npc_escape_event_trash { npc_lumbering_abominationAI(Creature* creature) : npc_escape_event_trash(creature) { } void Reset() override { npc_escape_event_trash::Reset(); _events.ScheduleEvent(EVENT_LUMBERING_ABOMINATION_VOMIT_SPRAY, 15s); _events.ScheduleEvent(EVENT_LUMBERING_ABOMINATION_CLEAVE, 6s); } void UpdateAI(uint32 diff) override { npc_escape_event_trash::UpdateAI(diff); if (!UpdateVictim()) return; _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (_events.ExecuteEvent()) { case EVENT_LUMBERING_ABOMINATION_VOMIT_SPRAY: DoCastVictim(SPELL_VOMIT_SPRAY); _events.ScheduleEvent(EVENT_LUMBERING_ABOMINATION_VOMIT_SPRAY, 15s, 20s); break; case EVENT_LUMBERING_ABOMINATION_CLEAVE: DoCastVictim(SPELL_CLEAVE); _events.ScheduleEvent(EVENT_LUMBERING_ABOMINATION_CLEAVE, 7s, 9s); break; default: break; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_lumbering_abominationAI>(creature); } }; enum QuelDelarUther { ACTION_UTHER_START_SCREAM = 1, ACTION_UTHER_OUTRO = 2, EVENT_UTHER_1 = 1, EVENT_UTHER_2 = 2, EVENT_UTHER_3 = 3, EVENT_UTHER_4 = 4, EVENT_UTHER_5 = 5, EVENT_UTHER_6 = 6, EVENT_UTHER_7 = 7, EVENT_UTHER_8 = 8, EVENT_UTHER_9 = 9, EVENT_UTHER_10 = 10, EVENT_UTHER_11 = 11, EVENT_UTHER_FACING = 12, EVENT_UTHER_KNEEL = 13, SAY_UTHER_QUEL_DELAR_1 = 16, SAY_UTHER_QUEL_DELAR_2 = 17, SAY_UTHER_QUEL_DELAR_3 = 18, SAY_UTHER_QUEL_DELAR_4 = 19, SAY_UTHER_QUEL_DELAR_5 = 20, SAY_UTHER_QUEL_DELAR_6 = 21, SPELL_ESSENCE_OF_CAPTURED_1 = 73036 }; enum QuelDelarSword { SPELL_WHIRLWIND_VISUAL = 70300, SPELL_HEROIC_STRIKE = 29426, SPELL_WHIRLWIND = 67716, SPELL_BLADESTORM = 67541, NPC_QUEL_DELAR = 37158, POINT_TAKE_OFF = 1, EVENT_QUEL_DELAR_INIT = 1, EVENT_QUEL_DELAR_FLIGHT_INIT = 2, EVENT_QUEL_DELAR_FLIGHT = 3, EVENT_QUEL_DELAR_LAND = 4, EVENT_QUEL_DELAR_FIGHT = 5, EVENT_QUEL_DELAR_BLADESTORM = 6, EVENT_QUEL_DELAR_HEROIC_STRIKE = 7, EVENT_QUEL_DELAR_WHIRLWIND = 8, SAY_QUEL_DELAR_SWORD = 0 }; enum QuelDelarMisc { SAY_FROSTMOURNE_BUNNY = 0, SPELL_QUEL_DELAR_WILL = 70698 }; Position const QuelDelarCenterPos = { 5309.259f, 2006.390f, 718.046f, 0.0f }; Position const QuelDelarSummonPos = { 5298.473f, 1994.852f, 709.424f, 3.979351f }; Position const QuelDelarMovement[] = { { 5292.870f, 1998.950f, 718.046f, 0.0f }, { 5295.819f, 1991.912f, 707.707f, 0.0f }, { 5295.301f, 1989.782f, 708.696f, 0.0f } }; Position const UtherQuelDelarMovement[] = { { 5336.830f, 1981.700f, 709.319f, 0.0f }, { 5314.350f, 1993.440f, 707.726f, 0.0f } }; class npc_uther_quel_delar : public CreatureScript { public: npc_uther_quel_delar() : CreatureScript("npc_uther_quel_delar") { } struct npc_uther_quel_delarAI : public ScriptedAI { npc_uther_quel_delarAI(Creature* creature) : ScriptedAI(creature) { _instance = me->GetInstanceScript(); } void Reset() override { // Prevent to break Uther in intro event during instance encounter if (_instance->GetData(DATA_QUEL_DELAR_EVENT) != IN_PROGRESS && _instance->GetData(DATA_QUEL_DELAR_EVENT) != SPECIAL) return; _events.Reset(); _events.ScheduleEvent(EVENT_UTHER_1, 1ms); } void DamageTaken(Unit* /*attacker*/, uint32& damage) override { if (damage >= me->GetHealth()) damage = me->GetHealth() - 1; } void DoAction(int32 action) override { switch (action) { case ACTION_UTHER_START_SCREAM: _instance->SetData(DATA_QUEL_DELAR_EVENT, SPECIAL); _events.ScheduleEvent(EVENT_UTHER_2, 0s); break; case ACTION_UTHER_OUTRO: _events.ScheduleEvent(EVENT_UTHER_6, 0s); break; default: break; } } void MovementInform(uint32 /*type*/, uint32 pointId) override { switch (pointId) { case 1: _events.ScheduleEvent(EVENT_UTHER_FACING, 1s); break; default: break; } } void UpdateAI(uint32 diff) override { // Prevent to break Uther in intro event during instance encounter if (_instance->GetData(DATA_QUEL_DELAR_EVENT) != IN_PROGRESS && _instance->GetData(DATA_QUEL_DELAR_EVENT) != SPECIAL) return; _events.Update(diff); while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_UTHER_1: Talk(SAY_UTHER_QUEL_DELAR_1); break; case EVENT_UTHER_2: if (Creature* bunny = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FROSTMOURNE_ALTAR_BUNNY))) if (Unit* target = ObjectAccessor::GetPlayer(*me, _instance->GetGuidData(DATA_QUEL_DELAR_INVOKER))) bunny->CastSpell(target, SPELL_QUEL_DELAR_WILL, true); _events.ScheduleEvent(EVENT_UTHER_3, 2s); break; case EVENT_UTHER_3: me->SummonCreature(NPC_QUEL_DELAR, QuelDelarSummonPos); _events.ScheduleEvent(EVENT_UTHER_4, 2s); break; case EVENT_UTHER_4: Talk(SAY_UTHER_QUEL_DELAR_2); _events.ScheduleEvent(EVENT_UTHER_5, 8s); break; case EVENT_UTHER_5: me->GetMotionMaster()->MovePoint(1, UtherQuelDelarMovement[0]); break; case EVENT_UTHER_6: me->SetWalk(true); me->GetMotionMaster()->MovePoint(0, UtherQuelDelarMovement[1]); _events.ScheduleEvent(EVENT_UTHER_7, 5s); break; case EVENT_UTHER_7: Talk(SAY_UTHER_QUEL_DELAR_3); _events.ScheduleEvent(EVENT_UTHER_8, 12s); break; case EVENT_UTHER_8: Talk(SAY_UTHER_QUEL_DELAR_4); _events.ScheduleEvent(EVENT_UTHER_9, 7s); break; case EVENT_UTHER_9: Talk(SAY_UTHER_QUEL_DELAR_5); _events.ScheduleEvent(EVENT_UTHER_10, 10s); break; case EVENT_UTHER_10: Talk(SAY_UTHER_QUEL_DELAR_6); _events.ScheduleEvent(EVENT_UTHER_11, 5s); break; case EVENT_UTHER_11: DoCast(me, SPELL_ESSENCE_OF_CAPTURED_1, true); me->DespawnOrUnsummon(3s); _instance->SetData(DATA_QUEL_DELAR_EVENT, DONE); break; case EVENT_UTHER_FACING: if (Creature* bunny = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FROSTMOURNE_ALTAR_BUNNY))) me->SetFacingToObject(bunny); _events.ScheduleEvent(EVENT_UTHER_KNEEL, 1s); break; case EVENT_UTHER_KNEEL: me->HandleEmoteCommand(EMOTE_STATE_KNEEL); break; default: break; } } } private: EventMap _events; InstanceScript* _instance; }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_uther_quel_delarAI>(creature); } }; class npc_quel_delar_sword : public CreatureScript { public: npc_quel_delar_sword() : CreatureScript("npc_quel_delar_sword") { } struct npc_quel_delar_swordAI : public ScriptedAI { npc_quel_delar_swordAI(Creature* creature) : ScriptedAI(creature) { _instance = me->GetInstanceScript(); me->SetDisplayFromModel(1); _intro = true; } void Reset() override { _events.Reset(); me->SetSpeedRate(MOVE_FLIGHT, 4.5f); DoCast(SPELL_WHIRLWIND_VISUAL); if (_intro) _events.ScheduleEvent(EVENT_QUEL_DELAR_INIT, 0s); else me->SetImmuneToAll(false); } void JustEngagedWith(Unit* /*victim*/) override { _events.ScheduleEvent(EVENT_QUEL_DELAR_HEROIC_STRIKE, 4s); _events.ScheduleEvent(EVENT_QUEL_DELAR_BLADESTORM, 6s); _events.ScheduleEvent(EVENT_QUEL_DELAR_WHIRLWIND, 6s); } void JustDied(Unit* /*killer*/) override { if (Creature* uther = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_UTHER_QUEL_DELAR))) uther->AI()->DoAction(ACTION_UTHER_OUTRO); } void MovementInform(uint32 type, uint32 pointId) override { if (type != EFFECT_MOTION_TYPE) return; switch (pointId) { case POINT_TAKE_OFF: _events.ScheduleEvent(EVENT_QUEL_DELAR_FLIGHT, 0s); break; default: break; } } void UpdateAI(uint32 diff) override { _events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (!UpdateVictim()) { while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_QUEL_DELAR_INIT: if (Creature* bunny = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_FROSTMOURNE_ALTAR_BUNNY))) bunny->AI()->Talk(SAY_FROSTMOURNE_BUNNY); _intro = false; _events.ScheduleEvent(EVENT_QUEL_DELAR_FLIGHT_INIT, 2500ms); break; case EVENT_QUEL_DELAR_FLIGHT_INIT: me->GetMotionMaster()->MoveTakeoff(POINT_TAKE_OFF, QuelDelarMovement[0]); break; case EVENT_QUEL_DELAR_FLIGHT: { me->GetMotionMaster()->MoveCirclePath(QuelDelarCenterPos.GetPositionX(), QuelDelarCenterPos.GetPositionY(), 718.046f, 18.0f, true, 16); _events.ScheduleEvent(EVENT_QUEL_DELAR_LAND, 15s); break; } case EVENT_QUEL_DELAR_LAND: me->StopMoving(); me->GetMotionMaster()->Clear(); me->GetMotionMaster()->MoveLand(0, QuelDelarMovement[1]); _events.ScheduleEvent(EVENT_QUEL_DELAR_FIGHT, 6s); break; case EVENT_QUEL_DELAR_FIGHT: Talk(SAY_QUEL_DELAR_SWORD); me->GetMotionMaster()->MovePoint(0, QuelDelarMovement[2]); me->SetImmuneToAll(false); break; default: break; } } } else { while (uint32 eventId = _events.ExecuteEvent()) { switch (eventId) { case EVENT_QUEL_DELAR_BLADESTORM: DoCast(me, SPELL_BLADESTORM); _events.ScheduleEvent(EVENT_QUEL_DELAR_BLADESTORM, 10s); break; case EVENT_QUEL_DELAR_HEROIC_STRIKE: DoCastVictim(SPELL_HEROIC_STRIKE); _events.ScheduleEvent(EVENT_QUEL_DELAR_HEROIC_STRIKE, 6s); break; case EVENT_QUEL_DELAR_WHIRLWIND: DoCastAOE(SPELL_WHIRLWIND); _events.ScheduleEvent(EVENT_QUEL_DELAR_WHIRLWIND, 1s); break; default: break; } } DoMeleeAttackIfReady(); } } private: EventMap _events; InstanceScript* _instance; bool _intro; }; CreatureAI* GetAI(Creature* creature) const override { return GetHallsOfReflectionAI<npc_quel_delar_swordAI>(creature); } }; // 5660 class at_hor_uther_quel_delar_start : public AreaTriggerScript { public: at_hor_uther_quel_delar_start() : AreaTriggerScript("at_hor_uther_quel_delar_start") { } bool OnTrigger(Player* player, AreaTriggerEntry const* /*areaTrigger*/) override { if (player->IsGameMaster()) return true; InstanceScript* _instance = player->GetInstanceScript(); if (_instance->GetData(DATA_QUEL_DELAR_EVENT) == IN_PROGRESS) if (Creature* uther = ObjectAccessor::GetCreature(*player, _instance->GetGuidData(DATA_UTHER_QUEL_DELAR))) uther->AI()->DoAction(ACTION_UTHER_START_SCREAM); return true; } }; // 72900 - Start Halls of Reflection Quest AE class spell_hor_start_halls_of_reflection_quest_ae : public SpellScriptLoader { public: spell_hor_start_halls_of_reflection_quest_ae() : SpellScriptLoader("spell_hor_start_halls_of_reflection_quest_ae") { } class spell_hor_start_halls_of_reflection_quest_ae_SpellScript : public SpellScript { PrepareSpellScript(spell_hor_start_halls_of_reflection_quest_ae_SpellScript); void StartQuests(SpellEffIndex /*effIndex*/) { if (Player* target = GetHitPlayer()) { // CanTakeQuest and CanAddQuest checks done in spell effect execution if (target->GetTeam() == ALLIANCE) target->CastSpell(target, SPELL_START_HALLS_OF_REFLECTION_QUEST_A, true); else target->CastSpell(target, SPELL_START_HALLS_OF_REFLECTION_QUEST_H, true); } } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_hor_start_halls_of_reflection_quest_ae_SpellScript::StartQuests, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_hor_start_halls_of_reflection_quest_ae_SpellScript(); } }; // 70190 - Evasion class spell_hor_evasion : public SpellScriptLoader { public: spell_hor_evasion() : SpellScriptLoader("spell_hor_evasion") { } class spell_hor_evasion_SpellScript : public SpellScript { PrepareSpellScript(spell_hor_evasion_SpellScript); bool Load() override { return GetCaster()->GetTypeId() == TYPEID_UNIT; } void SetDest(SpellDestination& dest) { WorldObject* target = GetExplTargetWorldObject(); Position pos(*target); Position home = GetCaster()->ToCreature()->GetHomePosition(); // prevent evasion outside the room if (pos.IsInDist2d(&home, 15.0f)) return; float angle = pos.GetAbsoluteAngle(&home); float dist = GetEffectInfo().CalcRadius(GetCaster()); target->MovePosition(pos, dist, angle); dest.Relocate(pos); } void Register() override { OnDestinationTargetSelect += SpellDestinationTargetSelectFn(spell_hor_evasion_SpellScript::SetDest, EFFECT_0, TARGET_DEST_TARGET_RADIUS); } }; SpellScript* GetSpellScript() const override { return new spell_hor_evasion_SpellScript(); } }; // 70017 - Gunship Cannon Fire class spell_hor_gunship_cannon_fire : public SpellScriptLoader { public: spell_hor_gunship_cannon_fire() : SpellScriptLoader("spell_hor_gunship_cannon_fire") { } class spell_hor_gunship_cannon_fire_AuraScript : public AuraScript { PrepareAuraScript(spell_hor_gunship_cannon_fire_AuraScript); void HandlePeriodic(AuraEffect const* /*aurEff*/) { if (!urand(0, 2)) { if (GetTarget()->GetEntry() == NPC_GUNSHIP_CANNON_HORDE) GetTarget()->CastSpell(nullptr, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_HORDE, true); else GetTarget()->CastSpell(nullptr, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_ALLIANCE, true); } } void Register() override { OnEffectPeriodic += AuraEffectPeriodicFn(spell_hor_gunship_cannon_fire_AuraScript::HandlePeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } }; AuraScript* GetAuraScript() const override { return new spell_hor_gunship_cannon_fire_AuraScript(); } }; // 70698 - Quel'Delar's Will class spell_hor_quel_delars_will : public SpellScript { PrepareSpellScript(spell_hor_quel_delars_will); bool Validate(SpellInfo const* spellInfo) override { return !spellInfo->GetEffects().empty() && ValidateSpellInfo({ spellInfo->GetEffect(EFFECT_0).TriggerSpell }); } void HandleReagent(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); // dummy spell consumes reagent, don't ignore it GetHitUnit()->CastSpell(GetCaster(), GetEffectInfo().TriggerSpell, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_hor_quel_delars_will::HandleReagent, EFFECT_0, SPELL_EFFECT_FORCE_CAST); } }; void AddSC_halls_of_reflection() { new at_hor_intro_start(); new at_hor_waves_restarter(); new at_hor_impenetrable_door(); new at_hor_shadow_throne(); new at_hor_uther_quel_delar_start(); new npc_jaina_or_sylvanas_intro_hor(); new npc_jaina_or_sylvanas_escape_hor(); new npc_the_lich_king_escape_hor(); new npc_ghostly_priest(); new npc_phantom_mage(); new npc_phantom_hallucination(); new npc_shadowy_mercenary(); new npc_spectral_footman(); new npc_tortured_rifleman(); new npc_frostsworn_general(); new npc_spiritual_reflection(); new npc_raging_ghoul(); new npc_risen_witch_doctor(); new npc_lumbering_abomination(); new npc_uther_quel_delar(); new npc_quel_delar_sword(); new spell_hor_start_halls_of_reflection_quest_ae(); new spell_hor_evasion(); new spell_hor_gunship_cannon_fire(); RegisterSpellScript(spell_hor_quel_delars_will); }
Shauren/TrinityCore
src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp
C++
gpl-2.0
118,457
#include "tcpal_os.h" #include "tcpal_debug.h" #include "tcbd_feature.h" #include "tcbd_api_common.h" #include "tcbd_drv_io.h" static TcbdIo_t TcbdIo; TcbdIo_t *TcbdGetIoStruct(void) { return &TcbdIo; } I32S TcbdIoOpen(TcbdDevice_t *_device) { I32S ret = 0; if(TcbdIo.Open == NULL) return -TCERR_IO_NOT_INITIALIZED; TcpalCreateSemaphore(&TcbdIo.sem, "TcbdIoSemaphore", 0); ret = TcbdIo.Open(); if(ret < 0) return ret; return ret; } I32S TcbdIoClose(TcbdDevice_t *_device) { I32S ret = 0; if(TcbdIo.Close == NULL) return -TCERR_IO_NOT_INITIALIZED; TcpalDeleteSemaphore(&TcbdIo.sem); ret = TcbdIo.Close(); TcpalMemorySet(_device, 0, sizeof(TcbdDevice_t)); return ret; } I32S TcbdRegRead(TcbdDevice_t *_device, I08U _addr, I08U *_data) { I32S ret; if(TcbdIo.RegRead == NULL) return -TCERR_IO_NOT_INITIALIZED; if(_device == NULL || _data == NULL) return TCERR_INVALID_ARG; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ret = TcbdIo.RegRead(_addr, _data); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdRegWrite(TcbdDevice_t *_device, I08U _addr, I08U _data) { I32S ret; if(TcbdIo.RegWrite == NULL) return -TCERR_IO_NOT_INITIALIZED; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ret = TcbdIo.RegWrite(_addr, _data); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdRegReadExCon(TcbdDevice_t *_device, I08U _addr, I08U *_data, I32S _size) { I32S ret; if(TcbdIo.RegReadExCon == NULL) return -TCERR_IO_NOT_INITIALIZED; if(_device == NULL || _data == NULL) return TCERR_INVALID_ARG; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ret = TcbdIo.RegReadExCon(_addr, _data, _size); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdRegWriteExCon(TcbdDevice_t *_device, I08U _addr, I08U *_data, I32S _size) { I32S ret; if(TcbdIo.RegWriteExCon == NULL) return -TCERR_IO_NOT_INITIALIZED; if(_device == NULL || _data == NULL || _size <= 0) return TCERR_INVALID_ARG; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ret = TcbdIo.RegWriteExCon(_addr, _data, _size); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdRegReadExFix(TcbdDevice_t *_device, I08U _addr, I08U *_data, I32S _size) { I32S ret; if(TcbdIo.RegReadExFix == NULL) return -TCERR_IO_NOT_INITIALIZED; if(_device == NULL || _data == NULL || _size <= 0) return TCERR_INVALID_ARG; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ret = TcbdIo.RegReadExFix(_addr, _data, _size); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdRegWriteExFix(TcbdDevice_t *_device, I08U _addr, I08U *_data, I32S _size) { I32S ret; if(TcbdIo.RegWriteExFix == NULL) return -TCERR_IO_NOT_INITIALIZED; if(_device == NULL || _data == NULL || _size <= 0) return TCERR_INVALID_ARG; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ret = TcbdIo.RegWriteExFix(_addr, _data, _size); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdMemWrite(TcbdDevice_t *_device, I32U _addr, I08U *_data, I32U _size) { I32S ret = 0; I32U addr = SWAP32(_addr); I16U size = SWAP16((I16U)(_size>>2)); I08U ctrlData; if(_size <= 0 || _data == NULL || _device == NULL) return -TCERR_INVALID_ARG; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ctrlData = TCBD_CMDDMA_DMAEN | TCBD_CMDDMA_WRITEMODE | TCBD_CMDDMA_CRC32EN; ret |= TcbdIo.RegWrite(TCBD_CMDDMA_CTRL, ctrlData); ret |= TcbdIo.RegWriteExCon(TCBD_CMDDMA_SADDR, (I08U*)&addr, sizeof(I32U)); ret |= TcbdIo.RegWriteExCon(TCBD_CMDDMA_SIZE, (I08U*)&size, sizeof(I16U)); ctrlData = TCBD_CMDDMA_START_AUTOCLR | TCBD_CMDDMA_INIT_AUTOCLR | TCBD_CMDDMA_CRC32INIT_AUTOCLR | TCBD_CMDDMA_CRC32INIT_AUTOCLR; ret |= TcbdIo.RegWrite(TCBD_CMDDMA_STARTCTRL, ctrlData); ret |= TcbdIo.RegWriteExFix(TCBD_CMDDMA_DATA_WIND, _data, _size); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdMemRead(TcbdDevice_t *_device, I32U _addr, I08U *_data, I32U _size) { I32S ret = 0; I32U addr = SWAP32(_addr); I16U size = SWAP16((I16U)(_size>>2)); I08U ctrlData; if(_size <= 0 || _data == NULL || _device == NULL) return -TCERR_INVALID_ARG; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ctrlData = TCBD_CMDDMA_DMAEN | TCBD_CMDDMA_READMODE; ret |= TcbdIo.RegWrite(TCBD_CMDDMA_CTRL, ctrlData); ret |= TcbdIo.RegWriteExCon(TCBD_CMDDMA_SADDR, (I08U*)&addr, sizeof(I32U)); ret |= TcbdIo.RegWriteExCon(TCBD_CMDDMA_SIZE, (I08U*)&size, sizeof(I16U)); ctrlData = TCBD_CMDDMA_START_AUTOCLR | TCBD_CMDDMA_INIT_AUTOCLR | TCBD_CMDDMA_CRC32INIT_AUTOCLR; ret |= TcbdIo.RegWrite(TCBD_CMDDMA_STARTCTRL, ctrlData); ret |= TcbdIo.RegReadExFix(TCBD_CMDDMA_DATA_WIND, _data, _size); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdRfRegWrite(TcbdDevice_t *_device, I08U _addr, I32U _data) { I32S ret = 0; I32U data = SWAP32(_data); if(_device == NULL) return TCERR_INVALID_ARG; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ret |= TcbdIo.RegWrite(TCBD_RF_CFG0, TCBD_RF_MANAGE_ENABLE|TCBD_RF_WRITE); ret |= TcbdIo.RegWrite(TCBD_RF_CFG2, _addr); ret |= TcbdIo.RegWriteExCon(TCBD_RF_CFG3, (I08U*)&data, sizeof(I32U)); ret |= TcbdIo.RegWrite(TCBD_RF_CFG1, TCBD_RF_ACTION); ret |= TcbdIo.RegWrite(TCBD_RF_CFG0, TCBD_RF_MANAGE_DISABLE); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdRfRegRead(TcbdDevice_t *_device, I32U _addr, I32U *_data) { I32S ret = 0; I32U data = 0; if(_device == NULL) return TCERR_INVALID_ARG; TcpalSemaphoreLock(&TcbdIo.sem); TcbdIo.chipAddr = _device->chipAddr; ret |= TcbdIo.RegWrite(TCBD_RF_CFG0, TCBD_RF_MANAGE_ENABLE|TCBD_RF_READ); ret |= TcbdIo.RegWrite(TCBD_RF_CFG2, _addr); ret |= TcbdIo.RegWrite(TCBD_RF_CFG1, TCBD_RF_ACTION); ret |= TcbdIo.RegReadExCon(TCBD_RF_CFG3, (I08U*)&data, sizeof(I32U)); ret |= TcbdIo.RegWrite(TCBD_RF_CFG0, TCBD_RF_MANAGE_DISABLE); *_data = SWAP32(data); TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdSendMail(TcbdDevice_t *_device, TcbdMail_t *_mail) { I32S ret = 0, count; I08U mailData[32]; I08U regData = 0; TcpalTime_t timeTick, elapsed; TcpalSemaphoreLock(&TcbdIo.sem); ret = TcbdIo.RegWrite(TCBD_MAIL_CTRL, TCBD_MAIL_INIT); *((I32U*)mailData) = (MB_HOSTMAIL<<24) | (_mail->count<<20) | (_mail->flag<<19) | (MB_ERR_OK<<16) | _mail->cmd; count = MIN(_mail->count, MAX_MAIL_COUNT); if(count > 0) TcpalMemoryCopy(mailData + sizeof(I32U), _mail->data, count*sizeof(I32U)); ret |= TcbdIo.RegWriteExFix(TCBD_MAIL_FIFO_WIND, mailData, sizeof(I32U) + count*sizeof(I32U)); ret |= TcbdIo.RegWrite(TCBD_MAIL_CTRL, TCBD_MAIL_HOSTMAILPOST); if(ret < 0) return ret; timeTick = TcpalGetCurrentTimeMs(); do { elapsed = TcpalGetTimeIntervalMs(timeTick); if(elapsed > (TcpalTime_t)MAX_TIME_TO_WAIT_MAIL) { ret = -TCERR_WAIT_MAIL_TIMEOUT; goto exitTcbdSendMail; } ret = TcbdIo.RegWrite(TCBD_MAIL_FIFO_W, 0x5E); /* latch mail status to register */ ret |= TcbdIo.RegRead(TCBD_MAIL_FIFO_W, &regData); /* read ratched status from register */ if(ret < 0) break; } while( !(regData & 0x1) ); /* check fifo status */ TcbdDebug(DEBUG_DRV_IO, "cmd:0x%X, count:%d, elapsed time:%Lu\n", _mail->cmd, count, elapsed); exitTcbdSendMail: TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; } I32S TcbdRecvMail(TcbdDevice_t *_device, TcbdMail_t *_mail) { I32S ret = 0; I32S mailHdr; I08U mailData[32] = {0, }; I08U regData = 0; I08U bytesToRead; TcpalTime_t timeTick, elapsed; TcpalSemaphoreLock(&TcbdIo.sem); timeTick = TcpalGetCurrentTimeMs(); do { ret = TcbdIo.RegWrite(TCBD_MAIL_FIFO_R, 0x5E); /* latch mail status to register */ ret |= TcbdIo.RegRead(TCBD_MAIL_FIFO_R, &regData); /* read ratched status from register */ elapsed = TcpalGetTimeIntervalMs(timeTick); if(elapsed > (TcpalTime_t)MAX_TIME_TO_WAIT_MAIL) ret = -TCERR_WAIT_MAIL_TIMEOUT; if(ret < 0) goto exitTcbdRecvMail; } while((regData & 0xFC) < 3); /* check fifo status */ bytesToRead = (regData>>2) & 0x3F; TcbdDebug(DEBUG_DRV_IO, "cmd:0x%X, bytesToRead:%d, elapsed time:%Lu\n", _mail->cmd, bytesToRead, elapsed); ret = TcbdIo.RegReadExFix(TCBD_MAIL_FIFO_WIND, mailData, bytesToRead); if(bytesToRead == 4) //only warm boot cmd { TcpalMemoryCopy(_mail->data, mailData, bytesToRead); goto exitTcbdRecvMail; } mailHdr = *((I32U*)mailData); if( (mailHdr>>24) != MB_SLAVEMAIL) { TcbdDebug(DEBUG_ERROR, "Error : cmd=0x%X bytesToRead=%d\n", _mail->cmd, bytesToRead); TcbdDebug(DEBUG_ERROR, " [0x%02X][0x%02X][0x%02X][0x%02X][0x%02X][0x%02X][0x%02X][0x%02X]\n", mailData[0], mailData[1], mailData[2], mailData[3], mailData[4], mailData[5], mailData[6], mailData[7]); ret = -TCERR_BROKEN_MAIL_HEADER; goto exitTcbdRecvMail; } _mail->cmd = mailHdr & 0xFFFF; _mail->status = (mailHdr>>16) & 0x7; if(_mail->status) { TcbdDebug(DEBUG_ERROR, "Mail Error : status=0x%X, cmd=0x%X\n", _mail->status, _mail->cmd); ret = -TCERR_UNKNOWN_MAIL_STATUS; goto exitTcbdRecvMail; } _mail->count = (bytesToRead>>2) - 1; TcpalMemoryCopy(_mail->data, mailData + 4, bytesToRead-4); exitTcbdRecvMail: TcpalSemaphoreUnLock(&TcbdIo.sem); return ret; }
Kernel-Saram/LG-SU760-Kernel
drivers/broadcast/tcc3170/src/tcbd_drv_io.c
C
gpl-2.0
10,474
<?php /** * @version $Id: link.php 4478 2012-02-10 01:50:39Z johanjanssens $ * @category Nooku * @package Nooku_Components * @subpackage Default * @copyright Copyright (C) 2007 - 2012 Johan Janssens. All rights reserved. * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Script Filter .* * @author Johan Janssens <johan@nooku.org> * @category Nooku * @package Nooku_Components * @subpackage Default */ class ComDefaultTemplateFilterLink extends KTemplateFilterLink { /** * Render script information * * @param string The script information * @param array Associative array of attributes * @return string */ protected function _renderScript($link, $attribs = array()) { if(KRequest::type() == 'AJAX') { return parent::_renderLink($script, $attribs); } $relType = 'rel'; $relValue = $attribs['rel']; unset($attribs['rel']); JFactory::getDocument() ->addHeadLink($link, $relValue, $relType, $attribs); } }
lflayton/centralc
components/com_default/templates/filters/link.php
PHP
gpl-2.0
1,158
#ifdef CONFIG_SCHED_QHMP #include "qhmp_sched.h" #else #include <linux/sched.h> #include <linux/sched/sysctl.h> #include <linux/sched/rt.h> #include <linux/sched/deadline.h> #include <linux/mutex.h> #include <linux/spinlock.h> #include <linux/stop_machine.h> #include <linux/tick.h> #include <linux/slab.h> #include "cpupri.h" #include "cpudeadline.h" #include "cpuacct.h" struct rq; struct cpuidle_state; /* task_struct::on_rq states: */ #define TASK_ON_RQ_QUEUED 1 #define TASK_ON_RQ_MIGRATING 2 extern __read_mostly int scheduler_running; extern unsigned long calc_load_update; extern atomic_long_t calc_load_tasks; struct freq_max_load_entry { /* The maximum load which has accounted governor's headroom. */ u64 hdemand; }; struct freq_max_load { struct rcu_head rcu; int length; struct freq_max_load_entry freqs[0]; }; extern DEFINE_PER_CPU(struct freq_max_load *, freq_max_load); extern long calc_load_fold_active(struct rq *this_rq); extern void update_cpu_load_active(struct rq *this_rq); /* * Helpers for converting nanosecond timing to jiffy resolution */ #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ)) /* * Increase resolution of nice-level calculations for 64-bit architectures. * The extra resolution improves shares distribution and load balancing of * low-weight task groups (eg. nice +19 on an autogroup), deeper taskgroup * hierarchies, especially on larger systems. This is not a user-visible change * and does not change the user-interface for setting shares/weights. * * We increase resolution only if we have enough bits to allow this increased * resolution (i.e. BITS_PER_LONG > 32). The costs for increasing resolution * when BITS_PER_LONG <= 32 are pretty high and the returns do not justify the * increased costs. */ #if 0 /* BITS_PER_LONG > 32 -- currently broken: it increases power usage under light load */ # define SCHED_LOAD_RESOLUTION 10 # define scale_load(w) ((w) << SCHED_LOAD_RESOLUTION) # define scale_load_down(w) ((w) >> SCHED_LOAD_RESOLUTION) #else # define SCHED_LOAD_RESOLUTION 0 # define scale_load(w) (w) # define scale_load_down(w) (w) #endif #define SCHED_LOAD_SHIFT (10 + SCHED_LOAD_RESOLUTION) #define SCHED_LOAD_SCALE (1L << SCHED_LOAD_SHIFT) #define NICE_0_LOAD SCHED_LOAD_SCALE #define NICE_0_SHIFT SCHED_LOAD_SHIFT /* * Single value that decides SCHED_DEADLINE internal math precision. * 10 -> just above 1us * 9 -> just above 0.5us */ #define DL_SCALE (10) /* * These are the 'tuning knobs' of the scheduler: */ /* * single value that denotes runtime == period, ie unlimited time. */ #define RUNTIME_INF ((u64)~0ULL) static inline int fair_policy(int policy) { return policy == SCHED_NORMAL || policy == SCHED_BATCH; } static inline int rt_policy(int policy) { return policy == SCHED_FIFO || policy == SCHED_RR; } static inline int dl_policy(int policy) { return policy == SCHED_DEADLINE; } static inline int task_has_rt_policy(struct task_struct *p) { return rt_policy(p->policy); } static inline int task_has_dl_policy(struct task_struct *p) { return dl_policy(p->policy); } static inline bool dl_time_before(u64 a, u64 b) { return (s64)(a - b) < 0; } /* * Tells if entity @a should preempt entity @b. */ static inline bool dl_entity_preempt(struct sched_dl_entity *a, struct sched_dl_entity *b) { return dl_time_before(a->deadline, b->deadline); } /* * This is the priority-queue data structure of the RT scheduling class: */ struct rt_prio_array { DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */ struct list_head queue[MAX_RT_PRIO]; }; struct rt_bandwidth { /* nests inside the rq lock: */ raw_spinlock_t rt_runtime_lock; ktime_t rt_period; u64 rt_runtime; struct hrtimer rt_period_timer; }; void __dl_clear_params(struct task_struct *p); /* * To keep the bandwidth of -deadline tasks and groups under control * we need some place where: * - store the maximum -deadline bandwidth of the system (the group); * - cache the fraction of that bandwidth that is currently allocated. * * This is all done in the data structure below. It is similar to the * one used for RT-throttling (rt_bandwidth), with the main difference * that, since here we are only interested in admission control, we * do not decrease any runtime while the group "executes", neither we * need a timer to replenish it. * * With respect to SMP, the bandwidth is given on a per-CPU basis, * meaning that: * - dl_bw (< 100%) is the bandwidth of the system (group) on each CPU; * - dl_total_bw array contains, in the i-eth element, the currently * allocated bandwidth on the i-eth CPU. * Moreover, groups consume bandwidth on each CPU, while tasks only * consume bandwidth on the CPU they're running on. * Finally, dl_total_bw_cpu is used to cache the index of dl_total_bw * that will be shown the next time the proc or cgroup controls will * be red. It on its turn can be changed by writing on its own * control. */ struct dl_bandwidth { raw_spinlock_t dl_runtime_lock; u64 dl_runtime; u64 dl_period; }; static inline int dl_bandwidth_enabled(void) { return sysctl_sched_rt_runtime >= 0; } extern struct dl_bw *dl_bw_of(int i); struct dl_bw { raw_spinlock_t lock; u64 bw, total_bw; }; extern struct mutex sched_domains_mutex; #ifdef CONFIG_CGROUP_SCHED #include <linux/cgroup.h> struct cfs_rq; struct rt_rq; extern struct list_head task_groups; struct cfs_bandwidth { #ifdef CONFIG_CFS_BANDWIDTH raw_spinlock_t lock; ktime_t period; u64 quota, runtime; s64 hierarchical_quota; u64 runtime_expires; int idle, timer_active; struct hrtimer period_timer, slack_timer; struct list_head throttled_cfs_rq; /* statistics */ int nr_periods, nr_throttled; u64 throttled_time; #endif }; /* task group related information */ struct task_group { struct cgroup_subsys_state css; bool notify_on_migrate; #ifdef CONFIG_SCHED_HMP bool upmigrate_discouraged; #endif #ifdef CONFIG_FAIR_GROUP_SCHED /* schedulable entities of this group on each cpu */ struct sched_entity **se; /* runqueue "owned" by this group on each cpu */ struct cfs_rq **cfs_rq; unsigned long shares; #ifdef CONFIG_SMP atomic_long_t load_avg; atomic_t runnable_avg; #endif #endif #ifdef CONFIG_RT_GROUP_SCHED struct sched_rt_entity **rt_se; struct rt_rq **rt_rq; struct rt_bandwidth rt_bandwidth; #endif struct rcu_head rcu; struct list_head list; struct task_group *parent; struct list_head siblings; struct list_head children; #ifdef CONFIG_SCHED_AUTOGROUP struct autogroup *autogroup; #endif struct cfs_bandwidth cfs_bandwidth; }; #ifdef CONFIG_FAIR_GROUP_SCHED #define ROOT_TASK_GROUP_LOAD NICE_0_LOAD /* * A weight of 0 or 1 can cause arithmetics problems. * A weight of a cfs_rq is the sum of weights of which entities * are queued on this cfs_rq, so a weight of a entity should not be * too large, so as the shares value of a task group. * (The default weight is 1024 - so there's no practical * limitation from this.) */ #define MIN_SHARES (1UL << 1) #define MAX_SHARES (1UL << 18) #endif typedef int (*tg_visitor)(struct task_group *, void *); extern int walk_tg_tree_from(struct task_group *from, tg_visitor down, tg_visitor up, void *data); /* * Iterate the full tree, calling @down when first entering a node and @up when * leaving it for the final time. * * Caller must hold rcu_lock or sufficient equivalent. */ static inline int walk_tg_tree(tg_visitor down, tg_visitor up, void *data) { return walk_tg_tree_from(&root_task_group, down, up, data); } extern int tg_nop(struct task_group *tg, void *data); extern void free_fair_sched_group(struct task_group *tg); extern int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent); extern void unregister_fair_sched_group(struct task_group *tg, int cpu); extern void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, struct sched_entity *se, int cpu, struct sched_entity *parent); extern void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b); extern int sched_group_set_shares(struct task_group *tg, unsigned long shares); extern void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b); extern void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b, bool force); extern void unthrottle_cfs_rq(struct cfs_rq *cfs_rq); extern void free_rt_sched_group(struct task_group *tg); extern int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent); extern void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq, struct sched_rt_entity *rt_se, int cpu, struct sched_rt_entity *parent); extern struct task_group *sched_create_group(struct task_group *parent); extern void sched_online_group(struct task_group *tg, struct task_group *parent); extern void sched_destroy_group(struct task_group *tg); extern void sched_offline_group(struct task_group *tg); extern void sched_move_task(struct task_struct *tsk); #ifdef CONFIG_FAIR_GROUP_SCHED extern int sched_group_set_shares(struct task_group *tg, unsigned long shares); #endif #else /* CONFIG_CGROUP_SCHED */ struct cfs_bandwidth { }; #endif /* CONFIG_CGROUP_SCHED */ #ifdef CONFIG_SCHED_HMP struct hmp_sched_stats { int nr_big_tasks; u64 cumulative_runnable_avg; #ifdef CONFIG_SCHED_FREQ_INPUT u64 pred_demands_sum; #endif }; struct sched_cluster { struct list_head list; struct cpumask cpus; int id; int max_power_cost; int min_power_cost; int max_possible_capacity; int capacity; int efficiency; /* Differentiate cpus with different IPC capability */ int load_scale_factor; /* * max_freq = user or thermal defined maximum * max_possible_freq = maximum supported by hardware */ unsigned int cur_freq, max_freq, min_freq, max_possible_freq; bool freq_init_done; int dstate, dstate_wakeup_latency, dstate_wakeup_energy; unsigned int static_cluster_pwr_cost; }; extern unsigned long all_cluster_ids[]; static inline int cluster_first_cpu(struct sched_cluster *cluster) { return cpumask_first(&cluster->cpus); } struct related_thread_group { int id; raw_spinlock_t lock; struct list_head tasks; struct list_head list; struct sched_cluster *preferred_cluster; struct rcu_head rcu; u64 last_update; }; extern struct list_head cluster_head; extern int num_clusters; extern struct sched_cluster *sched_cluster[NR_CPUS]; extern int group_will_fit(struct sched_cluster *cluster, struct related_thread_group *grp, u64 demand); #define for_each_sched_cluster(cluster) \ list_for_each_entry_rcu(cluster, &cluster_head, list) #endif /* CFS-related fields in a runqueue */ struct cfs_rq { struct load_weight load; unsigned int nr_running, h_nr_running; u64 exec_clock; u64 min_vruntime; #ifndef CONFIG_64BIT u64 min_vruntime_copy; #endif struct rb_root tasks_timeline; struct rb_node *rb_leftmost; /* * 'curr' points to currently running entity on this cfs_rq. * It is set to NULL otherwise (i.e when none are currently running). */ struct sched_entity *curr, *next, *last, *skip; #ifdef CONFIG_SCHED_DEBUG unsigned int nr_spread_over; #endif #ifdef CONFIG_SMP /* * CFS Load tracking * Under CFS, load is tracked on a per-entity basis and aggregated up. * This allows for the description of both thread and group usage (in * the FAIR_GROUP_SCHED case). */ unsigned long runnable_load_avg, blocked_load_avg; atomic64_t decay_counter; u64 last_decay; atomic_long_t removed_load; #ifdef CONFIG_FAIR_GROUP_SCHED /* Required to track per-cpu representation of a task_group */ u32 tg_runnable_contrib; unsigned long tg_load_contrib; /* * h_load = weight * f(tg) * * Where f(tg) is the recursive weight fraction assigned to * this group. */ unsigned long h_load; u64 last_h_load_update; struct sched_entity *h_load_next; #endif /* CONFIG_FAIR_GROUP_SCHED */ #endif /* CONFIG_SMP */ #ifdef CONFIG_FAIR_GROUP_SCHED struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */ /* * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in * a hierarchy). Non-leaf lrqs hold other higher schedulable entities * (like users, containers etc.) * * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This * list is used during load balance. */ int on_list; struct list_head leaf_cfs_rq_list; struct task_group *tg; /* group that "owns" this runqueue */ #ifdef CONFIG_CFS_BANDWIDTH #ifdef CONFIG_SCHED_HMP struct hmp_sched_stats hmp_stats; #endif int runtime_enabled; u64 runtime_expires; s64 runtime_remaining; u64 throttled_clock, throttled_clock_task; u64 throttled_clock_task_time; int throttled, throttle_count; struct list_head throttled_list; #endif /* CONFIG_CFS_BANDWIDTH */ #endif /* CONFIG_FAIR_GROUP_SCHED */ }; static inline int rt_bandwidth_enabled(void) { return sysctl_sched_rt_runtime >= 0; } /* Real-Time classes' related field in a runqueue: */ struct rt_rq { struct rt_prio_array active; unsigned int rt_nr_running; #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED struct { int curr; /* highest queued rt task prio */ #ifdef CONFIG_SMP int next; /* next highest */ #endif } highest_prio; #endif #ifdef CONFIG_SMP unsigned long rt_nr_migratory; unsigned long rt_nr_total; int overloaded; struct plist_head pushable_tasks; #endif int rt_queued; int rt_throttled; u64 rt_time; u64 rt_runtime; /* Nests inside the rq lock: */ raw_spinlock_t rt_runtime_lock; #ifdef CONFIG_RT_GROUP_SCHED unsigned long rt_nr_boosted; struct rq *rq; struct task_group *tg; #endif }; /* Deadline class' related fields in a runqueue */ struct dl_rq { /* runqueue is an rbtree, ordered by deadline */ struct rb_root rb_root; struct rb_node *rb_leftmost; unsigned long dl_nr_running; #ifdef CONFIG_SMP /* * Deadline values of the currently executing and the * earliest ready task on this rq. Caching these facilitates * the decision wether or not a ready but not running task * should migrate somewhere else. */ struct { u64 curr; u64 next; } earliest_dl; unsigned long dl_nr_migratory; int overloaded; /* * Tasks on this rq that can be pushed away. They are kept in * an rb-tree, ordered by tasks' deadlines, with caching * of the leftmost (earliest deadline) element. */ struct rb_root pushable_dl_tasks_root; struct rb_node *pushable_dl_tasks_leftmost; #else struct dl_bw dl_bw; #endif }; #ifdef CONFIG_SMP /* * We add the notion of a root-domain which will be used to define per-domain * variables. Each exclusive cpuset essentially defines an island domain by * fully partitioning the member cpus from any other cpuset. Whenever a new * exclusive cpuset is created, we also create and attach a new root-domain * object. * */ struct root_domain { atomic_t refcount; atomic_t rto_count; struct rcu_head rcu; cpumask_var_t span; cpumask_var_t online; /* Indicate more than one runnable task for any CPU */ bool overload; /* * The bit corresponding to a CPU gets set here if such CPU has more * than one runnable -deadline task (as it is below for RT tasks). */ cpumask_var_t dlo_mask; atomic_t dlo_count; struct dl_bw dl_bw; struct cpudl cpudl; /* * The "RT overload" flag: it gets set if a CPU has more than * one runnable RT task. */ cpumask_var_t rto_mask; struct cpupri cpupri; }; extern struct root_domain def_root_domain; #endif /* CONFIG_SMP */ /* * This is the main, per-CPU runqueue data structure. * * Locking rule: those places that want to lock multiple runqueues * (such as the load balancing or the thread migration code), lock * acquire operations must be ordered by ascending &runqueue. */ struct rq { /* runqueue lock: */ raw_spinlock_t lock; /* * nr_running and cpu_load should be in the same cacheline because * remote CPUs use both these fields when doing load calculation. */ unsigned int nr_running; #ifdef CONFIG_NUMA_BALANCING unsigned int nr_numa_running; unsigned int nr_preferred_running; #endif #define CPU_LOAD_IDX_MAX 5 unsigned long cpu_load[CPU_LOAD_IDX_MAX]; unsigned long last_load_update_tick; #ifdef CONFIG_NO_HZ_COMMON u64 nohz_stamp; unsigned long nohz_flags; #endif #ifdef CONFIG_NO_HZ_FULL unsigned long last_sched_tick; #endif int skip_clock_update; /* capture load from *all* tasks on this cpu: */ struct load_weight load; unsigned long nr_load_updates; u64 nr_switches; struct cfs_rq cfs; struct rt_rq rt; struct dl_rq dl; #ifdef CONFIG_FAIR_GROUP_SCHED /* list of leaf cfs_rq on this cpu: */ struct list_head leaf_cfs_rq_list; struct sched_avg avg; #endif /* CONFIG_FAIR_GROUP_SCHED */ /* * This is part of a global counter where only the total sum * over all CPUs matters. A task can increase this counter on * one CPU and if it got migrated afterwards it may decrease * it on another CPU. Always updated under the runqueue lock: */ unsigned long nr_uninterruptible; struct task_struct *curr, *idle, *stop; unsigned long next_balance; struct mm_struct *prev_mm; u64 clock; u64 clock_task; atomic_t nr_iowait; #ifdef CONFIG_SMP struct root_domain *rd; struct sched_domain *sd; unsigned long cpu_capacity; unsigned char idle_balance; /* For active balancing */ int post_schedule; int active_balance; int push_cpu; struct task_struct *push_task; struct cpu_stop_work active_balance_work; /* cpu of this runqueue: */ int cpu; int online; struct list_head cfs_tasks; u64 rt_avg; u64 age_stamp; u64 idle_stamp; u64 avg_idle; int cstate, wakeup_latency, wakeup_energy; /* This is used to determine avg_idle's max value */ u64 max_idle_balance_cost; #endif #ifdef CONFIG_SCHED_HMP struct sched_cluster *cluster; struct cpumask freq_domain_cpumask; struct hmp_sched_stats hmp_stats; u64 window_start; unsigned long hmp_flags; u64 cur_irqload; u64 avg_irqload; u64 irqload_ts; unsigned int static_cpu_pwr_cost; struct task_struct *ed_task; #ifdef CONFIG_SCHED_FREQ_INPUT unsigned int old_busy_time; int notifier_sent; u64 old_estimated_time; #endif #endif #ifdef CONFIG_SCHED_FREQ_INPUT u64 curr_runnable_sum; u64 prev_runnable_sum; u64 nt_curr_runnable_sum; u64 nt_prev_runnable_sum; #endif #ifdef CONFIG_IRQ_TIME_ACCOUNTING u64 prev_irq_time; #endif #ifdef CONFIG_PARAVIRT u64 prev_steal_time; #endif #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING u64 prev_steal_time_rq; #endif /* calc_load related fields */ unsigned long calc_load_update; long calc_load_active; #ifdef CONFIG_SCHED_HRTICK #ifdef CONFIG_SMP int hrtick_csd_pending; struct call_single_data hrtick_csd; #endif struct hrtimer hrtick_timer; #endif #ifdef CONFIG_SCHEDSTATS /* latency stats */ struct sched_info rq_sched_info; unsigned long long rq_cpu_time; /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */ /* sys_sched_yield() stats */ unsigned int yld_count; /* schedule() stats */ unsigned int sched_count; unsigned int sched_goidle; /* try_to_wake_up() stats */ unsigned int ttwu_count; unsigned int ttwu_local; #endif #ifdef CONFIG_SMP struct llist_head wake_list; #endif #ifdef CONFIG_CPU_IDLE /* Must be inspected within a rcu lock section */ struct cpuidle_state *idle_state; #endif }; static inline int cpu_of(struct rq *rq) { #ifdef CONFIG_SMP return rq->cpu; #else return 0; #endif } DECLARE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu))) #define this_rq() this_cpu_ptr(&runqueues) #define task_rq(p) cpu_rq(task_cpu(p)) #define cpu_curr(cpu) (cpu_rq(cpu)->curr) #define raw_rq() raw_cpu_ptr(&runqueues) static inline u64 rq_clock(struct rq *rq) { return rq->clock; } static inline u64 rq_clock_task(struct rq *rq) { return rq->clock_task; } #ifdef CONFIG_NUMA_BALANCING extern void sched_setnuma(struct task_struct *p, int node); extern int migrate_task_to(struct task_struct *p, int cpu); extern int migrate_swap(struct task_struct *, struct task_struct *); #endif /* CONFIG_NUMA_BALANCING */ #ifdef CONFIG_SMP extern void sched_ttwu_pending(void); #define rcu_dereference_check_sched_domain(p) \ rcu_dereference_check((p), \ lockdep_is_held(&sched_domains_mutex)) /* * The domain tree (rq->sd) is protected by RCU's quiescent state transition. * See detach_destroy_domains: synchronize_sched for details. * * The domain tree of any CPU may only be accessed from within * preempt-disabled sections. */ #define for_each_domain(cpu, __sd) \ for (__sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd); \ __sd; __sd = __sd->parent) #define for_each_lower_domain(sd) for (; sd; sd = sd->child) /** * highest_flag_domain - Return highest sched_domain containing flag. * @cpu: The cpu whose highest level of sched domain is to * be returned. * @flag: The flag to check for the highest sched_domain * for the given cpu. * * Returns the highest sched_domain of a cpu which contains the given flag. */ static inline struct sched_domain *highest_flag_domain(int cpu, int flag) { struct sched_domain *sd, *hsd = NULL; for_each_domain(cpu, sd) { if (!(sd->flags & flag)) break; hsd = sd; } return hsd; } static inline struct sched_domain *lowest_flag_domain(int cpu, int flag) { struct sched_domain *sd; for_each_domain(cpu, sd) { if (sd->flags & flag) break; } return sd; } DECLARE_PER_CPU(struct sched_domain *, sd_llc); DECLARE_PER_CPU(int, sd_llc_size); DECLARE_PER_CPU(int, sd_llc_id); DECLARE_PER_CPU(struct sched_domain *, sd_numa); DECLARE_PER_CPU(struct sched_domain *, sd_busy); DECLARE_PER_CPU(struct sched_domain *, sd_asym); struct sched_group_capacity { atomic_t ref; /* * CPU capacity of this group, SCHED_LOAD_SCALE being max capacity * for a single CPU. */ unsigned int capacity, capacity_orig; unsigned long next_update; int imbalance; /* XXX unrelated to capacity but shared group state */ /* * Number of busy cpus in this group. */ atomic_t nr_busy_cpus; unsigned long cpumask[0]; /* iteration mask */ }; struct sched_group { struct sched_group *next; /* Must be a circular list */ atomic_t ref; unsigned int group_weight; struct sched_group_capacity *sgc; /* * The CPUs this group covers. * * NOTE: this field is variable length. (Allocated dynamically * by attaching extra space to the end of the structure, * depending on how many CPUs the kernel has booted up with) */ unsigned long cpumask[0]; }; static inline struct cpumask *sched_group_cpus(struct sched_group *sg) { return to_cpumask(sg->cpumask); } /* * cpumask masking which cpus in the group are allowed to iterate up the domain * tree. */ static inline struct cpumask *sched_group_mask(struct sched_group *sg) { return to_cpumask(sg->sgc->cpumask); } /** * group_first_cpu - Returns the first cpu in the cpumask of a sched_group. * @group: The group whose first cpu is to be returned. */ static inline unsigned int group_first_cpu(struct sched_group *group) { return cpumask_first(sched_group_cpus(group)); } extern int group_balance_cpu(struct sched_group *sg); #else static inline void sched_ttwu_pending(void) { } #endif /* CONFIG_SMP */ #include "stats.h" #include "auto_group.h" extern void init_new_task_load(struct task_struct *p); #ifdef CONFIG_SCHED_HMP #define WINDOW_STATS_RECENT 0 #define WINDOW_STATS_MAX 1 #define WINDOW_STATS_MAX_RECENT_AVG 2 #define WINDOW_STATS_AVG 3 #define WINDOW_STATS_INVALID_POLICY 4 extern struct mutex policy_mutex; extern unsigned int sched_ravg_window; extern unsigned int sched_use_pelt; extern unsigned int sched_disable_window_stats; extern unsigned int sched_enable_hmp; extern unsigned int max_possible_freq; extern unsigned int min_max_freq; extern unsigned int pct_task_load(struct task_struct *p); extern unsigned int max_possible_efficiency; extern unsigned int min_possible_efficiency; extern unsigned int max_capacity; extern unsigned int min_capacity; extern unsigned int max_load_scale_factor; extern unsigned int max_possible_capacity; extern unsigned int min_max_possible_capacity; extern unsigned int sched_upmigrate; extern unsigned int sched_downmigrate; extern unsigned int sched_init_task_load_pelt; extern unsigned int sched_init_task_load_windows; extern unsigned int sched_heavy_task; extern unsigned int up_down_migrate_scale_factor; extern unsigned int sysctl_sched_restrict_cluster_spill; extern unsigned int sched_pred_alert_load; #ifdef CONFIG_SCHED_FREQ_INPUT #define MAJOR_TASK_PCT 85 extern unsigned int sched_major_task_runtime; #endif extern void reset_cpu_hmp_stats(int cpu, int reset_cra); extern unsigned int max_task_load(void); extern void sched_account_irqtime(int cpu, struct task_struct *curr, u64 delta, u64 wallclock); unsigned int cpu_temp(int cpu); int sched_set_group_id(struct task_struct *p, unsigned int group_id); extern unsigned int nr_eligible_big_tasks(int cpu); extern void update_up_down_migrate(void); static inline struct sched_cluster *cpu_cluster(int cpu) { return cpu_rq(cpu)->cluster; } static inline int cpu_capacity(int cpu) { return cpu_rq(cpu)->cluster->capacity; } static inline int cpu_max_possible_capacity(int cpu) { return cpu_rq(cpu)->cluster->max_possible_capacity; } static inline int cpu_load_scale_factor(int cpu) { return cpu_rq(cpu)->cluster->load_scale_factor; } static inline int cpu_efficiency(int cpu) { return cpu_rq(cpu)->cluster->efficiency; } static inline unsigned int cpu_cur_freq(int cpu) { return cpu_rq(cpu)->cluster->cur_freq; } static inline unsigned int cpu_min_freq(int cpu) { return cpu_rq(cpu)->cluster->min_freq; } static inline unsigned int cpu_max_freq(int cpu) { return cpu_rq(cpu)->cluster->max_freq; } static inline unsigned int cpu_max_possible_freq(int cpu) { return cpu_rq(cpu)->cluster->max_possible_freq; } static inline int same_cluster(int src_cpu, int dst_cpu) { return cpu_rq(src_cpu)->cluster == cpu_rq(dst_cpu)->cluster; } static inline int cpu_max_power_cost(int cpu) { return cpu_rq(cpu)->cluster->max_power_cost; } static inline bool hmp_capable(void) { return max_possible_capacity != min_max_possible_capacity; } /* * 'load' is in reference to "best cpu" at its best frequency. * Scale that in reference to a given cpu, accounting for how bad it is * in reference to "best cpu". */ static inline u64 scale_load_to_cpu(u64 task_load, int cpu) { u64 lsf = cpu_load_scale_factor(cpu); if (lsf != 1024) { task_load *= lsf; task_load /= 1024; } return task_load; } static inline unsigned int task_load(struct task_struct *p) { if (sched_use_pelt) return p->se.avg.runnable_avg_sum_scaled; return p->ravg.demand; } #ifdef CONFIG_SCHED_FREQ_INPUT #define set_pred_demands_sum(stats, x) ((stats)->pred_demands_sum = (x)) #define verify_pred_demands_sum(stat) BUG_ON((s64)(stat)->pred_demands_sum < 0) #else #define set_pred_demands_sum(stats, x) #define verify_pred_demands_sum(stat) #endif static inline void inc_cumulative_runnable_avg(struct hmp_sched_stats *stats, struct task_struct *p) { u32 task_load; if (!sched_enable_hmp || sched_disable_window_stats) return; task_load = sched_use_pelt ? p->se.avg.runnable_avg_sum_scaled : (sched_disable_window_stats ? 0 : p->ravg.demand); stats->cumulative_runnable_avg += task_load; set_pred_demands_sum(stats, stats->pred_demands_sum + p->ravg.pred_demand); } static inline void dec_cumulative_runnable_avg(struct hmp_sched_stats *stats, struct task_struct *p) { u32 task_load; if (!sched_enable_hmp || sched_disable_window_stats) return; task_load = sched_use_pelt ? p->se.avg.runnable_avg_sum_scaled : (sched_disable_window_stats ? 0 : p->ravg.demand); stats->cumulative_runnable_avg -= task_load; BUG_ON((s64)stats->cumulative_runnable_avg < 0); set_pred_demands_sum(stats, stats->pred_demands_sum - p->ravg.pred_demand); verify_pred_demands_sum(stats); } static inline void fixup_cumulative_runnable_avg(struct hmp_sched_stats *stats, struct task_struct *p, s64 task_load_delta, s64 pred_demand_delta) { if (!sched_enable_hmp || sched_disable_window_stats) return; stats->cumulative_runnable_avg += task_load_delta; BUG_ON((s64)stats->cumulative_runnable_avg < 0); set_pred_demands_sum(stats, stats->pred_demands_sum + pred_demand_delta); verify_pred_demands_sum(stats); } #define pct_to_real(tunable) \ (div64_u64((u64)tunable * (u64)max_task_load(), 100)) #define real_to_pct(tunable) \ (div64_u64((u64)tunable * (u64)100, (u64)max_task_load())) #define SCHED_HIGH_IRQ_TIMEOUT 3 static inline u64 sched_irqload(int cpu) { struct rq *rq = cpu_rq(cpu); s64 delta; delta = get_jiffies_64() - rq->irqload_ts; /* * Current context can be preempted by irq and rq->irqload_ts can be * updated by irq context so that delta can be negative. * But this is okay and we can safely return as this means there * was recent irq occurrence. */ if (delta < SCHED_HIGH_IRQ_TIMEOUT) return rq->avg_irqload; else return 0; } static inline int sched_cpu_high_irqload(int cpu) { return sched_irqload(cpu) >= sysctl_sched_cpu_high_irqload; } static inline struct related_thread_group *task_related_thread_group(struct task_struct *p) { return rcu_dereference(p->grp); } #else /* CONFIG_SCHED_HMP */ struct hmp_sched_stats; struct related_thread_group; static inline u64 scale_load_to_cpu(u64 load, int cpu) { return load; } static inline unsigned int nr_eligible_big_tasks(int cpu) { return 0; } static inline int pct_task_load(struct task_struct *p) { return 0; } static inline int cpu_capacity(int cpu) { return SCHED_LOAD_SCALE; } static inline int same_cluster(int src_cpu, int dst_cpu) { return 1; } static inline void inc_cumulative_runnable_avg(struct hmp_sched_stats *stats, struct task_struct *p) { } static inline void dec_cumulative_runnable_avg(struct hmp_sched_stats *stats, struct task_struct *p) { } static inline void sched_account_irqtime(int cpu, struct task_struct *curr, u64 delta, u64 wallclock) { } static inline int sched_cpu_high_irqload(int cpu) { return 0; } static inline void set_preferred_cluster(struct related_thread_group *grp) { } static inline struct related_thread_group *task_related_thread_group(struct task_struct *p) { return NULL; } static inline u32 task_load(struct task_struct *p) { return 0; } static inline int update_preferred_cluster(struct related_thread_group *grp, struct task_struct *p, u32 old_load) { return 0; } #endif /* CONFIG_SCHED_HMP */ /* * Returns the rq capacity of any rq in a group. This does not play * well with groups where rq capacity can change independently. */ #define group_rq_capacity(group) cpu_capacity(group_first_cpu(group)) #ifdef CONFIG_SCHED_FREQ_INPUT #define PRED_DEMAND_DELTA ((s64)new_pred_demand - p->ravg.pred_demand) extern void check_for_freq_change(struct rq *rq, bool check_cra); /* Is frequency of two cpus synchronized with each other? */ static inline int same_freq_domain(int src_cpu, int dst_cpu) { struct rq *rq = cpu_rq(src_cpu); if (src_cpu == dst_cpu) return 1; return cpumask_test_cpu(dst_cpu, &rq->freq_domain_cpumask); } #else /* CONFIG_SCHED_FREQ_INPUT */ #define sched_migration_fixup 0 #define PRED_DEMAND_DELTA (0) static inline void check_for_freq_change(struct rq *rq, bool check_cra) { } static inline int same_freq_domain(int src_cpu, int dst_cpu) { return 1; } #endif /* CONFIG_SCHED_FREQ_INPUT */ #ifdef CONFIG_SCHED_HMP #define BOOST_KICK 0 #define CPU_RESERVED 1 static inline int is_reserved(int cpu) { struct rq *rq = cpu_rq(cpu); return test_bit(CPU_RESERVED, &rq->hmp_flags); } static inline int mark_reserved(int cpu) { struct rq *rq = cpu_rq(cpu); /* Name boost_flags as hmp_flags? */ return test_and_set_bit(CPU_RESERVED, &rq->hmp_flags); } static inline void clear_reserved(int cpu) { struct rq *rq = cpu_rq(cpu); clear_bit(CPU_RESERVED, &rq->hmp_flags); } static inline u64 cpu_cravg_sync(int cpu, int sync) { struct rq *rq = cpu_rq(cpu); u64 load; load = rq->hmp_stats.cumulative_runnable_avg; /* * If load is being checked in a sync wakeup environment, * we may want to discount the load of the currently running * task. */ if (sync && cpu == smp_processor_id()) { if (load > rq->curr->ravg.demand) load -= rq->curr->ravg.demand; else load = 0; } return load; } extern void check_for_migration(struct rq *rq, struct task_struct *p); extern void pre_big_task_count_change(const struct cpumask *cpus); extern void post_big_task_count_change(const struct cpumask *cpus); extern void set_hmp_defaults(void); extern int power_delta_exceeded(unsigned int cpu_cost, unsigned int base_cost); extern unsigned int power_cost(int cpu, u64 demand); extern void reset_all_window_stats(u64 window_start, unsigned int window_size); extern void boost_kick(int cpu); extern int sched_boost(void); #else /* CONFIG_SCHED_HMP */ #define sched_enable_hmp 0 #define sched_freq_legacy_mode 1 static inline void check_for_migration(struct rq *rq, struct task_struct *p) { } static inline void pre_big_task_count_change(void) { } static inline void post_big_task_count_change(void) { } static inline void set_hmp_defaults(void) { } static inline void clear_reserved(int cpu) { } #define power_cost(...) 0 #define trace_sched_cpu_load(...) #define trace_sched_cpu_load_lb(...) #define trace_sched_cpu_load_cgroup(...) #define trace_sched_cpu_load_wakeup(...) #endif /* CONFIG_SCHED_HMP */ #ifdef CONFIG_CGROUP_SCHED /* * Return the group to which this tasks belongs. * * We cannot use task_css() and friends because the cgroup subsystem * changes that value before the cgroup_subsys::attach() method is called, * therefore we cannot pin it and might observe the wrong value. * * The same is true for autogroup's p->signal->autogroup->tg, the autogroup * core changes this before calling sched_move_task(). * * Instead we use a 'copy' which is updated from sched_move_task() while * holding both task_struct::pi_lock and rq::lock. */ static inline struct task_group *task_group(struct task_struct *p) { return p->sched_task_group; } static inline bool task_notify_on_migrate(struct task_struct *p) { return task_group(p)->notify_on_migrate; } /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */ static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { #if defined(CONFIG_FAIR_GROUP_SCHED) || defined(CONFIG_RT_GROUP_SCHED) struct task_group *tg = task_group(p); #endif #ifdef CONFIG_FAIR_GROUP_SCHED p->se.cfs_rq = tg->cfs_rq[cpu]; p->se.parent = tg->se[cpu]; #endif #ifdef CONFIG_RT_GROUP_SCHED p->rt.rt_rq = tg->rt_rq[cpu]; p->rt.parent = tg->rt_se[cpu]; #endif } #else /* CONFIG_CGROUP_SCHED */ static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { } static inline struct task_group *task_group(struct task_struct *p) { return NULL; } static inline bool task_notify_on_migrate(struct task_struct *p) { return false; } #endif /* CONFIG_CGROUP_SCHED */ static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu) { set_task_rq(p, cpu); #ifdef CONFIG_SMP /* * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be * successfuly executed on another CPU. We must ensure that updates of * per-task data have been completed by this moment. */ smp_wmb(); task_thread_info(p)->cpu = cpu; p->wake_cpu = cpu; #endif } /* * Tunables that become constants when CONFIG_SCHED_DEBUG is off: */ #ifdef CONFIG_SCHED_DEBUG # include <linux/static_key.h> # define const_debug __read_mostly #else # define const_debug const #endif extern const_debug unsigned int sysctl_sched_features; #define SCHED_FEAT(name, enabled) \ __SCHED_FEAT_##name , enum { #include "features.h" __SCHED_FEAT_NR, }; #undef SCHED_FEAT #if defined(CONFIG_SCHED_DEBUG) && defined(HAVE_JUMP_LABEL) #define SCHED_FEAT(name, enabled) \ static __always_inline bool static_branch_##name(struct static_key *key) \ { \ return static_key_##enabled(key); \ } #include "features.h" #undef SCHED_FEAT extern struct static_key sched_feat_keys[__SCHED_FEAT_NR]; #define sched_feat(x) (static_branch_##x(&sched_feat_keys[__SCHED_FEAT_##x])) #else /* !(SCHED_DEBUG && HAVE_JUMP_LABEL) */ #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x)) #endif /* SCHED_DEBUG && HAVE_JUMP_LABEL */ #ifdef CONFIG_NUMA_BALANCING #define sched_feat_numa(x) sched_feat(x) #ifdef CONFIG_SCHED_DEBUG #define numabalancing_enabled sched_feat_numa(NUMA) #else extern bool numabalancing_enabled; #endif /* CONFIG_SCHED_DEBUG */ #else #define sched_feat_numa(x) (0) #define numabalancing_enabled (0) #endif /* CONFIG_NUMA_BALANCING */ static inline u64 global_rt_period(void) { return (u64)sysctl_sched_rt_period * NSEC_PER_USEC; } static inline u64 global_rt_runtime(void) { if (sysctl_sched_rt_runtime < 0) return RUNTIME_INF; return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC; } static inline int task_current(struct rq *rq, struct task_struct *p) { return rq->curr == p; } static inline int task_running(struct rq *rq, struct task_struct *p) { #ifdef CONFIG_SMP return p->on_cpu; #else return task_current(rq, p); #endif } static inline int task_on_rq_queued(struct task_struct *p) { return p->on_rq == TASK_ON_RQ_QUEUED; } static inline int task_on_rq_migrating(struct task_struct *p) { return p->on_rq == TASK_ON_RQ_MIGRATING; } #ifndef prepare_arch_switch # define prepare_arch_switch(next) do { } while (0) #endif #ifndef finish_arch_switch # define finish_arch_switch(prev) do { } while (0) #endif #ifndef finish_arch_post_lock_switch # define finish_arch_post_lock_switch() do { } while (0) #endif static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next) { #ifdef CONFIG_SMP /* * We can optimise this out completely for !SMP, because the * SMP rebalancing from interrupt is the only thing that cares * here. */ next->on_cpu = 1; #endif } static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev) { #ifdef CONFIG_SMP /* * After ->on_cpu is cleared, the task can be moved to a different CPU. * We must ensure this doesn't happen until the switch is completely * finished. * * Pairs with the control dependency and rmb in try_to_wake_up(). */ smp_store_release(&prev->on_cpu, 0); #endif #ifdef CONFIG_DEBUG_SPINLOCK /* this is a valid case when another task releases the spinlock */ rq->lock.owner = current; #endif /* * If we are tracking spinlock dependencies then we have to * fix up the runqueue lock - which gets 'carried over' from * prev into current: */ spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_); raw_spin_unlock_irq(&rq->lock); } /* * wake flags */ #define WF_SYNC 0x01 /* waker goes to sleep after wakeup */ #define WF_FORK 0x02 /* child wakeup after fork */ #define WF_MIGRATED 0x4 /* internal use, task got migrated */ #define WF_NO_NOTIFIER 0x08 /* do not notify governor */ /* * To aid in avoiding the subversion of "niceness" due to uneven distribution * of tasks with abnormal "nice" values across CPUs the contribution that * each task makes to its run queue's load is weighted according to its * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a * scaled version of the new time slice allocation that they receive on time * slice expiry etc. */ #define WEIGHT_IDLEPRIO 3 #define WMULT_IDLEPRIO 1431655765 /* * Nice levels are multiplicative, with a gentle 10% change for every * nice level changed. I.e. when a CPU-bound task goes from nice 0 to * nice 1, it will get ~10% less CPU time than another CPU-bound task * that remained on nice 0. * * The "10% effect" is relative and cumulative: from _any_ nice level, * if you go up 1 level, it's -10% CPU usage, if you go down 1 level * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25. * If a task goes up by ~10% and another task goes down by ~10% then * the relative distance between them is ~25%.) */ static const int prio_to_weight[40] = { /* -20 */ 88761, 71755, 56483, 46273, 36291, /* -15 */ 29154, 23254, 18705, 14949, 11916, /* -10 */ 9548, 7620, 6100, 4904, 3906, /* -5 */ 3121, 2501, 1991, 1586, 1277, /* 0 */ 1024, 820, 655, 526, 423, /* 5 */ 335, 272, 215, 172, 137, /* 10 */ 110, 87, 70, 56, 45, /* 15 */ 36, 29, 23, 18, 15, }; /* * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated. * * In cases where the weight does not change often, we can use the * precalculated inverse to speed up arithmetics by turning divisions * into multiplications: */ static const u32 prio_to_wmult[40] = { /* -20 */ 48388, 59856, 76040, 92818, 118348, /* -15 */ 147320, 184698, 229616, 287308, 360437, /* -10 */ 449829, 563644, 704093, 875809, 1099582, /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326, /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587, /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126, /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717, /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153, }; #define ENQUEUE_WAKEUP 1 #define ENQUEUE_HEAD 2 #ifdef CONFIG_SMP #define ENQUEUE_WAKING 4 /* sched_class::task_waking was called */ #else #define ENQUEUE_WAKING 0 #endif #define ENQUEUE_REPLENISH 8 #define ENQUEUE_MIGRATING 16 #define DEQUEUE_SLEEP 1 #define DEQUEUE_MIGRATING 2 #define RETRY_TASK ((void *)-1UL) struct sched_class { const struct sched_class *next; void (*enqueue_task) (struct rq *rq, struct task_struct *p, int flags); void (*dequeue_task) (struct rq *rq, struct task_struct *p, int flags); void (*yield_task) (struct rq *rq); bool (*yield_to_task) (struct rq *rq, struct task_struct *p, bool preempt); void (*check_preempt_curr) (struct rq *rq, struct task_struct *p, int flags); /* * It is the responsibility of the pick_next_task() method that will * return the next task to call put_prev_task() on the @prev task or * something equivalent. * * May return RETRY_TASK when it finds a higher prio class has runnable * tasks. */ struct task_struct * (*pick_next_task) (struct rq *rq, struct task_struct *prev); void (*put_prev_task) (struct rq *rq, struct task_struct *p); #ifdef CONFIG_SMP int (*select_task_rq)(struct task_struct *p, int task_cpu, int sd_flag, int flags); void (*migrate_task_rq)(struct task_struct *p, int next_cpu); void (*post_schedule) (struct rq *this_rq); void (*task_waking) (struct task_struct *task); void (*task_woken) (struct rq *this_rq, struct task_struct *task); void (*set_cpus_allowed)(struct task_struct *p, const struct cpumask *newmask); void (*rq_online)(struct rq *rq); void (*rq_offline)(struct rq *rq); #endif void (*set_curr_task) (struct rq *rq); void (*task_tick) (struct rq *rq, struct task_struct *p, int queued); void (*task_fork) (struct task_struct *p); void (*task_dead) (struct task_struct *p); void (*switched_from) (struct rq *this_rq, struct task_struct *task); void (*switched_to) (struct rq *this_rq, struct task_struct *task); void (*prio_changed) (struct rq *this_rq, struct task_struct *task, int oldprio); unsigned int (*get_rr_interval) (struct rq *rq, struct task_struct *task); void (*update_curr) (struct rq *rq); #ifdef CONFIG_FAIR_GROUP_SCHED void (*task_move_group) (struct task_struct *p, int on_rq); #endif #ifdef CONFIG_SCHED_HMP void (*inc_hmp_sched_stats)(struct rq *rq, struct task_struct *p); void (*dec_hmp_sched_stats)(struct rq *rq, struct task_struct *p); void (*fixup_hmp_sched_stats)(struct rq *rq, struct task_struct *p, u32 new_task_load, u32 new_pred_demand); #endif }; static inline void put_prev_task(struct rq *rq, struct task_struct *prev) { prev->sched_class->put_prev_task(rq, prev); } #define sched_class_highest (&stop_sched_class) #define for_each_class(class) \ for (class = sched_class_highest; class; class = class->next) extern const struct sched_class stop_sched_class; extern const struct sched_class dl_sched_class; extern const struct sched_class rt_sched_class; extern const struct sched_class fair_sched_class; extern const struct sched_class idle_sched_class; #ifdef CONFIG_SMP extern void update_group_capacity(struct sched_domain *sd, int cpu); extern void trigger_load_balance(struct rq *rq); extern void idle_enter_fair(struct rq *this_rq); extern void idle_exit_fair(struct rq *this_rq); #else static inline void idle_enter_fair(struct rq *rq) { } static inline void idle_exit_fair(struct rq *rq) { } #endif #ifdef CONFIG_CPU_IDLE static inline void idle_set_state(struct rq *rq, struct cpuidle_state *idle_state) { rq->idle_state = idle_state; } static inline struct cpuidle_state *idle_get_state(struct rq *rq) { WARN_ON(!rcu_read_lock_held()); return rq->idle_state; } #else static inline void idle_set_state(struct rq *rq, struct cpuidle_state *idle_state) { } static inline struct cpuidle_state *idle_get_state(struct rq *rq) { return NULL; } #endif #ifdef CONFIG_SYSRQ_SCHED_DEBUG extern void sysrq_sched_debug_show(void); #endif extern void sched_init_granularity(void); extern void update_max_interval(void); extern void init_sched_dl_class(void); extern void init_sched_rt_class(void); extern void init_sched_fair_class(void); extern void init_sched_dl_class(void); extern void resched_curr(struct rq *rq); extern void resched_cpu(int cpu); extern struct rt_bandwidth def_rt_bandwidth; extern void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime); extern struct dl_bandwidth def_dl_bandwidth; extern void init_dl_bandwidth(struct dl_bandwidth *dl_b, u64 period, u64 runtime); extern void init_dl_task_timer(struct sched_dl_entity *dl_se); unsigned long to_ratio(u64 period, u64 runtime); extern void update_idle_cpu_load(struct rq *this_rq); extern void init_task_runnable_average(struct task_struct *p); static inline void add_nr_running(struct rq *rq, unsigned count) { unsigned prev_nr = rq->nr_running; sched_update_nr_prod(cpu_of(rq), count, true); rq->nr_running = prev_nr + count; if (prev_nr < 2 && rq->nr_running >= 2) { #ifdef CONFIG_SMP if (!rq->rd->overload) rq->rd->overload = true; #endif #ifdef CONFIG_NO_HZ_FULL if (tick_nohz_full_cpu(rq->cpu)) { /* * Tick is needed if more than one task runs on a CPU. * Send the target an IPI to kick it out of nohz mode. * * We assume that IPI implies full memory barrier and the * new value of rq->nr_running is visible on reception * from the target. */ tick_nohz_full_kick_cpu(rq->cpu); } #endif } } static inline void sub_nr_running(struct rq *rq, unsigned count) { sched_update_nr_prod(cpu_of(rq), count, false); rq->nr_running -= count; } static inline void rq_last_tick_reset(struct rq *rq) { #ifdef CONFIG_NO_HZ_FULL rq->last_sched_tick = jiffies; #endif } extern void update_rq_clock(struct rq *rq); extern void activate_task(struct rq *rq, struct task_struct *p, int flags); extern void deactivate_task(struct rq *rq, struct task_struct *p, int flags); extern void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags); extern const_debug unsigned int sysctl_sched_time_avg; extern const_debug unsigned int sysctl_sched_nr_migrate; extern const_debug unsigned int sysctl_sched_migration_cost; static inline u64 sched_avg_period(void) { return (u64)sysctl_sched_time_avg * NSEC_PER_MSEC / 2; } #ifdef CONFIG_SCHED_HRTICK /* * Use hrtick when: * - enabled by features * - hrtimer is actually high res */ static inline int hrtick_enabled(struct rq *rq) { if (!sched_feat(HRTICK)) return 0; if (!cpu_active(cpu_of(rq))) return 0; return hrtimer_is_hres_active(&rq->hrtick_timer); } void hrtick_start(struct rq *rq, u64 delay); #else static inline int hrtick_enabled(struct rq *rq) { return 0; } #endif /* CONFIG_SCHED_HRTICK */ #ifdef CONFIG_SMP extern void sched_avg_update(struct rq *rq); static inline void sched_rt_avg_update(struct rq *rq, u64 rt_delta) { rq->rt_avg += rt_delta; sched_avg_update(rq); } #else static inline void sched_rt_avg_update(struct rq *rq, u64 rt_delta) { } static inline void sched_avg_update(struct rq *rq) { } #endif extern void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period); #ifdef CONFIG_SMP #ifdef CONFIG_PREEMPT static inline void double_rq_lock(struct rq *rq1, struct rq *rq2); /* * fair double_lock_balance: Safely acquires both rq->locks in a fair * way at the expense of forcing extra atomic operations in all * invocations. This assures that the double_lock is acquired using the * same underlying policy as the spinlock_t on this architecture, which * reduces latency compared to the unfair variant below. However, it * also adds more overhead and therefore may reduce throughput. */ static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest) __releases(this_rq->lock) __acquires(busiest->lock) __acquires(this_rq->lock) { raw_spin_unlock(&this_rq->lock); double_rq_lock(this_rq, busiest); return 1; } #else /* * Unfair double_lock_balance: Optimizes throughput at the expense of * latency by eliminating extra atomic operations when the locks are * already in proper order on entry. This favors lower cpu-ids and will * grant the double lock to lower cpus over higher ids under contention, * regardless of entry order into the function. */ static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest) __releases(this_rq->lock) __acquires(busiest->lock) __acquires(this_rq->lock) { int ret = 0; if (unlikely(!raw_spin_trylock(&busiest->lock))) { if (busiest < this_rq) { raw_spin_unlock(&this_rq->lock); raw_spin_lock(&busiest->lock); raw_spin_lock_nested(&this_rq->lock, SINGLE_DEPTH_NESTING); ret = 1; } else raw_spin_lock_nested(&busiest->lock, SINGLE_DEPTH_NESTING); } return ret; } #endif /* CONFIG_PREEMPT */ /* * double_lock_balance - lock the busiest runqueue, this_rq is locked already. */ static inline int double_lock_balance(struct rq *this_rq, struct rq *busiest) { if (unlikely(!irqs_disabled())) { /* printk() doesn't work good under rq->lock */ raw_spin_unlock(&this_rq->lock); BUG_ON(1); } return _double_lock_balance(this_rq, busiest); } static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest) __releases(busiest->lock) { raw_spin_unlock(&busiest->lock); lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_); } static inline void double_lock(spinlock_t *l1, spinlock_t *l2) { if (l1 > l2) swap(l1, l2); spin_lock(l1); spin_lock_nested(l2, SINGLE_DEPTH_NESTING); } static inline void double_lock_irq(spinlock_t *l1, spinlock_t *l2) { if (l1 > l2) swap(l1, l2); spin_lock_irq(l1); spin_lock_nested(l2, SINGLE_DEPTH_NESTING); } static inline void double_raw_lock(raw_spinlock_t *l1, raw_spinlock_t *l2) { if (l1 > l2) swap(l1, l2); raw_spin_lock(l1); raw_spin_lock_nested(l2, SINGLE_DEPTH_NESTING); } /* * double_rq_lock - safely lock two runqueues * * Note this does not disable interrupts like task_rq_lock, * you need to do so manually before calling. */ static inline void double_rq_lock(struct rq *rq1, struct rq *rq2) __acquires(rq1->lock) __acquires(rq2->lock) { BUG_ON(!irqs_disabled()); if (rq1 == rq2) { raw_spin_lock(&rq1->lock); __acquire(rq2->lock); /* Fake it out ;) */ } else { if (rq1 < rq2) { raw_spin_lock(&rq1->lock); raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING); } else { raw_spin_lock(&rq2->lock); raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING); } } } /* * double_rq_unlock - safely unlock two runqueues * * Note this does not restore interrupts like task_rq_unlock, * you need to do so manually after calling. */ static inline void double_rq_unlock(struct rq *rq1, struct rq *rq2) __releases(rq1->lock) __releases(rq2->lock) { raw_spin_unlock(&rq1->lock); if (rq1 != rq2) raw_spin_unlock(&rq2->lock); else __release(rq2->lock); } #else /* CONFIG_SMP */ /* * double_rq_lock - safely lock two runqueues * * Note this does not disable interrupts like task_rq_lock, * you need to do so manually before calling. */ static inline void double_rq_lock(struct rq *rq1, struct rq *rq2) __acquires(rq1->lock) __acquires(rq2->lock) { BUG_ON(!irqs_disabled()); BUG_ON(rq1 != rq2); raw_spin_lock(&rq1->lock); __acquire(rq2->lock); /* Fake it out ;) */ } /* * double_rq_unlock - safely unlock two runqueues * * Note this does not restore interrupts like task_rq_unlock, * you need to do so manually after calling. */ static inline void double_rq_unlock(struct rq *rq1, struct rq *rq2) __releases(rq1->lock) __releases(rq2->lock) { BUG_ON(rq1 != rq2); raw_spin_unlock(&rq1->lock); __release(rq2->lock); } #endif extern struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq); extern struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq); extern void print_cfs_stats(struct seq_file *m, int cpu); extern void print_rt_stats(struct seq_file *m, int cpu); extern void init_cfs_rq(struct cfs_rq *cfs_rq); extern void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq); extern void init_dl_rq(struct dl_rq *dl_rq, struct rq *rq); extern void cfs_bandwidth_usage_inc(void); extern void cfs_bandwidth_usage_dec(void); #ifdef CONFIG_NO_HZ_COMMON enum rq_nohz_flag_bits { NOHZ_TICK_STOPPED, NOHZ_BALANCE_KICK, }; #define NOHZ_KICK_ANY 0 #define NOHZ_KICK_RESTRICT 1 #define nohz_flags(cpu) (&cpu_rq(cpu)->nohz_flags) #endif #ifdef CONFIG_IRQ_TIME_ACCOUNTING DECLARE_PER_CPU(u64, cpu_hardirq_time); DECLARE_PER_CPU(u64, cpu_softirq_time); #ifndef CONFIG_64BIT DECLARE_PER_CPU(seqcount_t, irq_time_seq); static inline void irq_time_write_begin(void) { __this_cpu_inc(irq_time_seq.sequence); smp_wmb(); } static inline void irq_time_write_end(void) { smp_wmb(); __this_cpu_inc(irq_time_seq.sequence); } static inline u64 irq_time_read(int cpu) { u64 irq_time; unsigned seq; do { seq = read_seqcount_begin(&per_cpu(irq_time_seq, cpu)); irq_time = per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu); } while (read_seqcount_retry(&per_cpu(irq_time_seq, cpu), seq)); return irq_time; } #else /* CONFIG_64BIT */ static inline void irq_time_write_begin(void) { } static inline void irq_time_write_end(void) { } static inline u64 irq_time_read(int cpu) { return per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu); } #endif /* CONFIG_64BIT */ #endif /* CONFIG_IRQ_TIME_ACCOUNTING */ #endif /* CONFIG_SCHED_QHMP */
msdx321/android_kernel_xiaomi_msm8996
kernel/sched/sched.h
C
gpl-2.0
54,936
/* * Memory merging support. * * This code enables dynamic sharing of identical pages found in different * memory areas, even if they are not shared by fork() * * Copyright (C) 2008-2009 Red Hat, Inc. * Authors: * Izik Eidus * Andrea Arcangeli * Chris Wright * Hugh Dickins * * This work is licensed under the terms of the GNU GPL, version 2. */ #include <linux/errno.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/mman.h> #include <linux/sched.h> #include <linux/rwsem.h> #include <linux/pagemap.h> #include <linux/rmap.h> #include <linux/spinlock.h> #include <linux/jhash.h> #include <linux/delay.h> #include <linux/kthread.h> #include <linux/wait.h> #include <linux/slab.h> #include <linux/rbtree.h> #include <linux/memory.h> #include <linux/mmu_notifier.h> #include <linux/swap.h> #include <linux/ksm.h> #include <linux/hashtable.h> #include <linux/freezer.h> #include <linux/oom.h> #include <linux/numa.h> #include <asm/tlbflush.h> #include "internal.h" #ifdef CONFIG_NUMA #define NUMA(x) (x) #define DO_NUMA(x) do { (x); } while (0) #else #define NUMA(x) (0) #define DO_NUMA(x) do { } while (0) #endif /* * A few notes about the KSM scanning process, * to make it easier to understand the data structures below: * * In order to reduce excessive scanning, KSM sorts the memory pages by their * contents into a data structure that holds pointers to the pages' locations. * * Since the contents of the pages may change at any moment, KSM cannot just * insert the pages into a normal sorted tree and expect it to find anything. * Therefore KSM uses two data structures - the stable and the unstable tree. * * The stable tree holds pointers to all the merged pages (ksm pages), sorted * by their contents. Because each such page is write-protected, searching on * this tree is fully assured to be working (except when pages are unmapped), * and therefore this tree is called the stable tree. * * In addition to the stable tree, KSM uses a second data structure called the * unstable tree: this tree holds pointers to pages which have been found to * be "unchanged for a period of time". The unstable tree sorts these pages * by their contents, but since they are not write-protected, KSM cannot rely * upon the unstable tree to work correctly - the unstable tree is liable to * be corrupted as its contents are modified, and so it is called unstable. * * KSM solves this problem by several techniques: * * 1) The unstable tree is flushed every time KSM completes scanning all * memory areas, and then the tree is rebuilt again from the beginning. * 2) KSM will only insert into the unstable tree, pages whose hash value * has not changed since the previous scan of all memory areas. * 3) The unstable tree is a RedBlack Tree - so its balancing is based on the * colors of the nodes and not on their contents, assuring that even when * the tree gets "corrupted" it won't get out of balance, so scanning time * remains the same (also, searching and inserting nodes in an rbtree uses * the same algorithm, so we have no overhead when we flush and rebuild). * 4) KSM never flushes the stable tree, which means that even if it were to * take 10 attempts to find a page in the unstable tree, once it is found, * it is secured in the stable tree. (When we scan a new page, we first * compare it against the stable tree, and then against the unstable tree.) * * If the merge_across_nodes tunable is unset, then KSM maintains multiple * stable trees and multiple unstable trees: one of each for each NUMA node. */ /** * struct mm_slot - ksm information per mm that is being scanned * @link: link to the mm_slots hash list * @mm_list: link into the mm_slots list, rooted in ksm_mm_head * @rmap_list: head for this mm_slot's singly-linked list of rmap_items * @mm: the mm that this information is valid for */ struct mm_slot { struct hlist_node link; struct list_head mm_list; struct rmap_item *rmap_list; struct mm_struct *mm; }; /** * struct ksm_scan - cursor for scanning * @mm_slot: the current mm_slot we are scanning * @address: the next address inside that to be scanned * @rmap_list: link to the next rmap to be scanned in the rmap_list * @seqnr: count of completed full scans (needed when removing unstable node) * * There is only the one ksm_scan instance of this cursor structure. */ struct ksm_scan { struct mm_slot *mm_slot; unsigned long address; struct rmap_item **rmap_list; unsigned long seqnr; }; /** * struct stable_node - node of the stable rbtree * @node: rb node of this ksm page in the stable tree * @head: (overlaying parent) &migrate_nodes indicates temporarily on that list * @list: linked into migrate_nodes, pending placement in the proper node tree * @hlist: hlist head of rmap_items using this ksm page * @kpfn: page frame number of this ksm page (perhaps temporarily on wrong nid) * @nid: NUMA node id of stable tree in which linked (may not match kpfn) */ struct stable_node { union { struct rb_node node; /* when node of stable tree */ struct { /* when listed for migration */ struct list_head *head; struct list_head list; }; }; struct hlist_head hlist; unsigned long kpfn; #ifdef CONFIG_NUMA int nid; #endif }; /** * struct rmap_item - reverse mapping item for virtual addresses * @rmap_list: next rmap_item in mm_slot's singly-linked rmap_list * @anon_vma: pointer to anon_vma for this mm,address, when in stable tree * @nid: NUMA node id of unstable tree in which linked (may not match page) * @mm: the memory structure this rmap_item is pointing into * @address: the virtual address this rmap_item tracks (+ flags in low bits) * @oldchecksum: previous checksum of the page at that virtual address * @node: rb node of this rmap_item in the unstable tree * @head: pointer to stable_node heading this list in the stable tree * @hlist: link into hlist of rmap_items hanging off that stable_node */ struct rmap_item { struct rmap_item *rmap_list; union { struct anon_vma *anon_vma; /* when stable */ #ifdef CONFIG_NUMA int nid; /* when node of unstable tree */ #endif }; struct mm_struct *mm; unsigned long address; /* + low bits used for flags below */ unsigned int oldchecksum; /* when unstable */ union { struct rb_node node; /* when node of unstable tree */ struct { /* when listed from stable tree */ struct stable_node *head; struct hlist_node hlist; }; }; }; #define SEQNR_MASK 0x0ff /* low bits of unstable tree seqnr */ #define UNSTABLE_FLAG 0x100 /* is a node of the unstable tree */ #define STABLE_FLAG 0x200 /* is listed from the stable tree */ /* The stable and unstable tree heads */ static struct rb_root one_stable_tree[1] = { RB_ROOT }; static struct rb_root one_unstable_tree[1] = { RB_ROOT }; static struct rb_root *root_stable_tree = one_stable_tree; static struct rb_root *root_unstable_tree = one_unstable_tree; /* Recently migrated nodes of stable tree, pending proper placement */ static LIST_HEAD(migrate_nodes); #define MM_SLOTS_HASH_BITS 10 static DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS); static struct mm_slot ksm_mm_head = { .mm_list = LIST_HEAD_INIT(ksm_mm_head.mm_list), }; static struct ksm_scan ksm_scan = { .mm_slot = &ksm_mm_head, }; static struct kmem_cache *rmap_item_cache; static struct kmem_cache *stable_node_cache; static struct kmem_cache *mm_slot_cache; /* The number of nodes in the stable tree */ static unsigned long ksm_pages_shared; /* The number of page slots additionally sharing those nodes */ static unsigned long ksm_pages_sharing; /* The number of nodes in the unstable tree */ static unsigned long ksm_pages_unshared; /* The number of rmap_items in use: to calculate pages_volatile */ static unsigned long ksm_rmap_items; /* Number of pages ksmd should scan in one batch */ static unsigned int ksm_thread_pages_to_scan = 100; /* Milliseconds ksmd should sleep between batches */ static unsigned int ksm_thread_sleep_millisecs = 20; #ifdef CONFIG_NUMA /* Zeroed when merging across nodes is not allowed */ static unsigned int ksm_merge_across_nodes = 1; static int ksm_nr_node_ids = 1; #else #define ksm_merge_across_nodes 1U #define ksm_nr_node_ids 1 #endif #define KSM_RUN_STOP 0 #define KSM_RUN_MERGE 1 #define KSM_RUN_UNMERGE 2 #define KSM_RUN_OFFLINE 4 static unsigned long ksm_run = KSM_RUN_STOP; static void wait_while_offlining(void); static DECLARE_WAIT_QUEUE_HEAD(ksm_thread_wait); static DEFINE_MUTEX(ksm_thread_mutex); static DEFINE_SPINLOCK(ksm_mmlist_lock); #define KSM_KMEM_CACHE(__struct, __flags) kmem_cache_create("ksm_"#__struct,\ sizeof(struct __struct), __alignof__(struct __struct),\ (__flags), NULL) static int __init ksm_slab_init(void) { rmap_item_cache = KSM_KMEM_CACHE(rmap_item, 0); if (!rmap_item_cache) goto out; stable_node_cache = KSM_KMEM_CACHE(stable_node, 0); if (!stable_node_cache) goto out_free1; mm_slot_cache = KSM_KMEM_CACHE(mm_slot, 0); if (!mm_slot_cache) goto out_free2; return 0; out_free2: kmem_cache_destroy(stable_node_cache); out_free1: kmem_cache_destroy(rmap_item_cache); out: return -ENOMEM; } static void __init ksm_slab_free(void) { kmem_cache_destroy(mm_slot_cache); kmem_cache_destroy(stable_node_cache); kmem_cache_destroy(rmap_item_cache); mm_slot_cache = NULL; } static inline struct rmap_item *alloc_rmap_item(void) { struct rmap_item *rmap_item; rmap_item = kmem_cache_zalloc(rmap_item_cache, GFP_KERNEL); if (rmap_item) ksm_rmap_items++; return rmap_item; } static inline void free_rmap_item(struct rmap_item *rmap_item) { ksm_rmap_items--; rmap_item->mm = NULL; /* debug safety */ kmem_cache_free(rmap_item_cache, rmap_item); } static inline struct stable_node *alloc_stable_node(void) { return kmem_cache_alloc(stable_node_cache, GFP_KERNEL); } static inline void free_stable_node(struct stable_node *stable_node) { kmem_cache_free(stable_node_cache, stable_node); } static inline struct mm_slot *alloc_mm_slot(void) { if (!mm_slot_cache) /* initialization failed */ return NULL; return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL); } static inline void free_mm_slot(struct mm_slot *mm_slot) { kmem_cache_free(mm_slot_cache, mm_slot); } static struct mm_slot *get_mm_slot(struct mm_struct *mm) { struct mm_slot *slot; hash_for_each_possible(mm_slots_hash, slot, link, (unsigned long)mm) if (slot->mm == mm) return slot; return NULL; } static void insert_to_mm_slots_hash(struct mm_struct *mm, struct mm_slot *mm_slot) { mm_slot->mm = mm; hash_add(mm_slots_hash, &mm_slot->link, (unsigned long)mm); } /* * ksmd, and unmerge_and_remove_all_rmap_items(), must not touch an mm's * page tables after it has passed through ksm_exit() - which, if necessary, * takes mmap_sem briefly to serialize against them. ksm_exit() does not set * a special flag: they can just back out as soon as mm_users goes to zero. * ksm_test_exit() is used throughout to make this test for exit: in some * places for correctness, in some places just to avoid unnecessary work. */ static inline bool ksm_test_exit(struct mm_struct *mm) { return atomic_read(&mm->mm_users) == 0; } /* * We use break_ksm to break COW on a ksm page: it's a stripped down * * if (get_user_pages(current, mm, addr, 1, 1, 1, &page, NULL) == 1) * put_page(page); * * but taking great care only to touch a ksm page, in a VM_MERGEABLE vma, * in case the application has unmapped and remapped mm,addr meanwhile. * Could a ksm page appear anywhere else? Actually yes, in a VM_PFNMAP * mmap of /dev/mem or /dev/kmem, where we would not want to touch it. */ static int break_ksm(struct vm_area_struct *vma, unsigned long addr) { struct page *page; int ret = 0; do { cond_resched(); page = follow_page(vma, addr, FOLL_GET | FOLL_MIGRATION); if (IS_ERR_OR_NULL(page)) break; if (PageKsm(page)) ret = handle_mm_fault(vma->vm_mm, vma, addr, FAULT_FLAG_WRITE); else ret = VM_FAULT_WRITE; put_page(page); } while (!(ret & (VM_FAULT_WRITE | VM_FAULT_SIGBUS | VM_FAULT_OOM))); /* * We must loop because handle_mm_fault() may back out if there's * any difficulty e.g. if pte accessed bit gets updated concurrently. * * VM_FAULT_WRITE is what we have been hoping for: it indicates that * COW has been broken, even if the vma does not permit VM_WRITE; * but note that a concurrent fault might break PageKsm for us. * * VM_FAULT_SIGBUS could occur if we race with truncation of the * backing file, which also invalidates anonymous pages: that's * okay, that truncation will have unmapped the PageKsm for us. * * VM_FAULT_OOM: at the time of writing (late July 2009), setting * aside mem_cgroup limits, VM_FAULT_OOM would only be set if the * current task has TIF_MEMDIE set, and will be OOM killed on return * to user; and ksmd, having no mm, would never be chosen for that. * * But if the mm is in a limited mem_cgroup, then the fault may fail * with VM_FAULT_OOM even if the current task is not TIF_MEMDIE; and * even ksmd can fail in this way - though it's usually breaking ksm * just to undo a merge it made a moment before, so unlikely to oom. * * That's a pity: we might therefore have more kernel pages allocated * than we're counting as nodes in the stable tree; but ksm_do_scan * will retry to break_cow on each pass, so should recover the page * in due course. The important thing is to not let VM_MERGEABLE * be cleared while any such pages might remain in the area. */ return (ret & VM_FAULT_OOM) ? -ENOMEM : 0; } static struct vm_area_struct *find_mergeable_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma; if (ksm_test_exit(mm)) return NULL; vma = find_vma(mm, addr); if (!vma || vma->vm_start > addr) return NULL; if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma) return NULL; return vma; } static void break_cow(struct rmap_item *rmap_item) { struct mm_struct *mm = rmap_item->mm; unsigned long addr = rmap_item->address; struct vm_area_struct *vma; /* * It is not an accident that whenever we want to break COW * to undo, we also need to drop a reference to the anon_vma. */ put_anon_vma(rmap_item->anon_vma); down_read(&mm->mmap_sem); vma = find_mergeable_vma(mm, addr); if (vma) break_ksm(vma, addr); up_read(&mm->mmap_sem); } static struct page *page_trans_compound_anon(struct page *page) { if (PageTransCompound(page)) { struct page *head = compound_head(page); /* * head may actually be splitted and freed from under * us but it's ok here. */ if (PageAnon(head)) return head; } return NULL; } static struct page *get_mergeable_page(struct rmap_item *rmap_item) { struct mm_struct *mm = rmap_item->mm; unsigned long addr = rmap_item->address; struct vm_area_struct *vma; struct page *page; down_read(&mm->mmap_sem); vma = find_mergeable_vma(mm, addr); if (!vma) goto out; page = follow_page(vma, addr, FOLL_GET); if (IS_ERR_OR_NULL(page)) goto out; if (PageAnon(page) || page_trans_compound_anon(page)) { flush_anon_page(vma, page, addr); flush_dcache_page(page); } else { put_page(page); out: page = NULL; } up_read(&mm->mmap_sem); return page; } /* * This helper is used for getting right index into array of tree roots. * When merge_across_nodes knob is set to 1, there are only two rb-trees for * stable and unstable pages from all nodes with roots in index 0. Otherwise, * every node has its own stable and unstable tree. */ static inline int get_kpfn_nid(unsigned long kpfn) { return ksm_merge_across_nodes ? 0 : NUMA(pfn_to_nid(kpfn)); } static void remove_node_from_stable_tree(struct stable_node *stable_node) { struct rmap_item *rmap_item; hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) { if (rmap_item->hlist.next) ksm_pages_sharing--; else ksm_pages_shared--; put_anon_vma(rmap_item->anon_vma); rmap_item->address &= PAGE_MASK; cond_resched(); } if (stable_node->head == &migrate_nodes) list_del(&stable_node->list); else rb_erase(&stable_node->node, root_stable_tree + NUMA(stable_node->nid)); free_stable_node(stable_node); } /* * get_ksm_page: checks if the page indicated by the stable node * is still its ksm page, despite having held no reference to it. * In which case we can trust the content of the page, and it * returns the gotten page; but if the page has now been zapped, * remove the stale node from the stable tree and return NULL. * But beware, the stable node's page might be being migrated. * * You would expect the stable_node to hold a reference to the ksm page. * But if it increments the page's count, swapping out has to wait for * ksmd to come around again before it can free the page, which may take * seconds or even minutes: much too unresponsive. So instead we use a * "keyhole reference": access to the ksm page from the stable node peeps * out through its keyhole to see if that page still holds the right key, * pointing back to this stable node. This relies on freeing a PageAnon * page to reset its page->mapping to NULL, and relies on no other use of * a page to put something that might look like our key in page->mapping. * is on its way to being freed; but it is an anomaly to bear in mind. */ static struct page *get_ksm_page(struct stable_node *stable_node, bool lock_it) { struct page *page; void *expected_mapping; unsigned long kpfn; expected_mapping = (void *)stable_node + (PAGE_MAPPING_ANON | PAGE_MAPPING_KSM); again: kpfn = ACCESS_ONCE(stable_node->kpfn); page = pfn_to_page(kpfn); /* * page is computed from kpfn, so on most architectures reading * page->mapping is naturally ordered after reading node->kpfn, * but on Alpha we need to be more careful. */ smp_read_barrier_depends(); if (ACCESS_ONCE(page->mapping) != expected_mapping) goto stale; /* * We cannot do anything with the page while its refcount is 0. * Usually 0 means free, or tail of a higher-order page: in which * case this node is no longer referenced, and should be freed; * however, it might mean that the page is under page_freeze_refs(). * The __remove_mapping() case is easy, again the node is now stale; * but if page is swapcache in migrate_page_move_mapping(), it might * still be our page, in which case it's essential to keep the node. */ while (!get_page_unless_zero(page)) { /* * Another check for page->mapping != expected_mapping would * work here too. We have chosen the !PageSwapCache test to * optimize the common case, when the page is or is about to * be freed: PageSwapCache is cleared (under spin_lock_irq) * in the freeze_refs section of __remove_mapping(); but Anon * page->mapping reset to NULL later, in free_pages_prepare(). */ if (!PageSwapCache(page)) goto stale; cpu_relax(); } if (ACCESS_ONCE(page->mapping) != expected_mapping) { put_page(page); goto stale; } if (lock_it) { lock_page(page); if (ACCESS_ONCE(page->mapping) != expected_mapping) { unlock_page(page); put_page(page); goto stale; } } return page; stale: /* * We come here from above when page->mapping or !PageSwapCache * suggests that the node is stale; but it might be under migration. * We need smp_rmb(), matching the smp_wmb() in ksm_migrate_page(), * before checking whether node->kpfn has been changed. */ smp_rmb(); if (ACCESS_ONCE(stable_node->kpfn) != kpfn) goto again; remove_node_from_stable_tree(stable_node); return NULL; } /* * Removing rmap_item from stable or unstable tree. * This function will clean the information from the stable/unstable tree. */ static void remove_rmap_item_from_tree(struct rmap_item *rmap_item) { if (rmap_item->address & STABLE_FLAG) { struct stable_node *stable_node; struct page *page; stable_node = rmap_item->head; page = get_ksm_page(stable_node, true); if (!page) goto out; hlist_del(&rmap_item->hlist); unlock_page(page); put_page(page); if (stable_node->hlist.first) ksm_pages_sharing--; else ksm_pages_shared--; put_anon_vma(rmap_item->anon_vma); rmap_item->address &= PAGE_MASK; } else if (rmap_item->address & UNSTABLE_FLAG) { unsigned char age; /* * Usually ksmd can and must skip the rb_erase, because * root_unstable_tree was already reset to RB_ROOT. * But be careful when an mm is exiting: do the rb_erase * if this rmap_item was inserted by this scan, rather * than left over from before. */ age = (unsigned char)(ksm_scan.seqnr - rmap_item->address); BUG_ON(age > 1); if (!age) rb_erase(&rmap_item->node, root_unstable_tree + NUMA(rmap_item->nid)); ksm_pages_unshared--; rmap_item->address &= PAGE_MASK; } out: cond_resched(); /* we're called from many long loops */ } static void remove_trailing_rmap_items(struct mm_slot *mm_slot, struct rmap_item **rmap_list) { while (*rmap_list) { struct rmap_item *rmap_item = *rmap_list; *rmap_list = rmap_item->rmap_list; remove_rmap_item_from_tree(rmap_item); free_rmap_item(rmap_item); } } /* * Though it's very tempting to unmerge rmap_items from stable tree rather * than check every pte of a given vma, the locking doesn't quite work for * that - an rmap_item is assigned to the stable tree after inserting ksm * page and upping mmap_sem. Nor does it fit with the way we skip dup'ing * rmap_items from parent to child at fork time (so as not to waste time * if exit comes before the next scan reaches it). * * Similarly, although we'd like to remove rmap_items (so updating counts * and freeing memory) when unmerging an area, it's easier to leave that * to the next pass of ksmd - consider, for example, how ksmd might be * in cmp_and_merge_page on one of the rmap_items we would be removing. */ static int unmerge_ksm_pages(struct vm_area_struct *vma, unsigned long start, unsigned long end) { unsigned long addr; int err = 0; for (addr = start; addr < end && !err; addr += PAGE_SIZE) { if (ksm_test_exit(vma->vm_mm)) break; if (signal_pending(current)) err = -ERESTARTSYS; else err = break_ksm(vma, addr); } return err; } #ifdef CONFIG_SYSFS /* * Only called through the sysfs control interface: */ static int remove_stable_node(struct stable_node *stable_node) { struct page *page; int err; page = get_ksm_page(stable_node, true); if (!page) { /* * get_ksm_page did remove_node_from_stable_tree itself. */ return 0; } if (WARN_ON_ONCE(page_mapped(page))) { /* * This should not happen: but if it does, just refuse to let * merge_across_nodes be switched - there is no need to panic. */ err = -EBUSY; } else { /* * The stable node did not yet appear stale to get_ksm_page(), * since that allows for an unmapped ksm page to be recognized * right up until it is freed; but the node is safe to remove. * This page might be in a pagevec waiting to be freed, * or it might be PageSwapCache (perhaps under writeback), * or it might have been removed from swapcache a moment ago. */ set_page_stable_node(page, NULL); remove_node_from_stable_tree(stable_node); err = 0; } unlock_page(page); put_page(page); return err; } static int remove_all_stable_nodes(void) { struct stable_node *stable_node; struct list_head *this, *next; int nid; int err = 0; for (nid = 0; nid < ksm_nr_node_ids; nid++) { while (root_stable_tree[nid].rb_node) { stable_node = rb_entry(root_stable_tree[nid].rb_node, struct stable_node, node); if (remove_stable_node(stable_node)) { err = -EBUSY; break; /* proceed to next nid */ } cond_resched(); } } list_for_each_safe(this, next, &migrate_nodes) { stable_node = list_entry(this, struct stable_node, list); if (remove_stable_node(stable_node)) err = -EBUSY; cond_resched(); } return err; } static int unmerge_and_remove_all_rmap_items(void) { struct mm_slot *mm_slot; struct mm_struct *mm; struct vm_area_struct *vma; int err = 0; spin_lock(&ksm_mmlist_lock); ksm_scan.mm_slot = list_entry(ksm_mm_head.mm_list.next, struct mm_slot, mm_list); spin_unlock(&ksm_mmlist_lock); for (mm_slot = ksm_scan.mm_slot; mm_slot != &ksm_mm_head; mm_slot = ksm_scan.mm_slot) { mm = mm_slot->mm; down_read(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) { if (ksm_test_exit(mm)) break; if (!(vma->vm_flags & VM_MERGEABLE) || !vma->anon_vma) continue; err = unmerge_ksm_pages(vma, vma->vm_start, vma->vm_end); if (err) goto error; } remove_trailing_rmap_items(mm_slot, &mm_slot->rmap_list); spin_lock(&ksm_mmlist_lock); ksm_scan.mm_slot = list_entry(mm_slot->mm_list.next, struct mm_slot, mm_list); if (ksm_test_exit(mm)) { hash_del(&mm_slot->link); list_del(&mm_slot->mm_list); spin_unlock(&ksm_mmlist_lock); free_mm_slot(mm_slot); clear_bit(MMF_VM_MERGEABLE, &mm->flags); up_read(&mm->mmap_sem); mmdrop(mm); } else { spin_unlock(&ksm_mmlist_lock); up_read(&mm->mmap_sem); } } /* Clean up stable nodes, but don't worry if some are still busy */ remove_all_stable_nodes(); ksm_scan.seqnr = 0; return 0; error: up_read(&mm->mmap_sem); spin_lock(&ksm_mmlist_lock); ksm_scan.mm_slot = &ksm_mm_head; spin_unlock(&ksm_mmlist_lock); return err; } #endif /* CONFIG_SYSFS */ static u32 calc_checksum(struct page *page) { u32 checksum; void *addr = kmap_atomic(page); checksum = jhash2(addr, PAGE_SIZE / 4, 17); kunmap_atomic(addr); return checksum; } static int memcmp_pages(struct page *page1, struct page *page2) { char *addr1, *addr2; int ret; addr1 = kmap_atomic(page1); addr2 = kmap_atomic(page2); ret = memcmp(addr1, addr2, PAGE_SIZE); kunmap_atomic(addr2); kunmap_atomic(addr1); return ret; } static inline int pages_identical(struct page *page1, struct page *page2) { return !memcmp_pages(page1, page2); } static int write_protect_page(struct vm_area_struct *vma, struct page *page, pte_t *orig_pte) { struct mm_struct *mm = vma->vm_mm; unsigned long addr; pte_t *ptep; spinlock_t *ptl; int swapped; int err = -EFAULT; unsigned long mmun_start; /* For mmu_notifiers */ unsigned long mmun_end; /* For mmu_notifiers */ addr = page_address_in_vma(page, vma); if (addr == -EFAULT) goto out; BUG_ON(PageTransCompound(page)); mmun_start = addr; mmun_end = addr + PAGE_SIZE; mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptep = page_check_address(page, mm, addr, &ptl, 0); if (!ptep) goto out_mn; if (pte_write(*ptep) || pte_dirty(*ptep)) { pte_t entry; swapped = PageSwapCache(page); flush_cache_page(vma, addr, page_to_pfn(page)); /* * Ok this is tricky, when get_user_pages_fast() run it doesn't * take any lock, therefore the check that we are going to make * with the pagecount against the mapcount is racey and * O_DIRECT can happen right after the check. * So we clear the pte and flush the tlb before the check * this assure us that no O_DIRECT can happen after the check * or in the middle of the check. */ entry = ptep_clear_flush(vma, addr, ptep); /* * Check that no O_DIRECT or similar I/O is in progress on the * page */ if (page_mapcount(page) + 1 + swapped != page_count(page)) { set_pte_at(mm, addr, ptep, entry); goto out_unlock; } if (pte_dirty(entry)) set_page_dirty(page); entry = pte_mkclean(pte_wrprotect(entry)); set_pte_at_notify(mm, addr, ptep, entry); } *orig_pte = *ptep; err = 0; out_unlock: pte_unmap_unlock(ptep, ptl); out_mn: mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); out: return err; } /** * replace_page - replace page in vma by new ksm page * @vma: vma that holds the pte pointing to page * @page: the page we are replacing by kpage * @kpage: the ksm page we replace page by * @orig_pte: the original value of the pte * * Returns 0 on success, -EFAULT on failure. */ static int replace_page(struct vm_area_struct *vma, struct page *page, struct page *kpage, pte_t orig_pte) { struct mm_struct *mm = vma->vm_mm; pmd_t *pmd; pte_t *ptep; spinlock_t *ptl; unsigned long addr; int err = -EFAULT; unsigned long mmun_start; /* For mmu_notifiers */ unsigned long mmun_end; /* For mmu_notifiers */ addr = page_address_in_vma(page, vma); if (addr == -EFAULT) goto out; pmd = mm_find_pmd(mm, addr); if (!pmd) goto out; BUG_ON(pmd_trans_huge(*pmd)); mmun_start = addr; mmun_end = addr + PAGE_SIZE; mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptep = pte_offset_map_lock(mm, pmd, addr, &ptl); if (!pte_same(*ptep, orig_pte)) { pte_unmap_unlock(ptep, ptl); goto out_mn; } get_page(kpage); page_add_anon_rmap(kpage, vma, addr); flush_cache_page(vma, addr, pte_pfn(*ptep)); ptep_clear_flush(vma, addr, ptep); set_pte_at_notify(mm, addr, ptep, mk_pte(kpage, vma->vm_page_prot)); page_remove_rmap(page); if (!page_mapped(page)) try_to_free_swap(page); put_page(page); pte_unmap_unlock(ptep, ptl); err = 0; out_mn: mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); out: return err; } static int page_trans_compound_anon_split(struct page *page) { int ret = 0; struct page *transhuge_head = page_trans_compound_anon(page); if (transhuge_head) { /* Get the reference on the head to split it. */ if (get_page_unless_zero(transhuge_head)) { /* * Recheck we got the reference while the head * was still anonymous. */ if (PageAnon(transhuge_head)) ret = split_huge_page(transhuge_head); else /* * Retry later if split_huge_page run * from under us. */ ret = 1; put_page(transhuge_head); } else /* Retry later if split_huge_page run from under us. */ ret = 1; } return ret; } /* * try_to_merge_one_page - take two pages and merge them into one * @vma: the vma that holds the pte pointing to page * @page: the PageAnon page that we want to replace with kpage * @kpage: the PageKsm page that we want to map instead of page, * or NULL the first time when we want to use page as kpage. * * This function returns 0 if the pages were merged, -EFAULT otherwise. */ static int try_to_merge_one_page(struct vm_area_struct *vma, struct page *page, struct page *kpage) { pte_t orig_pte = __pte(0); int err = -EFAULT; if (page == kpage) /* ksm page forked */ return 0; if (!(vma->vm_flags & VM_MERGEABLE)) goto out; if (PageTransCompound(page) && page_trans_compound_anon_split(page)) goto out; BUG_ON(PageTransCompound(page)); if (!PageAnon(page)) goto out; /* * We need the page lock to read a stable PageSwapCache in * write_protect_page(). We use trylock_page() instead of * lock_page() because we don't want to wait here - we * prefer to continue scanning and merging different pages, * then come back to this page when it is unlocked. */ if (!trylock_page(page)) goto out; /* * If this anonymous page is mapped only here, its pte may need * to be write-protected. If it's mapped elsewhere, all of its * ptes are necessarily already write-protected. But in either * case, we need to lock and check page_count is not raised. */ if (write_protect_page(vma, page, &orig_pte) == 0) { if (!kpage) { /* * While we hold page lock, upgrade page from * PageAnon+anon_vma to PageKsm+NULL stable_node: * stable_tree_insert() will update stable_node. */ set_page_stable_node(page, NULL); mark_page_accessed(page); err = 0; } else if (pages_identical(page, kpage)) err = replace_page(vma, page, kpage, orig_pte); } if ((vma->vm_flags & VM_LOCKED) && kpage && !err) { munlock_vma_page(page); if (!PageMlocked(kpage)) { unlock_page(page); lock_page(kpage); mlock_vma_page(kpage); page = kpage; /* for final unlock */ } } unlock_page(page); out: return err; } /* * try_to_merge_with_ksm_page - like try_to_merge_two_pages, * but no new kernel page is allocated: kpage must already be a ksm page. * * This function returns 0 if the pages were merged, -EFAULT otherwise. */ static int try_to_merge_with_ksm_page(struct rmap_item *rmap_item, struct page *page, struct page *kpage) { struct mm_struct *mm = rmap_item->mm; struct vm_area_struct *vma; int err = -EFAULT; down_read(&mm->mmap_sem); if (ksm_test_exit(mm)) goto out; vma = find_vma(mm, rmap_item->address); if (!vma || vma->vm_start > rmap_item->address) goto out; err = try_to_merge_one_page(vma, page, kpage); if (err) goto out; /* Unstable nid is in union with stable anon_vma: remove first */ remove_rmap_item_from_tree(rmap_item); /* Must get reference to anon_vma while still holding mmap_sem */ rmap_item->anon_vma = vma->anon_vma; get_anon_vma(vma->anon_vma); out: up_read(&mm->mmap_sem); return err; } /* * try_to_merge_two_pages - take two identical pages and prepare them * to be merged into one page. * * This function returns the kpage if we successfully merged two identical * pages into one ksm page, NULL otherwise. * * Note that this function upgrades page to ksm page: if one of the pages * is already a ksm page, try_to_merge_with_ksm_page should be used. */ static struct page *try_to_merge_two_pages(struct rmap_item *rmap_item, struct page *page, struct rmap_item *tree_rmap_item, struct page *tree_page) { int err; err = try_to_merge_with_ksm_page(rmap_item, page, NULL); if (!err) { err = try_to_merge_with_ksm_page(tree_rmap_item, tree_page, page); /* * If that fails, we have a ksm page with only one pte * pointing to it: so break it. */ if (err) break_cow(rmap_item); } return err ? NULL : page; } /* * stable_tree_search - search for page inside the stable tree * * This function checks if there is a page inside the stable tree * with identical content to the page that we are scanning right now. * * This function returns the stable tree node of identical content if found, * NULL otherwise. */ static struct page *stable_tree_search(struct page *page) { int nid; struct rb_root *root; struct rb_node **new; struct rb_node *parent; struct stable_node *stable_node; struct stable_node *page_node; page_node = page_stable_node(page); if (page_node && page_node->head != &migrate_nodes) { /* ksm page forked */ get_page(page); return page; } nid = get_kpfn_nid(page_to_pfn(page)); root = root_stable_tree + nid; again: new = &root->rb_node; parent = NULL; while (*new) { struct page *tree_page; int ret; cond_resched(); stable_node = rb_entry(*new, struct stable_node, node); tree_page = get_ksm_page(stable_node, false); if (!tree_page) return NULL; ret = memcmp_pages(page, tree_page); put_page(tree_page); parent = *new; if (ret < 0) new = &parent->rb_left; else if (ret > 0) new = &parent->rb_right; else { /* * Lock and unlock the stable_node's page (which * might already have been migrated) so that page * migration is sure to notice its raised count. * It would be more elegant to return stable_node * than kpage, but that involves more changes. */ tree_page = get_ksm_page(stable_node, true); if (tree_page) { unlock_page(tree_page); if (get_kpfn_nid(stable_node->kpfn) != NUMA(stable_node->nid)) { put_page(tree_page); goto replace; } return tree_page; } /* * There is now a place for page_node, but the tree may * have been rebalanced, so re-evaluate parent and new. */ if (page_node) goto again; return NULL; } } if (!page_node) return NULL; list_del(&page_node->list); DO_NUMA(page_node->nid = nid); rb_link_node(&page_node->node, parent, new); rb_insert_color(&page_node->node, root); get_page(page); return page; replace: if (page_node) { list_del(&page_node->list); DO_NUMA(page_node->nid = nid); rb_replace_node(&stable_node->node, &page_node->node, root); get_page(page); } else { rb_erase(&stable_node->node, root); page = NULL; } stable_node->head = &migrate_nodes; list_add(&stable_node->list, stable_node->head); return page; } /* * stable_tree_insert - insert stable tree node pointing to new ksm page * into the stable tree. * * This function returns the stable tree node just allocated on success, * NULL otherwise. */ static struct stable_node *stable_tree_insert(struct page *kpage) { int nid; unsigned long kpfn; struct rb_root *root; struct rb_node **new; struct rb_node *parent = NULL; struct stable_node *stable_node; kpfn = page_to_pfn(kpage); nid = get_kpfn_nid(kpfn); root = root_stable_tree + nid; new = &root->rb_node; while (*new) { struct page *tree_page; int ret; cond_resched(); stable_node = rb_entry(*new, struct stable_node, node); tree_page = get_ksm_page(stable_node, false); if (!tree_page) return NULL; ret = memcmp_pages(kpage, tree_page); put_page(tree_page); parent = *new; if (ret < 0) new = &parent->rb_left; else if (ret > 0) new = &parent->rb_right; else { /* * It is not a bug that stable_tree_search() didn't * find this node: because at that time our page was * not yet write-protected, so may have changed since. */ return NULL; } } stable_node = alloc_stable_node(); if (!stable_node) return NULL; INIT_HLIST_HEAD(&stable_node->hlist); stable_node->kpfn = kpfn; set_page_stable_node(kpage, stable_node); DO_NUMA(stable_node->nid = nid); rb_link_node(&stable_node->node, parent, new); rb_insert_color(&stable_node->node, root); return stable_node; } /* * unstable_tree_search_insert - search for identical page, * else insert rmap_item into the unstable tree. * * This function searches for a page in the unstable tree identical to the * page currently being scanned; and if no identical page is found in the * tree, we insert rmap_item as a new object into the unstable tree. * * This function returns pointer to rmap_item found to be identical * to the currently scanned page, NULL otherwise. * * This function does both searching and inserting, because they share * the same walking algorithm in an rbtree. */ static struct rmap_item *unstable_tree_search_insert(struct rmap_item *rmap_item, struct page *page, struct page **tree_pagep) { struct rb_node **new; struct rb_root *root; struct rb_node *parent = NULL; int nid; nid = get_kpfn_nid(page_to_pfn(page)); root = root_unstable_tree + nid; new = &root->rb_node; while (*new) { struct rmap_item *tree_rmap_item; struct page *tree_page; int ret; cond_resched(); tree_rmap_item = rb_entry(*new, struct rmap_item, node); tree_page = get_mergeable_page(tree_rmap_item); if (IS_ERR_OR_NULL(tree_page)) return NULL; /* * Don't substitute a ksm page for a forked page. */ if (page == tree_page) { put_page(tree_page); return NULL; } ret = memcmp_pages(page, tree_page); parent = *new; if (ret < 0) { put_page(tree_page); new = &parent->rb_left; } else if (ret > 0) { put_page(tree_page); new = &parent->rb_right; } else if (!ksm_merge_across_nodes && page_to_nid(tree_page) != nid) { /* * If tree_page has been migrated to another NUMA node, * it will be flushed out and put in the right unstable * tree next time: only merge with it when across_nodes. */ put_page(tree_page); return NULL; } else { *tree_pagep = tree_page; return tree_rmap_item; } } rmap_item->address |= UNSTABLE_FLAG; rmap_item->address |= (ksm_scan.seqnr & SEQNR_MASK); DO_NUMA(rmap_item->nid = nid); rb_link_node(&rmap_item->node, parent, new); rb_insert_color(&rmap_item->node, root); ksm_pages_unshared++; return NULL; } /* * stable_tree_append - add another rmap_item to the linked list of * rmap_items hanging off a given node of the stable tree, all sharing * the same ksm page. */ static void stable_tree_append(struct rmap_item *rmap_item, struct stable_node *stable_node) { rmap_item->head = stable_node; rmap_item->address |= STABLE_FLAG; hlist_add_head(&rmap_item->hlist, &stable_node->hlist); if (rmap_item->hlist.next) ksm_pages_sharing++; else ksm_pages_shared++; } /* * cmp_and_merge_page - first see if page can be merged into the stable tree; * if not, compare checksum to previous and if it's the same, see if page can * be inserted into the unstable tree, or merged with a page already there and * both transferred to the stable tree. * * @page: the page that we are searching identical page to. * @rmap_item: the reverse mapping into the virtual address of this page */ static void cmp_and_merge_page(struct page *page, struct rmap_item *rmap_item) { struct rmap_item *tree_rmap_item; struct page *tree_page = NULL; struct stable_node *stable_node; struct page *kpage; unsigned int checksum; int err; stable_node = page_stable_node(page); if (stable_node) { if (stable_node->head != &migrate_nodes && get_kpfn_nid(stable_node->kpfn) != NUMA(stable_node->nid)) { rb_erase(&stable_node->node, root_stable_tree + NUMA(stable_node->nid)); stable_node->head = &migrate_nodes; list_add(&stable_node->list, stable_node->head); } if (stable_node->head != &migrate_nodes && rmap_item->head == stable_node) return; } /* We first start with searching the page inside the stable tree */ kpage = stable_tree_search(page); if (kpage == page && rmap_item->head == stable_node) { put_page(kpage); return; } remove_rmap_item_from_tree(rmap_item); if (kpage) { err = try_to_merge_with_ksm_page(rmap_item, page, kpage); if (!err) { /* * The page was successfully merged: * add its rmap_item to the stable tree. */ lock_page(kpage); stable_tree_append(rmap_item, page_stable_node(kpage)); unlock_page(kpage); } put_page(kpage); return; } /* * If the hash value of the page has changed from the last time * we calculated it, this page is changing frequently: therefore we * don't want to insert it in the unstable tree, and we don't want * to waste our time searching for something identical to it there. */ checksum = calc_checksum(page); if (rmap_item->oldchecksum != checksum) { rmap_item->oldchecksum = checksum; return; } tree_rmap_item = unstable_tree_search_insert(rmap_item, page, &tree_page); if (tree_rmap_item) { kpage = try_to_merge_two_pages(rmap_item, page, tree_rmap_item, tree_page); put_page(tree_page); if (kpage) { /* * The pages were successfully merged: insert new * node in the stable tree and add both rmap_items. */ lock_page(kpage); stable_node = stable_tree_insert(kpage); if (stable_node) { stable_tree_append(tree_rmap_item, stable_node); stable_tree_append(rmap_item, stable_node); } unlock_page(kpage); /* * If we fail to insert the page into the stable tree, * we will have 2 virtual addresses that are pointing * to a ksm page left outside the stable tree, * in which case we need to break_cow on both. */ if (!stable_node) { break_cow(tree_rmap_item); break_cow(rmap_item); } } } } static struct rmap_item *get_next_rmap_item(struct mm_slot *mm_slot, struct rmap_item **rmap_list, unsigned long addr) { struct rmap_item *rmap_item; while (*rmap_list) { rmap_item = *rmap_list; if ((rmap_item->address & PAGE_MASK) == addr) return rmap_item; if (rmap_item->address > addr) break; *rmap_list = rmap_item->rmap_list; remove_rmap_item_from_tree(rmap_item); free_rmap_item(rmap_item); } rmap_item = alloc_rmap_item(); if (rmap_item) { /* It has already been zeroed */ rmap_item->mm = mm_slot->mm; rmap_item->address = addr; rmap_item->rmap_list = *rmap_list; *rmap_list = rmap_item; } return rmap_item; } static struct rmap_item *scan_get_next_rmap_item(struct page **page) { struct mm_struct *mm; struct mm_slot *slot; struct vm_area_struct *vma; struct rmap_item *rmap_item; int nid; if (list_empty(&ksm_mm_head.mm_list)) return NULL; slot = ksm_scan.mm_slot; if (slot == &ksm_mm_head) { /* * A number of pages can hang around indefinitely on per-cpu * pagevecs, raised page count preventing write_protect_page * from merging them. Though it doesn't really matter much, * it is puzzling to see some stuck in pages_volatile until * other activity jostles them out, and they also prevented * LTP's KSM test from succeeding deterministically; so drain * them here (here rather than on entry to ksm_do_scan(), * so we don't IPI too often when pages_to_scan is set low). */ lru_add_drain_all(); /* * Whereas stale stable_nodes on the stable_tree itself * get pruned in the regular course of stable_tree_search(), * those moved out to the migrate_nodes list can accumulate: * so prune them once before each full scan. */ if (!ksm_merge_across_nodes) { struct stable_node *stable_node; struct list_head *this, *next; struct page *page; list_for_each_safe(this, next, &migrate_nodes) { stable_node = list_entry(this, struct stable_node, list); page = get_ksm_page(stable_node, false); if (page) put_page(page); cond_resched(); } } for (nid = 0; nid < ksm_nr_node_ids; nid++) root_unstable_tree[nid] = RB_ROOT; spin_lock(&ksm_mmlist_lock); slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list); ksm_scan.mm_slot = slot; spin_unlock(&ksm_mmlist_lock); /* * Although we tested list_empty() above, a racing __ksm_exit * of the last mm on the list may have removed it since then. */ if (slot == &ksm_mm_head) return NULL; next_mm: ksm_scan.address = 0; ksm_scan.rmap_list = &slot->rmap_list; } mm = slot->mm; down_read(&mm->mmap_sem); if (ksm_test_exit(mm)) vma = NULL; else vma = find_vma(mm, ksm_scan.address); for (; vma; vma = vma->vm_next) { if (!(vma->vm_flags & VM_MERGEABLE)) continue; if (ksm_scan.address < vma->vm_start) ksm_scan.address = vma->vm_start; if (!vma->anon_vma) ksm_scan.address = vma->vm_end; while (ksm_scan.address < vma->vm_end) { if (ksm_test_exit(mm)) break; *page = follow_page(vma, ksm_scan.address, FOLL_GET); if (IS_ERR_OR_NULL(*page)) { ksm_scan.address += PAGE_SIZE; cond_resched(); continue; } if (PageAnon(*page) || page_trans_compound_anon(*page)) { flush_anon_page(vma, *page, ksm_scan.address); flush_dcache_page(*page); rmap_item = get_next_rmap_item(slot, ksm_scan.rmap_list, ksm_scan.address); if (rmap_item) { ksm_scan.rmap_list = &rmap_item->rmap_list; ksm_scan.address += PAGE_SIZE; } else put_page(*page); up_read(&mm->mmap_sem); return rmap_item; } put_page(*page); ksm_scan.address += PAGE_SIZE; cond_resched(); } } if (ksm_test_exit(mm)) { ksm_scan.address = 0; ksm_scan.rmap_list = &slot->rmap_list; } /* * Nuke all the rmap_items that are above this current rmap: * because there were no VM_MERGEABLE vmas with such addresses. */ remove_trailing_rmap_items(slot, ksm_scan.rmap_list); spin_lock(&ksm_mmlist_lock); ksm_scan.mm_slot = list_entry(slot->mm_list.next, struct mm_slot, mm_list); if (ksm_scan.address == 0) { /* * We've completed a full scan of all vmas, holding mmap_sem * throughout, and found no VM_MERGEABLE: so do the same as * __ksm_exit does to remove this mm from all our lists now. * This applies either when cleaning up after __ksm_exit * (but beware: we can reach here even before __ksm_exit), * or when all VM_MERGEABLE areas have been unmapped (and * mmap_sem then protects against race with MADV_MERGEABLE). */ hash_del(&slot->link); list_del(&slot->mm_list); spin_unlock(&ksm_mmlist_lock); free_mm_slot(slot); clear_bit(MMF_VM_MERGEABLE, &mm->flags); up_read(&mm->mmap_sem); mmdrop(mm); } else { spin_unlock(&ksm_mmlist_lock); up_read(&mm->mmap_sem); } /* Repeat until we've completed scanning the whole list */ slot = ksm_scan.mm_slot; if (slot != &ksm_mm_head) goto next_mm; ksm_scan.seqnr++; return NULL; } /** * ksm_do_scan - the ksm scanner main worker function. * @scan_npages - number of pages we want to scan before we return. */ static void ksm_do_scan(unsigned int scan_npages) { struct rmap_item *rmap_item; struct page *uninitialized_var(page); while (scan_npages-- && likely(!freezing(current))) { cond_resched(); rmap_item = scan_get_next_rmap_item(&page); if (!rmap_item) return; cmp_and_merge_page(page, rmap_item); put_page(page); } } static int ksmd_should_run(void) { return (ksm_run & KSM_RUN_MERGE) && !list_empty(&ksm_mm_head.mm_list); } static int ksm_scan_thread(void *nothing) { set_freezable(); set_user_nice(current, 5); while (!kthread_should_stop()) { mutex_lock(&ksm_thread_mutex); wait_while_offlining(); if (ksmd_should_run()) ksm_do_scan(ksm_thread_pages_to_scan); mutex_unlock(&ksm_thread_mutex); try_to_freeze(); if (ksmd_should_run()) { schedule_timeout_interruptible( msecs_to_jiffies(ksm_thread_sleep_millisecs)); } else { wait_event_freezable(ksm_thread_wait, ksmd_should_run() || kthread_should_stop()); } } return 0; } int ksm_madvise(struct vm_area_struct *vma, unsigned long start, unsigned long end, int advice, unsigned long *vm_flags) { struct mm_struct *mm = vma->vm_mm; int err; switch (advice) { case MADV_MERGEABLE: /* * Be somewhat over-protective for now! */ if (*vm_flags & (VM_MERGEABLE | VM_SHARED | VM_MAYSHARE | VM_PFNMAP | VM_IO | VM_DONTEXPAND | VM_HUGETLB | VM_NONLINEAR | VM_MIXEDMAP)) return 0; /* just ignore the advice */ #ifdef VM_SAO if (*vm_flags & VM_SAO) return 0; #endif if (!test_bit(MMF_VM_MERGEABLE, &mm->flags)) { err = __ksm_enter(mm); if (err) return err; } *vm_flags |= VM_MERGEABLE; break; case MADV_UNMERGEABLE: if (!(*vm_flags & VM_MERGEABLE)) return 0; /* just ignore the advice */ if (vma->anon_vma) { err = unmerge_ksm_pages(vma, start, end); if (err) return err; } *vm_flags &= ~VM_MERGEABLE; break; } return 0; } int __ksm_enter(struct mm_struct *mm) { struct mm_slot *mm_slot; int needs_wakeup; mm_slot = alloc_mm_slot(); if (!mm_slot) return -ENOMEM; /* Check ksm_run too? Would need tighter locking */ needs_wakeup = list_empty(&ksm_mm_head.mm_list); spin_lock(&ksm_mmlist_lock); insert_to_mm_slots_hash(mm, mm_slot); /* * When KSM_RUN_MERGE (or KSM_RUN_STOP), * insert just behind the scanning cursor, to let the area settle * down a little; when fork is followed by immediate exec, we don't * want ksmd to waste time setting up and tearing down an rmap_list. * * But when KSM_RUN_UNMERGE, it's important to insert ahead of its * scanning cursor, otherwise KSM pages in newly forked mms will be * missed: then we might as well insert at the end of the list. */ if (ksm_run & KSM_RUN_UNMERGE) list_add_tail(&mm_slot->mm_list, &ksm_mm_head.mm_list); else list_add_tail(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list); spin_unlock(&ksm_mmlist_lock); set_bit(MMF_VM_MERGEABLE, &mm->flags); atomic_inc(&mm->mm_count); if (needs_wakeup) wake_up_interruptible(&ksm_thread_wait); return 0; } void __ksm_exit(struct mm_struct *mm) { struct mm_slot *mm_slot; int easy_to_free = 0; /* * This process is exiting: if it's straightforward (as is the * case when ksmd was never running), free mm_slot immediately. * But if it's at the cursor or has rmap_items linked to it, use * mmap_sem to synchronize with any break_cows before pagetables * are freed, and leave the mm_slot on the list for ksmd to free. * Beware: ksm may already have noticed it exiting and freed the slot. */ spin_lock(&ksm_mmlist_lock); mm_slot = get_mm_slot(mm); if (mm_slot && ksm_scan.mm_slot != mm_slot) { if (!mm_slot->rmap_list) { hash_del(&mm_slot->link); list_del(&mm_slot->mm_list); easy_to_free = 1; } else { list_move(&mm_slot->mm_list, &ksm_scan.mm_slot->mm_list); } } spin_unlock(&ksm_mmlist_lock); if (easy_to_free) { free_mm_slot(mm_slot); clear_bit(MMF_VM_MERGEABLE, &mm->flags); mmdrop(mm); } else if (mm_slot) { down_write(&mm->mmap_sem); up_write(&mm->mmap_sem); } } struct page *ksm_might_need_to_copy(struct page *page, struct vm_area_struct *vma, unsigned long address) { struct anon_vma *anon_vma = page_anon_vma(page); struct page *new_page; if (PageKsm(page)) { if (page_stable_node(page) && !(ksm_run & KSM_RUN_UNMERGE)) return page; /* no need to copy it */ } else if (!anon_vma) { return page; /* no need to copy it */ } else if (anon_vma->root == vma->anon_vma->root && page->index == linear_page_index(vma, address)) { return page; /* still no need to copy it */ } if (!PageUptodate(page)) return page; /* let do_swap_page report the error */ new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address); if (new_page) { copy_user_highpage(new_page, page, address, vma); SetPageDirty(new_page); __SetPageUptodate(new_page); __set_page_locked(new_page); } return new_page; } int page_referenced_ksm(struct page *page, struct mem_cgroup *memcg, unsigned long *vm_flags) { struct stable_node *stable_node; struct rmap_item *rmap_item; unsigned int mapcount = page_mapcount(page); int referenced = 0; int search_new_forks = 0; VM_BUG_ON(!PageKsm(page)); VM_BUG_ON(!PageLocked(page)); stable_node = page_stable_node(page); if (!stable_node) return 0; again: hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) { struct anon_vma *anon_vma = rmap_item->anon_vma; struct anon_vma_chain *vmac; struct vm_area_struct *vma; anon_vma_lock_read(anon_vma); anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root, 0, ULONG_MAX) { vma = vmac->vma; if (rmap_item->address < vma->vm_start || rmap_item->address >= vma->vm_end) continue; /* * Initially we examine only the vma which covers this * rmap_item; but later, if there is still work to do, * we examine covering vmas in other mms: in case they * were forked from the original since ksmd passed. */ if ((rmap_item->mm == vma->vm_mm) == search_new_forks) continue; if (memcg && !mm_match_cgroup(vma->vm_mm, memcg)) continue; referenced += page_referenced_one(page, vma, rmap_item->address, &mapcount, vm_flags); if (!search_new_forks || !mapcount) break; } anon_vma_unlock_read(anon_vma); if (!mapcount) goto out; } if (!search_new_forks++) goto again; out: return referenced; } int try_to_unmap_ksm(struct page *page, enum ttu_flags flags, struct vm_area_struct *target_vma) { struct stable_node *stable_node; struct rmap_item *rmap_item; int ret = SWAP_AGAIN; int search_new_forks = 0; VM_BUG_ON(!PageKsm(page)); VM_BUG_ON(!PageLocked(page)); stable_node = page_stable_node(page); if (!stable_node) return SWAP_FAIL; if (target_vma) { unsigned long address = vma_address(page, target_vma); ret = try_to_unmap_one(page, target_vma, address, flags); goto out; } again: hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) { struct anon_vma *anon_vma = rmap_item->anon_vma; struct anon_vma_chain *vmac; struct vm_area_struct *vma; anon_vma_lock_read(anon_vma); anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root, 0, ULONG_MAX) { vma = vmac->vma; if (rmap_item->address < vma->vm_start || rmap_item->address >= vma->vm_end) continue; /* * Initially we examine only the vma which covers this * rmap_item; but later, if there is still work to do, * we examine covering vmas in other mms: in case they * were forked from the original since ksmd passed. */ if ((rmap_item->mm == vma->vm_mm) == search_new_forks) continue; ret = try_to_unmap_one(page, vma, rmap_item->address, flags); if (ret != SWAP_AGAIN || !page_mapped(page)) { anon_vma_unlock_read(anon_vma); goto out; } } anon_vma_unlock_read(anon_vma); } if (!search_new_forks++) goto again; out: return ret; } #ifdef CONFIG_MIGRATION int rmap_walk_ksm(struct page *page, int (*rmap_one)(struct page *, struct vm_area_struct *, unsigned long, void *), void *arg) { struct stable_node *stable_node; struct rmap_item *rmap_item; int ret = SWAP_AGAIN; int search_new_forks = 0; VM_BUG_ON(!PageKsm(page)); VM_BUG_ON(!PageLocked(page)); stable_node = page_stable_node(page); if (!stable_node) return ret; again: hlist_for_each_entry(rmap_item, &stable_node->hlist, hlist) { struct anon_vma *anon_vma = rmap_item->anon_vma; struct anon_vma_chain *vmac; struct vm_area_struct *vma; anon_vma_lock_read(anon_vma); anon_vma_interval_tree_foreach(vmac, &anon_vma->rb_root, 0, ULONG_MAX) { vma = vmac->vma; if (rmap_item->address < vma->vm_start || rmap_item->address >= vma->vm_end) continue; /* * Initially we examine only the vma which covers this * rmap_item; but later, if there is still work to do, * we examine covering vmas in other mms: in case they * were forked from the original since ksmd passed. */ if ((rmap_item->mm == vma->vm_mm) == search_new_forks) continue; ret = rmap_one(page, vma, rmap_item->address, arg); if (ret != SWAP_AGAIN) { anon_vma_unlock_read(anon_vma); goto out; } } anon_vma_unlock_read(anon_vma); } if (!search_new_forks++) goto again; out: return ret; } void ksm_migrate_page(struct page *newpage, struct page *oldpage) { struct stable_node *stable_node; VM_BUG_ON(!PageLocked(oldpage)); VM_BUG_ON(!PageLocked(newpage)); VM_BUG_ON(newpage->mapping != oldpage->mapping); stable_node = page_stable_node(newpage); if (stable_node) { VM_BUG_ON(stable_node->kpfn != page_to_pfn(oldpage)); stable_node->kpfn = page_to_pfn(newpage); /* * newpage->mapping was set in advance; now we need smp_wmb() * to make sure that the new stable_node->kpfn is visible * to get_ksm_page() before it can see that oldpage->mapping * has gone stale (or that PageSwapCache has been cleared). */ smp_wmb(); set_page_stable_node(oldpage, NULL); } } #endif /* CONFIG_MIGRATION */ #ifdef CONFIG_MEMORY_HOTREMOVE static int just_wait(void *word) { schedule(); return 0; } static void wait_while_offlining(void) { while (ksm_run & KSM_RUN_OFFLINE) { mutex_unlock(&ksm_thread_mutex); wait_on_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE), just_wait, TASK_UNINTERRUPTIBLE); mutex_lock(&ksm_thread_mutex); } } static void ksm_check_stable_tree(unsigned long start_pfn, unsigned long end_pfn) { struct stable_node *stable_node; struct list_head *this, *next; struct rb_node *node; int nid; for (nid = 0; nid < ksm_nr_node_ids; nid++) { node = rb_first(root_stable_tree + nid); while (node) { stable_node = rb_entry(node, struct stable_node, node); if (stable_node->kpfn >= start_pfn && stable_node->kpfn < end_pfn) { /* * Don't get_ksm_page, page has already gone: * which is why we keep kpfn instead of page* */ remove_node_from_stable_tree(stable_node); node = rb_first(root_stable_tree + nid); } else node = rb_next(node); cond_resched(); } } list_for_each_safe(this, next, &migrate_nodes) { stable_node = list_entry(this, struct stable_node, list); if (stable_node->kpfn >= start_pfn && stable_node->kpfn < end_pfn) remove_node_from_stable_tree(stable_node); cond_resched(); } } static int ksm_memory_callback(struct notifier_block *self, unsigned long action, void *arg) { struct memory_notify *mn = arg; switch (action) { case MEM_GOING_OFFLINE: /* * Prevent ksm_do_scan(), unmerge_and_remove_all_rmap_items() * and remove_all_stable_nodes() while memory is going offline: * it is unsafe for them to touch the stable tree at this time. * But unmerge_ksm_pages(), rmap lookups and other entry points * which do not need the ksm_thread_mutex are all safe. */ mutex_lock(&ksm_thread_mutex); ksm_run |= KSM_RUN_OFFLINE; mutex_unlock(&ksm_thread_mutex); break; case MEM_OFFLINE: /* * Most of the work is done by page migration; but there might * be a few stable_nodes left over, still pointing to struct * pages which have been offlined: prune those from the tree, * otherwise get_ksm_page() might later try to access a * non-existent struct page. */ ksm_check_stable_tree(mn->start_pfn, mn->start_pfn + mn->nr_pages); /* fallthrough */ case MEM_CANCEL_OFFLINE: mutex_lock(&ksm_thread_mutex); ksm_run &= ~KSM_RUN_OFFLINE; mutex_unlock(&ksm_thread_mutex); smp_mb(); /* wake_up_bit advises this */ wake_up_bit(&ksm_run, ilog2(KSM_RUN_OFFLINE)); break; } return NOTIFY_OK; } #else static void wait_while_offlining(void) { } #endif /* CONFIG_MEMORY_HOTREMOVE */ #ifdef CONFIG_SYSFS /* * This all compiles without CONFIG_SYSFS, but is a waste of space. */ #define KSM_ATTR_RO(_name) \ static struct kobj_attribute _name##_attr = __ATTR_RO(_name) #define KSM_ATTR(_name) \ static struct kobj_attribute _name##_attr = \ __ATTR(_name, 0644, _name##_show, _name##_store) static ssize_t sleep_millisecs_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%u\n", ksm_thread_sleep_millisecs); } static ssize_t sleep_millisecs_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { unsigned long msecs; int err; err = strict_strtoul(buf, 10, &msecs); if (err || msecs > UINT_MAX) return -EINVAL; ksm_thread_sleep_millisecs = msecs; return count; } KSM_ATTR(sleep_millisecs); static ssize_t pages_to_scan_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%u\n", ksm_thread_pages_to_scan); } static ssize_t pages_to_scan_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int err; unsigned long nr_pages; err = strict_strtoul(buf, 10, &nr_pages); if (err || nr_pages > UINT_MAX) return -EINVAL; ksm_thread_pages_to_scan = nr_pages; return count; } KSM_ATTR(pages_to_scan); static ssize_t run_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%lu\n", ksm_run); } static ssize_t run_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int err; unsigned long flags; err = strict_strtoul(buf, 10, &flags); if (err || flags > UINT_MAX) return -EINVAL; if (flags > KSM_RUN_UNMERGE) return -EINVAL; /* * KSM_RUN_MERGE sets ksmd running, and 0 stops it running. * KSM_RUN_UNMERGE stops it running and unmerges all rmap_items, * breaking COW to free the pages_shared (but leaves mm_slots * on the list for when ksmd may be set running again). */ mutex_lock(&ksm_thread_mutex); wait_while_offlining(); if (ksm_run != flags) { ksm_run = flags; if (flags & KSM_RUN_UNMERGE) { set_current_oom_origin(); err = unmerge_and_remove_all_rmap_items(); clear_current_oom_origin(); if (err) { ksm_run = KSM_RUN_STOP; count = err; } } } mutex_unlock(&ksm_thread_mutex); if (flags & KSM_RUN_MERGE) wake_up_interruptible(&ksm_thread_wait); return count; } KSM_ATTR(run); #ifdef CONFIG_NUMA static ssize_t merge_across_nodes_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%u\n", ksm_merge_across_nodes); } static ssize_t merge_across_nodes_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int err; unsigned long knob; err = kstrtoul(buf, 10, &knob); if (err) return err; if (knob > 1) return -EINVAL; mutex_lock(&ksm_thread_mutex); wait_while_offlining(); if (ksm_merge_across_nodes != knob) { if (ksm_pages_shared || remove_all_stable_nodes()) err = -EBUSY; else if (root_stable_tree == one_stable_tree) { struct rb_root *buf; /* * This is the first time that we switch away from the * default of merging across nodes: must now allocate * a buffer to hold as many roots as may be needed. * Allocate stable and unstable together: * MAXSMP NODES_SHIFT 10 will use 16kB. */ buf = kcalloc(nr_node_ids + nr_node_ids, sizeof(*buf), GFP_KERNEL | __GFP_ZERO); /* Let us assume that RB_ROOT is NULL is zero */ if (!buf) err = -ENOMEM; else { root_stable_tree = buf; root_unstable_tree = buf + nr_node_ids; /* Stable tree is empty but not the unstable */ root_unstable_tree[0] = one_unstable_tree[0]; } } if (!err) { ksm_merge_across_nodes = knob; ksm_nr_node_ids = knob ? 1 : nr_node_ids; } } mutex_unlock(&ksm_thread_mutex); return err ? err : count; } KSM_ATTR(merge_across_nodes); #endif static ssize_t pages_shared_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%lu\n", ksm_pages_shared); } KSM_ATTR_RO(pages_shared); static ssize_t pages_sharing_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%lu\n", ksm_pages_sharing); } KSM_ATTR_RO(pages_sharing); static ssize_t pages_unshared_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%lu\n", ksm_pages_unshared); } KSM_ATTR_RO(pages_unshared); static ssize_t pages_volatile_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { long ksm_pages_volatile; ksm_pages_volatile = ksm_rmap_items - ksm_pages_shared - ksm_pages_sharing - ksm_pages_unshared; /* * It was not worth any locking to calculate that statistic, * but it might therefore sometimes be negative: conceal that. */ if (ksm_pages_volatile < 0) ksm_pages_volatile = 0; return sprintf(buf, "%ld\n", ksm_pages_volatile); } KSM_ATTR_RO(pages_volatile); static ssize_t full_scans_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return sprintf(buf, "%lu\n", ksm_scan.seqnr); } KSM_ATTR_RO(full_scans); static struct attribute *ksm_attrs[] = { &sleep_millisecs_attr.attr, &pages_to_scan_attr.attr, &run_attr.attr, &pages_shared_attr.attr, &pages_sharing_attr.attr, &pages_unshared_attr.attr, &pages_volatile_attr.attr, &full_scans_attr.attr, #ifdef CONFIG_NUMA &merge_across_nodes_attr.attr, #endif NULL, }; static struct attribute_group ksm_attr_group = { .attrs = ksm_attrs, .name = "ksm", }; #endif /* CONFIG_SYSFS */ static int __init ksm_init(void) { struct task_struct *ksm_thread; int err; err = ksm_slab_init(); if (err) goto out; ksm_thread = kthread_run(ksm_scan_thread, NULL, "ksmd"); if (IS_ERR(ksm_thread)) { printk(KERN_ERR "ksm: creating kthread failed\n"); err = PTR_ERR(ksm_thread); goto out_free; } #ifdef CONFIG_SYSFS err = sysfs_create_group(mm_kobj, &ksm_attr_group); if (err) { printk(KERN_ERR "ksm: register sysfs failed\n"); kthread_stop(ksm_thread); goto out_free; } #else ksm_run = KSM_RUN_MERGE; /* no way for user to start it */ #endif /* CONFIG_SYSFS */ #ifdef CONFIG_MEMORY_HOTREMOVE /* There is no significance to this priority 100 */ hotplug_memory_notifier(ksm_memory_callback, 100); #endif return 0; out_free: ksm_slab_free(); out: return err; } module_init(ksm_init)
The-Sickness/DOL1-S6
mm/ksm.c
C
gpl-2.0
67,617
/* packet-adwin-config.c * Routines for ADwin configuration protocol dissection * Copyright 2010, Thomas Boehne <TBoehne[AT]ADwin.de> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * SPDX-License-Identifier: GPL-2.0-or-later */ #include "config.h" #include <epan/packet.h> #include "packet-tcp.h" /* Forward declarations */ void proto_register_adwin_config(void); void proto_reg_handoff_adwin_config(void); /* This is registered to a different protocol */ #define ADWIN_CONFIGURATION_PORT 7000 #define UDPStatusLENGTH 52 #define UDPExtStatusLENGTH 432 #define UDPMessageLENGTH 100 #define UDPMessageLENGTH_wrong 104 #define UDPInitAckLENGTH 96 #define UDPIXP425FlashUpdateLENGTH 92 #define UDPOutLENGTH 22 #define STATUS_WITH_BOOTLOADER 0x0001 #define STATUS_REPROGRAMMABLE 0x0002 #define STATUS_CONFIGURABLE 0x0004 #define STATUS_BOOTLOADER_BOOTS 0x0008 #define STATUS_BOOTLOADER_REPROGRAMMABLE 0x0010 #define STATUS_BOOTLOADER_RECEIVES_DATA 0x0020 #define STATUS_BOOTLOADER_REPROGRAMMING_DONE 0x0040 #define STATUS_WITH_EEPROM_SUPPORT 0x0080 static const value_string pattern_mapping[] = { { 0x12343210, "Reset reset/socket counters"}, { 0x73241291, "Scan Netarm + IXP"}, { 0x37241291, "Scan IXP"}, { 0, NULL }, }; static const value_string config_command_mapping[] = { { 100, "Apply all config values except MAC if MAC matches."}, { 105, "Apply all config values including MAC if current MAC is 00:50:C2:0A:22:EE."}, { 110, "Apply all config values including MAC."}, { 120, "Enable/Disable bootloader if MAC matches."}, { 130, "Write extended hardware info to EEPROM."}, { 0, NULL }, }; static const string_string system_type_mapping[] = { { "01", "Light 16"}, { "02", "Gold"}, { "03", "Pro I"}, { "04", "Pro II"}, { "05", "Gold II"}, { 0, NULL }, }; static const string_string processor_type_mapping[] = { { "09", "T9"}, { "10", "T10"}, { "11", "T11"}, { 0, NULL }, }; /* Initialize the protocol and registered fields */ static int proto_adwin_config = -1; static int hf_adwin_config_bootloader = -1; static int hf_adwin_config_command = -1; static int hf_adwin_config_data = -1; static int hf_adwin_config_date = -1; static int hf_adwin_config_description = -1; static int hf_adwin_config_dhcp = -1; static int hf_adwin_config_filename = -1; static int hf_adwin_config_filesize = -1; static int hf_adwin_config_filetime = -1; static int hf_adwin_config_updatetime = -1; static int hf_adwin_config_gateway = -1; static int hf_adwin_config_mac = -1; static int hf_adwin_config_netmask_count = -1; static int hf_adwin_config_netmask = -1; static int hf_adwin_config_password = -1; static int hf_adwin_config_path = -1; static int hf_adwin_config_pattern = -1; static int hf_adwin_config_port16 = -1; static int hf_adwin_config_port32 = -1; static int hf_adwin_config_reboot = -1; static int hf_adwin_config_scan_id = -1; static int hf_adwin_config_reply_broadcast = -1; static int hf_adwin_config_revision = -1; static int hf_adwin_config_processor_type_raw = -1; static int hf_adwin_config_system_type_raw = -1; static int hf_adwin_config_processor_type = -1; static int hf_adwin_config_system_type = -1; static int hf_adwin_config_server_ip = -1; static int hf_adwin_config_server_version = -1; static int hf_adwin_config_server_version_beta = -1; static int hf_adwin_config_socketshutdowns = -1; static int hf_adwin_config_status = -1; static int hf_adwin_config_status_bootloader = -1; static int hf_adwin_config_status_reprogrammable = -1; static int hf_adwin_config_status_configurable = -1; static int hf_adwin_config_status_bootloader_boots = -1; static int hf_adwin_config_status_bootloader_reprogrammable = -1; static int hf_adwin_config_status_bootloader_receive = -1; static int hf_adwin_config_status_bootloader_reprogramming_done = -1; static int hf_adwin_config_status_eeprom_support = -1; static int hf_adwin_config_stream_length = -1; static int hf_adwin_config_eeprom_support = -1; static int hf_adwin_config_timeout = -1; static int hf_adwin_config_timerresets = -1; static int hf_adwin_config_disk_free = -1; static int hf_adwin_config_disk_size = -1; static int hf_adwin_config_unused = -1; static int hf_adwin_config_version = -1; static int hf_adwin_config_xilinx_version = -1; /* Initialize the subtree pointers */ static gint ett_adwin_config = -1; static gint ett_adwin_config_status = -1; static gint ett_adwin_config_debug = -1; static void dissect_UDPStatus(tvbuff_t *tvb, proto_tree *adwin_tree) { proto_tree *debug_tree; proto_item *dt; static int * const status_flags[] = { &hf_adwin_config_status_bootloader, &hf_adwin_config_status_reprogrammable, &hf_adwin_config_status_configurable, &hf_adwin_config_status_bootloader_boots, &hf_adwin_config_status_bootloader_reprogrammable, &hf_adwin_config_status_bootloader_receive, &hf_adwin_config_status_bootloader_reprogramming_done, &hf_adwin_config_status_eeprom_support, NULL }; if (! adwin_tree) return; dt = proto_tree_add_item(adwin_tree, proto_adwin_config, tvb, 0, -1, ENC_NA); debug_tree = proto_item_add_subtree(dt, ett_adwin_config_debug); proto_item_set_text(dt, "ADwin Debug information"); proto_tree_add_item(adwin_tree, hf_adwin_config_pattern, tvb, 0, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_version, tvb, 4, 4, ENC_BIG_ENDIAN); proto_tree_add_bitmask(adwin_tree, tvb, 8, hf_adwin_config_status, ett_adwin_config_status, status_flags, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_server_version_beta, tvb, 12, 2, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_server_version, tvb, 14, 2, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_xilinx_version, tvb, 16, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_mac, tvb, 20, 6, ENC_NA); proto_tree_add_item(debug_tree, hf_adwin_config_unused, tvb, 26, 2, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_port16, tvb, 28, 2, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_dhcp, tvb, 30, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_netmask_count, tvb, 31, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_gateway, tvb, 32, 4, ENC_BIG_ENDIAN); proto_tree_add_item(debug_tree, hf_adwin_config_unused, tvb, 36, 11, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_reply_broadcast, tvb, 47, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_scan_id, tvb, 48, 4, ENC_LITTLE_ENDIAN); } static void dissect_UDPExtStatus(tvbuff_t *tvb, proto_tree *adwin_tree) { const gchar *processor_type, *system_type; if (! adwin_tree) return; proto_tree_add_item(adwin_tree, hf_adwin_config_mac, tvb, 0, 6, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 6, 2, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_pattern, tvb, 8, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_version, tvb, 12, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_description, tvb, 16, 16, ENC_ASCII|ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_timerresets, tvb, 32, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_socketshutdowns, tvb, 36, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_disk_free, tvb, 40, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_disk_size, tvb, 44, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_date, tvb, 48, 8, ENC_ASCII|ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_revision, tvb, 56, 8, ENC_ASCII|ENC_NA); /* add the processor type raw values to the tree, to allow filtering */ proto_tree_add_item(adwin_tree, hf_adwin_config_processor_type_raw, tvb, 64, 2, ENC_ASCII|ENC_NA); /* add the processor type as a pretty printed string */ processor_type = tvb_get_string_enc(wmem_packet_scope(), tvb, 64, 2, ENC_ASCII|ENC_NA); processor_type = str_to_str(processor_type, processor_type_mapping, "Unknown (%s)"); proto_tree_add_string(adwin_tree, hf_adwin_config_processor_type, tvb, 64, 2, processor_type); /* add system type as raw value and pretty printed string */ proto_tree_add_item(adwin_tree, hf_adwin_config_system_type_raw, tvb, 66, 2, ENC_ASCII|ENC_NA); system_type = tvb_get_string_enc(wmem_packet_scope(), tvb, 66, 2, ENC_ASCII|ENC_NA); system_type = str_to_str(system_type, system_type_mapping, "Unknown (%s)"); proto_tree_add_string(adwin_tree, hf_adwin_config_system_type, tvb, 66, 2, system_type); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 68, 364, ENC_NA); } static void dissect_UDPMessage(tvbuff_t *tvb, proto_tree *adwin_tree) { const gchar *processor_type, *system_type; if (! adwin_tree) return; proto_tree_add_item(adwin_tree, hf_adwin_config_command, tvb, 0, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_version, tvb, 4, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_mac, tvb, 8, 6, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 14, 2, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_server_ip, tvb, 16, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 20, 4, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_netmask, tvb, 24, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 28, 4, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_gateway, tvb, 32, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 36, 4, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_dhcp, tvb, 40, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_port32, tvb, 44, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_password, tvb, 48, 10, ENC_ASCII|ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_bootloader, tvb, 58, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 59, 5, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_description, tvb, 64, 16, ENC_ASCII|ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_date, tvb, 80, 8, ENC_ASCII|ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_revision, tvb, 88, 8, ENC_ASCII|ENC_NA); /* add the processor type raw values to the tree, to allow filtering */ proto_tree_add_item(adwin_tree, hf_adwin_config_processor_type_raw, tvb, 96, 2, ENC_ASCII|ENC_NA); /* add the processor type as a pretty printed string */ processor_type = tvb_get_string_enc(wmem_packet_scope(), tvb, 96, 2, ENC_ASCII|ENC_NA); processor_type = str_to_str(processor_type, processor_type_mapping, "Unknown"); proto_tree_add_string(adwin_tree, hf_adwin_config_processor_type, tvb, 96, 2, processor_type); /* add system type as raw value and pretty printed string */ proto_tree_add_item(adwin_tree, hf_adwin_config_system_type_raw, tvb, 98, 2, ENC_ASCII|ENC_NA); system_type = tvb_get_string_enc(wmem_packet_scope(), tvb, 98, 2, ENC_ASCII|ENC_NA); system_type = str_to_str(system_type, system_type_mapping, "Unknown"); proto_tree_add_string(adwin_tree, hf_adwin_config_system_type, tvb, 98, 2, system_type); } static void dissect_UDPInitAck(tvbuff_t *tvb, proto_tree *adwin_tree) { if (! adwin_tree) return; proto_tree_add_item(adwin_tree, hf_adwin_config_pattern, tvb, 0, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_reboot, tvb, 4, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_mac, tvb, 8, 6, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 14, 2, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 16, 80, ENC_NA); } static void dissect_UDPIXP425FlashUpdate(tvbuff_t *tvb, proto_tree *adwin_tree) { if (! adwin_tree) return; proto_tree_add_item(adwin_tree, hf_adwin_config_pattern, tvb, 0, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_version, tvb, 4, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_scan_id, tvb, 8, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_status, tvb, 12, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_timeout, tvb, 16, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_filename, tvb, 20, 24, ENC_ASCII|ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_mac, tvb, 44, 6, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, 50, 42, ENC_NA); } static void dissect_UDPOut(tvbuff_t *tvb, proto_tree *adwin_tree) { if (! adwin_tree) return; proto_tree_add_item(adwin_tree, hf_adwin_config_status, tvb, 0, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_mac, tvb, 4, 6, ENC_NA); proto_tree_add_item(adwin_tree, hf_adwin_config_netmask, tvb, 10, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_gateway, tvb, 14, 4, ENC_BIG_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_dhcp, tvb, 18, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(adwin_tree, hf_adwin_config_port16, tvb, 20, 2, ENC_BIG_ENDIAN); } static guint get_adwin_TCPUpdate_len(packet_info *pinfo _U_, tvbuff_t *tvb, int offset, void *data _U_) { /* * Return the length of the packet. (Doesn't include the length field itself) */ return tvb_get_ntohl(tvb, offset); } static int dissect_TCPFlashUpdate(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_) { proto_tree *adwin_tree; proto_item *ti; gint length, offset; guint8 *filename; col_set_str(pinfo->cinfo, COL_PROTOCOL, "ADwin Config"); col_set_str(pinfo->cinfo, COL_INFO, "TCPFlashUpdate"); ti = proto_tree_add_item(tree, proto_adwin_config, tvb, 0, -1, ENC_NA); adwin_tree = proto_item_add_subtree(ti, ett_adwin_config); proto_tree_add_item(adwin_tree, hf_adwin_config_stream_length, tvb, 0, 4, ENC_BIG_ENDIAN); offset = 4; length = tvb_strnlen(tvb, offset, -1) + 1; filename = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, length, ENC_ASCII|ENC_NA); if (strncmp(filename, "eeprom_on", length) == 0) { proto_tree_add_boolean(adwin_tree, hf_adwin_config_eeprom_support, tvb, offset, length, TRUE); return offset+length; } if (strncmp(filename, "eeprom_off", length) == 0) { proto_tree_add_boolean(adwin_tree, hf_adwin_config_eeprom_support, tvb, offset, length, FALSE); return offset+length; } proto_tree_add_item(adwin_tree, hf_adwin_config_filename, tvb, 4, length, ENC_ASCII|ENC_NA); offset += length; length = tvb_strnlen(tvb, 4 + length, -1) + 1; proto_tree_add_item(adwin_tree, hf_adwin_config_path, tvb, offset, length, ENC_ASCII|ENC_NA); offset += length; proto_tree_add_item(adwin_tree, hf_adwin_config_filesize, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; proto_tree_add_item(adwin_tree, hf_adwin_config_filetime, tvb, offset, 4, ENC_TIME_SECS|ENC_BIG_ENDIAN); offset += 4; proto_tree_add_item(adwin_tree, hf_adwin_config_updatetime, tvb, offset, 4, ENC_TIME_SECS|ENC_BIG_ENDIAN); offset += 4; proto_tree_add_item(adwin_tree, hf_adwin_config_unused, tvb, offset, 128, ENC_NA); offset += 128; length = tvb_captured_length_remaining(tvb, offset); proto_tree_add_item(adwin_tree, hf_adwin_config_data, tvb, offset, length, ENC_NA); return tvb_captured_length(tvb); } /* 00:50:c2:0a:2*:** */ static const unsigned char mac_iab_start[] = { 0x00, 0x50, 0xc2, 0x0a, 0x20, 0x00 }; static const unsigned char mac_iab_end[] = { 0x00, 0x50, 0xc2, 0x0a, 0x2f, 0xff }; /* 00:22:71:**:**:** */ static const unsigned char mac_oui_start[] = { 0x00, 0x22, 0x71, 0x00, 0x00, 0x00 }; static const unsigned char mac_oui_end[] = { 0x00, 0x22, 0x71, 0xff, 0xff, 0xff }; /* ff:ff:ff:ff:ff:ff */ static const unsigned char mac_broadcast[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; /* return TRUE if mac is in mac address range assigned to ADwin or if * mac is broadcast */ static gboolean is_adwin_mac_or_broadcast(address mac) { if (mac.type != AT_ETHER) return FALSE; if (mac.len != 6) /* length of MAC address */ return FALSE; if ((memcmp(mac.data, mac_iab_start, mac.len) >= 0) && (memcmp(mac.data, mac_iab_end , mac.len) <= 0)) return TRUE; if ((memcmp(mac.data, mac_oui_start, mac.len) >= 0) && (memcmp(mac.data, mac_oui_end, mac.len) <= 0)) return TRUE; /* adwin configuration protocol uses MAC broadcasts for device discovery */ if (memcmp(mac.data, mac_broadcast, mac.len) == 0) return TRUE; return FALSE; } /* Here we determine which type of packet is sent by looking at its size. Let's hope that future ADwin packets always differ in size. They probably will, since the server classifies the packets according to their sizes, too. */ static const value_string length_mapping[] = { { UDPStatusLENGTH, "UDPStatus" }, { UDPExtStatusLENGTH, "UDPExtStatus" }, { UDPMessageLENGTH, "UDPMessage" }, { UDPMessageLENGTH_wrong, "UDPMessage (broken - upgrade ADConfig!)" }, { UDPInitAckLENGTH, "UDPInitAck" }, { UDPIXP425FlashUpdateLENGTH, "UDPIXP425FlashUpdate" }, { UDPOutLENGTH, "UDPOut" }, { 0, NULL }, }; static int dissect_adwin_config_udp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) { proto_item *ti; proto_tree *adwin_config_tree; guint32 length; length = tvb_reported_length(tvb); if (!(length == UDPStatusLENGTH || length == UDPExtStatusLENGTH || length == UDPMessageLENGTH || length == UDPMessageLENGTH_wrong || length == UDPInitAckLENGTH || length == UDPIXP425FlashUpdateLENGTH || length == UDPOutLENGTH)) return 0; if (! (is_adwin_mac_or_broadcast(pinfo->dl_src) || is_adwin_mac_or_broadcast(pinfo->dl_dst))) return 0; col_set_str(pinfo->cinfo, COL_PROTOCOL, "ADwin Config"); col_clear(pinfo->cinfo, COL_INFO); ti = proto_tree_add_item(tree, proto_adwin_config, tvb, 0, -1, ENC_NA); adwin_config_tree = proto_item_add_subtree(ti, ett_adwin_config); switch (length) { case UDPStatusLENGTH: dissect_UDPStatus(tvb, adwin_config_tree); break; case UDPExtStatusLENGTH: dissect_UDPExtStatus(tvb, adwin_config_tree); break; case UDPMessageLENGTH: dissect_UDPMessage(tvb, adwin_config_tree); break; case UDPMessageLENGTH_wrong: /* incorrect packet length */ /* formerly used by adconfig */ dissect_UDPMessage(tvb, adwin_config_tree); break; case UDPInitAckLENGTH: dissect_UDPInitAck(tvb, adwin_config_tree); break; case UDPIXP425FlashUpdateLENGTH: dissect_UDPIXP425FlashUpdate(tvb, adwin_config_tree); break; case UDPOutLENGTH: dissect_UDPOut(tvb, adwin_config_tree); break; default: /* Heuristics above should mean we never get here */ col_add_str(pinfo->cinfo, COL_INFO, val_to_str(length, length_mapping, "Unknown ADwin Configuration packet, length: %d")); } return (tvb_reported_length(tvb)); } static int dissect_adwin_config_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) { if(!(pinfo->srcport == ADWIN_CONFIGURATION_PORT || pinfo->destport == ADWIN_CONFIGURATION_PORT)) return 0; /* XXX - Is this possible for TCP? */ if (! (is_adwin_mac_or_broadcast(pinfo->dl_src) || is_adwin_mac_or_broadcast(pinfo->dl_dst))) return 0; tcp_dissect_pdus(tvb, pinfo, tree, 1, 4, get_adwin_TCPUpdate_len, dissect_TCPFlashUpdate, NULL); return (tvb_reported_length(tvb)); } void proto_register_adwin_config(void) { static hf_register_info hf[] = { { &hf_adwin_config_bootloader, { "Enable Bootloader", "adwin_config.bootloader", FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_command, { "Command", "adwin_config.command", FT_UINT32, BASE_DEC, VALS(config_command_mapping), 0x0, NULL, HFILL } }, { &hf_adwin_config_data, { "Data", "adwin_config.data", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_date, { "Date", "adwin_config.date", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_description, { "Description", "adwin_config.description", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_dhcp, { "DHCP enabled", "adwin_config.dhcp", FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_filename, { "File name", "adwin_config.filename", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_filesize, { "File size", "adwin_config.filesize", FT_INT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_filetime, { "File time", "adwin_config.filetime", FT_ABSOLUTE_TIME, ABSOLUTE_TIME_LOCAL, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_updatetime, { "Update time", "adwin_config.updatetime", FT_ABSOLUTE_TIME, ABSOLUTE_TIME_LOCAL, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_gateway, { "Gateway IP", "adwin_config.gateway", FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_mac, { "MAC address", "adwin_config.mac", FT_ETHER, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_netmask, { "Netmask", "adwin_config.netmask", FT_IPv4, BASE_NETMASK, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_netmask_count, { "Netmask count", "adwin_config.netmask_count", FT_UINT8, BASE_DEC, NULL, 0x0, "The number of binary ones in the netmask.", HFILL } }, { &hf_adwin_config_password, { "Password", "adwin_config.password", FT_STRING, BASE_NONE, NULL, 0x0, "Password to set for ADwin system.", HFILL } }, { &hf_adwin_config_pattern, { "Pattern", "adwin_config.pattern", FT_UINT32, BASE_HEX, VALS(pattern_mapping), 0x0, NULL, HFILL } }, { &hf_adwin_config_path, { "Path", "adwin_config.path", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_port16, { "Port (16bit)", "adwin_config.port", FT_UINT16, BASE_DEC, NULL, 0x0, "The server port on which the ADwin system is listening on (16bit).", HFILL } }, { &hf_adwin_config_port32, { "Port (32bit)", "adwin_config.port", FT_UINT32, BASE_DEC, NULL, 0x0, "The server port on which the ADwin system is listening on (32bit).", HFILL } }, { &hf_adwin_config_reboot, { "Reboot", "adwin_config.reboot", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "Number of system reboots.", HFILL } }, { &hf_adwin_config_scan_id, { "Scan ID", "adwin_config.scan_id", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_reply_broadcast, /* send_normal in UDPStatus */ { "Reply with broadcast", "adwin_config.reply_broadcast", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "If this bit is set, the scanned system should reply with a broadcast.", HFILL } }, { &hf_adwin_config_revision, { "Revision", "adwin_config.revision", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_processor_type_raw, { "Processor Type (Raw value)", "adwin_config.processor_type_raw", FT_STRING, BASE_NONE, NULL, 0x0, "The DSP processor type of the ADwin system, e.g. T9, T10 or T11.", HFILL } }, { &hf_adwin_config_system_type_raw, { "System Type (Raw value)", "adwin_config.system_type_raw", FT_STRING, BASE_NONE, NULL, 0x0, "The system type of the ADwin system, e.g. Gold, Pro or Light.", HFILL } }, { &hf_adwin_config_processor_type, { "Processor Type", "adwin_config.processor_type", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_system_type, { "System Type", "adwin_config.system_type", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_server_ip, { "Server IP", "adwin_config.server_ip", FT_IPv4, BASE_NONE, NULL, 0x0, "In scan replies, this is the current IP address of the ADwin system. In configuration packets, this is the new IP to be used by the ADwin system.", HFILL } }, { &hf_adwin_config_server_version, { "Server version", "adwin_config.server_version", FT_UINT32, BASE_DEC, NULL, 0x0, "The version number of the server program. This number represents the complete firmware version, e.g. 2.74.", HFILL } }, { &hf_adwin_config_server_version_beta, { "server version (beta part)", "adwin_config.server_version_beta", FT_UINT32, BASE_DEC, NULL, 0x0, "A non-zero value of this field indicates a beta firmware version, where this number represents the current revision.", HFILL } }, { &hf_adwin_config_socketshutdowns, { "Socket shutdowns", "adwin_config.socketshutdowns", FT_UINT32, BASE_DEC, NULL, 0x0, "Number of socket errors that lead to a recreation of the socket (ethernet interface version 1 only).", HFILL } }, { &hf_adwin_config_status, { "Status", "adwin_config.status", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_status_bootloader, { "Status Bootloader", "adwin_config.status_bootloader", FT_BOOLEAN, 32, NULL, STATUS_WITH_BOOTLOADER, "Indicates if the ADwin system has bootloader capabilities.", HFILL } }, { &hf_adwin_config_status_reprogrammable, { "Status Reprogrammable", "adwin_config.status_reprogrammable", FT_BOOLEAN, 32, NULL, STATUS_REPROGRAMMABLE, NULL, HFILL } }, { &hf_adwin_config_status_configurable, { "Status Configurable", "adwin_config.status_configurable", FT_BOOLEAN, 32, NULL, STATUS_CONFIGURABLE, NULL, HFILL } }, { &hf_adwin_config_status_bootloader_boots, { "Status Bootloader boots", "adwin_config.status_bootloader_boots", FT_BOOLEAN, 32, NULL, STATUS_BOOTLOADER_BOOTS, NULL, HFILL } }, { &hf_adwin_config_status_bootloader_reprogrammable, { "Status Bootloader reprogrammable", "adwin_config.status_bootloader_reprogrammable", FT_BOOLEAN, 32, NULL, STATUS_BOOTLOADER_REPROGRAMMABLE, NULL, HFILL } }, { &hf_adwin_config_status_bootloader_receive, { "Status Bootloader receive", "adwin_config.status_bootloader_receive", FT_BOOLEAN, 32, NULL, STATUS_BOOTLOADER_RECEIVES_DATA, NULL, HFILL } }, { &hf_adwin_config_status_bootloader_reprogramming_done, { "Status Bootloader reprogramming done", "adwin_config.status_bootloader_reprogramming_done", FT_BOOLEAN, 32, NULL, STATUS_BOOTLOADER_REPROGRAMMING_DONE, NULL, HFILL } }, { &hf_adwin_config_status_eeprom_support, { "Status EEPROM Support", "adwin_config.status_eeprom_support", FT_BOOLEAN, 32, NULL, STATUS_WITH_EEPROM_SUPPORT, NULL, HFILL } }, { &hf_adwin_config_stream_length, { "Stream length", "adwin_config.stream_length", FT_INT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_eeprom_support, { "EEPROM Support", "adwin_config.eeprom_support", FT_BOOLEAN, BASE_NONE, TFS(&tfs_enabled_disabled), 0x0, NULL, HFILL } }, { &hf_adwin_config_timeout, { "Timeout", "adwin_config.timeout", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_timerresets, { "Timer resets", "adwin_config.timerresets", FT_UINT32, BASE_DEC, NULL, 0x0, "Counter for resets of the timer (ethernet interface version 1 only).", HFILL } }, { &hf_adwin_config_disk_free, { "Free disk space (kb)", "adwin_config.disk_free", FT_UINT32, BASE_DEC, NULL, 0x0, "Free disk space in kb on flash (ethernet interface version 2 only).", HFILL } }, { &hf_adwin_config_disk_size, { "Disk size (kb)", "adwin_config.disk_size", FT_UINT32, BASE_DEC, NULL, 0x0, "Flash disk size in kb (ethernet interface version 2 only).", HFILL } }, { &hf_adwin_config_unused, { "Unused", "adwin_config.unused", FT_NONE, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_version, { "Version", "adwin_config.version", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_adwin_config_xilinx_version, { "XILINX Version", "adwin_config.xilinx_version", FT_UINT32, BASE_HEX, NULL, 0x0, "Version of XILINX program", HFILL } }, }; /* Setup protocol subtree array */ static gint *ett[] = { &ett_adwin_config, &ett_adwin_config_status, &ett_adwin_config_debug, }; /* Register the protocol name and description */ proto_adwin_config = proto_register_protocol("ADwin configuration protocol", "ADwin-Config", "adwin_config"); /* Required function calls to register the header fields and subtrees used */ proto_register_field_array(proto_adwin_config, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); } void proto_reg_handoff_adwin_config(void) { heur_dissector_add("udp", dissect_adwin_config_udp, "ADwin-Config over UDP", "adwin_config_udp", proto_adwin_config, HEURISTIC_ENABLE); heur_dissector_add("tcp", dissect_adwin_config_tcp, "ADwin-Config over TCP", "adwin_config_tcp", proto_adwin_config, HEURISTIC_ENABLE); } /* * Editor modelines - https://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
zzqcn/wireshark
epan/dissectors/packet-adwin-config.c
C
gpl-2.0
30,208
/* * drivers/base/power/main.c - Where the driver meets power management. * * Copyright (c) 2003 Patrick Mochel * Copyright (c) 2003 Open Source Development Lab * * This file is released under the GPLv2 * * * The driver model core calls device_pm_add() when a device is registered. * This will intialize the embedded device_pm_info object in the device * and add it to the list of power-controlled devices. sysfs entries for * controlling device power management will also be added. * * A separate list is used for keeping track of power info, because the power * domain dependencies may differ from the ancestral dependencies that the * subsystem list maintains. */ #include <linux/device.h> #include <linux/kallsyms.h> #include <linux/mutex.h> #include <linux/pm.h> #include <linux/pm_runtime.h> #include <linux/resume-trace.h> #include <linux/interrupt.h> #include <linux/sched.h> #include <linux/async.h> #include <linux/timer.h> #include "../base.h" #include "power.h" /* * The entries in the dpm_list list are in a depth first order, simply * because children are guaranteed to be discovered after parents, and * are inserted at the back of the list on discovery. * * Since device_pm_add() may be called with a device lock held, * we must never try to acquire a device lock while holding * dpm_list_mutex. */ LIST_HEAD(dpm_list); static DEFINE_MUTEX(dpm_list_mtx); static pm_message_t pm_transition; static struct task_struct *suspend_task = NULL; static void dpm_drv_timeout(unsigned long data); static DEFINE_TIMER(dpm_drv_wd, dpm_drv_timeout, 0, 0); /* * Set once the preparation of devices for a PM transition has started, reset * before starting to resume devices. Protected by dpm_list_mtx. */ static bool transition_started; /** * device_pm_init - Initialize the PM-related part of a device object. * @dev: Device object being initialized. */ void device_pm_init(struct device *dev) { dev->power.status = DPM_ON; init_completion(&dev->power.completion); complete_all(&dev->power.completion); pm_runtime_init(dev); } /** * device_pm_lock - Lock the list of active devices used by the PM core. */ void device_pm_lock(void) { mutex_lock(&dpm_list_mtx); } /** * device_pm_unlock - Unlock the list of active devices used by the PM core. */ void device_pm_unlock(void) { mutex_unlock(&dpm_list_mtx); } /** * device_pm_add - Add a device to the PM core's list of active devices. * @dev: Device to add to the list. */ void device_pm_add(struct device *dev) { pr_debug("PM: Adding info for %s:%s\n", dev->bus ? dev->bus->name : "No Bus", kobject_name(&dev->kobj)); mutex_lock(&dpm_list_mtx); if (dev->parent) { if (dev->parent->power.status >= DPM_SUSPENDING) dev_warn(dev, "parent %s should not be sleeping\n", dev_name(dev->parent)); } else if (transition_started) { /* * We refuse to register parentless devices while a PM * transition is in progress in order to avoid leaving them * unhandled down the road */ dev_WARN(dev, "Parentless device registered during a PM transaction\n"); } list_add_tail(&dev->power.entry, &dpm_list); mutex_unlock(&dpm_list_mtx); } /** * device_pm_remove - Remove a device from the PM core's list of active devices. * @dev: Device to be removed from the list. */ void device_pm_remove(struct device *dev) { pr_debug("PM: Removing info for %s:%s\n", dev->bus ? dev->bus->name : "No Bus", kobject_name(&dev->kobj)); complete_all(&dev->power.completion); mutex_lock(&dpm_list_mtx); list_del_init(&dev->power.entry); mutex_unlock(&dpm_list_mtx); pm_runtime_remove(dev); } /** * device_pm_move_before - Move device in the PM core's list of active devices. * @deva: Device to move in dpm_list. * @devb: Device @deva should come before. */ void device_pm_move_before(struct device *deva, struct device *devb) { pr_debug("PM: Moving %s:%s before %s:%s\n", deva->bus ? deva->bus->name : "No Bus", kobject_name(&deva->kobj), devb->bus ? devb->bus->name : "No Bus", kobject_name(&devb->kobj)); /* Delete deva from dpm_list and reinsert before devb. */ list_move_tail(&deva->power.entry, &devb->power.entry); } /** * device_pm_move_after - Move device in the PM core's list of active devices. * @deva: Device to move in dpm_list. * @devb: Device @deva should come after. */ void device_pm_move_after(struct device *deva, struct device *devb) { pr_debug("PM: Moving %s:%s after %s:%s\n", deva->bus ? deva->bus->name : "No Bus", kobject_name(&deva->kobj), devb->bus ? devb->bus->name : "No Bus", kobject_name(&devb->kobj)); /* Delete deva from dpm_list and reinsert after devb. */ list_move(&deva->power.entry, &devb->power.entry); } /** * device_pm_move_last - Move device to end of the PM core's list of devices. * @dev: Device to move in dpm_list. */ void device_pm_move_last(struct device *dev) { pr_debug("PM: Moving %s:%s to end of list\n", dev->bus ? dev->bus->name : "No Bus", kobject_name(&dev->kobj)); list_move_tail(&dev->power.entry, &dpm_list); } static ktime_t initcall_debug_start(struct device *dev) { ktime_t calltime = ktime_set(0, 0); if (initcall_debug) { pr_info("calling %s+ @ %i\n", dev_name(dev), task_pid_nr(current)); calltime = ktime_get(); } return calltime; } static void initcall_debug_report(struct device *dev, ktime_t calltime, int error) { ktime_t delta, rettime; if (initcall_debug) { rettime = ktime_get(); delta = ktime_sub(rettime, calltime); pr_info("call %s+ returned %d after %Ld usecs\n", dev_name(dev), error, (unsigned long long)ktime_to_ns(delta) >> 10); } } /** * dpm_wait - Wait for a PM operation to complete. * @dev: Device to wait for. * @async: If unset, wait only if the device's power.async_suspend flag is set. */ static void dpm_wait(struct device *dev, bool async) { if (!dev) return; if (async || (pm_async_enabled && dev->power.async_suspend)) wait_for_completion(&dev->power.completion); } static int dpm_wait_fn(struct device *dev, void *async_ptr) { dpm_wait(dev, *((bool *)async_ptr)); return 0; } static void dpm_wait_for_children(struct device *dev, bool async) { device_for_each_child(dev, &async, dpm_wait_fn); } /** * pm_op - Execute the PM operation appropriate for given PM event. * @dev: Device to handle. * @ops: PM operations to choose from. * @state: PM transition of the system being carried out. */ static int pm_op(struct device *dev, const struct dev_pm_ops *ops, pm_message_t state) { int error = 0; ktime_t calltime; calltime = initcall_debug_start(dev); switch (state.event) { #ifdef CONFIG_SUSPEND case PM_EVENT_SUSPEND: if (ops->suspend) { error = ops->suspend(dev); suspend_report_result(ops->suspend, error); } break; case PM_EVENT_RESUME: if (ops->resume) { error = ops->resume(dev); suspend_report_result(ops->resume, error); } break; #endif /* CONFIG_SUSPEND */ #ifdef CONFIG_HIBERNATION case PM_EVENT_FREEZE: case PM_EVENT_QUIESCE: if (ops->freeze) { error = ops->freeze(dev); suspend_report_result(ops->freeze, error); } break; case PM_EVENT_HIBERNATE: if (ops->poweroff) { error = ops->poweroff(dev); suspend_report_result(ops->poweroff, error); } break; case PM_EVENT_THAW: case PM_EVENT_RECOVER: if (ops->thaw) { error = ops->thaw(dev); suspend_report_result(ops->thaw, error); } break; case PM_EVENT_RESTORE: if (ops->restore) { error = ops->restore(dev); suspend_report_result(ops->restore, error); } break; #endif /* CONFIG_HIBERNATION */ default: error = -EINVAL; } initcall_debug_report(dev, calltime, error); return error; } /** * pm_noirq_op - Execute the PM operation appropriate for given PM event. * @dev: Device to handle. * @ops: PM operations to choose from. * @state: PM transition of the system being carried out. * * The driver of @dev will not receive interrupts while this function is being * executed. */ static int pm_noirq_op(struct device *dev, const struct dev_pm_ops *ops, pm_message_t state) { int error = 0; ktime_t calltime, delta, rettime; if (initcall_debug) { pr_info("calling %s+ @ %i, parent: %s\n", dev_name(dev), task_pid_nr(current), dev->parent ? dev_name(dev->parent) : "none"); calltime = ktime_get(); } switch (state.event) { #ifdef CONFIG_SUSPEND case PM_EVENT_SUSPEND: if (ops->suspend_noirq) { error = ops->suspend_noirq(dev); suspend_report_result(ops->suspend_noirq, error); } break; case PM_EVENT_RESUME: if (ops->resume_noirq) { error = ops->resume_noirq(dev); suspend_report_result(ops->resume_noirq, error); } break; #endif /* CONFIG_SUSPEND */ #ifdef CONFIG_HIBERNATION case PM_EVENT_FREEZE: case PM_EVENT_QUIESCE: if (ops->freeze_noirq) { error = ops->freeze_noirq(dev); suspend_report_result(ops->freeze_noirq, error); } break; case PM_EVENT_HIBERNATE: if (ops->poweroff_noirq) { error = ops->poweroff_noirq(dev); suspend_report_result(ops->poweroff_noirq, error); } break; case PM_EVENT_THAW: case PM_EVENT_RECOVER: if (ops->thaw_noirq) { error = ops->thaw_noirq(dev); suspend_report_result(ops->thaw_noirq, error); } break; case PM_EVENT_RESTORE: if (ops->restore_noirq) { error = ops->restore_noirq(dev); suspend_report_result(ops->restore_noirq, error); } break; #endif /* CONFIG_HIBERNATION */ default: error = -EINVAL; } if (initcall_debug) { rettime = ktime_get(); delta = ktime_sub(rettime, calltime); printk("initcall %s_i+ returned %d after %Ld usecs\n", dev_name(dev), error, (unsigned long long)ktime_to_ns(delta) >> 10); } return error; } static char *pm_verb(int event) { switch (event) { case PM_EVENT_SUSPEND: return "suspend"; case PM_EVENT_RESUME: return "resume"; case PM_EVENT_FREEZE: return "freeze"; case PM_EVENT_QUIESCE: return "quiesce"; case PM_EVENT_HIBERNATE: return "hibernate"; case PM_EVENT_THAW: return "thaw"; case PM_EVENT_RESTORE: return "restore"; case PM_EVENT_RECOVER: return "recover"; default: return "(unknown PM event)"; } } static void pm_dev_dbg(struct device *dev, pm_message_t state, char *info) { dev_dbg(dev, "%s%s%s\n", info, pm_verb(state.event), ((state.event & PM_EVENT_SLEEP) && device_may_wakeup(dev)) ? ", may wakeup" : ""); } static void pm_dev_err(struct device *dev, pm_message_t state, char *info, int error) { printk(KERN_ERR "PM: Device %s failed to %s%s: error %d\n", kobject_name(&dev->kobj), pm_verb(state.event), info, error); } static void dpm_show_time(ktime_t starttime, pm_message_t state, char *info) { ktime_t calltime; s64 usecs64; int usecs; calltime = ktime_get(); usecs64 = ktime_to_ns(ktime_sub(calltime, starttime)); do_div(usecs64, NSEC_PER_USEC); usecs = usecs64; if (usecs == 0) usecs = 1; pr_info("PM: %s%s%s of devices complete after %ld.%03ld msecs\n", info ?: "", info ? " " : "", pm_verb(state.event), usecs / USEC_PER_MSEC, usecs % USEC_PER_MSEC); } /*------------------------- Resume routines -------------------------*/ /** * device_resume_noirq - Execute an "early resume" callback for given device. * @dev: Device to handle. * @state: PM transition of the system being carried out. * * The driver of @dev will not receive interrupts while this function is being * executed. */ static int device_resume_noirq(struct device *dev, pm_message_t state) { int error = 0; TRACE_DEVICE(dev); TRACE_RESUME(0); if (dev->bus && dev->bus->pm) { pm_dev_dbg(dev, state, "EARLY "); error = pm_noirq_op(dev, dev->bus->pm, state); if (error) goto End; } if (dev->type && dev->type->pm) { pm_dev_dbg(dev, state, "EARLY type "); error = pm_noirq_op(dev, dev->type->pm, state); if (error) goto End; } if (dev->class && dev->class->pm) { pm_dev_dbg(dev, state, "EARLY class "); error = pm_noirq_op(dev, dev->class->pm, state); } End: TRACE_RESUME(error); return error; } /** * dpm_resume_noirq - Execute "early resume" callbacks for non-sysdev devices. * @state: PM transition of the system being carried out. * * Call the "noirq" resume handlers for all devices marked as DPM_OFF_IRQ and * enable device drivers to receive interrupts. */ void dpm_resume_noirq(pm_message_t state) { struct device *dev; ktime_t starttime = ktime_get(); mutex_lock(&dpm_list_mtx); transition_started = false; list_for_each_entry(dev, &dpm_list, power.entry) if (dev->power.status > DPM_OFF) { int error; dev->power.status = DPM_OFF; error = device_resume_noirq(dev, state); if (error) pm_dev_err(dev, state, " early", error); } mutex_unlock(&dpm_list_mtx); dpm_show_time(starttime, state, "early"); resume_device_irqs(); } EXPORT_SYMBOL_GPL(dpm_resume_noirq); /** * legacy_resume - Execute a legacy (bus or class) resume callback for device. * @dev: Device to resume. * @cb: Resume callback to execute. */ static int legacy_resume(struct device *dev, int (*cb)(struct device *dev)) { int error; ktime_t calltime; calltime = initcall_debug_start(dev); error = cb(dev); suspend_report_result(cb, error); initcall_debug_report(dev, calltime, error); return error; } /** * device_resume - Execute "resume" callbacks for given device. * @dev: Device to handle. * @state: PM transition of the system being carried out. * @async: If true, the device is being resumed asynchronously. */ static int device_resume(struct device *dev, pm_message_t state, bool async) { int error = 0; TRACE_DEVICE(dev); TRACE_RESUME(0); if (dev->parent && dev->parent->power.status >= DPM_OFF) dpm_wait(dev->parent, async); device_lock(dev); dev->power.status = DPM_RESUMING; if (dev->bus) { if (dev->bus->pm) { pm_dev_dbg(dev, state, ""); error = pm_op(dev, dev->bus->pm, state); } else if (dev->bus->resume) { pm_dev_dbg(dev, state, "legacy "); error = legacy_resume(dev, dev->bus->resume); } if (error) goto End; } if (dev->type) { if (dev->type->pm) { pm_dev_dbg(dev, state, "type "); error = pm_op(dev, dev->type->pm, state); } if (error) goto End; } if (dev->class) { if (dev->class->pm) { pm_dev_dbg(dev, state, "class "); error = pm_op(dev, dev->class->pm, state); } else if (dev->class->resume) { pm_dev_dbg(dev, state, "legacy class "); error = legacy_resume(dev, dev->class->resume); } } End: device_unlock(dev); complete_all(&dev->power.completion); TRACE_RESUME(error); return error; } static void async_resume(void *data, async_cookie_t cookie) { struct device *dev = (struct device *)data; int error; error = device_resume(dev, pm_transition, true); if (error) pm_dev_err(dev, pm_transition, " async", error); put_device(dev); } static bool is_async(struct device *dev) { return dev->power.async_suspend && pm_async_enabled && !pm_trace_is_enabled(); } #define SMEM_LOG_ITEM_PRINT_SIZE 160 #define SMEM_LOG_NUM_ENTRIES 2000 #define EVENTS_PRINT_SIZE \ (SMEM_LOG_ITEM_PRINT_SIZE * SMEM_LOG_NUM_ENTRIES) int debug_dump_sym(char *buf, int max, uint32_t cont); void smd_restart_modem(struct work_struct *work); void rpc_zdelay_work_func(struct work_struct *work); static char debug_buffer[EVENTS_PRINT_SIZE]; #define PRINTK_BUFF_SIZE 1024 /** * dpm_drv_timeout - Driver suspend / resume watchdog handler * @data: struct device which timed out * * Called when a driver has timed out suspending or resuming. * There's not much we can do here to recover so * BUG() out for a crash-dump * */ static void dpm_drv_timeout(unsigned long data) { struct device *dev = (struct device *) data; printk(KERN_EMERG "**** DPM device timeout: %s (%s)\n", dev_name(dev), (dev->driver ? dev->driver->name : "no driver")); if (suspend_task) show_stack(suspend_task, NULL); { int dump_loop; char* dump_ptr = debug_buffer; rpc_zdelay_work_func(NULL); #if 0 debug_dump_sym(debug_buffer, EVENTS_PRINT_SIZE, 0); for (dump_loop = 0; dump_loop < (EVENTS_PRINT_SIZE / PRINTK_BUFF_SIZE); dump_loop++) { printk("%s", dump_ptr); dump_ptr += PRINTK_BUFF_SIZE; } #endif } #if 0 smd_restart_modem(NULL); #endif BUG(); } /** * dpm_drv_wdset - Sets up driver suspend/resume watchdog timer. * @dev: struct device which we're guarding. * */ static void dpm_drv_wdset(struct device *dev) { dpm_drv_wd.data = (unsigned long) dev; mod_timer(&dpm_drv_wd, jiffies + (HZ * 10)); } /** * dpm_drv_wdclr - clears driver suspend/resume watchdog timer. * @dev: struct device which we're no longer guarding. * */ static void dpm_drv_wdclr(struct device *dev) { del_timer_sync(&dpm_drv_wd); } /** * dpm_resume - Execute "resume" callbacks for non-sysdev devices. * @state: PM transition of the system being carried out. * * Execute the appropriate "resume" callback for all devices whose status * indicates that they are suspended. */ static void dpm_resume(pm_message_t state) { struct list_head list; struct device *dev; ktime_t starttime = ktime_get(); INIT_LIST_HEAD(&list); mutex_lock(&dpm_list_mtx); pm_transition = state; list_for_each_entry(dev, &dpm_list, power.entry) { if (dev->power.status < DPM_OFF) continue; INIT_COMPLETION(dev->power.completion); if (is_async(dev)) { get_device(dev); async_schedule(async_resume, dev); } } while (!list_empty(&dpm_list)) { dev = to_device(dpm_list.next); get_device(dev); if (dev->power.status >= DPM_OFF && !is_async(dev)) { int error; mutex_unlock(&dpm_list_mtx); error = device_resume(dev, state, false); mutex_lock(&dpm_list_mtx); if (error) pm_dev_err(dev, state, "", error); } else if (dev->power.status == DPM_SUSPENDING) { /* Allow new children of the device to be registered */ dev->power.status = DPM_RESUMING; } if (!list_empty(&dev->power.entry)) list_move_tail(&dev->power.entry, &list); put_device(dev); } list_splice(&list, &dpm_list); mutex_unlock(&dpm_list_mtx); async_synchronize_full(); dpm_show_time(starttime, state, NULL); } /** * device_complete - Complete a PM transition for given device. * @dev: Device to handle. * @state: PM transition of the system being carried out. */ static void device_complete(struct device *dev, pm_message_t state) { device_lock(dev); if (dev->class && dev->class->pm && dev->class->pm->complete) { pm_dev_dbg(dev, state, "completing class "); dev->class->pm->complete(dev); } if (dev->type && dev->type->pm && dev->type->pm->complete) { pm_dev_dbg(dev, state, "completing type "); dev->type->pm->complete(dev); } if (dev->bus && dev->bus->pm && dev->bus->pm->complete) { pm_dev_dbg(dev, state, "completing "); dev->bus->pm->complete(dev); } device_unlock(dev); } /** * dpm_complete - Complete a PM transition for all non-sysdev devices. * @state: PM transition of the system being carried out. * * Execute the ->complete() callbacks for all devices whose PM status is not * DPM_ON (this allows new devices to be registered). */ static void dpm_complete(pm_message_t state) { struct list_head list; INIT_LIST_HEAD(&list); mutex_lock(&dpm_list_mtx); transition_started = false; while (!list_empty(&dpm_list)) { struct device *dev = to_device(dpm_list.prev); get_device(dev); if (dev->power.status > DPM_ON) { dev->power.status = DPM_ON; mutex_unlock(&dpm_list_mtx); device_complete(dev, state); pm_runtime_put_sync(dev); mutex_lock(&dpm_list_mtx); } if (!list_empty(&dev->power.entry)) list_move(&dev->power.entry, &list); put_device(dev); } list_splice(&list, &dpm_list); mutex_unlock(&dpm_list_mtx); } /** * dpm_resume_end - Execute "resume" callbacks and complete system transition. * @state: PM transition of the system being carried out. * * Execute "resume" callbacks for all devices and complete the PM transition of * the system. */ void dpm_resume_end(pm_message_t state) { might_sleep(); dpm_resume(state); dpm_complete(state); } EXPORT_SYMBOL_GPL(dpm_resume_end); /*------------------------- Suspend routines -------------------------*/ /** * resume_event - Return a "resume" message for given "suspend" sleep state. * @sleep_state: PM message representing a sleep state. * * Return a PM message representing the resume event corresponding to given * sleep state. */ static pm_message_t resume_event(pm_message_t sleep_state) { switch (sleep_state.event) { case PM_EVENT_SUSPEND: return PMSG_RESUME; case PM_EVENT_FREEZE: case PM_EVENT_QUIESCE: return PMSG_RECOVER; case PM_EVENT_HIBERNATE: return PMSG_RESTORE; } return PMSG_ON; } /** * device_suspend_noirq - Execute a "late suspend" callback for given device. * @dev: Device to handle. * @state: PM transition of the system being carried out. * * The driver of @dev will not receive interrupts while this function is being * executed. */ static int device_suspend_noirq(struct device *dev, pm_message_t state) { int error = 0; if (dev->class && dev->class->pm) { pm_dev_dbg(dev, state, "LATE class "); error = pm_noirq_op(dev, dev->class->pm, state); if (error) goto End; } if (dev->type && dev->type->pm) { pm_dev_dbg(dev, state, "LATE type "); error = pm_noirq_op(dev, dev->type->pm, state); if (error) goto End; } if (dev->bus && dev->bus->pm) { pm_dev_dbg(dev, state, "LATE "); error = pm_noirq_op(dev, dev->bus->pm, state); } End: return error; } /** * dpm_suspend_noirq - Execute "late suspend" callbacks for non-sysdev devices. * @state: PM transition of the system being carried out. * * Prevent device drivers from receiving interrupts and call the "noirq" suspend * handlers for all non-sysdev devices. */ int dpm_suspend_noirq(pm_message_t state) { struct device *dev; ktime_t starttime = ktime_get(); int error = 0; suspend_device_irqs(); mutex_lock(&dpm_list_mtx); list_for_each_entry_reverse(dev, &dpm_list, power.entry) { error = device_suspend_noirq(dev, state); if (error) { pm_dev_err(dev, state, " late", error); break; } dev->power.status = DPM_OFF_IRQ; } mutex_unlock(&dpm_list_mtx); if (error) dpm_resume_noirq(resume_event(state)); else dpm_show_time(starttime, state, "late"); return error; } EXPORT_SYMBOL_GPL(dpm_suspend_noirq); /** * legacy_suspend - Execute a legacy (bus or class) suspend callback for device. * @dev: Device to suspend. * @state: PM transition of the system being carried out. * @cb: Suspend callback to execute. */ static int legacy_suspend(struct device *dev, pm_message_t state, int (*cb)(struct device *dev, pm_message_t state)) { int error; ktime_t calltime; calltime = initcall_debug_start(dev); error = cb(dev, state); suspend_report_result(cb, error); initcall_debug_report(dev, calltime, error); return error; } static int async_error; /** * device_suspend - Execute "suspend" callbacks for given device. * @dev: Device to handle. * @state: PM transition of the system being carried out. * @async: If true, the device is being suspended asynchronously. */ static int __device_suspend(struct device *dev, pm_message_t state, bool async) { int error = 0; dpm_wait_for_children(dev, async); device_lock(dev); if (async_error) goto End; if (dev->class) { if (dev->class->pm) { pm_dev_dbg(dev, state, "class "); error = pm_op(dev, dev->class->pm, state); } else if (dev->class->suspend) { pm_dev_dbg(dev, state, "legacy class "); error = legacy_suspend(dev, state, dev->class->suspend); } if (error) goto End; } if (dev->type) { if (dev->type->pm) { pm_dev_dbg(dev, state, "type "); error = pm_op(dev, dev->type->pm, state); } if (error) goto End; } if (dev->bus) { if (dev->bus->pm) { pm_dev_dbg(dev, state, ""); error = pm_op(dev, dev->bus->pm, state); } else if (dev->bus->suspend) { pm_dev_dbg(dev, state, "legacy "); error = legacy_suspend(dev, state, dev->bus->suspend); } } if (!error) dev->power.status = DPM_OFF; End: device_unlock(dev); complete_all(&dev->power.completion); return error; } static void async_suspend(void *data, async_cookie_t cookie) { struct device *dev = (struct device *)data; int error; error = __device_suspend(dev, pm_transition, true); if (error) { pm_dev_err(dev, pm_transition, " async", error); async_error = error; } put_device(dev); } static int device_suspend(struct device *dev) { INIT_COMPLETION(dev->power.completion); if (pm_async_enabled && dev->power.async_suspend) { get_device(dev); async_schedule(async_suspend, dev); return 0; } return __device_suspend(dev, pm_transition, false); } /** * dpm_suspend - Execute "suspend" callbacks for all non-sysdev devices. * @state: PM transition of the system being carried out. */ static int dpm_suspend(pm_message_t state) { struct list_head list; ktime_t starttime = ktime_get(); int error = 0; INIT_LIST_HEAD(&list); mutex_lock(&dpm_list_mtx); pm_transition = state; async_error = 0; while (!list_empty(&dpm_list)) { struct device *dev = to_device(dpm_list.prev); get_device(dev); mutex_unlock(&dpm_list_mtx); suspend_task = current; dpm_drv_wdset(dev); error = device_suspend(dev); dpm_drv_wdclr(dev); suspend_task = NULL; mutex_lock(&dpm_list_mtx); if (error) { pm_dev_err(dev, state, "", error); put_device(dev); break; } if (!list_empty(&dev->power.entry)) list_move(&dev->power.entry, &list); put_device(dev); if (async_error) break; } list_splice(&list, dpm_list.prev); mutex_unlock(&dpm_list_mtx); async_synchronize_full(); if (!error) error = async_error; if (!error) dpm_show_time(starttime, state, NULL); return error; } /** * device_prepare - Prepare a device for system power transition. * @dev: Device to handle. * @state: PM transition of the system being carried out. * * Execute the ->prepare() callback(s) for given device. No new children of the * device may be registered after this function has returned. */ static int device_prepare(struct device *dev, pm_message_t state) { int error = 0; device_lock(dev); if (dev->bus && dev->bus->pm && dev->bus->pm->prepare) { pm_dev_dbg(dev, state, "preparing "); error = dev->bus->pm->prepare(dev); suspend_report_result(dev->bus->pm->prepare, error); if (error) goto End; } if (dev->type && dev->type->pm && dev->type->pm->prepare) { pm_dev_dbg(dev, state, "preparing type "); error = dev->type->pm->prepare(dev); suspend_report_result(dev->type->pm->prepare, error); if (error) goto End; } if (dev->class && dev->class->pm && dev->class->pm->prepare) { pm_dev_dbg(dev, state, "preparing class "); error = dev->class->pm->prepare(dev); suspend_report_result(dev->class->pm->prepare, error); } End: device_unlock(dev); return error; } /** * dpm_prepare - Prepare all non-sysdev devices for a system PM transition. * @state: PM transition of the system being carried out. * * Execute the ->prepare() callback(s) for all devices. */ static int dpm_prepare(pm_message_t state) { struct list_head list; int error = 0; INIT_LIST_HEAD(&list); mutex_lock(&dpm_list_mtx); transition_started = true; while (!list_empty(&dpm_list)) { struct device *dev = to_device(dpm_list.next); get_device(dev); dev->power.status = DPM_PREPARING; mutex_unlock(&dpm_list_mtx); pm_runtime_get_noresume(dev); if (pm_runtime_barrier(dev) && device_may_wakeup(dev)) { /* Wake-up requested during system sleep transition. */ pm_runtime_put_sync(dev); error = -EBUSY; } else { error = device_prepare(dev, state); } mutex_lock(&dpm_list_mtx); if (error) { dev->power.status = DPM_ON; if (error == -EAGAIN) { put_device(dev); error = 0; continue; } printk(KERN_ERR "PM: Failed to prepare device %s " "for power transition: error %d\n", kobject_name(&dev->kobj), error); put_device(dev); break; } dev->power.status = DPM_SUSPENDING; if (!list_empty(&dev->power.entry)) list_move_tail(&dev->power.entry, &list); put_device(dev); } list_splice(&list, &dpm_list); mutex_unlock(&dpm_list_mtx); return error; } /** * dpm_suspend_start - Prepare devices for PM transition and suspend them. * @state: PM transition of the system being carried out. * * Prepare all non-sysdev devices for system PM transition and execute "suspend" * callbacks for them. */ int dpm_suspend_start(pm_message_t state) { int error; might_sleep(); error = dpm_prepare(state); if (!error) error = dpm_suspend(state); return error; } EXPORT_SYMBOL_GPL(dpm_suspend_start); void __suspend_report_result(const char *function, void *fn, int ret) { if (ret) printk(KERN_ERR "%s(): %pF returns %d\n", function, fn, ret); } EXPORT_SYMBOL_GPL(__suspend_report_result); /** * device_pm_wait_for_dev - Wait for suspend/resume of a device to complete. * @dev: Device to wait for. * @subordinate: Device that needs to wait for @dev. */ void device_pm_wait_for_dev(struct device *subordinate, struct device *dev) { dpm_wait(dev, subordinate->power.async_suspend); } EXPORT_SYMBOL_GPL(device_pm_wait_for_dev);
tenorntex/lhbalanced
drivers/base/power/main.c
C
gpl-2.0
29,176
/* (c) 2001-2004 by Marcin Wiacek */ #ifndef __gsm_wap_h #define __gsm_wap_h #include <gammu-wap.h> #include <gammu-message.h> void NOKIA_EncodeWAPMMSSettingsSMSText(unsigned char *Buffer, size_t *Length, GSM_WAPSettings *settings, gboolean MMS); /* -------------------------------- WAP Bookmark --------------------------- */ void NOKIA_EncodeWAPBookmarkSMSText (unsigned char *Buffer, size_t *Length, GSM_WAPBookmark *bookmark); /* ------------------------------ MMS Indicator ---------------------------- */ void GSM_EncodeMMSIndicatorSMSText(unsigned char *Buffer, size_t *Length, GSM_MMSIndicator Indicator); void GSM_EncodeWAPIndicatorSMSText(unsigned char *Buffer, size_t *Length, char *Text, char *URL); #endif /* How should editor hadle tabs in this file? Add editor commands here. * vim: noexpandtab sw=8 ts=8 sts=8: */
dunn/gammu
libgammu/service/gsmdata.h
C
gpl-2.0
844
/* Copyright (c) 2008-2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * 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 <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/spinlock.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/semaphore.h> #include <linux/uaccess.h> #include <linux/clk.h> #include <linux/platform_device.h> #include <asm/system.h> #include <asm/mach-types.h> #include <mach/hardware.h> #include <mach/gpio.h> #include <mach/clk.h> #include <mach/dma.h> #include "msm_fb.h" #include "mipi_dsi.h" #include "mdp.h" #include "mdp4.h" #define DSI_HOST_DEBUG static struct completion dsi_dma_comp; static struct dsi_buf dsi_tx_buf; static int dsi_irq_enabled; static spinlock_t dsi_lock; static struct list_head pre_kickoff_list; static struct list_head post_kickoff_list; void mipi_dsi_init(void) { init_completion(&dsi_dma_comp); mipi_dsi_buf_alloc(&dsi_tx_buf, DSI_BUF_SIZE); spin_lock_init(&dsi_lock); INIT_LIST_HEAD(&pre_kickoff_list); INIT_LIST_HEAD(&post_kickoff_list); } void mipi_dsi_enable_irq(void) { unsigned long flags; spin_lock_irqsave(&dsi_lock, flags); if (dsi_irq_enabled) { pr_debug("%s: IRQ aleady enabled\n", __func__); spin_unlock_irqrestore(&dsi_lock, flags); return; } dsi_irq_enabled = 1; enable_irq(DSI_IRQ); spin_unlock_irqrestore(&dsi_lock, flags); } void mipi_dsi_disable_irq(void) { unsigned long flags; spin_lock_irqsave(&dsi_lock, flags); if (dsi_irq_enabled == 0) { pr_debug("%s: IRQ already disabled\n", __func__); spin_unlock_irqrestore(&dsi_lock, flags); return; } dsi_irq_enabled = 0; disable_irq(DSI_IRQ); spin_unlock_irqrestore(&dsi_lock, flags); } /* * mipi_dsi_disale_irq_nosync() should be called * from interrupt context */ void mipi_dsi_disable_irq_nosync(void) { spin_lock(&dsi_lock); if (dsi_irq_enabled == 0) { pr_debug("%s: IRQ cannot be disabled\n", __func__); return; } dsi_irq_enabled = 0; disable_irq_nosync(DSI_IRQ); spin_unlock(&dsi_lock); } static void mipi_dsi_action(struct list_head *act_list) { struct list_head *lp; struct dsi_kickoff_action *act; list_for_each(lp, act_list) { act = list_entry(lp, struct dsi_kickoff_action, act_entry); if (act && act->action) act->action(act->data); } } void mipi_dsi_pre_kickoff_action(void) { mipi_dsi_action(&pre_kickoff_list); } void mipi_dsi_post_kickoff_action(void) { mipi_dsi_action(&post_kickoff_list); } /* * mipi_dsi_pre_kickoff_add: * ov_mutex need to be acquired before call this function. */ void mipi_dsi_pre_kickoff_add(struct dsi_kickoff_action *act) { if (act) list_add_tail(&act->act_entry, &pre_kickoff_list); } /* * mipi_dsi_pre_kickoff_add: * ov_mutex need to be acquired before call this function. */ void mipi_dsi_post_kickoff_add(struct dsi_kickoff_action *act) { if (act) list_add_tail(&act->act_entry, &post_kickoff_list); } /* * mipi_dsi_pre_kickoff_add: * ov_mutex need to be acquired before call this function. */ void mipi_dsi_pre_kickoff_del(struct dsi_kickoff_action *act) { if (!list_empty(&pre_kickoff_list) && act) list_del(&act->act_entry); } /* * mipi_dsi_pre_kickoff_add: * ov_mutex need to be acquired before call this function. */ void mipi_dsi_post_kickoff_del(struct dsi_kickoff_action *act) { if (!list_empty(&post_kickoff_list) && act) list_del(&act->act_entry); } /* * mipi dsi buf mechanism */ char *mipi_dsi_buf_reserve(struct dsi_buf *dp, int len) { dp->data += len; return dp->data; } char *mipi_dsi_buf_unreserve(struct dsi_buf *dp, int len) { dp->data -= len; return dp->data; } char *mipi_dsi_buf_push(struct dsi_buf *dp, int len) { dp->data -= len; dp->len += len; return dp->data; } char *mipi_dsi_buf_reserve_hdr(struct dsi_buf *dp, int hlen) { dp->hdr = (uint32 *)dp->data; return mipi_dsi_buf_reserve(dp, hlen); } char *mipi_dsi_buf_init(struct dsi_buf *dp) { int off; dp->data = dp->start; off = (int)dp->data; /* 8 byte align */ off &= 0x07; if (off) off = 8 - off; dp->data += off; dp->len = 0; return dp->data; } int mipi_dsi_buf_alloc(struct dsi_buf *dp, int size) { dp->start = kmalloc(size, GFP_KERNEL); if (dp->start == NULL) { pr_err("%s:%u\n", __func__, __LINE__); return -ENOMEM; } dp->end = dp->start + size; dp->size = size; if ((int)dp->start & 0x07) pr_err("%s: buf NOT 8 bytes aligned\n", __func__); dp->data = dp->start; dp->len = 0; return size; } /* * mipi dsi gerneric long write */ static int mipi_dsi_generic_lwrite(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { char *bp; uint32 *hp; int i, len; bp = mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); /* fill up payload */ if (cm->payload) { len = cm->dlen; len += 3; len &= ~0x03; /* multipled by 4 */ for (i = 0; i < cm->dlen; i++) *bp++ = cm->payload[i]; /* append 0xff to the end */ for (; i < len; i++) *bp++ = 0xff; dp->len += len; } /* fill up header */ hp = dp->hdr; *hp = 0; *hp = DSI_HDR_WC(cm->dlen); *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_LONG_PKT; *hp |= DSI_HDR_DTYPE(DTYPE_GEN_LWRITE); if (cm->last) *hp |= DSI_HDR_LAST; mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; } /* * mipi dsi gerneric short write with 0, 1 2 parameters */ static int mipi_dsi_generic_swrite(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; int len; if (cm->dlen && cm->payload == 0) { pr_err("%s: NO payload error\n", __func__); return 0; } mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); if (cm->last) *hp |= DSI_HDR_LAST; len = (cm->dlen > 2) ? 2 : cm->dlen; if (len == 1) { *hp |= DSI_HDR_DTYPE(DTYPE_GEN_WRITE1); *hp |= DSI_HDR_DATA1(cm->payload[0]); *hp |= DSI_HDR_DATA2(0); } else if (len == 2) { *hp |= DSI_HDR_DTYPE(DTYPE_GEN_WRITE2); *hp |= DSI_HDR_DATA1(cm->payload[0]); *hp |= DSI_HDR_DATA2(cm->payload[1]); } else { *hp |= DSI_HDR_DTYPE(DTYPE_GEN_WRITE); *hp |= DSI_HDR_DATA1(0); *hp |= DSI_HDR_DATA2(0); } mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } /* * mipi dsi gerneric read with 0, 1 2 parameters */ static int mipi_dsi_generic_read(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; int len; if (cm->dlen && cm->payload == 0) { pr_err("%s: NO payload error\n", __func__); return 0; } mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_BTA; if (cm->last) *hp |= DSI_HDR_LAST; len = (cm->dlen > 2) ? 2 : cm->dlen; if (len == 1) { *hp |= DSI_HDR_DTYPE(DTYPE_GEN_READ1); *hp |= DSI_HDR_DATA1(cm->payload[0]); *hp |= DSI_HDR_DATA2(0); } else if (len == 2) { *hp |= DSI_HDR_DTYPE(DTYPE_GEN_READ2); *hp |= DSI_HDR_DATA1(cm->payload[0]); *hp |= DSI_HDR_DATA2(cm->payload[1]); } else { *hp |= DSI_HDR_DTYPE(DTYPE_GEN_READ); *hp |= DSI_HDR_DATA1(0); *hp |= DSI_HDR_DATA2(0); } mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } /* * mipi dsi dcs long write */ static int mipi_dsi_dcs_lwrite(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { char *bp; uint32 *hp; int i, len; bp = mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); /* * fill up payload * dcs command byte (first byte) followed by payload */ if (cm->payload) { len = cm->dlen; len += 3; len &= ~0x03; /* multipled by 4 */ for (i = 0; i < cm->dlen; i++) *bp++ = cm->payload[i]; /* append 0xff to the end */ for (; i < len; i++) *bp++ = 0xff; dp->len += len; } /* fill up header */ hp = dp->hdr; *hp = 0; *hp = DSI_HDR_WC(cm->dlen); *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_LONG_PKT; *hp |= DSI_HDR_DTYPE(DTYPE_DCS_LWRITE); if (cm->last) *hp |= DSI_HDR_LAST; mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; } /* * mipi dsi dcs short write with 0 parameters */ static int mipi_dsi_dcs_swrite(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; int len; if (cm->payload == 0) { pr_err("%s: NO payload error\n", __func__); return -EINVAL; } mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); if (cm->ack) /* ask ACK trigger msg from peripeheral */ *hp |= DSI_HDR_BTA; if (cm->last) *hp |= DSI_HDR_LAST; len = (cm->dlen > 1) ? 1 : cm->dlen; *hp |= DSI_HDR_DTYPE(DTYPE_DCS_WRITE); *hp |= DSI_HDR_DATA1(cm->payload[0]); /* dcs command byte */ *hp |= DSI_HDR_DATA2(0); mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; } /* * mipi dsi dcs short write with 1 parameters */ static int mipi_dsi_dcs_swrite1(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; if (cm->dlen < 2 || cm->payload == 0) { pr_err("%s: NO payload error\n", __func__); return -EINVAL; } mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); if (cm->ack) /* ask ACK trigger msg from peripeheral */ *hp |= DSI_HDR_BTA; if (cm->last) *hp |= DSI_HDR_LAST; *hp |= DSI_HDR_DTYPE(DTYPE_DCS_WRITE1); *hp |= DSI_HDR_DATA1(cm->payload[0]); /* dcs comamnd byte */ *hp |= DSI_HDR_DATA2(cm->payload[1]); /* parameter */ mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; } /* * mipi dsi dcs read with 0 parameters */ static int mipi_dsi_dcs_read(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; if (cm->payload == 0) { pr_err("%s: NO payload error\n", __func__); return -EINVAL; } mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_BTA; *hp |= DSI_HDR_DTYPE(DTYPE_DCS_READ); if (cm->last) *hp |= DSI_HDR_LAST; *hp |= DSI_HDR_DATA1(cm->payload[0]); /* dcs command byte */ *hp |= DSI_HDR_DATA2(0); mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } static int mipi_dsi_cm_on(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_DTYPE(DTYPE_CM_ON); if (cm->last) *hp |= DSI_HDR_LAST; mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } static int mipi_dsi_cm_off(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_DTYPE(DTYPE_CM_OFF); if (cm->last) *hp |= DSI_HDR_LAST; mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } static int mipi_dsi_peripheral_on(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_DTYPE(DTYPE_PERIPHERAL_ON); if (cm->last) *hp |= DSI_HDR_LAST; mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } static int mipi_dsi_peripheral_off(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_DTYPE(DTYPE_PERIPHERAL_OFF); if (cm->last) *hp |= DSI_HDR_LAST; mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } static int mipi_dsi_set_max_pktsize(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; if (cm->payload == 0) { pr_err("%s: NO payload error\n", __func__); return 0; } mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_DTYPE(DTYPE_MAX_PKTSIZE); if (cm->last) *hp |= DSI_HDR_LAST; *hp |= DSI_HDR_DATA1(cm->payload[0]); *hp |= DSI_HDR_DATA2(cm->payload[1]); mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } static int mipi_dsi_null_pkt(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp = DSI_HDR_WC(cm->dlen); *hp |= DSI_HDR_LONG_PKT; *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_DTYPE(DTYPE_NULL_PKT); if (cm->last) *hp |= DSI_HDR_LAST; mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } static int mipi_dsi_blank_pkt(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { uint32 *hp; mipi_dsi_buf_reserve_hdr(dp, DSI_HOST_HDR_SIZE); hp = dp->hdr; *hp = 0; *hp = DSI_HDR_WC(cm->dlen); *hp |= DSI_HDR_LONG_PKT; *hp |= DSI_HDR_VC(cm->vc); *hp |= DSI_HDR_DTYPE(DTYPE_BLANK_PKT); if (cm->last) *hp |= DSI_HDR_LAST; mipi_dsi_buf_push(dp, DSI_HOST_HDR_SIZE); return dp->len; /* 4 bytes */ } /* * prepare cmd buffer to be txed */ int mipi_dsi_cmd_dma_add(struct dsi_buf *dp, struct dsi_cmd_desc *cm) { int len = 0; switch (cm->dtype) { case DTYPE_GEN_WRITE: case DTYPE_GEN_WRITE1: case DTYPE_GEN_WRITE2: len = mipi_dsi_generic_swrite(dp, cm); break; case DTYPE_GEN_LWRITE: len = mipi_dsi_generic_lwrite(dp, cm); break; case DTYPE_GEN_READ: case DTYPE_GEN_READ1: case DTYPE_GEN_READ2: len = mipi_dsi_generic_read(dp, cm); break; case DTYPE_DCS_LWRITE: len = mipi_dsi_dcs_lwrite(dp, cm); break; case DTYPE_DCS_WRITE: len = mipi_dsi_dcs_swrite(dp, cm); break; case DTYPE_DCS_WRITE1: len = mipi_dsi_dcs_swrite1(dp, cm); break; case DTYPE_DCS_READ: len = mipi_dsi_dcs_read(dp, cm); break; case DTYPE_MAX_PKTSIZE: len = mipi_dsi_set_max_pktsize(dp, cm); break; case DTYPE_NULL_PKT: len = mipi_dsi_null_pkt(dp, cm); break; case DTYPE_BLANK_PKT: len = mipi_dsi_blank_pkt(dp, cm); break; case DTYPE_CM_ON: len = mipi_dsi_cm_on(dp, cm); break; case DTYPE_CM_OFF: len = mipi_dsi_cm_off(dp, cm); break; case DTYPE_PERIPHERAL_ON: len = mipi_dsi_peripheral_on(dp, cm); break; case DTYPE_PERIPHERAL_OFF: len = mipi_dsi_peripheral_off(dp, cm); break; default: pr_debug("%s: dtype=%x NOT supported\n", __func__, cm->dtype); break; } return len; } void mipi_dsi_host_init(struct mipi_panel_info *pinfo) { uint32 dsi_ctrl, intr_ctrl; uint32 data; if (pinfo->mode == DSI_VIDEO_MODE) { data = 0; if (pinfo->pulse_mode_hsa_he) data |= BIT(28); if (pinfo->hfp_power_stop) data |= BIT(24); if (pinfo->hbp_power_stop) data |= BIT(20); if (pinfo->hsa_power_stop) data |= BIT(16); if (pinfo->eof_bllp_power_stop) data |= BIT(15); if (pinfo->bllp_power_stop) data |= BIT(12); data |= ((pinfo->traffic_mode & 0x03) << 8); data |= ((pinfo->dst_format & 0x03) << 4); /* 2 bits */ data |= (pinfo->vc & 0x03); MIPI_OUTP(MIPI_DSI_BASE + 0x000c, data); data = 0; data |= ((pinfo->rgb_swap & 0x07) << 12); if (pinfo->b_sel) data |= BIT(8); if (pinfo->g_sel) data |= BIT(4); if (pinfo->r_sel) data |= BIT(0); MIPI_OUTP(MIPI_DSI_BASE + 0x001c, data); } else if (pinfo->mode == DSI_CMD_MODE) { data = 0; data |= ((pinfo->interleave_max & 0x0f) << 20); data |= ((pinfo->rgb_swap & 0x07) << 16); if (pinfo->b_sel) data |= BIT(12); if (pinfo->g_sel) data |= BIT(8); if (pinfo->r_sel) data |= BIT(4); data |= (pinfo->dst_format & 0x0f); /* 4 bits */ MIPI_OUTP(MIPI_DSI_BASE + 0x003c, data); /* DSI_COMMAND_MODE_MDP_DCS_CMD_CTRL */ data = pinfo->wr_mem_continue & 0x0ff; data <<= 8; data |= (pinfo->wr_mem_start & 0x0ff); if (pinfo->insert_dcs_cmd) data |= BIT(16); MIPI_OUTP(MIPI_DSI_BASE + 0x0040, data); } else pr_err("%s: Unknown DSI mode=%d\n", __func__, pinfo->mode); dsi_ctrl = BIT(8) | BIT(2); /* clock enable & cmd mode */ intr_ctrl = 0; intr_ctrl = (DSI_INTR_CMD_DMA_DONE_MASK | DSI_INTR_CMD_MDP_DONE_MASK); if (pinfo->crc_check) dsi_ctrl |= BIT(24); if (pinfo->ecc_check) dsi_ctrl |= BIT(20); if (pinfo->data_lane3) dsi_ctrl |= BIT(7); if (pinfo->data_lane2) dsi_ctrl |= BIT(6); if (pinfo->data_lane1) dsi_ctrl |= BIT(5); if (pinfo->data_lane0) dsi_ctrl |= BIT(4); #ifdef RGB_SWAP /* there has hardware problem * the color channel between dsi and mdp are swapped */ MIPI_OUTP(MIPI_DSI_BASE + 0x1c, 0x2000); /* rGB --> BGR */ #endif /* from frame buffer, low power mode */ /* DSI_COMMAND_MODE_DMA_CTRL */ #if 0 MIPI_OUTP(MIPI_DSI_BASE + 0x38, 0x14000000); #else MIPI_OUTP(MIPI_DSI_BASE + 0x38, 0x10000000); #endif data = 0; if (pinfo->te_sel) data |= BIT(31); data |= pinfo->mdp_trigger << 4;/* cmd mdp trigger */ data |= pinfo->dma_trigger; /* cmd dma trigger */ data |= (pinfo->stream & 0x01) << 8; MIPI_OUTP(MIPI_DSI_BASE + 0x0080, data); /* DSI_TRIG_CTRL */ /* DSI_LAN_SWAP_CTRL */ MIPI_OUTP(MIPI_DSI_BASE + 0x00ac, pinfo->dlane_swap); /* clock out ctrl */ data = pinfo->t_clk_post & 0x3f; /* 6 bits */ data <<= 8; data |= pinfo->t_clk_pre & 0x3f; /* 6 bits */ MIPI_OUTP(MIPI_DSI_BASE + 0xc0, data); /* DSI_CLKOUT_TIMING_CTRL */ data = 0; if (pinfo->rx_eot_ignore) data |= BIT(4); if (pinfo->tx_eot_append) data |= BIT(0); MIPI_OUTP(MIPI_DSI_BASE + 0x00c8, data); /* DSI_EOT_PACKET_CTRL */ /* allow only ack-err-status to generate interrupt */ MIPI_OUTP(MIPI_DSI_BASE + 0x0108, 0x13ff3fe0); /* DSI_ERR_INT_MASK0 */ intr_ctrl |= DSI_INTR_ERROR_MASK; MIPI_OUTP(MIPI_DSI_BASE + 0x010c, intr_ctrl); /* DSI_INTL_CTRL */ /* turn esc, byte, dsi, pclk, sclk, hclk on */ MIPI_OUTP(MIPI_DSI_BASE + 0x118, 0x23f); /* DSI_CLK_CTRL */ #if 1 MIPI_OUTP(MIPI_DSI_BASE + 0xA8, 0x10000000); #endif dsi_ctrl |= BIT(0); /* enable dsi */ MIPI_OUTP(MIPI_DSI_BASE + 0x0000, dsi_ctrl); wmb(); } void mipi_set_tx_power_mode(int mode) { uint32 data = MIPI_INP(MIPI_DSI_BASE + 0x38); if (mode == 0) data &= ~BIT(26); else data |= BIT(26); MIPI_OUTP(MIPI_DSI_BASE + 0x38, data); } void mipi_dsi_sw_reset(void) { MIPI_OUTP(MIPI_DSI_BASE + 0x114, 0x01); wmb(); MIPI_OUTP(MIPI_DSI_BASE + 0x114, 0x00); wmb(); } void mipi_dsi_controller_cfg(int enable) { uint32 dsi_ctrl; uint32 status; int cnt; cnt = 16; while (cnt--) { status = MIPI_INP(MIPI_DSI_BASE + 0x0004); status &= 0x02; /* CMD_MODE_DMA_BUSY */ if (status == 0) break; usleep(1000); } if (cnt == 0) pr_info("%s: DSI status=%x failed\n", __func__, status); cnt = 16; while (cnt--) { status = MIPI_INP(MIPI_DSI_BASE + 0x0008); status &= 0x11111000; /* x_HS_FIFO_EMPTY */ if (status == 0x11111000) /* all empty */ break; usleep(1000); } if (cnt == 0) pr_info("%s: FIFO status=%x failed\n", __func__, status); dsi_ctrl = MIPI_INP(MIPI_DSI_BASE + 0x0000); if (enable) dsi_ctrl |= 0x01; else dsi_ctrl &= ~0x01; MIPI_OUTP(MIPI_DSI_BASE + 0x0000, dsi_ctrl); wmb(); } void mipi_dsi_op_mode_config(int mode) { uint32 dsi_ctrl, intr_ctrl; dsi_ctrl = MIPI_INP(MIPI_DSI_BASE + 0x0000); dsi_ctrl &= ~0x07; if (mode == DSI_VIDEO_MODE) { dsi_ctrl |= 0x03; intr_ctrl = DSI_INTR_CMD_DMA_DONE_MASK; } else { /* command mode */ dsi_ctrl |= 0x05; intr_ctrl = DSI_INTR_CMD_DMA_DONE_MASK | DSI_INTR_ERROR_MASK | DSI_INTR_CMD_MDP_DONE_MASK; } pr_debug("%s: dsi_ctrl=%x intr=%x\n", __func__, dsi_ctrl, intr_ctrl); MIPI_OUTP(MIPI_DSI_BASE + 0x010c, intr_ctrl); /* DSI_INTL_CTRL */ MIPI_OUTP(MIPI_DSI_BASE + 0x0000, dsi_ctrl); wmb(); } void mipi_dsi_cmd_mdp_sw_trigger(void) { mipi_dsi_pre_kickoff_action(); mipi_dsi_enable_irq(); MIPI_OUTP(MIPI_DSI_BASE + 0x090, 0x01); /* trigger */ wmb(); } void mipi_dsi_cmd_bta_sw_trigger(void) { uint32 data; int cnt = 0; MIPI_OUTP(MIPI_DSI_BASE + 0x094, 0x01); /* trigger */ wmb(); while (cnt < 10000) { data = MIPI_INP(MIPI_DSI_BASE + 0x0004);/* DSI_STATUS */ if ((data & 0x0010) == 0) break; cnt++; } mipi_dsi_ack_err_status(); pr_debug("%s: BTA done, cnt=%d\n", __func__, cnt); } static char set_tear_on[2] = {0x35, 0x00}; static struct dsi_cmd_desc dsi_tear_on_cmd = { DTYPE_DCS_WRITE1, 1, 0, 0, 0, sizeof(set_tear_on), set_tear_on}; static char set_tear_off[2] = {0x34, 0x00}; static struct dsi_cmd_desc dsi_tear_off_cmd = { DTYPE_DCS_WRITE, 1, 0, 0, 0, sizeof(set_tear_off), set_tear_off}; #ifdef SET_TEAR_SCANLINE static char set_tear_scanline[3] = {0x44, 0x02, 0xcf}; /* line 719 */ static struct dsi_cmd_desc dsi_tear_scanline_cmd = { DTYPE_DCS_LWRITE, 1, 0, 0, 0, sizeof(set_tear_scanline), set_tear_scanline}; #endif void mipi_dsi_set_tear_on(struct msm_fb_data_type *mfd) { mipi_dsi_buf_init(&dsi_tx_buf); mipi_dsi_cmds_tx(mfd, &dsi_tx_buf, &dsi_tear_on_cmd, 1); } void mipi_dsi_set_tear_off(struct msm_fb_data_type *mfd) { mipi_dsi_buf_init(&dsi_tx_buf); mipi_dsi_cmds_tx(mfd, &dsi_tx_buf, &dsi_tear_off_cmd, 1); } int mipi_dsi_cmd_reg_tx(uint32 data) { #ifdef DSI_HOST_DEBUG int i; char *bp; bp = (char *)&data; pr_debug("%s: ", __func__); for (i = 0; i < 4; i++) pr_debug("%x ", *bp++); pr_debug("\n"); #endif MIPI_OUTP(MIPI_DSI_BASE + 0x0080, 0x04);/* sw trigger */ MIPI_OUTP(MIPI_DSI_BASE + 0x0, 0x135); wmb(); MIPI_OUTP(MIPI_DSI_BASE + 0x038, data); wmb(); MIPI_OUTP(MIPI_DSI_BASE + 0x08c, 0x01); /* trigger */ wmb(); udelay(300); return 4; } /* * mipi_dsi_cmds_tx: * ov_mutex need to be acquired before call this function. */ int mipi_dsi_cmds_tx(struct msm_fb_data_type *mfd, struct dsi_buf *tp, struct dsi_cmd_desc *cmds, int cnt) { struct dsi_cmd_desc *cm; uint32 dsi_ctrl, ctrl; int i, video_mode; /* turn on cmd mode * for video mode, do not send cmds more than * one pixel line, since it only transmit it * during BLLP. */ dsi_ctrl = MIPI_INP(MIPI_DSI_BASE + 0x0000); video_mode = dsi_ctrl & 0x02; /* VIDEO_MODE_EN */ if (video_mode) { ctrl = dsi_ctrl | 0x04; /* CMD_MODE_EN */ MIPI_OUTP(MIPI_DSI_BASE + 0x0000, ctrl); } else { /* cmd mode */ /* * during boot up, cmd mode is configured * even it is video mode panel. */ /* make sure mdp dma is not txing pixel data */ if (mfd->panel_info.type == MIPI_CMD_PANEL) mdp4_dsi_cmd_dma_busy_wait(mfd); } mipi_dsi_enable_irq(); cm = cmds; mipi_dsi_buf_init(tp); for (i = 0; i < cnt; i++) { mipi_dsi_buf_init(tp); mipi_dsi_cmd_dma_add(tp, cm); mipi_dsi_cmd_dma_tx(tp); if (cm->wait) msleep(cm->wait); cm++; } mipi_dsi_disable_irq(); if (video_mode) MIPI_OUTP(MIPI_DSI_BASE + 0x0000, dsi_ctrl); /* restore */ return cnt; } /* MIPI_DSI_MRPS, Maximum Return Packet Size */ static char max_pktsize[2] = {0x00, 0x00}; /* LSB tx first, 10 bytes */ static struct dsi_cmd_desc pkt_size_cmd[] = { {DTYPE_MAX_PKTSIZE, 1, 0, 0, 0, sizeof(max_pktsize), max_pktsize} }; /* * DSI panel reply with MAX_RETURN_PACKET_SIZE bytes of data * plus DCS header, ECC and CRC for DCS long read response * mipi_dsi_controller only have 4x32 bits register ( 16 bytes) to * hold data per transaction. * MIPI_DSI_LEN equal to 8 * len should be either 4 or 8 * any return data more than MIPI_DSI_LEN need to be break down * to multiple transactions. * * ov_mutex need to be acquired before call this function. */ int mipi_dsi_cmds_rx(struct msm_fb_data_type *mfd, struct dsi_buf *tp, struct dsi_buf *rp, struct dsi_cmd_desc *cmds, int len) { int cnt, res; static int pkt_size; if (len <= 2) cnt = 4; /* short read */ else { if (len > MIPI_DSI_LEN) len = MIPI_DSI_LEN; /* 8 bytes at most */ res = len & 0x03; len += (4 - res); /* 4 bytes align */ /* * add extra 2 bytes to len to have overall * packet size is multipe by 4. This also make * sure 4 bytes dcs headerlocates within a * 32 bits register after shift in. * after all, len should be either 6 or 10. */ len += 2; cnt = len + 6; /* 4 bytes header + 2 bytes crc */ } if (mfd->panel_info.type == MIPI_CMD_PANEL) { /* make sure mdp dma is not txing pixel data */ mdp4_dsi_cmd_dma_busy_wait(mfd); } mipi_dsi_enable_irq(); if (pkt_size != len) { /* set new max pkt size */ pkt_size = len; max_pktsize[0] = pkt_size; mipi_dsi_buf_init(tp); mipi_dsi_cmd_dma_add(tp, pkt_size_cmd); mipi_dsi_cmd_dma_tx(tp); } mipi_dsi_buf_init(tp); mipi_dsi_cmd_dma_add(tp, cmds); /* transmit read comamnd to client */ mipi_dsi_cmd_dma_tx(tp); /* * once cmd_dma_done interrupt received, * return data from client is ready and stored * at RDBK_DATA register already */ mipi_dsi_cmd_dma_rx(rp, cnt); mipi_dsi_disable_irq(); /* strip off dcs header & crc */ if (cnt > 4) { /* long response */ rp->data += 4; /* skip dcs header */ rp->len -= 6; /* deduct 4 bytes header + 2 bytes crc */ rp->len -= 2; /* extra 2 bytes added */ } else { rp->data += 1; /* skip dcs short header */ rp->len -= 2; /* deduct 1 byte header + 1 byte ecc */ } return rp->len; } int mipi_dsi_cmd_dma_tx(struct dsi_buf *tp) { int len; #ifdef DSI_HOST_DEBUG int i; char *bp; bp = tp->data; pr_debug("%s: ", __func__); for (i = 0; i < tp->len; i++) pr_debug("%x ", *bp++); pr_debug("\n"); #endif len = tp->len; len += 3; len &= ~0x03; /* multipled by 4 */ tp->dmap = dma_map_single(&dsi_dev, tp->data, len, DMA_TO_DEVICE); if (dma_mapping_error(&dsi_dev, tp->dmap)) pr_err("%s: dmap mapp failed\n", __func__); INIT_COMPLETION(dsi_dma_comp); MIPI_OUTP(MIPI_DSI_BASE + 0x044, tp->dmap); MIPI_OUTP(MIPI_DSI_BASE + 0x048, len); wmb(); MIPI_OUTP(MIPI_DSI_BASE + 0x08c, 0x01); /* trigger */ wmb(); wait_for_completion(&dsi_dma_comp); dma_unmap_single(&dsi_dev, tp->dmap, len, DMA_TO_DEVICE); tp->dmap = 0; return tp->len; } int mipi_dsi_cmd_dma_rx(struct dsi_buf *rp, int rlen) { uint32 *lp, data; int i, off, cnt; lp = (uint32 *)rp->data; cnt = rlen; cnt += 3; cnt >>= 2; if (cnt > 4) cnt = 4; /* 4 x 32 bits registers only */ off = 0x068; /* DSI_RDBK_DATA0 */ off += ((cnt - 1) * 4); for (i = 0; i < cnt; i++) { data = (uint32)MIPI_INP(MIPI_DSI_BASE + off); *lp++ = ntohl(data); /* to network byte order */ off -= 4; rp->len += sizeof(*lp); } return rlen; } void mipi_dsi_irq_set(uint32 mask, uint32 irq) { uint32 data; data = MIPI_INP(MIPI_DSI_BASE + 0x010c);/* DSI_INTR_CTRL */ data &= ~mask; data |= irq; MIPI_OUTP(MIPI_DSI_BASE + 0x010c, data); } void mipi_dsi_ack_err_status(void) { uint32 status; status = MIPI_INP(MIPI_DSI_BASE + 0x0064);/* DSI_ACK_ERR_STATUS */ if (status) { MIPI_OUTP(MIPI_DSI_BASE + 0x0064, status); pr_debug("%s: status=%x\n", __func__, status); } } void mipi_dsi_timeout_status(void) { uint32 status; status = MIPI_INP(MIPI_DSI_BASE + 0x00bc);/* DSI_TIMEOUT_STATUS */ if (status & 0x0111) { MIPI_OUTP(MIPI_DSI_BASE + 0x00bc, status); pr_debug("%s: status=%x\n", __func__, status); } } void mipi_dsi_dln0_phy_err(void) { uint32 status; status = MIPI_INP(MIPI_DSI_BASE + 0x00b0);/* DSI_DLN0_PHY_ERR */ if (status & 0x011111) { MIPI_OUTP(MIPI_DSI_BASE + 0x00b0, status); pr_debug("%s: status=%x\n", __func__, status); } } void mipi_dsi_fifo_status(void) { uint32 status; status = MIPI_INP(MIPI_DSI_BASE + 0x0008);/* DSI_FIFO_STATUS */ if (status & 0x44444489) { MIPI_OUTP(MIPI_DSI_BASE + 0x0008, status); pr_debug("%s: status=%x\n", __func__, status); } } void mipi_dsi_status(void) { uint32 status; status = MIPI_INP(MIPI_DSI_BASE + 0x0004);/* DSI_STATUS */ if (status & 0x80000000) { MIPI_OUTP(MIPI_DSI_BASE + 0x0004, status); pr_debug("%s: status=%x\n", __func__, status); } } void mipi_dsi_error(void) { /* DSI_ERR_INT_MASK0 */ mipi_dsi_ack_err_status(); /* mask0, 0x01f */ mipi_dsi_timeout_status(); /* mask0, 0x0e0 */ mipi_dsi_fifo_status(); /* mask0, 0x133d00 */ mipi_dsi_status(); /* mask0, 0xc0100 */ mipi_dsi_dln0_phy_err(); /* mask0, 0x3e00000 */ } irqreturn_t mipi_dsi_isr(int irq, void *ptr) { uint32 isr; isr = MIPI_INP(MIPI_DSI_BASE + 0x010c);/* DSI_INTR_CTRL */ MIPI_OUTP(MIPI_DSI_BASE + 0x010c, isr); #ifdef CONFIG_FB_MSM_MDP40 mdp4_stat.intr_dsi++; #endif if (isr & DSI_INTR_ERROR) { mipi_dsi_error(); } if (isr & DSI_INTR_VIDEO_DONE) { /* * do something here */ } if (isr & DSI_INTR_CMD_DMA_DONE) { complete(&dsi_dma_comp); } if (isr & DSI_INTR_CMD_MDP_DONE) { mipi_dsi_disable_irq_nosync(); mipi_dsi_post_kickoff_action(); } return IRQ_HANDLED; }
dagnarf/i957kernel
drivers/video/msm/mipi_dsi_host.c
C
gpl-2.0
28,650
/* This program is part of Netmodeler, a library for graph and network modeling and simulation. Copyright (C) 2005 University of California Copyright (C) 2005 P. Oscar Boykin <boykin@pobox.com>, University of Florida This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef starsky__edgefactory_h #define starsky__edgefactory_h #include <edge.h> namespace Starsky { /** * A templated class to create * edges. Any attribute other * than the direction of the edge * are passed as a string */ class EdgeFactory { public: virtual Edge* create(Node* from, Node* to) { return new Edge(from, to); } /** * The default implemenation returns the same as the above */ virtual Edge* create(Node* from, Node* to, const std::string& attr) { return new Edge(from, to); } }; } #endif
johnynek/netmodeler
src/edgefactory.h
C
gpl-2.0
1,450
<?php /** * @package Joomla.Platform * @subpackage Session * * @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Custom session storage handler for PHP * * @package Joomla.Platform * @subpackage Session * @see http://www.php.net/manual/en/function.session-set-save-handler.php * @since 11.1 */ abstract class JSessionStorage extends JObject { /** * @var array JSessionStorage instances container. * @since 11.3 */ protected static $instances = array(); /** * Constructor * * @param array $options Optional parameters. * * @since 11.1 */ public function __construct($options = array()) { $this->register($options); } /** * Returns a session storage handler object, only creating it if it doesn't already exist. * * @param string $name The session store to instantiate * @param array $options Array of options * * @return JSessionStorage * * @since 11.1 */ public static function getInstance($name = 'none', $options = array()) { $name = strtolower(JFilterInput::getInstance()->clean($name, 'word')); if (empty(self::$instances[$name])) { $class = 'JSessionStorage' . ucfirst($name); if (!class_exists($class)) { $path = __DIR__ . '/storage/' . $name . '.php'; if (file_exists($path)) { require_once $path; } else { // No attempt to die gracefully here, as it tries to close the non-existing session jexit('Unable to load session storage class: ' . $name); } } self::$instances[$name] = new $class($options); } return self::$instances[$name]; } /** * Register the functions of this class with PHP's session handler * * @param array $options Optional parameters * * @return void * * @since 11.1 */ public function register($options = array()) { // Use this object as the session handler session_set_save_handler( array($this, 'open'), array($this, 'close'), array($this, 'read'), array($this, 'write'), array($this, 'destroy'), array($this, 'gc') ); } /** * Open the SessionHandler backend. * * @param string $save_path The path to the session object. * @param string $session_name The name of the session. * * @return boolean True on success, false otherwise. * * @since 11.1 */ public function open($save_path, $session_name) { return true; } /** * Close the SessionHandler backend. * * @return boolean True on success, false otherwise. * * @since 11.1 */ public function close() { return true; } /** * Read the data for a particular session identifier from the * SessionHandler backend. * * @param string $id The session identifier. * * @return string The session data. * * @since 11.1 */ public function read($id) { return; } /** * Write session data to the SessionHandler backend. * * @param string $id The session identifier. * @param string $session_data The session data. * * @return boolean True on success, false otherwise. * * @since 11.1 */ public function write($id, $session_data) { return true; } /** * Destroy the data for a particular session identifier in the * SessionHandler backend. * * @param string $id The session identifier. * * @return boolean True on success, false otherwise. * * @since 11.1 */ public function destroy($id) { return true; } /** * Garbage collect stale sessions from the SessionHandler backend. * * @param integer $maxlifetime The maximum age of a session. * * @return boolean True on success, false otherwise. * * @since 11.1 */ public function gc($maxlifetime = null) { return true; } /** * Test to see if the SessionHandler is available. * * @return boolean True on success, false otherwise. * * @since 12.1 */ public static function isSupported() { return true; } /** * Test to see if the SessionHandler is available. * * @return boolean True on success, false otherwise. * * @since 11.1 * @deprecated 12.3 Use JSessionStorage::isSupported() instead. */ public static function test() { JLog::add('JSessionStorage::test() is deprecated. Use JSessionStorage::isSupported() instead.', JLog::WARNING, 'deprecated'); return static::isSupported(); } }
eBaySF/joomla-platform
libraries/joomla/session/storage.php
PHP
gpl-2.0
4,531
package org.paninij.proc.check.capsule.decls; import java.util.List; import org.paninij.lang.Capsule; @Capsule class TypeParamsCore { <T> void init(List<T> list) { // Nothing } }
paninij/paninij
core/proc/src/test/paninij/org/paninij/proc/check/capsule/decls/run/TypeParamsCore.java
Java
gpl-2.0
198
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /** * @author Michael Danilov */ package java.awt.event; import java.awt.AWTEvent; import junit.framework.TestCase; public class AWTEventListenerProxyTest extends TestCase { boolean flag = false; public final void testAWTEventListenerProxy() { AWTEventListenerProxy proxy = new AWTEventListenerProxy(AWTEvent.ACTION_EVENT_MASK, new AWTEventListener() { public void eventDispatched(AWTEvent event) { } } ); assertEquals(proxy.getEventMask(), AWTEvent.ACTION_EVENT_MASK); } public final void testEventDispatched() { AWTEventListenerProxy proxy = new AWTEventListenerProxy(AWTEvent.ACTION_EVENT_MASK, new AWTEventListener() { public void eventDispatched(AWTEvent event) { flag = true; } } ); proxy.eventDispatched(new TextEvent(new Object(), TextEvent.TEXT_VALUE_CHANGED)); assertTrue(flag); } }
shannah/cn1
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/awt/src/test/impl/boot/java/awt/event/AWTEventListenerProxyTest.java
Java
gpl-2.0
1,915
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Ombi.Api.Plex; using Ombi.Api.Plex.Models.Status; using Ombi.Core.Settings; using Ombi.Core.Settings.Models.External; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Ombi.HealthChecks.Checks { public class PlexHealthCheck : BaseHealthCheck { public PlexHealthCheck(IServiceScopeFactory serviceScopeFactory) : base(serviceScopeFactory) { } public override async Task<HealthCheckResult> CheckHealthAsync( HealthCheckContext context, CancellationToken cancellationToken = default) { using (var scope = CreateScope()) { var settingsProvider = scope.ServiceProvider.GetRequiredService<ISettingsService<PlexSettings>>(); var api = scope.ServiceProvider.GetRequiredService<IPlexApi>(); var settings = await settingsProvider.GetSettingsAsync(); if (settings == null) { return HealthCheckResult.Healthy("Plex is not confiured."); } var taskResult = new List<Task<PlexStatus>>(); foreach (var server in settings.Servers) { taskResult.Add(api.GetStatus(server.PlexAuthToken, server.FullUri)); } try { var result = await Task.WhenAll(taskResult.ToArray()); return HealthCheckResult.Healthy(); } catch (Exception e) { return HealthCheckResult.Unhealthy("Could not communicate with Plex", e); } } } } }
tidusjar/PlexRequests.Net
src/Ombi.HealthChecks/Checks/PlexHealthCheck.cs
C#
gpl-2.0
1,842
#ifndef _CNWDOMAIN_H_ #define _CNWDOMAIN_H_ #include "nwndef.h" class CNWDomain { public: int GetDescriptionText(); int GetNameText(); ~CNWDomain(); CNWDomain(); }; #endif
jd28/nwnx2-linux
api/CNWDomain.h
C
gpl-2.0
190
<?php // this file contains the contents of the popup window $type = 'Column'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Insert <?php echo $type; ?> Icon</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script> <script language="javascript" type="text/javascript" src="../../../../wp-includes/js/tinymce/tiny_mce_popup.js"></script> <style type="text/css" src="../../wp-includes/js/tinymce/themes/advanced/skins/wp_theme/dialog.css"></style> <link rel="stylesheet" href="../css/themewich-tinyMCE.css" /> <script type="text/javascript"> var <?php echo $type; ?>Dialog = { init : function(ed) { // Resize box to inner size tinyMCEPopup.resizeToInnerSize(); }, insert : function insert<?php echo $type; ?>(ed) { // set up variables to contain our input values var width = jQuery('#<?php echo strtolower($type); ?>-dialog select#<?php echo strtolower($type); ?>-width').val(); var position = jQuery('#<?php echo strtolower($type); ?>-dialog select#<?php echo strtolower($type); ?>-position').val(); // setup the output of our shortcode output = '[tw-column '; output += 'width="' + width + '"'; if (position && position != '') { output += ' position="' + position + '"'; } output += ']'; // Add selected content if (ed.selection.getContent()) { output += ed.selection.getContent(); } else { output += 'Column Text' } // Close column shortcode output += '[/tw-column]<br /><br />'; ed.execCommand('mceReplaceContent', false, output); // Return tinyMCEPopup.close(); } }; tinyMCEPopup.onInit.add(<?php echo $type; ?>Dialog.init, <?php echo $type; ?>Dialog); </script> </head> <body> <div id="<?php echo strtolower($type); ?>-dialog" class="themewich-dialog-box"> <form action="/" method="get" accept-charset="utf-8"> <div> <label for="<?php echo strtolower($type); ?>-width">Column Width</label> <select name="<?php echo strtolower($type); ?>-width" id="<?php echo strtolower($type); ?>-width" size="1"> <option value="one-half" selected="selected">1/2</option> <option value="one-third">1/3</option> <option value="one-fourth">1/4</option> <option value="one-fifth">1/5</option> <option value="one-sixth">1/6</option> <option value="two-third">2/3</option> <option value="three-fourth">3/4</option> <option value="two-fifth">2/5</option> <option value="three-fifth">3/5</option> <option value="four-fifth">4/5</option> <option value="five-sixth">5/6</option> </select> </div> <br style="clear:both;" /> <div> <label for="<?php echo strtolower($type); ?>-position">Position</label> <select name="<?php echo strtolower($type); ?>-position" id="<?php echo strtolower($type); ?>-position" size="1"> <option value="" selected="selected">Not Last</option> <option value="last">Last</option> </select> </div> <br style="clear:both;" /> <div> <a href="javascript:<?php echo $type; ?>Dialog.insert(tinyMCEPopup.editor)" id="insert" title="Insert Shortcode" style="display: block; line-height: 24px;">Insert</a> </div> <br style="clear:both;" /> </form> </div> </body> </html>
alogic/fightchoice
wp-content/plugins/themewich-shortcodes/popups/column_popup.php
PHP
gpl-2.0
3,422
/* linux/arch/arm/plat-s5p/reserve_mem.c * * Copyright (c) 2011 Samsung Electronics Co., Ltd. * http://www.samsung.com/ * * Reserve mem helper functions * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/err.h> #include <linux/memblock.h> #include <linux/mm.h> #include <linux/swap.h> #include <asm/setup.h> #include <linux/io.h> #include <mach/memory.h> #include <plat/media.h> #include <mach/media.h> #ifdef CONFIG_CMA #include <linux/cma.h> void __init s5p_cma_region_reserve(struct cma_region *regions_normal, struct cma_region *regions_secure, size_t align_secure, const char *map) { struct cma_region *reg; phys_addr_t paddr_last = 0xFFFFFFFF; for (reg = regions_normal; reg->size != 0; reg++) { phys_addr_t paddr; if (!IS_ALIGNED(reg->size, PAGE_SIZE)) { pr_debug("S5P/CMA: size of '%s' is NOT page-aligned\n", reg->name); reg->size = PAGE_ALIGN(reg->size); } if (reg->reserved) { pr_err("S5P/CMA: '%s' already reserved\n", reg->name); continue; } if (reg->alignment) { if ((reg->alignment & ~PAGE_MASK) || (reg->alignment & ~reg->alignment)) { pr_err("S5P/CMA: Failed to reserve '%s': " "incorrect alignment 0x%08x.\n", reg->name, reg->alignment); continue; } } else { reg->alignment = PAGE_SIZE; } if (reg->start) { if (!memblock_is_region_reserved(reg->start, reg->size) && (memblock_reserve(reg->start, reg->size) == 0)) reg->reserved = 1; else { pr_err("S5P/CMA: Failed to reserve '%s'\n", reg->name); continue; } pr_debug("S5P/CMA: " "Reserved 0x%08x/0x%08x for '%s'\n", reg->start, reg->size, reg->name); paddr = reg->start; } else { paddr = memblock_find_in_range(0, MEMBLOCK_ALLOC_ACCESSIBLE, reg->size, reg->alignment); } if (paddr != MEMBLOCK_ERROR) { if (memblock_reserve(paddr, reg->size)) { pr_err("S5P/CMA: Failed to reserve '%s'\n", reg->name); continue; } reg->start = paddr; reg->reserved = 1; pr_debug("S5P/CMA: Reserved 0x%08x/0x%08x for '%s'\n", reg->start, reg->size, reg->name); } else { pr_err("S5P/CMA: No free space in memory for '%s'\n", reg->name); } if (cma_early_region_register(reg)) { pr_err("S5P/CMA: Failed to register '%s'\n", reg->name); memblock_free(reg->start, reg->size); } else { paddr_last = min(paddr, paddr_last); } } if (align_secure & ~align_secure) { pr_err("S5P/CMA: " "Wrong alignment requirement for secure region.\n"); } else if (regions_secure && regions_secure->size) { size_t size_secure = 0; for (reg = regions_secure; reg->size != 0; reg++) size_secure += reg->size; reg--; /* Entire secure regions will be merged into 2 * consecutive regions. */ if (align_secure == 0) { size_t size_region2; size_t order_region2; size_t aug_size; align_secure = 1 << (get_order((size_secure + 1) / 2) + PAGE_SHIFT); /* Calculation of a subregion size */ size_region2 = size_secure - align_secure; order_region2 = get_order(size_region2) + PAGE_SHIFT; if (order_region2 < 20) order_region2 = 20; /* 1MB */ order_region2 -= 3; /* divide by 8 */ size_region2 = ALIGN(size_region2, 1 << order_region2); aug_size = align_secure + size_region2 - size_secure; if (aug_size > 0) { reg->size += aug_size; size_secure += aug_size; pr_debug("S5P/CMA: " "Augmented size of '%s' by %#x B.\n", reg->name, aug_size); } } else size_secure = ALIGN(size_secure, align_secure); pr_debug("S5P/CMA: " "Reserving %#x for secure region aligned by %#x.\n", size_secure, align_secure); if (paddr_last >= memblock.current_limit) { paddr_last = memblock_find_in_range(0, MEMBLOCK_ALLOC_ACCESSIBLE, size_secure, reg->alignment); } else { paddr_last -= size_secure; paddr_last = round_down(paddr_last, align_secure); } if (paddr_last) { while (memblock_reserve(paddr_last, size_secure)) paddr_last -= align_secure; do { reg->start = paddr_last; reg->reserved = 1; paddr_last += reg->size; pr_info("S5P/CMA: " "Reserved 0x%08x/0x%08x for '%s'\n", reg->start, reg->size, reg->name); if (cma_early_region_register(reg)) { memblock_free(reg->start, reg->size); pr_err("S5P/CMA: " "Failed to register secure region " "'%s'\n", reg->name); } else { size_secure -= reg->size; } } while (reg-- != regions_secure); if (size_secure > 0) memblock_free(paddr_last, size_secure); } else { pr_err("S5P/CMA: Failed to reserve secure regions\n"); } } if (map) cma_set_defaults(NULL, map); } #else extern struct s5p_media_device media_devs[]; extern int nr_media_devs; static dma_addr_t media_base[NR_BANKS]; static struct s5p_media_device *s5p_get_media_device(int dev_id, int bank) { struct s5p_media_device *mdev = NULL; int i = 0, found = 0; if (dev_id < 0) return NULL; while (!found && (i < nr_media_devs)) { mdev = &media_devs[i]; if (mdev->id == dev_id && mdev->bank == bank) found = 1; else i++; } if (!found) mdev = NULL; return mdev; } dma_addr_t s5p_get_media_memory_bank(int dev_id, int bank) { struct s5p_media_device *mdev; mdev = s5p_get_media_device(dev_id, bank); if (!mdev) { printk(KERN_ERR "invalid media device\n"); return 0; } if (!mdev->paddr) { printk(KERN_ERR "no memory for %s\n", mdev->name); return 0; } return mdev->paddr; } EXPORT_SYMBOL(s5p_get_media_memory_bank); size_t s5p_get_media_memsize_bank(int dev_id, int bank) { struct s5p_media_device *mdev; mdev = s5p_get_media_device(dev_id, bank); if (!mdev) { printk(KERN_ERR "invalid media device\n"); return 0; } return mdev->memsize; } EXPORT_SYMBOL(s5p_get_media_memsize_bank); dma_addr_t s5p_get_media_membase_bank(int bank) { if (bank > meminfo.nr_banks) { printk(KERN_ERR "invalid bank.\n"); return -EINVAL; } return media_base[bank]; } EXPORT_SYMBOL(s5p_get_media_membase_bank); void s5p_reserve_mem(size_t boundary) { struct s5p_media_device *mdev; u64 start, end; int i, ret; for (i = 0; i < meminfo.nr_banks; i++) media_base[i] = meminfo.bank[i].start + meminfo.bank[i].size; for (i = 0; i < nr_media_devs; i++) { mdev = &media_devs[i]; if (mdev->memsize <= 0) continue; if (mdev->bank > meminfo.nr_banks) { pr_err("mdev %s: mdev->bank(%d), max_bank(%d)\n", mdev->name, mdev->bank, meminfo.nr_banks); return; } if (!mdev->paddr) { start = meminfo.bank[mdev->bank].start; end = start + meminfo.bank[mdev->bank].size; if (boundary && (boundary < end - start)) start = end - boundary; mdev->paddr = memblock_find_in_range(start, end, mdev->memsize, PAGE_SIZE); } ret = memblock_reserve(mdev->paddr, mdev->memsize); if (ret < 0) pr_err("memblock_reserve(%x, %x) failed\n", mdev->paddr, mdev->memsize); if (media_base[mdev->bank] > mdev->paddr) media_base[mdev->bank] = mdev->paddr; printk(KERN_INFO "s5p: %lu bytes system memory reserved " "for %s at 0x%08x, %d-bank base(0x%08x)\n", (unsigned long) mdev->memsize, mdev->name, mdev->paddr, mdev->bank, media_base[mdev->bank]); } } #endif /* CONFIG_CMA */
moguriso/isw11sc-kernel
arch/arm/plat-s5p/reserve_mem.c
C
gpl-2.0
7,420
\documentclass{article} \begin{document} \section{Font commands} First the trickiest bit. {\it This is in italics {\em this is emphasized} but this is italics and {\em this final bit is emphasized} but this is not.} An easier test. \textit{This is in italics \emph{this is emphasized} but this is italics and \emph{this final bit is emphasized} but this is not.} This is roman, testing \verb#itshape# {\itshape italics} more roman text. This is roman, testing \verb#\begin{itshape}# \begin{itshape} italics\end{itshape} more roman text. This is roman, testing \verb#\textit# \textit{italics} more roman text. \section{Emphasize commands} \subsection{the em environment} Testing the \verb#\em# environment by \begin{em}emphasizing text and then \begin{em}embedding another level inside\end{em} of the first level.\end{em} this is some text \begin{em} with some emphasized text \end{em} in the middle. {\bf this is some bold text \begin{em} with some emphasized text \end{em} in the middle.} \textbf{this is some bold text \begin{em} with some emphasized text \end{em} in the middle.} \textit{this is some italic text \begin{em} with some emphasized text \end{em} in the middle.} \subsection{the emph command} Next testing \verb#\emph# by \emph{emphasizing text and then \emph{embedding another level inside} of the first level.} this is some text \emph{with some emphasized text} in the middle. {\bf this is some bold text \emph{with some emphasized text} in the middle.} \textbf{this is some bold text \emph{with some emphasized text} in the middle.} \textit{this is some italic text \emph{with some emphasized text} in the middle.} \subsection{the em command} First testing \verb#\em# by {\em emphasizing text and then {\em embedding another level inside} of the first level.} this is some text {\em with some emphasized text} in the middle. {\bf this is some bold text {\em with some emphasized text} in the middle.} \textbf{this is some bold text {\em with some emphasized text} in the middle.} \textit{this is some italic text {\em with some emphasized text} in the middle.} \section{Miscellaneous} what about \it some italics \bf some bold \rm followed by roman {\it here is italics \tt followed by plain typewriter} {\it here is italics \sf followed by plain sans serif} \textbf{here is bold roman \sf followed by plain sans serif} {\bf here is bold roman \textsf{followed by bold sans serif}} \textbf{\textit{bold italics \sf followed by plain sans serif}} \textbf{\textit{bold italics \textsf{followed by bold italics sans serif}}} \section{Normal roman font} \begin{itemize} \item Testing \verb#\rm# by \textsf{sans serif text with {\rm some roman text} in the middle}. \item Testing \verb#\rm# by \textit{italic text with {\rm some roman text} in the middle}. \item Testing \verb#\rm# by \textbf{bold text with {\rm some plain roman text} in the middle}. \item Testing \verb#\rm# by \textsc{small caps with some {\rm some plain roman text} in the middle}. \item Testing \verb#\textrm# by \textsf{sans serif text with \textrm{some roman text} in the middle}. \item Testing \verb#\textrm# by \textit{italic text with \textrm{some italic roman text} in the middle}. \item Testing \verb#\textrm# by \textbf{bold text with \textrm{some bold roman text} in the middle}. \item Testing \verb#\textrm# by \textsc{small caps with some \textrm{some small caps roman text} in the middle}. \item Testing \verb#\rmfamily# by \textsf{sans serif text with {\rmfamily some roman text} in the middle}. \item Testing \verb#\rmfamily# by \textit{italic text with {\rmfamily some italic roman text} in the middle}. \item Testing \verb#\rmfamily# by \textbf{bold text with {\rmfamily some bold roman text} in the middle}. \item Testing \verb#\rmfamily# by \textsc{small caps with some {\rmfamily some roman text} in the middle}. \item We also have math $x+y = \mathrm{truth}$. \end{itemize} \section{Normal sans serif font} This is some text. \emph{This text is emphasized} \begin{itemize} \item Testing \verb#\sf# by \textrm{roman text with {\sf some plain sans serif text} in the middle}. \item Testing \verb#\sf# by \textit{italic text with {\sf some plain sans serif text} in the middle}. \item Testing \verb#\sf# by \textbf{bold text with {\sf some plain sans serif text} in the middle}. \item Testing \verb#\sf# by \textsc{small caps with some {\sf some plain sans serif text} in the middle}. \item Testing \verb#\textsf# by \textrm{roman text with \textsf{some sans serif text} in the middle}. \item Testing \verb#\textsf# by \textit{italic text with \textsf{some italic sans serif text} in the middle}. \item Testing \verb#\textsf# by \textbf{bold text with \textsf{some bold sans serif text} in the middle}. \item Testing \verb#\textsf# by \textsc{small caps with some \textsf{some small caps sans serif text} in the middle}. \item Testing \verb#\sffamily# by \textrm{roman text with {\sffamily some sans serif text} in the middle}. \item Testing \verb#\sffamily# by \textit{italic text with {\sffamily some italic sans serif text} in the middle}. \item Testing \verb#\sffamily# by \textbf{bold text with {\sffamily some bold sans serif text} in the middle}. \item Testing \verb#\sffamily# by \textsc{small caps with some {\sffamily some small caps sans serif text} in the middle}. \end{itemize} \end{document}
zvr/latex2rtf-zvr
test/fonts.tex
TeX
gpl-2.0
5,346
/* * Copyright (c) 2009 Voltaire, Inc. All rights reserved. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * */ #include <stdio.h> #include <string.h> #include <errno.h> #include <inttypes.h> #include <getopt.h> #include <sys/time.h> #include <infiniband/umad.h> #include <infiniband/mad.h> static unsigned number_queries = 1; static uint8_t dr_path[64]; static size_t dr_path_size = 0; static uint16_t attribute_id = IB_ATTR_NODE_INFO; static uint32_t attribute_mod = 0; static unsigned timeout = 100; static unsigned retries = 3; static unsigned verbose = 0; #define ERROR(fmt, ...) fprintf(stderr, "ERR: " fmt, ##__VA_ARGS__) #define VERBOSE(fmt, ...) if (verbose) fprintf(stderr, fmt, ##__VA_ARGS__) #define NOISE(fmt, ...) if (verbose > 1) fprintf(stderr, fmt, ##__VA_ARGS__) static const char *print_path(uint8_t path[], size_t path_cnt) { static char buf[256]; int i, n = 0; for (i = 0; i <= path_cnt; i++) n += snprintf(buf + n, sizeof(buf) - n, "%u,", path[i]); buf[n] = '\0'; return buf; } static size_t parse_direct_path(const char *str, uint8_t path[], size_t size) { size_t i; for (i = 0; i < size; i++) { path[i] = strtoul(str, NULL, 0); str = strchr(str, ','); if (!str) break; str++; } return i; } static void build_umad_req(void *umad, uint8_t * path, unsigned path_cnt, uint64_t trid, uint8_t method, uint16_t attr_id, uint32_t attr_mod, uint64_t mkey) { void *mad = umad_get_mad(umad); memset(umad, 0, umad_size() + IB_MAD_SIZE); umad_set_addr(umad, 0xffff, 0, 0, 0); mad_set_field(mad, 0, IB_MAD_METHOD_F, method); mad_set_field(mad, 0, IB_MAD_CLASSVER_F, 1); mad_set_field(mad, 0, IB_MAD_MGMTCLASS_F, IB_SMI_DIRECT_CLASS); mad_set_field(mad, 0, IB_MAD_BASEVER_F, 1); mad_set_field(mad, 0, IB_DRSMP_HOPCNT_F, path_cnt); mad_set_field(mad, 0, IB_DRSMP_HOPPTR_F, 0); mad_set_field64(mad, 0, IB_MAD_TRID_F, trid); mad_set_field(mad, 0, IB_DRSMP_DRDLID_F, 0xffff); mad_set_field(mad, 0, IB_DRSMP_DRSLID_F, 0xffff); mad_set_array(mad, 0, IB_DRSMP_PATH_F, path); mad_set_field(mad, 0, IB_MAD_ATTRID_F, attr_id); mad_set_field(mad, 0, IB_MAD_ATTRMOD_F, attr_mod); mad_set_field64(mad, 0, IB_MAD_MKEY_F, mkey); } static void check_diff(const char *name, void *mad, struct timeval *tv1, struct timeval *tv) { unsigned long diff = (tv1->tv_sec - tv->tv_sec) * 1000000 + tv1->tv_usec - tv->tv_usec; if (diff > 1000) { uint8_t path[256]; uint8_t method = mad_get_field(mad, 0, IB_MAD_METHOD_F); uint64_t trid = mad_get_field64(mad, 0, IB_MAD_TRID_F); uint16_t attr_id = mad_get_field(mad, 0, IB_MAD_ATTRID_F); uint32_t attr_mod = mad_get_field(mad, 0, IB_MAD_ATTRMOD_F); size_t path_cnt = mad_get_field(mad, 0, IB_DRSMP_HOPCNT_F); mad_get_array(mad, 0, IB_DRSMP_PATH_F, path); printf("LONG %s (%lu) %016" PRIx64 ": method %x, attr %x," " mod %x, path %s\n", name, diff, trid, method, attr_id, attr_mod, print_path(path, path_cnt)); fflush(stdout); } } static int send_query(int fd, int agent, void *umad, uint64_t trid, uint8_t * path, size_t path_cnt, uint16_t attr_id, uint32_t attr_mod) { struct timeval tv, tv1; int ret; build_umad_req(umad, path, path_cnt, trid, IB_MAD_METHOD_GET, attr_id, attr_mod, 0); gettimeofday(&tv, NULL); ret = umad_send(fd, agent, umad, IB_MAD_SIZE, timeout, retries); gettimeofday(&tv1, NULL); if (ret < 0) { ERROR("umad_send failed: trid 0x%016" PRIx64 ", attr_id %x, attr_mod %x: %s\n", trid, attr_id, attr_mod, strerror(errno)); return -1; } VERBOSE("send %016" PRIx64 ": attr %x, mod %x to %s\n", trid, attr_id, attr_mod, print_path(path, path_cnt)); check_diff("SEND", umad_get_mad(umad), &tv1, &tv); return ret; } static int recv_response(int fd, int agent, uint8_t * umad, uint8_t path[]) { struct timeval tv, tv1; void *mad; uint64_t trid; uint32_t attr_mod; uint16_t attr_id, status; size_t path_size; int len = IB_MAD_SIZE, ret; gettimeofday(&tv, NULL); do { ret = umad_recv(fd, umad, &len, timeout); } while (ret >= 0 && ret != agent); gettimeofday(&tv1, NULL); if (ret < 0 || umad_status(umad)) { ERROR("umad_recv failed: umad status %x: %s\n", umad_status(umad), strerror(errno)); return -1; } check_diff("RESP", umad_get_mad(umad), &tv1, &tv); mad = umad_get_mad(umad); status = mad_get_field(mad, 0, IB_DRSMP_STATUS_F); trid = mad_get_field64(mad, 0, IB_MAD_TRID_F); attr_id = mad_get_field(mad, 0, IB_MAD_ATTRID_F); attr_mod = mad_get_field(mad, 0, IB_MAD_ATTRMOD_F); path_size = mad_get_field(mad, 0, IB_DRSMP_HOPCNT_F); mad_get_array(mad, 0, IB_DRSMP_PATH_F, path); if (status) { ERROR("error response 0x%016" PRIx64 ": attr_id %x" ", attr_mod %x from %s with status %x\n", trid, attr_id, attr_mod, print_path(path, path_size), status); return -1; } VERBOSE("recv %016" PRIx64 ": attr %x, mod %x from %s\n", trid, attr_id, attr_mod, print_path(path, path_size)); return ret; } static int query(int fd, int agent) { uint8_t path[64] = { 0 }; uint64_t trid = 0x20090000; void *umad; unsigned n = 0; int ret = 0; umad = malloc(IB_MAD_SIZE + umad_size()); if (!umad) return -ENOMEM; while (n++ < number_queries) send_query(fd, agent, umad, trid++, dr_path, dr_path_size, attribute_id, attribute_mod); n = 0; do { ret = recv_response(fd, agent, umad, path); } while (ret >= 0 && ++n < number_queries); free(umad); return ret; } static int umad_query(char *card_name, unsigned int port_num) { int fd, agent, ret; ret = umad_init(); if (ret) { ERROR("cannot init umad\n"); return -1; } fd = umad_open_port(card_name, port_num); if (fd < 0) { ERROR("cannot open umad port %s:%u: %s\n", card_name ? card_name : "NULL", port_num, strerror(errno)); return -1; } agent = umad_register(fd, IB_SMI_DIRECT_CLASS, 1, 0, NULL); if (agent < 0) { ERROR("cannot register SMI DR class for umad port %s:%u: %s\n", card_name ? card_name : "NULL", port_num, strerror(errno)); return -1; } ret = query(fd, agent); if (ret) ERROR("Failed.\n"); umad_unregister(fd, agent); umad_close_port(fd); umad_done(); return ret; } int main(int argc, char **argv) { const struct option long_opts[] = { {"number", 1, 0, 'n'}, {"drpath", 1, 0, 'd'}, {"attribute", 1, 0, 'a'}, {"modifier", 1, 0, 'm'}, {"Card", 1, 0, 'C'}, {"Port", 1, 0, 'P'}, {"timeout", 1, 0, 't'}, {"retries", 1, 0, 'r'}, {} }; char *card_name = NULL; unsigned int port_num = 0; int ch, ret; while (1) { ch = getopt_long(argc, argv, "n:d:a:m:C:P:t:r:v", long_opts, NULL); if (ch == -1) break; switch (ch) { case 'n': number_queries = strtoul(optarg, NULL, 0); break; case 'd': dr_path_size = parse_direct_path(optarg, dr_path, sizeof(dr_path)); break; case 'a': attribute_id = strtoul(optarg, NULL, 0); break; case 'm': attribute_mod = strtoul(optarg, NULL, 0); break; case 'C': card_name = optarg; break; case 'P': port_num = strtoul(optarg, NULL, 0); break; case 't': timeout = strtoul(optarg, NULL, 0); break; case 'r': retries = strtoul(optarg, NULL, 0); break; case 'v': verbose++; break; default: printf("Usage: %s [-n num_queries] [-d path]" " [-a attr] [-m mod]" " [-C card_name] [-P port_num]" " [-t timeout] [-r retries] [-v[v]]\n", argv[0]); exit(2); break; } } ret = umad_query(card_name, port_num); return ret; }
jgunthorpe/ibsim
tests/query_many.c
C
gpl-2.0
7,734
<?php /* * @version $Id$ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2014 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ if (!defined('GLPI_ROOT')) { die("Sorry. You can't access directly to this file"); } /// LDAP criteria class class RuleRightParameter extends CommonDropdown { static $rightname = 'rule_ldap'; var $can_be_translated = false; /** * @see CommonDBTM::prepareInputForAdd() **/ function prepareInputForAdd($input) { //LDAP parameters MUST be in lower case //because the are retieved in lower case from the directory $input["value"] = Toolbox::strtolower($input["value"]); return $input; } function getAdditionalFields() { return array(array('name' => 'value', 'label' => _n('Criterion', 'Criteria', 1), 'type' => 'text', 'list' => false)); } /** * Get search function for the class * * @return array of search option **/ function getSearchOptions() { $tab = parent::getSearchOptions(); $tab[11]['table'] = $this->getTable(); $tab[11]['field'] = 'value'; $tab[11]['name'] = _n('Criterion', 'Criteria', 1); $tab[11]['datatype'] = 'string'; return $tab; } static function getTypeName($nb=0) { return _n('LDAP criterion', 'LDAP criteria', $nb); } } ?>
orthagh/glpi-configuration
inc/rulerightparameter.class.php
PHP
gpl-2.0
2,354
#!/usr/bin/pythonTest # -*- coding: utf-8 -*- # # Web functions want links # # 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 Library General Public License for more details. # # The GNU General Public License is available from: # The Free Software Foundation, Inc. # 51 Franklin Street, Fifth Floor # Boston MA 02110-1301 USA # # http://www.gnu.org/licenses/gpl.html # # Copyright 2015-2016 Rick Graves # def getUniqueLinks( sReadFile, sOutFile ): # from File.Get import getListFromFileLines from File.Write import QuickDumpLines # from Web.Address import getHostPathTuple, getDomainOffURL from Web.Test import isURL # lLines = getListFromFileLines( sReadFile ) # setLinks= frozenset( filter( isURL, lLines ) ) # # lDecorate = [ ( getHostPathTuple( sURL ), sURL ) for sURL in setLinks ] # lDecorate = [ ( ( getDomainOffURL( t[0][0] ), t[0][1] ), t[1] ) for t in lDecorate ] # lDecorate.sort() # lLinks = [ t[1] for t in lDecorate ] # QuickDumpLines( lLinks, sOutFile ) if __name__ == "__main__": # from os.path import join from sys import argv # from six import print_ as print3 # from Dir.Get import sTempDir from File.Test import isFileThere from Utils.Result import sayTestResult # lProblems = [] # args = argv[ 1 : ] # sReadFile = join( sTempDir, 'LotsOfLinks.txt' ) sOutFile = join( sTempDir, 'UniqueLinks.txt' ) # if args: # sReadFile = args[0] # if len( args ) > 1: # sOutFile = args[2] # # else: # if isFileThere( sReadFile ): # getUniqueLinks( sReadFile, sOutFile ) # else: # print3( 'Usage: WantLinks [inputFile [, outputFile] ]' ) print3( 'default inputFile {temp dir}lotsolinks.txt' ) print3( 'default outputFile {temp dir}UniqueLinks.txt' ) # # # if False: # lProblems.append( 'getDotQuad4IspTester()' ) # # # sayTestResult( lProblems )
netvigator/myPyPacks
pyPacks/Web/WantLinks.py
Python
gpl-2.0
2,653
import BaseHTTPServer import cgi import ctypes import os import sys import threading from PySide import QtGui import MaxPlus PORT = 8000 class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.exiting = False address = ('localhost', PORT) self.server = BaseHTTPServer.HTTPServer(address, MyHandler) self._stop = threading.Event() def run(self): self.server.serve_forever() def stop(self): self.server.server_close() self.server.shutdown() self._stop.set() class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): rootdir = os.path.join(os.path.dirname(__file__) + '/html') try: if self.path == '/': self.path = '/index.html' if self.path.endswith('.html'): self.send_response(200) self.send_header('Content-type','text-html') self.end_headers() f = open(rootdir + self.path) self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404, 'file not found') def do_POST(self): if self.path=="/cmd": form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) self.send_response(301) self.send_header('Location', '/') self.end_headers() try: MaxPlus.Core.EvalMAXScript(form["cmd"].value) MaxPlus.ViewportManager_ForceCompleteRedraw() except: print "Needs to be run from a 3ds max instance" return class MyWindow(QtGui.QWidget): def __init__(self, parent=None): super(MyWindow, self).__init__(parent) self.setWindowTitle('Simple 3ds Max webserver') self.resize(200,50) self.btn_run = QtGui.QPushButton('Run') layout = QtGui.QVBoxLayout() layout.addWidget(self.btn_run) self.setLayout(layout) self.btn_run.clicked.connect(self.run) self.serverThread = None def run(self): if not self.serverThread: print "Serving at port", PORT self.btn_run.setText('Stop...') self.serverThread = MyThread() self.serverThread.start() else: print "Stopping webserver" self.btn_run.setText('Run') self.serverThread.stop() self.serverThread = None def closeEvent(self, *args, **kwargs): if self.serverThread: print "Stopping webserver" self.btn_run.setText('Run') self.serverThread.stop() self.serverThread = None class _GCProtector(object): controls = [] if __name__ == '__main__': app = QtGui.QApplication.instance() if not app: app = QtGui.QApplication([]) window = MyWindow() _GCProtector.controls.append(window) window.show() capsule = window.effectiveWinId() ctypes.pythonapi.PyCObject_AsVoidPtr.restype = ctypes.c_void_p ctypes.pythonapi.PyCObject_AsVoidPtr.argtypes = [ctypes.py_object] ptr = ctypes.pythonapi.PyCObject_AsVoidPtr(capsule) MaxPlus.Win32.Set3dsMaxAsParentWindow(ptr)
maxwellalive/YCDIVFX_MaxPlus
Examples/simplewebserver.py
Python
gpl-2.0
3,452
<?php /** * Installation routines for optimizeMember. * * Copyright: © 2009-2011 * {@link http://www.optimizepress.com/ optimizePress, Inc.} * ( coded in the USA ) * * Released under the terms of the GNU General Public License. * You should have received a copy of the GNU General Public License, * along with this software. In the main directory, see: /licensing/ * If not, see: {@link http://www.gnu.org/licenses/}. * * @package optimizeMember\Installation * @since 3.5 */ if(realpath(__FILE__) === realpath($_SERVER["SCRIPT_FILENAME"])) exit("Do not access this file directly."); /**/ if(!class_exists("c_ws_plugin__optimizemember_installation")) { /** * Installation routines for optimizeMember. * * @package optimizeMember\Installation * @since 3.5 */ class c_ws_plugin__optimizemember_installation { /** * Activation routines for optimizeMember. * * @package optimizeMember\Installation * @since 3.5 * * @return null */ public static function activate($reactivation_reason = FALSE) { global $wpdb; /* Global database object reference. */ global $current_site, $current_blog; /* Multisite. */ /**/ do_action("ws_plugin__optimizemember_before_activation", get_defined_vars()); /**/ c_ws_plugin__optimizemember_roles_caps::config_roles(); /* Config Roles/Caps. */ update_option("ws_plugin__optimizemember_activated_levels", $GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["levels"]); /**/ /*THIS LINE MOVE PRO FOLDER INTO RIGHT PLACE!*/ //@rename($GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["dir"].'/optimizeMember-pro', WP_PLUGIN_DIR.'/optimizeMember-pro'); if(!is_dir($files_dir = $GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["files_dir"])) if(is_writable(dirname(c_ws_plugin__optimizemember_utils_dirs::strip_dir_app_data($files_dir)))) mkdir($files_dir, 0777, true); /**/ if(is_dir($files_dir) && is_writable($files_dir)) if(!file_exists($htaccess = $files_dir."/.htaccess") || !apply_filters("ws_plugin__optimizemember_preserve_files_dir_htaccess", false, get_defined_vars())) file_put_contents($htaccess, trim(c_ws_plugin__optimizemember_utilities::evl(file_get_contents($GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["files_dir_htaccess"])))); /**/ c_ws_plugin__optimizemember_files::write_no_gzip_into_root_htaccess /* Handle the root `.htaccess` file as well now, for GZIP exclusions. */(); /**/ if(!is_dir($logs_dir = $GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["logs_dir"])) if(is_writable(dirname(c_ws_plugin__optimizemember_utils_dirs::strip_dir_app_data($logs_dir)))) mkdir($logs_dir, 0777, true); /**/ if(is_dir($logs_dir) && is_writable($logs_dir)) if(!file_exists($htaccess = $logs_dir."/.htaccess") || !apply_filters("ws_plugin__optimizemember_preserve_logs_dir_htaccess", false, get_defined_vars())) file_put_contents($htaccess, trim(c_ws_plugin__optimizemember_utilities::evl(file_get_contents($GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["logs_dir_htaccess"])))); /**/ (!is_array(get_option("ws_plugin__optimizemember_cache"))) ? update_option("ws_plugin__optimizemember_cache", array()) : null; (!is_array(get_option("ws_plugin__optimizemember_notices"))) ? update_option("ws_plugin__optimizemember_notices", array()) : null; (!is_array(get_option("ws_plugin__optimizemember_options"))) ? update_option("ws_plugin__optimizemember_options", array()) : null; (!is_numeric(get_option("ws_plugin__optimizemember_configured"))) ? update_option("ws_plugin__optimizemember_configured", "0") : null; /**/ if($GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["configured"]) /* If we are re-activating. */ { $v = get_option("ws_plugin__optimizemember_activated_version"); /* Currently. */ /**/ if(!$v || !version_compare($v, "3.2", ">=")) /* Needs to be upgraded? */ /* Version 3.2 is where `meta_key` names were changed. They're prefixed now. */ { $like = "`meta_key` LIKE 's2member\_%' AND `meta_key` NOT LIKE '%s2member\_originating\_blog%'"; $wpdb->query("UPDATE `".$wpdb->usermeta."` SET `meta_key` = CONCAT('".$wpdb->prefix."', `meta_key`) WHERE ".$like); } /**/ if(!$v || !version_compare($v, "3.2.5", ">=")) /* Needs to be upgraded? */ /* Version 3.2.5 is where transient names were changed. They're prefixed now. */ { $wpdb->query("DELETE FROM `".$wpdb->options."` WHERE `option_name` LIKE '\_transient\_%'"); } /**/ if(!$v || !version_compare($v, "3.2.6", ">=")) /* Needs to be upgraded? */ /* Version 3.2.6 fixed `optimizemember_ccaps_req` being stored empty and/or w/ one empty element in the array. */ { $wpdb->query("DELETE FROM `".$wpdb->postmeta."` WHERE `meta_key` = 'optimizemember_ccaps_req' AND `meta_value` IN('','a:0:{}','a:1:{i:0;s:0:\"\";}')"); } /**/ if(!$v || !version_compare($v, "110912", ">=") && $GLOBALS["WS_PLUGIN__"]["optimizemember"]["o"]["filter_wp_query"] === array("all")) /* optimizeMember v110912 changed the way the "all" option for Alternative Views was handled. */ { //$notice = '<strong>IMPORTANT:</strong> This version of optimizeMember changes the way your <code>Alternative View Protections</code> work. Please review your options under: <code>optimizeMember -> Restriction Options -> Alternative View Protections</code>.<br />'; $notice = ''; c_ws_plugin__optimizemember_admin_notices::enqueue_admin_notice($notice, array("blog|network:plugins.php", "blog|network:ws-plugin--optimizemember-start", "blog|network:ws-plugin--optimizemember-mms-ops", "blog|network:ws-plugin--optimizemember-gen-ops", "blog|network:ws-plugin--optimizemember-res-ops")); } /**/ $notice = '<strong>optimizeMember</strong> has been <strong>reactivated</strong>, with '.(($reactivation_reason === "levels") ? '<code>'.esc_html($GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["levels"]).'</code> Membership Levels' : 'the latest version').'.<br />'; $notice .= 'You now have version '.esc_html(WS_PLUGIN__OPTIMIZEMEMBER_VERSION).'. Your existing configuration remains.'; /**/ if(!is_multisite() || !c_ws_plugin__optimizemember_utils_conds::is_multisite_farm() || is_main_site()) /* No Changelog on a Multisite Blog Farm. */ //$notice .= '<br />Have fun, <a href="'.esc_attr(admin_url("/admin.php?page=ws-plugin--optimizemember-info#rm-changelog")).'">read the Changelog</a>, and make some money! :-)'; /**/ c_ws_plugin__optimizemember_admin_notices::enqueue_admin_notice($notice, array("blog|network:plugins.php", "blog|network:ws-plugin--optimizemember-start", "blog|network:ws-plugin--optimizemember-mms-ops", "blog|network:ws-plugin--optimizemember-gen-ops", "blog|network:ws-plugin--optimizemember-res-ops")); } else /* Otherwise (initial activation); we'll help the Site Owner out by giving them a link to the Quick Start Guide. */ { $notice = '<strong>Note:</strong> optimizeMember adds some new data columns to your list of Users/Members. If your list gets overcrowded, please use the <strong>Screen Options</strong> tab <em>( upper right-hand corner )</em>. With WordPress Screen Options, you can add/remove specific data columns; thereby making the most important data easier to read. For example, if you create Custom Registration/Profile Fields with optimizeMember, those Custom Fields will result in new data columns; which can cause your list of Users/Members to become nearly unreadable. So just use the Screen Options tab to clean things up.'; /**/ c_ws_plugin__optimizemember_admin_notices::enqueue_admin_notice($notice, "blog:users.php", false, false, true); /**/ $notice = '<strong>optimizeMember</strong> v'.esc_html(WS_PLUGIN__OPTIMIZEMEMBER_VERSION).' has been <strong>activated</strong>. Nice work!<br />'; $notice .= 'Have fun, <a href="'.esc_attr(admin_url("/admin.php?page=ws-plugin--optimizemember-start")).'">read the Quick Start Guide</a>, and make some money! :-)'; /**/ c_ws_plugin__optimizemember_admin_notices::enqueue_admin_notice($notice, array("blog|network:plugins.php", "blog|network:ws-plugin--optimizemember-start", "blog|network:ws-plugin--optimizemember-mms-ops", "blog|network:ws-plugin--optimizemember-gen-ops", "blog|network:ws-plugin--optimizemember-res-ops")); } /**/ if(is_multisite() && is_main_site()) /* Network activation routines. */ { $wpdb->query("INSERT INTO `".$wpdb->usermeta."` (`user_id`, `meta_key`, `meta_value`) SELECT `ID`, 'optimizemember_originating_blog', '".esc_sql($current_site->blog_id)."' FROM `".$wpdb->users."` WHERE `ID` NOT IN (SELECT `user_id` FROM `".$wpdb->usermeta."` WHERE `meta_key` = 'optimizemember_originating_blog')"); /**/ $notice = '<strong>Multisite Network</strong> updated automatically by <strong>optimizeMember</strong> v'.esc_html(WS_PLUGIN__OPTIMIZEMEMBER_VERSION).'.<br />'; $notice .= 'You\'ll want to configure optimizeMember\'s Multisite options now.<br />'; $notice .= 'In the Dashboard for your Main Site, see:<br />'; $notice .= '<code>optimizeMember -> Multisite ( Config )</code>.'; /**/ c_ws_plugin__optimizemember_admin_notices::enqueue_admin_notice($notice, array("blog|network:plugins.php", "blog|network:ws-plugin--optimizemember-start", "blog|network:ws-plugin--optimizemember-mms-ops", "blog|network:ws-plugin--optimizemember-gen-ops", "blog|network:ws-plugin--optimizemember-res-ops")); /**/ update_site_option("ws_plugin__optimizemember_options", (array)get_option("ws_plugin__optimizemember_options")); /**/ update_option("ws_plugin__optimizemember_activated_mms_version", WS_PLUGIN__OPTIMIZEMEMBER_VERSION); } /**/ update_option("ws_plugin__optimizemember_activated_version", WS_PLUGIN__OPTIMIZEMEMBER_VERSION); /**/ do_action("ws_plugin__optimizemember_after_activation", get_defined_vars()); /**/ return; /* Return for uniformity. */ } /** * Deactivation routines for optimizeMember. * * @package optimizeMember\Installation * @since 3.5 * * @return null */ public static function deactivate() { global $wpdb; /* Global database object reference. */ global $current_site, $current_blog; /* Multisite. */ /**/ do_action("ws_plugin__optimizemember_before_deactivation", get_defined_vars()); /**/ /*THIS LINES MOVE PRO FOLDER INTO RIGHT PLACE!*/ //@rename(WP_PLUGIN_DIR.'/optimizeMember-pro', $GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["dir"].'/optimizeMember-pro'); if($GLOBALS["WS_PLUGIN__"]["optimizemember"]["o"]["run_deactivation_routines"]) { c_ws_plugin__optimizemember_roles_caps::unlink_roles(); /* Unlink Roles/Caps. */ /**/ c_ws_plugin__optimizemember_files::remove_no_gzip_from_root_htaccess /* Remove GZIP exclusions. */(); /**/ if(is_dir($files_dir = $GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["files_dir"])) { if(file_exists($htaccess = $files_dir."/.htaccess")) if(is_writable($htaccess)) unlink($htaccess); /**/ @rmdir($files_dir).@rmdir(c_ws_plugin__optimizemember_utils_dirs::strip_dir_app_data($files_dir)); } /**/ if(is_dir($logs_dir = $GLOBALS["WS_PLUGIN__"]["optimizemember"]["c"]["logs_dir"])) { foreach(scandir($logs_dir) as $log_file) if(is_file($log_file = $logs_dir."/".$log_file)) if(is_writable($log_file)) unlink($log_file); /**/ @rmdir($logs_dir).@rmdir(c_ws_plugin__optimizemember_utils_dirs::strip_dir_app_data($logs_dir)); } /**/ delete_option("ws_plugin__optimizemember_cache"); delete_option("ws_plugin__optimizemember_notices"); delete_option("ws_plugin__optimizemember_options"); delete_option("ws_plugin__optimizemember_configured"); delete_option("ws_plugin__optimizemember_activated_levels"); delete_option("ws_plugin__optimizemember_activated_version"); delete_option("ws_plugin__optimizemember_activated_mms_version"); /**/ if(is_multisite() && is_main_site()) /* Site options? */ delete_site_option("ws_plugin__optimizemember_options"); /**/ $wpdb->query("DELETE FROM `".$wpdb->options."` WHERE `option_name` LIKE '%".esc_sql(like_escape("optimizemember_"))."%'"); $wpdb->query("DELETE FROM `".$wpdb->options."` WHERE `option_name` LIKE '".esc_sql(like_escape("_transient_s2m_"))."%'"); $wpdb->query("DELETE FROM `".$wpdb->options."` WHERE `option_name` LIKE '".esc_sql(like_escape("_transient_timeout_s2m_"))."%'"); $wpdb->query("DELETE FROM `".$wpdb->postmeta."` WHERE `meta_key` LIKE '%".esc_sql(like_escape("optimizemember_"))."%'"); $wpdb->query("DELETE FROM `".$wpdb->usermeta."` WHERE `meta_key` LIKE '%".esc_sql(like_escape("optimizemember_"))."%'"); /**/ do_action("ws_plugin__optimizemember_during_deactivation", get_defined_vars()); } /**/ do_action("ws_plugin__optimizemember_after_deactivation", get_defined_vars()); /**/ return; /* Return for uniformity. */ } } } ?>
sarahkpeck/thought-leaders
wp-content/plugins/optimizeMember/includes/classes/installation.inc.php
PHP
gpl-2.0
13,641
/* * This file is part of TILT. * * TILT 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. * * TILT 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 TILT. If not, see <http://www.gnu.org/licenses/>. * (c) copyright Desmond Schmidt 2014 */ /** * <p>This package is an adaptation of Esko Ukkonen's diff algorithm in * Information and Control 64, 100-118, 1985. Originally designed for the * alignment of two sets of characters or strings, it is here adapted to the * alignment of precise pixel-widths in an image and approximated pixel-widths * in a text. The original algorithm found the optimal alignment between two * texts using the insert, delete and exchange operations via a set of * diagonals. This adaptation uses the same approach, but adds * two new moves: h-extension and v-extension, which allows a number in one * set to be aligned with more than one in the other set, so 25, 35 could be * aligned with 60. This reflects the problem in recognising manuscript texts * that sometimes two words are joined in the page-image, or one word split * apart into two or more pieces. Using this method, and an existing * transcription, shapes of words identified in the image can be aligned with * the correct text, and the shapes themselves merged or split as needed.</p> * <p align="center"><img src="doc-files/alignment.png" width="500"></p> * <p>This algorithm is central to the correct function of the TILT * application.</p> */ package tilt.align;
AustESE-Infrastructure/TILT2
src/tilt/align/package-info.java
Java
gpl-2.0
1,957
/* * Copyright 2014-2018 University of Dundee. All rights reserved. * Use is subject to license terms supplied in LICENSE.txt */ package omero.cmd.admin; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.MailException; import ome.conditions.ApiUsageException; import ome.model.meta.Experimenter; import ome.model.meta.ExperimenterGroup; import ome.security.SecuritySystem; import ome.security.auth.PasswordChangeException; import ome.security.auth.PasswordProvider; import ome.security.auth.PasswordUtil; import ome.services.mail.MailUtil; import omero.cmd.HandleI.Cancel; import omero.cmd.ERR; import omero.cmd.Helper; import omero.cmd.IRequest; import omero.cmd.Response; import omero.cmd.ResetPasswordRequest; import omero.cmd.ResetPasswordResponse; /** * Callback interface allowing to reset password for the given user. * * @author Aleksandra Tarkowska, A (dot) Tarkowska at dundee.ac.uk * @since 5.1.0 */ public class ResetPasswordRequestI extends ResetPasswordRequest implements IRequest { private final static Logger log = LoggerFactory .getLogger(ResetPasswordRequestI.class); private static final long serialVersionUID = -1L; private final ResetPasswordResponse rsp = new ResetPasswordResponse(); private String sender = null; private final MailUtil mailUtil; private final PasswordUtil passwordUtil; private final SecuritySystem sec; private final PasswordProvider passwordProvider; private Helper helper; public ResetPasswordRequestI(MailUtil mailUtil, PasswordUtil passwordUtil, SecuritySystem sec, PasswordProvider passwordProvider) { this.mailUtil = mailUtil; this.passwordUtil = passwordUtil; this.sec = sec; this.passwordProvider = passwordProvider; } // // CMD API // public Map<String, String> getCallContext() { Map<String, String> all = new HashMap<String, String>(); all.put("omero.group", "-1"); return all; } public void init(Helper helper) { this.helper = helper; this.sender = mailUtil.getSender(); if (omename == null) throw helper.cancel(new ERR(), null, "no-omename"); if (email == null) throw helper.cancel(new ERR(), null, "no-email"); helper.allowGuests(); this.helper.setSteps(1); } public Object step(int step) throws Cancel { helper.assertStep(step); return resetPassword(); } @Override public void finish() throws Cancel { // no-op } public void buildResponse(int step, Object object) { helper.assertResponse(step); if (helper.isLast(step)) { helper.setResponseIfNull(rsp); } } public Response getResponse() { return helper.getResponse(); } private boolean resetPassword() { Experimenter e = null; try { e = helper.getServiceFactory().getAdminService() .lookupExperimenter(omename); } catch (ApiUsageException ex) { throw helper.cancel(new ERR(), null, "unknown-user", "ApiUsageException", ex.getMessage()); } if (e.getEmail() == null) throw helper.cancel(new ERR(), null, "unknown-email", "ApiUsageException", String.format("User has no email address.")); else if (!e.getEmail().equals(email)) throw helper.cancel(new ERR(), null, "not-match", "ApiUsageException", String.format("Email address does not match.")); else if (passwordUtil.getDnById(e.getId())) throw helper.cancel(new ERR(), null, "ldap-user", "ApiUsageException", String .format("User is authenticated by LDAP server. " + "You cannot reset this password.")); else { final long systemGroupId = sec.getSecurityRoles().getSystemGroupId(); for (final ExperimenterGroup group : e.linkedExperimenterGroupList()) { if (group.getId() == systemGroupId) { throw helper.cancel(new ERR(), null, "password-change-failed", "PasswordChangeException", "Cannot reset password of administrators. Have another administrator set the new password."); } } final String newPassword = passwordUtil.generateRandomPasswd(); // FIXME // workaround as sec.runAsAdmin doesn't execute with the root // context // helper.getServiceFactory().getAdminService().changeUserPassword(e.getOmeName(), // newPassword); try { passwordProvider.changePassword(e.getOmeName(), newPassword); log.info("Changed password for user: " + e.getOmeName()); } catch (PasswordChangeException pce) { log.error(pce.getMessage()); throw helper.cancel(new ERR(), null, "password-change-failed", "PasswordChangeException", String.format(pce.getMessage())); } String subject = "OMERO - Reset password"; String body = "Dear " + e.getFirstName() + " " + e.getLastName() + " (" + e.getOmeName() + ")" + " your new password is: " + newPassword; try { mailUtil.sendEmail(sender, e.getEmail(), subject, body, false, null, null); log.info("sent new password for {} to {}", e.getOmeName(), e.getEmail()); } catch (MailException me) { log.error(me.getMessage()); throw helper.cancel(new ERR(), null, "mail-send-failed", "MailException", String.format(me.getMessage())); } } return true; } }
knabar/openmicroscopy
components/blitz/src/omero/cmd/admin/ResetPasswordRequestI.java
Java
gpl-2.0
6,121
#sb-title-inner,#sb-info-inner,#sb-loading-inner,div.sb-message{font-family:"HelveticaNeue-Light","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:200;color:#fff;} #sb-container{position:fixed;margin:0;padding:0;top:0;left:0;z-index:999;text-align:left;visibility:hidden;display:none;} #sb-overlay{position:relative;height:100%;width:100%;} #sb-wrapper{position:absolute;visibility:hidden;width:100px;} #sb-wrapper-inner{position:relative;border:1px solid #303030;overflow:hidden;height:100px;} #sb-body{position:relative;height:100%;} #sb-body-inner{position:absolute;height:100%;width:100%;} #sb-player.html{height:100%;overflow:auto;} #sb-body img{border:none;} #sb-loading{position:relative;height:100%;} #sb-loading-inner{position:absolute;font-size:14px;line-height:24px;height:24px;top:50%;margin-top:-12px;width:100%;text-align:center;} #sb-loading-inner span{background:url("../../images/megnor/lightbox/loading.gif") no-repeat;padding-left:34px;display:inline-block;} #sb-body,#sb-loading{background-color:#060606;} #sb-title,#sb-info{position:relative;margin:0;padding:0;overflow:hidden;} #sb-title,#sb-title-inner{height:26px;line-height:26px;} #sb-title-inner{font-size:16px;} #sb-info,#sb-info-inner{height:20px;line-height:20px;} #sb-info-inner{font-size:12px;} #sb-nav{float:right;height:16px;padding:2px 0;width:45%;} #sb-nav a{display:block;float:right;height:16px;width:16px;margin-left:3px;cursor:pointer;background-repeat:no-repeat;} #sb-nav-close{background-image:url("../../images/megnor/lightbox/close.png");} #sb-nav-next{background-image:url("../../images/megnor/lightbox/next.png");} #sb-nav-previous{background-image:url("../../images/megnor/lightbox/previous.png");} #sb-nav-play{background-image:url("../../images/megnor/lightbox/play.png");} #sb-nav-pause{background-image:url("../../images/megnor/lightbox/pause.png");} #sb-counter{float:left;width:45%;} #sb-counter a{padding:0 4px 0 0;text-decoration:none;cursor:pointer;color:#fff;} #sb-counter a.sb-counter-current{text-decoration:underline;} div.sb-message{font-size:12px;padding:10px;text-align:center;} div.sb-message a:link,div.sb-message a:visited{color:#fff;text-decoration:underline;}
toninh/maydothucpham
wp-content/themes/starter/css/megnor/shadowbox.css
CSS
gpl-2.0
2,185
######################################################################## # # File Name: HTMLButtonElement # # Documentation: http://docs.4suite.com/4DOM/HTMLButtonElement.html # ### This file is automatically generated by GenerateHtml.py. ### DO NOT EDIT! """ WWW: http://4suite.com/4DOM e-mail: support@4suite.com Copyright (c) 2000 Fourthought Inc, USA. All Rights Reserved. See http://4suite.com/COPYRIGHT for license and copyright information """ import string from xml.dom import Node from xml.dom.html.HTMLElement import HTMLElement class HTMLButtonElement(HTMLElement): def __init__(self, ownerDocument, nodeName="BUTTON"): HTMLElement.__init__(self, ownerDocument, nodeName) ### Attribute Methods ### def _get_accessKey(self): return self.getAttribute("ACCESSKEY") def _set_accessKey(self, value): self.setAttribute("ACCESSKEY", value) def _get_disabled(self): return self.hasAttribute("DISABLED") def _set_disabled(self, value): if value: self.setAttribute("DISABLED", "DISABLED") else: self.removeAttribute("DISABLED") def _get_form(self): parent = self.parentNode while parent: if parent.nodeName == "FORM": return parent parent = parent.parentNode return None def _get_name(self): return self.getAttribute("NAME") def _set_name(self, value): self.setAttribute("NAME", value) def _get_tabIndex(self): value = self.getAttribute("TABINDEX") if value: return int(value) return 0 def _set_tabIndex(self, value): self.setAttribute("TABINDEX", str(value)) def _get_type(self): return self.getAttribute("TYPE") def _get_value(self): return self.getAttribute("VALUE") def _set_value(self, value): self.setAttribute("VALUE", value) ### Attribute Access Mappings ### _readComputedAttrs = HTMLElement._readComputedAttrs.copy() _readComputedAttrs.update({ "accessKey" : _get_accessKey, "disabled" : _get_disabled, "form" : _get_form, "name" : _get_name, "tabIndex" : _get_tabIndex, "type" : _get_type, "value" : _get_value }) _writeComputedAttrs = HTMLElement._writeComputedAttrs.copy() _writeComputedAttrs.update({ "accessKey" : _set_accessKey, "disabled" : _set_disabled, "name" : _set_name, "tabIndex" : _set_tabIndex, "value" : _set_value }) _readOnlyAttrs = filter(lambda k,m=_writeComputedAttrs: not m.has_key(k), HTMLElement._readOnlyAttrs + _readComputedAttrs.keys())
carvalhomb/tsmells
guess/src/Lib/xml/dom/html/HTMLButtonElement.py
Python
gpl-2.0
2,860
#pragma once #ifdef LIBTGB_EXPORT #define LIBTGB_API __declspec(dllexport) #else #define LIBTGB_API __declspec(dllimport) #endif class gb; struct ext_hook; namespace tgb { class GBRenderer; class LIBTGB_API Emulator { private: gb* _gb; GBRenderer* _renderer; ext_hook* _exthookDef; public: Emulator(GBRenderer& renderer); virtual ~Emulator(); void Clear(); bool LoadCartridge(const char* name); void Update(); unsigned char SeriSend(unsigned char data); void HookExport(unsigned char(*send)(unsigned char), bool(*led)(void)); void UnhookExport(); }; }
valentin-bas/VRoom
libvrgb/libtgb/Emulator.h
C
gpl-2.0
591
/******************************************************************************** * * Filename: base.css * Description: Oxwall Crayon Theme Base CSS File * Version: 1.0.0 * * -- FILE STRUCTURE: -- * * [ 1] CSS Defaults Reset __reset * [ 2] Base Elements __base * [ 3] Masterpage & Page Layout __layout * [ 4] Forms __forms * [ 5] Common Blocks __blocks * [ 6] Standard Listings __listings * [ 7] Tables __tables * [ 8] Messages & Notifications __messages * [ 9] Thumbnails & Icons __icons * [10] Menus __menus * [11] Pagination __pagination * [12] Typography __typography * [13] Misc __misc * [14] Clearfix __clearfix * [15] Plugin Styles __plugins * [16] Admin Styles __admin * * ********************************************************************************/ /*======================================================== [1] CSS Defaults Reset __reset ========================================================*/ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td{ margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; } body{ line-height: 1; /* TODO delete */ } ol, ul{ list-style: none; /* TODO delete */ } blockquote, q{ quotes: none; } blockquote:before, blockquote:after, q:before, q:after{ content: ''; content: none; } table{ border-collapse: collapse; border-spacing: 0; } /* remember to define focus styles! */ :focus{ outline: 0; } /* remember to highlight inserts somehow! */ ins{ text-decoration: none; } del{ text-decoration: line-through; } /*======================================================== [2] Base Elements __base ========================================================*/ body { background-repeat: repeat; background-color: #e7e7e7; /** OW_Control type:color, section:1. General Settings, key:pageColor, label:1. Page background color **/ } body, html { font-family: "Tahoma","Lucida Grande", "Verdana"; color: #888; /** OW_Control type:color, section:2. Colors, key:textColor, label:1. Text **/ font-size: 13px; line-height: 18px; /*min-height: 100%;*/ height: 100%; min-width: 1000px; } a { color: #0091a9; /** OW_Control type:color, key:linkColor, section:2. Colors, label:3. Links **/ text-decoration: none; } a:hover{ text-decoration: underline; } a:hover img{ text-decoration: none; } p{ text-indent: 0; margin-bottom: 4px; } h1, h2, h3, h4, h5{ color: #636d74; /** OW_Control type: color, key: titleColor, section: 2. Colors, label:2. Titles **/ margin: 0; padding: 0; font-weight: bold; } h1{ font-size: 20px; line-height: 19px; padding-left: 0px; color: #979ca0; text-transform: uppercase; margin-left: 0px; background-repeat: no-repeat; } html body div .ow_page h1 { background: none; } .maintenance_cont h1 { padding-left: 23px; background-position: left center; } h2 { font-size: 18px; } h3 { font-size: 13px; } h4 { font-size: 13px; margin-bottom: 10px; text-transform: none; } table { border: none; } img { border: 0; vertical-align: middle; } th, td { padding: 2px 5px; vertical-align: top; } th { border-bottom-width: 1px; border-bottom-style: solid; padding: 10px; vertical-align: middle; } th { background-color: #C4C4C4; } hr { background-color: #ccc; border: none; height: 1px; margin: 5px 5px 15px 5px; } /*======================================================== [3] Masterpage & Page Layout __layout ========================================================*/ /* ---- Page Layout styles ---- */ /*Opera Fix*/ body:before { content:""; height:100%; float:left; width:0; margin-top:-32767px; } .ow_bg_color{ background-color: #f1f1f1;/** OW_Control key:pageColor **/ } .ow_page_wrap { position: relative; background-image: url('images/promo.jpg');/** OW_Control type:image, key:pageBackground, section:1. General Settings, label:2. Page background image **/ background-repeat: no-repeat; background-position: center top; } body > .ow_page_wrap { min-height: 100%; } .ow_page_padding { padding-bottom: 99px; } .ow_canvas { margin: 0 auto; width: 1000px; word-wrap: break-word; } .ow_page { margin: 0 185px 0px auto; padding: 0 18px; } .ow_page_container { width: 1000px; margin: 0px auto 16px; } .ow_page_container .ow_page { padding: 28px 16px 16px; min-height: 400px; color: #696C74;/** OW_Control key:textColor **/ border-bottom-left-radius: 6px; border-bottom-right-radius: 6px; -moz-border-bottom-left-radius: 6px; -moz-border-bottom-right-radius: 6px; -webkit-border-bottom-left-radius: 6px; -webkit-border-bottom-right-radius: 6px; } .ow_content { float: left; width: 100%; } .ow_content a { color: #0091a9; /** OW_Control key: linkColor **/ } .ow_sidebar { margin-right: -201px; float: right; width: 168px; } .ow_footer { color: #aaa; padding:1px 0px; background:transparent; height: 96px; position: relative; margin-top: -99px; clear: both; } .ow_footer a { color: #0091A9; } .ow_footer .ow_copyright{ float: left; font-size:11px; line-height: 1; } h1.page_title{ background: url(images/ic_file.png) no-repeat left 50%; color: #FF7000; margin-bottom: 20px; padding-left: 22px; } .ow_column { width: 49%; overflow: hidden; } .ow_narrow { width: 39%; overflow: hidden; } .ow_wide { width: 59%; overflow: hidden; } .ow_superwide { width: 75%; overflow: hidden; } .ow_supernarrow { width: 23%; font-size: 11px; overflow: hidden; } .ow_left { float: left; } td.ow_left { float: none; } .ow_right { float: right; } .ow_center { text-align: center; } .ow_vertical_middle { vertical-align: middle; } .ow_txtleft, table td.ow_txtleft { text-align: left; } .ow_txtcenter { text-align: center; } .ow_txtright { text-align: right; } html body .ow_hidden{ display: none; } .ow_visible { display: block; } .ow_nocontent { padding: 20px 0px; text-align: center; } table.ow_nomargin, div.ow_nomargin { margin-bottom:0px; } .ow_nowrap { white-space: nowrap; } ul.ow_regular { margin-bottom: 12px; } ul.ow_regular li { line-height: 17px; margin: 0 0 3px 0px; padding: 0px 0px 0px 16px; background-repeat: no-repeat; background-image: url(images/miniic_li.png); background-position: left 5px; } .ow_preloader{ background: url(images/ajax_preloader_button.gif) no-repeat center center; } .ow_preloader_content{ background: url(images/ajax_preloader_content.gif) no-repeat center center; } .ow_page_layout_scheme { width: 580px; } .ow_page_layout_scheme a { background-position: center center; background-repeat: no-repeat; border: 1px solid #FFFFFF; display: block; float: left; height: 103px; margin: 2px; padding: 5px; width: 100px; } .ow_page_layout_scheme a.active, .ow_page_layout_scheme a:hover { background-color: #CCFFCC; border: 1px solid #CCCCCC; } .ow_item_set2{ width: 49%; } .ow_item_set3{ width: 33%; } .ow_item_set4{ width: 25%; } .ow_item_set5{ width: 20%; } /* ---- End of Page Layout styles ---- */ /* ---- Header styles ---- */ .ow_header { width: 100%; } .ow_top { position: relative; height: auto; min-height: 105px; padding-top: 50px; } .ow_logo_wrap { width: 1000px; margin: 0px auto; padding: 12px 0px 0px 10px; } .ow_logo_wrap a { font-family: 'UbuntuBold', "Trebuchet MS", "Helvetica CY", sans-serif; font-size: 13px; text-transform: uppercase; color: #626060; } .ow_logo_wrap a:hover { text-decoration: none; } .ow_logo { float: left; margin: 0px 0 0px 0px; padding-bottom: 27px; padding-left: 9px; } .ow_logo h2 { font-family: 'UbuntuBold', "Trebuchet MS", "Helvetica CY", sans-serif; font-size: 32px; line-height: 32px; text-shadow: 0 1px 0 #fefefe; font-weight: normal; } .ow_logo .ow_tagline { font-size: 13px; color: #999; padding: 0px 0 0 2px; text-shadow: 0 1px 0 #FFFFFF; } .ow_logo a { color: #000; text-decoration: none; font-family: 'UbuntuBold', "Trebuchet MS", "Helvetica CY", sans-serif; } .ow_header .ow_search{ float: right; padding: 5px; } .ow_header_pic { background-image: url("images/header_image.png");/** OW_Control type:image, key:headerImage, section:1. General Settings, label:3. Header background image **/ background-position: 20px 87px; background-repeat: no-repeat; height: 375px; margin: 0 auto; width: 1000px; } /* ---- End of the Header styles ---- */ /* ---- Sidebar styles ---- */ .ow_sidebar .ow_box_cap_empty { border-color: #d8d8d8; } .ow_sidebar .ow_box_cap { border-color: #d8d8d8; border-bottom: 0px; } .ow_sidebar .ow_box { border-color: #d8d8d8; } html body .ow_sidebar h3 { font-size: 13px; } /* ---- End of Sidebar styles ---- */ /* ---- Console styles ---- */ .ow_console .wackwall_link{ background: url(images/console-w.png) no-repeat 50% 50%; display: block; height: 30px; width: 35px; } .ow_console .wackwall_link:hover{ text-decoration:none; } .ow_console .common_shortcuts a{ background-position:50% 50%; background-repeat: no-repeat; display:inline-block; height:30px; width:25px; } .ow_console .common_shortcuts a:hover{ text-decoration:none; } .ow_console .notification_shortcut{ padding:0 7px; } .ow_console .notification_shortcut a{ background-position:0 50%; background-repeat:no-repeat; display:block; padding: 5px 0 5px 20px; text-decoration:none; } .ow_site_panel { height: 41px; background: url(images/site_panel_bg.png) repeat-x; } .ow_console { font-size: 11px; height: 40px; position: fixed; top: 0px; right: 0px; z-index: 99; color: #666; background: url(images/site_panel_bg.png) repeat-x; } .ow_console_body { padding: 8px 4px 8px 8px; text-align: right; border-bottom-left-radius: 2px; -moz-border-radius-bottomleft: 2px; -webkit-bottom-left-border-radius: 2px; } .ow_console_block { display: inline-block; text-align: left; vertical-align: top; } .ow_console_item { background:url(images/box_menu.gif) repeat-x 0px 0px; display: inline-block; position:relative; line-height: 21px; height:22px; margin:0 4px 0 0px; padding:0 8px; color: #626060; text-shadow: #fafafa 0 1px 0; border-style: solid; border-color: #ccc; border-width: 1px 1px 1px 1px; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; vertical-align: top; text-align: left; } .ow_console_item:hover { border-color: #999; border-style: solid; border-color: #ccc; border-width: 1px 1px 1px 1px; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; cursor: pointer; background:url(images/console_bg_hover.gif) repeat-x 0px 0px; } .ow_console_dropdown_hover:hover { background:url(images/console_active_item_bg.gif) repeat-x 0px 0px; border-color: #ccc; cursor: pointer; } .ow_console_dropdown_pressed, .ow_console_dropdown_pressed:hover { background: url(images/console_active_item_bg.gif) repeat-x 0px 0px; border-color: #ccc; } .ow_console_item a { color: #626060; text-shadow: #fafafa 0 1px 0; } .ow_console_item a:hover { text-decoration: none; } .ow_console_more { background: url("images/console_arr.png") no-repeat scroll right 9px transparent; display: inline-block; height: 22px; min-width: 8px; padding: 0 0px 0 3px; vertical-align: top; } .ow_console_item:hover .ow_console_more { background: url("images/console_arr.png") no-repeat scroll right 9px transparent; } /* ---- Console select language styles ---- */ .ow_console_lang_item { text-transform: uppercase; } li.ow_console_lang_item { padding: 0px 8px; border: 1px solid transparent; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; margin-bottom: 1px; } li.ow_console_lang_item:hover { background-color: #57c0e7; color: #e5ffff; text-shadow: 0 1px 0 #007a9e; } .ow_console_lang_item span { display: inline-block; padding-left: 23px; } /* ---- End Console select language styles ---- */ .ow_console .ow_tooltip_top_right { top: 10px; padding-top: 2px; } .ow_console .ow_tooltip_top_right .ow_tooltip_tail span { background-position: 1px -6px; } .ow_console span.ow_count_wrap { padding: 4px 0px 0px; margin: 0px -3px 0px 2px; } .ow_console span.ow_count_bg { } .ow_console span.ow_count { position: relative; top: 0px; line-height: 13px; } .ow_console .ow_tooltip_body { -webkit-box-shadow: 0 2px 8px rgba(0,0,0,0.4); -moz-box-shadow: 0 2px 8px rgba(0,0,0,0.4); box-shadow: 0 2px 8px rgba(0,0,0,0.4); } .ow_console_list_wrapper { width: 330px; overflow-y: auto; word-wrap: break-word; min-height: 60px; } .ow_console_list { cursor: default; } .ow_console_list li { padding: 3px; margin: 0px 0px 4px; height: auto; overflow: hidden; border: 1px solid #E7EBEE; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; background-color:#f6fafd; } .ow_console_list li:hover { border-color: #cbcfd2; background-color: #f6fafd; } .ow_console_list li.ow_console_new_message { background: #fff; border-color: #ccc; } .ow_console_list li:last-child { margin-bottom: 0px; } .ow_console .ow_avatar { float: left; margin-right: -40px; height: 40px; width: 40px; padding: 0px; background-image: none; } .ow_console .ow_avatar img { height: 40px; width: 40px; } .ow_console_ntf_txt, .ow_console_invt_txt { display: block; line-height: 16px; color: #666; } .ow_console_invt_txt a { color: #2A80AE; } .ow_console_view_all_btn_wrap { padding-top: 4px; } .ow_console_view_all_btn { text-decoration: none; display: block; line-height: 11px; padding: 8px 0px; text-align: center; border: 1px solid #ccc; background: url(images/console_item_bg.png) repeat-x; } ul.ow_console_dropdown { min-width: 110px; text-align: left; overflow-x: auto; cursor: default; } ul.ow_console_dropdown .ow_console_dropdown_cont { white-space: nowrap; margin-bottom: 1px; } ul.ow_console_dropdown .ow_console_dropdown_cont a { padding: 3px 8px; border: 1px solid transparent; display: block; } ul.ow_console_dropdown .ow_console_dropdown_cont a:hover { background:#57c0e7; border-radius: 3px 3px 3px 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; color: #e5ffff; text-shadow: 0 1px 0 #007a9e; } ul.ow_console_dropdown li:last-child .ow_console_dropdown_cont { margin-bottom: 0px; } .ow_console .ow_tooltip .ow_tooltip_body { max-width: 340px; } .ow_console_ntf_cont, .ow_console_invt_cont { display: block; margin: 0px 57px 0px 45px; line-height: 16px; color: #666; } .ow_console_ntf_txt, .ow_console_invt_txt { min-height: 19px; padding: 0px 0px 3px 0px; } .ow_console_invt_txt { width: 211px; word-wrap: break-word; } .ow_console_invt_cont a { color: #2A80AE; } .ow_console_invt_cont a:hover { color: #666; text-decoration: underline; } .ow_console_invt_cont .ow_lbutton:hover { text-decoration: none; } .ow_console_invt_img { float: right; margin-left: -54px; width: 54px; height: 54px; text-align: right; } .ow_console_invt_img img { max-height: 100%; max-width: 100%; } .ow_console_invt_no_img .ow_console_invt_txt { width: 100%; } .ow_console_invt_no_img { margin-right: 0px; } .ow_console_divider { line-height: 1px; height: 1px; background: #D1D1D1; border-bottom: 1px solid #fff; margin: 3px 0px 2px; } .ow_cursor_pointer { cursor: pointer; } .ow_cursor_default { cursor: default; } /* Messages notifications */ .ow_console_mailbox_txt { font-size: 12px; } .ow_console_mailbox_title { font-size: 12px; font-weight: bold; padding-right: 52px; } .ow_console_mailbox_title .ow_mailbox_convers_info_date { font-size: 10px; font-weight: normal; margin-right: -49px; } .ow_chat_request_item .console_list_ipc_item { padding-left: 16px; background: url(images/miniic_buble.png) 2px 12px no-repeat; } .ow_mailbox_request_item .console_list_ipc_item { padding-left: 16px; background: url(images/miniic_envelope.png) 2px 12px no-repeat; } .ow_chat_request_item .ow_console_mailbox_txt { font-size: 11px; font-weight: normal; line-height: 13px; } .ow_console_messages_btns, .ow_console_messages_btn { margin-top: 4px; } .ow_console_messages_viewall, .ow_console_messages_send { width: 50%; float: left; box-sizing: border-box; -moz-box-sizing: border-box; -wenkit-box-sizing: border-box; } .ow_console_messages_btn .ow_console_messages_send { display: none; } .ow_console_messages_btn .ow_console_messages_viewall { width: 100%; padding-right: 0; } .ow_console_messages_viewall { padding-right: 2px; } .ow_console_messages_send { padding-left: 2px; } .ow_console_messages_viewall a, .ow_console_messages_send a { display: inline-block; width: 100%; line-height: 25px; text-align: center; border: 1px solid #cccccc; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; box-sizing: border-box; -moz-box-sizing: border-box; -wenkit-box-sizing: border-box; font-size: 11px; background: url(images/console_item_bg.png) repeat-x left top #fafafa; } .ow_console li.ow_chat_request_item .ow_avatar, .ow_console li.ow_mailbox_request_item .ow_avatar { width: 32px; height: 32px; margin-right: -32px; } .ow_console li.ow_chat_request_item .ow_avatar img, .ow_console li.ow_mailbox_request_item .ow_avatar img { height: 32px; width: 32px; } .ow_console li.ow_chat_request_item .ow_console_invt_cont, .ow_console li.ow_mailbox_request_item .ow_console_invt_cont { margin-left: 38px; } #conversationItemListSub { width: 280px !important; } /*End of Messages notifications*/ /* ---- End of Console styles ---- */ /*======================================================== [4] Forms __forms ========================================================*/ /* ---- Form Elements styles ---- */ input[type=text], input[type=password], textarea, select, div.jhtmlarea, body .ow_photo_upload_description, .ow_photo_preview_edit .CodeMirror{ background-image: url(images/inputbg.gif); background-repeat: repeat-x; background-position: 0px 0px; background-color: #E4E7E8; border: 1px solid #CBCFD0; color: #585858; font-family: "Lucida Grande", "Verdana"; font-size: 13px; padding: 4px; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } body form div.jhtmlarea { padding: 0px; background: #fff; width: 100% !important; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body .toolbar { padding: 2px 2px 0px; height: 24px; background: #ccc; border-bottom: 1px solid #C4C4C4; border-radius: 3px 3px 0px 0px; -moz-border-radius: 3px 3px 0px 0px; -webkit-border-radius: 3px 3px 0px 0px; } body .jhtmlarea .toolbar ul { height: 24px; } body .toolbar ul li a { background-image: url(images/wysiwyg.png); } .jhtmlarea .input_ws_cont { padding: 8px; } body.htmlarea_styles { margin: 0px; } html body .ow_sidebar *, html body .ow_console *{ font-size: 11px; } select{ background-image: none; } textarea{ height: 100px; width: 100%; resize: vertical; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } input[type=text], input[type=password]{ width: 100%; height: 30px; line-height: 22px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } /*.ow_supernarrow input[type=text], .ow_supernarrow input[type=password]{ width: 95%; }*/ input[type=submit], input[type=button]{ background-color: transparent; background-position: right 50%; background-repeat: no-repeat; background-image: url(images/ic_right_arrow.png); padding: 1px 31px 2px 0px; color: #fff; font-weight: normal; cursor: pointer; height: 30px; font-family: 'UbuntuBold', "Trebuchet MS", "Helvetica CY", sans-serif; text-transform: uppercase; font-size: 13px; border: none; text-shadow: #e45da1 0 1px 0; } /* temp hack for decorating buttons in FF */ body:not(:-moz-handler-blocked) input[type=submit], body:not(:-moz-handler-blocked) input[type=button]{ padding-top: 0px; padding-right: 31px; } /* End of temp hack for decorating buttons in FF */ html body div span.ow_button input[type=submit], html body div span.ow_button input[type=button]{ } html body.ow input[type=submit], html body.ow input[type=button]{ margin: 0px; } span.ow_button { display: inline-block; background-color: #fba7e3; background-repeat:repeat; background-image: url(images/btn_main_bg.gif); background-position: right top; padding: 0px 8px; border: 1px solid #FF95D7; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; } span.ow_button:hover { border-color: #FF95D7; background-color: #fba7e3; background-image:none; background-repeat:repeat; background-position: right top; } span.ow_button span.ow_button { border-radius: none; -moz-border-radius: none; -webkit-border-radius: none; border: none; background-image: none; background-position: right center; background-repeat: no-repeat; background-color: transparent; } span.ow_button span { display: inline-block; padding: 0px 0px 0px 0px; background-position: right center; background-repeat: no-repeat; background-color: transparent; } .ow_btn_delimiter span.ow_button:first-child { margin-right: 16px; } .ow_btn_delimiter span.ow_button span.ow_button { margin: 0px; } html body.ow span.ow_button { } body.ow input.ow_inprogress, body.ow .ow_inprogress { background-image: url(images/ajax_preloader_button.gif); } *+html input[type=submit], *+html input[type=button]{ overflow: visible; } input[type=submit]:hover, input[type=button]:hover{ /* empty */ } input[type=submit].submit{ background-color: #00aa00; color: #fff; } input[type=submit].alert{ background-color: #ff6666; color: #fff; } input[type=submit].submit:hover{ /* empty */ } input[type=submit].alert:hover{ /* empty */ } ul.ow_radio_group li{ float:left; } ul.ow_checkbox_group li{ float:left; } textarea.invitation, input[type=text].invitation, input[type=password].invitation{ color:#999; } .form_auto_click textarea.invitation{ height:50px; } form .error{ color:red; } form input[type=text].hasDatepicker{ width: 87%; } form br.ow_no_height{ line-height: 0; } .color_input input[type=text]{ width:70%; } .ow_multiselect select{ width: 120px; padding: 2px; } .ow_multiselect input[type=button]{ padding-left: 20px; } .form_auto_click .ow_submit_auto_click{ display:none; } /* ---- Positive and Negative buttons ---- */ html body div .ow_positive input[type=submit], html body div .ow_positive input[type=button]{ color: #fff; } .ow_negative input[type=submit], .ow_negative input[type=button]{ background: none; padding-right: 2px; } body:not(:-moz-handler-blocked) .ow_negative input[type=submit], body:not(:-moz-handler-blocked) .ow_negative input[type=button] { padding-right: 2px; } /* ---- End of Positive and Negative buttons ---- */ html body div .ow_green { color: #089634; } html body div .ow_red{ color: #ee3d32; } html body div .ow_mild_red, .ow_navbox.ow_mild_red a.move{ color: #f42217; } html body div .ow_mild_green, .ow_navbox.ow_mild_green a.move{ color: #7cbb11; } html body .ow_button.ow_red, html body .ow_button.ow_mild_red, html body .ow_button.ow_green, html body .ow_button.ow_mild_green, .ow_button .ow_mild_red, .ow_button .ow_red, .ow_button .ow_green, .ow_button .ow_mild_green { background-color: transparent; border-color: transparent; color: #fff; } input[type=submit].ow_green, input[type=button].ow_green, input[type=submit].ow_mild_green, input[type=button].ow_mild_green, input[type=submit].ow_red, input[type=button].ow_red, input[type=submit].ow_mild_red, input[type=button].ow_mild_red { background-color: transparent; } /* wysiwyg styles */ body.htmlarea_styles{ font-family: "Lucida Grande", "Verdana", "Tahoma"; /** key:commonFontFamily **/ color: #888; font-size: 13px; /** key:commonFontSize **/ line-height: 18px; } body.htmlarea_styles a{ color: #0091a9; } body.htmlarea_styles p{ margin:0; } /* wysiwyg styles end */ /* tag styles */ div.tagsinput { background-image: url(images/inputbg.gif); background-color: #E4E7E8; } /* tag styles end */ /* ---- End of Form Elements styles ---- */ /* ---- End of Form Table styles ---- */ /* -------Attachments styles----------*/ .ow_attachment_btn { float: right; margin: 0 0 0 4px; padding: 0; } .ow_attachments input[type="file"] { cursor: pointer; float: right; opacity: 0; } .ow_attachment_icons { float: right; } .ow_attachments a { background: url(images/wysiwyg.png) no-repeat scroll -175px 1px rgba(0, 0, 0, 0); cursor: pointer; float: left; height: 22px; overflow: hidden; text-decoration: none; width: 22px; } .ow_attachments a.video{ background:url(images/wysiwyg.png) -197px 1px no-repeat; } .ow_attachments a.attach { background: url(images/wysiwyg.png) no-repeat scroll -241px 1px rgba(0, 0, 0, 0); border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; } .ow_attachments a.attach.uploading { background: url(images/ajax_preloader_button.gif) no-repeat center center; } .ow_attachment_delete { width: 12px; height: 12px; display: block; position: absolute; top: 4px; right: 4px; } .ow_ajax_oembed_attachment { width: 100%; } .ow_attachment_title { margin-bottom: 4px; line-height: 13.5px; font-size: 11px; color: #000; display: inline-block; } .ow_attachment_description { padding-right: 16px; line-height: 13.5px; height: 27px; overflow: hidden; font-size: 11px; display: inline-block; } .ow_video_attachment_preview .ow_attachment_description { color: #000; } .ow_attachment_title a { font-weight: bold; font-size: 11px; } .ow_video_attachment_preview .ow_attachment_title a { color: #000; } .ow_video_attachment_preview.loading_content .ow_video_attachment_pic, .ow_video_attachment_preview.loading_content .ow_attachment_title, .ow_video_attachment_preview.loading_content .ow_attachment_description { display: none; } .ow_video_attachment_preview.loading_content { background: url(images/ajax_preloader_content.gif) center center no-repeat; } .ow_attachment_preload { background-image: url(images/ajax_preloader_content.gif); background-repeat: no-repeat; background-position: center center; background-size: normal; } .ow_attachment_btn span.ow_button { background-color: #f5f5f5; background-image: none; background-repeat: repeat-x; background-position: center left; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; border-color: #CFCFCF; display: inline-block; padding: 1px; text-align: center; } .ow_attachment_btn span.ow_button span { display: inline-block; background-image: url('images/btn_bg.gif'); background-repeat: repeat-x; background-position: 0px 0px; background-color: #faa274; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; border-style: 1px; border-width: 1px; border-color: #f7b63c #f68d2d #f57d26 #f6932f; margin: 1px; } .ow_attachment_btn span.ow_button input[type=submit], .ow_attachment_btn span.ow_button input[type="button"] { padding: 1px 8px 4px; height: 22px; color: #FFD1FF; background: none; text-shadow: 1px 1px #B42E77; } /*Video, links embed*/ body .ow_oembed_attachment_preview { height: 60px; position: relative; padding: 6px 20px 0 88px; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; border-width: 1px; } .ow_mailbox_log .ow_oembed_attachment_preview { border: none; padding: 0 0 0 88px; background-color: transparent; margin-top: 12px; } .ow_mailbox_log .ow_oembed_attachment_preview .ow_attachment_delete { display: none; } .ow_oembed_attachment_pic .attachment_other_images_btn { position: absolute; left: 4px; bottom: 4px; display: none; } .ow_oembed_attachment_pic:hover .attachment_other_images_btn { display: inline-block; } body .ow_oembed_attachment_pic { width: 80px; height: 60px; position: absolute; top: -1px; left: -1px; border-width: 0 1px 0 0; background-color: #C7BBA9; } .ow_oembed_atachment_pic_nopic { background-image: url(images/no-picture.png); background-position: center center; background-repeat: no-repeat; background-size: 100%; } .ow_oembed_attachment_pic img { width: 80px; height: 60px; } .ow_oembed_attachment_url { position: relative; } .ow_oembed_attachment_url a { position: absolute; bottom: 4px; left: 4px; } .ow_attachment_title { margin-bottom: 4px; line-height: 13.5px; font-size: 11px; display: inline-block; } .ow_attachment_description { line-height: 13.5px; height: 27px; overflow: hidden; font-size: 11px; display: block; } .ow_attachment_title a { display: block; height: 13px; overflow: hidden; text-overflow: ellipsis; font-weight: bold; font-size: 11px; } .ow_oembed_attachment_preview.loading_content .ow_oembed_attachment_pic, .ow_oembed_attachment_preview.loading_content .ow_attachment_title, .ow_oembed_attachment_preview.loading_content .ow_attachment_description { display: none; } .ow_oembed_attachment_preview.loading_content { background: url(images/ajax_preloader_content.gif) center center no-repeat; } .attachment_image_item { border-width: 1px; cursor: pointer; float: left; height: 85px; margin: 2px; padding: 3px; text-align: center; width: 85px; } .attachment_image_item img { max-width: 100%; max-height: 100%; } /*Photo attachment*/ .ow_photo_attachment_preview { height: auto; padding: 8px 0; border-width: 0 0 1px 0; border-style: solid; margin-left: 0; } .ow_comments_mipc .ow_photo_attachment_preview, .ow_comments_mipc .ow_oembed_attachment_preview { margin-left: 48px; } .ow_comments_ipc .ow_photo_attachment_preview, .ow_comments_ipc .ow_oembed_attachment_preview { margin-left: 57px; } .ow_feed_comments_input_sticky .ow_photo_attachment_preview, .ow_feed_comments_input_sticky .ow_oembed_attachment_preview, .ow_feed_comments_input_sticky .comments_hidden_btn{ margin: 0 12px 8px 22px; } .ow_photo_attachment_pic { display: inline-block; background-color: #ececec; width: 120px; height: 120px; border: 1px solid #e6e6e6; border-top-color: #dbdbdb; position: relative; background-size: cover; background-repeat: no-repeat; } .ow_photo_attachment_pic.loading { background-size: auto; background-image: url(images/ajax_preloader_content.gif); background-position: center center; } .ow_photo_attachment_stage { width: 150px; height: 150px; background-position: center; background-size: cover; background-repeat: no-repeat; } /*File attachments*/ .ow_file_attachment_preview { width: 100%; height: auto; margin-top: -2px; margin-bottom: 6px; } .ow_file_attachment_block1, .ow_file_attachment_block2 { float: left; width: 50%; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; margin: 2px 0; } .ow_file_attachment_block1 { padding-right: 4px; } .ow_file_attachment_block2 { padding-left: 4px; } .ow_dialog_items_wrap .ow_file_attachment_block1, .ow_dialog_items_wrap .ow_file_attachment_block2 { width: auto; float: none; padding-right: 0; padding-left: 0; padding-top: 4px; } .ow_dialog_items_wrap .ow_file_attachment_info, .ow_mailbox_log .ow_file_attachment_info { padding-right: 4px; } .ow_dialog_item_mailchat .ow_mailbox_message_content_attach { padding-top: 0px; } .ow_dialog_items_wrap .ow_file_attachment_name, .ow_mailbox_log .ow_file_attachment_name { font-weight: normal; padding-right: 4px; } .ow_file_attachment_info { border: 1px solid #DCDCDC; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; padding-right: 50px; position: relative; height: 22px; overflow: hidden; } .ow_file_attachment_info a { line-height: 22px; padding-left: 8px; } .ow_dialog_in_item.fileattach { padding-top: 1px; padding-bottom: 1px; } .ow_dialog_in_item.fileattach .ow_file_attachment_info { border: none; } .ow_file_attachment_name { width: 100%; line-height: 22px; height: 22px; overflow: hidden; padding-left: 8px; font-size: 11px; font-weight: bold; } .ow_file_attachment_size { font-weight: normal; display: none; } .ow_file_attachment_close { position: absolute; top: 0; right: 0; width: 22px; height: 22px; border-left: 1px solid #DCDCDC; background-image: url(images/tag_close_btn.png); background-repeat: no-repeat; background-position: center center; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; } .ow_file_attachment_preload { position: absolute; top: 0; right: 25px; width: 16px; height: 22px; background: url(images/ajax_preloader_content.gif) center center no-repeat; display: none; } .ow_dialog_in_item.errormessage p, .ow_mailbox_log_message.errormessage .ow_mailbox_message_content, .ow_dialog_item_mailchat.errormessage .ow_dialog_item_mailchat_text { color: #b1b1b1; } .ow_errormessage_not { display: block; padding-bottom: 4px; padding-left: 4px; } .ow_dialog_in_item.errormessage .ow_errormessage_not { padding-left: 0; } /* -------End of attachments styles----------*/ /* ----------- Comments styles---------- */ body .ow_attachments .buttons { padding: 1px; background: #f5f5f5; border: 1px solid #ebebeb; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; } body .ow_attachments a { border: 1px solid #CFCFCF; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; } body .ow_attachments a.video { border-radius: 0 2px 2px 0; margin: 0 0 0 -1px; } .base_cmnts_temp_cont .ow_ipc_info { border: none; padding-bottom: 1px; } .ow_comments_item, .ow_feed_comments_viewall, .ow_feed_comments_input_sticky, .ow_photo_attachment_preview, .ow_oembed_attachment_preview, .ow_oembed_attachment_pic, .ow_comments_form_wrap, .ow_newsfeed_features .ow_tooltip .ow_tooltip_body { background-color: #ECF0F1; border-color: #D3D6D7; border-style: solid; } .ow_comments_item { position: relative; padding: 0px 0px 4px; padding: 6px 6px 4px 6px; border-width: 1px 1px 0 1px; } .ow_comments_form_top .ow_comments_item { border-width: 0 1px 1px 1px; } .ow_comments_form_top .ow_paging { margin-bottom: 0; margin-top: 8px; } .ow_newsfeed_features .ow_comments_item { border-width: 1px 0 0 0; } .ow_photoview_info_wrap.sticked .ow_comments_item:last-child { border-width: 1px; margin-bottom: 12px; } .ow_comments_form_top .ow_comments_list .ow_comments_item:last-child { border-radius: 0px 0px 2px 2px; -moz-border-radius: 0px 0px 2px 2px; -webkit-border-radius: 0px 0px 2px 2px; } .ow_comments_list .ow_comments_item:first-child { border-radius: 2px 2px 0 0; -moz-border-radius: 2px 2px 0 0; -webkit-border-radius: 2px 2px 0 0; } .ow_comments_form_top .ow_comments_list .ow_comments_item:first-child { border-radius: 0; } .ow_comments_no_form .ow_comments_list .ow_comments_item:last-child { border-bottom-left-radius: 2px; -webkit-border-bottom-left-radius: 2px; -moz-border-radius-bottomleft: 2px; border-bottom-right-radius: 2px; -webkti-border-bottom-right-radius: 2px; -moz-border-radius-bottomright: 2px; border-width: 1px; } .ow_comments_form_top.ow_comments_no_form .ow_comments_list .ow_comments_item:first-child { border-top-left-radius: 2px; -webkit-border-top-left-radius: 2px; -moz-border-radius-topleft: 2px; border-top-right-radius: 2px; -webkit-border-top-right-radius: 2px; -moz-border-radius-topright: 2px; border-width: 1px; } .ow_newsfeed_features .ow_comments_list div .ow_context_action_block .ow_context_action { border-top-width: 1px; } .ow_comments_form_wrap { padding: 6px 6px 4px 6px; border-radius: 0 0 2px 2px; -moz-border-radius: 0 0 2px 2px; -webkit-border-radius: 0 0 2px 2px; border-width: 1px; min-height: 42px; } .ow_comments_ipc .ow_comments_form_wrap { min-height: 50px; } .ow_newsfeed_features .ow_comments_form_wrap, .ow_newsfeed_features .ow_feed_comments_viewall { border-width: 1px 0 0 0; } .ow_comments_form_top .ow_comments_form_wrap { border-radius: 2px 2px 0 0; -moz-border-radius: 2px 2px 0 0; -webkit-border-radius: 2px 2px 0 0; } .ow_feed_comments_viewall { text-align: right; padding: 8px 8px 8px 0; border-width: 1px 1px 0 1px; border-radius: 2px 2px 0 0; -moz-border-radius: 2px 2px 0 0; -webkit-border-radius: 2px 2px 0 0; min-height: 14px; } .ow_feed_comments_input_sticky { position: absolute; bottom: 0; left: 0; width: 100%; } .ow_feed_comments_input_sticky .ow_comments_input_wrap { padding: 6px 12px 4px 22px; } .ow_feed_comments_input_sticky .ow_comments_form_wrap { border-top-width: 1px; } .ow_comments_item_picture{ float: left; margin-right: -50px; width: 50px; } .ow_comments_item_info { margin-left: 57px; } .ow_comments_item_info textarea.ow_smallmargin { margin-bottom: 6px; width: 100%; margin-top: 4px; } .ow_comments_item_info .comments_fake_autoclick { width: 100%; height: 28px; margin-top: 4px; } .ow_comments_item_header { margin-bottom: 2px; } .ow_comments_item_header a { font-size: 11px; font-weight: bold; } .ow_comments_item_toolbar { float: left; font-size:10px; width: 100%; } .ow_comments_item_info .clearfix .ow_comments_item_toolbar { white-space: normal; } .ow_comments_date { float: right; font-size: 10px; } .ow_comments_list .ow_tooltip .ow_tooltip_body { padding: 4px 0px; } .ow_comments_list .ow_context_action_list a { padding: 4px 12px; } .ow_comments_item_info .mipc_url{ font-weight: bold; } .comment_add_arr { float: left; display: block; position: relative; z-index: 1; left: 1px; width: 5px; height: 9px; margin: 14px 0px 0px -5px; background: url(images/comment_arr.png) no-repeat 0px 0px; } .ow_comments_list .comments_view_all { padding-bottom: 5px; } body .ow_comments_list .ow_attachment { padding-top: 4px; } body .ow_comments_content.ow_smallmargin { margin-bottom: 0px; } .ow_comments_content img { max-width: 100%; } .ow_comments_btn_block { padding: 0 0px 0px 0; } .ow_comments_item .cnx_action { position: absolute; right: 4px; top: 4px; } .ow_comments_msg { margin-top: 4px; color: #666; } body .item_loaded { margin: 0px 3px 8px 57px; } body textarea.ow_newsfeed_status_input { height: 58px; } body textarea.ow_newsfeed_status_input.invitation { width: 100%; height: 28px; } .ow_comments_mipc.ow_comments_paging .ow_comments_list { margin-bottom: 8px; } .ow_comments_mipc .ow_comments_item_picture, .ow_feed_comments_input_sticky .ow_comments_item_picture { width: 42px; margin-right: -42px; float: left; } .ow_comments_mipc .ow_comments_item_picture .ow_avatar, .ow_feed_comments_input_sticky .ow_comments_item_picture .ow_avatar { height: 32px; width: 32px; background: url(images/avatar_mini_bg.png) no-repeat scroll 0 0 rgba(0, 0, 0, 0); } .ow_comments_mipc .ow_comments_item_picture .ow_avatar img, .ow_feed_comments_input_sticky .ow_comments_item_picture .ow_avatar img { width: 32px; height: 32px; } .ow_comments_mipc .ow_comments_item_info, .ow_feed_comments_input_sticky .ow_comments_item_info { margin-left: 48px; } .ow_comments_mipc .ow_comments_list { margin-bottom: 1px; } .ow_comments_item_info .ow_comments_content { padding: 2px 0; width: 100%; word-wrap: break-word; } .ow_comments_input_wrap textarea.comments_fake_autoclick { resize: none; height: 30px; padding-right: 28px; } .ow_comments_input_wrap .ow_comments_input { padding-top: 4px; position: relative; } .ow_comments_input_wrap .ow_comments_input .comments_fake_autoclick { margin-top: 0; } .ow_comments_input .ow_attachment_icons { position: absolute; top: 8px; right: 4px; } .ow_comments_input .ow_attachments a { background: url(images/wysiwyg.png) no-repeat scroll -176px 0px rgba(0, 0, 0, 0); cursor: pointer; float: left; height: 20px; overflow: hidden; text-decoration: none; width: 20px; } .ow_attachments input[type="file"] { cursor: pointer; float: right; opacity: 0; } /*End of comments styles*/ /*======================================================== [5] Common Blocks __blocks ========================================================*/ .ow_box_cap_empty { background: #e7e7e7 url('images/box_cap.gif') repeat-x left top; border-radius: 6px 6px 0px 0px; margin-bottom: 8px; } .ow_box_cap_empty .ow_box_cap_right { } .ow_box_cap_empty .ow_box_cap_body { min-height: 33px; } .ow_box_cap h3, .ow_box_cap_empty h3{ background-image: url(images/ic_file.png); background-repeat: no-repeat; background-position: 8px 8px; padding: 8px 0 8px 32px; text-transform: uppercase; height: auto; line-height: 16px; overflow: hidden; font-weight: normal; font-family: 'UbuntuBold', "Trebuchet MS", "Helvetica CY", sans-serif; } .ow_box_cap { background: #f3f3f3 url('images/box_cap.gif') repeat-x left top; border-radius: 6px 6px 0px 0px; } .ow_box_cap .ow_box_cap_body { min-height: 32px; } .ow_box { background-color: #F5F9FA; margin-bottom: 8px; padding: 8px 8px 8px 8px; position: relative; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px; } .ow_box_empty{ position: relative; } .ow_box .bottom_toolbar, .ow_box_mod .bottom_toolbar{ margin-top: 10px; border-top: 1px solid #ccc; font-size: 10px; padding: 0 5px; text-align: right; } .ow_box.ow_no_cap { border-top-left-radius: 6px; border-top-right-radius: 6px; } .ow_sidebar .ow_box_bottom_shadow, .ow_supernarrow .ow_box_bottom_shadow { background-image: url('images/box-shadow-small.png'); bottom: -12px; } /*======================================================== [6] Standard Listings __listings ========================================================*/ .ow_canvas .ow_avatar img, .ow_canvas .ow_lp_avatars img, .ow_canvas .ow_newsfeed_avatar img { width: 40px; height: 40px; } /* ---- Item Picture Content ---- */ .ow_ipc { margin-top: 16px; margin-bottom: 0px; } .ow_ipc:first-child { margin-top: 0px; } .ow_ipc_picture{ float: left; margin-right: -50px; width: 50px; /*padding: 4px 5px 6px;*/ } .ow_ipc_picture .ow_avatar { background: url(images/avatar_bg.png) no-repeat; } .ow_ipc_picture img { width: 40px; height: 40px; } .ow_ipc_picture img:first-child { margin-top: 7px; margin-left: 5px; } .ow_ipc_picture .ow_avatar img { margin-top: 0px; margin-left: 0px; } .ow_ipc_info{ margin-left: 57px; padding: 0px 0px 10px 0px; border-bottom: 1px solid #DBDDDE; } .ow_ipc_header{ padding: 0px 0px 0px; margin: 0px 0px 0px; } .ow_ipc_header a { font-size: 12px; font-weight: bold; } .ow_ipc.ow_smallmargin { margin-bottom: 0px; } .ow_ipc_content{ padding: 0px 0px 12px 0px; line-height: 1.25em; } .ow_ipc_toolbar{ font-size: 11px; float: left; padding: 0 0px 0px 0px; width: 100%; } .ow_ipc_toolbar .ow_icon_control { padding: 0px; } html body div .ow_ipc_toolbar span { background: none; } .ow_ipc_toolbar .ow_ipc_date, .ow_ipc_date { float: right; font-size: 10px; line-height: 14px; } /* ---- End of the Item Picture Content ---- */ /* ---- Mini Item Picture Content ---- */ .ow_mini_ipc_picture { float: left; margin-right: -42px; width: 42px; } .ow_mini_ipc_picture .ow_avatar { background: url(images/avatar_mini_bg.png) no-repeat 0px 0px; } .ow_mini_ipc_picture img, .ow_mini_ipc_picture .ow_avatar, .ow_mini_ipc_picture .ow_avatar img { width: 32px; height: 32px; } .ow_mini_ipc_info { margin-left: 49px; padding-top: 0; } .ow_mini_ipc_info .mipc_url { font-weight: bold; } .ow_mini_ipc_content { margin-top: 5px; } /* ---- End of the Mini Item Picture Content ---- */ /* ---- Item Content ---- */ .ow_ic_header { margin-bottom: 5px; } .ow_ic_description { margin-bottom: 5px; } .ow_ic_date { float: right; font-size: 10px; line-height: 14px; } th, .ow_highbox_table .ow_highbox, .ow_page .ow_highbox, .ow_sidebar, .ow_table_3 td { border-color: #e7e7e7; } .ow_page td.ow_highbox { border-color: #C4C4C4; } .ow_box_toolbar { margin-top: 16px; font-size: 11px; float: right; white-space: nowrap; } .ow_box_toolbar span { padding: 0px 2px 0px 0px; } .ow_box_toolbar span.ow_nowrap a { display: inline-block; color: #91959B; text-shadow: #fff 0 1px 0; border-style: solid; border-top-color: #ccc; border-right-color: #ccc; border-left-color: #ccc; border-bottom-color: #ccc; border-width: 1px 1px 1px 1px; background: url(images/box_menu.gif) repeat-x; padding: 0px 6px 0px; line-height: 22px; border-radius: 3px; -moz-border-radius:3px; -webkit-border-radius: 3px; -khtml-border-radius:3px; } .ow_box_toolbar span.ow_nowrap a:hover { background: url(images/box_menu_active.gif) repeat-x; color:#DDFFFF; text-shadow: #0075D6 0 1px 0; border-color: #2F95C4; } .ow_box_empty .ow_box_toolbar { } .ow_box_toolbar a { color: #5a5a5a; } .ow_box_toolbar a:hover { text-decoration: none; } .ow_box_toolbar .ow_delimiter, .ow_ic_toolbar .ow_delimiter{ display: none; } .ow_avatar_list{ text-align: center; } .ow_avatar_list a{ margin-bottom: 0px; margin-right: 1px; } /* ---- Tooltip ---- */ .ow_tooltip { margin-top: 0; padding-top: 2px; } .ow_tooltip_tail { display:inline-block; padding: 0px 0px; width: 100%; } .ow_tooltip_tail span { display:inline-block; background: url(images/tooltip_tail.png) no-repeat 8px -6px; width: 19px; height: 6px; margin-bottom: -1px; } .ow_tooltip .ow_tooltip_body { background:#f6fafd; padding:4px; border-radius:4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; border: 1px solid #d1d1d1; -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); box-shadow:0 2px 4px rgba(0, 0, 0, 0.2); /*max-width: 250px;*/ } .ow_forum_search_context_menu .ow_tooltip .ow_tooltip_body { padding: 4px 0; } .ow_forum_search_context_menu .ow_context_action_list a { padding: 4px 12px; } /* ---- Top Right Tooltip ---- */ .ow_tooltip_top_right.ow_tooltip { margin-top: 0; position: absolute; right: -1px; top: 0px; } .ow_tooltip_top_right .ow_tooltip_tail span { background-position: 3px -6px; } .ow_tooltip_top_right .ow_tooltip_tail { text-align: right; } /* ---- Bottom Left Tooltip ---- */ .ow_tooltip_bottom_left .ow_tooltip_tail span { background-position: 9px 0px; margin-top: -1px; } /* ---- Bottom Right Tooltip ---- */ .ow_tooltip_bottom_right .ow_tooltip_tail span { background-position: 1px 0px; margin-top: -1px; } .ow_tooltip_bottom_right .ow_tooltip_tail { text-align: right; } /* ---- Left Side Tooltip ---- */ .ow_tooltip_left .ow_tooltip_tail { float: left; margin-right: -4px; width: 4px; padding-top: 8px; } .ow_tooltip_left .ow_tooltip_tail span { margin: 0px; width: 5px; height: 11px; background-position: 0px -28px; } .ow_tooltip_left .ow_tooltip_body { display: block; margin-left: 4px; } /* ---- Right Side Tooltip ---- */ .ow_tooltip_right .ow_tooltip_tail { float: right; margin-left: -4px; width: 5px; padding-top: 8px; } .ow_tooltip_right .ow_tooltip_tail span { margin: 0px; width: 5px; height: 11px; background-position: 0px -15px; } .ow_tooltip_right .ow_tooltip_body { display:block; margin-right: 4px; } /* ---- End of Tooltip ---- */ /* ---- Counter ---- */ .ow_count_wrap { text-align: center; display: inline-block; line-height: 15px; font-size: 10px; vertical-align: top; } .ow_count_bg { border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; display: inline-block; background: none repeat scroll 0 0 #57C0E7; min-height: 15px; overflow: hidden; } .ow_count { color: #e5ffff; padding: 0 4px 0 4px; text-shadow: #2482a3 0 1px 0; } .ow_count_active { background: none repeat scroll 0 0 #ff77b9; text-shadow: #c5528b 0 1px 0; } /* ---- End of Counter ---- */ /* ---- Item Voted Content ---- */ .ow_ivc_box{ } .ow_ivc_voteupdown{ background-repeat: no-repeat; background-position: center 5px; float: left; margin-right: -50px; padding: 0px 5px 5px; text-align: center; } .ow_ivc_content{ margin-left: 75px; } /* .ow_ivc_origin{ background-repeat: no-repeat; margin-bottom: 8px; padding: 2px 0px 2px 20px; } .ow_ivc_toolbar .ow_comments, .ow_ivc_toolbar .ow_tags, .ow_ivc_toolbar .ow_voteup, .ow_ivc_toolbar .ow_votedown{ background-repeat: no-repeat; display: inline-block; margin-left: 5px; padding: 0px 0px 2px 20px; } */ /* ---- Listing Picture ---- */ .ow_lp_picture{ float: left; margin: 0 1px 1px 0; } .ow_lp_wrapper{ /*float: left; overflow: hidden; text-align: center;*/ } .ow_lp_avatars{ text-align:center; } .ow_lp_avatars .ow_lp_wrapper{ display: inline-block; margin: 0 1px 1px 0; width: 40px; } .ow_lp_albums .ow_lp_wrapper{ width: 77px; height: 77px; padding: 4px 0px 0px 5px; float: left; margin-right: 4px; background: url(images/lp_wrapper.png) no-repeat 0px 0px; } .ow_lp_photos .ow_lp_wrapper{ width: 77px; height: 77px; padding: 4px 0px 0px 5px; margin: 0 2px 2px 0; display: inline-block; float: none; background: url(images/lp_wrapper.png) no-repeat 0px 0px; text-align: left; } .ow_lp_avatars img { /*display: block;*/ } .ow_lp_avatars .ow_avatar { margin: 1px; text-align: left; } .ow_lp_photos img, .ow_lp_albums img{ width: 72px; height: 72px; /*display: block;*/ } .ow_lp_label{ margin-left: 80px; } .ow_lp_avatars.ow_mini_avatar{ text-align:left; } .ow_mini_avatar .ow_avatar{ background: url(images/avatar_mini_bg.png) no-repeat 0px 0px; } .ow_mini_avatar .ow_avatar, .ow_avatar.ow_mini_avatar, .ow_mini_avatar .ow_avatar img, .ow_avatar.ow_mini_avatar img { width: 32px; height: 32px; } a.avatar_list_more_icon{ width: 25px; height: 32px; display: inline-block; margin: 0 1px; background: #eee url(images/more_icon.png) no-repeat 50% 50%; } /* ---- User List ---- */ .ow_user_list { } .ow_user_list .ow_item_set3{ width: 32%; word-wrap: break-word; } .ow_user_list_item{ float: left; padding: 10px; padding-right: 0px; position: relative; } .ow_user_list_picture{ float: left; margin-right: -50px; width: 50px; } .ow_user_list_picture img{ width: 40px; height: 40px; } .ow_user_list_data{ margin-left: 53px; } .ow_uli_context_menu { position: absolute; top: 10px; right: 10px; display: none; } .ow_user_list_item:hover .ow_uli_context_menu { display: block; } .ow_uli_context_menu .ow_tooltip .ow_tooltip_body { padding: 4px 0; } .ow_uli_context_menu .ow_context_action_list a { padding: 4px 12px; } /*======================================================= [7] Tables __tables ========================================================*/ .ow_table_1, .ow_table_2 { border-collapse: separate; } .ow_table_3 { border-collapse: collapse; } .ow_table_1, .ow_table_2, .ow_table_3{ margin-bottom: 25px; width: 100%; } .ow_table_1 tr td, .ow_table_2 tr td, .ow_user_list .ow_alt1, .ow_user_list .ow_alt2, .ow_video_list .ow_alt1, .ow_video_list .ow_alt2, .ow_photo_list .ow_alt1, .ow_photo_list .ow_alt2 { border-style: solid; border-color: #C4C4C4; } .ow_table_1 tr td, .ow_table_2 tr td { border-width: 0px 1px 1px 0px; } .ow_table_1 .ow_empty + tr td:first-child, .ow_table_2 .ow_empty + tr td:first-child { border-radius: 4px 0px 0px 0px; -moz-border-radius: 4px 0px 0px 0px; -webkit-border-radius: 4px 0px 0px 0px; border-bottom-width: 1px; border-left-width: 1px; border-top-width: 1px; } .ow_photo_list div:first-child, .ow_video_list div:first-child, .ow_user_list div:first-child { border-left-width: 1px; border-top-width: 1px; } .ow_table_1 tr td:first-child, .ow_table_2 tr td:first-child { border-left-width: 1px; } .ow_photo_list div, .ow_video_list div, .ow_user_list div { border-bottom-width: 1px; border-left-width: 1px; border-right-width: 1px; } .ow_photo_list div:last-child, .ow_video_list div:last-child, .ow_user_list div:last-child { border-bottom-width: 1px; border-left-width: 1px; border-right-width: 1px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; } .ow_photo_list div:first-child, .ow_video_list div:first-child, .ow_user_list div:first-child { border-top-left-radius: 4px; border-top-right-radius: 4px; } .ow_table_1 tr td:last-child, .ow_table_2 tr td:last-child { border-bottom-width: 1px; border-right-width: 1px; } .ow_table_1 tr:first-child td, .ow_table_2 tr:first-child td { border-top-width: 1px; } .ow_table_1 tr:first-child td:first-child, .ow_table_1 tr:first-child th:first-child, .ow_table_2 tr:first-child td:first-child, .ow_table_2 tr:first-child th:first-child { border-top-left-radius: 4px; -moz-border-top-left-radius: 4px; -webkit-border-top-left-radius: 4px; border-bottom-width: 1px; border-left-width: 1px; border-top-width: 1px; } .ow_table_1 tr:first-child td:last-child, .ow_table_1 tr:first-child th:last-child, .ow_table_2 tr:first-child td:last-child, .ow_table_2 tr:first-child th:last-child { border-top-right-radius: 4px; -moz-border-top-right-radius: 4px; -webkit-border-top-right-radius: 4px; border-bottom-width: 1px; border-top-width: 1px; border-right-width: 1px; } .ow_table_1 tr:last-child td:first-child, .ow_table_1 tr.ow_alt1:last-child td:first-child, .ow_table_1 tr.ow_tr_last td:first-child, .ow_table_1 tr.ow_tr_last th:first-child, .ow_table_2 tr:last-child td:first-child, .ow_table_2 tr.ow_alt1:last-child td:first-child, .ow_table_2 tr.ow_tr_last td:first-child, .ow_table_2 tr.ow_tr_last th:first-child { border-bottom-left-radius: 4px; -moz-border-left-radius: 4px; -webkit-border-left-radius: 4px; border-bottom-width: 1px; border-left-width: 1px; border-bottom-right-radius: 0px; -moz-border-bottom-right-radius: 0px; -webkit-border-bottom-right-radius: 0px; } .ow_table_1 tr:last-child td:last-child, .ow_table_1 tr.alt1:last-child td:last-child, .ow_table_1 tr.ow_tr_last td:last-child, .ow_table_1 tr.ow_tr_last th:last-child, .ow_table_2 tr:last-child td:last-child, .ow_table_2 tr.alt1:last-child td:last-child, .ow_table_2 tr.ow_tr_last td:last-child, .ow_table_2 tr.ow_tr_last th:last-child { border-bottom-right-radius: 4px; -moz-border-bottom-right-radius: 4px; -webkit-border-bottom-right-radius: 4px; border-bottom-width: 1px; border-right-width: 1px; border-top-right-radius: 0px; -moz-border-top-right-radius: 0px; -webkit-border-top-right-radius: 0px; } .ow_table_1 tr:last-child td, .ow_table_1 tr:last-child th, .ow_table_2 tr:last-child td, .ow_table_2 tr:last-child th { border-top-width: 0px; } .ow_table_1 th, .ow_table_2 th { border-style: solid; border-color: #e8e8e8 #e8e8e8 #ccc #e8e8e8; border-width: 0px 1px 1px; _border-width: 1px; } .ow_table_1 tr.ow_tr_first td, .ow_table_2 tr.ow_tr_first td{ border-top-width: 1px; } .ow_table_1 tr.ow_tr_first th, .ow_table_2 tr.ow_tr_first th { border-width: 1px 0px; border-color: #C4C4C4; } .ow_table_1 tr.ow_tr_first th:first-child, .ow_table_1 tr.ow_tr_first td:first-child, .ow_table_2 tr.ow_tr_first th:first-child, .ow_table_2 tr.ow_tr_first td:first-child { border-left-width: 1px; border-top-left-radius: 4px; } .ie8 .ow_table_1 tr.ow_tr_first th, .ie8 .ow_table_2 tr.ow_tr_first th { border-right-width: 1px; } /*@media \0screen { .ow_table_1 tr.ow_tr_first th, .ow_table_2 tr.ow_tr_first th { border-right-width: 1px; } }*/ .ow_table_1 tr.ow_tr_delimiter td, .ow_table_2 tr.ow_tr_delimiter td { border: none; } .ow_table_1 tr.ow_tr_first th:last-child, .ow_table_1 tr.ow_tr_first td:last-child, .ow_table_2 tr.ow_tr_first th:last-child, .ow_table_2 tr.ow_tr_first td:last-child { border-right-width: 1px; border-top-right-radius: 4px; } .ow_table_1 tr.ow_tr_first th:last-child, .ow_table_2 tr.ow_tr_first th:last-child { border-right-color: #ABABAB; } .ow_table_1 td, .ow_table_2 td{ padding: 8px; vertical-align: middle; } .ow_table_1 td .text{ color: #999; } .ow_table_2{ border-collapse: separate; } .ow_table_2 td{ text-align: center; } .ow_table_3{ border-collapse: separate; border-spacing: 5px; } .ow_table_3 td{ border-left-width: 1px; border-left-style: solid; vertical-align: top; } .ow_table_3 td.ow_label{ border: none; color: #666; text-align: right; } .ow_table_3 td.ow_value{ width: 50%; padding-left: 10px; } .ow_table_4{ border-collapse: separate; border-spacing: 5px; } .ow_table_4 td{ vertical-align: top; } .ow_table_4 td.ow_label{ border: none; color: #666; text-align: right; } .ow_table_4 td.ow_value{ padding-left: 10px; } th.ow_section{ border: 0 none; padding: 15px 0; text-align: center; background: transparent; } th span.ow_section_icon{ background-repeat: no-repeat; padding-left: 22px; } th.ow_section span{ background: #f0f0f0; padding: 5px 10px; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; text-shadow: #fff 0 1px 0; font-weight: normal; } table.ow_form td.ow_label{ color: #666; text-align: right; width: 20%; } table.ow_form td.ow_desc{ width: 25%; color: #666666; font-size: 11px; } table.ow_form td.ow_submit{ text-align: center; } /*======================================================== [8] Messages & Notifications __messages ========================================================*/ /*======================================================== [9] Thumbnails & Icons __icons ========================================================*/ img.thumb{ width: 100px; } html body div .ow_ic_add{ background-image: url(images/ic_add.png); } html body div .ow_ic_aloud{ background-image: url(images/ic_aloud.png); } html body div .ow_ic_app{ background-image: url(images/ic_app.png); } html body div .ow_ic_attach{ background-image: url(images/ic_attach.png); } html body div .ow_ic_birthday{ background-image: url(images/ic_birthday.png); } html body div .ow_ic_bookmark{ background-image: url(images/ic_bookmark.png); } html body div .ow_ic_calendar{ background-image: url(images/ic_calendar.png); } html body div .ow_ic_cart{ background-image: url(images/ic_cart.png); } html body div .ow_ic_chat{ background-image: url(images/ic_chat.png); } html body div .ow_ic_clock{ background-image: url(images/ic_clock.png); } html body div .ow_ic_comment{ background-image: url(images/ic_comment.png); } html body div .ow_ic_cut{ background-image: url(images/ic_cut.png); } html body div .ow_ic_dashboard{ background-image: url(images/ic_dashboard.png); } html body div .ow_ic_delete{ background-image: url(images/ic_delete.png); } html body div .ow_ic_draft{ background-image: url(images/ic_draft.png); } html body div .ow_ic_down_arrow{ background-image: url(images/ic_down_arrow.png); } html body div .ow_ic_edit{ background-image: url(images/ic_edit.png); } html body div .ow_ic_female{ background-image: url(images/ic_female.png); } html body div .ow_ic_file{ background-image: url(images/ic_file.png); } html body div .ow_ic_files{ background-image: url(images/ic_files.png); } html body div .ow_ic_flag{ background-image: url(images/ic_flag.png); } html body div .ow_ic_folder{ background-image: url(images/ic_folder.png); } html body div .ow_ic_forum{ background-image: url(images/ic_forum.png); } html body div .ow_ic_friends{ background-image: url(images/ic_friends.png); } html body div .ow_ic_gear_wheel{ background-image: url(images/ic_gear_wheel.png); } html body div .ow_ic_heart{ background-image: url(images/ic_heart.png); } html body div .ow_ic_help{ background-image: url(images/ic_help.png); } html body div .ow_ic_house{ background-image: url(images/ic_house.png); } html body div .ow_ic_info{ background-image: url(images/ic_info.png); } html body div .ow_ic_key{ background-image: url(images/ic_key.png); } html body div .ow_ic_left_arrow{ background-image: url(images/ic_left_arrow.png); } html body div .ow_ic_lens{ background-image: url(images/ic_lens.png); } html body div .ow_ic_link{ background-image: url(images/ic_link.png); } html body div .ow_ic_lock{ background-image: url(images/ic_lock.png); } html body div .ow_ic_mail{ background-image: url(images/ic_mail.png); } html body div .ow_ic_male{ background-image: url(images/ic_male.png); } html body div .ow_ic_mobile{ background-image: url(images/ic_mobile.png); } html body div .ow_ic_moderator{ background-image: url(images/ic_moderator.png); } html body div .ow_ic_monitor{ background-image: url(images/ic_monitor.png); } html body div .ow_ic_move{ background-image: url(images/ic_move.png); } html body div .ow_ic_music{ background-image: url(images/ic_music.png); } html body div .ow_ic_new{ background-image: url(images/ic_new.png); } html body div .ow_ic_ok{ background-image: url(images/ic_ok.png); } html body div .ow_ic_online{ background-image: url(images/ic_online.png); } html body div .ow_ic_picture{ background-image: url(images/ic_picture.png); } html body div .ow_ic_places{ background-image: url(images/ic_places.png); } html body div .ow_ic_plugin{ background-image: url(images/ic_plugin.png); } html body div .ow_ic_push_pin{ background-image: url(images/ic_push_pin.png); } html body div .ow_ic_reply{ background-image: url(images/ic_reply.png); } html body div .ow_ic_right_arrow{ background-image: url(images/ic_right_arrow.png); } html body div .ow_ic_rss{ background-image: url(images/ic_rss.png); } html body div .ow_ic_save{ background-image: url(images/ic_download.png); } html body div .ow_ic_restrict{ background-image: url(images/ic_restrict.png); } html body div .ow_ic_script{ background-image: url(images/ic_script.png); } html body div .ow_ic_server{ background-image: url(images/ic_server.png); } html body div .ow_ic_star{ background-image: url(images/ic_star.png); } html body div .ow_ic_tag{ background-image: url(images/ic_tag.png); } html body div .ow_ic_trash{ background-image: url(images/ic_trash.png); } html body div .ow_ic_unlock{ background-image: url(images/ic_unlock.png); } html body div .ow_ic_up_arrow{ background-image: url(images/ic_up_arrow.png); } html body div .ow_ic_update{ background-image: url(images/ic_update.png); } html body div .ow_ic_user{ background-image: url(images/ic_user.png); } html body div .ow_ic_video{ background-image: url(images/ic_video.png); } html body div .ow_ic_warning{ background-image: url(images/ic_warning.png); } html body div .ow_ic_write{ background-image: url(images/ic_write.png); } html body div .ow_button span, html body div .ow_button span.ow_negative, html body div .ow_button span.ow_negative .ow_inprogress { background-image: none; background-repeat: no-repeat; } .maintenance_cont h1 { background-image: none; } .ow_icon_control{ background-repeat: no-repeat; display: inline-block; padding: 0px 0 2px 20px; line-height: 15px; } html body div .ow_miniic_comment{ background: url(images/miniic_set.png) no-repeat 4px 5px; } html body div .ow_miniic_like { background: url(images/miniic_set.png) no-repeat -15px 4px; } html body div .ow_miniic_delete{ background-image: url(images/miniic_x.png); } html body div .ow_tinyic_delete{ background-image: url(images/tinyic_delete.png); } html body div .ow_tinyic_tag{ background-image: url(images/tinyic_tag.png); } html body div .ow_tinyic_write{ background-image: url(images/tinyic_write.png); } .ow_miniicon_control{ background-repeat: no-repeat; display: inline-block; padding: 1px 0 2px 14px; line-height: 9px; } .ow_box_cap_icons { margin-top: -26px; } span.ow_icon{ background-repeat: no-repeat; display: inline-block; height: 16px; width: 16px; } .ow_marked_cell{ background-image: url(images/ic_ok.png); background-repeat: no-repeat; background-position: center center; } .ow_box_cap_icons a.close{ background-position: 50% 50%; background-repeat: no-repeat; float: right; width: 20px; height: 20px; } /*======================================================== [10] Menus __menus ========================================================*/ /* ---- Main Menu styles ---- */ .ow_menu_wrap { height: 76px; display: table; background: url('images/menu.png') repeat-x; margin: 0px 0px 0px 0px; width: 815px; } .ow_main_menu{ font-family: 'UbuntuBold', "Trebuchet MS", "Helvetica CY", sans-serif; display: table-cell; text-align: center; vertical-align: middle; padding: 4px 0px 0px; } html[xmlns] .ow_main_menu.clearfix { display: table-cell; } .ow_main_menu li { padding: 0; display: inline-block; } .ow_main_menu li a { color: #00AEEC; /** OW_Control type:color, key:menuColor, section:2. Colors, label:4. Menu text color **/ display: inline-block; font-size: 13px; padding: 2px 8px 6px 8px; text-decoration: none; text-transform: uppercase; text-shadow: #fff 0 1px 0; font-weight: normal; } .ow_main_menu li.active a { } .ow_main_menu li.active a, .ow_main_menu li a:hover { color: #FF77B9; text-shadow: #fff 0 1px 0; } .ow_box_menu { font-size: 0px; line-height: 21px; margin-bottom: 16px; } .ow_box .ow_box_menu { text-align: right; } .ow_box_menu a { background: #fff; display: inline-block; font-size:11px; height: 23px; padding: 0px 6px 0 7px; color: #91959b; text-shadow: #fff 0 1px 0; border-style: solid; border-top-color: #ccc; border-right-color: #ccc; border-left-color: #ccc; border-bottom-color: #ccc; border-width: 1px 1px 1px 1px; margin: 0px 0px 0px -1px; outline: 0; background: transparent url('images/box_menu.gif') repeat-x left top; } .ow_box_menu a:first-child { border-left-width: 1px; border-top-left-radius: 3px; -moz-border-top-left-radius: 3px; -webkit-border-top-left-radius: 3px; border-bottom-left-radius: 3px; -moz-border-bottom-left-radius: 3px; -webkit-border-bottom-left-radius: 3px; } .ow_box_menu a:last-child { border-top-right-radius: 3px; -moz-border-top-right-radius: 3px; -webkit-border-top-right-radius: 3px; border-bottom-right-radius: 3px; -moz-border-bottom-right-radius: 3px; -webkit-border-bottom-right-radius: 3px; } .ow_box_empty .ow_box_menu{ float: right; padding-left: 5px; } .ow_box_menu a.active, .ow_box_menu a:hover{ color:#DDFFFF; text-decoration:none; background: transparent url('images/box_menu_active.gif') repeat-x left top; text-shadow: #0075D6 0 1px 0; border-color: #2F95C4; } /* ---- End of Main Menu styles ---- */ /* ---- Content Menu styles ---- */ .ow_content_menu{ font-size: 0px; font-family: 'UbuntuBold', "Trebuchet MS", "Helvetica CY", sans-serif; text-transform: uppercase; font-weight: normal; } .ow_content_menu_wrap{ margin-bottom:20px; } .ow_content_menu li{ float: left; padding-left: 5px; border-left: 1px solid #E2E3E4; } .ow_content_menu li:first-child { border-color: transparent; } .ow_content_menu li a{ display: block; padding: 3px 3px 4px 0px; font-size: 13px; color: #626060; } .ow_content_menu span{ background-image: url(images/ic_file.png); background-position: 5px 9px; background-repeat: no-repeat; padding: 8px 8px 10px 28px; display: block; } .ow_content_menu li.active { background: url(images/content_menu_bg_left.png) no-repeat; } .ow_content_menu li.active, .ow_content_menu li.active +li { border-color: transparent; } .ow_content_menu li.active a { background: url(images/content_menu_bg.png) no-repeat right 0px; color: #636D74; text-decoration: none; } .ow_content_menu li a:hover { color: #9f9f9f; text-decoration: none; } /* ---- End of Content Menu styles ---- */ /* ---- Button List styles ---- */ ul.ow_bl{ padding: 0; } ul.ow_bl li{ float: right; list-style: none; margin-left: 4px; margin-bottom: 4px; } ul.ow_bl a { display: block; background: url(images/box_menu.gif) repeat-x center left; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; border: 1px solid #ccc; color: #626060; padding: 0px 8px; line-height: 21px; height: 22px; text-decoration: none; font-size: 11px; } ul.ow_bl a:hover { border-color: #bababa; } span.ow_blitem { background: url(images/box_menu.gif) repeat-x center left; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: 1px solid #CCCCCC; padding: 0px 0px; line-height: 20px; height: 22px; text-decoration: none; display: inline-block; margin: 0px 4px 0px 0px; } span.ow_blitem span { display: inline-block; } span.ow_blitem.ow_red input[type="submit"]{ text-shadow: none; color: #EE3D32; } span.ow_blitem input[type="submit"], span.ow_blitem input[type="button"] { border: none; padding: 0px; background: none; font-weight: normal; height: auto; text-shadow: 0 1px 0 #FAFAFA; padding: 2px 5px 0 6px; font-size: 11px; line-height: 17px; font-family: "Tahoma","Lucida Grande", "Verdana"; text-transform: none; color: #626060; } span.ow_blitem:hover, span.ow_blitem input:hover { border-color: #b4b4b4; } /* ---- Button List styles Cover Image ---- */ .ow_bg_controls span.ow_blitem{ background: url(images/btnl_black_bg.png) repeat-x center left; border-radius: 3px; border: none; height: 24px; line-height: 22px; } .ow_bg_controls span.ow_blitem:hover{ background: url(images/btnl_black_hover_bg.png) repeat-x center left; } html body div .ow_bg_controls .ow_green{ color:#ccc; } .ow_bg_controls span.ow_blitem input[type="submit"], .ow_bg_controls span.ow_blitem input[type="button"]{ color: #ccc; text-shadow: none; } .ow_bg_controls span.ow_blitem input[type="submit"]:hover, .ow_bg_controls span.ow_blitem input[type="button"]:hover{ color: #eee; } /* ---- End of Button List styles Cover Image ---- */ /* ---- End of Button List styles ---- */ /* ---- Footer Menu styles ---- */ .ow_footer_menu{ font-size: 11px; padding: 10px; text-align: center; margin-bottom: 15px; } /* ---- End of Footer Menu styles ---- */ /* ---- Inventory Line styles ---- */ .ow_inventory_line{ } /*======================================================== [11] Pagination __pagination ========================================================*/ html[xmlns] .ow_paging.clearfix { display: inline-block; } .ow_paging{ font-size: 11px; background: #f5f5f5; border: 1px solid #cfcfcf; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; padding: 1px; } .ow_paging a{ display: inline-block; line-height: 16px; background: url(images/box_menu.gif) repeat-x 0px 0px; padding: 2px 6px 2px 7px; text-decoration: none; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; color: #6c6c6c; border: 1px solid #ccc; } .ow_paging a.active, .ow_paging a:hover{ background: url(images/console_active_item_bg.gif) repeat-x 0px 0px; color: #FF77B9; } .ow_paging span { display: inline-block; padding-left: 3px; } /*======================================================== [12] Typography __typography ========================================================*/ @font-face { font-family: 'UbuntuBold'; src: url(images/Ubuntu-B-webfont.eot); src: url(images/Ubuntu-B-webfont.eot?#iefix) format('embedded-opentype'), url(images/Ubuntu-B-webfont.woff) format('woff'), url(images/Ubuntu-B-webfont.ttf) format('truetype'), url(images/Ubuntu-B-webfont.svg#UbuntuBold) format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'UbuntuRegular'; src: url(images/Ubuntu-R-webfont.eot); src: url(images/Ubuntu-R-webfont.eot?#iefix) format('embedded-opentype'), url(images/Ubuntu-R-webfont.woff) format('woff'), url(images/Ubuntu-R-webfont.ttf) format('truetype'), url(images/Ubuntu-R-webfont.svg#UbuntuRegular) format('svg'); font-weight: normal; font-style: normal; } .ow_small{ font-size: 11px; line-height: 14px; } .ow_highlight{ background: #aaffaa; } .ow_std_margin{ margin-bottom: 25px; } .ow_normal{ font-size: 13px; } html body .ow_sidebar .ow_tiny, html body .ow_console .ow_tiny, .ow_tiny { font-size: 9px; } .ow_stdmargin{ margin-bottom: 28px; } .ow_smallmargin{ margin-bottom: 8px; } .ow_outline{ color: #FF7000; font-weight: bold; } .ow_lightweight{ font-weight: normal; } .ow_txt_value { font-weight: bold; color: #FF7000; /** OW_Control type:color, section:2. Colors, key:txtValue, label:5. Numeric values **/ } .ow_remark { color: #999; } .ow_alt1, tr.ow_alt1 td{ background-color: #ececec; } .ow_alt2, tr.ow_alt2 td{ background-color: #E3E3E3; } .ow_high1{ background-color: #fff; } .ow_high2{ background-color: #f8f8f8; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; } .ow_add_content{ background-color: #f5f9fa; } .ow_add_content:hover{ background-color: #ececec; } a.ow_lbutton, span.ow_lbutton { background: #fff; color: #666; padding: 0px 3px 0px; line-height: 13px; text-transform: uppercase; border-radius: 2px; border: 1px solid #ccc; text-shadow: none; display: inline-block; font-weight: bold; vertical-align: middle; } html body a.ow_lbutton, html body span.ow_lbutton { font-size: 8px; } .ow_lbutton:hover{ cursor: pointer; text-decoration: none; } .ow_disabled{ background: #ccc; } .info{ margin-bottom: 8px; } .ow_automargin{ margin-left: auto; margin-right: auto; } .ow_autowidth, table.ow_form td.ow_autowidth{ width: auto; } .ow_anno { background:#ffeed7 url(images/ic_warning.png) no-repeat scroll 15px 45%; border:1px solid #ffd399; padding:10px; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; } .outline{ color: #FF7000; font-weight: bold; } input[type=text].ow_inputready, textarea.ow_inputready { color: #999999; } /*======================================================== [13] Misc __misc ========================================================*/ .clr{ clear: both; } .ow_column_equal_fix{ padding-bottom: 20001px !important; margin-bottom: -20000px !important; } /*======================================================== [14] Clearfix __clearfix ========================================================*/ .clearfix{ zoom: 1; } .clearfix:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .clearfix { display: inline-block; } html[xmlns] .clearfix { display: block; } *html .clearfix { height: 1%; } /*======================================================== [15] Plugin Styles __plugins ========================================================*/ /* ---- Base plugin styles ---- */ .ow_add_content{ background-image: url(images/ic_add.png); background-repeat: no-repeat; background-position: center 8px; float: left; margin: 0 0px 4px 3px; overflow:hidden; padding: 28px 0 6px; text-align:center; width:47%; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; } .ow_add_content:hover{ text-decoration:none; } .ow_add_content:nth-child(odd) { margin-left: 0px; } /* ---- End of base plugin styles ---- */ /* ---- Forum styles ---- */ .ow_forum{ text-align: center; width: 100%; } .ow_forum .ow_name{ text-align: left; width: 563px; } .ow_forum .ow_topics{ width: 55px; } .ow_forum .ow_replies{ width: 55px; } .ow_forum .ow_action{ white-space: nowrap; width: 70px; } .ow_forum_topic .ow_author{ width: 20%; } .ow_forum_topic .ow_posts{ text-align: center; width: 1%; } .ow_forum_topic .ow_views{ text-align: center; width: 1%; } .ow_forum_topic .ow_icon{ line-height: 14px; text-align: center; width: 8%; } body.htmlarea_styles blockquote.ow_quote, blockquote.ow_quote{ margin: 10px 0 10px 40px; background: #f0f0f0; border-left: 2px solid #ccc; padding: 2px 5px; } body.htmlarea_styles blockquote.ow_quote .ow_author, blockquote.ow_quote .ow_author{ border-bottom: 1px solid #ccc; font-size: 11px; display: inline-block; padding: 2px 0; width: 98%; } .ow_forum_topic_posts .ow_post_comment{ background-repeat: no-repeat; font-style: italic; font-size: 11px; margin: 10px 0; padding-left: 20px; } .ow_forum_post_area{ height: 240px; } .ow_forum_status{ font-style: italic; } /* ---- Forum sortable ---- */ .forum_placeholder{ border: 1px dashed #999; background-color: #FFF9DB; margin-bottom: 25px; width: 100%; } tr.forum_placeholder td{ background-color: #FFF9DB; border: 1px dashed #999; height: 45px; width: 100%; } .forum_section{ cursor: move; } .forum_section_tr{ height: 41px; } .ow_forum_topic_posts .ow_box .ow_ipc_info { border: none; padding: 0px; } body .ow_forum_attachment_icon { width: 16px; } body .forum_search_wrap { background: #E4E7E8; } /* ---- End of Forum styles ---- */ /* ---- Mailbox styles ---- */ .ow_mailbox_left_loading .ow_mailbox_left_body { background: url(images/ajax_preloader_content.gif) center 220px no-repeat; } body .ow_mailbox_right.ow_mailbox_right_loading div.ow_mailbox_right_preloading { background: url(images/ajax_preloader_content.gif) no-repeat center center; } .ow_mailbox_message_content .ow_file_attachment_info, .ow_dialog_items_wrap .ow_file_attachment_info, .ow_mailbox_log .ow_file_attachment_info { padding-left: 16px; background: url(images/miniic_doc.png) no-repeat 8px 50%; } .ow_mailbox_convers_info.mails { background-image: url(images/miniic_envelope.png); background-position: 8px 27px; background-repeat: no-repeat; } .ow_mailbox_convers_info.chats { background-image: url(images/miniic_buble.png); background-position: 8px 27px; background-repeat: no-repeat; } .ow_mailbox_convers_info_attach { background: url(images/miniic_attach.png) center center no-repeat; } .ow_mailbox_conv_options_label { background-image: url(images/chat_tiny_arrow_down.png); } .ow_mailbox_convers_info, .ow_vertical_nav_item.selected, .ow_vertical_nav_item.selected:hover { background-color: #ececec; } .ow_mailbox_convers_info_new, .ow_vertical_nav_item { background-color: #fafafa; } .ow_mailbox_convers_info_selected, .ow_vertical_nav_item:hover { background-color: #E3E3E3; } .ow_mailbox_convers_info:hover, .ow_mailbox_convers_info_selected, .ow_mailbox_convers_info_selected:hover, .ow_vertical_nav_item.selected, .ow_vertical_nav_item:hover { -webkit-box-shadow: inset 1px 0px 0px 0px rgba(172,172,172,1); -moz-box-shadow: inset 1px 0px 0px 0px rgba(172,172,172,1); box-shadow: inset 1px 0px 0px 0px rgba(172,172,172,1); } .ow_mailbox_convers_info .ow_mailbox_convers_info_date:hover { color: #999; } .ow_mailbox_convers_info .ow_mailbox_convers_info_string a, a.ow_vertical_nav_item { color: #444; } .ow_mailbox_convers_info span.ic_reply { background-image: url(images/ic_reply_g.png); } .ow_mailbox_table, .ow_mailbox_table .ow_mailbox_convers_info, .ow_mailbox_table .ow_mailbox_cap, .ow_mailbox_table .ow_mailbox_date_cap, .ow_mailbox_table .ow_mailbox_conv_options, .ow_mailbox_table .ow_mailbox_subject_block, .ow_mailbox_table .ow_mailbox_log, .ow_mailbox_table .ow_mailbox_log_date, .ow_mailbox_table .ow_mailbox_left .ow_mailbox_cap, .ow_mailbox_table .ow_mailbox_left .ow_mailbox_search, .ow_mailbox_table .ow_mailbox_left .ow_mailbox_left_body, .ow_mailbox_right .ow_chat_message_block, .ow_vertical_nav, .ow_vertical_nav_item { border-color: #D3D6D7; } .ow_mailbox_log .ow_dialog_item.odd .ow_dialog_in_item, .ow_mailbox_log .ow_dialog_item.even .ow_dialog_in_item { border: 1px solid #d3d6d7; } .ow_mailbox_log .ow_dialog_item.even i { background-image: url(images/dialog_tail.png); background-position: 0 -1px; } .ow_mailbox_log .ow_dialog_item.odd i { background-image: url(images/dialog_tail.png); background-position: 0 -6px; } .ow_mailbox_convers_actions .ow_miniic_control { margin-right: 0px; } .ow_mailbox_convers_actions .ow_miniic_control span { background: url(images/miniic_gearwheel.png) -1px -1px no-repeat; } .ow_mailbox_convers_actions .ow_miniic_control.active span { background: url(images/miniic_gearwheel.png) -1px -22px no-repeat; } /* wysiwyg only for new message */ .htmlarea_styles.mailbox { color: #333; } .htmlarea_styles.mailbox a { color: #2a80ae; } /* end of wysiwyg only for new message */ /* ---- End of Mailbox styles ---- */ /* ---- Blogs styles ---- */ .ow_blogpost_compose textarea{ height: 235px; } .ow_ws_video object, .ow_ws_video embed { max-width: 100%; } /* ---- End of Blogs styles ---- */ /* ---- Rates Styles ---- */ .inactive_rate_list, .active_rate_list { background: url(images/stars.png) no-repeat 0 -13px; width: 65px; height: 13px; text-align: left; display: inline-block; } .active_rate_list { background-position: 0 0; } .rates_cont a.rate_item { background: url(images/stars.png) no-repeat 0 -13px; cursor: pointer; float: left; height: 13px; text-decoration: none; width: 13px; } .rates_cont a.active { background-position: 0 0; } .rates_cont{ margin: 0 auto; width: 65px; } .ow_rate_score{ font-size: 20px; } /* ---- End of Rates Styles ---- */ /* ---- Video styles ---- */ .ow_video_list .ow_alt1, .ow_video_list .ow_alt2 { padding: 24px 0px 24px 24px; } .ow_video_player{ text-align: center; } .ow_video_description{ margin: 8px 0 20px; } .ow_video_list_item{ float: left; max-height: 165px; padding: 5px; width: 120px; margin-right: 20px; background: url(images/video_bg.png) no-repeat 0px 0px; } .ow_other_video_item_title{ margin-left: 88px; padding-left: 4px; } .ow_video_thumb{ background: url(images/video-no-video.png) no-repeat center center; display: block; } .ow_video_thumb, .ow_video_list_item img{ height: 90px; width: 120px; } .ow_other_video_thumb{ display: block; margin-right: -80px; background: url(images/video_thumb_bg.png) no-repeat 0 0; padding: 4px 4px 4px 5px; } .ow_other_video_thumb a { display: inline-block; width: 80px; height: 60px; background: url(images/video-no-video.png) no-repeat center center; } .video_thumb_no_title { margin: 0px 4px 4px 0px; } .ow_other_video_thumb, .ow_other_video_thumb img, .ow_other_video_floated img{ height: 60px; width: 80px; } .ow_other_video_floated{ display: inline-block; background: #fff url(images/video-no-video.png) no-repeat center center; width: 80px; height: 60px; vertical-align: middle; } .ow_video_item_title{ font-weight: bold; padding-bottom: 3px; } .ow_video_item_rate{ height: 15px; text-align: center; } .ow_video_infobar{ padding: 10px; text-align: right; } .ow_video_player object, .ow_video_player embed { max-width: 100%; } /* ---- End of Video styles ---- */ /* ---- Avatar styles ---- */ .ow_change_avatar .avatar_current{ border-right: 1px solid #CCCCCC; padding-right: 3px; } .ow_change_avatar .ow_avatar_preview{ border-left: 1px solid #CCCCCC; } .ow_change_avatar .avatar_crop{ border-bottom: 1px solid #CCCCCC; } .ow_avatar_crop .jcrop-holder{ margin: 0px auto; } .ow_avatar_preview div{ margin: 0px auto; } .ow_avatar { position: relative; display: inline-block; padding: 4px 5px 6px 5px; width: 40px; height: 40px; background-image: url('images/avatar_bg.png'); background-position: 0px 0px; background-repeat: no-repeat; } .ow_avatar img { vertical-align: bottom; width: 40px; height: 40px; } .ow_avatar_label { font-size: 7px; display: inline-block; position: absolute; line-height: 10px; text-transform: uppercase; bottom: 6px; background-color: #999; right: 5px; color: #fff; font-weight: bold; padding: 0px 2px; border-radius: 3px 0px 0px 0px; -moz-border-radius: 3px 0px 0px 0px; -webkit-border-radius: 3px 0px 0px 0px; } html body .ow_sidebar .ow_avatar_label, html body .ow_console .ow_avatar_label { font-size: 7px; } html body .ow_console .ow_avatar_label { bottom: 0px; right: 0px; } .ow_canvas .ow_newsfeed_avatar { width: 50px; height: 50px; margin-right: -50px; } .ow_canvas .ow_newsfeed_body { margin-left: 50px; padding-left: 7px; } /* ---- End of the Avatar styles ---- */ /* ---- User Avatar Console styles ---- */ .ow_avatar_console{ position: relative; background: #fff; border: 1px solid #e8e8e8; padding: 4px; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; } .ow_avatar_console .ow_avatar_image { height: 190px; max-width: 170px; } .ow_avatar_change{ position: absolute; right: 4px; top: 4px; } .ow_avatar_console_links { background: #F0F0F0; display: block; padding: 5px 10px; border-top: 1px solid #fff; } body .ow_avatar_console .ow_avatar_label { bottom: 4px; right: 4px; } .user_online_wrap { padding-top: 3px; min-height: 12px; text-align: left; } body .ow_avatar_console .avatar_console_label { bottom: 7px; } /* ---- End of User Avatar Console styles ---- */ /* ---- Photo styles ---- */ .ow_photo_dragndrop { font-family: 'UbuntuBold',"Trebuchet MS","Helvetica CY",sans-serif; text-transform: uppercase; color: #666; background-color: #f5f9fa; border: 1px solid #ccc; font-size: 15px; } .ow_photo_upload_wrap .ow_photo_preview_block_wrap .ow_photo_preview_edit { border: 1px solid #ccc; } .ow_photo_preview_image { background-color: #fafafa; } .ow_photo_preview_loading { background-image: url(images/ajax_preloader_content.gif) !important; background-size: auto !important; } .ow_photo_preview_image_filter { background: #000; } .ow_photo_preview_x { background: url(images/photo_upload_btn_x.png) center center no-repeat; } .ow_photo_preview_rotate { background: url(images/photo_upload_btn_rotate.png) center center no-repeat; } .ow_photo_prev{ background-repeat: no-repeat; background-position: right center; text-align: left; width: 39%; } .ow_photo_next{ background-repeat: no-repeat; background-position: left center; text-align: right; width: 39%; } .ow_photo_list_item{ float: left; height: 165px; padding: 16px 0px; text-align: center; } .ow_photo_info_str{ padding-top: 5px; } .ow_photo_infobar{ padding: 10px; text-align: right; } .ow_photo_rate{ height: 15px; text-align: center; } html body div.floatbox_photo_preview a.ow_ic_delete.close, html body div.floatbox_empty a.ow_ic_delete.close { background-image: url('images/photo_prev_x.png'); } .floatbox_empty .ow_box_cap_icons { top: -20px; right: -20px; } .ow_photo_context_action .ow_tooltip .ow_tooltip_body { padding: 4px 0; } .ow_photo_context_action .ow_context_action a { color: #fff; } .ow_photo_context_action .ow_context_action a:hover { text-decoration: none; } .ow_photo_context_action .ow_context_action_list a { color: #fff; padding: 4px 12px; } .ow_photo_context_action { border: 1px solid #808080; } body .ow_photo_context_action .ow_context_action_block .ow_context_action, html body .ow_photo_context_action .ow_context_action { border: none; } .ow_photo_context_action .ow_context_action:hover { background: url(images/photo_context_action_bg_active.png) repeat-x 0px 0px; } .ow_photo_context_action .ow_tooltip .ow_tooltip_body { background: transparent url('images/photo_context_action_tooltip_bg.png'); border-color: #737373; } .ow_photo_context_action .ow_context_action_list a:hover { background: transparent url('images/photo_context_action_item_hover.png'); } .ow_photo_context_action .ow_context_action_list.ow_alt2 { background: transparent; } .ow_photo_list_item_thumb span.ow_lbutton:hover { cursor: default; } .ow_photo_list_item_thumb { width: 120px; height: 120px; padding: 4px 6px 6px 20px; background: transparent url('images/photo_list_item_thumb.png') no-repeat 15px 0px; } .ow_photo_list_item_thumb img { width: 120px; height: 120px; } body .ow_photo_list_item_thumb span.ow_lbutton { bottom: 6px; right: 6px; } .ow_photo_submit_wrapper.ow_mild_green { background-color: #7CBB11; } /*Photo list*/ .ow_fw_menu { background-color: #F5F9FA; border: 1px solid #E7E7E7; border-radius: 4px; padding: 4px 8px; min-height: 24px; clear: both; } .ow_fw_btns { display: inline-block; } .ow_photo_list_wrap div.ow_photo_item { background-color: #ececec; border-color: #CBCFD0; } .ow_photo_list_wrap .ow_photo_item_wrap .ow_photo_item_info { background-color: rgba(0,0,0,0.85); } .ow_photo_item_info_user, .ow_photo_item_info_album, .ow_photo_item_info .ow_rates_wrap { color: #fff; } .ow_photo_item_wrap.ow_photo_album .ow_photo_item_info_description { color: #fff; } .ow_photo_pint_mode .ow_photo_item_wrap.ow_photo_album .ow_photo_item_info_description { color: #606060; } .ow_photo_album_info_wrap { border-bottom: 1px solid #DBDDDE; } .ow_photo_album_cover { border-color: #cccccc; } body .ow_photo_album_info_wrap .ow_photo_album_info .ow_photo_album_description_textarea, body .ow_photo_album_info_wrap .ow_photo_album_info .ow_photo_album_description { color: #666; } a.ow_context_action_value { color: #666; } .ow_photo_item .ow_photo_context_action.ow_photo_context_action_loading .ow_tooltip_body { background-image: url(images/ajax_preloader_content.gif); } body .ow_photo_context_action .ow_context_action { background-image: url(images/photo_view_context.png); background-color: transparent; } body .ow_photo_context_action .ow_context_action:hover { background-color: rgba(144,144,144, 0.3); background-image: url(images/photo_view_context.png); } body .ow_photoview_stage_wrap .ow_photo_context_action .ow_context_action, body .ow_photoview_stage_wrap .ow_photo_context_action .ow_context_action:hover { background-image: url(images/photo_view_context.png); background-repeat: no-repeat; background-position: center center; } .ow_photoview_stage_wrap_fullscreen .ow_photoview_fullscreen { background-image: url(images/fullscreen_min.png); } .ow_photoview_fullscreen { background-image: url(images/fullscreen_max.png); } .ow_photoview_play_btn { background-image: url(images/fullscreen_play.png); } .ow_photoview_play_btn.stop { background-image: url(images/fullscreen_stop.png); } .ow_photoview_info_btn.open { background-image: url(images/fullscreen_info_open.png); } .ow_photoview_info_btn.close { background-image: url(images/fullscreen_info_close.png); } .ow_photoview_slide_settings_btn { background-image: url(images/fullscreen_settings.png); } .ow_photoview_arrow_left { background-image: url(images/photoview_arrow_left.png); } .ow_photoview_arrow_right { background-image: url(images/photoview_arrow_right.png); } body .ow_photoview_stage_wrap .ow_photo_context_action .ow_context_action .ow_context_more { background-image: none; } .ow_photo_context_action .ow_tooltip .ow_tooltip_body { background: #464646; border: 1px solid #9b9b9a; } .ow_photo_context_action .ow_context_action_list a:hover { background-color: #8e8e8e; text-shadow: none; -webkit-text-shadow: none; -moz-text-shadow: none; } .ow_photo_context_action .ow_tooltip_tail span { background: url(images/photo_tooltip_tail.png) no-repeat 3px 0; } .ow_photo_context_action .ow_context_action_divider { background-color: rgba(160,160,160,0.7); } .ow_context_action_list a.ow_context_action_item_hierarchy_right span { background: url(images/miniic_arrow_left_bb.png) no-repeat center center; } .ow_context_action_list a.ow_context_action_item_hierarchy_left span { background: url(images/miniic_arrow_right_bb.png) no-repeat center center; } .ow_photo_pint_mode .ow_photo_item_wrap .ow_photo_item_info { background-color: #fafafa; border-top: 1px solid rgba(0, 0, 0, 0.1); } .ow_photo_pint_mode .ow_photo_item_info_user, .ow_photo_pint_mode .ow_photo_item_info_album, .ow_photo_pint_mode .ow_photo_item_info_description, .ow_photo_pint_mode .ow_photo_item_info .ow_rates_wrap { color: #606060; } .ow_photo_list.ow_photo_edit_mode .ow_photo_item .ow_photo_chekbox_area { background-color: rgba(255,255,255,0.4); } .ow_photo_list.ow_photo_edit_mode .ow_photo_item.ow_photo_item_checked .ow_photo_chekbox_area, .ow_photo_list.ow_photo_edit_mode.ow_photo_pint_mode .ow_photo_item .ow_photo_chekbox_area { background-color: rgba(255,255,255,0); } .ow_photo_edit_mode .ow_photo_chekbox_area .ow_photo_checkbox { border: 1px solid rgba(255,255,255,0.6); background-color: rgba(87,87,87, 0.6); } .ow_photo_edit_mode .ow_photo_item_checked .ow_photo_chekbox_area .ow_photo_checkbox { background-image: url(images/checkbox_icon.png); } .ow_photo_list.ow_photo_pint_mode .ow_photo_item { background: #fafafa; } /*Searchbar*/ .ow_searchbar_ac { border: 1px solid #ccc; } .ow_searchbar_ac li { background-color: #f5f9fa; font-size: 11px; } .ow_searchbar_ac li:hover { background-color: #f1f1f1; } /*Rates*/ .ow_photoview_info .ow_rates_wrap { padding-left: 4px; margin: 6px 0 8px 0; } .ow_rates_wrap span { vertical-align: middle; } .ow_rates { width: 65px; display: inline-block; vertical-align: middle; margin: 0 2px; } .ow_rates .rates_cont { position: absolute; opacity: 0; transition: opacity 0.15s; -moz-transition: opacity 0.15s; -webkit-transition: opacity 0.15s; } .ow_rates:hover .rates_cont { opacity: 1; } /*Dropdown*/ body input.ow_dropdown_btn { background-image: none; height: 28px; } .ow_dropdown_arrow_down, .ow_dropdown_arrow_up { height: 10px; position: absolute; right: 8px; top: 12px; width: 12px; cursor: pointer; } .ow_dropdown_arrow_down { background: url(images/chat_tiny_arrow_down.png) no-repeat center center; } .ow_dropdown_arrow_up { background: url(images/chat_tiny_arrow_up.png) no-repeat center center; } .ow_dropdown_list_wrap { position: relative; width: 100%; } .ow_dropdown_list { border: 1px solid #dedede; position: absolute; top: -1px; left: 0; width: 99%; margin-left: 0.5%; border-radius-bottom-left: 4px; -moz-border-radius-bottom-left: 4px; -webkit-border-radius-bottom-left: 4px; border-radius-bottom-right: 4px; -moz-border-radius-bottom-right: 4px; -webkit-border-radius-bottom-right: 4px; display: none; } .ow_dropdown_list li { width: 100%; box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; padding: 4px; background-color: #f5f9fa; color: #666; cursor: pointer; position: relative; } .ow_dropdown_list li:hover { background-color: #ececec; } .ow_add_item { position: absolute; background: url(images/miniic_plus.png) center center no-repeat; width: 10px; height: 10px; right: 8px; top: 50%; margin-top: -5px; } li.ow_dropdown_delimeter { padding: 0 4px; } .ow_dropdown_delimeter div { width: 100%; height: 1px; background-color: #dedede; } .ow_photo_upload_drop_area { border: 1px dashed #e8e8e8; } /*-----button_list narrow---------*/ ul.ow_bl_narrow{ border-top: 1px solid #ccc; padding: 0; } ul.ow_bl_narrow li{ list-style: none; } ul.ow_bl_narrow li a{ background: none; border-bottom: 1px solid #ccc; display: block; padding: 5px 7px; text-decoration: none; } ul.ow_bl_narrow li a:hover{ background: #999; color: #fff; } /* ---- Newsfeed ---- */ body ul.ow_newsfeed { padding: 0px; } .ow_newsfeed_section { list-style-image: none; margin: 15px 0; } .ow_newsfeed_section span{ background: #f0f0f0; padding: 5px 10px; text-shadow: #fff 0 1px 0; border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; } .ow_newsfeed_comments .base_cmnts_temp_cont, .ow_newsfeed_comments .base_cmnt_mark { margin-bottom: 0px; } .base_cmnt_mark .ow_ipc_info { padding-bottom: 0px; } .ow_newsfeed_features .ow_tooltip .ow_tooltip_body { border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; padding: 0; border-width: 0 1px 1px; box-shadow: none; } .ow_newsfeed_features .ow_tooltip.ow_comments_context_tooltip .ow_tooltip_body, .ow_tooltip.ow_newsfeed_context_tooltip .ow_tooltip_body { padding: 4px 0; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; } .ow_newsfeed_features .ow_tooltip.ow_comments_context_tooltip .ow_tooltip_body { border: 1px solid #D0D0D0; } .ow_newsfeed_features .ow_tooltip .ow_tooltip_tail span { height: 5px; background: url(images/comment_block_arr.png) no-repeat 8px 0px; position: relative; z-index: 1; } .ow_newsfeed_comments .ow_tooltip .ow_tooltip_tail span { height:6px; background-position: 3px -6px; background-image: url(images/tooltip_tail.png); } .ow_newsfeed_features .ow_tooltip .ow_tooltip_body .ow_tooltip .ow_tooltip_body { -webkit-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); box-shadow:0 2px 4px rgba(0, 0, 0, 0.2); } .ow_newsfeed_features .ow_context_action_list a, .ow_newsfeed_item .ow_context_action_list a { padding: 4px 12px; } .ow_newsfeed_context_tooltip { margin-top: 2px; } .ow_newsfeed_left { float: left; } .ow_newsfeed_date { float: right; text-align: right; font-size: 10px; line-height: 24px; } .ow_newsfeed_context_menu { display: none; position: absolute; right: 0; top: 0px; } .ow_newsfeed_control { display: inline-block; } .ow_content .ow_newsfeed_date { color: #8C9095; } .ow_newsfeed_date:hover { color: #2A80AE; } /* ---- if container ow_superwide ---- */ body .ow_newsfeed_control .ow_newsfeed_string { display: inline-block; vertical-align: middle; max-width: 74%; } .ow_newsfeed_left { width: 76%; } .ow_newsfeed_btns { margin-top: 14px; } .ow_newsfeed_btn_wrap { display: inline-block; line-height: 20px; background: #F5F5F5; border: 1px solid #CFCFCF; border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; padding: 1px 5px 1px 1px; margin-right: 4px; color: #91959A; vertical-align: middle; } .ow_newsfeed_item .ow_newsfeed_activity_content { padding-top: 8px; } .ow_newsfeed_item .ow_newsfeed_item_picture { margin-right: 8px; } .ow_miniic_control { display: inline-block; background: #ccc url(images/newsfeed_btn_bg.png) repeat-x 0px 0px; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; vertical-align: top; margin-right: 6px; border:1px solid #ccc; } .ow_miniic_control.active { background: #2f95c4 url(images/newsfeed_btn_bg_active.png) repeat-x 0px 0px; border: 1px solid #2f95c4; } .ow_miniic_control span { display: inline-block; width: 18px; height: 18px; } .ow_miniic_like { background-position: -15px 4px; } .ow_miniic_comment { background-position: 4px 5px; } .ow_miniic_control.active .ow_miniic_like { background-position: -15px -15px; } .ow_miniic_control.active .ow_miniic_comment { background-position: 4px -15px; } body .ow_newsfeed_doublesided_stdmargin { margin: 16px 0px; } body .newsfeed-attachment-preview.item_loaded { width: 98.7%; margin-left: 0px; margin-right: 0px; } .ow_newsfeed_item_picture { float: left; width: 100px; margin-right: 1%; } .ow_newsfeed_large_image .ow_newsfeed_item_picture { max-width: 400px; width: 100%; height: auto; } .ow_newsfeed_large_image .ow_newsfeed_item_content { width: 100%; max-width: 400px; } .ow_newsfeed_item_picture img { max-height: 400px; max-width: 100%; width: auto; height: auto; } .ow_newsfeed_photo_grid { max-width: 400px; width: 100%; } .ow_newsfeed_photo_grid_item { padding: 0px 4px 4px 0px; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; width: 50%; float: left; } .ow_newsfeed_photo_grid_3 .ow_newsfeed_photo_grid_item { width: 33.3%; } .ow_newsfeed_photo_grid_item a { float: left; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; background-size: cover; width: 100%; } /* ---- Suggest field styles ---- */ .ac_results { padding: 0px; border: 1px solid #BBB; background-color: #FFF; overflow: hidden; z-index: 105; position: absolute; display: none; width: 100%; top: -1px; } .ac_results ul { list-style-position: outside; list-style: none; padding: 0; margin: 0; } .ac_results iframe { display:none;/*sorry for IE5*/ display/**/:block;/*sorry for IE5*/ position:absolute; top:0; left:0; z-index:-1; filter:mask(); width:3000px; height:3000px; } .ac_list_container{ width: 99.6%; position: relative; } .ac_results li { margin: 0px; padding: 4px 5px; cursor: pointer; display: block; width: 98%; font: menu; font-size: 12px; overflow: hidden; } .ac_loading { background : url(images/ajax_preloader_button.gif) right center no-repeat; } .ac_over { background-color: #F0F0F0; } .ac_match{ font-weight: bold; } .ow_suggest_field { position: relative; } .ow_suggest_invitation { position: absolute; right: 9px; top: 9px; width: 12px; height: 12px; background: url(images/miniic_corner.png) no-repeat center center; } /* ow custom tips */ .ow_tip{ display:inline-block; position:absolute; z-index: 10005; color:#fff; } .ow_tip_arrow{ display:inline-block; position:absolute; } .ow_tip_arrow span{ display:block; border:5px dashed transparent; } .ow_tip_right .ow_tip_arrow span{ border-right-color:#505050; border-right-style:solid; border-right-width:5px; border-left-width:0; } .ow_tip_right .ow_tip_arrow{ top:50%; margin-top:-5px; left:0; } .ow_tip_right .ow_tip_box{ margin-left:5px; } .ow_tip_left .ow_tip_arrow span{ border-left-color:#505050; border-left-style:solid; border-left-width:5px; border-right-width:0; } .ow_tip_left .ow_tip_arrow{ top:50%; margin-top:-5px; right:0; } .ow_tip_left .ow_tip_box{ margin-right:5px; } .ow_tip_bot .ow_tip_arrow span{ border-bottom-color:#505050; border-bottom-style:solid; border-bottom-width:5px; border-top-width:0; } .ow_tip_bot .ow_tip_arrow{ left:50%; margin-left:-5px; top:0; } .ow_tip_bot .ow_tip_box{ margin-top:5px; } .ow_tip_top{ position:absolute; } .ow_tip_top .ow_tip_arrow span{ border-top-color:#57C0E7; border-top-style:solid; border-top-width:5px; border-bottom-width:0; } .ow_tip_top .ow_tip_arrow{ left:50%; margin-left:-5px; bottom:0; } .ow_tip_top .ow_tip_box{ margin-bottom:5px; } .ow_tip_box{ border-radius:3px; -webkit-border-radius:3px; -moz-border-radius:3px; padding:2px 9px 4px; background-color:#57C0E7; color:#fff; font-size: 11px; font-weight: normal; } /* ---- Group styles ---- */ body .ow_group_brief_info .details { padding-left: 8px; } /* ---- End of the Group styles ---- */ /* ---- Membership Subscribe styles ---- */ .ow_subscribe_table .ow_highbox { border-radius: 0px; -moz-border-radius: 0px; -webkit-border-radius: 0px; } body .ow_table_1 tr td.ow_plans_td_empty + td { border-top-left-radius: 4px; } body .ow_table_1 tr td.ow_gateways_td_empty + td { border-bottom-left-radius: 4px; } /* ---- End of the Membership Subscribe styles ---- */ /*-------------------------------------------------------------------- [?] Custom pages declarations TODO remove ---------------------------------------------------------------------*/ /* !!!admin pages styles */ .ow_admin_content{ width: 815px; } html body .selected_theme_info { float: right; width: 336px; } /* pages and menus */ .ow_navbox{ background:url(images/btnl_bg.png) repeat-x center left; float:left; font-size:11px; height:18px; margin-right:5px; margin-bottom:5px; padding:4px 8px; border: 1px solid #ccc; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .ow_navbox a.move{ color:#666; font-weight:bold; } .ow_navbox a.move:hover{ cursor:move; text-decoration:none; } .ow_navbox a.edit{ background:url(images/arrow-up-down.png) no-repeat 10px 10px; cursor:pointer; } .ow_navbox a.edit:hover{ text-decoration:none; } .guest_item{ background-color:#aaffaa; } .member_item{ background-color:#ffaaaa; } .ow_main_menu_scheme, .ow_bottom_menu_scheme{ float: left; height: 134px; margin-right: 10px; width: 155px; } .ow_main_menu_scheme{ background: url(images/admin-pages-menu-main.jpg) no-repeat; } .ow_bottom_menu_scheme{ background: url(images/admin-pages-menu-bottom.jpg) no-repeat; } .ow_dash_help_box{ float: left; margin-left: 5px; margin-right: 5px; width: 31%; height: 105px; } .ow_dash_help_box h3{ padding: 4px 0 4px 20px; background: transparent no-repeat left center; } .ow_dash_help_box a{ display: block; } /* user dashboard settings */ .ow_dragndrop_panel { background: #fff; /*padding: 0px 10px 10px;*/ margin-top: 5px; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; } .ow_dashboard_box{ background: #FFFFFF; padding: 5px 10px 10px 10px; margin-top: 5px; } .ow_dnd_schem_item{ background:#F0F0F0 url(images/ic_file.png) no-repeat 10px 50%; border-radius: 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; border:1px solid #ccc; cursor:move; /*float:left;*/ height:30px; margin:2px 4px 2px 0; padding:0 5px 0 33px; /*width:157px;*/ position: relative; font-size: 11px; } .ow_dnd_schem_item span.ow_label{ float:left; overflow:hidden; padding-top:5px; /*white-space:nowrap;*/ /*width:80px;*/ height: 20px; } .ow_dnd_schem_item span.action{ /*float:right;*/ line-height:15px; overflow:hidden; width:70px; position: absolute; right: 4px; top: 2px; } .ow_dnd_schem_item span.action .ow_lbutton { vertical-align: top; } .ow_dnd_helper { border: 1px dashed #000; } .ow_dnd_freezed .ow_dnd_schem_item { background-color: #FFAAAA; } .ow_dragndrop_sections .ow_highbox{ margin-top: 6px; } .ow_dnd_placeholder { height: 10px; border: 1px dashed #999999; background-color: #FFF; } .ow_dnd_preloader { height: 30px; } .ow_dnd_configurable_component .control { display: inline-block; width: 18px; height: 16px; text-decoration: none; background-position: center; background-repeat: no-repeat; } .ow_dnd_configurable_component .ow_box_icons { float: right; padding: 8px 2px 0 0; } .ow_dnd_configurable_component h3 { float: left; } .ow_dnd_content_components{ padding: 10px 0; width: 74%; } .ow_dnd_clonable_components { border-left: 1px solid #ccc; padding: 10px 0 10px 10px; width: 24%; } /* Dnd Slider */ .ow_dnd_slider { /*background:url(images/h2bg.png) repeat-x center;*/ height: 6px; background-color: #ddd; position: relative; margin: 10px 3px 0; cursor: pointer; } .ow_dnd_slider_pusher { float: left; height: 1px; } .ow_dnd_slider_marker { width: 10px; height: 1px; float: left; } .ow_dnd_slider_marker_point { position: absolute; width: 0px; height: 6px; border-left: 1px solid #999; border-right: 1px solid #FFF; top: 0; } .ow_dnd_slider_handle { position: absolute; top: -5px; width: 22px; height: 16px; cursor: move; z-index: 50; background: transparent url(images/ic_move_horizontal.png) no-repeat center; } .ow_dnd_slider_helper { } .ow_dnd_slider_in_move { opacity: 0.5; filter: alpha(opacity = 50); } .ow_dragndrop_sections .top_section, .ow_dragndrop_sections .left_section, .ow_dragndrop_sections .right_section, .ow_dragndrop_sections .bottom_section, .ow_dragndrop_sections .sidebar_section{ background-position: center 7px; background-repeat: no-repeat; } .ow_dragndrop_sections .top_section { background-image: url(images/dnd-label-top.png) } .ow_dragndrop_sections .left_section { background-image: url(images/dnd-label-column1.png) } .ow_dragndrop_sections .right_section { background-image: url(images/dnd-label-column2.png) } .ow_dragndrop_sections .bottom_section { background-image: url(images/dnd-label-bottom.png) } .ow_dragndrop_sections .sidebar_section { background-image: url(images/dnd-label-sidebar.png) } body .ow_dragndrop_panel .ow_dnd_schem_item{ width: 134px; } .ow_dragndrop_sections .ow_highbox{ margin-top: 6px; } .ow_highbox_table .ow_highbox, .ow_highbox { background-color: #F5F9FA; } .ow_highbox { border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; padding: 4px; } .ow_dragndrop_sections .ow_highbox { padding: 0; } .ow_dragndrop_sections .ow_highbox.join_now_widget { padding: 10px; } .join_now_widget { background-image: url('images/ic_warning.png'); padding: 10px; background-position: 10px 10px; background-repeat: no-repeat; } .ow_highbox .ow_highbox.join_now_widget { background-image: none; border: none; } .ow_highbox, .ow_highbox_table .ow_highbox { border:1px solid #31363A; border-top: none; border-left: none; } .ow_highbox_table .ow_highbox { height:50px; padding:10px; } .ow_highbox_table .ow_highbox .ow_dnd_schem_item{ float:none; margin-bottom:4px; margin-right:0; width:auto; } input[type=text].ow_settings_input{ width: 40px; } /* color picker */ .special_block_top { width: 252px; height: 7px; } .special_block_mid { width: 238px; padding: 0 7px 5px; margin: 0 auto; } .special_block_bot { width: 252px; height: 19px; } .colorCode { width: 68px; } table.colorPicker { border-collapse: separate !important; border-spacing: 3px !important; } table.colorPicker td { width: 20px; height: 20px; padding: 0; } /* FloatBox implementation */ #floatbox_overlay { position: fixed; z-index: 100; top: 0px; left: 0px; height: 100%; width: 100%; } .floatbox_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} .floatbox_overlayBG { background-color: #000; filter: alpha(opacity=75); -moz-opacity: 0.75; opacity: 0.75; } *html #floatbox_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #floatbox_HideSelect { z-index: 99; position: fixed; top: 0; left: 0; background-color: #fff; border: none; filter: alpha(opacity=0); -moz-opacity: 0; opacity: 0; height: 100%; width: 100%; } *html #floatbox_HideSelect { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } body .floatbox_canvas .floatbox_container { margin-top: 100px; } .floatbox_container { position: fixed; z-index: 102; width: 300px; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 0 8px 12px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 8px 12px rgba(0, 0, 0, 0.2); box-shadow: 0 8px 12px rgba(0, 0, 0, 0.2); border: 8px solid rgba(0, 0, 0, 0.22); } .floatbox_header { padding: 4px; text-align: left; } .floatbox_header a.close_btn { margin: 2px; background: url(images/ow-ic-close.png) no-repeat; } .floatbox_title { text-transform: uppercase; font-size: 16px; padding: 8px 12px 0px; float: left; font-weight: normal; font-family: 'UbuntuBold', "Trebuchet MS", "Helvetica CY", sans-serif; } .floatbox_header .ow_box_cap_icons { float: right; margin-top: 1px; } .floatbox_body { padding: 8px 16px; text-align: left; } .floatbox_bottom { padding: 0px 16px 16px; text-align: center; } .floatbox_container .ow_bg_color { -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px; } /* End FloatBox implementation */ /* ---- Message (Feedback) styles ---- */ .ow_message_cont{ left: 50%; margin-left: -278px; position: fixed; top:0; width: 556px; z-index: 1000; margin-top: 25px; } .ow_message_node{ font-size:14px; font-weight:bold; font-family: Arial, Helvetica, sans-serif; color: #fff; text-align:center; text-shadow: 0 1px 0 rgba(0,0,0,0.4); line-height: 24px; margin:15px; padding:7px 12px; overflow: auto; position:relative; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 21px 16px rgba(0,0,0,0.2); -moz-box-shadow: 0 21px 16px rgba(0,0,0,0.2); box-shadow:0 21px 16px rgba(0,0,0,0.2); } .ow_message_node div div{ padding-right:24px; } .ow_message_node a.close_button { display:block; width:12px; height:13px; float:right; position:absolute; top:14px; right:14px; background:url(images/message_btn_close.png) no-repeat 50% 50%; } /*info*/ .ow_message_cont .ow_message_node.info { background: #90c105; border-top:1px solid #90c105; border-right:1px solid #90c105; border-bottom:1px solid #519200; border-left:1px solid #90c105; } /*warning*/ .ow_message_cont .ow_message_node.warning { background: #ffbf22; border-top:1px solid #ffbf22; border-right:1px solid #ffbf22; border-bottom:1px solid #ff8f05; border-left:1px solid #ffbf22; } /*error*/ .ow_message_cont .ow_message_node.error { background: #ea400b; border-top:1px solid #ea400b; border-right:1px solid #ea400b; border-bottom:1px solid #d71000; border-left:1px solid #ea400b; } /* ---- End of the Message (Feedback) styles ---- */ /* thickbox 8aa */ .ow_preloader_content_cont{ width: 30px; height: 30px; } /* ~thickbox 8aa */ /* ---- Captcha styles ---- */ span.ic_refresh{ background: url(images/ic_refresh.png) no-repeat; display: inline-block; height: 16px; width: 16px; } /* ---- End of Captcha styles ---- */ .alignleft{ float: left; } .alignright{ float: right; } .aligncenter{ display: block; margin-left: auto; margin-right: auto; } /*----------------------------------------------------------------------BASE_ADD--------------------------------------------------------------------------------*/ .index_customize_box { /*width: 985px;*/ } .fullsize-photo{display: none;} .ow_ajax_floatbox_preloader { width: 100%; height: 50px; } .ow_border { border-style: solid; border-color: #f8fbfb; } .ow_cursor_pointer { cursor: pointer; } .ow_break_word{ word-wrap:break-word; } /* ---- Sort styles ---- */ .ow_sort_control { padding: 4px; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; border: 1px solid #e8e8e8; } .ow_sort_control a { background: url("images/box_menu.gif") repeat-x scroll left top transparent; display: inline-block; color: #91959B; font-size:11px; height: 22px; padding: 0px 6px 0 7px; text-shadow: #fff 0 1px 0; border-style: solid; border-color: #dcdcdc; border-width: 1px 1px 1px 1px; margin: 0px 0px 0px -1px; outline: 0 none; border-left-width: 1px; border-top-left-radius: 2px; -moz-border-top-left-radius: 2px; -webkit-border-top-left-radius: 2px; border-bottom-left-radius: 2px; -moz-border-bottom-left-radius: 2px; -webkit-border-bottom-left-radius: 2px; } .ow_sort_control a span { display: inline-block; line-height: 21px; } .ow_sort_control a:first-child { border-left-width: 1px; border-top-left-radius: 2px; -moz-border-top-left-radius: 2px; -webkit-border-top-left-radius: 2px; border-bottom-left-radius: 2px; -moz-border-bottom-left-radius: 2px; -webkit-border-bottom-left-radius: 2px; } .ow_sort_control a:last-child { border-top-right-radius: 2px; -moz-border-top-right-radius: 2px; -webkit-border-top-right-radius: 2px; border-bottom-right-radius: 2px; -moz-border-bottom-right-radius: 2px; -webkit-border-bottom-right-radius: 2px; } .ow_sort_control a.active, .ow_sort_control a:hover{ color:#DDFFFF; text-shadow: 1px 1px 0 #0075D6; text-decoration:none; background: transparent url('images/box_menu_active.gif') repeat-x left top; border-color: #ccc; border-bottom-left-radius: 2px; border-left-width: 1px; border-top-left-radius: 2px; border-style: solid; border-width: 1px; } .ow_sort_control_label { padding: 0px 8px 0px 6px; } /*td.sort_link{ width:100%; } td.sort_link li{ display:inline; padding: 0 15px 0 0; } td.sort_link li.active a { font-weight:bold; color:#333; } td.sort_link li.active a:hover{ text-decoration:none; }*/ /* ---- End of Sort styles ---- */ /* ---- Context Action styles ---- */ .ow_context_action_block { float: right; text-align: right; font-size: 0px; line-height: 17px; } .ow_context_action { display: inline-block; position: relative; z-index: 3; font-size: 11px; height: 18px; padding: 0px 0px 0px 5px; border-top: 1px solid #50b6dd; border-bottom: 1px solid #50b6dd; border-right: 1px solid #50b6dd; vertical-align: top; *display: inline; zoom: 1; background-image: url(images/context_action.gif); background-position: 0px 0px; background-repeat: repeat-x; } .ow_context_action_value_block.ow_context_action_block.ow_profile_toolbar_group .ow_context_action { background-image: url(images/box_menu.gif); border: 1px solid #ccc; } .ow_context_action_value_block.ow_context_action_block.ow_profile_toolbar_group .ow_context_action:hover, .ow_context_action_value_block.ow_context_action_block.ow_profile_toolbar_group .ow_context_action:active { border-color: #bababa; } body .ow_fw_menu .ow_context_action_value_block .ow_context_action:hover, body .ow_fw_menu .ow_context_action_value_block .ow_context_action:active { background-image: url(images/box_menu.giff); border-color: #bababa; } body .ow_fw_menu .ow_context_action_value_block .ow_context_action .ow_context_more, body .ow_fw_menu .ow_context_action_value_block .ow_context_action .ow_context_more:hover { background-image: url(images/chat_tiny_arrow_down.png); background-position: 1px 7px; } .ow_context_action_value { display: inline-block; padding: 0px 5px 0px 0px; text-decoration: none; color: #666; /*color: #3366CC; font-weight: bold; text-shadow: 1px 1px 0 #F6F6F6;*/ } .ow_context_more { display: inline-block; min-width: 10px; height: 18px; padding: 0px 5px 0px 0px; background: url(images/context_action_arrow.png) no-repeat 1px 8px; vertical-align: top; } .ow_context_action_block .ow_context_action:first-child { border-left: 1px solid #50b6dd; border-radius: 2px 0px 0px 2px; } .ow_context_action_block .ow_context_action:last-child { border-top-right-radius:2px; border-bottom-right-radius: 2px; } .ow_context_action:hover, .ow_context_action.active { cursor: pointer; background: url('images/context_action_hover.gif') repeat-x 0px 0px; } .ow_context_action:hover .ow_context_action_wrap { display: block; } .ow_context_action:hover .ow_context_action_value, .ow_context_action.active .ow_context_action_value { text-decoration: none; } .ow_context_action:hover .ow_context_more, .ow_context_action.active .ow_context_more { background: url(images/context_action_arrow_active.png) no-repeat 1px 8px; } .ow_context_action_wrap { /*position: absolute; right: -1px; top: 23px; padding-top: 1px; max-width: 250px; display: none;*/ } .ow_context_action_list { min-width: 100px; text-align: left; overflow-x: auto; } .ow_context_action_list li { white-space: nowrap; } .ow_context_action_list a { font-size: 11px; font-weight: normal; display: block; padding: 3px 0px; color: #5a5a5a; } .ow_context_action_list a:hover { text-decoration: none; background: #57c0e7; color: #e5ffff; text-shadow: 0 1px 0 #007a9e; } .ow_context_action .ow_tooltip { display: none; } .ow_context_action_divider { line-height: 1px; height: 1px; background: #dcdcdc; border-bottom: 1px solid #fff; margin: 1px 0px 0px; } /* ---- End of Context Action styles ---- */ /* ---- Cover Context Action styles ---- */ .uh-cover-add-btn-wrap .ow_context_action { padding-left: 7px; } .uh-cover-add-btn-wrap .ow_tooltip_body { padding: 4px 0px; } .uh-cover-add-btn-wrap .ow_context_action_list a { padding: 4px 12px; } .uh-cover-add-btn-wrap .ow_context_action_value { color: #e5ffff; } /* ---- End of Cover Context Action styles ---- */ /* ---- SignIn Form styles ---- */ .ow_sign_in_cont { width:100%; height:100%; position:absolute; top:0; left:0; background:#fff; z-index:97; } .ow_sign_in_wrap { width:702px; } .ow_sign_in_wrap h2 { font-size: 28px; line-height: 36px; margin:0 8px 10px 8px; padding:0 40px; color: #000; } .ow_sign_in_wrap form{ margin:8px; padding:40px 40px 22px 40px; background:#F1F1F1; -moz-border-radius:5px; -webkit-border-radius: 5px; -khtml-border-radius:5px; border-radius:5px; -webkit-box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); box-shadow:0 2px 6px rgba(0, 0, 0, 0.2); border:1px solid #e7e7e7; } .ow_sign_in_wrap form .ow_sign_in{float:left; width:312px;} .ow_sign_in_wrap form .ow_sign_up {margin:0px 0 0 342px; color: #585858; padding-top: 7px;} .ow_sign_in_wrap form .ow_sign_up hr{margin:5px 0 15px;} .ow_sign_in_wrap form .ow_box_cap{ margin-bottom:0; position:relative; z-index:99; } .ow_sign_in_wrap form .ow_box{ padding:16px 16px 6px 16px; margin-bottom:16px; position:relative; z-index:98; } .ow_sign_in_wrap form .ow_user_name input[type="text"]{margin-bottom:8px;} .ow_sign_in_wrap form .ow_password input[type="password"] {margin-bottom:16px;} .ow_sign_in_wrap form .ow_form_options {margin-bottom:6px;} .ow_sign_in_wrap form .ow_form_options p.ow_remember_me, .ow_sign_in_wrap form .ow_form_options p.ow_forgot_pass {font-size:11px; padding:0 0 0 20px; line-height: 13px;} .ow_sign_in_wrap form .ow_form_options p.ow_remember_me {padding-bottom:5px;} .ow_sign_in_wrap form .ow_form_options p.ow_remember_me input[type="checkbox"]{float:left; margin:0px 0 0 -20px; padding:0px;} .ow_sign_in_wrap form .ow_connect_buttons {padding: 0 0 0 20px;} .ow_sign_in_wrap form .ow_connect_buttons .ow_fb_button {float:left;} .ow_connect_text { background: url('images/miniic_li.png') no-repeat left center; padding: 0px 0 0 16px; margin-right: 16px; float: left; line-height: 22px; } .ow_sign_in .connect_button_list { padding: 0px; float: left; } .floatbox_container .ow_sign_in_wrap form { margin: 0px; box-shadow: none; border: none; border-radius: none; -moz-border-radius: 0px; -webkit-border-radius: 0px; padding: 10px 40px 0; } .floatbox_container .ow_sign_in_wrap h2 { display: none; } .ow_signin_label { display: inline-block; height: 14px; line-height: 13px; margin: 4px 0; vertical-align: top; } .ow_signin_delimiter { border-right: 1px solid #CCCCCC; padding: 0 7px 0 0; } .ow_console_item .ow_ico_signin { background-color: transparent; background-position: 0 0; background-repeat: no-repeat; display: inline-block; height: 14px; margin: 4px 0 0 4px; vertical-align: top; width: 14px; } .ow_ico_signin:last-child { margin-right: -4px; } /* ---- End SignIn Form styles ---- */ /* ---- My Avatar Widget styles ---- */ .ow_my_avatar_img { } .ow_my_avatar_username { display: table-cell; vertical-align: middle; } .ow_my_avatar_cont { height: 47px; display: table; padding-left: 5px; } .ow_my_avatar_cont span { display: inline-block; width: 90px; word-wrap: break-word; } /* ---- End of My Avatar Widget styles ---- */ /* ---- Live Member Icon ---- */ .ow_miniic_live .ow_live_on { width: 16px; height: 16px; display: inline-block; vertical-align: middle; background: url(images/miniic_live.png) center center no-repeat; margin-right: 4px; } .ow_miniic_live .ow_lbutton { display: inline-block; vertical-align: middle; margin-right: 4px; line-height: 12px; height: 12px; } .ow_miniic_live .ow_preloader_content{ height: 16px; width: 16px; display: inline-block; vertical-align: middle; background-position:center center; } .ow_miniic_live .ow_preloader_content.ow_hidden { display: none; } .ow_miniic_live .ow_lbutton.ow_green { color: #666; } /* ---- End Live Member Icon ---- */ .ow_field_eye { padding-left: 14px; background:url(images/miniic_field_eye.png) 0 7px no-repeat; display: inline-block; } /* ---- Gheader styles---- */ .gh-header .uh-head .uh-toolbox { padding-top: 11px; } /* ---- End of the Gheader ---- */ .base_index_page, .ow_dragndrop_content { float: left; width: 100%; }
locthdev/shopthoitrang-oxwall
ow_themes/crayon/base.css
CSS
gpl-2.0
126,772
/* * Copyright (C) 2008, 2009, 2013 Apple Inc. All rights reserved. * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca> * Copyright (C) Research In Motion Limited 2010, 2011. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef JITStubsX86_64_h #define JITStubsX86_64_h #include "JITStubsX86Common.h" #if !CPU(X86_64) #error "JITStubsX86_64.h should only be #included if CPU(X86_64)" #endif #if !USE(JSVALUE64) #error "JITStubsX86_64.h only implements USE(JSVALUE64)" #endif namespace JSC { #if COMPILER(GCC) #if USE(MASM_PROBE) asm ( ".globl " SYMBOL_STRING(ctiMasmProbeTrampoline) "\n" HIDE_SYMBOL(ctiMasmProbeTrampoline) "\n" SYMBOL_STRING(ctiMasmProbeTrampoline) ":" "\n" "pushfq" "\n" // MacroAssembler::probe() has already generated code to store some values. // Together with the rflags pushed above, the top of stack now looks like // this: // esp[0 * ptrSize]: rflags // esp[1 * ptrSize]: return address / saved rip // esp[2 * ptrSize]: probeFunction // esp[3 * ptrSize]: arg1 // esp[4 * ptrSize]: arg2 // esp[5 * ptrSize]: saved rax // esp[6 * ptrSize]: saved rsp "movq %rsp, %rax" "\n" "subq $" STRINGIZE_VALUE_OF(PROBE_SIZE) ", %rsp" "\n" // The X86_64 ABI specifies that the worse case stack alignment requirement // is 32 bytes. "andq $~0x1f, %rsp" "\n" "movq %rbp, " STRINGIZE_VALUE_OF(PROBE_CPU_EBP_OFFSET) "(%rsp)" "\n" "movq %rsp, %rbp" "\n" // Save the ProbeContext*. "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_ECX_OFFSET) "(%rbp)" "\n" "movq %rdx, " STRINGIZE_VALUE_OF(PROBE_CPU_EDX_OFFSET) "(%rbp)" "\n" "movq %rbx, " STRINGIZE_VALUE_OF(PROBE_CPU_EBX_OFFSET) "(%rbp)" "\n" "movq %rsi, " STRINGIZE_VALUE_OF(PROBE_CPU_ESI_OFFSET) "(%rbp)" "\n" "movq %rdi, " STRINGIZE_VALUE_OF(PROBE_CPU_EDI_OFFSET) "(%rbp)" "\n" "movq 0 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EFLAGS_OFFSET) "(%rbp)" "\n" "movq 1 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EIP_OFFSET) "(%rbp)" "\n" "movq 2 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_PROBE_FUNCTION_OFFSET) "(%rbp)" "\n" "movq 3 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_ARG1_OFFSET) "(%rbp)" "\n" "movq 4 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_ARG2_OFFSET) "(%rbp)" "\n" "movq 5 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EAX_OFFSET) "(%rbp)" "\n" "movq 6 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%rbp)" "\n" "movq %r8, " STRINGIZE_VALUE_OF(PROBE_CPU_R8_OFFSET) "(%rbp)" "\n" "movq %r9, " STRINGIZE_VALUE_OF(PROBE_CPU_R9_OFFSET) "(%rbp)" "\n" "movq %r10, " STRINGIZE_VALUE_OF(PROBE_CPU_R10_OFFSET) "(%rbp)" "\n" "movq %r11, " STRINGIZE_VALUE_OF(PROBE_CPU_R11_OFFSET) "(%rbp)" "\n" "movq %r12, " STRINGIZE_VALUE_OF(PROBE_CPU_R12_OFFSET) "(%rbp)" "\n" "movq %r13, " STRINGIZE_VALUE_OF(PROBE_CPU_R13_OFFSET) "(%rbp)" "\n" "movq %r14, " STRINGIZE_VALUE_OF(PROBE_CPU_R14_OFFSET) "(%rbp)" "\n" "movq %r15, " STRINGIZE_VALUE_OF(PROBE_CPU_R15_OFFSET) "(%rbp)" "\n" "movdqa %xmm0, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM0_OFFSET) "(%rbp)" "\n" "movdqa %xmm1, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM1_OFFSET) "(%rbp)" "\n" "movdqa %xmm2, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM2_OFFSET) "(%rbp)" "\n" "movdqa %xmm3, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM3_OFFSET) "(%rbp)" "\n" "movdqa %xmm4, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM4_OFFSET) "(%rbp)" "\n" "movdqa %xmm5, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM5_OFFSET) "(%rbp)" "\n" "movdqa %xmm6, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM6_OFFSET) "(%rbp)" "\n" "movdqa %xmm7, " STRINGIZE_VALUE_OF(PROBE_CPU_XMM7_OFFSET) "(%rbp)" "\n" "movq %rbp, %rdi" "\n" // the ProbeContext* arg. "call *" STRINGIZE_VALUE_OF(PROBE_PROBE_FUNCTION_OFFSET) "(%rbp)" "\n" // To enable probes to modify register state, we copy all registers // out of the ProbeContext before returning. "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EDX_OFFSET) "(%rbp), %rdx" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EBX_OFFSET) "(%rbp), %rbx" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_ESI_OFFSET) "(%rbp), %rsi" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EDI_OFFSET) "(%rbp), %rdi" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_R8_OFFSET) "(%rbp), %r8" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_R9_OFFSET) "(%rbp), %r9" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_R10_OFFSET) "(%rbp), %r10" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_R11_OFFSET) "(%rbp), %r11" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_R12_OFFSET) "(%rbp), %r12" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_R13_OFFSET) "(%rbp), %r13" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_R14_OFFSET) "(%rbp), %r14" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_R15_OFFSET) "(%rbp), %r15" "\n" "movdqa " STRINGIZE_VALUE_OF(PROBE_CPU_XMM0_OFFSET) "(%rbp), %xmm0" "\n" "movdqa " STRINGIZE_VALUE_OF(PROBE_CPU_XMM1_OFFSET) "(%rbp), %xmm1" "\n" "movdqa " STRINGIZE_VALUE_OF(PROBE_CPU_XMM2_OFFSET) "(%rbp), %xmm2" "\n" "movdqa " STRINGIZE_VALUE_OF(PROBE_CPU_XMM3_OFFSET) "(%rbp), %xmm3" "\n" "movdqa " STRINGIZE_VALUE_OF(PROBE_CPU_XMM4_OFFSET) "(%rbp), %xmm4" "\n" "movdqa " STRINGIZE_VALUE_OF(PROBE_CPU_XMM5_OFFSET) "(%rbp), %xmm5" "\n" "movdqa " STRINGIZE_VALUE_OF(PROBE_CPU_XMM6_OFFSET) "(%rbp), %xmm6" "\n" "movdqa " STRINGIZE_VALUE_OF(PROBE_CPU_XMM7_OFFSET) "(%rbp), %xmm7" "\n" // There are 6 more registers left to restore: // rax, rcx, rbp, rsp, rip, and rflags. // We need to handle these last few restores carefully because: // // 1. We need to push the return address on the stack for ret to use // That means we need to write to the stack. // 2. The user probe function may have altered the restore value of esp to // point to the vicinity of one of the restore values for the remaining // registers left to be restored. // That means, for requirement 1, we may end up writing over some of the // restore values. We can check for this, and first copy the restore // values to a "safe area" on the stack before commencing with the action // for requirement 1. // 3. For both requirement 2, we need to ensure that the "safe area" is // protected from interrupt handlers overwriting it. Hence, the esp needs // to be adjusted to include the "safe area" before we start copying the // the restore values. "movq %rbp, %rax" "\n" "addq $" STRINGIZE_VALUE_OF(PROBE_CPU_EFLAGS_OFFSET) ", %rax" "\n" "cmpq %rax, " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%rbp)" "\n" "jg " SYMBOL_STRING(ctiMasmProbeTrampolineEnd) "\n" // Locate the "safe area" at 2x sizeof(ProbeContext) below where the new // rsp will be. This time we don't have to 32-byte align it because we're // not using to store any xmm regs. "movq " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%rbp), %rax" "\n" "subq $2 * " STRINGIZE_VALUE_OF(PROBE_SIZE) ", %rax" "\n" "movq %rax, %rsp" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EAX_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EAX_OFFSET) "(%rax)" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_ECX_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_ECX_OFFSET) "(%rax)" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EBP_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EBP_OFFSET) "(%rax)" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%rax)" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EIP_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EIP_OFFSET) "(%rax)" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EFLAGS_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, " STRINGIZE_VALUE_OF(PROBE_CPU_EFLAGS_OFFSET) "(%rax)" "\n" "movq %rax, %rbp" "\n" SYMBOL_STRING(ctiMasmProbeTrampolineEnd) ":" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_ESP_OFFSET) "(%rbp), %rax" "\n" "subq $5 * " STRINGIZE_VALUE_OF(PTR_SIZE) ", %rax" "\n" // At this point, %rsp should be < %rax. "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EFLAGS_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, 0 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax)" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EAX_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, 1 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax)" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_ECX_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, 2 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax)" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EBP_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, 3 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax)" "\n" "movq " STRINGIZE_VALUE_OF(PROBE_CPU_EIP_OFFSET) "(%rbp), %rcx" "\n" "movq %rcx, 4 * " STRINGIZE_VALUE_OF(PTR_SIZE) "(%rax)" "\n" "movq %rax, %rsp" "\n" "popfq" "\n" "popq %rax" "\n" "popq %rcx" "\n" "popq %rbp" "\n" "ret" "\n" ); #endif // USE(MASM_PROBE) #endif // COMPILER(GCC) } // namespace JSC #endif // JITStubsX86_64_h
loveyoupeng/rt
modules/web/src/main/native/Source/JavaScriptCore/jit/JITStubsX86_64.h
C
gpl-2.0
10,951
/** * PreTranslationDialog.java * * Version information : * * Date:Oct 20, 2011 * * Copyright notice : * 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。 * 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动, * 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。 */ package net.heartsome.cat.ts.pretranslation.dialog; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.heartsome.cat.common.util.CommonFunction; import net.heartsome.cat.ts.core.bean.XliffBean; import net.heartsome.cat.ts.pretranslation.Activator; import net.heartsome.cat.ts.pretranslation.bean.ImageConstants; import net.heartsome.cat.ts.pretranslation.bean.PreTransParameters; import net.heartsome.cat.ts.pretranslation.resource.Messages; import net.heartsome.cat.ts.ui.composite.DialogLogoCmp; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.GridLayoutFactory; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.PlatformUI; /** * 预翻译信息显示对话框,用于展示文件列表 * @author Jason * @version * @since JDK1.6 */ public class PreTranslationDialog extends TrayDialog { private TableViewer viewer; private Map<String, List<XliffBean>> xliffInofs; private PreTransParameters parameters = null; private Image logoImage = Activator.getImageDescriptor(ImageConstants.PRE_TRANSLTATION_LOGO).createImage(); /** 忽略大小写 */ private Button btnIgnoreCase; /** 忽略标记 */ private Button btnIgnoretag; /** 最低匹配率 */ private Spinner spinner; /** 完全匹配 */ private Button btn101Match; /** 上下文匹配 */ private Button btnContextMatch; /** 保留原来译文 */ private Button btnKeepOld; /** 匹配率高于现有译文 */ private Button btnKeepBestMatch; /** 始终覆盖现有译文 */ private Button btnKeepNew; /** 不一致罚分. */ private Spinner spinnnerPanalty; private Label lblTagPenalty; private IDialogSettings dialogSettings; /** * Create the dialog. * @param parentShell * @param parameters */ public PreTranslationDialog(Shell parentShell, Map<String, List<XliffBean>> xliffInofs, PreTransParameters parameters) { super(parentShell); dialogSettings = Activator.getDefault().getDialogSettings(); this.parameters = parameters; this.xliffInofs = xliffInofs; setHelpAvailable(true); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(Messages.getString("dialog.PreTranslationDialog.title")); } /** * 添加帮助按钮 robert 2012-09-06 */ @Override protected Control createHelpControl(Composite parent) { // ROBERTHELP 预翻译 String language = CommonFunction.getSystemLanguage(); final String helpUrl = MessageFormat.format( "/net.heartsome.cat.ts.ui.help/html/{0}/ch05s03.html#pre-translation", language); Image helpImage = JFaceResources.getImage(DLG_IMG_HELP); ToolBar toolBar = new ToolBar(parent, SWT.FLAT | SWT.NO_FOCUS); ((GridLayout) parent.getLayout()).numColumns++; toolBar.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER)); final Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_HAND); toolBar.setCursor(cursor); toolBar.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { cursor.dispose(); } }); ToolItem helpItem = new ToolItem(toolBar, SWT.NONE); helpItem.setImage(helpImage); helpItem.setToolTipText(JFaceResources.getString("helpToolTip")); //$NON-NLS-1$ helpItem.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(helpUrl); } }); return toolBar; } /** * Create contents of the dialog. * @param parent */ @Override protected Control createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); GridLayoutFactory.fillDefaults().extendedMargins(-1, -1, -1, 8).numColumns(1).applyTo(container); createLogoArea(container); Composite parentCmp = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().extendedMargins(9, 9, 0, 0).numColumns(1).applyTo(parentCmp); GridDataFactory.fillDefaults().grab(true, true).applyTo(parentCmp); createPageContent(parentCmp); viewer.getTable().setFocus(); return container; } /** * Return the initial size of the dialog. */ @Override protected Point getInitialSize() { return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT); } /** * 创建页面内容 * @param parent * ; */ private void createPageContent(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout gl_composite = new GridLayout(1, false); gl_composite.marginHeight = 0; gl_composite.marginWidth = 0; gl_composite.verticalSpacing = 0; composite.setLayout(gl_composite); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); viewer = new TableViewer(composite, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); final Table table = viewer.getTable(); GridData tableGd = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); tableGd.heightHint = 220; table.setLayoutData(tableGd); table.setLinesVisible(true); table.setHeaderVisible(true); String[] clmnTitles = new String[] { Messages.getString("dialog.PreTranslationDialog.clmnTitles1"), Messages.getString("dialog.PreTranslationDialog.clmnTitles2"), Messages.getString("dialog.PreTranslationDialog.clmnTitles3"), Messages.getString("dialog.PreTranslationDialog.clmnTitles4") }; int[] clmnBounds = { 80, 250, 100, 100 }; for (int i = 0; i < clmnTitles.length; i++) { createTableViewerColumn(viewer, clmnTitles[i], clmnBounds[i], i); } viewer.setLabelProvider(new TableViewerLabelProvider()); viewer.setContentProvider(new ArrayContentProvider()); viewer.setInput(this.getTableViewerInput()); // 参数面板 Composite cmpPerTranParam = new Composite(composite, SWT.BORDER); GridDataFactory.createFrom(new GridData(GridData.FILL_BOTH)).applyTo(cmpPerTranParam); GridLayoutFactory.swtDefaults().numColumns(3).applyTo(cmpPerTranParam); // 预翻译参数 Group groupMatch = new Group(cmpPerTranParam, SWT.NONE); GridDataFactory.createFrom(new GridData(GridData.FILL_BOTH)).applyTo(groupMatch); GridLayoutFactory.swtDefaults().applyTo(groupMatch); groupMatch.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.match")); Composite cmpPercent = new Composite(groupMatch, SWT.NONE); GridDataFactory.createFrom(new GridData(GridData.FILL_BOTH)).applyTo(cmpPercent); GridLayoutFactory.fillDefaults().numColumns(3).applyTo(cmpPercent); Label lblLowest = new Label(cmpPercent, SWT.NONE); lblLowest.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.lowestmatch")); spinner = new Spinner(cmpPercent, SWT.BORDER); spinner.setMinimum(1); spinner.setIncrement(5); spinner.setSelection(70); Label lblPercentage = new Label(cmpPercent, SWT.NONE); lblPercentage.setText("%"); btnIgnoreCase = new Button(groupMatch, SWT.CHECK); btnIgnoreCase.setSelection(true); btnIgnoreCase.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.ignorecase")); GridDataFactory.swtDefaults().align(SWT.LEFT, SWT.CENTER).span(2, 1).applyTo(btnIgnoreCase); btnIgnoretag = new Button(groupMatch, SWT.CHECK); GridDataFactory.swtDefaults().align(SWT.LEFT, SWT.CENTER).span(2, 1).applyTo(btnIgnoretag); btnIgnoretag.setSelection(true); btnIgnoretag.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.ignoretag")); btnIgnoretag.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { setPanalty(!btnIgnoretag.getSelection()); } }); Composite cmpPenalty = new Composite(groupMatch, SWT.NONE); cmpPenalty.setLayoutData(new GridData(GridData.FILL_BOTH)); GridLayoutFactory.fillDefaults().margins(15, 0).numColumns(2).applyTo(cmpPenalty); lblTagPenalty = new Label(cmpPenalty, SWT.NONE); lblTagPenalty.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.tagPenalty")); spinnnerPanalty = new Spinner(cmpPenalty, SWT.BORDER); spinnnerPanalty.setSelection(2); setPanalty(false); // 锁定参数 String lockGrpText = Messages.getString("dialog.PreTranslationDialog.pertrans.lock"); Group groupLockWhenPerTrans = new Group(cmpPerTranParam, SWT.MULTI | SWT.WRAP); GridDataFactory.createFrom(new GridData(GridData.FILL_BOTH)).applyTo(groupLockWhenPerTrans); GridLayoutFactory.swtDefaults().numColumns(1).applyTo(groupLockWhenPerTrans); groupLockWhenPerTrans.setText(lockGrpText); btn101Match = new Button(groupLockWhenPerTrans, SWT.CHECK); btn101Match.setSelection(true); btn101Match.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.fullMatch")); btnContextMatch = new Button(groupLockWhenPerTrans, SWT.CHECK); btnContextMatch.setSelection(true); btnContextMatch.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.contextMatch")); Label lbl = new Label(groupLockWhenPerTrans, SWT.NONE); lbl.setText(lockGrpText); lbl.setVisible(false); // 覆盖策略 Group groupHandleOldTarget = new Group(cmpPerTranParam, SWT.NONE); GridDataFactory.createFrom(new GridData(GridData.FILL_BOTH)).applyTo(groupHandleOldTarget); GridLayoutFactory.swtDefaults().numColumns(1).applyTo(groupHandleOldTarget); groupHandleOldTarget.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.handleTargetText")); btnKeepOld = new Button(groupHandleOldTarget, SWT.RADIO); btnKeepOld.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.keepOld")); btnKeepBestMatch = new Button(groupHandleOldTarget, SWT.RADIO); btnKeepBestMatch.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.keepBestMatch")); btnKeepNew = new Button(groupHandleOldTarget, SWT.RADIO); btnKeepNew.setText(Messages.getString("dialog.PreTranslationDialog.pertrans.keepNew")); setDefaultValues(); } /** * 重设上次的状态; */ private void setDefaultValues() { if (dialogSettings.getBoolean("hasSetting")) { String tmp = null; tmp = dialogSettings.get("spinner"); spinner.setSelection(tmp == null ? 70 : Integer.valueOf(tmp)); btnIgnoreCase.setSelection(dialogSettings.getBoolean("btnIgnoreCase")); btnIgnoretag.setSelection(dialogSettings.getBoolean("btnIgnoretag")); setPanalty(!btnIgnoretag.getSelection()); tmp = dialogSettings.get("spinnnerPanalty"); spinnnerPanalty.setSelection(tmp == null ? 2 : Integer.valueOf(tmp)); btn101Match.setSelection(dialogSettings.getBoolean("btn101Match")); btnContextMatch.setSelection(dialogSettings.getBoolean("btnContextMatch")); tmp = dialogSettings.get("updateStrategy"); switch (tmp == null ? -11 : Integer.valueOf(tmp)) { case PreTransParameters.KEEP_BEST_MATCH_TARGET: btnKeepBestMatch.setSelection(true); break; case PreTransParameters.KEEP_NEW_TARGET: btnKeepNew.setSelection(true); break; case PreTransParameters.KEEP_OLD_TARGET: btnKeepOld.setSelection(true); break; default: btnKeepBestMatch.setSelection(true); break; } } else { btnIgnoreCase.setSelection(true); btnIgnoretag.setSelection(true); btn101Match.setSelection(true); btnContextMatch.setSelection(true); btnKeepBestMatch.setSelection(true); spinner.setSelection(70); spinnnerPanalty.setSelection(2); } } /** * 从当前的数据库获取需要显示到界面上的数据 * @return ; */ private String[][] getTableViewerInput() { String wPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString(); Iterator<Entry<String, List<XliffBean>>> it = xliffInofs.entrySet().iterator(); List<String[]> rows = new ArrayList<String[]>(); int index = 1; while (it.hasNext()) { Entry<String, List<XliffBean>> entry = it.next(); String filePath = entry.getKey(); String iFilePath = filePath.replace(wPath, ""); // 获取到项目为根的路径 List<XliffBean> xliffBeans = entry.getValue(); // for (int i = 0; i < xliffBeans.size(); i++) { XliffBean xliffBean = xliffBeans.get(0); String srcLang = xliffBean.getSourceLanguage(); String tagLang = xliffBean.getTargetLanguage(); String[] rowValue = new String[] { (index++) + "", iFilePath, srcLang, tagLang }; rows.add(rowValue); // } } return rows.toArray(new String[][] {}); } /** * tableViewer的标签提供器 * @author Jason */ class TableViewerLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { if (element instanceof String[]) { String[] array = (String[]) element; return array[columnIndex]; } return null; } } /** * 显示图片区 * @param parent */ public void createLogoArea(Composite parent) { new DialogLogoCmp(parent, SWT.NONE, Messages.getString("dialog.PreTranslationDialog.logoTitle"), Messages.getString("dialog.PreTranslationDialog.desc"), logoImage); } /** * 设置TableViewer 列属性 * @param viewer * @param title * 列标题 * @param bound * 列宽 * @param colNumber * 列序号 * @return {@link TableViewerColumn}; */ private TableViewerColumn createTableViewerColumn(TableViewer viewer, String title, int bound, final int colNumber) { final TableViewerColumn viewerColumn = new TableViewerColumn(viewer, SWT.NONE | SWT.Resize); final TableColumn column = viewerColumn.getColumn(); column.setText(title); column.setWidth(bound); column.setResizable(true); column.setMoveable(true); return viewerColumn; } @Override protected void okPressed() { // 填充预翻译换参数策 parameters.setIgnoreCase(btnIgnoreCase.getSelection()); parameters.setIgnoreTag(btnIgnoretag.getSelection()); if (spinner.getText().isEmpty()) { parameters.setLowestMatchPercent(0); } else { parameters.setLowestMatchPercent(Integer.valueOf(spinner.getText())); } if (spinnnerPanalty.getText().isEmpty()) { parameters.setPanalty(0); } else { parameters.setPanalty(Integer.valueOf(spinnnerPanalty.getText())); } parameters.setLockFullMatch(btn101Match.getSelection()); parameters.setLockContextMatch(btnContextMatch.getSelection()); if (btnKeepOld.getSelection()) { parameters.setUpdateStrategy(PreTransParameters.KEEP_OLD_TARGET); } else if (btnKeepBestMatch.getSelection()) { parameters.setUpdateStrategy(PreTransParameters.KEEP_BEST_MATCH_TARGET); } else if (btnKeepNew.getSelection()) { parameters.setUpdateStrategy(PreTransParameters.KEEP_NEW_TARGET); } dialogSettings.put("hasSetting", true); dialogSettings.put("btn101Match", parameters.isLockFullMatch()); dialogSettings.put("btnContextMatch", parameters.isLockContextMatch()); dialogSettings.put("btnIgnoreCase", parameters.getIgnoreCase()); dialogSettings.put("btnIgnoretag", parameters.getIgnoreTag()); dialogSettings.put("spinner", parameters.getLowestMatchPercent()); dialogSettings.put("spinnnerPanalty", parameters.getPanalty()); dialogSettings.put("updateStrategy", parameters.getUpdateStrategy()); setReturnCode(OK); close(); } @Override public boolean close() { if (logoImage != null && !logoImage.isDisposed()) { logoImage.dispose(); } return super.close(); } private void setPanalty(boolean enabled) { lblTagPenalty.setEnabled(enabled); spinnnerPanalty.setEnabled(enabled); } }
heartsome/translationstudio8
ts/net.heartsome.cat.ts.pretranslation/src/net/heartsome/cat/ts/pretranslation/dialog/PreTranslationDialog.java
Java
gpl-2.0
17,397
<?php /************************************************************************************* * c_mac.php * --------- * Author: M. Uli Kusterer (witness.of.teachtext@gmx.net) * Copyright: (c) 2004 M. Uli Kusterer, Nigel McNie (http://qbnz.com/highlighter/) * Release Version: 1.0.8.11 * Date Started: 2004/06/04 * * C for Macs language file for GeSHi. * * CHANGES * ------- * 2008/05/23 (1.0.7.22) * - Added description of extra language features (SF#1970248) * 2004/11/27 * - First Release * * TODO (updated 2004/11/27) * ------------------------- * ************************************************************************************* * * This file is part of GeSHi. * * GeSHi 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. * * GeSHi 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 GeSHi; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ************************************************************************************/ $language_data = array( 'LANG_NAME' => 'C (Mac)', 'COMMENT_SINGLE' => array(1 => '//', 2 => '#'), 'COMMENT_MULTI' => array('/*' => '*/'), 'COMMENT_REGEXP' => array( //Multiline-continued single-line comments 1 => '/\/\/(?:\\\\\\\\|\\\\\\n|.)*$/m', //Multiline-continued preprocessor define 2 => '/#(?:\\\\\\\\|\\\\\\n|.)*$/m' ), 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'QUOTEMARKS' => array("'", '"'), 'ESCAPE_CHAR' => '', 'ESCAPE_REGEXP' => array( //Simple Single Char Escapes 1 => "#\\\\[\\\\abfnrtv\'\"?\n]#i", //Hexadecimal Char Specs 2 => "#\\\\x[\da-fA-F]{2}#", //Hexadecimal Char Specs 3 => "#\\\\u[\da-fA-F]{4}#", //Hexadecimal Char Specs 4 => "#\\\\U[\da-fA-F]{8}#", //Octal Char Specs 5 => "#\\\\[0-7]{1,3}#" ), 'NUMBERS' => GESHI_NUMBER_INT_BASIC | GESHI_NUMBER_INT_CSTYLE | GESHI_NUMBER_BIN_PREFIX_0B | GESHI_NUMBER_OCT_PREFIX | GESHI_NUMBER_HEX_PREFIX | GESHI_NUMBER_FLT_NONSCI | GESHI_NUMBER_FLT_NONSCI_F | GESHI_NUMBER_FLT_SCI_SHORT | GESHI_NUMBER_FLT_SCI_ZERO, 'KEYWORDS' => array( 1 => array( 'if', 'return', 'while', 'case', 'continue', 'default', 'do', 'else', 'for', 'switch', 'goto' ), 2 => array( 'NULL', 'false', 'break', 'true', 'enum', 'errno', 'EDOM', 'ERANGE', 'FLT_RADIX', 'FLT_ROUNDS', 'FLT_DIG', 'DBL_DIG', 'LDBL_DIG', 'FLT_EPSILON', 'DBL_EPSILON', 'LDBL_EPSILON', 'FLT_MANT_DIG', 'DBL_MANT_DIG', 'LDBL_MANT_DIG', 'FLT_MAX', 'DBL_MAX', 'LDBL_MAX', 'FLT_MAX_EXP', 'DBL_MAX_EXP', 'LDBL_MAX_EXP', 'FLT_MIN', 'DBL_MIN', 'LDBL_MIN', 'FLT_MIN_EXP', 'DBL_MIN_EXP', 'LDBL_MIN_EXP', 'CHAR_BIT', 'CHAR_MAX', 'CHAR_MIN', 'SCHAR_MAX', 'SCHAR_MIN', 'UCHAR_MAX', 'SHRT_MAX', 'SHRT_MIN', 'USHRT_MAX', 'INT_MAX', 'INT_MIN', 'UINT_MAX', 'LONG_MAX', 'LONG_MIN', 'ULONG_MAX', 'HUGE_VAL', 'SIGABRT', 'SIGFPE', 'SIGILL', 'SIGINT', 'SIGSEGV', 'SIGTERM', 'SIG_DFL', 'SIG_ERR', 'SIG_IGN', 'BUFSIZ', 'EOF', 'FILENAME_MAX', 'FOPEN_MAX', 'L_tmpnam', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'stdin', 'stdout', 'stderr', 'EXIT_FAILURE', 'EXIT_SUCCESS', 'RAND_MAX', 'CLOCKS_PER_SEC', // Mac-specific constants: 'kCFAllocatorDefault' ), 3 => array( 'printf', 'fprintf', 'snprintf', 'sprintf', 'assert', 'isalnum', 'isalpha', 'isdigit', 'iscntrl', 'isgraph', 'islower', 'isprint', 'ispunct', 'isspace', 'isupper', 'isxdigit', 'tolower', 'toupper', 'exp', 'log', 'log10', 'pow', 'sqrt', 'ceil', 'floor', 'fabs', 'ldexp', 'frexp', 'modf', 'fmod', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2', 'sinh', 'cosh', 'tanh', 'setjmp', 'longjmp', 'va_start', 'va_arg', 'va_end', 'offsetof', 'sizeof', 'fopen', 'freopen', 'fflush', 'fclose', 'remove', 'rename', 'tmpfile', 'tmpname', 'setvbuf', 'setbuf', 'vfprintf', 'vprintf', 'vsprintf', 'fscanf', 'scanf', 'sscanf', 'fgetc', 'fgets', 'fputc', 'fputs', 'getc', 'getchar', 'gets', 'putc', 'putchar', 'puts', 'ungetc', 'fread', 'fwrite', 'fseek', 'ftell', 'rewind', 'fgetpos', 'fsetpos', 'clearerr', 'feof', 'ferror', 'perror', 'abs', 'labs', 'div', 'ldiv', 'atof', 'atoi', 'atol', 'strtod', 'strtol', 'strtoul', 'calloc', 'malloc', 'realloc', 'free', 'abort', 'exit', 'atexit', 'system', 'getenv', 'bsearch', 'qsort', 'rand', 'srand', 'strcpy', 'strncpy', 'strcat', 'strncat', 'strcmp', 'strncmp', 'strcoll', 'strchr', 'strrchr', 'strspn', 'strcspn', 'strpbrk', 'strstr', 'strlen', 'strerror', 'strtok', 'strxfrm', 'memcpy', 'memmove', 'memcmp', 'memchr', 'memset', 'clock', 'time', 'difftime', 'mktime', 'asctime', 'ctime', 'gmtime', 'localtime', 'strftime' ), 4 => array( 'auto', 'char', 'const', 'double', 'float', 'int', 'long', 'register', 'short', 'signed', 'static', 'struct', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'extern', 'jmp_buf', 'signal', 'raise', 'va_list', 'ptrdiff_t', 'size_t', 'FILE', 'fpos_t', 'div_t', 'ldiv_t', 'clock_t', 'time_t', 'tm', 'wchar_t', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'int_fast8_t', 'int_fast16_t', 'int_fast32_t', 'int_fast64_t', 'uint_fast8_t', 'uint_fast16_t', 'uint_fast32_t', 'uint_fast64_t', 'int_least8_t', 'int_least16_t', 'int_least32_t', 'int_least64_t', 'uint_least8_t', 'uint_least16_t', 'uint_least32_t', 'uint_least64_t', 'int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', 'intmax_t', 'uintmax_t', 'intptr_t', 'uintptr_t', // Mac-specific types: 'CFArrayRef', 'CFDictionaryRef', 'CFMutableDictionaryRef', 'CFBundleRef', 'CFSetRef', 'CFStringRef', 'CFURLRef', 'CFLocaleRef', 'CFDateFormatterRef', 'CFNumberFormatterRef', 'CFPropertyListRef', 'CFTreeRef', 'CFWriteStreamRef', 'CFCharacterSetRef', 'CFMutableStringRef', 'CFNotificationRef', 'CFReadStreamRef', 'CFNull', 'CFAllocatorRef', 'CFBagRef', 'CFBinaryHeapRef', 'CFBitVectorRef', 'CFBooleanRef', 'CFDataRef', 'CFDateRef', 'CFMachPortRef', 'CFMessagePortRef', 'CFMutableArrayRef', 'CFMutableBagRef', 'CFMutableBitVectorRef', 'CFMutableCharacterSetRef', 'CFMutableDataRef', 'CFMutableSetRef', 'CFNumberRef', 'CFPlugInRef', 'CFPlugInInstanceRef', 'CFRunLoopRef', 'CFRunLoopObserverRef', 'CFRunLoopSourceRef', 'CFRunLoopTimerRef', 'CFSocketRef', 'CFTimeZoneRef', 'CFTypeRef', 'CFUserNotificationRef', 'CFUUIDRef', 'CFXMLNodeRef', 'CFXMLParserRef', 'CFXMLTreeRef' ), ), 'SYMBOLS' => array( '(', ')', '{', '}', '[', ']', '=', '+', '-', '*', '/', '!', '%', '^', '&', ':' ), 'CASE_SENSITIVE' => array( GESHI_COMMENTS => false, 1 => true, 2 => true, 3 => true, 4 => true, ), 'STYLES' => array( 'KEYWORDS' => array( 1 => 'color: #0000ff;', 2 => 'color: #0000ff;', 3 => 'color: #0000dd;', 4 => 'color: #0000ff;' ), 'COMMENTS' => array( 1 => 'color: #ff0000;', 2 => 'color: #339900;', 'MULTI' => 'color: #ff0000; font-style: italic;' ), 'ESCAPE_CHAR' => array( 0 => 'color: #000099; font-weight: bold;', 1 => 'color: #000099; font-weight: bold;', 2 => 'color: #660099; font-weight: bold;', 3 => 'color: #660099; font-weight: bold;', 4 => 'color: #660099; font-weight: bold;', 5 => 'color: #006699; font-weight: bold;', 'HARD' => '', ), 'BRACKETS' => array( 0 => 'color: #000000;' ), 'STRINGS' => array( 0 => 'color: #666666;' ), 'NUMBERS' => array( 0 => 'color: #0000dd;', GESHI_NUMBER_BIN_PREFIX_0B => 'color: #208080;', GESHI_NUMBER_OCT_PREFIX => 'color: #208080;', GESHI_NUMBER_HEX_PREFIX => 'color: #208080;', GESHI_NUMBER_FLT_SCI_SHORT => 'color:#800080;', GESHI_NUMBER_FLT_SCI_ZERO => 'color:#800080;', GESHI_NUMBER_FLT_NONSCI_F => 'color:#800080;', GESHI_NUMBER_FLT_NONSCI => 'color:#800080;' ), 'METHODS' => array( 1 => 'color: #00eeff;', 2 => 'color: #00eeff;' ), 'SYMBOLS' => array( 0 => 'color: #000000;' ), 'REGEXPS' => array( ), 'SCRIPT' => array( ) ), 'URLS' => array( 1 => '', 2 => '', 3 => 'http://www.opengroup.org/onlinepubs/009695399/functions/{FNAMEL}.html', 4 => '' ), 'OOLANG' => true, 'OBJECT_SPLITTERS' => array( 1 => '.', 2 => '::' ), 'REGEXPS' => array( ), 'STRICT_MODE_APPLIES' => GESHI_NEVER, 'SCRIPT_DELIMITERS' => array( ), 'HIGHLIGHT_STRICT_BLOCK' => array( ), 'TAB_WIDTH' => 4 ); ?>
nitestryker/php-bin
include/geshi/c_mac.php
PHP
gpl-2.0
9,992
<?php /**************************************************************************/ /* PHP-NUKE: Advanced Content Management System */ /* ============================================ */ /* */ /* This is the language module with all the system messages */ /* */ /* If you made a translation, please go to the site and send to me */ /* the translated file. Please keep the original text order by modules, */ /* and just one message per line, also double check your translation! */ /* */ /* You need to change the second quoted phrase, not the capital one! */ /* */ /* If you need to use double quotes (") remember to add a backslash (\), */ /* so your entry will look like: This is \"double quoted\" text. */ /* And, if you use HTML code, please double check it. */ /**************************************************************************/ define("_PREVIOUS","Forrige side"); define("_NEXT","Neste side"); define("_YOURNAME","Ditt navn"); define("_SORTASC","Sorter stigende"); define("_SORTDESC","Sorter synkende"); define("_CANCEL","Avbryt"); define("_YES","Ja"); define("_NO","Nei"); define("_SCORE","Poeng:"); define("_REPLYMAIN","Skriv kommentar"); define("_ALLOWEDHTML","Tillatt HTML:"); define("_POSTANON","Skriv anonymt"); define("_WRITEREVIEW","Skriv en anmeldelse"); define("_WRITEREVIEWFOR","Skriv en anmeldelse for"); define("_ENTERINFO","Angi informasjon etter våre spesifikasjoner"); define("_PRODUCTTITLE","Produktnavn"); define("_NAMEPRODUCT","Navnet på produktet du anmelder."); define("_REVIEW","Anmeldelse"); define("_CHECKREVIEW","Den egentlige anmeldelsen. Forsøk å gjøre den grammatisk korrekt! Skriv minst 100 ord. Du må gjerne bruke HTML-kode dersom du ved hvordan!"); define("_FULLNAMEREQ","Ditt navn. Obligatorisk."); define("_REMAIL","Din e-postadresse"); define("_REMAILREQ","Din e-postadresse. Obligatorisk."); define("_SELECTSCORE","Karakter for dette produktet"); define("_RELATEDLINK","Relatert link"); define("_PRODUCTSITE","Produktets ofisielle websted. Merk: adressen må begynne med \"http://\""); define("_LINKTITLE","Titell på linken"); define("_LINKTITLEREQ","Kreves om du har en relatert link."); define("_RIMAGEFILE","Bildets filnavn"); define("_RIMAGEFILEREQ","Navnet på billedfilen til produktet. Skal ligge i mappen /images/reviews/"); define("_CHECKINFO","Vær sikker på at informasjonen du har angitt er riktig og du bruker riktig grammatikk og tegnsetting."); define("_INVALIDTITLE","Feil i tittel... Feltet kan ikke være tomt"); define("_INVALIDSCORE","Feil i karakter... Må være mellom 1 og 10"); define("_INVALIDTEXT","Feil i anmeldelsestekst... Feltet kan ikke være tomt\"); define("_INVALIDHITS","Treff må være en positiv integer"); define("_CHECKNAME","Du må oppgi både ditt navn og din e-postadresse"); define("_INVALIDEMAIL","Ugyldig e-postadresse. Må være på formen navn@adresse.no"); define("_INVALIDLINK","Du må angi BÅDE tittel på link og relatert link, eller la begge felt være tomme."); define("_ADDED","Lagt til:"); define("_REVIEWER","Anmelder"); define("_REVIEWID","Anmelder ID"); define("_HITS","Treff"); define("_LOOKSRIGHT","Ser dette riktig ut?"); define("_RMODIFIED","redigert"); define("_RADDED","lagt til"); define("_ADMINLOGGED","Du er innlogget som administrator... Denne anmeldelsen vil bli publisert umiddelbart"); define("_RTHANKS","Takk for at du skrev denne anmeldelsen"); define("_MODIFICATION","modifisering"); define("_ISAVAILABLE","Den er nå tilgjengelig i vår database."); define("_EDITORWILLLOOK","Våre redaktører vil se på den. Den bør være publisert i løpet av kort tid!"); define("_RBACK","Tilbake til anmeldelser"); define("_RWELCOME","Velkommen til anmeldelsesavdelingen"); define("_10MOSTPOP","10 mest leste anmeldelser"); define("_10MOSTREC","10 nyeste anmeldelser"); define("_THEREARE","Det finnes"); define("_REVIEWSINDB","anmeldelser i databasen"); define("_REVIEWS","Anmeldelser"); define("_REVIEWSLETTER","Anmeldelser under bokstaven"); define("_NOREVIEWS","Det finnes ingen anmeldelser under denne bokstaven"); define("_TOTALREVIEWS","Anmeldelse(r) ble funnet."); define("_RETURN2MAIN","Tilbake til hovedmeny"); define("_REVIEWCOMMENT","Kommentarer til anmeldelsen:"); define("_YOURNICK","Ditt alias:"); define("_RCREATEACCOUNT","<a href=modules.php?name=Your_Account>Bli medlem</a>"); define("_YOURCOMMENT","Din kommentar:"); define("_MYSCORE","Din karakter:"); define("_REVIEWMOD","Kontroller modifisering"); define("_RDATE","Dato:"); define("_RTITLE","Tittel:"); define("_RTEXT","Tekst:"); define("_REVEMAIL","E-postbeskjed:"); define("_RLINK","Link:"); define("_RLINKTITLE","Linktittel:"); define("_COVERIMAGE","Bilde:"); define("_PREMODS","Forhåndsvis modifisering"); define("_PAGE","Side"); define("_PAGEBREAK","Dersom du vil ha artikkelen over flere sider skriver du <b>[--pagebreak--]</b> der du vil ha sideskift."); define("_PREVIEW","Forhåndsvisning"); define("_LANGUAGE","Språk"); ?>
mpranivong/golf-phpnuke
modules/Reviews/language/lang-norwegian.php
PHP
gpl-2.0
5,289
/* * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.api.nodes; import java.io.*; import java.lang.annotation.*; import java.net.*; import java.util.*; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; import com.oracle.truffle.api.nodes.NodeUtil.NodeClass; import com.oracle.truffle.api.nodes.NodeUtil.NodeField; import com.oracle.truffle.api.nodes.NodeUtil.NodeFieldKind; /** * Utility class for creating output for the ideal graph visualizer. */ public class GraphPrintVisitor { public static final String GraphVisualizerAddress = "127.0.0.1"; public static final int GraphVisualizerPort = 4444; private Document dom; private Map<Object, Element> nodeMap; private List<Element> edgeList; private Map<Object, Element> prevNodeMap; private int id; private Element graphDocument; private Element groupElement; private Element graphElement; private Element nodesElement; private Element edgesElement; public GraphPrintVisitor() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); dom = db.newDocument(); } catch (ParserConfigurationException ex) { throw new RuntimeException(ex); } graphDocument = dom.createElement("graphDocument"); dom.appendChild(graphDocument); } public GraphPrintVisitor beginGroup(String groupName) { groupElement = dom.createElement("group"); graphDocument.appendChild(groupElement); Element properties = dom.createElement("properties"); groupElement.appendChild(properties); if (!groupName.isEmpty()) { // set group name Element propName = dom.createElement("p"); propName.setAttribute("name", "name"); propName.setTextContent(groupName); properties.appendChild(propName); } // forget old nodes nodeMap = prevNodeMap = null; edgeList = null; return this; } public GraphPrintVisitor beginGraph(String graphName) { if (null == groupElement) { beginGroup(""); } else if (null != prevNodeMap) { // TODO: difference (create removeNode,removeEdge elements) } graphElement = dom.createElement("graph"); groupElement.appendChild(graphElement); Element properties = dom.createElement("properties"); graphElement.appendChild(properties); nodesElement = dom.createElement("nodes"); graphElement.appendChild(nodesElement); edgesElement = dom.createElement("edges"); graphElement.appendChild(edgesElement); // set graph name Element propName = dom.createElement("p"); propName.setAttribute("name", "name"); propName.setTextContent(graphName); properties.appendChild(propName); // save old nodes prevNodeMap = nodeMap; nodeMap = new HashMap<>(); edgeList = new ArrayList<>(); return this; } @Override public String toString() { if (null != dom) { try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter strWriter = new StringWriter(); tr.transform(new DOMSource(dom), new StreamResult(strWriter)); return strWriter.toString(); } catch (TransformerException e) { e.printStackTrace(); } } return ""; } public void printToFile(File f) { try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(f))); } catch (TransformerException | FileNotFoundException e) { e.printStackTrace(); } } public void printToSysout() { try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); tr.transform(new DOMSource(dom), new StreamResult(System.out)); } catch (TransformerException e) { e.printStackTrace(); } } public void printToNetwork(boolean ignoreErrors) { try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.METHOD, "xml"); Socket socket = new Socket(GraphVisualizerAddress, GraphVisualizerPort); BufferedOutputStream stream = new BufferedOutputStream(socket.getOutputStream(), 0x4000); tr.transform(new DOMSource(dom), new StreamResult(stream)); } catch (TransformerException | IOException e) { if (!ignoreErrors) { e.printStackTrace(); } } } private String nextId() { return String.valueOf(id++); } private String oldOrNextId(Object node) { if (null != prevNodeMap && prevNodeMap.containsKey(node)) { Element nodeElem = prevNodeMap.get(node); return nodeElem.getAttribute("id"); } else { return nextId(); } } protected Element getElementByObject(Object op) { return nodeMap.get(op); } protected void createElementForNode(Object node) { boolean exists = nodeMap.containsKey(node); if (!exists || NodeUtil.findAnnotation(node.getClass(), GraphDuplicate.class) != null) { Element nodeElem = dom.createElement("node"); nodeElem.setAttribute("id", !exists ? oldOrNextId(node) : nextId()); nodeMap.put(node, nodeElem); Element properties = dom.createElement("properties"); nodeElem.appendChild(properties); nodesElement.appendChild(nodeElem); setNodeProperty(node, "name", node.getClass().getSimpleName().replaceFirst("Node$", "")); NodeInfo nodeInfo = node.getClass().getAnnotation(NodeInfo.class); if (nodeInfo != null) { setNodeProperty(node, "cost", nodeInfo.cost()); if (!nodeInfo.shortName().isEmpty()) { setNodeProperty(node, "shortName", nodeInfo.shortName()); } } setNodeProperty(node, "class", node.getClass().getSimpleName()); if (node instanceof Node) { readNodeProperties((Node) node); copyDebugProperties((Node) node); } } } private Element getPropertyElement(Object node, String propertyName) { Element nodeElem = getElementByObject(node); Element propertiesElem = (Element) nodeElem.getElementsByTagName("properties").item(0); if (propertiesElem == null) { return null; } NodeList propList = propertiesElem.getElementsByTagName("p"); for (int i = 0; i < propList.getLength(); i++) { Element p = (Element) propList.item(i); if (propertyName.equals(p.getAttribute("name"))) { return p; } } return null; } protected void setNodeProperty(Object node, String propertyName, Object value) { Element nodeElem = getElementByObject(node); Element propElem = getPropertyElement(node, propertyName); // if property exists, replace // its value if (null == propElem) { // if property doesn't exist, create one propElem = dom.createElement("p"); propElem.setAttribute("name", propertyName); nodeElem.getElementsByTagName("properties").item(0).appendChild(propElem); } propElem.setTextContent(String.valueOf(value)); } private void copyDebugProperties(Node node) { Map<String, Object> debugProperties = node.getDebugProperties(); for (Map.Entry<String, Object> property : debugProperties.entrySet()) { setNodeProperty(node, property.getKey(), property.getValue()); } } private void readNodeProperties(Node node) { NodeField[] fields = NodeClass.get(node.getClass()).getFields(); for (NodeField field : fields) { if (field.getKind() == NodeFieldKind.DATA) { String key = field.getName(); if (getPropertyElement(node, key) == null) { Object value = field.loadValue(node); setNodeProperty(node, key, value); } } } } protected void connectNodes(Object a, Object b, String label) { if (nodeMap.get(a) == null || nodeMap.get(b) == null) { return; } String fromId = nodeMap.get(a).getAttribute("id"); String toId = nodeMap.get(b).getAttribute("id"); // count existing to-edges int count = 0; for (Element e : edgeList) { if (e.getAttribute("to").equals(toId)) { ++count; } } Element edgeElem = dom.createElement("edge"); edgeElem.setAttribute("from", fromId); edgeElem.setAttribute("to", toId); edgeElem.setAttribute("index", String.valueOf(count)); if (label != null) { edgeElem.setAttribute("label", label); } edgesElement.appendChild(edgeElem); edgeList.add(edgeElem); } public GraphPrintVisitor visit(Object node) { if (null == graphElement) { beginGraph("truffle tree"); } // if node is visited once again, skip if (getElementByObject(node) != null && NodeUtil.findAnnotation(node.getClass(), GraphDuplicate.class) == null) { return this; } // respect node's custom handler if (NodeUtil.findAnnotation(node.getClass(), CustomGraphPrintHandler.class) != null) { Class<? extends GraphPrintHandler> customHandlerClass = NodeUtil.findAnnotation(node.getClass(), CustomGraphPrintHandler.class).handler(); try { GraphPrintHandler customHandler = customHandlerClass.newInstance(); customHandler.visit(node, new GraphPrintAdapter()); } catch (InstantiationException | IllegalAccessException e) { assert false : e; } } else if (NodeUtil.findAnnotation(node.getClass(), NullGraphPrintHandler.class) != null) { // ignore } else { // default handler createElementForNode(node); if (node instanceof Node) { for (Map.Entry<String, Node> child : findNamedNodeChildren((Node) node).entrySet()) { visit(child.getValue()); connectNodes(node, child.getValue(), child.getKey()); } } } return this; } private static LinkedHashMap<String, Node> findNamedNodeChildren(Node node) { LinkedHashMap<String, Node> nodes = new LinkedHashMap<>(); NodeClass nodeClass = NodeClass.get(node.getClass()); for (NodeField field : nodeClass.getFields()) { NodeFieldKind kind = field.getKind(); if (kind == NodeFieldKind.CHILD || kind == NodeFieldKind.CHILDREN) { Object value = field.loadValue(node); if (value != null) { if (kind == NodeFieldKind.CHILD) { nodes.put(field.getName(), (Node) value); } else if (kind == NodeFieldKind.CHILDREN) { Object[] children = (Object[]) value; for (int i = 0; i < children.length; i++) { if (children[i] != null) { nodes.put(field.getName() + "[" + i + "]", (Node) children[i]); } } } } } } return nodes; } public class GraphPrintAdapter { public void createElementForNode(Object node) { GraphPrintVisitor.this.createElementForNode(node); } public void visit(Object node) { GraphPrintVisitor.this.visit(node); } public void connectNodes(Object node, Object child) { GraphPrintVisitor.this.connectNodes(node, child, null); } public void setNodeProperty(Object node, String propertyName, Object value) { GraphPrintVisitor.this.setNodeProperty(node, propertyName, value); } } public interface GraphPrintHandler { void visit(Object node, GraphPrintAdapter gPrinter); } public interface ChildSupplier { /** Supplies an additional child if available. */ Object startNode(Object callNode); void endNode(Object callNode); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface CustomGraphPrintHandler { Class<? extends GraphPrintHandler> handler(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface NullGraphPrintHandler { } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface GraphDuplicate { } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface HiddenField { } }
smarr/graal
graal/com.oracle.truffle.api/src/com/oracle/truffle/api/nodes/GraphPrintVisitor.java
Java
gpl-2.0
15,335
/* $Id: mapgen.cpp 33770 2009-03-17 19:41:19Z jhinrichs $ */ /* Copyright (C) 2003 - 2009 by David White <dave@whitevine.net> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License 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. See the COPYING file for more details. */ /** * @file mapgen.cpp * Map-generator, with standalone testprogram. */ #include "global.hpp" #include "gettext.hpp" #include "language.hpp" #include "log.hpp" #include "map.hpp" #include "mapgen.hpp" #include "pathfind.hpp" #include "race.hpp" #include "wml_exception.hpp" #include "formula_string_utils.hpp" #define ERR_CF LOG_STREAM(err, config) #define ERR_NG LOG_STREAM(err, engine) #define LOG_NG LOG_STREAM(info, engine) config map_generator::create_scenario(const std::vector<std::string>& args) { config res; res["map_data"] = create_map(args); return res; } typedef std::vector<std::vector<int> > height_map; typedef t_translation::t_map terrain_map; typedef map_location location; /** * Generate a height-map. * * Basically we generate alot of hills, each hill being centered at a certain * point, with a certain radius - being a half sphere. Hills are combined * additively to form a bumpy surface. The size of each hill varies randomly * from 1-hill_size. We generate 'iterations' hills in total. The range of * heights is normalized to 0-1000. 'island_size' controls whether or not the * map should tend toward an island shape, and if so, how large the island * should be. Hills with centers that are more than 'island_size' away from * the center of the map will be inverted (i.e. be valleys). 'island_size' as * 0 indicates no island. */ static height_map generate_height_map(size_t width, size_t height, size_t iterations, size_t hill_size, size_t island_size, size_t island_off_center) { height_map res(width,std::vector<int>(height,0)); size_t center_x = width/2; size_t center_y = height/2; LOG_NG << "off-centering...\n"; if(island_off_center != 0) { switch(rand()%4) { case 0: center_x += island_off_center; break; case 1: center_y += island_off_center; break; case 2: if(center_x < island_off_center) center_x = 0; else center_x -= island_off_center; break; case 3: if(center_y < island_off_center) center_y = 0; else center_y -= island_off_center; break; } } for(size_t i = 0; i != iterations; ++i) { // (x1,y1) is the location of the hill, // and 'radius' is the radius of the hill. // We iterate over all points, (x2,y2). // The formula for the amount the height is increased by is: // radius - sqrt((x2-x1)^2 + (y2-y1)^2) with negative values ignored. // // Rather than iterate over every single point, we can reduce the points // to a rectangle that contains all the positive values for this formula -- // the rectangle is given by min_x,max_x,min_y,max_y. // Is this a negative hill? (i.e. a valley) bool is_valley = false; int x1 = island_size > 0 ? center_x - island_size + (rand()%(island_size*2)) : int(rand()%width); int y1 = island_size > 0 ? center_y - island_size + (rand()%(island_size*2)) : int(rand()%height); // We have to check whether this is actually a valley if(island_size != 0) { const size_t diffx = abs(x1 - int(center_x)); const size_t diffy = abs(y1 - int(center_y)); const size_t dist = size_t(std::sqrt(double(diffx*diffx + diffy*diffy))); is_valley = dist > island_size; } const int radius = rand()%hill_size + 1; const int min_x = x1 - radius > 0 ? x1 - radius : 0; const int max_x = x1 + radius < static_cast<long>(res.size()) ? x1 + radius : res.size(); const int min_y = y1 - radius > 0 ? y1 - radius : 0; const int max_y = y1 + radius < static_cast<long>(res.front().size()) ? y1 + radius : res.front().size(); for(int x2 = min_x; x2 < max_x; ++x2) { for(int y2 = min_y; y2 < max_y; ++y2) { const int xdiff = (x2-x1); const int ydiff = (y2-y1); const int height = radius - int(std::sqrt(double(xdiff*xdiff + ydiff*ydiff))); if(height > 0) { if(is_valley) { if(height > res[x2][y2]) { res[x2][y2] = 0; } else { res[x2][y2] -= height; } } else { res[x2][y2] += height; } } } } } // Find the highest and lowest points on the map for normalization: int heighest = 0, lowest = 100000, x; for(x = 0; size_t(x) != res.size(); ++x) { for(int y = 0; size_t(y) != res[x].size(); ++y) { if(res[x][y] > heighest) heighest = res[x][y]; if(res[x][y] < lowest) lowest = res[x][y]; } } // Normalize the heights to the range 0-1000: heighest -= lowest; for(x = 0; size_t(x) != res.size(); ++x) { for(int y = 0; size_t(y) != res[x].size(); ++y) { res[x][y] -= lowest; res[x][y] *= 1000; if(heighest != 0) res[x][y] /= heighest; } } return res; } /** * Generate a lake. * * It will create water at (x,y), and then have 'lake_fall_off' % chance to * make another water tile in each of the directions n,s,e,w. In each of the * directions it does make another water tile, it will have 'lake_fall_off'/2 % * chance to make another water tile in each of the directions. This will * continue recursively. */ static bool generate_lake(terrain_map& terrain, int x, int y, int lake_fall_off, std::set<location>& locs_touched) { if(x < 0 || y < 0 || size_t(x) >= terrain.size() || size_t(y) >= terrain.front().size()) { return false; } terrain[x][y] = t_translation::SHALLOW_WATER; locs_touched.insert(location(x,y)); if((rand()%100) < lake_fall_off) { generate_lake(terrain,x+1,y,lake_fall_off/2,locs_touched); } if((rand()%100) < lake_fall_off) { generate_lake(terrain,x-1,y,lake_fall_off/2,locs_touched); } if((rand()%100) < lake_fall_off) { generate_lake(terrain,x,y+1,lake_fall_off/2,locs_touched); } if((rand()%100) < lake_fall_off) { generate_lake(terrain,x,y-1,lake_fall_off/2,locs_touched); } return true; } /** * River generation. * * Rivers have a source, and then keep on flowing until they meet another body * of water, which they flow into, or until they reach the edge of the map. * Rivers will always flow downhill, except that they can flow a maximum of * 'river_uphill' uphill. This is to represent the water eroding the higher * ground lower. * * Every possible path for a river will be attempted, in random order, and the * first river path that can be found that makes the river flow into another * body of water or off the map will be used. * * If no path can be found, then the river's generation will be aborted, and * false will be returned. true is returned if the river is generated * successfully. */ static bool generate_river_internal(const height_map& heights, terrain_map& terrain, int x, int y, std::vector<location>& river, std::set<location>& seen_locations, int river_uphill) { const bool on_map = x >= 0 && y >= 0 && x < static_cast<long>(heights.size()) && y < static_cast<long>(heights.back().size()); if(on_map && !river.empty() && heights[x][y] > heights[river.back().x][river.back().y] + river_uphill) { return false; } // If we're at the end of the river if(!on_map || terrain[x][y] == t_translation::SHALLOW_WATER || terrain[x][y] == t_translation::DEEP_WATER) { LOG_NG << "generating river...\n"; // Generate the river for(std::vector<location>::const_iterator i = river.begin(); i != river.end(); ++i) { terrain[i->x][i->y] = t_translation::SHALLOW_WATER; } LOG_NG << "done generating river\n"; return true; } location current_loc(x,y); location adj[6]; get_adjacent_tiles(current_loc,adj); static int items[6] = {0,1,2,3,4,5}; std::random_shuffle(items,items+4); // Mark that we have attempted from this location seen_locations.insert(current_loc); river.push_back(current_loc); for(int a = 0; a != 6; ++a) { const location& loc = adj[items[a]]; if(seen_locations.count(loc) == 0) { const bool res = generate_river_internal(heights,terrain,loc.x,loc.y,river,seen_locations,river_uphill); if(res) { return true; } } } river.pop_back(); return false; } static std::vector<location> generate_river(const height_map& heights, terrain_map& terrain, int x, int y, int river_uphill) { std::vector<location> river; std::set<location> seen_locations; const bool res = generate_river_internal(heights,terrain,x,y,river,seen_locations,river_uphill); if(!res) { river.clear(); } return river; } /** * Returns a random tile at one of the borders of a map that is of the given * dimensions. */ static location random_point_at_side(size_t width, size_t height) { const int side = rand()%4; if(side < 2) { const int x = rand()%width; const int y = side == 0 ? 0 : height-1; return location(x,y); } else { const int y = rand()%height; const int x = side == 2 ? 0 : width-1; return location(x,y); } } /** Function which, given the map will output it in a valid format. */ static std::string output_map(const terrain_map& terrain, std::map<int, t_translation::coordinate> starting_positions) { // Remember that we only want the middle 1/9th of the map. // All other segments of the map are there only to give // the important middle part some context. // We also have a border so also adjust for that. const size_t begin_x = terrain.size() / 3 - gamemap::default_border ; const size_t end_x = terrain.size() * 2 / 3 + gamemap::default_border; const size_t begin_y = terrain.front().size() / 3 - gamemap::default_border; const size_t end_y = terrain.front().size() * 2 / 3 + gamemap::default_border; terrain_map map; map.resize(end_x - begin_x); for(size_t y = begin_y; y != end_y; ++y) { for(size_t x = begin_x; x != end_x; ++x) { if((y - begin_y) == 0){ map[x - begin_x].resize(end_y - begin_y); } map[x - begin_x][y - begin_y] = terrain[x][y]; } } // Since the map has been resized, // the starting locations also need to be fixed std::map<int, t_translation::coordinate>::iterator itor = starting_positions.begin(); for(; itor != starting_positions.end(); ++itor) { itor->second.x -= begin_x; itor->second.y -= begin_y; } return gamemap::default_map_header + t_translation::write_game_map(map, starting_positions); } namespace { /** * Calculates the cost of building a road over terrain. For use in the * a_star_search algorithm. */ struct road_path_calculator : cost_calculator { road_path_calculator(const terrain_map& terrain, const config& cfg) : calls(0), map_(terrain), cfg_(cfg), // Find out how windy roads should be. windiness_(std::max<int>(1,atoi(cfg["road_windiness"].c_str()))), seed_(rand()), cache_() { } virtual double cost(const location& src, const location& loc, const double so_far) const; mutable int calls; private: const terrain_map& map_; const config& cfg_; int windiness_; int seed_; mutable std::map<t_translation::t_terrain, double> cache_; }; double road_path_calculator::cost(const location& /*src*/, const location& loc, const double /*so_far*/) const { ++calls; if (loc.x < 0 || loc.y < 0 || loc.x >= static_cast<long>(map_.size()) || loc.y >= static_cast<long>(map_.front().size())) { return (getNoPathValue()); } // We multiply the cost by a random amount, // depending upon how 'windy' the road should be. // If windiness is 1, that will mean that the cost is always genuine, // and so the road always takes the shortest path. // If windiness is greater than 1, we sometimes over-report costs // for some segments, to make the road wind a little. double windiness = 1.0; if (windiness_ > 1) { // modified pseudo_random taken from builder.cpp unsigned int a = (loc.x + 92872973) ^ 918273; unsigned int b = (loc.y + 1672517) ^ 128123; unsigned int c = a*b + a + b + seed_; unsigned int random = c*c; // this is just "big random number modulo windiness_" // but avoid the "modulo by a low number (like 2)" // because it can increase arithmetic patterns int noise = random % (windiness_ * 137) / 137; windiness += noise; } const t_translation::t_terrain c = map_[loc.x][loc.y]; const std::map<t_translation::t_terrain, double>::const_iterator itor = cache_.find(c); if(itor != cache_.end()) { return itor->second*windiness; } static std::string terrain; terrain = t_translation::write_terrain_code(c); const config* const child = cfg_.find_child("road_cost","terrain",terrain); double res = getNoPathValue(); if(child != NULL) { res = double(atof((*child)["cost"].c_str())); } cache_.insert(std::pair<t_translation::t_terrain, double>(c,res)); return windiness*res; } struct is_valid_terrain { is_valid_terrain(const t_translation::t_map& map, const t_translation::t_list& terrain_list); bool operator()(int x, int y) const; private: t_translation::t_map map_; const t_translation::t_list& terrain_; }; is_valid_terrain::is_valid_terrain(const t_translation::t_map& map, const t_translation::t_list& terrain_list) : map_(map), terrain_(terrain_list) {} bool is_valid_terrain::operator()(int x, int y) const { if(x < 0 || x >= static_cast<long>(map_.size()) || y < 0 || y >= static_cast<long>(map_[x].size())) { return false; } return std::find(terrain_.begin(),terrain_.end(),map_[x][y]) != terrain_.end(); } } static int rank_castle_location(int x, int y, const is_valid_terrain& valid_terrain, int min_x, int max_x, int min_y, int max_y, size_t min_distance, const std::vector<map_location>& other_castles, int highest_ranking) { const map_location loc(x,y); size_t avg_distance = 0, lowest_distance = 1000; for(std::vector<map_location>::const_iterator c = other_castles.begin(); c != other_castles.end(); ++c) { const size_t distance = distance_between(loc,*c); if(distance < 6) { return 0; } if(distance < lowest_distance) { lowest_distance = distance; } if(distance < min_distance) { avg_distance = 0; return -1; } avg_distance += distance; } if(other_castles.empty() == false) { avg_distance /= other_castles.size(); } for(int i = x-1; i <= x+1; ++i) { for(int j = y-1; j <= y+1; ++j) { if(!valid_terrain(i,j)) { return 0; } } } const int x_from_border = std::min<int>(x - min_x,max_x - x); const int y_from_border = std::min<int>(y - min_y,max_y - y); const int border_ranking = min_distance - std::min<int>(x_from_border,y_from_border) + min_distance - x_from_border - y_from_border; int current_ranking = border_ranking*2 + avg_distance*10 + lowest_distance*10; static const int num_nearby_locations = 11*11; const int max_possible_ranking = current_ranking + num_nearby_locations; if(max_possible_ranking < highest_ranking) { return current_ranking; } int surrounding_ranking = 0; for(int xpos = x-5; xpos <= x+5; ++xpos) { for(int ypos = y-5; ypos <= y+5; ++ypos) { if(valid_terrain(xpos,ypos)) { ++surrounding_ranking; } } } return surrounding_ranking + current_ranking; } typedef std::map<t_translation::t_terrain, t_translation::t_list> tcode_list_cache; static map_location place_village(const t_translation::t_map& map, const size_t x, const size_t y, const size_t radius, const config& cfg, tcode_list_cache &adj_liked_cache) { const map_location loc(x,y); std::set<map_location> locs; get_tiles_radius(loc,radius,locs); map_location best_loc; size_t best_rating = 0; for(std::set<map_location>::const_iterator i = locs.begin(); i != locs.end(); ++i) { if(i->x < 0 || i->y < 0 || i->x >= static_cast<long>(map.size()) || i->y >= static_cast<long>(map[i->x].size())) { continue; } const t_translation::t_terrain t = map[i->x][i->y]; const std::string str = t_translation::write_terrain_code(t); const config* const child = cfg.find_child("village","terrain",str); if(child != NULL) { tcode_list_cache::iterator l = adj_liked_cache.find(t); t_translation::t_list *adjacent_liked; if (l != adj_liked_cache.end()) { adjacent_liked = &(l->second); } else { adj_liked_cache[t] = t_translation::read_list((*child)["adjacent_liked"]); adjacent_liked = &(adj_liked_cache[t]); } size_t rating = atoi((*child)["rating"].c_str()); map_location adj[6]; get_adjacent_tiles(map_location(i->x,i->y),adj); for(size_t n = 0; n != 6; ++n) { if(adj[n].x < 0 || adj[n].y < 0 || adj[n].x >= static_cast<long>(map.size()) || adj[n].y >= static_cast<long>(map[adj[n].x].size())) { continue; } const t_translation::t_terrain t2 = map[adj[n].x][adj[n].y]; rating += std::count(adjacent_liked->begin(),adjacent_liked->end(),t2); } if(rating > best_rating) { best_loc = map_location(i->x,i->y); best_rating = rating; } } } return best_loc; } static std::string generate_name(const unit_race& name_generator, const std::string& id, std::string* base_name=NULL, utils::string_map* additional_symbols=NULL) { const std::vector<std::string>& options = utils::split(string_table[id]); if(options.empty() == false) { const size_t choice = rand()%options.size(); LOG_NG << "calling name generator...\n"; const std::string& name = name_generator.generate_name(unit_race::MALE); LOG_NG << "name generator returned '" << name << "'\n"; if(base_name != NULL) { *base_name = name; } LOG_NG << "assigned base name..\n"; utils::string_map table; if(additional_symbols == NULL) { additional_symbols = &table; } LOG_NG << "got additional symbols\n"; (*additional_symbols)["name"] = name; LOG_NG << "interpolation variables into '" << options[choice] << "'\n"; return utils::interpolate_variables_into_string(options[choice], additional_symbols); } return ""; } namespace { // the configuration file should contain a number of [height] tags: // [height] // height=n // terrain=x // [/height] // These should be in descending order of n. // They are checked sequentially, and if height is greater than n for that tile, // then the tile is set to terrain type x. class terrain_height_mapper { public: explicit terrain_height_mapper(const config& cfg); bool convert_terrain(const int height) const; t_translation::t_terrain convert_to() const; private: int terrain_height; t_translation::t_terrain to; }; terrain_height_mapper::terrain_height_mapper(const config& cfg) : terrain_height(lexical_cast_default<int>(cfg["height"],0)), to(t_translation::GRASS_LAND) { const std::string& terrain = cfg["terrain"]; if(terrain != "") { to = t_translation::read_terrain_code(terrain); } } bool terrain_height_mapper::convert_terrain(const int height) const { return height >= terrain_height; } t_translation::t_terrain terrain_height_mapper::convert_to() const { return to; } class terrain_converter { public: explicit terrain_converter(const config& cfg); bool convert_terrain(const t_translation::t_terrain terrain, const int height, const int temperature) const; t_translation::t_terrain convert_to() const; private: int min_temp, max_temp, min_height, max_height; t_translation::t_list from; t_translation::t_terrain to; }; terrain_converter::terrain_converter(const config& cfg) : min_temp(-1), max_temp(-1), min_height(-1), max_height(-1), from(t_translation::read_list(cfg["from"])), to(t_translation::NONE_TERRAIN) { min_temp = lexical_cast_default<int>(cfg["min_temperature"],-100000); max_temp = lexical_cast_default<int>(cfg["max_temperature"],100000); min_height = lexical_cast_default<int>(cfg["min_height"],-100000); max_height = lexical_cast_default<int>(cfg["max_height"],100000); const std::string& to_str = cfg["to"]; if(to_str != "") { to = t_translation::read_terrain_code(to_str); } } bool terrain_converter::convert_terrain(const t_translation::t_terrain terrain, const int height, const int temperature) const { return std::find(from.begin(),from.end(),terrain) != from.end() && height >= min_height && height <= max_height && temperature >= min_temp && temperature <= max_temp && to != t_translation::NONE_TERRAIN; } t_translation::t_terrain terrain_converter::convert_to() const { return to; } } // end anon namespace std::string default_generate_map(size_t width, size_t height, size_t island_size, size_t island_off_center, size_t iterations, size_t hill_size, size_t max_lakes, size_t nvillages, size_t castle_size, size_t nplayers, bool roads_between_castles, std::map<map_location,std::string>* labels, const config& cfg) { log_scope("map generation"); // Odd widths are nasty VALIDATE(is_even(width), _("Random maps with an odd width aren't supported.")); int ticks = SDL_GetTicks(); // Find out what the 'flatland' on this map is, i.e. grassland. std::string flatland = cfg["default_flatland"]; if(flatland == "") { flatland = t_translation::write_terrain_code(t_translation::GRASS_LAND); } const t_translation::t_terrain grassland = t_translation::read_terrain_code(flatland); // We want to generate a map that is 9 times bigger // than the actual size desired. // Only the middle part of the map will be used, // but the rest is so that the map we end up using // can have a context (e.g. rivers flowing from // out of the map into the map, same for roads, etc.) width *= 3; height *= 3; LOG_NG << "generating height map...\n"; // Generate the height of everything. const height_map heights = generate_height_map(width,height,iterations,hill_size,island_size,island_off_center); LOG_NG << "done generating height map...\n"; LOG_NG << (SDL_GetTicks() - ticks) << "\n"; ticks = SDL_GetTicks(); const config* const names_info = cfg.child("naming"); config naming; if(names_info != NULL) { naming = *names_info; } // Make a dummy race for generating names unit_race name_generator(naming); std::vector<terrain_height_mapper> height_conversion; const config::child_list& height_cfg = cfg.get_children("height"); for(config::child_list::const_iterator h = height_cfg.begin(); h != height_cfg.end(); ++h) { height_conversion.push_back(terrain_height_mapper(**h)); } terrain_map terrain(width, t_translation::t_list(height, grassland)); size_t x, y; for(x = 0; x != heights.size(); ++x) { for(y = 0; y != heights[x].size(); ++y) { for(std::vector<terrain_height_mapper>::const_iterator i = height_conversion.begin(); i != height_conversion.end(); ++i) { if(i->convert_terrain(heights[x][y])) { terrain[x][y] = i->convert_to(); break; } } } } std::map<int, t_translation::coordinate> starting_positions; LOG_NG << output_map(terrain, starting_positions); LOG_NG << "placed land forms\n"; LOG_NG << (SDL_GetTicks() - ticks) << "\n"; ticks = SDL_GetTicks(); // Now that we have our basic set of flatland/hills/mountains/water, // we can place lakes and rivers on the map. // All rivers are sourced at a lake. // Lakes must be in high land - at least 'min_lake_height'. // (Note that terrain below a certain altitude may be made // into bodies of water in the code above - i.e. 'sea', // but these are not considered 'lakes', because // they are not sources of rivers). // // We attempt to place 'max_lakes' lakes. // Each lake will be placed at a random location, // if that random location meets the minimum terrain requirements for a lake. // We will also attempt to source a river from each lake. std::set<location> lake_locs; std::map<location,std::string> river_names, lake_names; const size_t nlakes = max_lakes > 0 ? (rand()%max_lakes) : 0; for(size_t lake = 0; lake != nlakes; ++lake) { for(int tries = 0; tries != 100; ++tries) { const int x = rand()%width; const int y = rand()%height; if(heights[x][y] > atoi(cfg["min_lake_height"].c_str())) { const std::vector<location> river = generate_river(heights,terrain,x,y,atoi(cfg["river_frequency"].c_str())); if(river.empty() == false && labels != NULL) { std::string base_name; LOG_NG << "generating name for river...\n"; const std::string& name = generate_name(name_generator,"river_name",&base_name); LOG_NG << "named river '" << name << "'\n"; size_t name_frequency = 20; for(std::vector<location>::const_iterator r = river.begin(); r != river.end(); ++r) { const map_location loc(r->x-width/3,r->y-height/3); if(((r - river.begin())%name_frequency) == name_frequency/2) { labels->insert(std::pair<map_location,std::string>(loc,name)); } river_names.insert(std::pair<location,std::string>(loc,base_name)); } LOG_NG << "put down river name...\n"; } LOG_NG << "generating lake...\n"; std::set<location> locs; const bool res = generate_lake(terrain,x,y,atoi(cfg["lake_size"].c_str()),locs); if(res && labels != NULL) { bool touches_other_lake = false; std::string base_name; const std::string& name = generate_name(name_generator,"lake_name",&base_name); std::set<location>::const_iterator i; // Only generate a name if the lake hasn't touched any other lakes, // so that we don't end up with one big lake with multiple names. for(i = locs.begin(); i != locs.end(); ++i) { if(lake_locs.count(*i) != 0) { touches_other_lake = true; // Reassign the name of this lake to be the same as the other lake const location loc(i->x-width/3,i->y-height/3); const std::map<location,std::string>::const_iterator other_name = lake_names.find(loc); if(other_name != lake_names.end()) { base_name = other_name->second; } } lake_locs.insert(*i); } if(!touches_other_lake) { const map_location loc(x-width/3,y-height/3); labels->erase(loc); labels->insert(std::pair<map_location,std::string>(loc,name)); } for(i = locs.begin(); i != locs.end(); ++i) { const location loc(i->x-width/3,i->y-height/3); lake_names.insert(std::pair<location,std::string>(*i,base_name)); } } break; } } } LOG_NG << "done generating rivers...\n"; LOG_NG << (SDL_GetTicks() - ticks) << "\n"; ticks = SDL_GetTicks(); const size_t default_dimensions = 40*40*9; /* * Convert grassland terrain to other types of flat terrain. * * We generate a 'temperature map' which uses the height generation * algorithm to generate the temperature levels all over the map. Then we * can use a combination of height and terrain to divide terrain up into * more interesting types than the default. */ const height_map temperature_map = generate_height_map(width,height, (atoi(cfg["temperature_iterations"].c_str())*width*height)/default_dimensions, atoi(cfg["temperature_size"].c_str()),0,0); LOG_NG << "generated temperature map...\n"; LOG_NG << (SDL_GetTicks() - ticks) << "\n"; ticks = SDL_GetTicks(); std::vector<terrain_converter> converters; const config::child_list& converter_items = cfg.get_children("convert"); for(config::child_list::const_iterator cv = converter_items.begin(); cv != converter_items.end(); ++cv) { converters.push_back(terrain_converter(**cv)); } LOG_NG << "created terrain converters\n"; LOG_NG << (SDL_GetTicks() - ticks) << "\n"; ticks = SDL_GetTicks(); // Iterate over every flatland tile, and determine // what type of flatland it is, based on our [convert] tags. for(x = 0; x != width; ++x) { for(y = 0; y != height; ++y) { for(std::vector<terrain_converter>::const_iterator i = converters.begin(); i != converters.end(); ++i) { if(i->convert_terrain(terrain[x][y],heights[x][y],temperature_map[x][y])) { terrain[x][y] = i->convert_to(); break; } } } } LOG_NG << "placing villages...\n"; LOG_NG << (SDL_GetTicks() - ticks) << "\n"; ticks = SDL_GetTicks(); /* * Place villages in a 'grid', to make placing fair, but with villages * displaced from their position according to terrain and randomness, to * add some variety. */ std::set<location> villages; LOG_NG << "placing castles...\n"; /** Try to find configuration for castles. */ const config* const castle_config = cfg.child("castle"); if(castle_config == NULL) { LOG_NG << "Could not find castle configuration\n"; return ""; } /* * Castle configuration tag contains a 'valid_terrain' attribute which is a * list of terrains that the castle may appear on. */ const t_translation::t_list list = t_translation::read_list((*castle_config)["valid_terrain"]); const is_valid_terrain terrain_tester(terrain, list); /* * Attempt to place castles at random. * * Once we have placed castles, we run a sanity check to make sure that the * castles are well-placed. If the castles are not well-placed, we try * again. Definition of 'well-placed' is if no two castles are closer than * 'min_distance' hexes from each other, and the castles appear on a * terrain listed in 'valid_terrain'. */ std::vector<location> castles; std::set<location> failed_locs; for(size_t player = 0; player != nplayers; ++player) { LOG_NG << "placing castle for " << player << "\n"; log_scope("placing castle"); const int min_x = width/3 + 3; const int min_y = height/3 + 3; const int max_x = (width/3)*2 - 4; const int max_y = (height/3)*2 - 4; const size_t min_distance = atoi((*castle_config)["min_distance"].c_str()); location best_loc; int best_ranking = 0; for(int x = min_x; x != max_x; ++x) { for(int y = min_y; y != max_y; ++y) { const location loc(x,y); if(failed_locs.count(loc)) { continue; } const int ranking = rank_castle_location(x,y,terrain_tester,min_x,max_x,min_y,max_y,min_distance,castles,best_ranking); if(ranking <= 0) { failed_locs.insert(loc); } if(ranking > best_ranking) { best_ranking = ranking; best_loc = loc; } } } if(best_ranking == 0) { //FIXME: Make this error message translatable (not possible atm due to string freeze) ERR_NG << "No castle location found, aborting.\n"; std::string error = "No valid castle location found. Too many or too few mountain hexes? (please check the 'max hill size' parameter)"; throw mapgen_exception(error); } assert(std::find(castles.begin(), castles.end(), best_loc) == castles.end()); castles.push_back(best_loc); // Make sure the location can't get a second castle. failed_locs.insert(best_loc); } LOG_NG << "placing roads...\n"; LOG_NG << (SDL_GetTicks() - ticks) << "\n"; ticks = SDL_GetTicks(); // Place roads. // We select two tiles at random locations on the borders // of the map, and try to build roads between them. size_t nroads = atoi(cfg["roads"].c_str()); if(roads_between_castles) { nroads += castles.size()*castles.size(); } std::set<location> bridges; road_path_calculator calc(terrain,cfg); for(size_t road = 0; road != nroads; ++road) { log_scope("creating road"); /* * We want the locations to be on the portion of the map we're actually * going to use, since roads on other parts of the map won't have any * influence, and doing it like this will be quicker. */ location src = random_point_at_side(width/3 + 2,height/3 + 2); location dst = random_point_at_side(width/3 + 2,height/3 + 2); src.x += width/3 - 1; src.y += height/3 - 1; dst.x += width/3 - 1; dst.y += height/3 - 1; if(roads_between_castles && road < castles.size()*castles.size()) { const size_t src_castle = road/castles.size(); const size_t dst_castle = road%castles.size(); if(src_castle >= dst_castle) { continue; } src = castles[src_castle]; dst = castles[dst_castle]; } // If the road isn't very interesting (on the same border), don't draw it. else if(src.x == dst.x || src.y == dst.y) { continue; } if (calc.cost(src,src, 0.0) >= 1000.0 || calc.cost(src,dst, 0.0) >= 1000.0) { continue; } // Search a path out for the road const paths::route rt = a_star_search(src, dst, 10000.0, &calc, width, height); const std::string& name = generate_name(name_generator,"road_name"); const int name_frequency = 20; int name_count = 0; bool on_bridge = false; // Draw the road. // If the search failed, rt.steps will simply be empty. for(std::vector<location>::const_iterator step = rt.steps.begin(); step != rt.steps.end(); ++step) { const int x = step->x; const int y = step->y; if(x < 0 || y < 0 || x >= static_cast<long>(width) || y >= static_cast<long>(height)) { continue; } // Find the configuration which tells us // what to convert this tile to, to make it into a road. const config* const child = cfg.find_child("road_cost", "terrain", t_translation::write_terrain_code(terrain[x][y])); if(child != NULL) { // Convert to bridge means that we want to convert // depending upon the direction the road is going. // Typically it will be in a format like, // convert_to_bridge=\,|,/ // '|' will be used if the road is going north-south // '/' will be used if the road is going south west-north east // '\' will be used if the road is going south east-north west // The terrain will be left unchanged otherwise // (if there is no clear direction). const std::string& convert_to_bridge = (*child)["convert_to_bridge"]; if(convert_to_bridge.empty() == false) { if(step == rt.steps.begin() || step+1 == rt.steps.end()) continue; const location& last = *(step-1); const location& next = *(step+1); location adj[6]; get_adjacent_tiles(*step,adj); int direction = -1; // If we are going north-south if((last == adj[0] && next == adj[3]) || (last == adj[3] && next == adj[0])) { direction = 0; } // If we are going south west-north east else if((last == adj[1] && next == adj[4]) || (last == adj[4] && next == adj[1])) { direction = 1; } // If we are going south east-north west else if((last == adj[2] && next == adj[5]) || (last == adj[5] && next == adj[2])) { direction = 2; } if(labels != NULL && on_bridge == false) { on_bridge = true; const std::string& name = generate_name(name_generator,"bridge_name"); const location loc(x-width/3,y-height/3); labels->insert(std::pair<map_location,std::string>(loc,name)); bridges.insert(loc); } if(direction != -1) { const std::vector<std::string> items = utils::split(convert_to_bridge); if(size_t(direction) < items.size() && items[direction].empty() == false) { terrain[x][y] = t_translation::read_terrain_code(items[direction]); } continue; } } else { on_bridge = false; } // Just a plain terrain substitution for a road const std::string& convert_to = (*child)["convert_to"]; if(convert_to.empty() == false) { const t_translation::t_terrain letter = t_translation::read_terrain_code(convert_to); if(labels != NULL && terrain[x][y] != letter && name_count++ == name_frequency && on_bridge == false) { labels->insert(std::pair<map_location,std::string>(map_location(x-width/3,y-height/3),name)); name_count = 0; } terrain[x][y] = letter; } } } LOG_NG << "looked at " << calc.calls << " locations\n"; } // Now that road drawing is done, we can plonk down the castles. for(std::vector<location>::const_iterator c = castles.begin(); c != castles.end(); ++c) { if(c->valid() == false) { continue; } const int x = c->x; const int y = c->y; const int player = c - castles.begin() + 1; const struct t_translation::coordinate coord = {x, y}; starting_positions.insert(std::pair<int, t_translation::coordinate>(player, coord)); terrain[x][y] = t_translation::HUMAN_KEEP; const int castles[13][2] = { {-1, 0}, {-1, -1}, {0, -1}, {1, -1}, {1, 0}, {0, 1}, {-1, 1}, {-2, 1}, {-2, 0}, {-2, -1}, {-1, -2}, {0, -2}, {1, -2} }; for (size_t i = 0; i < castle_size - 1; i++) { terrain[x+castles[i][0]][y+castles[i][1]] = t_translation::HUMAN_CASTLE; } // Remove all labels under the castle tiles if(labels != NULL) { labels->erase(location(x-width/3,y-height/3)); for (size_t i = 0; i < castle_size - 1; i++) { labels->erase(location(x+castles[i][0]-width/3, y+castles[i][1]-height/3)); } } } LOG_NG << "placed castles\n"; LOG_NG << (SDL_GetTicks() - ticks) << "\n"; ticks = SDL_GetTicks(); if(nvillages > 0) { const config* const naming = cfg.child("village_naming"); config naming_cfg; if(naming != NULL) { naming_cfg = *naming; } const unit_race village_names_generator(naming_cfg); // First we work out the size of the x and y distance between villages const size_t tiles_per_village = ((width*height)/9)/nvillages; size_t village_x = 1, village_y = 1; // Alternate between incrementing the x and y value. // When they are high enough to equal or exceed the tiles_per_village, // then we have them to the value we want them at. while(village_x*village_y < tiles_per_village) { if(village_x < village_y) { ++village_x; } else { ++village_y; } } std::set<std::string> used_names; tcode_list_cache adj_liked_cache; for(size_t vx = 0; vx < width; vx += village_x) { LOG_NG << "village at " << vx << "\n"; for(size_t vy = rand()%village_y; vy < height; vy += village_y) { const size_t add_x = rand()%3; const size_t add_y = rand()%3; const size_t x = (vx + add_x) - 1; const size_t y = (vy + add_y) - 1; const map_location res = place_village(terrain,x,y,2,cfg,adj_liked_cache); if(res.x >= static_cast<long>(width) / 3 && res.x < static_cast<long>(width * 2) / 3 && res.y >= static_cast<long>(height) / 3 && res.y < static_cast<long>(height * 2) / 3) { const std::string str = t_translation::write_terrain_code(terrain[res.x][res.y]); const config* const child = cfg.find_child("village","terrain",str); if(child != NULL) { const std::string& convert_to = (*child)["convert_to"]; if(convert_to != "") { terrain[res.x][res.y] = t_translation::read_terrain_code(convert_to); villages.insert(res); if(labels != NULL && naming_cfg.empty() == false) { const map_location loc(res.x-width/3,res.y-height/3); map_location adj[6]; get_adjacent_tiles(loc,adj); std::string name_type = "village_name"; const t_translation::t_list field = t_translation::t_list(1, t_translation::GRASS_LAND), forest = t_translation::t_list(1, t_translation::FOREST), mountain = t_translation::t_list(1, t_translation::MOUNTAIN), hill = t_translation::t_list(1, t_translation::HILL); size_t field_count = 0, forest_count = 0, mountain_count = 0, hill_count = 0; utils::string_map symbols; size_t n; for(n = 0; n != 6; ++n) { const std::map<location,std::string>::const_iterator river_name = river_names.find(adj[n]); if(river_name != river_names.end()) { symbols["river"] = river_name->second; name_type = "village_name_river"; if(bridges.count(loc)) { name_type = "village_name_river_bridge"; } break; } const std::map<location,std::string>::const_iterator lake_name = lake_names.find(adj[n]); if(lake_name != lake_names.end()) { symbols["lake"] = lake_name->second; name_type = "village_name_lake"; break; } const t_translation::t_terrain terr = terrain[adj[n].x+width/3][adj[n].y+height/3]; if(std::count(field.begin(),field.end(),terr) > 0) { ++field_count; } else if(std::count(forest.begin(),forest.end(),terr) > 0) { ++forest_count; } else if(std::count(hill.begin(),hill.end(),terr) > 0) { ++hill_count; } else if(std::count(mountain.begin(),mountain.end(),terr) > 0) { ++mountain_count; } } if(n == 6) { if(field_count == 6) { name_type = "village_name_grassland"; } else if(forest_count >= 2) { name_type = "village_name_forest"; } else if(mountain_count >= 1) { name_type = "village_name_mountain"; } else if(hill_count >= 2) { name_type = "village_name_hill"; } } std::string name; for(size_t ntry = 0; ntry != 30 && (ntry == 0 || used_names.count(name) > 0); ++ntry) { name = generate_name(village_names_generator,name_type,NULL,&symbols); } used_names.insert(name); labels->insert(std::pair<map_location,std::string>(loc,name)); } } } } } } } LOG_NG << "placed villages\n"; LOG_NG << (SDL_GetTicks() - ticks) << "\n"; ticks = SDL_GetTicks(); return output_map(terrain, starting_positions); } namespace { typedef std::map<std::string,map_generator*> generator_map; generator_map generators; } #ifdef TEST_MAPGEN /** Standalone testprogram for the mapgenerator. */ int main(int argc, char** argv) { int x = 50, y = 50, iterations = 50, hill_size = 50, lakes=3, nvillages = 25, nplayers = 2; if(argc >= 2) { x = atoi(argv[1]); } if(argc >= 3) { y = atoi(argv[2]); } if(argc >= 4) { iterations = atoi(argv[3]); } if(argc >= 5) { hill_size = atoi(argv[4]); } if(argc >= 6) { lakes = atoi(argv[5]); } if(argc >= 7) { nvillages = atoi(argv[6]); } if(argc >= 8) { nplayers = atoi(argv[7]); } srand(time(NULL)); std::cout << generate_map(x,y,iterations,hill_size,lakes,nvillages,nplayers) << "\n"; } #endif
fstltna/Wesnoth-New-Era
Classes/mapgen.cpp
C++
gpl-2.0
42,175
/* $Id: style.css,v 1.1.2.6 2010/06/13 02:06:37 zyxware Exp $ */ /** * Theme Name: Mystique_theme * Theme URI: http://digitalnature.ro/projects/mystique * Designed by <a href="http://digitalnature.ro/">digitalnature</a>. */ /* reset spacing */ *{ margin:0; padding:0; font-family:"Segoe UI",Calibri,"Myriad Pro",Myriad,"Trebuchet MS",Helvetica,Arial,sans-serif; } html,body{min-height:100%;} body{background:#000 url(images/bg.png) repeat-x center bottom;font-size:13px;font-style:normal;color:#4e4e4e;} #page{background:transparent url(images/header.jpg) no-repeat center top;} /* (max. possible width is limited by design, 1735px) */ .page-content{max-width:1600px;min-width:780px;margin:0 auto;} /* fluid width page */ body.fluid .page-content{ padding:0 10px; width: auto; } /* fixed width page - 960gs */ body.fixed .page-content{ width:940px; } /*** GENERAL ELEMENTS ***/ /* links */ a{color:#0071bb;outline:none;} a:hover{color:#ed1e24;text-decoration:none;} /* headings */ h1{font-weight:normal;font-size:270%;letter-spacing:-.04em;line-height:100%;margin:.8em 0 .2em;letter-spacing:-0.04em;} h2{font-weight:normal;font-size:200%;letter-spacing:-.04em;line-height:110%;margin:.7em 0 .2em;letter-spacing:-0.03em;} h3{font-size:160%;font-weight:normal;letter-spacing:-.04em;line-height:110%;margin:.7em 0 .2em;letter-spacing:-0.02em;} h4{font-size:140%;font-weight:bold;margin:.7em 0 .2em;letter-spacing:-0.02em;} h5{font-family:"Palatino Linotype", Georgia, Serif;font-size:140%;font-weight:bold;margin:.5em 0 .2em;letter-spacing:-0.02em;} h6{font-size:120%;font-weight:normal;text-transform:uppercase;margin:.5em 0 .2em;} /* tables */ table{ margin:.5em 0 1em; } table td,table th{text-align:left;border-right:1px solid #fff;padding:.4em .8em;} table th{background-color:#5e5e5e;color:#fff;text-transform:uppercase;font-weight:bold;border-bottom:1px solid #e8e1c8;} table td{background-color:#eee;} table th a{color:#d6f325;} table th a:hover{color:#fff;} table tr.even td{background-color:#ddd;} table tr:hover td{background-color:#fff;} table.nostyle td,table.nostyle th,table.nostyle tr.even td,table.nostyle tr:hover td{border:0;background:none;background-color:transparent;} /* forms */ input,textarea,select{font-size:100%;margin:.2em 0;} input,textarea{padding:.2em .4em;margin:0 2px 4px 2px;} input.radio,input.checkbox{background-color:#fff;padding:2px;} textarea{width:90%;} form label{font-weight:normal;margin:0 2px;} form .row label{display:block;margin:10px 2px 0 2px;} fieldset{padding:.8em;border:1px solid #ddd;background-color:#fff;margin:1em 0;} legend { padding:2px 15px 10px; text-transform:uppercase; font-style:italic; font-size:115%; background-color:#fff; border-top:1px solid #ddd; } /* lists */ ul,ol{margin:.4em 0 1em;line-height:150%;} ul li,ol li{list-style-position:outside;margin-left:2.5em;} dl{padding:.3em 0 .8em;} dt{font-weight:bold;text-decoration:underline;} dd { padding:10px; } /* other */ p{margin:.6em 0 .3em;line-height:150%;} img{border:0;} hr{color:#b4aca1;background-color:#b4aca1;border-bottom:1px solid #f6f4eb;} small{font-size:80%;} pre{overflow:auto;white-space:pre-wrap;/* <- css3 */white-space:0;/* <- ff */font-size:12px;font-family:"Courier New", Courier, "Lucida Console", Monaco, "DejaVu Sans Mono", "Nimbus Mono L", "Bitstream Vera Sans Mono";background-color:#fff;padding:.4em;margin:1em 0;} pre{width:80%;overflow:hidden;border:1px solid #ddd;background-color:#fff;padding:.8em;margin:1em 0;} blockquote{margin:1em 25% 1em 0;min-height:40px;padding:.6em 1em .6em 2.4em;border:1px dotted #ddd;font-style:italic;color:#474747;background:#fff url(images/blockquote.png) no-repeat 4px top;} blockquote p{padding:8px;margin:2px;} blockquote blockquote{margin:1em 0 1em;} #header{display:block;position:relative;z-index:5;} #header p.nav-extra{position:absolute;top:-25px;z-index:10;right:10px;} #header a.nav-extra{width:64px;height:46px;display:block;float:right;margin-left:6px;} #header a.nav-extra span{display:none;} #header a.nav-extra.rss{background:transparent url(images/nav-icons.png) no-repeat right top;} #header a.twitter{background:transparent url(images/nav-icons.png) no-repeat left top;} /*** LOGO & HEADLINE ***/ #site-title{padding:4em 0 3.6em 0;} #site-title #logo{font-size:400%;font-weight:bold;font-style:normal;margin:0;padding:0;float:left;line-height:60px;} #site-title #logo a{color:#fff;text-decoration:none;text-shadow:#000 1px 1px 1px;font-variant:small-caps;letter-spacing:-0.04em;} #site-title #logo a:hover{color:#ed1e24;} #site-title p.headline{float:left;border-left:1px solid #999;margin:0 0 0 1em;padding:.2em 0 .2em .8em;font-weight:normal;font-size:140%;line-height:64px;letter-spacing:0.4em;} /*** TOP NAVIGATION ***/ ul.navigation{ background:#eee url(images/nav.png) repeat-x left top; width:100%; padding:0; margin:0; list-style-type:none; position:relative; z-index:15; height:35px; } ul.navigation li{display:block;position:relative;float:left;list-style-type:none;padding:0 1px 0 0;margin:0;background:transparent url(images/nav-div.png) no-repeat right top;} ul.navigation li a{ min-height:35px; display:block; font-weight:bold; font-size:115%; text-transform:uppercase; text-decoration:none; text-shadow:#fff 1px 1px 1px; text-align:center; color:#4e4e4e; padding:0 13px 0 11px; position:relative; line-height:35px; } ul.navigation li.first a span.title{background:transparent url(images/icons.png) no-repeat 0px -756px;padding-left:22px;} ul.navigation li.active a span.title{background-position:0px -710px;} ul.navigation li a:hover,ul#navigation li:hover a{background-color:#fff;} ul.navigation li.active a:hover,ul#navigation li.active:hover a{background-color:#000;} ul.navigation li a span.title{display:block;padding:0;} ul.navigation li a span.pointer{display:none;} ul.navigation li.active a span.pointer, ul.navigation li.active-parent a span.pointer, ul.navigation li.active-ancestor a span.pointer {position:absolute;width:100%;height:7px;bottom:-7px;left:0;display:block;background:transparent url(images/nav-pointer.png) no-repeat center top;} ul.navigation li.active a, ul.navigation li.active-parent a, ul.navigation li.active-ancestor a {background:#000 url(images/nav-active.png) no-repeat left top;color:#dedede;text-shadow:#000 1px 1px 1px;} ul.navigation li a span.arrow{display:none;} /* fade on mouse out */ ul.navigation li a.fadeThis{position:relative;z-index:1;} ul.navigation li a.fadeThis span.hover{position:absolute;top:0;left:0;display:block;height:100%;width:100%;background-color:#fff;z-index:-1;margin:0;padding:0;} ul.navigation li.active a.fadeThis span.hover, ul.navigation li.active-parent a.fadeThis span.hover, ul.navigation li.active-ancestor a.fadeThis span.hover {background:none;} ul.navigation li.active a.fadeThis span.hover {background-color:transparent;} /* submenus */ ul.navigation ul li a span.pointer{display:none !important;} ul.navigation ul{list-style-type:none;border-bottom:1px solid #ccc;border-left:1px solid #ccc;border-right:1px solid #ccc;position:absolute;display:none;width:250px;top:32px;left:0;margin:0;padding:4px;line-height:normal;background-color:#fff;-moz-box-shadow:0px 8px 14px rgba(0,0,0,0.3);-moz-border-radius-bottomright:8px;-moz-border-radius-bottomleft:8px;-webkit-box-shadow:0px 8px 14px rgba(0,0,0,0.3);-webkit-border-bottom-right-radius:8px;-webkit-border-bottom-left-radius:8px;box-shadow:0px 8px 14px rgba(0,0,0,0.3);border-bottom-right-radius:8px;border-bottom-left-radius:8px;} ul.navigation li.active ul, ul.navigation li.active-parent ul,ul#navigation li.active-ancestor ul {background-color:#000;border-bottom:1px solid #333;border-left:1px solid #333;border-right:1px solid #333;} ul.navigation li.active li a, ul.navigation li.active-parent li a, ul.navigation li.active-ancestor li a {background:none;} ul.navigation ul li{float:none;margin:0;background:none;} ul.navigation ul li a span.title{padding-left:10px;} ul.navigation ul li a{min-height:1px;height:auto;padding:8px 14px 8px 8px;margin:0;text-align:left;text-transform:none;line-height:125%;} ul.navigation li.active ul a{background:none;} ul.navigation ul li a:hover{background-color:#333;color:#fff;text-shadow:#333 1px 1px 1px;} ul.navigation ul li.active a{color:#f8b013;} ul.navigation ul li.active li a{color:#dedede;} ul.navigation ul li a span.title{padding:0;} ul.navigation ul ul{left:250px;top:0;border-top:1px solid #ccc;-moz-border-radius:8px;-webkit-border-radius:8px;border-radius:8px;} ul.navigation li:hover ul ul,ul#navigation li:hover ul ul ul,ul#navigation li:hover ul ul ul ul{display:none;} ul.navigation li:hover ul,ul#navigation li li:hover ul,ul#navigation li li li:hover ul,ul#navigation li li li li:hover ul{display:block;} ul.navigation li li a span.arrow{display:block;position:absolute;right:6px;top:0;line-height:32px;} /* fade on mouse out */ ul.navigation li li a.fadeThis span.hover, ul.navigation li.active li a.fadeThis span.hover, ul.navigation li.active-ancestor li a.fadeThis span.hover{background-color:#333;} /*** FEATURED CONTENT ***/ #featured-content{background:#5e5e5e url(images/featured.jpg) no-repeat center top;border-top:1px solid #818389;color:#fff;position:relative;margin:0 auto;color:#ccc;} #featured-content ul.slides li.slide .slide-content{padding: 0 1em;} #featured-content .slide-container{max-width:940px;margin:0;padding:0 0 1em 0;} #featured-content h2{font-size:180%;font-weight:bold;text-shadow:#000 1px 1px 1px;margin:0;padding:.2em 0;line-height:140%;} #featured-content p{margin:0 0 .6em 0;} #featured-content a{color:#fff;text-decoration:none;font-weight:bold;} #featured-content a:hover{background-color:rgba(0,0,0, 0.15);} #featured-content .post-thumb img{border:4px solid #777;} #featured-content .details{float:left;width:920px;} #featured-content .summary{font-size:125%;font-style:italic;line-height:150%;} /* fixed size if we have a slider */ #featured-content.withSlider .slide-container{height:174px;} /*** MAIN LAYOUT ***/ .shadow-left{background:url(images/shadow.png) no-repeat left bottom;} .shadow-right{background:url(images/shadow.png) no-repeat right bottom;padding-bottom:32px;position:relative;} #main{background:#fff url(images/main-right.jpg) no-repeat right top;} #main-inside{background:transparent url(images/main-left.jpg) no-repeat left top;min-height:380px;} /*** MAIN LAYOUT ***/ /* default widths */ #primary-content{width:630px;} #sidebar{width:310px;} #sidebar2{width:230px;} /* col-1 */ body.col-1 #primary-content{width:940px;left:0;} body.col-1 #sidebar, body.col-1 #sidebar2{display:none;} /* col-2-left */ body.col-2-left #primary-content{left:310px;} body.col-2-left #sidebar{left:-630px;} body.col-2-left #sidebar2{display:none;} /* col-2-right, default */ body.col-2-right #primary-content{left:0;} body.col-2-right #sidebar{right:0;} body.col-2-right #sidebar2{display:none;} /* col-3 */ body.col-3 #primary-content{left:230px;width:480px;} body.col-3 #sidebar{right:0px;width:230px;} body.col-3 #sidebar2{left:-480px;} /* col-3-left */ body.col-3-left #primary-content{left:460px;width:480px;} body.col-3-left #sidebar{left:-710px;width:230px;} body.col-3-left #sidebar2{left:-250px;} /* gs - s1 - (s1+s2) */ body.col-3-left #primary-content .blocks{margin-left:10px;} /* col-3-right */ body.col-3-right #primary-content{left:0;width:480px;} body.col-3-right #sidebar{left:0;width:230px;} body.col-3-right #sidebar2{left:0;} body.col-3-right #primary-content .blocks{margin-right:10px;} #main{ position: relative; min-height: 540px; } #primary-content,#sidebar,#sidebar2{ top:0; position:relative; float:left; z-index:0; overflow:hidden; min-height: 150px; } #primary-content .blocks{ padding: 1em; } #sidebar .blocks, #sidebar2 .blocks{padding:1em;margin:0;list-style-type:none;} li.block{list-style-type:none;padding:0;margin:0;} li.block, .arbitrary-block{margin:1em 0 2.6em;position:relative;} .block ul{list-style-type:none;margin:0 0 .4em 0;} .block li{background:transparent url(images/icons.png) no-repeat 4px -816px;margin:0;padding:0 0 0 18px;} .block li:hover{background-position:4px -1005px;} .block li li{margin-left:.4em;} h1.title{ font-weight: bold; font-size: 250%; text-shadow: #fff 1px 1px 1px; margin: .5em 0 .3em 0; padding: 0; } /* post */ .post, .page{margin:1em 0 2em 0;padding:0 0 .6em;display:block;background:transparent url(images/dot.gif) repeat-x left bottom;} .post.preview-title{background:none;} body.single-page .page, body.single-post .post{background: none;margin:0;padding:0;} h2.title{ font-weight: bold; font-size: 180%; margin:0 0 .2em 0; padding:.2em 0 0 0; text-shadow: #fff 1px 1px 1px; } h2.title a{text-decoration:none;color:#4e4e4e;} h2.title a:hover{color:#ed1e24;text-decoration:none;} h3.title{font-size:140%;font-weight:bold;margin:1em 0 0 0;padding:0;} h3.title a{text-decoration:none;color:#4e4e4e;} h3.title a:hover{color:#ed1e24;text-decoration:none;} .post-excerpt{font-size:90%;font-style:italic;color:#666;} .post-short-info{margin:0;padding:0;} .post-thumb img{border:4px solid #eee;} .post-info{background:transparent url(images/info-bar.png) no-repeat right top;height:42px;margin-left:11px;color:#bbb;text-shadow:#fff 1px 1px 1px;} .post-info a{font-weight:bold;color:#999;} .post-info a:hover{color:#ed1e24;} .post-info p.author{padding: 0 0 0 6px;margin:0;line-height:32px;} .post-info p.comments{padding: 0 12px 0 0;margin:0;line-height:32px;} .post-info p.comments a.comments{background:transparent url(images/icons.png) no-repeat 0px -49px;padding-left:20px;} .post-info p.comments a.no.comments{background-position:0px 1px;} .post-date{background:transparent url(images/info-bar.png) no-repeat left -75px;padding-left:11px;float:left;text-transform:uppercase;font-weight:bold;} .post-date p.day{background:transparent url(images/info-bar.png) no-repeat right -42px;height:33px;padding:0 16px 0 0;margin:0;line-height:31px;color:#fff;} .post-content p{margin:0 0 .8em 0;padding:0;} .post-content a.post-edit-link{border:#ddd 1px solid;background-color:#fff;padding:3px 6px;text-decoration:none;} .post-content a.post-edit-link:hover{border:#ff284b 1px solid;background-color:#ed1e24;color:#fff;} .post-content a.more-link{background-color:#eee;text-decoration:none;color:#666;text-shadow:#fff 1px 1px 1px;padding:2px 6px 3px 6px;margin:0;font-size:85%;text-transform:uppercase;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;} .post-content a.more-link:hover{background-color:#999;color:#fff;text-shadow:#666 1px 1px 1px;} .post-content a.more-link.loading{border:0;margin:0 4px;padding:3px 8px;border:0;background:transparent url(images/loader-white.gif) no-repeat center center;} .post-tags{background:transparent url(images/icons.png) no-repeat 0px -104px;font-style:italic;padding-left:20px;line-height:22px;} .post-tags ul li { margin-left: 0px; } .category-description{ font-size: 115%; font-style: italic; } .about_the_author{ padding: 8px 10px; line-height: 150%; background-color: #5e5e5e; color: #ccc; font-style: italic; } .about_the_author a{ color: #f9f9f9; text-decoration: underline; } .about_the_author a:hover{ color: #fff; text-decoration: none; } .about_the_author h3{ margin: 0; padding: 0; font-size: 130%; font-weight: bold; font-style: normal; color: #f9f9f9; } .about_the_author div.avatar{ float: left; margin-right: 8px; } .about_the_author div.avatar img{ border: 6px solid #333; } .post-meta{padding:6px 4px;border-top:1px solid #ddd;background-color:#f6f6f6;color:#999;display:block;} .post-meta td { background-color: transparent; border: 0; padding: 0 2px; margin: 0; } .post-meta a{color:#666;text-decoration:underline;} .post-meta a:hover{color:#ed1e24;text-decoration:none;} .post-meta .details{font-size:80%;line-height:150%;} .post-meta a.control{display:block;padding:2px 6px 4px;background-color:#eee;text-shadow:#fff 1px 1px 1px;font-style:italic;text-decoration:none;font-size:115%;border:1px solid #fff;border-radius:3px;text-align:center;letter-spacing:-0.02em;-moz-border-radius:4px;-webkit-border-radius:4px;border-radius:4px;cursor:pointer;} .post-meta a.control:hover, .post-meta a.control:hover a{background-color:#0071bb;text-shadow:#666 1px 1px 1px;color:#fff;} /* share this */ .shareThis{position:relative;float:left;} .shareThis a.share:hover,.shareThis:hover a{} .shareThis .bubble{width:288px;left:0px;top:0px;margin-top:40px;padding:4px;background-color:#fff;border:1px solid #ddd;-moz-box-shadow:0px 0px 8px rgba(0,0,0,0.4);-moz-border-radius:8px;-webkit-box-shadow:0px 0px 8px rgba(0,0,0,0.4);-webkit-border-radius:8px;box-shadow:0px 0px 8px rgba(0,0,0,0.4);border-radius:8px;} .shareThis .bubble a{background:transparent url(images/socialize.jpg) no-repeat left bottom;width:32px;height:32px;float:left;position:relative;z-index:5;} .shareThis .bubble li{list-style-type:none;padding:0;margin:0;float:left;} .shareThis .bubble a.twitter{background-position:0px -32px;} .shareThis .bubble a.digg{background-position:-32px -32px;} .shareThis .bubble a.facebook{background-position:-64px -32px;} .shareThis .bubble a.delicious{background-position:-96px -32px;} .shareThis .bubble a.stumbleupon{background-position:-128px -32px;} .shareThis .bubble a.google{background-position:-160px -32px;} .shareThis .bubble a.linkedin{background-position:-192px -32px;} .shareThis .bubble a.yahoo{background-position:-224px -32px;} .shareThis .bubble a.technorati{background-position:-256px -32px;} .shareThis .bubble a.twitter:hover{background-position:0 0px;} .shareThis .bubble a.digg:hover{background-position:-32px 0px;} .shareThis .bubble a.facebook:hover{background-position:-64px 0px;} .shareThis .bubble a.delicious:hover{background-position:-96px 0px;} .shareThis .bubble a.stumbleupon:hover{background-position:-128px 0px;} .shareThis .bubble a.google:hover{background-position:-160px 0px;} .shareThis .bubble a.linkedin:hover{background-position:-192px 0px;} .shareThis .bubble a.yahoo:hover{background-position:-224px 0px;} .shareThis .bubble a.technorati:hover{background-position:-256px 0px;} .shareThis .bubble a span{display:none;} .single-navigation a{font-size:85%;border:0;background-color:transparent;padding:2px 4px;color:#ccc;text-shadow:#fff 1px 1px 1px;text-decoration:none;} .single-navigation a:hover{color:#ed1e24;} .single-navigation div{display:block;line-height:normal;color:#ccc;} .single-navigation .alignright{text-align:right;} /* comments */ .tabbed-content div.section#section-comments{display:block;} /* show comment tab, just in case jquery is disabled */ ul.comments, li.comment,div#comments, div.comment-published {margin:0;padding:0;list-style-type:none;} ul.comments, div#comments{width:100%;max-width:1000px;float:right;display:block;} ul.comments ul.children{margin:0 0 0 40px;padding:0;} li.comment, div.comment-published{display:block;margin:.4em 0;line-height:normal;} li.comment .comment-head, .comment-head{background-color:#5e5e5e;background-repeat:no-repeat;background-position:left bottom;position:relative;color:#e4e4e4;padding:0 0 6px 0;margin:0;line-height:normal;} li.comment .comment-head.comment-author-admin,li.comment .comment-head.bypostauthor{background-position:-1000px bottom;color:#fff;text-shadow:rgba(0,0,0,0.4) 1px 1px 1px;} li.comment.withAvatars .comment-head, .comment-head{padding-left:78px;} li.comment .comment-head .author, .comment-head .author{margin:0;padding: 4px 1em 16px 1em;line-height:150%;} li.comment .comment-head a, .comment-head a{color:#fff;text-decoration:underline;} li.comment .comment-head a:hover, .comment-head a:hover{text-decoration:none;} li.comment .comment-head .author .by, .comment-head .author .by{font-weight:bold;} li.comment .comment-body, .comment-body{background:#f6f6f6 url(images/comment-bg.gif) no-repeat right bottom;padding:.4em 1em;} li.comment .comment-body p, .comment-body p{margin:0;padding: 0 0 1em 0;} li.comment .avatar-box, .avatar-box{position:absolute;bottom:0px;width:48px;height:48px;left:8px;z-index:2;padding:3px;background-color:#fff;border: 1px solid #bfbfbf;} li.comment .controls{position:absolute;right:10px;top:8px;margin-top:16px;} li.comment .controls a{display:block;background-color:#e4e4e4;padding:4px 8px;color:#4e4e4e;text-shadow:#fff 1px 1px 1px;font-weight:bold;text-transform:uppercase;text-decoration:none;float:left;margin-right:4px;border-top:1px solid #fff;} li.comment .controls a:hover{background-color:#ed1e24;border-top:1px solid #ff284b;color:#fff;text-shadow:#333 1px 1px 1px;} li.ping{background:transparent url(images/dot.gif) repeat-x left bottom;padding:0 0 .6em 0;margin:.2em 0;line-height:150%;} li.ping a{font-weight:bold;font-size:115%;text-decoration:none;} /* comment form */ .comment-form{background:#f6f6f6 url(images/comment-bg.gif) no-repeat right bottom;border-top:1px solid #ddd;padding:1em;margin:1em 0;float:left;} .comment-form #comment{width:90%;} #cancel-reply{display:none;} #comment_post_status{font-weight:bold;} /* PAGE/COMMENT NAVIGATION */ .page-navigation, .comment-navigation{ padding: 5px 0px; color: #333; } /* align to right on col-3-left layout, looks better */ body.col-3-left .page-navigation, body.col-3-left .comment-navigation{float: right;} .page-navigation a, .page-navigation span.current, .page-navigation span.extend, .comment-navigation a, .comment-navigation span.current, .comment-navigation span.dots{ padding: 3px 5px 4px 5px; margin: 2px; float: left; } .page-navigation a, .comment-navigation a{ text-decoration: none; border: 1px solid #ddd; background-color: #fff; } .page-navigation a:hover, .comment-navigation a:hover{ border: 1px solid #ed1e24; color: #fff; background-color: #ed1e24; } .page-navigation span.current, .comment-navigation span.current{ border: 1px solid #0072cf; color: #fff; background-color: #0072cf; } .comment-navigation a.loading{border:0;padding:3px 8px;border:0;background:transparent url(images/loader-white.gif) no-repeat center center;} /* search */ div.search-form{position:relative;margin:0 8px 0 4px;width:auto !important;width: 400px;max-width:400px;} div.search-form form > div:first-child { border:0; margin:0; padding:0; background:none; background-color:transparent; } div.search-form .form-item{background-repeat:no-repeat;background-position:left top;height:34px;display:block;margin-right:55px;} div.search-form input.text{border:0;margin:9px 0 0 34px;padding:0;} div.search-form input.submit{background-color:transparent;background-repeat:no-repeat;background-position:right -34px;height:34px;width:56px;margin:0;padding:0;position:absolute;right:0;top:0;border:0;text-transform:uppercase;text-shadow:#fff 1px 1px 1px;font-weight:bold;font-size:160%;color:#9b9b9b;cursor:pointer;} div.search-form input.submit:hover{background-position:right bottom;} #primary-content div.search-form{margin:2em 0;} /* block style */ .block h3.title{font-weight:bold;font-size:130%;background-repeat:no-repeat;background-position:left top;color:#fff;line-height:100%;letter-spacing:normal;margin:0;padding:0;text-shadow:1px 1px 1px rgba(0,0,0,0.4);text-transform:uppercase;text-align:left;line-height:23px;} .block h3.title span{background-repeat:no-repeat;background-position:right top;margin-left:7px;display:block;padding:4px 8px 0 4px;} .block h3.title a{color:#fff;text-decoration:none;} .block h3.title a:hover{color:#FFFF00;} .block .block-div{background-color:transparent;background-repeat:no-repeat;background-position:left bottom;width:7px;height:23px;float:left;} .block .block-div-arrow{background-color:transparent;background-repeat:no-repeat;background-position:right bottom;height:23px;margin-left:7px;} .block fieldset{margin:0;padding:0 1.3em;border:0;background-color:transparent;} .box { max-width:600px; position:relative; z-index:5; } .box-top-left{background:transparent url(images/box.png) no-repeat left top;padding-left:7px;} .box-top-right{background:transparent url(images/box.png) no-repeat right top;height:7px;} .box-main{background:transparent url(images/box.png) no-repeat left bottom;padding-left:7px;} .box-main .box-content{background:transparent url(images/box.png) no-repeat right bottom;padding:10px 7px 10px 0;} .box a{color:#4E4E4E;} .box .tag-cloud{text-align:justify;line-height:150%;} .box .tag-cloud a{vertical-align:middle;text-decoration:none;padding:0 0.2em;letter-spacing:-0.02em;color:#ccc;text-shadow:#000 1px 1px 1px;} .tag-cloud a:hover{background-color:#dde90d;color:#000;text-shadow:rgba(0,0,0,0.6) 1px 1px 1px;} .sidebar-tabs{position:relative;padding-top:44px;} ul.box-tabs, ul.box-tabs li{padding:0;margin:0;line-height:100%;list-style-type:none;background:none;} ul.box-tabs{position:absolute;right:6px;top:0;z-index:10;height:50px;overflow:hidden;} ul.box-tabs li{float:right;margin-right:3px;} ul.box-tabs li a{width:43px;height:50px;display:block;background:transparent url(images/box-tabs.png) no-repeat left top;} ul.box-tabs li.categories a{background-position:0px 0px;} ul.box-tabs li.popular a{background-position:-43px 0px;} ul.box-tabs li.recentcomm a{background-position:-86px 0px;} ul.box-tabs li.tags a{background-position:-129px 0px;} ul.box-tabs li.archives a{background-position:-172px 0px;} ul.box-tabs li a:hover{height:43px;} ul.box-tabs li.active a:hover{height:50px;} ul.box-tabs li.categories.active a,ul.box-tabs li.categories a:hover{background-position:0px -50px;} ul.box-tabs li.popular.active a,ul.box-tabs li.popular a:hover{background-position:-43px -50px;} ul.box-tabs li.recentcomm.active a,ul.box-tabs li.recentcomm a:hover{background-position:-86px -50px;} ul.box-tabs li.tags.active a,ul.box-tabs li.tags a:hover{background-position:-129px -50px;} ul.box-tabs li.archives.active a,ul.box-tabs li.archives a:hover{background-position:-172px -50px;} ul.box-tabs li a span{display:none;} /* menu list */ .box ul.menuList,.box ul.menuList li{margin:0;padding:0;list-style-type:none;font-size:100%;} .box ul.menuList{background:transparent url(images/dot2.gif) repeat-x left bottom;margin-bottom:.6em;padding-bottom:2px;} .box ul.menuList li{background:transparent url(images/dot2.gif) repeat-x left top;display:block;padding:2px 0 0px;} .box ul.menuList li li{background-image:none;} .box ul.menuList li a{display:block;text-decoration:none;padding:3px 25px 3px 0;color:#ccc;} .box ul.menuList.categories li a{padding-right:25px;} /* rss icon space */ .box ul.menuList li a:hover{color:#fff;} .box ul.menuList li a span.entry{background:transparent url(images/icons.png) no-repeat 4px -816px;padding-left:18px;display:block;font-weight:bold;} .box ul.menuList li a span.entry .details{font-weight:normal;font-style:italic;display:block;} .box ul.menuList li a span.entry .details.inline{display:inline;} .box ul.menuList li a:hover span.entry{background-position:4px -1005px;} .box ul.menuList li li a span.entry{background:none;} .box ul.menuList .fadeThis{position:relative;z-index:1;} .box ul.menuList span.hover{position:absolute;top:0;left:0;display:block;height:100%;width:100%;background-color:#747474;z-index:-1;padding:0!important;} /* sub menus */ .box ul.menuList ul{margin:0 0 1em 0;padding:0;} .box ul.menuList li li{margin:0 0 0 1.8em;padding:0;float:none;background:none;width:auto;} .box ul.menuList li li li{margin-left:1em;} .box ul.menuList li li a{text-transform:none;padding:0;font-size:100%;font-style:italic;} .box ul.menuList li li a:hover{background:none;} /* rss popups */ .box ul.menuList li.cat-item{position:relative;} .box ul.menuList li.cat-item a.rss{position:absolute;padding:0;margin:0;display:none;background:transparent url(images/icons.png) no-repeat center -664px;width:24px;height:22px;top:0;right:6px;z-index:10;cursor:pointer;} .box ul.menuList li.cat-item li.cat-item a.rss{background:none;visibility:hidden;} .box ul.menuList li li .fadeThis{position:static;background:none;} .box ul.menuList li li .fadeThis span.hover{display:none;} .box ul.menuList.recentcomm li a span.entry,.box ul.menuList.recentcomm li a:hover span.entry{background:none;padding-left:0px;margin-left:40px;} .box ul.menuList.recentcomm li .avatar{ float: left; margin: 2px 4px 2px 0; } /*** FOOTER ***/ #footer{ background: #fff; } /* block slider */ #footer-blocks{position:relative;margin:0 auto 1em auto;} #footer-blocks.withSlider{width:940px;} #footer-blocks .leftFade,#footer-blocks .rightFade{background:transparent url(images/bg-trans2.png) repeat-y left top;position:absolute;width:46px;min-height:100%;height:100%;/* <- for opera */top:0;z-index:10;} #footer-blocks .leftFade{left:0;} #footer-blocks .rightFade{background-position:right top;right:0;} .slide-container{width:100%;overflow:hidden;position:relative;margin:0 auto;} ul.slides{position:relative;top:0;left:0;list-style-type:none;margin:0;padding:0;width:100%;min-height:100%;display:block;} #footer-blocks .slide-navigation a.next,#footer-blocks .slide-navigation a.previous{background:transparent url(images/block-nav.png) no-repeat left top;width:30px;height:42px;position:absolute;z-index:12;top:60px;} #footer-blocks .slide-navigation a.next{background-position:right top;right:0;} #footer-blocks .slide-navigation a.previous{left:0;} #footer-blocks .slide-navigation a.next:hover{background-position:right bottom;} #footer-blocks .slide-navigation a.previous:hover{background-position:left bottom;} #footer-blocks .slide-navigation a.next span,#footer-blocks .slide-navigation a.previous span{display:none;} ul.slides li.slide{list-style-type:none;position:relative;top:0;margin:0;padding:1em 0 0;display:block;} /* only hide if slider is enabled (it is if there are more than 3 blocks) */ .withSlider ul.slides li.slide.page-content{position:absolute;display:none;width:940px;} #footer-blocks ul.slides li.slide .slide-content{width:95%;margin:0 auto;} ul.slides li.slide .slide-content ul.blocks,#footer-blocks ul.slides li.slide .slide-content ul.blocks li.block{list-style-type:none;margin:0;padding:0;} ul.slides li.slide .slide-content ul.blocks li.block{width:33%;float:left;margin:0;padding:0;position:relative;} ul.slides li.slide .slide-content ul.blocks li.block .block-content{padding:0 .8em;} /* block width based on widget number (default block width is 30% + spacing, 3 blocks per slide) */ ul.slides li.slide .slide-content ul.blocks.widgetcount-1 li.block{width:100%;} ul.slides li.slide .slide-content ul.blocks.widgetcount-2 li.block{width:50%;} ul.slides li.slide .slide-content ul.blocks.widgetcount-3 li.block{width:33%;} ul.slides li.slide .slide-content ul.blocks.widgetcount-4 li.block{width:25%;} ul.slides li.slide .slide-content ul.blocks.widgetcount-4 li.block .block-content{padding:0 .6em;} ul.slides li.slide .slide-content ul.blocks.widgetcount-5 li.block{width:20%;} ul.slides li.slide .slide-content ul.blocks.widgetcount-5 li.block .block-content{padding:0 .5em;} ul.slides li.slide .slide-content ul.blocks.widgetcount-6 li.block{width:16.6%;} ul.slides li.slide .slide-content ul.blocks.widgetcount-6 li.block .block-content{padding:0 .4em;} ul.slides li.slide .slide-content ul.blocks li.block h4.title{font-size:160%;font-weight:bold;background:#eee url(images/bg-lightgray.png) no-repeat left top;padding:.4em .6em;margin:0 0 .2em;text-shadow:#fff 1px 1px 1px;line-height:100%;color:#797979;position:relative;} ul.slides li.slide.slide-2, ul.slides li.slide.slide-3, ul.slides li.slide.slide-4, ul.slides li.slide.slide-5, ul.slides li.slide.slide-6, ul.slides li.slide.slide-7, ul.slides li.slide.slide-8{display:none;} /* copyright & other info */ #footer #copyright { display:block; padding:1em 2em; text-align:center; border-top:1px solid #ddd; line-height:200%; overflow:hidden; } #footer a.rss-subscribe { padding:4px 8px 4px 28px; background:#666 url(images/icons.png) no-repeat 2px -666px; color:#fff; text-decoration:none; text-transform:uppercase; font-weight:bold; margin-right:2px; } #footer a.valid-xhtml,#footer a.valid-css,#footer a#goTop{ padding:4px 8px 4px 8px; color:#fff; background-color:#666; text-decoration:none; text-transform:uppercase; font-weight:bold; margin-right:2px; } /*** BLOCKS ***/ /* info */ .block-info{font-size: 150%;font-weight:bold;text-align:center;padding: .3em .7em;background-color:#eee;text-shadow:#fff 1px 1px 1px;border:1px solid #fff;} /* increase right padding to fit rss icon */ .block-categories ul.menuList.linkBased li a span.entry{display:block;text-decoration:none;padding-right:36px;} /* twitter */ .block-twitter ul, .block-twitter ul li{padding:0;margin:0;list-style-type:none;} .block-twitter ul{background:transparent url(images/dot.gif) repeat-x left top;padding-top:.2em;} .block-twitter ul li,.block-twitter ul li:hover{background:transparent url(images/dot.gif) repeat-x left bottom;margin-bottom:.2em;padding-bottom:.2em;} .block-twitter ul li span.entry{background:transparent url(images/icons.png) no-repeat 6px -383px;padding-left:24px;display:block;} .block-twitter div.avatar{float:left;display:block;margin-left:10px;} .block-twitter div.info{float:left;display:block;padding:2px 0 0 10px;line-height:175%;font-weight:bold;} .block-twitter div.info .followers{font-size:125%;} .block-twitter a.date{color:#bbb;text-decoration:none;font-style:italic;font-size:85%;display:block;} .block-twitter a.date:hover{color:#ed1e24;} .block-twitter .links{text-align:right;background:transparent url(images/bg-trans.png) repeat-x left bottom;padding-right:1em;} .block-twitter a.followMe{position:absolute;background:transparent url(images/twitter.png) no-repeat center top;width:45px;height:57px;display:block;top:-14px;right:20px;z-index:4;} .block-twitter a.followMe span{display:none;} .block-twitter h3.title span{padding-right:60px;} .block-twitter .loading{background:transparent url(images/loader-white.gif) no-repeat 6px 6px;padding:6px 10px 6px 28px;float:left;} /* flickr */ .block-flickr h3.title{position:relative;} .block-flickr h3.title span{padding-left:42px;} .block-flickr h3.title span.icon{background:transparent url(images/flickr.png) no-repeat left top;top:30%;left:0;position:absolute;width:37px;height:17px;padding:0;} .block-flickr ul,.block-flickr ul li{list-style-type:none;padding:0;margin:0;} .block-flickr li{float:left;} .block-flickr li a{padding:0 2px;display:block;} .block-flickr li img{border:5px solid #eee;} .block-flickr .flickrGallery{padding-left:4px;} /* login */ .block-login .avatar img{border:6px solid #ddd;} /*** MISC ***/ /* lightbox */ div#fancyoverlay{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;display:none;z-index:30;} div#fancywrap{text-align:left;} div#fancyloading{position:absolute;height:40px;width:40px;cursor:pointer;display:none;overflow:hidden;background:transparent;z-index:100;} div#fancyloading div{position:absolute;top:0;left:0;width:40px;height:480px;background:transparent url(images/loader.gif) no-repeat;} div#fancyloadingoverlay{position:absolute;background-color:#FFF;z-index:30;} div#fancyouter{position:absolute;top:0;left:0;z-index:90;padding:18px 18px 33px;margin:0;overflow:hidden;background:transparent;display:none;} div#fancyinner{position:relative;width:100%;height:100%;background-color:#eee;-moz-box-shadow:0px 0px 20px rgba(0,0,0,0.85);-moz-border-radius:8px;-webkit-box-shadow:0px 0px 20px rgba(0,0,0,0.85);-webkit-border-radius:8px;box-shadow:0px 0px 20px rgba(0,0,0,0.85);border-radius:8px;} div#fancycontent{margin:0;z-index:100;position:absolute;} div#fancydiv{background-color:#000;color:#fff;height:100%;width:100%;z-index:100;} img#fancyimg{position:absolute;top:0;left:0;border:0;padding:0;margin:0;z-index:100;width:100%;height:100%;} #fancyframe{position:relative;width:100%;height:100%;display:none;} #fancyajax{width:100%;height:100%;overflow:auto;} a#fancyleft,a#fancyright{position:absolute;bottom:0;height:100%;width:35%;cursor:pointer;z-index:111;display:none;outline:none;} a#fancyleft{left:0;} a#fancyright{right:0;} span.fancyico{position:absolute;top:50%;margin-top:-15px;width:30px;height:42px;z-index:112;cursor:pointer;display:block;opacity:0.5;} span#fancyleftico{left:-9999px;background:transparent url(images/block-nav.png) no-repeat left top;} span#fancyrightico{right:-9999px;background:transparent url(images/block-nav.png) no-repeat right top;} a#fancyleft:hover{visibility:visible;} a#fancyright:hover{visibility:visible;} a#fancyleft:hover span{left:20px;} a#fancyright:hover span{right:20px;} .fancybigIframe{position:absolute;top:0;left:0;width:100%;height:100%;background:transparent;} div#fancytitle{width:100%;z-index:100;display:none;background-color:#4e4e4e;color:#fff;text-align:center;font-weight:bold;font-size:150%;padding:.2em 0;} /* page controls */ #pageControls{position:absolute;right:0;top:0;width:25%;height:100px;z-index:4;} #pageControls a{background:transparent url(images/page-controls.png) no-repeat right top;position:absolute;width:22px;height:21px;right:10px;top:10px;cursor:pointer;z-index:15;} #pageControls a:hover{background-position:right bottom;} #pageControls a.fontSize{background-position:left top;right:36px;} #pageControls a.fontSize:hover{background-position:left bottom;} /* other */ .clearFieldBlurred{color:#ccc;font-style:italic;font-weight:normal;} .clearFieldActive{color:#4e4e4e;font-weight:bold;} .error{color:#ed1e24;} .success{color:#a0c207;} .divider{padding:1em 0 0 0;display:block;background:transparent url(images/dot.gif) repeat-x left bottom;height:2px;min-height:2px;} .altText{font-style:italic;} .highlight{background-color: #FFE4B5;} /* clearfix */ .clearfix:after{content:".";display:block;clear:both;visibility:hidden;line-height:0;height:0;} img.alignleft,img.alignright{padding:3px;margin-top:4px;margin-bottom:4px;border-radius:4px;} .alignleft{float:left;margin-right:8px;} .alignright{float:right;margin-left:8px;} .aligncenter{display:block;margin-left:auto;margin-right:auto;text-align:center;} .bubble-trigger{position:relative;} .bubble{display:none;position:absolute;z-index:10;} /* jquery caption - to do */ .imgCaption{position:relative;overflow:hidden;padding:0;border:0;margin-top:8px;margin-bottom:8px;display:inline-block;} .imgCaption p{position:absolute;background-color:#000;color:#fff;width:100%;font-weight:bold;padding:0;margin:0;line-height:150%;text-align:center;border:0;z-index:10;left:0;opacity:0.6;} .imgCaption p span{ padding:12px;display:block;} .wp-caption{border: 1px solid #ddd;text-align:center;background-color:#f3f3f3;padding-top:4px;margin-top:10px;margin-bottom:10px;-moz-border-radius:3px;-khtml-border-radius:3px;-webkit-border-radius:3px;border-radius:3px;} .wp-caption img{margin:0;padding:0;border:0 none;} .wp-caption-dd{font-size:11px;line-height:17px;padding:0 4px 5px;margin:0;} .webshot{position:absolute;left:-20000px;background-color:rgba(0,0,0,0.4);padding:5px;z-index:10;display:none;-moz-box-shadow:0px 0px 8px rgba(0,0,0,0.4);-webkit-box-shadow:0px 0px 8px rgba(0,0,0,0.4);box-shadow:0px 0px 8px rgba(0,0,0,0.4);} .webshot img{margin:0;padding:0;} /* smiley adjustment */ img.wp-smiley{vertical-align:-15%;} /* tabs (code inspired by smashing magazine's comment tabs */ ul.tabs li a{} ul.tabs li a:hover{} .tabbed-content div.sections{position:relative;overflow:hidden;} .tabbed-content div.section{position:relative;display:none;} .tabbed-content div.section h6.title{font-size:115%;font-weight:normal;font-style:italic;text-transform:uppercase;margin:0;padding:0;} .tabs,.tabs li{margin:0;padding:0;list-style-type:none;} .tabs-wrap{padding-bottom:30px;background-color:transparent;background-repeat:no-repeat;background-position:left 34px;margin:2em 0 .4em 0;} .tabs{list-style:none;overflow:hidden;height:34px;position:relative;text-transform:uppercase;padding-right:12px;} .tabs li{float:right;text-align:center;height:31px;background-color:transparent;background-repeat:no-repeat;background-position:right top;margin-right:-20px;padding-right:24px;margin-top:4px;position:relative;z-index:0;bottom:-4px;/* <-for the animation */line-height:28px;} .tabs li a{height:31px;color:#4e4e4e;float:left;text-decoration:none;text-shadow:#fff 1px 1px 1px;font-weight:bold;background-color:transparent;background-repeat:no-repeat;background-position:left top;padding-left:26px;padding-right:4px;} .tabs li:hover{background-position:right -66px;} .tabs li:hover a,.tabs li a:hover{background-position:0 -66px;} .tabs li.active{background-position:100% -33px;z-index:8;padding-right:24px;} .tabs li.active a,.tabs li.active a:hover{background-position:0 -33px;color:#fff;text-shadow:rgba(0,0,0,0.4) 1px 1px 1px;} a.js-link{cursor:pointer;text-decoration:underline;} a.js-link:hover{text-decoration:none;} .hidden{display:none;} /* form container */ div.form{width:50%;} #sidebar div.form,#footer div.form{width:100%;} /* full width if there's only one widget in the footer */ #footer ul.slides li.slide .slide-content ul.blocks.widgetcount-1 div.form{width:50%;} div.form .error{font-weight:bold;} div.form fieldset{margin:0;padding:0;background:transparent;border:0;} /*** WORDPRESS: SUPPORT FOR OTHER WIDGETS ***/ /* tag cloud */ .block-widget_tag_cloud{text-align:justify;line-height:150%;} .block-widget_tag_cloud a{vertical-align:middle;text-decoration:none;padding:0 0.2em;letter-spacing:-0.02em;color:#666;} .block-widget_tag_cloud a:hover{background-color:#dde90d;color:#000;} /* calendar */ table#wp-calendar{width:100%;padding:0;margin:0;} table#wp-calendar td,table#wp-calendar th{text-align:center;padding:2px;} table#wp-calendar th{font-weight:bold;font-size:125%;} table#wp-calendar caption{font-style:italic;text-align:right;} .post-ratings{font-style:italic;font-size:85%;} .post-ratings img{vertical-align:-10%;} .post-ratings span.post-ratings-text{display:none !important;} /*** PRINT STYLES ***/ @media print { body{background:white;color:black;font-size:10pt} .header-wrapper{display:none;} .shadow-left.main-wrapper,.main-wrapper .shadow-right,#main,#main-inside{background:none;} #main{background-color:#fff;} .page-content{width:100% !important;max-width:none !important;min-width:0 !important;} #footer-blocks .leftFade,#footer-blocks .rightFade{display:none;} } .block ul { padding:0px; } ul.menu li { margin:0px; } li.leaf { list-style-image:none; list-style-type:none; } li.collapsed { list-style-image:none; list-style-type:none; } li.expanded { list-style-image:none; list-style-type:none; } li a.active { color:#0071BB; } .item-list ul li { list-style-image: none; list-style-type:none; margin:none; padding:0 0 0 18px; margin:0px; text-align:left; } .with-tabs { clear:both; margin-top:-20px; width:100%; } li.sfHover { background-color:#FFFFFF !important; } #copyright div.block{ width:225px; float:left; margin:5px; } div.attribution { width:100%; float:left; } div.footer_icon { width:100%; float:left; } .footer_content { } .footer_icon div { } div.author div.links { //width:130px; } div.author div.links ul { text-align:right; } div.author div.links ul li { margin:0px; } span.submitted { } div.theme-info h2 { font-size:100%; } div.theme-info div.description { font-size:75%; } div.logo { text-align:right; } div.links ul li { margin: 0px; } div.messages { padding: 10px; }
dkgndec/snehi
themes/mystique_theme/style.css
CSS
gpl-2.0
44,170
<?php /** * @package Admin */ if ( ! defined( 'WPSEO_VERSION' ) ) { header( 'Status: 403 Forbidden' ); header( 'HTTP/1.1 403 Forbidden' ); exit(); } if ( ! class_exists( 'WPSEO_Bulk_Description_List_Table' ) ) { /** * */ class WPSEO_Bulk_Description_List_Table extends WP_List_Table { /* * Array of post types for which the current user has `edit_others_posts` capabilities. */ private $all_posts; /* * Array of post types for which the current user has `edit_posts` capabilities, but not `edit_others_posts`. */ private $own_posts; /** * */ function __construct() { parent::__construct( array( 'singular' => 'wpseo_bulk_description', 'plural' => 'wpseo_bulk_descriptions', 'ajax' => true, ) ); $this->populate_editable_post_types(); } /* * Used in the constructor to build a reference list of post types the current user can edit. */ private function populate_editable_post_types() { $post_types = get_post_types( array( 'public' => true, 'exclude_from_search' => false ), 'object' ); $this->all_posts = array(); $this->own_posts = array(); if ( is_array( $post_types ) && $post_types !== array() ) { foreach ( $post_types as $post_type ) { if ( ! current_user_can( $post_type->cap->edit_posts ) ) { continue; } if ( current_user_can( $post_type->cap->edit_others_posts ) ) { $this->all_posts[] = esc_sql( $post_type->name ); } else { $this->own_posts[] = esc_sql( $post_type->name ); } } } } /** * @param $which */ function display_tablenav( $which ) { $post_status = ''; if ( ! empty( $_GET['post_status'] ) ) { $post_status = sanitize_text_field( $_GET['post_status'] ); } ?> <div class="tablenav <?php echo esc_attr( $which ); ?>"> <?php if ( 'top' === $which ) { ?> <form id="posts-filter" action="" method="get"> <input type="hidden" name="page" value="wpseo_bulk-description-editor" /> <?php if ( ! empty( $post_status ) ) {?> <input type="hidden" name="post_status" value="<?php echo esc_attr( $post_status ); ?>" /> <?php } ?> <?php } ?> <?php $this->extra_tablenav( $which ); $this->pagination( $which ); ?> <br class="clear" /> <?php if ( 'top' === $which ) { ?> </form> <?php } ?> </div> <?php } /** * This function builds the base sql subquery used in this class. * * This function takes into account the post types in which the current user can * edit all posts, and the ones the current user can only edit his/her own. * * @return string $subquery The subquery, which should always be used in $wpdb->prepare(), passing the current user_id in as the first parameter. */ function get_base_subquery() { global $wpdb; $all_posts_string = "'" . implode( "', '", $this->all_posts ) . "'"; $own_posts_string = "'" . implode( "', '", $this->own_posts ) . "'"; $subquery = "( SELECT * FROM {$wpdb->posts} WHERE post_type IN ({$all_posts_string}) UNION ALL SELECT * FROM {$wpdb->posts} WHERE post_type IN ({$own_posts_string}) AND post_author = %d )sub_base"; return $subquery; } /** * @return array */ function get_views() { global $wpdb; $status_links = array(); $states = get_post_stati( array( 'show_in_admin_all_list' => true ) ); $states['trash'] = 'trash'; $states = esc_sql( $states ); $all_states = "'" . implode( "', '", $states ) . "'"; $subquery = $this->get_base_subquery(); $current_user_id = get_current_user_id(); $total_posts = $wpdb->get_var( $wpdb->prepare( " SELECT COUNT(*) FROM {$subquery} WHERE post_status IN ({$all_states}) ", $current_user_id ) ); $class = empty( $_GET['post_status'] ) ? ' class="current"' : ''; $status_links['all'] = '<a href="' . esc_url( admin_url( 'admin.php?page=wpseo_bulk-description-editor' ) ) . '"' . $class . '>' . sprintf( _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_posts, 'posts', 'wordpress-seo' ), number_format_i18n( $total_posts ) ) . '</a>'; $post_stati = get_post_stati( array( 'show_in_admin_all_list' => true ), 'objects' ); if ( is_array( $post_stati ) && $post_stati !== array() ) { foreach ( $post_stati as $status ) { $status_name = esc_sql( $status->name ); $total = $wpdb->get_var( $wpdb->prepare( " SELECT COUNT(*) FROM {$subquery} WHERE post_status = %s ", $current_user_id, $status_name ) ); if ( $total == 0 ) { continue; } $class = ''; if ( isset( $_GET['post_status'] ) && $status_name == $_GET['post_status'] ) { $class = ' class="current"'; } $status_links[ $status_name ] = '<a href="' . esc_url( admin_url( 'admin.php?page=wpseo_bulk-description-editor&post_status=' . $status_name ) ) . '"' . $class . '>' . sprintf( translate_nooped_plural( $status->label_count, $total ), number_format_i18n( $total ) ) . '</a>'; } } unset( $post_stati, $status, $status_name, $total, $class ); $trashed_posts = $wpdb->get_var( $wpdb->prepare( " SELECT COUNT(*) FROM {$subquery} WHERE post_status IN ('trash') ", $current_user_id ) ); $class = ( isset( $_GET['post_status'] ) && 'trash' == $_GET['post_status'] ) ? 'class="current"' : ''; $status_links['trash'] = '<a href="' . esc_url( admin_url( 'admin.php?page=wpseo_bulk-description-editor&post_status=trash' ) ) . '"' . $class . '>' . sprintf( _nx( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>', $trashed_posts, 'posts', 'wordpress-seo' ), number_format_i18n( $trashed_posts ) ) . '</a>'; return $status_links; } /** * @param $which */ function extra_tablenav( $which ) { if ( 'top' === $which ) { $post_types = get_post_types( array( 'public' => true, 'exclude_from_search' => false ) ); if ( is_array( $post_types ) && $post_types !== array() ) { global $wpdb; echo '<div class="alignleft actions">'; $post_types = esc_sql( $post_types ); $post_types = "'" . implode( "', '", $post_types ) . "'"; $states = get_post_stati( array( 'show_in_admin_all_list' => true ) ); $states['trash'] = 'trash'; $states = esc_sql( $states ); $all_states = "'" . implode( "', '", $states ) . "'"; $subquery = $this->get_base_subquery(); $current_user_id = get_current_user_id(); $post_types = $wpdb->get_results( $wpdb->prepare( " SELECT DISTINCT post_type FROM {$subquery} WHERE post_status IN ({$all_states}) ORDER BY 'post_type' ASC ", $current_user_id ) ); $selected = ! empty( $_GET['post_type_filter'] ) ? sanitize_text_field( $_GET['post_type_filter'] ) : -1; $options = '<option value="-1">Show All Post Types</option>'; if ( is_array( $post_types ) && $post_types !== array() ) { foreach ( $post_types as $post_type ) { $obj = get_post_type_object( $post_type->post_type ); $options .= sprintf( '<option value="%2$s" %3$s>%1$s</option>', $obj->labels->name, $post_type->post_type, selected( $selected, $post_type->post_type, false ) ); } } echo sprintf( '<select name="post_type_filter">%1$s</select>' , $options ); submit_button( __( 'Filter', 'wordpress-seo' ), 'button', false, false, array( 'id' => 'post-query-submit' ) ); echo '</div>'; } } elseif ( 'bottom' === $which ) { } } /** * @return array */ function get_columns() { return $columns = array( 'col_page_title' => __( 'WP Page Title', 'wordpress-seo' ), 'col_post_type' => __( 'Post Type', 'wordpress-seo' ), 'col_post_status' => __( 'Post Status', 'wordpress-seo' ), 'col_page_slug' => __( 'Page URL/Slug', 'wordpress-seo' ), 'col_existing_yoast_seo_metadesc' => __( 'Existing Yoast Meta Description', 'wordpress-seo' ), 'col_new_yoast_seo_metadesc' => __( 'New Yoast Meta Description', 'wordpress-seo' ), 'col_row_action' => __( 'Action', 'wordpress-seo' ), ); } /** * @return array */ function get_sortable_columns() { return $sortable = array( 'col_page_title' => array( 'post_title', true ), 'col_post_type' => array( 'post_type', false ), 'col_existing_yoast_seo_metadesc' => array( 'meta_desc', false ) ); } function prepare_items() { global $wpdb; // Filter Block $post_types = null; $post_type_clause = ''; if ( ! empty( $_GET['post_type_filter'] ) && get_post_type_object( sanitize_text_field( $_GET['post_type_filter'] ) ) ) { $post_types = esc_sql( sanitize_text_field( $_GET['post_type_filter'] ) ); $post_type_clause = "AND post_type IN ('{$post_types}')"; } // Order By block $orderby = ! empty( $_GET['orderby'] ) ? esc_sql( sanitize_text_field( $_GET['orderby'] ) ) : 'post_title'; $order = 'ASC'; if ( ! empty( $_GET['order'] ) ) { $order = esc_sql( strtoupper( sanitize_text_field( $_GET['order'] ) ) ); } $states = get_post_stati( array( 'show_in_admin_all_list' => true ) ); $states['trash'] = 'trash'; if ( ! empty( $_GET['post_status'] ) ) { $requested_state = sanitize_text_field( $_GET['post_status'] ); if ( in_array( $requested_state, $states ) ) { $states = array( $requested_state ); } } $states = esc_sql( $states ); $all_states = "'" . implode( "', '", $states ) . "'"; $subquery = $this->get_base_subquery(); $current_user_id = get_current_user_id(); $query = " SELECT ID, post_title, post_type, meta_value AS meta_desc, post_status, post_modified FROM {$subquery} LEFT JOIN ( SELECT * FROM {$wpdb->postmeta} WHERE meta_key = %s )a ON a.post_id = ID WHERE post_status IN ({$all_states}) $post_type_clause ORDER BY {$orderby} {$order} "; $total_items = $wpdb->query( $wpdb->prepare( $query, $current_user_id, WPSEO_Meta::$meta_prefix . 'metadesc' ) ); $query .= ' LIMIT %d,%d'; $per_page = $this->get_items_per_page( 'wpseo_posts_per_page', 10 ); $paged = ! empty( $_GET['paged'] ) ? esc_sql( sanitize_text_field( $_GET['paged'] ) ) : ''; if ( empty( $paged ) || ! is_numeric( $paged ) || $paged <= 0 ) { $paged = 1; } $total_pages = ceil( $total_items / $per_page ); $offset = ( $paged - 1 ) * $per_page; $this->set_pagination_args( array( 'total_items' => $total_items, 'total_pages' => $total_pages, 'per_page' => $per_page, ) ); $columns = $this->get_columns(); $hidden = array(); $sortable = $this->get_sortable_columns(); $this->_column_headers = array( $columns, $hidden, $sortable ); $this->items = $wpdb->get_results( $wpdb->prepare( $query, $current_user_id, WPSEO_Meta::$meta_prefix . 'metadesc', $offset, $per_page ) ); } function display_rows() { $records = $this->items; list( $columns, $hidden ) = $this->get_column_info(); if ( ( is_array( $records ) && $records !== array() ) && ( is_array( $columns ) && $columns !== array() ) ) { foreach ( $records as $rec ) { echo '<tr id="record_' . $rec->ID . '">'; foreach ( $columns as $column_name => $column_display_name ) { $class = sprintf( 'class="%1$s column-%1$s"', $column_name ); $style = ''; if ( in_array( $column_name, $hidden ) ) { $style = ' style="display:none;"'; } $attributes = $class . $style; switch ( $column_name ) { case 'col_page_title': echo sprintf( '<td %2$s><strong>%1$s</strong>', stripslashes( $rec->post_title ), $attributes ); $post_type_object = get_post_type_object( $rec->post_type ); $can_edit_post = current_user_can( $post_type_object->cap->edit_post, $rec->ID ); $actions = array(); if ( $can_edit_post && 'trash' != $rec->post_status ) { $actions['edit'] = '<a href="' . esc_url( get_edit_post_link( $rec->ID, true ) ) . '" title="' . esc_attr( __( 'Edit this item', 'wordpress-seo' ) ) . '">' . __( 'Edit', 'wordpress-seo' ) . '</a>'; } if ( $post_type_object->public ) { if ( in_array( $rec->post_status, array( 'pending', 'draft', 'future' ) ) ) { if ( $can_edit_post ) { $actions['view'] = '<a href="' . esc_url( add_query_arg( 'preview', 'true', get_permalink( $rec->ID ) ) ) . '" title="' . esc_attr( sprintf( __( 'Preview &#8220;%s&#8221;', 'wordpress-seo' ), $rec->post_title ) ) . '">' . __( 'Preview', 'wordpress-seo' ) . '</a>'; } } elseif ( 'trash' != $rec->post_status ) { $actions['view'] = '<a href="' . esc_url( get_permalink( $rec->ID ) ) . '" title="' . esc_attr( sprintf( __( 'View &#8220;%s&#8221;', 'wordpress-seo' ), $rec->post_title ) ) . '" rel="bookmark">' . __( 'View', 'wordpress-seo' ) . '</a>'; } } echo $this->row_actions( $actions ); echo '</td>'; break; case 'col_page_slug': $permalink = get_permalink( $rec->ID ); $display_slug = str_replace( get_bloginfo( 'url' ), '', $permalink ); echo sprintf( '<td %2$s><a href="%3$s" target="_blank">%1$s</a></td>', stripslashes( $display_slug ), $attributes, esc_url( $permalink ) ); break; case 'col_post_type': $post_type = get_post_type_object( $rec->post_type ); echo sprintf( '<td %2$s>%1$s</td>', $post_type->labels->singular_name, $attributes ); break; case 'col_post_status': $post_status = get_post_status_object( $rec->post_status ); echo sprintf( '<td %2$s>%1$s</td>', $post_status->label, $attributes ); break; case 'col_existing_yoast_seo_metadesc': echo sprintf( '<td %2$s id="wpseo-existing-metadesc-%3$s">%1$s</td>', ( ($rec->meta_desc ) ? $rec->meta_desc : '' ), $attributes, $rec->ID ); break; case 'col_new_yoast_seo_metadesc': $input = sprintf( '<textarea id="%1$s" name="%1$s" class="wpseo-new-metadesc" data-id="%2$s"></textarea>', 'wpseo-new-metadesc-' . $rec->ID, $rec->ID ); echo sprintf( '<td %2$s>%1$s</td>', $input , $attributes ); break; case 'col_row_action': $actions = sprintf( '<a href="#" class="wpseo-save" data-id="%1$s">Save</a> | <a href="#" class="wpseo-save-all">Save All</a>', $rec->ID ); echo sprintf( '<td %2$s>%1$s</td>', $actions , $attributes ); break; } } echo '</tr>'; } } } } /* End of class */ } /* End of class-exists wrapper */
emergugue/ff2014
wp-content/plugins/wordpress-seo/admin/class-bulk-description-editor-list-table.php
PHP
gpl-2.0
15,087
/* Copyright (c) 2008-2012, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #ifndef MSM_FB_H #define MSM_FB_H #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/init.h> #include <linux/interrupt.h> #include "linux/proc_fs.h" #include <mach/hardware.h> #include <linux/io.h> #include <mach/board.h> #include <asm/system.h> #include <asm/mach-types.h> #include <mach/memory.h> #include <linux/semaphore.h> #include <linux/spinlock.h> #include <linux/workqueue.h> #include <linux/hrtimer.h> #include <linux/fb.h> #include <linux/list.h> #include <linux/types.h> #include <linux/msm_mdp.h> #ifdef CONFIG_HAS_EARLYSUSPEND #include <linux/earlysuspend.h> #endif #include "msm_fb_panel.h" #include "mdp.h" #define MSM_FB_DEFAULT_PAGE_SIZE 2 #define MFD_KEY 0x11161126 #define MSM_FB_MAX_DEV_LIST 32 struct disp_info_type_suspend { boolean op_enable; boolean sw_refreshing_enable; boolean panel_power_on; boolean op_suspend; }; struct msmfb_writeback_data_list { struct list_head registered_entry; struct list_head active_entry; void *addr; struct ion_handle *ihdl; struct file *pmem_file; struct msmfb_data buf_info; struct msmfb_img img; int state; }; struct msm_fb_data_type { __u32 key; __u32 index; __u32 ref_cnt; __u32 fb_page; panel_id_type panel; struct msm_panel_info panel_info; DISP_TARGET dest; struct fb_info *fbi; struct delayed_work backlight_worker; boolean op_enable; uint32 fb_imgType; boolean sw_currently_refreshing; boolean sw_refreshing_enable; boolean hw_refresh; #ifdef CONFIG_FB_MSM_OVERLAY int overlay_play_enable; #endif MDPIBUF ibuf; boolean ibuf_flushed; struct timer_list refresh_timer; struct completion refresher_comp; boolean pan_waiting; struct completion pan_comp; /* vsync */ boolean use_mdp_vsync; __u32 vsync_gpio; __u32 total_lcd_lines; __u32 total_porch_lines; __u32 lcd_ref_usec_time; __u32 refresh_timer_duration; struct hrtimer dma_hrtimer; boolean panel_power_on; struct work_struct dma_update_worker; struct semaphore sem; struct timer_list vsync_resync_timer; boolean vsync_handler_pending; struct work_struct vsync_resync_worker; ktime_t last_vsync_timetick; __u32 *vsync_width_boundary; unsigned int pmem_id; struct disp_info_type_suspend suspend; __u32 channel_irq; struct mdp_dma_data *dma; struct device_attribute dev_attr; void (*dma_fnc) (struct msm_fb_data_type *mfd); int (*cursor_update) (struct fb_info *info, struct fb_cursor *cursor); int (*lut_update) (struct fb_info *info, struct fb_cmap *cmap); int (*do_histogram) (struct fb_info *info, struct mdp_histogram_data *hist); int (*start_histogram) (struct mdp_histogram_start_req *req); int (*stop_histogram) (struct fb_info *info, uint32_t block); void (*vsync_ctrl) (int enable); void (*vsync_init) (int cndx); void *vsync_show; void *cursor_buf; void *cursor_buf_phys; void *cmd_port; void *data_port; void *data_port_phys; __u32 bl_level; struct platform_device *pdev; __u32 var_xres; __u32 var_yres; __u32 var_pixclock; __u32 var_frame_rate; #ifdef MSM_FB_ENABLE_DBGFS struct dentry *sub_dir; #endif #ifdef CONFIG_HAS_EARLYSUSPEND struct early_suspend early_suspend; #ifdef CONFIG_FB_MSM_MDDI struct early_suspend mddi_early_suspend; struct early_suspend mddi_ext_early_suspend; #endif #endif u32 mdp_fb_page_protection; struct clk *ebi1_clk; boolean dma_update_flag; struct timer_list msmfb_no_update_notify_timer; struct completion msmfb_update_notify; struct completion msmfb_no_update_notify; struct mutex writeback_mutex; struct mutex unregister_mutex; struct list_head writeback_busy_queue; struct list_head writeback_free_queue; struct list_head writeback_register_queue; wait_queue_head_t wait_q; struct ion_client *iclient; unsigned long display_iova; unsigned long rotator_iova; struct mdp_buf_type *ov0_wb_buf; struct mdp_buf_type *ov1_wb_buf; u32 ov_start; u32 mem_hid; u32 mdp_rev; u32 writeback_state; bool writeback_active_cnt; int cont_splash_done; void *cpu_pm_hdl; u32 acq_fen_cnt; struct sync_fence *acq_fen[MDP_MAX_FENCE_FD]; int cur_rel_fen_fd; struct sync_pt *cur_rel_sync_pt; struct sync_fence *cur_rel_fence; struct sync_fence *last_rel_fence; struct sw_sync_timeline *timeline; int timeline_value; u32 last_acq_fen_cnt; struct sync_fence *last_acq_fen[MDP_MAX_FENCE_FD]; struct mutex sync_mutex; struct completion commit_comp; u32 is_committing; struct work_struct commit_work; void *msm_fb_backup; boolean panel_driver_on; int vsync_sysfs_created; }; struct msm_fb_backup_type { struct fb_info info; struct mdp_display_commit disp_commit; }; struct dentry *msm_fb_get_debugfs_root(void); void msm_fb_debugfs_file_create(struct dentry *root, const char *name, u32 *var); void msm_fb_set_backlight(struct msm_fb_data_type *mfd, __u32 bkl_lvl); struct platform_device *msm_fb_add_device(struct platform_device *pdev); struct fb_info *msm_fb_get_writeback_fb(void); int msm_fb_writeback_init(struct fb_info *info); int msm_fb_writeback_start(struct fb_info *info); int msm_fb_writeback_queue_buffer(struct fb_info *info, struct msmfb_data *data); int msm_fb_writeback_dequeue_buffer(struct fb_info *info, struct msmfb_data *data); int msm_fb_writeback_stop(struct fb_info *info); int msm_fb_writeback_terminate(struct fb_info *info); int msm_fb_detect_client(const char *name); int calc_fb_offset(struct msm_fb_data_type *mfd, struct fb_info *fbi, int bpp); int msm_fb_wait_for_fence(struct msm_fb_data_type *mfd); int msm_fb_signal_timeline(struct msm_fb_data_type *mfd); #ifdef CONFIG_FB_BACKLIGHT void msm_fb_config_backlight(struct msm_fb_data_type *mfd); #endif void fill_black_screen(bool on, uint8 pipe_num, uint8 mixer_num); int msm_fb_check_frame_rate(struct msm_fb_data_type *mfd, struct fb_info *info); #ifdef CONFIG_FB_MSM_LOGO #define INIT_IMAGE_FILE "/initlogo.rle" int load_565rle_image(char *filename, bool bf_supported); #endif #endif /* MSM_FB_H */
thicklizard/komodo_ville
drivers/video/msm/msm_fb.h
C
gpl-2.0
6,518
# -*- coding: utf-8 -*- # MouseTrap # # Copyright 2009 Flavio Percoco Premoli # # This file is part of mouseTrap. # # MouseTrap is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License v2 as published # by the Free Software Foundation. # # mouseTrap 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 mouseTrap. If not, see <http://www.gnu.org/licenses/>. """ Common MouseTrap Functions. """ __id__ = "$Id$" __version__ = "$Revision$" __date__ = "$Date$" __copyright__ = "Copyright (c) 2008 Flavio Percoco Premoli." __license__ = "GPLv2" import os import re def get_py_list(dirlist): """ Checks for .py files on directories in dirlist and removes the extensions. Arguments: - dirlist: The directories list. """ if not type(dirlist) is list: dirlist = [dirlist] reg = re.compile(r'([A-Za-z0-9]+)\.py$', re.DOTALL) group = [] for dir in dirlist: if not os.path.isdir(dir): continue group.append([ mod[0] for mod in [ reg.findall(f) for f in os.listdir("%s/" % dir) if "handler" not in f] if mod ]) return [] + [x for l in group for x in l]
lhotchkiss/mousetrap
src/mousetrap/app/commons.py
Python
gpl-2.0
1,477
<?php /** * OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures * all the essential functionalities required for any enterprise. * Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com * * OrangeHRM 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. * * OrangeHRM 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 * */ class LocationForm extends BaseForm { public $locationId; private $locationService; private $countryService; public $edited = false; /** * Returns Country Service * @returns CountryService */ public function getCountryService() { if (is_null($this->countryService)) { $this->countryService = new CountryService(); } return $this->countryService; } public function getLocationService() { if (is_null($this->locationService)) { $this->locationService = new LocationService(); $this->locationService->setLocationDao(new LocationDao()); } return $this->locationService; } public function configure() { $this->locationId = $this->getOption('locationId'); $countries = $this->getCountryList(); $states = $this->getStatesList(); $this->setWidgets(array( 'locationId' => new sfWidgetFormInputHidden(), 'name' => new sfWidgetFormInputText(array(), array('class' => 'formInput')), 'country' => new sfWidgetFormSelect(array('choices' => $countries), array('class' => 'formInput')), 'state' => new sfWidgetFormSelect(array('choices' => $states), array('class' => 'formInput')), 'province' => new sfWidgetFormInputText(array(), array('class' => 'formInput')), 'city' => new sfWidgetFormInputText(array(), array('class' => 'formInput')), 'address' => new sfWidgetFormTextArea(array(), array('class' => 'formInput')), 'zipCode' => new sfWidgetFormInputText(array(), array('class' => 'formInput')), 'phone' => new sfWidgetFormInputText(array(), array('class' => 'formInput')), 'fax' => new sfWidgetFormInputText(array(), array('class' => 'formInput')), 'notes' => new sfWidgetFormTextArea(array(), array('class' => 'formInput')), )); $this->setValidators(array( 'locationId' => new sfValidatorNumber(array('required' => false)), 'name' => new sfValidatorString(array('required' => true, 'max_length' => 102)), 'country' => new sfValidatorString(array('required' => true, 'max_length' => 3)), 'state' => new sfValidatorString(array('required' => false, 'max_length' => 52)), 'province' => new sfValidatorString(array('required' => false, 'max_length' => 52)), 'city' => new sfValidatorString(array('required' => false, 'max_length' => 52)), 'address' => new sfValidatorString(array('required' => false, 'max_length' => 256)), 'zipCode' => new sfValidatorString(array('required' => false, 'max_length' => 32)), 'phone' => new sfValidatorString(array('required' => false, 'max_length' => 32)), 'fax' => new sfValidatorString(array('required' => false, 'max_length' => 32)), 'notes' => new sfValidatorString(array('required' => false, 'max_length' => 256, 'trim' => true)), )); $this->widgetSchema->setNameFormat('location[%s]'); if ($this->locationId != null) { $this->setDefaultValues($this->locationId); } $this->getWidgetSchema()->setLabels($this->getFormLabels()); } private function setDefaultValues($locationId) { $location = $this->getLocationService()->getLocationById($this->locationId); $this->setDefault('locationId', $locationId); $this->setDefault('name', $location->getName()); $this->setDefault('country', $location->getCountryCode()); if($location->getCountryCode() == 'US') { $this->setDefault('state', $location->getProvince()); } else { $this->setDefault('province', $location->getProvince()); } $this->setDefault('city', $location->getCity()); $this->setDefault('address', $location->getAddress()); $this->setDefault('zipCode', $location->getZipCode()); $this->setDefault('phone', $location->getPhone()); $this->setDefault('fax', $location->getFax()); $this->setDefault('notes', $location->getNotes()); } /** * Returns Country List * @return array */ private function getCountryList() { $list = array("" => "-- " . __('Select') . " --"); $countries = $this->getCountryService()->getCountryList(); foreach ($countries as $country) { $list[$country->cou_code] = $country->cou_name; } return $list; } /** * Returns States List * @return array */ private function getStatesList() { $list = array("" => "-- " . __('Select') . " --"); $states = $this->getCountryService()->getProvinceList(); foreach ($states as $state) { $list[$state->province_code] = $state->province_name; } return $list; } public function save() { $locationId = $this->getValue('locationId'); if(empty($locationId)){ $location = new Location(); } else { $this->edited = true; $location = $this->getLocationService()->getLocationById($locationId); } $location->setName($this->getValue('name')); $country = $this->getValue('country'); $location->setCountryCode($country); if ($country == 'US') { $location->setProvince($this->getValue('state')); } else { $location->setProvince($this->getValue('province')); } $location->setCity($this->getValue('city')); $location->setAddress($this->getValue('address')); $location->setZipCode($this->getValue('zipCode')); $location->setPhone($this->getValue('phone')); $location->setFax($this->getValue('fax')); $location->setNotes($this->getValue('notes')); $location->save(); return $location->getId(); } public function getLocationListAsJson() { $list = array(); $locationList = $this->getLocationService()->getLocationList(); foreach ($locationList as $location) { $list[] = array('id' => $location->getId(), 'name' => $location->getName()); } return json_encode($list); } /** * * @return string */ public function getFormLabels() { $requiredMarker = ' <em>*</em>'; $labels = array( 'name' => __('Name') . $requiredMarker, 'country' => __('Country') . $requiredMarker, 'state' => __('State'), 'province' => __('State/Province'), 'city' => __('City'), 'address' => __('Address'), 'zipCode' => __('Zip/Postal Code'), 'phone' => __('Phone'), 'fax' => __('Fax'), 'notes' => __('Notes'), ); return $labels; } } ?>
monokal/docker-orangehrm
www/symfony/plugins/orangehrmAdminPlugin/lib/form/LocationForm.php
PHP
gpl-2.0
7,085
package Smokeping::probes::CiscoRTTMonTcpConnect; =head1 301 Moved Permanently This is a Smokeping probe module. Please use the command C<smokeping -man Smokeping::probes::CiscoRTTMonTcpConnect> to view the documentation or the command C<smokeping -makepod Smokeping::probes::CiscoRTTMonTcpConnect> to generate the POD document. =cut use strict; use base qw(Smokeping::probes::basefork); use Symbol; use Carp; use BER; use SNMP_Session; use SNMP_util "0.97"; use Smokeping::ciscoRttMonMIB "0.2"; sub pod_hash { my $e = "="; return { name => <<DOC, Smokeping::probes::CiscoRTTMonTcpConnect - Probe for SmokePing DOC description => <<DOC, A probe for smokeping, which uses the ciscoRttMon MIB functionality ("Service Assurance Agent", "SAA") of Cisco IOS to measure TCP connect times between a Cisco router and a TCP server. The measured value is the time is the time to establish a TCP session, i.e. the time between the initial "SYN" TCP packet of the router and the "SYN ACK" packet of the host. The router terminates the TCP session immediately after the reception of "SYN ACK" with a "FIN" packet. DOC notes => <<DOC, ${e}head2 IOS VERSIONS This probe only works with Cisco IOS 12.0(3)T or higher. It is recommended to test it on less critical routers first. ${e}head2 INSTALLATION To install this probe copy ciscoRttMonMIB.pm to (\$SMOKEPINGINSTALLDIR)/Smokeping/lib and CiscoRTTMonTcpConnect.pm to (\$SMOKEPINGINSTALLDIR)/lib/Smokeping/probes. V0.97 or higher of Simon Leinen's SNMP_Session.pm is required. The router(s) must be configured to allow read/write SNMP access. Sufficient is: snmp-server community RTTCommunity RW If you want to be a bit more restrictive with SNMP write access to the router, then consider configuring something like this access-list 2 permit 10.37.3.5 snmp-server view RttMon ciscoRttMonMIB included snmp-server community RTTCommunity view RttMon RW 2 The above configuration grants SNMP read-write only to 10.37.3.5 (the smokeping host) and only to the ciscoRttMon MIB tree. The probe does not need access to SNMP variables outside the RttMon tree. DOC bugs => <<DOC, The probe establishes unnecessary connections, i.e. more than configured in the "pings" variable, because the RTTMon MIB only allows to set a total time for all connections in one measurement run (one "life"). Currently the probe sets the life duration to "pings"*5+3 seconds (5 secs is the timeout value hardcoded into this probe). DOC see_also => <<DOC, L<http://oss.oetiker.ch/smokeping/> L<http://www.switch.ch/misc/leinen/snmp/perl/> The best source for background info on SAA is Cisco's documentation on L<http://www.cisco.com> and the CISCO-RTTMON-MIB documentation, which is available at: L<ftp://ftp.cisco.com/pub/mibs/v2/CISCO-RTTMON-MIB.my> DOC authors => <<DOC, Joerg.Kummer at Roche.com DOC } } my $pingtimeout = 5; sub new($$$) { my $proto = shift; my $class = ref($proto) || $proto; my $self = $class->SUPER::new(@_); # no need for this if we run as a cgi unless ( $ENV{SERVER_SOFTWARE} ) { $self->{pingfactor} = 1000; }; return $self; } sub ProbeDesc($){ my $self = shift; return "CiscoRTTMonTcpConnect"; } sub pingone ($$) { my $self = shift; my $target = shift; my $pings = $self->pings($target) || 20; my $tos = $target->{vars}{tos}; my $port = $target->{vars}{port}; # use the proces ID as as row number to make this poll distinct on the router; my $row=$$; if (defined StartRttMibEcho($target->{vars}{ioshost}.":::::2", $target->{addr}, $port, $pings, $target->{vars}{iosint}, $tos, $row)) { # wait for the series to finish sleep ($pings*$pingtimeout+5); if (my @times=FillTimesFromHistoryTable($target->{vars}{ioshost}.":::::2", $pings, $row)){ DestroyData ($target->{vars}{ioshost}.":::::2", $row); return @times; } else { return(); } } else { return (); } } sub StartRttMibEcho ($$$$$$){ my ($host, $target, $port, $pings, $sourceip, $tos, $row) = @_; # resolve the target name and encode its IP address $_=$target; if (!/^([0-9]|\.)+/) { (my $name, my $aliases, my $addrtype, my $length, my @addrs) = gethostbyname ($target); $target=join('.',(unpack("C4",$addrs[0]))); } my @octets=split(/\./,$target); my $encoded_target= pack ("CCCC", @octets); # resolve the source name and encode its IP address my $encoded_source = undef; if (defined $sourceip) { $_=$sourceip; if (!/^([0-9]|\.)+/) { (my $name, my $aliases, my $addrtype, my $length, my @addrs) = gethostbyname ($sourceip); $sourceip=join('.',(unpack("C4",$addrs[0]))); } my @octets=split(/\./,$sourceip); $encoded_source= pack ("CCCC", @octets); } ############################################################# # rttMonCtrlAdminStatus - 1:active 2:notInService 3:notReady 4:createAndGo 5:createAndWait 6:destroy #delete data from former measurements #return undef unless defined # &snmpset($host, "rttMonCtrlAdminStatus.$row",'integer', 6); ############################################################# # Check RTTMon version and supported protocols $SNMP_Session::suppress_warnings = 10; # be silent (my $version)=&snmpget ($host, "rttMonApplVersion"); if (! defined $version ) { Smokeping::do_log ("$host doesn't support or allow RTTMon !\n"); return undef; } Smokeping::do_log ("$host supports $version\n"); $SNMP_Session::suppress_warnings = 0; # report errors # echo(1), pathEcho(2), fileIO(3), script(4), udpEcho(5), tcpConnect(6), http(7), # dns(8), jitter(9), dlsw(10), dhcp(11), ftp(12) my $tcpConnSupported=0==1; snmpmaptable ($host, sub () { my ($proto, $supported) = @_; # 1 is true , 2 is false $tcpConnSupported=0==0 if ($proto==6 && $supported==1); }, "rttMonApplSupportedRttTypesValid"); if (! $tcpConnSupported) { Smokeping::do_log ("$host doesn't support TCP connection time measurements !\n"); return undef; } ############################################################# #setup the new data row my @params=(); push @params, "rttMonCtrlAdminStatus.$row", 'integer', 5, "rttMonCtrlAdminRttType.$row", 'integer', 6, "rttMonEchoAdminProtocol.$row", 'integer', 24, "rttMonEchoAdminTargetAddress.$row", 'octetstring', $encoded_target, "rttMonEchoAdminTargetPort.$row", 'integer', $port, "rttMonCtrlAdminTimeout.$row", 'integer', $pingtimeout*1000, "rttMonCtrlAdminFrequency.$row", 'integer', $pingtimeout, "rttMonEchoAdminControlEnable.$row", 'integer', 2, "rttMonEchoAdminTOS.$row", 'integer', $tos, "rttMonCtrlAdminNvgen.$row", 'integer', 2, "rttMonHistoryAdminNumBuckets.$row", 'integer', $pings, "rttMonHistoryAdminNumLives.$row", 'integer', 1, "rttMonHistoryAdminFilter.$row", 'integer', 2, "rttMonScheduleAdminRttStartTime.$row", 'timeticks', 1, "rttMonScheduleAdminRttLife.$row", 'integer', $pings*$pingtimeout+3, "rttMonScheduleAdminConceptRowAgeout.$row",'integer', 60; # the router (or this script) doesn't check whether the IP address is one of # the router's IP address, i.e. the router might send packets, but never # gets replies.. if (defined $sourceip) { push @params, "rttMonEchoAdminSourceAddress.$row", 'octetstring', $encoded_source; } return undef unless defined &snmpset($host, @params); ############################################################# # and go ! return undef unless defined &snmpset($host, "rttMonCtrlAdminStatus.$row",'integer',1); return 1; } # RttResponseSense values # 1:ok 2:disconnected 3:overThreshold 4:timeout 5:busy 6:notConnected 7:dropped 8:sequenceError # 9:verifyError 10:applicationSpecific 11:dnsServerTimeout 12:tcpConnectTimeout 13:httpTransactionTimeout #14:dnsQueryError 15:httpError 16:error sub FillTimesFromHistoryTable($$$$) { my ($host, $pings, $row) = @_; my @times; # snmpmaptable walks two columns of rttMonHistoryCollectionTable # - "rttMonHistoryCollectionCompletionTime.$row", # - "rttMonHistoryCollectionSense.$row" # The code in the sub() argument is executed for each index value snmptable walks snmpmaptable ($host, sub () { my ($index, $rtt, $status) = @_; push @times, (sprintf ("%.10e", $rtt/1000)) if ($status==1); }, "rttMonHistoryCollectionCompletionTime.$row", "rttMonHistoryCollectionSense.$row"); return sort { $a <=> $b } @times; } sub DestroyData ($$) { my ($host, $row) = @_; &snmpset($host, "rttMonCtrlOperState.$row", 'integer', 3); &snmpset($host, "rttMonCtrlAdminStatus.$row", 'integer', 2); #delete any old config &snmpset($host, "rttMonCtrlAdminStatus.$row", 'integer', 6); } sub targetvars { my $class = shift; return $class->_makevars($class->SUPER::targetvars, { _mandatory => [ 'ioshost' ], ioshost => { _example => 'RTTcommunity@Myrouter.foobar.com.au', _doc => <<DOC, The (mandatory) ioshost parameter specifies the Cisco router, which will establish the TCP connections as well as the SNMP community string on the router. DOC }, port => { _default => 80, _re => '\d+', _doc => <<DOC, The (optional) port parameter lets you configure the destination TCP port on the host. The default is the http port 80. DOC }, timeout => { _re => '\d+', _example => 15, _default => $pingtimeout+10, _doc => "How long a single RTTMon TcpConnect 'ping' take at maximum plus 10 seconds to spare. Since we control our own timeout the only purpose of this is to not have us killed by the ping method from basefork.", }, iosint => { _example => '10.33.22.11', _doc => <<DOC, The (optional) iosint parameter is the source address for the TCP connections. This should be one of the active (!) IP addresses of the router to get results. IOS looks up the target host address in the forwarding table and then uses the interface(s) listed there to send the TCP packets. By default IOS uses the (primary) IP address on the sending interface as source address for a connection. DOC }, tos => { _default => 0, _example => 160, _re => '\d+', _doc => <<DOC, The (optional) tos parameter specifies the value of the ToS byte in the IP header of the packets from the router. Multiply DSCP values times 4 and Precedence values times 32 to calculate the ToS values to configure, e.g. ToS 160 corresponds to a DSCP value 40 and a Precedence value of 5. Please note that this will not influence the ToS value in the packets sent by the the host. DOC }, }); } 1;
slesru/SmokePing
lib/Smokeping/probes/CiscoRTTMonTcpConnect.pm
Perl
gpl-2.0
10,625
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; namespace Trithemius { public partial class Form5 : Form { public Form5() { InitializeComponent(); } char[] alphabet = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; private void button1_Click(object sender, EventArgs e) { if (!Regex.IsMatch(textBox1.Text, @"^[a-zA-Z ]+$") || !Regex.IsMatch(textBox2.Text, @"^[a-zA-Z]+$")) { MessageBox.Show(this, "No special characters are allowed in the message or key box.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } char[] key = textBox2.Text.ToUpper().ToCharArray(); char[] txt = textBox1.Text.ToUpper().Replace(" ", "").ToCharArray(); StringBuilder sb = new StringBuilder(); int i = 0; foreach (char c in txt) { sb.Append(alphabet[ (indexOf(c) + indexOf(key[i % key.Length])) % 26]); i++; } textBox3.Text = sb.ToString(); } int indexOf(char c) { return alphabet.ToList().IndexOf(c); } private void button2_Click(object sender, EventArgs e) { if (!Regex.IsMatch(textBox1.Text, @"^[a-zA-Z]+$") || !Regex.IsMatch(textBox2.Text, @"^[a-zA-Z]+$")) { MessageBox.Show(this, "No special characters are allowed in the message or key box.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } char[] key = textBox2.Text.ToUpper().ToCharArray(); char[] txt = textBox1.Text.ToUpper().ToCharArray(); StringBuilder sb = new StringBuilder(); int i = 0; foreach (char c in txt) { int index = indexOf(c) - indexOf(key[i % key.Length]); if (index < 0) { index = 26 + index; } sb.Append(alphabet[ (index) % 26]); i++; } textBox3.Text = sb.ToString(); } } }
tbaxendale/trithemius
historical/beta2/Cryptography/Form5.cs
C#
gpl-2.0
2,625
/** * 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/GObjectTypes.h> #include "AnnotationTableObjectConstraints.h" namespace U2 { AnnotationTableObjectConstraints::AnnotationTableObjectConstraints( QObject *p ) : GObjectConstraints( GObjectTypes::ANNOTATION_TABLE, p ), sequenceSizeToFit( 0 ) { } AnnotationTableObjectConstraints::AnnotationTableObjectConstraints( const AnnotationTableObjectConstraints &c, QObject *p ) : GObjectConstraints( GObjectTypes::ANNOTATION_TABLE, p ), sequenceSizeToFit( c.sequenceSizeToFit ) { } } // namespace U2
mfursov/ugene
src/corelibs/U2Core/src/datatype/AnnotationTableObjectConstraints.cpp
C++
gpl-2.0
1,378
<?php /** * * Ajax Shoutbox extension for the phpBB Forum Software package. * * @copyright (c) 2014 Paul Sohier <http://www.ajax-shoutbox.com> * @license GNU General Public License, version 2 (GPL-2.0) * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine // // Some characters you may want to copy&paste: // ’ » “ ” … // $lang = array_merge( $lang, array( 'ACP_AJAXSHOUTBOX_SETTINGS' => 'Ajax Shoutbox instellingen', 'ACP_AJAXSHOUTBOX_SETTINGS_EXPLAIN' => 'Op deze pagina vind je de instellingen specifiek voor de shoutbox.<br /><br /> Als je wilt dat je gebruikers gebruik kunnen maken van de iOS en android APPs (Op dit moment in een gesloten beta, maar gebruikers kunnen de APP nog steeds gebruik maken als ze toegang hebben tot de BETA. Zie <a href="http://www.ajax-shoutbox.com/viewtopic.php?f=2&t=9">hier</a> voor meer informatie), moet je een account aanmaken op <a href="https://www.shoutbox-app.com/">www.shoutbox-app.com</a>. Hierna moet je een nieuw forum toevoegen op de site. Bij dit proces heb je een activatie code nodig. Deze vind je hieronder. ', 'ACP_AJAXSHOUTBOX_PRUNE' => 'Prune instellingen', 'AJAXSHOUTBOX_ENABLE_PRUNE' => 'Zet het automatische verwijderen van oude posts aan', 'AJAXSHOUTBOX_PRUNE_DAYS' => 'Prune posts na', 'AJAXSHOUTBOX_DEFAULT_DATE_FORMAT' => 'Datum formaat', 'AJAXSHOUTBOX_DEFAULT_DATE_FORMAT_EXPLAIN' => 'Standaard datum formaat voor in de shoutbox. Je kan het beste geen gebruik maken van relatieve formaten, aangezien de datum niet update wanneer de shoutbox ververst. ', 'ACP_AJAXSHOUTBOX_PUSH' => 'App configuratie', 'AJAXSHOUTBOX_ACTIVATION_KEY' => 'Activatie code', 'ACP_AJAXSHOUTBOX_ENABLE_PUSH' => 'Schakel de android en iOS app in', 'ACP_AJAXSHOUTBOX_ENABLE_PUSH_EXPLAIN' => 'Voordat je je kan registeren, moet je deze feature eerst inschakelen', 'ACP_AJAXSHOUTBOX_API_KEY_PUSH' => 'API Key', 'ACP_AJAXSHOUTBOX_API_KEY_PUSH_EXPLAIN' => 'Deze key zal je ontvangen wanneer je je forum toevoegt op www.shoutbox-app.com', 'ACP_AJAXSHOUTBOX_CON_KEY_PUSH' => 'Connection ID', 'ACP_AJAXSHOUTBOX_CON_KEY_PUSH_EXPLAIN' => 'Deze ID zal je ontvangen wanneer je je forum toevoegt op www.shoutbox-app.com.<br />Je gebruikers kunnen dit ID gebruiken om je forum te vinden in de APP.', 'ACP_AJAXSHOUTBOX_PUSH_DISABLED' => 'Push features uitgeschakeld', 'ACP_AJAXSHOUTBOX_PUSH_DISABLED_EXPLAIN' => 'De push features zijn, standaard, uitgeschakeld. Wanneer je deze functionaliteit wilt inschakelen voeg je de volgende code toe aan je config.php:', ) );
alhitary/ajax-shoutbox-ext
language/nl/acp_ajax_shoutbox.php
PHP
gpl-2.0
3,318
import ppc_commands ppc_model = 'ppc440gx' funcs = {} ppc_commands.setup_local_functions(ppc_model, funcs) class_funcs = { ppc_model: funcs } ppc_commands.enable_generic_ppc_commands(ppc_model) ppc_commands.enable_4xx_tlb_commands(ppc_model) ppc_commands.enable_440_tlb_commands(ppc_model)
iniverno/RnR-LLC
simics-3.0-install/simics-3.0.31/amd64-linux/lib/python/mod_ppc440gx_turbo_commands.py
Python
gpl-2.0
293
/* FCE Ultra - NES/Famicom Emulator * * Copyright notice for this file: * Copyright (C) 2005 CaH4e3 * * 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 "mapinc.h" #include "mmc3.h" // brk is a system call in *nix, and is an illegal variable name - soules static uint8 chrcmd[8], prg0, prg1, bbrk, mirr, swap; static SFORMAT StateRegs[]= { {chrcmd, 8, "CHRC"}, {&prg0, 1, "PRG0"}, {&prg1, 1, "PRG1"}, {&bbrk, 1, "BRK"}, {&mirr, 1, "MIRR"}, {&swap, 1, "SWAP"}, {0} }; static void Sync(void) { int i; setprg8(0x8000,prg0); setprg8(0xA000,prg1); setprg8(0xC000,~1); setprg8(0xE000,~0); for(i=0; i<8; i++) setchr1(i<<10,chrcmd[i]); setmirror(mirr^1); } static void UNLSL1632CW(uint32 A, uint8 V) { int cbase=(MMC3_cmd&0x80)<<5; int page0=(bbrk&0x08)<<5; int page1=(bbrk&0x20)<<3; int page2=(bbrk&0x80)<<1; setchr1(cbase^0x0000,page0|(DRegBuf[0]&(~1))); setchr1(cbase^0x0400,page0|DRegBuf[0]|1); setchr1(cbase^0x0800,page0|(DRegBuf[1]&(~1))); setchr1(cbase^0x0C00,page0|DRegBuf[1]|1); setchr1(cbase^0x1000,page1|DRegBuf[2]); setchr1(cbase^0x1400,page1|DRegBuf[3]); setchr1(cbase^0x1800,page2|DRegBuf[4]); setchr1(cbase^0x1c00,page2|DRegBuf[5]); } static DECLFW(UNLSL1632CMDWrite) { if(A==0xA131) { bbrk=V; } if(bbrk&2) { FixMMC3PRG(MMC3_cmd); FixMMC3CHR(MMC3_cmd); if(A<0xC000) MMC3_CMDWrite(A,V); else MMC3_IRQWrite(A,V); } else { if((A>=0xB000)&&(A<=0xE003)) { int ind=((((A&2)|(A>>10))>>1)+2)&7; int sar=((A&1)<<2); chrcmd[ind]=(chrcmd[ind]&(0xF0>>sar))|((V&0x0F)<<sar); } else switch(A&0xF003) { case 0x8000: prg0=V; break; case 0xA000: prg1=V; break; case 0x9000: mirr=V&1; break; } Sync(); } } static void StateRestore(int version) { if(bbrk&2) { FixMMC3PRG(MMC3_cmd); FixMMC3CHR(MMC3_cmd); } else Sync(); } static void UNLSL1632Power(void) { GenMMC3Power(); SetWriteHandler(0x4100,0xFFFF,UNLSL1632CMDWrite); } void UNLSL1632_Init(CartInfo *info) { GenMMC3_Init(info, 256, 512, 0, 0); cwrap=UNLSL1632CW; info->Power=UNLSL1632Power; GameStateRestore=StateRestore; AddExState(&StateRegs, ~0, 0, 0); }
anubisthejackle/playfun
fceu/boards/sl1632.cpp
C++
gpl-2.0
2,914
/* FUSE: Filesystem in Userspace Copyright (C) 2001-2008 Miklos Szeredi <miklos@szeredi.hu> This program can be distributed under the terms of the GNU GPL. See the file COPYING. */ #include "fuse_i.h" #include "fuse_shortcircuit.h" #include <linux/init.h> #include <linux/module.h> #include <linux/poll.h> #include <linux/uio.h> #include <linux/miscdevice.h> #include <linux/namei.h> #include <linux/pagemap.h> #include <linux/file.h> #include <linux/slab.h> #include <linux/pipe_fs_i.h> #include <linux/swap.h> #include <linux/splice.h> #include <linux/aio.h> #include <linux/freezer.h> MODULE_ALIAS_MISCDEV(FUSE_MINOR); MODULE_ALIAS("devname:fuse"); #define wake_up_sync(x) __wake_up_sync((x), TASK_NORMAL, 1) static struct kmem_cache *fuse_req_cachep; static struct fuse_conn *fuse_get_conn(struct file *file) { return file->private_data; } static void fuse_request_init(struct fuse_req *req, struct page **pages, struct fuse_page_desc *page_descs, unsigned npages) { memset(req, 0, sizeof(*req)); memset(pages, 0, sizeof(*pages) * npages); memset(page_descs, 0, sizeof(*page_descs) * npages); INIT_LIST_HEAD(&req->list); INIT_LIST_HEAD(&req->intr_entry); init_waitqueue_head(&req->waitq); atomic_set(&req->count, 1); req->pages = pages; req->page_descs = page_descs; req->max_pages = npages; } static struct fuse_req *__fuse_request_alloc(unsigned npages, gfp_t flags) { struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, flags); if (req) { struct page **pages; struct fuse_page_desc *page_descs; if (npages <= FUSE_REQ_INLINE_PAGES) { pages = req->inline_pages; page_descs = req->inline_page_descs; } else { pages = kmalloc(sizeof(struct page *) * npages, flags); page_descs = kmalloc(sizeof(struct fuse_page_desc) * npages, flags); } if (!pages || !page_descs) { kfree(pages); kfree(page_descs); kmem_cache_free(fuse_req_cachep, req); return NULL; } fuse_request_init(req, pages, page_descs, npages); } return req; } struct fuse_req *fuse_request_alloc(unsigned npages) { return __fuse_request_alloc(npages, GFP_KERNEL); } EXPORT_SYMBOL_GPL(fuse_request_alloc); struct fuse_req *fuse_request_alloc_nofs(unsigned npages) { return __fuse_request_alloc(npages, GFP_NOFS); } void fuse_request_free(struct fuse_req *req) { if (req->pages != req->inline_pages) { kfree(req->pages); kfree(req->page_descs); } kmem_cache_free(fuse_req_cachep, req); } static void block_sigs(sigset_t *oldset) { sigset_t mask; siginitsetinv(&mask, sigmask(SIGKILL)); sigprocmask(SIG_BLOCK, &mask, oldset); } static void restore_sigs(sigset_t *oldset) { sigprocmask(SIG_SETMASK, oldset, NULL); } void __fuse_get_request(struct fuse_req *req) { atomic_inc(&req->count); } static void __fuse_put_request(struct fuse_req *req) { BUG_ON(atomic_read(&req->count) < 2); atomic_dec(&req->count); } static void fuse_req_init_context(struct fuse_req *req) { req->in.h.uid = from_kuid_munged(&init_user_ns, current_fsuid()); req->in.h.gid = from_kgid_munged(&init_user_ns, current_fsgid()); req->in.h.pid = current->pid; } static bool fuse_block_alloc(struct fuse_conn *fc, bool for_background) { return !fc->initialized || (for_background && fc->blocked); } static struct fuse_req *__fuse_get_req(struct fuse_conn *fc, unsigned npages, bool for_background) { struct fuse_req *req; int err; atomic_inc(&fc->num_waiting); if (fuse_block_alloc(fc, for_background)) { sigset_t oldset; int intr; block_sigs(&oldset); intr = wait_event_interruptible_exclusive(fc->blocked_waitq, !fuse_block_alloc(fc, for_background)); restore_sigs(&oldset); err = -EINTR; if (intr) goto out; } err = -ENOTCONN; if (!fc->connected) goto out; req = fuse_request_alloc(npages); err = -ENOMEM; if (!req) { if (for_background) wake_up(&fc->blocked_waitq); goto out; } fuse_req_init_context(req); req->waiting = 1; req->background = for_background; return req; out: atomic_dec(&fc->num_waiting); return ERR_PTR(err); } struct fuse_req *fuse_get_req(struct fuse_conn *fc, unsigned npages) { return __fuse_get_req(fc, npages, false); } EXPORT_SYMBOL_GPL(fuse_get_req); struct fuse_req *fuse_get_req_for_background(struct fuse_conn *fc, unsigned npages) { return __fuse_get_req(fc, npages, true); } EXPORT_SYMBOL_GPL(fuse_get_req_for_background); static struct fuse_req *get_reserved_req(struct fuse_conn *fc, struct file *file) { struct fuse_req *req = NULL; struct fuse_file *ff = file->private_data; do { wait_event(fc->reserved_req_waitq, ff->reserved_req); spin_lock(&fc->lock); if (ff->reserved_req) { req = ff->reserved_req; ff->reserved_req = NULL; req->stolen_file = get_file(file); } spin_unlock(&fc->lock); } while (!req); return req; } static void put_reserved_req(struct fuse_conn *fc, struct fuse_req *req) { struct file *file = req->stolen_file; struct fuse_file *ff = file->private_data; spin_lock(&fc->lock); fuse_request_init(req, req->pages, req->page_descs, req->max_pages); BUG_ON(ff->reserved_req); ff->reserved_req = req; wake_up_all(&fc->reserved_req_waitq); spin_unlock(&fc->lock); fput(file); } struct fuse_req *fuse_get_req_nofail_nopages(struct fuse_conn *fc, struct file *file) { struct fuse_req *req; atomic_inc(&fc->num_waiting); wait_event(fc->blocked_waitq, fc->initialized); req = fuse_request_alloc(0); if (!req) req = get_reserved_req(fc, file); fuse_req_init_context(req); req->waiting = 1; req->background = 0; return req; } void fuse_put_request(struct fuse_conn *fc, struct fuse_req *req) { if (atomic_dec_and_test(&req->count)) { if (unlikely(req->background)) { spin_lock(&fc->lock); if (!fc->blocked) wake_up(&fc->blocked_waitq); spin_unlock(&fc->lock); } if (req->waiting) atomic_dec(&fc->num_waiting); if (req->stolen_file) put_reserved_req(fc, req); else fuse_request_free(req); } } EXPORT_SYMBOL_GPL(fuse_put_request); static unsigned len_args(unsigned numargs, struct fuse_arg *args) { unsigned nbytes = 0; unsigned i; for (i = 0; i < numargs; i++) nbytes += args[i].size; return nbytes; } static u64 fuse_get_unique(struct fuse_conn *fc) { fc->reqctr++; if (fc->reqctr == 0) fc->reqctr = 1; return fc->reqctr; } static void queue_request(struct fuse_conn *fc, struct fuse_req *req) { req->in.h.len = sizeof(struct fuse_in_header) + len_args(req->in.numargs, (struct fuse_arg *) req->in.args); list_add_tail(&req->list, &fc->pending); req->state = FUSE_REQ_PENDING; if (!req->waiting) { req->waiting = 1; atomic_inc(&fc->num_waiting); } wake_up_sync(&fc->waitq); kill_fasync(&fc->fasync, SIGIO, POLL_IN); } void fuse_queue_forget(struct fuse_conn *fc, struct fuse_forget_link *forget, u64 nodeid, u64 nlookup) { forget->forget_one.nodeid = nodeid; forget->forget_one.nlookup = nlookup; spin_lock(&fc->lock); if (fc->connected) { fc->forget_list_tail->next = forget; fc->forget_list_tail = forget; wake_up(&fc->waitq); kill_fasync(&fc->fasync, SIGIO, POLL_IN); } else { kfree(forget); } spin_unlock(&fc->lock); } static void flush_bg_queue(struct fuse_conn *fc) { while (fc->active_background < fc->max_background && !list_empty(&fc->bg_queue)) { struct fuse_req *req; req = list_entry(fc->bg_queue.next, struct fuse_req, list); list_del(&req->list); fc->active_background++; req->in.h.unique = fuse_get_unique(fc); queue_request(fc, req); } } static void request_end(struct fuse_conn *fc, struct fuse_req *req) __releases(fc->lock) { void (*end) (struct fuse_conn *, struct fuse_req *) = req->end; req->end = NULL; list_del(&req->list); list_del(&req->intr_entry); req->state = FUSE_REQ_FINISHED; if (req->background) { req->background = 0; if (fc->num_background == fc->max_background) fc->blocked = 0; if (!fc->blocked && waitqueue_active(&fc->blocked_waitq)) wake_up(&fc->blocked_waitq); if (fc->num_background == fc->congestion_threshold && fc->connected && fc->bdi_initialized) { clear_bdi_congested(&fc->bdi, BLK_RW_SYNC); clear_bdi_congested(&fc->bdi, BLK_RW_ASYNC); } fc->num_background--; fc->active_background--; flush_bg_queue(fc); } spin_unlock(&fc->lock); wake_up_sync(&req->waitq); if (end) end(fc, req); fuse_put_request(fc, req); } static void wait_answer_interruptible(struct fuse_conn *fc, struct fuse_req *req) __releases(fc->lock) __acquires(fc->lock) { if (signal_pending(current)) return; spin_unlock(&fc->lock); wait_event_interruptible(req->waitq, req->state == FUSE_REQ_FINISHED); spin_lock(&fc->lock); } static void queue_interrupt(struct fuse_conn *fc, struct fuse_req *req) { list_add_tail(&req->intr_entry, &fc->interrupts); wake_up(&fc->waitq); kill_fasync(&fc->fasync, SIGIO, POLL_IN); } static void request_wait_answer(struct fuse_conn *fc, struct fuse_req *req) __releases(fc->lock) __acquires(fc->lock) { if (!fc->no_interrupt) { wait_answer_interruptible(fc, req); if (req->aborted) goto aborted; if (req->state == FUSE_REQ_FINISHED) return; req->interrupted = 1; if (req->state == FUSE_REQ_SENT) queue_interrupt(fc, req); } if (!req->force) { sigset_t oldset; block_sigs(&oldset); wait_answer_interruptible(fc, req); restore_sigs(&oldset); if (req->aborted) goto aborted; if (req->state == FUSE_REQ_FINISHED) return; if (req->state == FUSE_REQ_PENDING) { list_del(&req->list); __fuse_put_request(req); req->out.h.error = -EINTR; return; } } spin_unlock(&fc->lock); while (req->state != FUSE_REQ_FINISHED) wait_event_freezable(req->waitq, req->state == FUSE_REQ_FINISHED); spin_lock(&fc->lock); if (!req->aborted) return; aborted: BUG_ON(req->state != FUSE_REQ_FINISHED); if (req->locked) { spin_unlock(&fc->lock); wait_event(req->waitq, !req->locked); spin_lock(&fc->lock); } } static void __fuse_request_send(struct fuse_conn *fc, struct fuse_req *req) { BUG_ON(req->background); spin_lock(&fc->lock); if (!fc->connected) req->out.h.error = -ENOTCONN; else if (fc->conn_error) req->out.h.error = -ECONNREFUSED; else { req->in.h.unique = fuse_get_unique(fc); queue_request(fc, req); __fuse_get_request(req); request_wait_answer(fc, req); } spin_unlock(&fc->lock); } void fuse_request_send(struct fuse_conn *fc, struct fuse_req *req) { req->isreply = 1; __fuse_request_send(fc, req); } EXPORT_SYMBOL_GPL(fuse_request_send); static void fuse_request_send_nowait_locked(struct fuse_conn *fc, struct fuse_req *req) { BUG_ON(!req->background); fc->num_background++; if (fc->num_background == fc->max_background) fc->blocked = 1; if (fc->num_background == fc->congestion_threshold && fc->bdi_initialized) { set_bdi_congested(&fc->bdi, BLK_RW_SYNC); set_bdi_congested(&fc->bdi, BLK_RW_ASYNC); } list_add_tail(&req->list, &fc->bg_queue); flush_bg_queue(fc); } static void fuse_request_send_nowait(struct fuse_conn *fc, struct fuse_req *req) { spin_lock(&fc->lock); if (fc->connected) { fuse_request_send_nowait_locked(fc, req); spin_unlock(&fc->lock); } else { req->out.h.error = -ENOTCONN; request_end(fc, req); } } void fuse_request_send_background(struct fuse_conn *fc, struct fuse_req *req) { req->isreply = 1; fuse_request_send_nowait(fc, req); } EXPORT_SYMBOL_GPL(fuse_request_send_background); static int fuse_request_send_notify_reply(struct fuse_conn *fc, struct fuse_req *req, u64 unique) { int err = -ENODEV; req->isreply = 0; req->in.h.unique = unique; spin_lock(&fc->lock); if (fc->connected) { queue_request(fc, req); err = 0; } spin_unlock(&fc->lock); return err; } void fuse_request_send_background_locked(struct fuse_conn *fc, struct fuse_req *req) { req->isreply = 1; fuse_request_send_nowait_locked(fc, req); } void fuse_force_forget(struct file *file, u64 nodeid) { struct inode *inode = file_inode(file); struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; struct fuse_forget_in inarg; memset(&inarg, 0, sizeof(inarg)); inarg.nlookup = 1; req = fuse_get_req_nofail_nopages(fc, file); req->in.h.opcode = FUSE_FORGET; req->in.h.nodeid = nodeid; req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->isreply = 0; __fuse_request_send(fc, req); fuse_put_request(fc, req); } static int lock_request(struct fuse_conn *fc, struct fuse_req *req) { int err = 0; if (req) { spin_lock(&fc->lock); if (req->aborted) err = -ENOENT; else req->locked = 1; spin_unlock(&fc->lock); } return err; } static void unlock_request(struct fuse_conn *fc, struct fuse_req *req) { if (req) { spin_lock(&fc->lock); req->locked = 0; if (req->aborted) wake_up(&req->waitq); spin_unlock(&fc->lock); } } struct fuse_copy_state { struct fuse_conn *fc; int write; struct fuse_req *req; const struct iovec *iov; struct pipe_buffer *pipebufs; struct pipe_buffer *currbuf; struct pipe_inode_info *pipe; unsigned long nr_segs; unsigned long seglen; unsigned long addr; struct page *pg; void *mapaddr; void *buf; unsigned len; unsigned move_pages:1; }; static void fuse_copy_init(struct fuse_copy_state *cs, struct fuse_conn *fc, int write, const struct iovec *iov, unsigned long nr_segs) { memset(cs, 0, sizeof(*cs)); cs->fc = fc; cs->write = write; cs->iov = iov; cs->nr_segs = nr_segs; } static void fuse_copy_finish(struct fuse_copy_state *cs) { if (cs->currbuf) { struct pipe_buffer *buf = cs->currbuf; if (!cs->write) { buf->ops->unmap(cs->pipe, buf, cs->mapaddr); } else { kunmap(buf->page); buf->len = PAGE_SIZE - cs->len; } cs->currbuf = NULL; cs->mapaddr = NULL; } else if (cs->mapaddr) { kunmap(cs->pg); if (cs->write) { flush_dcache_page(cs->pg); set_page_dirty_lock(cs->pg); } put_page(cs->pg); cs->mapaddr = NULL; } } static int fuse_copy_fill(struct fuse_copy_state *cs) { unsigned long offset; int err; unlock_request(cs->fc, cs->req); fuse_copy_finish(cs); if (cs->pipebufs) { struct pipe_buffer *buf = cs->pipebufs; if (!cs->write) { err = buf->ops->confirm(cs->pipe, buf); if (err) return err; BUG_ON(!cs->nr_segs); cs->currbuf = buf; cs->mapaddr = buf->ops->map(cs->pipe, buf, 0); cs->len = buf->len; cs->buf = cs->mapaddr + buf->offset; cs->pipebufs++; cs->nr_segs--; } else { struct page *page; if (cs->nr_segs == cs->pipe->buffers) return -EIO; page = alloc_page(GFP_HIGHUSER); if (!page) return -ENOMEM; buf->page = page; buf->offset = 0; buf->len = 0; cs->currbuf = buf; cs->mapaddr = kmap(page); cs->buf = cs->mapaddr; cs->len = PAGE_SIZE; cs->pipebufs++; cs->nr_segs++; } } else { if (!cs->seglen) { BUG_ON(!cs->nr_segs); cs->seglen = cs->iov[0].iov_len; cs->addr = (unsigned long) cs->iov[0].iov_base; cs->iov++; cs->nr_segs--; } err = get_user_pages_fast(cs->addr, 1, cs->write, &cs->pg); if (err < 0) return err; BUG_ON(err != 1); offset = cs->addr % PAGE_SIZE; cs->mapaddr = kmap(cs->pg); cs->buf = cs->mapaddr + offset; cs->len = min(PAGE_SIZE - offset, cs->seglen); cs->seglen -= cs->len; cs->addr += cs->len; } return lock_request(cs->fc, cs->req); } static int fuse_copy_do(struct fuse_copy_state *cs, void **val, unsigned *size) { unsigned ncpy = min(*size, cs->len); if (val) { if (cs->write) memcpy(cs->buf, *val, ncpy); else memcpy(*val, cs->buf, ncpy); *val += ncpy; } *size -= ncpy; cs->len -= ncpy; cs->buf += ncpy; return ncpy; } static int fuse_check_page(struct page *page) { if (page_mapcount(page) || page->mapping != NULL || page_count(page) != 1 || (page->flags & PAGE_FLAGS_CHECK_AT_PREP & ~(1 << PG_locked | 1 << PG_referenced | 1 << PG_uptodate | 1 << PG_lru | 1 << PG_active | 1 << PG_reclaim))) { printk(KERN_WARNING "fuse: trying to steal weird page\n"); printk(KERN_WARNING " page=%p index=%li flags=%08lx, count=%i, mapcount=%i, mapping=%p\n", page, page->index, page->flags, page_count(page), page_mapcount(page), page->mapping); return 1; } return 0; } static int fuse_try_move_page(struct fuse_copy_state *cs, struct page **pagep) { int err; struct page *oldpage = *pagep; struct page *newpage; struct pipe_buffer *buf = cs->pipebufs; unlock_request(cs->fc, cs->req); fuse_copy_finish(cs); err = buf->ops->confirm(cs->pipe, buf); if (err) return err; BUG_ON(!cs->nr_segs); cs->currbuf = buf; cs->len = buf->len; cs->pipebufs++; cs->nr_segs--; if (cs->len != PAGE_SIZE) goto out_fallback; if (buf->ops->steal(cs->pipe, buf) != 0) goto out_fallback; newpage = buf->page; if (!PageUptodate(newpage)) SetPageUptodate(newpage); ClearPageMappedToDisk(newpage); if (fuse_check_page(newpage) != 0) goto out_fallback_unlock; if (WARN_ON(page_mapped(oldpage))) goto out_fallback_unlock; if (WARN_ON(page_has_private(oldpage))) goto out_fallback_unlock; if (WARN_ON(PageDirty(oldpage) || PageWriteback(oldpage))) goto out_fallback_unlock; if (WARN_ON(PageMlocked(oldpage))) goto out_fallback_unlock; err = replace_page_cache_page(oldpage, newpage, GFP_KERNEL); if (err) { unlock_page(newpage); return err; } page_cache_get(newpage); if (!(buf->flags & PIPE_BUF_FLAG_LRU)) lru_cache_add_file(newpage); err = 0; spin_lock(&cs->fc->lock); if (cs->req->aborted) err = -ENOENT; else *pagep = newpage; spin_unlock(&cs->fc->lock); if (err) { unlock_page(newpage); page_cache_release(newpage); return err; } unlock_page(oldpage); page_cache_release(oldpage); cs->len = 0; return 0; out_fallback_unlock: unlock_page(newpage); out_fallback: cs->mapaddr = buf->ops->map(cs->pipe, buf, 1); cs->buf = cs->mapaddr + buf->offset; err = lock_request(cs->fc, cs->req); if (err) return err; return 1; } static int fuse_ref_page(struct fuse_copy_state *cs, struct page *page, unsigned offset, unsigned count) { struct pipe_buffer *buf; if (cs->nr_segs == cs->pipe->buffers) return -EIO; unlock_request(cs->fc, cs->req); fuse_copy_finish(cs); buf = cs->pipebufs; page_cache_get(page); buf->page = page; buf->offset = offset; buf->len = count; cs->pipebufs++; cs->nr_segs++; cs->len = 0; return 0; } static int fuse_copy_page(struct fuse_copy_state *cs, struct page **pagep, unsigned offset, unsigned count, int zeroing) { int err; struct page *page = *pagep; if (page && zeroing && count < PAGE_SIZE) clear_highpage(page); while (count) { if (cs->write && cs->pipebufs && page) { return fuse_ref_page(cs, page, offset, count); } else if (!cs->len) { if (cs->move_pages && page && offset == 0 && count == PAGE_SIZE) { err = fuse_try_move_page(cs, pagep); if (err <= 0) return err; } else { err = fuse_copy_fill(cs); if (err) return err; } } if (page) { void *mapaddr = kmap_atomic(page); void *buf = mapaddr + offset; offset += fuse_copy_do(cs, &buf, &count); kunmap_atomic(mapaddr); } else offset += fuse_copy_do(cs, NULL, &count); } if (page && !cs->write) flush_dcache_page(page); return 0; } static int fuse_copy_pages(struct fuse_copy_state *cs, unsigned nbytes, int zeroing) { unsigned i; struct fuse_req *req = cs->req; for (i = 0; i < req->num_pages && (nbytes || zeroing); i++) { int err; unsigned offset = req->page_descs[i].offset; unsigned count = min(nbytes, req->page_descs[i].length); err = fuse_copy_page(cs, &req->pages[i], offset, count, zeroing); if (err) return err; nbytes -= count; } return 0; } static int fuse_copy_one(struct fuse_copy_state *cs, void *val, unsigned size) { while (size) { if (!cs->len) { int err = fuse_copy_fill(cs); if (err) return err; } fuse_copy_do(cs, &val, &size); } return 0; } static int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs, unsigned argpages, struct fuse_arg *args, int zeroing) { int err = 0; unsigned i; for (i = 0; !err && i < numargs; i++) { struct fuse_arg *arg = &args[i]; if (i == numargs - 1 && argpages) err = fuse_copy_pages(cs, arg->size, zeroing); else err = fuse_copy_one(cs, arg->value, arg->size); } return err; } static int forget_pending(struct fuse_conn *fc) { return fc->forget_list_head.next != NULL; } static int request_pending(struct fuse_conn *fc) { return !list_empty(&fc->pending) || !list_empty(&fc->interrupts) || forget_pending(fc); } static void request_wait(struct fuse_conn *fc) __releases(fc->lock) __acquires(fc->lock) { DECLARE_WAITQUEUE(wait, current); add_wait_queue_exclusive(&fc->waitq, &wait); while (fc->connected && !request_pending(fc)) { set_current_state(TASK_INTERRUPTIBLE); if (signal_pending(current)) break; spin_unlock(&fc->lock); schedule(); spin_lock(&fc->lock); } set_current_state(TASK_RUNNING); remove_wait_queue(&fc->waitq, &wait); } static int fuse_read_interrupt(struct fuse_conn *fc, struct fuse_copy_state *cs, size_t nbytes, struct fuse_req *req) __releases(fc->lock) { struct fuse_in_header ih; struct fuse_interrupt_in arg; unsigned reqsize = sizeof(ih) + sizeof(arg); int err; list_del_init(&req->intr_entry); req->intr_unique = fuse_get_unique(fc); memset(&ih, 0, sizeof(ih)); memset(&arg, 0, sizeof(arg)); ih.len = reqsize; ih.opcode = FUSE_INTERRUPT; ih.unique = req->intr_unique; arg.unique = req->in.h.unique; spin_unlock(&fc->lock); if (nbytes < reqsize) return -EINVAL; err = fuse_copy_one(cs, &ih, sizeof(ih)); if (!err) err = fuse_copy_one(cs, &arg, sizeof(arg)); fuse_copy_finish(cs); return err ? err : reqsize; } static struct fuse_forget_link *dequeue_forget(struct fuse_conn *fc, unsigned max, unsigned *countp) { struct fuse_forget_link *head = fc->forget_list_head.next; struct fuse_forget_link **newhead = &head; unsigned count; for (count = 0; *newhead != NULL && count < max; count++) newhead = &(*newhead)->next; fc->forget_list_head.next = *newhead; *newhead = NULL; if (fc->forget_list_head.next == NULL) fc->forget_list_tail = &fc->forget_list_head; if (countp != NULL) *countp = count; return head; } static int fuse_read_single_forget(struct fuse_conn *fc, struct fuse_copy_state *cs, size_t nbytes) __releases(fc->lock) { int err; struct fuse_forget_link *forget = dequeue_forget(fc, 1, NULL); struct fuse_forget_in arg = { .nlookup = forget->forget_one.nlookup, }; struct fuse_in_header ih = { .opcode = FUSE_FORGET, .nodeid = forget->forget_one.nodeid, .unique = fuse_get_unique(fc), .len = sizeof(ih) + sizeof(arg), }; spin_unlock(&fc->lock); kfree(forget); if (nbytes < ih.len) return -EINVAL; err = fuse_copy_one(cs, &ih, sizeof(ih)); if (!err) err = fuse_copy_one(cs, &arg, sizeof(arg)); fuse_copy_finish(cs); if (err) return err; return ih.len; } static int fuse_read_batch_forget(struct fuse_conn *fc, struct fuse_copy_state *cs, size_t nbytes) __releases(fc->lock) { int err; unsigned max_forgets; unsigned count; struct fuse_forget_link *head; struct fuse_batch_forget_in arg = { .count = 0 }; struct fuse_in_header ih = { .opcode = FUSE_BATCH_FORGET, .unique = fuse_get_unique(fc), .len = sizeof(ih) + sizeof(arg), }; if (nbytes < ih.len) { spin_unlock(&fc->lock); return -EINVAL; } max_forgets = (nbytes - ih.len) / sizeof(struct fuse_forget_one); head = dequeue_forget(fc, max_forgets, &count); spin_unlock(&fc->lock); arg.count = count; ih.len += count * sizeof(struct fuse_forget_one); err = fuse_copy_one(cs, &ih, sizeof(ih)); if (!err) err = fuse_copy_one(cs, &arg, sizeof(arg)); while (head) { struct fuse_forget_link *forget = head; if (!err) { err = fuse_copy_one(cs, &forget->forget_one, sizeof(forget->forget_one)); } head = forget->next; kfree(forget); } fuse_copy_finish(cs); if (err) return err; return ih.len; } static int fuse_read_forget(struct fuse_conn *fc, struct fuse_copy_state *cs, size_t nbytes) __releases(fc->lock) { if (fc->minor < 16 || fc->forget_list_head.next->next == NULL) return fuse_read_single_forget(fc, cs, nbytes); else return fuse_read_batch_forget(fc, cs, nbytes); } static ssize_t fuse_dev_do_read(struct fuse_conn *fc, struct file *file, struct fuse_copy_state *cs, size_t nbytes) { int err; struct fuse_req *req; struct fuse_in *in; unsigned reqsize; restart: spin_lock(&fc->lock); err = -EAGAIN; if ((file->f_flags & O_NONBLOCK) && fc->connected && !request_pending(fc)) goto err_unlock; request_wait(fc); err = -ENODEV; if (!fc->connected) goto err_unlock; err = -ERESTARTSYS; if (!request_pending(fc)) goto err_unlock; if (!list_empty(&fc->interrupts)) { req = list_entry(fc->interrupts.next, struct fuse_req, intr_entry); return fuse_read_interrupt(fc, cs, nbytes, req); } if (forget_pending(fc)) { if (list_empty(&fc->pending) || fc->forget_batch-- > 0) return fuse_read_forget(fc, cs, nbytes); if (fc->forget_batch <= -8) fc->forget_batch = 16; } req = list_entry(fc->pending.next, struct fuse_req, list); req->state = FUSE_REQ_READING; list_move(&req->list, &fc->io); in = &req->in; reqsize = in->h.len; if (nbytes < reqsize) { req->out.h.error = -EIO; if (in->h.opcode == FUSE_SETXATTR) req->out.h.error = -E2BIG; request_end(fc, req); goto restart; } spin_unlock(&fc->lock); cs->req = req; err = fuse_copy_one(cs, &in->h, sizeof(in->h)); if (!err) err = fuse_copy_args(cs, in->numargs, in->argpages, (struct fuse_arg *) in->args, 0); fuse_copy_finish(cs); spin_lock(&fc->lock); req->locked = 0; if (req->aborted) { request_end(fc, req); return -ENODEV; } if (err) { req->out.h.error = -EIO; request_end(fc, req); return err; } if (!req->isreply) request_end(fc, req); else { req->state = FUSE_REQ_SENT; list_move_tail(&req->list, &fc->processing); if (req->interrupted) queue_interrupt(fc, req); spin_unlock(&fc->lock); } return reqsize; err_unlock: spin_unlock(&fc->lock); return err; } static ssize_t fuse_dev_read(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct fuse_copy_state cs; struct file *file = iocb->ki_filp; struct fuse_conn *fc = fuse_get_conn(file); if (!fc) return -EPERM; fuse_copy_init(&cs, fc, 1, iov, nr_segs); return fuse_dev_do_read(fc, file, &cs, iov_length(iov, nr_segs)); } static ssize_t fuse_dev_splice_read(struct file *in, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { int ret; int page_nr = 0; int do_wakeup = 0; struct pipe_buffer *bufs; struct fuse_copy_state cs; struct fuse_conn *fc = fuse_get_conn(in); if (!fc) return -EPERM; bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL); if (!bufs) return -ENOMEM; fuse_copy_init(&cs, fc, 1, NULL, 0); cs.pipebufs = bufs; cs.pipe = pipe; ret = fuse_dev_do_read(fc, in, &cs, len); if (ret < 0) goto out; ret = 0; pipe_lock(pipe); if (!pipe->readers) { send_sig(SIGPIPE, current, 0); if (!ret) ret = -EPIPE; goto out_unlock; } if (pipe->nrbufs + cs.nr_segs > pipe->buffers) { ret = -EIO; goto out_unlock; } while (page_nr < cs.nr_segs) { int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1); struct pipe_buffer *buf = pipe->bufs + newbuf; buf->page = bufs[page_nr].page; buf->offset = bufs[page_nr].offset; buf->len = bufs[page_nr].len; buf->ops = &nosteal_pipe_buf_ops; pipe->nrbufs++; page_nr++; ret += buf->len; if (pipe->files) do_wakeup = 1; } out_unlock: pipe_unlock(pipe); if (do_wakeup) { smp_mb(); if (waitqueue_active(&pipe->wait)) wake_up_interruptible(&pipe->wait); kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN); } out: for (; page_nr < cs.nr_segs; page_nr++) page_cache_release(bufs[page_nr].page); kfree(bufs); return ret; } static int fuse_notify_poll(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_poll_wakeup_out outarg; int err = -EINVAL; if (size != sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; fuse_copy_finish(cs); return fuse_notify_poll_wakeup(fc, &outarg); err: fuse_copy_finish(cs); return err; } static int fuse_notify_inval_inode(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_inval_inode_out outarg; int err = -EINVAL; if (size != sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; fuse_copy_finish(cs); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) { err = fuse_reverse_inval_inode(fc->sb, outarg.ino, outarg.off, outarg.len); } up_read(&fc->killsb); return err; err: fuse_copy_finish(cs); return err; } static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_inval_entry_out outarg; int err = -ENOMEM; char *buf; struct qstr name; buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL); if (!buf) goto err; err = -EINVAL; if (size < sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; err = -ENAMETOOLONG; if (outarg.namelen > FUSE_NAME_MAX) goto err; err = -EINVAL; if (size != sizeof(outarg) + outarg.namelen + 1) goto err; name.name = buf; name.len = outarg.namelen; err = fuse_copy_one(cs, buf, outarg.namelen + 1); if (err) goto err; fuse_copy_finish(cs); buf[outarg.namelen] = 0; name.hash = full_name_hash(name.name, name.len); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) err = fuse_reverse_inval_entry(fc->sb, outarg.parent, 0, &name); up_read(&fc->killsb); kfree(buf); return err; err: kfree(buf); fuse_copy_finish(cs); return err; } static int fuse_notify_delete(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_delete_out outarg; int err = -ENOMEM; char *buf; struct qstr name; buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL); if (!buf) goto err; err = -EINVAL; if (size < sizeof(outarg)) goto err; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto err; err = -ENAMETOOLONG; if (outarg.namelen > FUSE_NAME_MAX) goto err; err = -EINVAL; if (size != sizeof(outarg) + outarg.namelen + 1) goto err; name.name = buf; name.len = outarg.namelen; err = fuse_copy_one(cs, buf, outarg.namelen + 1); if (err) goto err; fuse_copy_finish(cs); buf[outarg.namelen] = 0; name.hash = full_name_hash(name.name, name.len); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) err = fuse_reverse_inval_entry(fc->sb, outarg.parent, outarg.child, &name); up_read(&fc->killsb); kfree(buf); return err; err: kfree(buf); fuse_copy_finish(cs); return err; } static int fuse_notify_store(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_store_out outarg; struct inode *inode; struct address_space *mapping; u64 nodeid; int err; pgoff_t index; unsigned int offset; unsigned int num; loff_t file_size; loff_t end; err = -EINVAL; if (size < sizeof(outarg)) goto out_finish; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto out_finish; err = -EINVAL; if (size - sizeof(outarg) != outarg.size) goto out_finish; nodeid = outarg.nodeid; down_read(&fc->killsb); err = -ENOENT; if (!fc->sb) goto out_up_killsb; inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid); if (!inode) goto out_up_killsb; mapping = inode->i_mapping; index = outarg.offset >> PAGE_CACHE_SHIFT; offset = outarg.offset & ~PAGE_CACHE_MASK; file_size = i_size_read(inode); end = outarg.offset + outarg.size; if (end > file_size) { file_size = end; fuse_write_update_size(inode, file_size); } num = outarg.size; while (num) { struct page *page; unsigned int this_num; err = -ENOMEM; page = find_or_create_page(mapping, index, mapping_gfp_mask(mapping)); if (!page) goto out_iput; this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset); err = fuse_copy_page(cs, &page, offset, this_num, 0); if (!err && offset == 0 && (num != 0 || file_size == end)) SetPageUptodate(page); unlock_page(page); page_cache_release(page); if (err) goto out_iput; num -= this_num; offset = 0; index++; } err = 0; out_iput: iput(inode); out_up_killsb: up_read(&fc->killsb); out_finish: fuse_copy_finish(cs); return err; } static void fuse_retrieve_end(struct fuse_conn *fc, struct fuse_req *req) { release_pages(req->pages, req->num_pages, 0); } static int fuse_retrieve(struct fuse_conn *fc, struct inode *inode, struct fuse_notify_retrieve_out *outarg) { int err; struct address_space *mapping = inode->i_mapping; struct fuse_req *req; pgoff_t index; loff_t file_size; unsigned int num; unsigned int offset; size_t total_len = 0; int num_pages; offset = outarg->offset & ~PAGE_CACHE_MASK; file_size = i_size_read(inode); num = outarg->size; if (outarg->offset > file_size) num = 0; else if (outarg->offset + num > file_size) num = file_size - outarg->offset; num_pages = (num + offset + PAGE_SIZE - 1) >> PAGE_SHIFT; num_pages = min(num_pages, FUSE_MAX_PAGES_PER_REQ); req = fuse_get_req(fc, num_pages); if (IS_ERR(req)) return PTR_ERR(req); req->in.h.opcode = FUSE_NOTIFY_REPLY; req->in.h.nodeid = outarg->nodeid; req->in.numargs = 2; req->in.argpages = 1; req->page_descs[0].offset = offset; req->end = fuse_retrieve_end; index = outarg->offset >> PAGE_CACHE_SHIFT; while (num && req->num_pages < num_pages) { struct page *page; unsigned int this_num; page = find_get_page(mapping, index); if (!page) break; this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset); req->pages[req->num_pages] = page; req->page_descs[req->num_pages].length = this_num; req->num_pages++; offset = 0; num -= this_num; total_len += this_num; index++; } req->misc.retrieve_in.offset = outarg->offset; req->misc.retrieve_in.size = total_len; req->in.args[0].size = sizeof(req->misc.retrieve_in); req->in.args[0].value = &req->misc.retrieve_in; req->in.args[1].size = total_len; err = fuse_request_send_notify_reply(fc, req, outarg->notify_unique); if (err) fuse_retrieve_end(fc, req); return err; } static int fuse_notify_retrieve(struct fuse_conn *fc, unsigned int size, struct fuse_copy_state *cs) { struct fuse_notify_retrieve_out outarg; struct inode *inode; int err; err = -EINVAL; if (size != sizeof(outarg)) goto copy_finish; err = fuse_copy_one(cs, &outarg, sizeof(outarg)); if (err) goto copy_finish; fuse_copy_finish(cs); down_read(&fc->killsb); err = -ENOENT; if (fc->sb) { u64 nodeid = outarg.nodeid; inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid); if (inode) { err = fuse_retrieve(fc, inode, &outarg); iput(inode); } } up_read(&fc->killsb); return err; copy_finish: fuse_copy_finish(cs); return err; } static int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code, unsigned int size, struct fuse_copy_state *cs) { /* Don't try to move pages (yet) */ cs->move_pages = 0; switch (code) { case FUSE_NOTIFY_POLL: return fuse_notify_poll(fc, size, cs); case FUSE_NOTIFY_INVAL_INODE: return fuse_notify_inval_inode(fc, size, cs); case FUSE_NOTIFY_INVAL_ENTRY: return fuse_notify_inval_entry(fc, size, cs); case FUSE_NOTIFY_STORE: return fuse_notify_store(fc, size, cs); case FUSE_NOTIFY_RETRIEVE: return fuse_notify_retrieve(fc, size, cs); case FUSE_NOTIFY_DELETE: return fuse_notify_delete(fc, size, cs); default: fuse_copy_finish(cs); return -EINVAL; } } static struct fuse_req *request_find(struct fuse_conn *fc, u64 unique) { struct list_head *entry; list_for_each(entry, &fc->processing) { struct fuse_req *req; req = list_entry(entry, struct fuse_req, list); if (req->in.h.unique == unique || req->intr_unique == unique) return req; } return NULL; } static int copy_out_args(struct fuse_copy_state *cs, struct fuse_out *out, unsigned nbytes) { unsigned reqsize = sizeof(struct fuse_out_header); if (out->h.error) return nbytes != reqsize ? -EINVAL : 0; reqsize += len_args(out->numargs, out->args); if (reqsize < nbytes || (reqsize > nbytes && !out->argvar)) return -EINVAL; else if (reqsize > nbytes) { struct fuse_arg *lastarg = &out->args[out->numargs-1]; unsigned diffsize = reqsize - nbytes; if (diffsize > lastarg->size) return -EINVAL; lastarg->size -= diffsize; } return fuse_copy_args(cs, out->numargs, out->argpages, out->args, out->page_zeroing); } static ssize_t fuse_dev_do_write(struct fuse_conn *fc, struct fuse_copy_state *cs, size_t nbytes) { int err; struct fuse_req *req; struct fuse_out_header oh; if (nbytes < sizeof(struct fuse_out_header)) return -EINVAL; err = fuse_copy_one(cs, &oh, sizeof(oh)); if (err) goto err_finish; err = -EINVAL; if (oh.len != nbytes) goto err_finish; if (!oh.unique) { err = fuse_notify(fc, oh.error, nbytes - sizeof(oh), cs); return err ? err : nbytes; } err = -EINVAL; if (oh.error <= -1000 || oh.error > 0) goto err_finish; spin_lock(&fc->lock); err = -ENOENT; if (!fc->connected) goto err_unlock; req = request_find(fc, oh.unique); if (!req) goto err_unlock; if (req->aborted) { spin_unlock(&fc->lock); fuse_copy_finish(cs); spin_lock(&fc->lock); request_end(fc, req); return -ENOENT; } if (req->intr_unique == oh.unique) { err = -EINVAL; if (nbytes != sizeof(struct fuse_out_header)) goto err_unlock; if (oh.error == -ENOSYS) fc->no_interrupt = 1; else if (oh.error == -EAGAIN) queue_interrupt(fc, req); spin_unlock(&fc->lock); fuse_copy_finish(cs); return nbytes; } req->state = FUSE_REQ_WRITING; list_move(&req->list, &fc->io); req->out.h = oh; req->locked = 1; cs->req = req; if (!req->out.page_replace) cs->move_pages = 0; spin_unlock(&fc->lock); err = copy_out_args(cs, &req->out, nbytes); if (req->in.h.opcode == FUSE_CANONICAL_PATH) { req->out.h.error = kern_path((char *)req->out.args[0].value, 0, req->canonical_path); } fuse_copy_finish(cs); fuse_setup_shortcircuit(fc, req); spin_lock(&fc->lock); req->locked = 0; if (!err) { if (req->aborted) err = -ENOENT; } else if (!req->aborted) req->out.h.error = -EIO; request_end(fc, req); return err ? err : nbytes; err_unlock: spin_unlock(&fc->lock); err_finish: fuse_copy_finish(cs); return err; } static ssize_t fuse_dev_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct fuse_copy_state cs; struct fuse_conn *fc = fuse_get_conn(iocb->ki_filp); if (!fc) return -EPERM; fuse_copy_init(&cs, fc, 0, iov, nr_segs); return fuse_dev_do_write(fc, &cs, iov_length(iov, nr_segs)); } static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe, struct file *out, loff_t *ppos, size_t len, unsigned int flags) { unsigned nbuf; unsigned idx; struct pipe_buffer *bufs; struct fuse_copy_state cs; struct fuse_conn *fc; size_t rem; ssize_t ret; fc = fuse_get_conn(out); if (!fc) return -EPERM; bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL); if (!bufs) return -ENOMEM; pipe_lock(pipe); nbuf = 0; rem = 0; for (idx = 0; idx < pipe->nrbufs && rem < len; idx++) rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len; ret = -EINVAL; if (rem < len) { pipe_unlock(pipe); goto out; } rem = len; while (rem) { struct pipe_buffer *ibuf; struct pipe_buffer *obuf; BUG_ON(nbuf >= pipe->buffers); BUG_ON(!pipe->nrbufs); ibuf = &pipe->bufs[pipe->curbuf]; obuf = &bufs[nbuf]; if (rem >= ibuf->len) { *obuf = *ibuf; ibuf->ops = NULL; pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1); pipe->nrbufs--; } else { ibuf->ops->get(pipe, ibuf); *obuf = *ibuf; obuf->flags &= ~PIPE_BUF_FLAG_GIFT; obuf->len = rem; ibuf->offset += obuf->len; ibuf->len -= obuf->len; } nbuf++; rem -= obuf->len; } pipe_unlock(pipe); fuse_copy_init(&cs, fc, 0, NULL, nbuf); cs.pipebufs = bufs; cs.pipe = pipe; if (flags & SPLICE_F_MOVE) cs.move_pages = 1; ret = fuse_dev_do_write(fc, &cs, len); for (idx = 0; idx < nbuf; idx++) { struct pipe_buffer *buf = &bufs[idx]; buf->ops->release(pipe, buf); } out: kfree(bufs); return ret; } static unsigned fuse_dev_poll(struct file *file, poll_table *wait) { unsigned mask = POLLOUT | POLLWRNORM; struct fuse_conn *fc = fuse_get_conn(file); if (!fc) return POLLERR; poll_wait(file, &fc->waitq, wait); spin_lock(&fc->lock); if (!fc->connected) mask = POLLERR; else if (request_pending(fc)) mask |= POLLIN | POLLRDNORM; spin_unlock(&fc->lock); return mask; } static void end_requests(struct fuse_conn *fc, struct list_head *head) __releases(fc->lock) __acquires(fc->lock) { while (!list_empty(head)) { struct fuse_req *req; req = list_entry(head->next, struct fuse_req, list); req->out.h.error = -ECONNABORTED; request_end(fc, req); spin_lock(&fc->lock); } } static void end_io_requests(struct fuse_conn *fc) __releases(fc->lock) __acquires(fc->lock) { while (!list_empty(&fc->io)) { struct fuse_req *req = list_entry(fc->io.next, struct fuse_req, list); void (*end) (struct fuse_conn *, struct fuse_req *) = req->end; req->aborted = 1; req->out.h.error = -ECONNABORTED; req->state = FUSE_REQ_FINISHED; list_del_init(&req->list); wake_up(&req->waitq); if (end) { req->end = NULL; __fuse_get_request(req); spin_unlock(&fc->lock); wait_event(req->waitq, !req->locked); end(fc, req); fuse_put_request(fc, req); spin_lock(&fc->lock); } } } static void end_queued_requests(struct fuse_conn *fc) __releases(fc->lock) __acquires(fc->lock) { fc->max_background = UINT_MAX; flush_bg_queue(fc); end_requests(fc, &fc->pending); end_requests(fc, &fc->processing); while (forget_pending(fc)) kfree(dequeue_forget(fc, 1, NULL)); } static void end_polls(struct fuse_conn *fc) { struct rb_node *p; p = rb_first(&fc->polled_files); while (p) { struct fuse_file *ff; ff = rb_entry(p, struct fuse_file, polled_node); wake_up_interruptible_all(&ff->poll_wait); p = rb_next(p); } } void fuse_abort_conn(struct fuse_conn *fc) { spin_lock(&fc->lock); if (fc->connected) { fc->connected = 0; fc->blocked = 0; fc->initialized = 1; end_io_requests(fc); end_queued_requests(fc); end_polls(fc); wake_up_all(&fc->waitq); wake_up_all(&fc->blocked_waitq); kill_fasync(&fc->fasync, SIGIO, POLL_IN); } spin_unlock(&fc->lock); } EXPORT_SYMBOL_GPL(fuse_abort_conn); int fuse_dev_release(struct inode *inode, struct file *file) { struct fuse_conn *fc = fuse_get_conn(file); if (fc) { spin_lock(&fc->lock); fc->connected = 0; fc->blocked = 0; fc->initialized = 1; end_queued_requests(fc); end_polls(fc); wake_up_all(&fc->blocked_waitq); spin_unlock(&fc->lock); fuse_conn_put(fc); } return 0; } EXPORT_SYMBOL_GPL(fuse_dev_release); static int fuse_dev_fasync(int fd, struct file *file, int on) { struct fuse_conn *fc = fuse_get_conn(file); if (!fc) return -EPERM; return fasync_helper(fd, file, on, &fc->fasync); } const struct file_operations fuse_dev_operations = { .owner = THIS_MODULE, .llseek = no_llseek, .read = do_sync_read, .aio_read = fuse_dev_read, .splice_read = fuse_dev_splice_read, .write = do_sync_write, .aio_write = fuse_dev_write, .splice_write = fuse_dev_splice_write, .poll = fuse_dev_poll, .release = fuse_dev_release, .fasync = fuse_dev_fasync, }; EXPORT_SYMBOL_GPL(fuse_dev_operations); static struct miscdevice fuse_miscdevice = { .minor = FUSE_MINOR, .name = "fuse", .fops = &fuse_dev_operations, }; int __init fuse_dev_init(void) { int err = -ENOMEM; fuse_req_cachep = kmem_cache_create("fuse_request", sizeof(struct fuse_req), 0, 0, NULL); if (!fuse_req_cachep) goto out; err = misc_register(&fuse_miscdevice); if (err) goto out_cache_clean; return 0; out_cache_clean: kmem_cache_destroy(fuse_req_cachep); out: return err; } void fuse_dev_cleanup(void) { misc_deregister(&fuse_miscdevice); kmem_cache_destroy(fuse_req_cachep); }
M8s-dev/kernel_htc_msm8939
fs/fuse/dev.c
C
gpl-2.0
44,700
/* * The Mana Client * Copyright (C) 2009-2012 The Mana Developers * * This file is part of The Mana Client. * * 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 * 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 <cstdlib> // pulls in int64_t #include <cstdio> #include <string> #ifndef NET_DOWNLOAD_H #define NET_DOWNLOAD_H enum DownloadStatus { DOWNLOAD_STATUS_CANCELLED = -3, DOWNLOAD_STATUS_THREAD_ERROR = -2, DOWNLOAD_STATUS_ERROR = -1, DOWNLOAD_STATUS_STARTING = 0, DOWNLOAD_STATUS_IDLE, DOWNLOAD_STATUS_COMPLETE }; typedef int (*DownloadUpdate)(void *ptr, DownloadStatus status, size_t total, size_t remaining); // Matches what CURL expects typedef size_t (*WriteFunction)( void *ptr, size_t size, size_t nmemb, void *stream); struct SDL_Thread; typedef void CURL; struct curl_slist; namespace Net { class Download { public: Download(void *ptr, const std::string &url, DownloadUpdate updateFunction); ~Download(); void addHeader(const std::string &header); /** * Convience method for adding no-cache headers. */ void noCache(); void setFile(const std::string &filename, int64_t adler32 = -1); void setWriteFunction(WriteFunction write); /** * Starts the download thread. * @returns true if thread was created * false if the thread could not be made or download wasn't * properly setup */ bool start(); /** * Cancels the download. Returns immediately, the cancelled status will * be noted in the next avialable update call. */ void cancel(); char *getError(); private: static int downloadThread(void *ptr); static int downloadProgress(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow); void *mPtr; std::string mUrl; struct { unsigned cancel : 1; unsigned memoryWrite: 1; unsigned checkAdler: 1; } mOptions; std::string mFileName; WriteFunction mWriteFunction; unsigned long mAdler; DownloadUpdate mUpdateFunction; SDL_Thread *mThread; CURL *mCurl; curl_slist *mHeaders; char *mError; }; } // namespace Net #endif // NET_DOWNLOAD_H
mana/mana
src/net/download.h
C
gpl-2.0
3,033
/* * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.truffle.r.runtime; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; public final class NullProfile { @CompilationFinal private boolean alwaysNull = true; public static NullProfile create() { return new NullProfile(); } public <T> T profile(T value) { if (alwaysNull) { if (value == null) { return null; } CompilerDirectives.transferToInterpreterAndInvalidate(); alwaysNull = false; } return value; } }
akunft/fastr
com.oracle.truffle.r.runtime/src/com/oracle/truffle/r/runtime/NullProfile.java
Java
gpl-2.0
1,667
// Copyright 2022 The Forgotten Server Authors. All rights reserved. // Use of this source code is governed by the GPL-2.0 License that can be found in the LICENSE file. #ifndef FS_HOUSE_H #define FS_HOUSE_H #include <set> #include <unordered_set> #include "container.h" #include "housetile.h" #include "position.h" class House; class BedItem; class Player; class AccessList { public: void parseList(const std::string& list); void addPlayer(const std::string& name); void addGuild(const std::string& name); void addGuildRank(const std::string& name, const std::string& rankName); bool isInList(const Player* player) const; void getList(std::string& list) const; private: std::string list; std::unordered_set<uint32_t> playerList; std::unordered_set<uint32_t> guildRankList; bool allowEveryone = false; }; class Door final : public Item { public: explicit Door(uint16_t type); // non-copyable Door(const Door&) = delete; Door& operator=(const Door&) = delete; Door* getDoor() override { return this; } const Door* getDoor() const override { return this; } House* getHouse() { return house; } //serialization Attr_ReadValue readAttr(AttrTypes_t attr, PropStream& propStream) override; void serializeAttr(PropWriteStream&) const override {} void setDoorId(uint32_t doorId) { setIntAttr(ITEM_ATTRIBUTE_DOORID, doorId); } uint32_t getDoorId() const { return getIntAttr(ITEM_ATTRIBUTE_DOORID); } bool canUse(const Player* player); void setAccessList(const std::string& textlist); bool getAccessList(std::string& list) const; void onRemoved() override; private: void setHouse(House* house); House* house = nullptr; std::unique_ptr<AccessList> accessList; friend class House; }; enum AccessList_t { GUEST_LIST = 0x100, SUBOWNER_LIST = 0x101, }; enum AccessHouseLevel_t { HOUSE_NOT_INVITED = 0, HOUSE_GUEST = 1, HOUSE_SUBOWNER = 2, HOUSE_OWNER = 3, }; using HouseTileList = std::list<HouseTile*>; using HouseBedItemList = std::list<BedItem*>; class HouseTransferItem final : public Item { public: static HouseTransferItem* createHouseTransferItem(House* house); explicit HouseTransferItem(House* house) : Item(0), house(house) {} void onTradeEvent(TradeEvents_t event, Player* owner) override; bool canTransform() const override { return false; } private: House* house; }; class House { public: explicit House(uint32_t houseId); void addTile(HouseTile* tile); void updateDoorDescription() const; bool canEditAccessList(uint32_t listId, const Player* player); // listId special values: // GUEST_LIST guest list // SUBOWNER_LIST subowner list void setAccessList(uint32_t listId, const std::string& textlist); bool getAccessList(uint32_t listId, std::string& list) const; bool isInvited(const Player* player) const; AccessHouseLevel_t getHouseAccessLevel(const Player* player) const; bool kickPlayer(Player* player, Player* target); void setEntryPos(Position pos) { posEntry = pos; } const Position& getEntryPosition() const { return posEntry; } void setName(std::string houseName) { this->houseName = houseName; } const std::string& getName() const { return houseName; } void setOwner(uint32_t guid, bool updateDatabase = true, Player* player = nullptr); uint32_t getOwner() const { return owner; } void setPaidUntil(time_t paid) { paidUntil = paid; } time_t getPaidUntil() const { return paidUntil; } void setRent(uint32_t rent) { this->rent = rent; } uint32_t getRent() const { return rent; } void setPayRentWarnings(uint32_t warnings) { rentWarnings = warnings; } uint32_t getPayRentWarnings() const { return rentWarnings; } void setTownId(uint32_t townId) { this->townId = townId; } uint32_t getTownId() const { return townId; } uint32_t getId() const { return id; } void addDoor(Door* door); void removeDoor(Door* door); Door* getDoorByNumber(uint32_t doorId) const; Door* getDoorByPosition(const Position& pos); HouseTransferItem* getTransferItem(); void resetTransferItem(); bool executeTransfer(HouseTransferItem* item, Player* newOwner); const HouseTileList& getTiles() const { return houseTiles; } const std::set<Door*>& getDoors() const { return doorSet; } void addBed(BedItem* bed); const HouseBedItemList& getBeds() const { return bedsList; } uint32_t getBedCount() { return static_cast<uint32_t>(std::ceil(bedsList.size() / 2.)); //each bed takes 2 sqms of space, ceil is just for bad maps } private: bool transferToDepot() const; bool transferToDepot(Player* player) const; AccessList guestList; AccessList subOwnerList; Container transfer_container{ITEM_LOCKER1}; HouseTileList houseTiles; std::set<Door*> doorSet; HouseBedItemList bedsList; std::string houseName; std::string ownerName; HouseTransferItem* transferItem = nullptr; time_t paidUntil = 0; uint32_t id; uint32_t owner = 0; uint32_t ownerAccountId = 0; uint32_t rentWarnings = 0; uint32_t rent = 0; uint32_t townId = 0; Position posEntry = {}; bool isLoaded = false; }; using HouseMap = std::map<uint32_t, House*>; enum RentPeriod_t { RENTPERIOD_DAILY, RENTPERIOD_WEEKLY, RENTPERIOD_MONTHLY, RENTPERIOD_YEARLY, RENTPERIOD_NEVER, }; class Houses { public: Houses() = default; ~Houses() { for (const auto& it : houseMap) { delete it.second; } } // non-copyable Houses(const Houses&) = delete; Houses& operator=(const Houses&) = delete; House* addHouse(uint32_t id) { auto it = houseMap.find(id); if (it != houseMap.end()) { return it->second; } House* house = new House(id); houseMap[id] = house; return house; } House* getHouse(uint32_t houseId) { auto it = houseMap.find(houseId); if (it == houseMap.end()) { return nullptr; } return it->second; } House* getHouseByPlayerId(uint32_t playerId); bool loadHousesXML(const std::string& filename); void payHouses(RentPeriod_t rentPeriod) const; const HouseMap& getHouses() const { return houseMap; } private: HouseMap houseMap; }; #endif // FS_HOUSE_H
otland/forgottenserver
src/house.h
C
gpl-2.0
6,244
#pragma once /* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #if !defined(TARGET_WINDOWS) #define DECLARE_UNUSED(a,b) a __attribute__((unused)) b; #endif /***************** * All platforms *****************/ #define HAS_DVD_SWSCALE #define HAS_VideoPlayer #define HAS_EVENT_SERVER #define HAS_SCREENSAVER #define HAS_VIDEO_PLAYBACK #define HAS_VISUALISATION #define HAS_PVRCLIENTS #define HAS_ADSPADDONS #ifdef HAVE_LIBMICROHTTPD #define HAS_WEB_SERVER #define HAS_WEB_INTERFACE #endif #define HAS_JSONRPC #define HAS_FILESYSTEM #define HAS_FILESYSTEM_CDDA #ifdef HAVE_LIBSMBCLIENT #define HAS_FILESYSTEM_SMB #endif #ifdef HAVE_LIBNFS #define HAS_FILESYSTEM_NFS #endif #ifdef HAVE_LIBPLIST #define HAS_AIRPLAY #endif #if defined(HAVE_LIBSHAIRPLAY) #define HAS_AIRTUNES #endif #ifdef HAVE_MYSQL #define HAS_MYSQL #endif #if defined(USE_UPNP) #define HAS_UPNP #endif #if defined(HAVE_LIBMDNS) #define HAS_ZEROCONF #define HAS_MDNS #if defined(HAVE_LIBMDNSEMBEDDED) #define HAS_MDNS_EMBEDDED #endif #endif /***************** * Win32 Specific *****************/ #if defined(TARGET_WINDOWS) #define HAS_WIN32_NETWORK #define HAS_IRSERVERSUITE #define HAS_FILESYSTEM_SMB #define DECLARE_UNUSED(a,b) a b; #endif /***************** * Mac Specific *****************/ #if defined(TARGET_DARWIN) #if defined(TARGET_DARWIN_OSX) #define HAS_GL #define HAS_SDL #define HAS_SDL_WIN_EVENTS #endif #define HAS_ZEROCONF #define HAS_LINUX_NETWORK #endif /***************** * Linux Specific *****************/ #if defined(TARGET_LINUX) || defined(TARGET_FREEBSD) #if defined(HAVE_LIBAVAHI_COMMON) && defined(HAVE_LIBAVAHI_CLIENT) #define HAS_ZEROCONF #define HAS_AVAHI #endif #ifdef HAVE_DBUS #define HAS_DBUS #endif #define HAS_GL #ifdef HAVE_X11 #define HAS_X11_WIN_EVENTS #endif #ifdef HAVE_SDL #define HAS_SDL #ifndef HAVE_X11 #define HAS_SDL_WIN_EVENTS #endif #else #ifndef HAVE_X11 #define HAS_LINUX_EVENTS #endif #endif #define HAS_LINUX_NETWORK #ifdef HAVE_LIRC #define HAS_LIRC #endif #ifdef HAVE_LIBPULSE #define HAS_PULSEAUDIO #endif #ifdef HAVE_ALSA #define HAS_ALSA #endif #endif #ifdef HAVE_LIBSSH #define HAS_FILESYSTEM_SFTP #endif #if defined(HAVE_X11) #define HAS_EGL #if !defined(HAVE_LIBGLESV2) #define HAS_GLX #endif #endif /**************************************** * Additional platform specific includes ****************************************/ #if defined(TARGET_WINDOWS) #include <windows.h> #define DIRECTINPUT_VERSION 0x0800 #include "mmsystem.h" #include "DInput.h" #include "DSound.h" #define DSSPEAKER_USE_DEFAULT DSSPEAKER_STEREO #define LPDIRECTSOUND8 LPDIRECTSOUND #undef GetFreeSpace #include "PlatformInclude.h" #ifdef HAS_DX #include "d3d9.h" // On Win32, we're always using DirectX for something, whether it be the actual rendering #include "d3d11_1.h" #include "dxgi.h" #include "d3dcompiler.h" #include "directxmath.h" #else #include <d3d9types.h> #endif #ifdef HAS_SDL #include "SDL\SDL.h" #endif #endif #if defined(TARGET_POSIX) #include <time.h> #include <sys/time.h> #include <sys/types.h> #include <errno.h> #include "PlatformInclude.h" #endif #if defined(TARGET_ANDROID) #undef HAS_LINUX_EVENTS #undef HAS_LIRC #endif #ifdef HAVE_LIBEGL #define HAS_EGL #endif // GLES2.0 detected. Dont use GL! #ifdef HAVE_LIBGLESV2 #undef HAS_GL #define HAS_GLES 2 #endif // GLES1.0 detected. Dont use GL! #ifdef HAVE_LIBGLES #undef HAS_GL #define HAS_GLES 1 #endif #ifdef HAS_DVD_DRIVE #define HAS_CDDA_RIPPER #endif #define SAFE_DELETE(p) do { delete (p); (p)=NULL; } while (0) #define SAFE_DELETE_ARRAY(p) do { delete[] (p); (p)=NULL; } while (0) #define SAFE_RELEASE(p) do { if(p) { (p)->Release(); (p)=NULL; } } while (0) // Useful pixel colour manipulation macros #define GET_A(color) ((color >> 24) & 0xFF) #define GET_R(color) ((color >> 16) & 0xFF) #define GET_G(color) ((color >> 8) & 0xFF) #define GET_B(color) ((color >> 0) & 0xFF)
stammen/xbmc
xbmc/system.h
C
gpl-2.0
4,693
<html> <head> <title>RunUO Documentation - Class Overview - RenameRequests</title> </head> <body bgcolor="white" style="font-family: Courier New" text="#000000" link="#000000" vlink="#000000" alink="#808080"> <h4><a href="../namespaces/Server.Misc.html">Back to Server.Misc</a></h4> <h2>RenameRequests</h2> (<font color="blue">static</font>) <font color="blue">void</font> EventSink_RenameRequest( <!-- DBG-0 --><a href="RenameRequestEventArgs.html">RenameRequestEventArgs</a> e )<br> (<font color="blue">static</font>) <font color="blue">void</font> Initialize()<br> (<font color="blue">ctor</font>) RenameRequests()<br> </body> </html>
alucardxlx/caoticamente-shards
docs/types/RenameRequests.html
HTML
gpl-2.0
698
<?php /** * A project's member requests * * @uses $vars['entity'] Elggproject * @uses $vars['requests'] Array of ElggUsers */ if (!empty($vars['requests']) && is_array($vars['requests'])) { echo '<ul class="elgg-list">'; foreach ($vars['requests'] as $user) { $icon = elgg_view_entity_icon($user, 'tiny', array('use_hover' => 'true')); $user_title = elgg_view('output/url', array( 'href' => $user->getURL(), 'text' => $user->name, 'is_trusted' => true, )); $url = "action/projects/addfbacker?user_guid={$user->guid}&project_guid={$vars['entity']->guid}"; $url = elgg_add_action_tokens_to_url($url); $accept_button = elgg_view('output/url', array( 'href' => $url, 'text' => elgg_echo('accept'), 'class' => 'elgg-button elgg-button-submit', 'is_trusted' => true, )); $url = 'action/projects/killfbacker?user_guid=' . $user->guid . '&project_guid=' . $vars['entity']->guid; $delete_button = elgg_view('output/confirmlink', array( 'href' => $url, 'confirm' => elgg_echo('projects:backerrequest:remove:check'), 'text' => elgg_echo('delete'), 'class' => 'elgg-button elgg-button-delete mlm', )); $body = "<h4>$user_title</h4>"; $alt = $accept_button . $delete_button; echo '<li class="pvs">'; echo elgg_view_image_block($icon, $body, array('image_alt' => $alt)); echo '</li>'; } echo '</ul>'; } else { echo '<p class="mtm">' . elgg_echo('projects:requests:none') . '</p>'; }
CyberCRI/creabator
mod/projects/views/default/projects/fbacker_request.php
PHP
gpl-2.0
1,454
/* * Driver for the NXP SAA7164 PCIe bridge * * Copyright (c) 2010 Steven Toth <stoth@kernellabs.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/io.h> #include "saa7164.h" static int i2c_xfer(struct i2c_adapter *i2c_adap, struct i2c_msg *msgs, int num) { struct saa7164_i2c *bus = i2c_adap->algo_data; struct saa7164_dev *dev = bus->dev; int i, retval = 0; dprintk(DBGLVL_I2C, "%s(num = %d)\n", __func__, num); for (i = 0 ; i < num; i++) { dprintk(DBGLVL_I2C, "%s(num = %d) addr = 0x%02x len = 0x%x\n", __func__, num, msgs[i].addr, msgs[i].len); if (msgs[i].flags & I2C_M_RD) { /* Unsupported - Yet*/ printk(KERN_ERR "%s() Unsupported - Yet\n", __func__); continue; } else if (i + 1 < num && (msgs[i + 1].flags & I2C_M_RD) && msgs[i].addr == msgs[i + 1].addr) { /* write then read from same address */ retval = saa7164_api_i2c_read(bus, msgs[i].addr, msgs[i].len, msgs[i].buf, msgs[i+1].len, msgs[i+1].buf ); i++; if (retval < 0) goto err; } else { /* write */ retval = saa7164_api_i2c_write(bus, msgs[i].addr, msgs[i].len, msgs[i].buf); } if (retval < 0) goto err; } return num; err: return retval; } void saa7164_call_i2c_clients(struct saa7164_i2c *bus, unsigned int cmd, void *arg) { if (bus->i2c_rc != 0) return; i2c_clients_command(&bus->i2c_adap, cmd, arg); } static u32 saa7164_functionality(struct i2c_adapter *adap) { return I2C_FUNC_I2C; } static struct i2c_algorithm saa7164_i2c_algo_template = { .master_xfer = i2c_xfer, .functionality = saa7164_functionality, }; /* ----------------------------------------------------------------------- */ static struct i2c_adapter saa7164_i2c_adap_template = { .name = "saa7164", .owner = THIS_MODULE, .algo = &saa7164_i2c_algo_template, }; static struct i2c_client saa7164_i2c_client_template = { .name = "saa7164 internal", }; int saa7164_i2c_register(struct saa7164_i2c *bus) { struct saa7164_dev *dev = bus->dev; dprintk(DBGLVL_I2C, "%s(bus = %d)\n", __func__, bus->nr); memcpy(&bus->i2c_adap, &saa7164_i2c_adap_template, sizeof(bus->i2c_adap)); memcpy(&bus->i2c_algo, &saa7164_i2c_algo_template, sizeof(bus->i2c_algo)); memcpy(&bus->i2c_client, &saa7164_i2c_client_template, sizeof(bus->i2c_client)); bus->i2c_adap.dev.parent = &dev->pci->dev; strlcpy(bus->i2c_adap.name, bus->dev->name, sizeof(bus->i2c_adap.name)); bus->i2c_algo.data = bus; bus->i2c_adap.algo_data = bus; i2c_set_adapdata(&bus->i2c_adap, bus); i2c_add_adapter(&bus->i2c_adap); bus->i2c_client.adapter = &bus->i2c_adap; if (0 != bus->i2c_rc) printk(KERN_ERR "%s: i2c bus %d register FAILED\n", dev->name, bus->nr); return bus->i2c_rc; } int saa7164_i2c_unregister(struct saa7164_i2c *bus) { i2c_del_adapter(&bus->i2c_adap); return 0; }
Jackeagle/android_kernel_sony_c2305
drivers/media/video/saa7164/saa7164-i2c.c
C
gpl-2.0
3,807
/* * menu.c - the menu idle governor * * Copyright (C) 2006-2007 Adam Belay <abelay@novell.com> * Copyright (C) 2009 Intel Corporation * Author: * Arjan van de Ven <arjan@linux.intel.com> * * This code is licenced under the GPL version 2 as described * in the COPYING file that acompanies the Linux Kernel. */ #include <linux/kernel.h> #include <linux/cpuidle.h> #include <linux/pm_qos.h> #include <linux/time.h> #include <linux/ktime.h> #include <linux/hrtimer.h> #include <linux/tick.h> #include <linux/sched.h> #include <linux/math64.h> #include <linux/module.h> #define BUCKETS 12 #define INTERVALS 8 #define RESOLUTION 1024 #define DECAY 8 #define MAX_INTERESTING 50000 #define STDDEV_THRESH 400 /* 60 * 60 > STDDEV_THRESH * INTERVALS = 400 * 8 */ #define MAX_DEVIATION 60 static DEFINE_PER_CPU(struct hrtimer, menu_hrtimer); static DEFINE_PER_CPU(int, hrtimer_status); /* menu hrtimer mode */ enum {MENU_HRTIMER_STOP, MENU_HRTIMER_REPEAT, MENU_HRTIMER_GENERAL}; /* * Concepts and ideas behind the menu governor * * For the menu governor, there are 3 decision factors for picking a C * state: * 1) Energy break even point * 2) Performance impact * 3) Latency tolerance (from pmqos infrastructure) * These these three factors are treated independently. * * Energy break even point * ----------------------- * C state entry and exit have an energy cost, and a certain amount of time in * the C state is required to actually break even on this cost. CPUIDLE * provides us this duration in the "target_residency" field. So all that we * need is a good prediction of how long we'll be idle. Like the traditional * menu governor, we start with the actual known "next timer event" time. * * Since there are other source of wakeups (interrupts for example) than * the next timer event, this estimation is rather optimistic. To get a * more realistic estimate, a correction factor is applied to the estimate, * that is based on historic behavior. For example, if in the past the actual * duration always was 50% of the next timer tick, the correction factor will * be 0.5. * * menu uses a running average for this correction factor, however it uses a * set of factors, not just a single factor. This stems from the realization * that the ratio is dependent on the order of magnitude of the expected * duration; if we expect 500 milliseconds of idle time the likelihood of * getting an interrupt very early is much higher than if we expect 50 micro * seconds of idle time. A second independent factor that has big impact on * the actual factor is if there is (disk) IO outstanding or not. * (as a special twist, we consider every sleep longer than 50 milliseconds * as perfect; there are no power gains for sleeping longer than this) * * For these two reasons we keep an array of 12 independent factors, that gets * indexed based on the magnitude of the expected duration as well as the * "is IO outstanding" property. * * Repeatable-interval-detector * ---------------------------- * There are some cases where "next timer" is a completely unusable predictor: * Those cases where the interval is fixed, for example due to hardware * interrupt mitigation, but also due to fixed transfer rate devices such as * mice. * For this, we use a different predictor: We track the duration of the last 8 * intervals and if the stand deviation of these 8 intervals is below a * threshold value, we use the average of these intervals as prediction. * * Limiting Performance Impact * --------------------------- * C states, especially those with large exit latencies, can have a real * noticeable impact on workloads, which is not acceptable for most sysadmins, * and in addition, less performance has a power price of its own. * * As a general rule of thumb, menu assumes that the following heuristic * holds: * The busier the system, the less impact of C states is acceptable * * This rule-of-thumb is implemented using a performance-multiplier: * If the exit latency times the performance multiplier is longer than * the predicted duration, the C state is not considered a candidate * for selection due to a too high performance impact. So the higher * this multiplier is, the longer we need to be idle to pick a deep C * state, and thus the less likely a busy CPU will hit such a deep * C state. * * Two factors are used in determing this multiplier: * a value of 10 is added for each point of "per cpu load average" we have. * a value of 5 points is added for each process that is waiting for * IO on this CPU. * (these values are experimentally determined) * * The load average factor gives a longer term (few seconds) input to the * decision, while the iowait value gives a cpu local instantanious input. * The iowait factor may look low, but realize that this is also already * represented in the system load average. * */ /* * The C-state residency is so long that is is worthwhile to exit * from the shallow C-state and re-enter into a deeper C-state. */ static unsigned int perfect_cstate_ms __read_mostly = 30; module_param(perfect_cstate_ms, uint, 0000); struct menu_device { int last_state_idx; int needs_update; unsigned int expected_us; u64 predicted_us; unsigned int exit_us; unsigned int bucket; u64 correction_factor[BUCKETS]; u32 intervals[INTERVALS]; int interval_ptr; }; #define LOAD_INT(x) ((x) >> FSHIFT) #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100) /* static int get_loadavg(void) { unsigned long this = this_cpu_load(); return LOAD_INT(this) * 10 + LOAD_FRAC(this) / 10; } */ static inline int which_bucket(unsigned int duration) { int bucket = 0; /* * We keep two groups of stats; one with no * IO pending, one without. * This allows us to calculate * E(duration)|iowait */ if (nr_iowait_cpu(smp_processor_id())) bucket = BUCKETS/2; if (duration < 10) return bucket; if (duration < 100) return bucket + 1; if (duration < 1000) return bucket + 2; if (duration < 10000) return bucket + 3; if (duration < 100000) return bucket + 4; return bucket + 5; } /* * Return a multiplier for the exit latency that is intended * to take performance requirements into account. * The more performance critical we estimate the system * to be, the higher this multiplier, and thus the higher * the barrier to go to an expensive C state. */ static inline int performance_multiplier(void) { int mult = 1; /* for higher loadavg, we are more reluctant */ /* * this doesn't work as intended - it is almost always 0, but can * sometimes, depending on workload, spike very high into the hundreds * even when the average cpu load is under 10%. */ /* mult += 2 * get_loadavg(); */ /* for IO wait tasks (per cpu!) we add 5x each */ mult += 10 * nr_iowait_cpu(smp_processor_id()); return mult; } static DEFINE_PER_CPU(struct menu_device, menu_devices); static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev); /* This implements DIV_ROUND_CLOSEST but avoids 64 bit division */ static u64 div_round64(u64 dividend, u32 divisor) { return div_u64(dividend + (divisor / 2), divisor); } /* Cancel the hrtimer if it is not triggered yet */ void menu_hrtimer_cancel(void) { int cpu = smp_processor_id(); struct hrtimer *hrtmr = &per_cpu(menu_hrtimer, cpu); /* The timer is still not time out*/ if (per_cpu(hrtimer_status, cpu)) { hrtimer_cancel(hrtmr); per_cpu(hrtimer_status, cpu) = MENU_HRTIMER_STOP; } } EXPORT_SYMBOL_GPL(menu_hrtimer_cancel); /* Call back for hrtimer is triggered */ static enum hrtimer_restart menu_hrtimer_notify(struct hrtimer *hrtimer) { int cpu = smp_processor_id(); struct menu_device *data = &per_cpu(menu_devices, cpu); /* In general case, the expected residency is much larger than * deepest C-state target residency, but prediction logic still * predicts a small predicted residency, so the prediction * history is totally broken if the timer is triggered. * So reset the correction factor. */ if (per_cpu(hrtimer_status, cpu) == MENU_HRTIMER_GENERAL) data->correction_factor[data->bucket] = RESOLUTION * DECAY; per_cpu(hrtimer_status, cpu) = MENU_HRTIMER_STOP; return HRTIMER_NORESTART; } /* * Try detecting repeating patterns by keeping track of the last 8 * intervals, and checking if the standard deviation of that set * of points is below a threshold. If it is... then use the * average of these 8 points as the estimated value. */ static u32 get_typical_interval(struct menu_device *data) { int i = 0, divisor = 0; uint64_t max = 0, avg = 0, stddev = 0; int64_t thresh = LLONG_MAX; /* Discard outliers above this value. */ unsigned int ret = 0; again: /* first calculate average and standard deviation of the past */ max = avg = divisor = stddev = 0; for (i = 0; i < INTERVALS; i++) { int64_t value = data->intervals[i]; if (value <= thresh) { avg += value; divisor++; if (value > max) max = value; } } do_div(avg, divisor); for (i = 0; i < INTERVALS; i++) { int64_t value = data->intervals[i]; if (value <= thresh) { int64_t diff = value - avg; stddev += diff * diff; } } do_div(stddev, divisor); stddev = int_sqrt(stddev); /* * If we have outliers to the upside in our distribution, discard * those by setting the threshold to exclude these outliers, then * calculate the average and standard deviation again. Once we get * down to the bottom 3/4 of our samples, stop excluding samples. * * This can deal with workloads that have long pauses interspersed * with sporadic activity with a bunch of short pauses. * * The typical interval is obtained when standard deviation is small * or standard deviation is small compared to the average interval. */ if (((avg > stddev * 6) && (divisor * 4 >= INTERVALS * 3)) || stddev <= 20) { data->predicted_us = avg; ret = 1; return ret; } else if ((divisor * 4) > INTERVALS * 3) { /* Exclude the max interval */ thresh = max - 1; goto again; } return ret; } /* In some cases, idle should return RIGHT index to enter * correct idle states. */ #define CONFIG_SKIP_IDLE_CORRELATION /** * menu_select - selects the next idle state to enter * @drv: cpuidle driver containing state data * @dev: the CPU */ static int menu_select(struct cpuidle_driver *drv, struct cpuidle_device *dev) { struct menu_device *data = &__get_cpu_var(menu_devices); int latency_req = pm_qos_request(PM_QOS_CPU_DMA_LATENCY); int i; int multiplier; struct timespec t; int repeat = 0, low_predicted = 0; int cpu = smp_processor_id(); struct hrtimer *hrtmr = &per_cpu(menu_hrtimer, cpu); if (data->needs_update) { menu_update(drv, dev); data->needs_update = 0; } data->last_state_idx = 0; data->exit_us = 0; /* Special case when user has set very strict latency requirement */ if (unlikely(latency_req == 0)) return 0; /* determine the expected residency time, round up */ t = ktime_to_timespec(tick_nohz_get_sleep_length()); data->expected_us = t.tv_sec * USEC_PER_SEC + t.tv_nsec / NSEC_PER_USEC; data->bucket = which_bucket(data->expected_us); multiplier = performance_multiplier(); #ifdef CONFIG_SKIP_IDLE_CORRELATION if (dev->skip_idle_correlation) data->correction_factor[data->bucket] = RESOLUTION * DECAY; #endif /* * if the correction factor is 0 (eg first time init or cpu hotplug * etc), we actually want to start out with a unity factor. */ if (data->correction_factor[data->bucket] == 0) data->correction_factor[data->bucket] = RESOLUTION * DECAY; /* Make sure to round up for half microseconds */ data->predicted_us = div_round64(data->expected_us * data->correction_factor[data->bucket], RESOLUTION * DECAY); /* This patch is not checked */ #ifndef CONFIG_CPU_THERMAL_IPA repeat = get_typical_interval(data); #else /* * HACK - Ignore repeating patterns when we're * forecasting a very large idle period. */ if(data->predicted_us < MAX_INTERESTING) repeat = get_typical_interval(data); #endif /* * We want to default to C1 (hlt), not to busy polling * unless the timer is happening really really soon. */ if (data->expected_us > 5 && !drv->states[CPUIDLE_DRIVER_STATE_START].disabled && dev->states_usage[CPUIDLE_DRIVER_STATE_START].disable == 0) data->last_state_idx = CPUIDLE_DRIVER_STATE_START; /* * Find the idle state with the lowest power while satisfying * our constraints. */ for (i = CPUIDLE_DRIVER_STATE_START; i < drv->state_count; i++) { struct cpuidle_state *s = &drv->states[i]; struct cpuidle_state_usage *su = &dev->states_usage[i]; if (s->disabled || su->disable) continue; if (s->target_residency > data->predicted_us) { low_predicted = 1; continue; } if (s->exit_latency > latency_req) continue; if (s->exit_latency * multiplier > data->predicted_us) continue; data->last_state_idx = i; data->exit_us = s->exit_latency; } /* not deepest C-state chosen for low predicted residency */ if (low_predicted) { unsigned int timer_us = 0; unsigned int perfect_us = 0; /* * Set a timer to detect whether this sleep is much * longer than repeat mode predicted. If the timer * triggers, the code will evaluate whether to put * the CPU into a deeper C-state. * The timer is cancelled on CPU wakeup. */ timer_us = 2 * (data->predicted_us + MAX_DEVIATION); perfect_us = perfect_cstate_ms * 1000; if (repeat && (4 * timer_us < data->expected_us)) { RCU_NONIDLE(hrtimer_start(hrtmr, ns_to_ktime(1000 * timer_us), HRTIMER_MODE_REL_PINNED)); /* In repeat case, menu hrtimer is started */ per_cpu(hrtimer_status, cpu) = MENU_HRTIMER_REPEAT; } else if (perfect_us < data->expected_us) { /* * The next timer is long. This could be because * we did not make a useful prediction. * In that case, it makes sense to re-enter * into a deeper C-state after some time. */ RCU_NONIDLE(hrtimer_start(hrtmr, ns_to_ktime(1000 * timer_us), HRTIMER_MODE_REL_PINNED)); /* In general case, menu hrtimer is started */ per_cpu(hrtimer_status, cpu) = MENU_HRTIMER_GENERAL; } } return data->last_state_idx; } /** * menu_reflect - records that data structures need update * @dev: the CPU * @index: the index of actual entered state * * NOTE: it's important to be fast here because this operation will add to * the overall exit latency. */ static void menu_reflect(struct cpuidle_device *dev, int index) { struct menu_device *data = &__get_cpu_var(menu_devices); data->last_state_idx = index; if (index >= 0) data->needs_update = 1; } /** * menu_update - attempts to guess what happened after entry * @drv: cpuidle driver containing state data * @dev: the CPU */ static void menu_update(struct cpuidle_driver *drv, struct cpuidle_device *dev) { struct menu_device *data = &__get_cpu_var(menu_devices); int last_idx = data->last_state_idx; unsigned int last_idle_us = cpuidle_get_last_residency(dev); struct cpuidle_state *target = &drv->states[last_idx]; unsigned int measured_us; u64 new_factor; /* * Ugh, this idle state doesn't support residency measurements, so we * are basically lost in the dark. As a compromise, assume we slept * for the whole expected time. */ if (unlikely(!(target->flags & CPUIDLE_FLAG_TIME_VALID))) last_idle_us = data->expected_us; measured_us = last_idle_us; /* * We correct for the exit latency; we are assuming here that the * exit latency happens after the event that we're interested in. */ if (measured_us > data->exit_us) measured_us -= data->exit_us; /* update our correction ratio */ new_factor = data->correction_factor[data->bucket] * (DECAY - 1) / DECAY; if (data->expected_us > 0 && measured_us < MAX_INTERESTING) new_factor += RESOLUTION * measured_us / data->expected_us; else /* * we were idle so long that we count it as a perfect * prediction */ new_factor += RESOLUTION; /* * We don't want 0 as factor; we always want at least * a tiny bit of estimated time. */ if (new_factor == 0) new_factor = 1; data->correction_factor[data->bucket] = new_factor; /* update the repeating-pattern data */ data->intervals[data->interval_ptr++] = last_idle_us; if (data->interval_ptr >= INTERVALS) data->interval_ptr = 0; } /** * menu_enable_device - scans a CPU's states and does setup * @drv: cpuidle driver * @dev: the CPU */ static int menu_enable_device(struct cpuidle_driver *drv, struct cpuidle_device *dev) { struct menu_device *data = &per_cpu(menu_devices, dev->cpu); struct hrtimer *t = &per_cpu(menu_hrtimer, dev->cpu); hrtimer_init(t, CLOCK_MONOTONIC, HRTIMER_MODE_REL); t->function = menu_hrtimer_notify; memset(data, 0, sizeof(struct menu_device)); return 0; } static struct cpuidle_governor menu_governor = { .name = "menu", .rating = 20, .enable = menu_enable_device, .select = menu_select, .reflect = menu_reflect, .owner = THIS_MODULE, }; /** * init_menu - initializes the governor */ static int __init init_menu(void) { return cpuidle_register_governor(&menu_governor); } /** * exit_menu - exits the governor */ static void __exit exit_menu(void) { cpuidle_unregister_governor(&menu_governor); } MODULE_LICENSE("GPL"); module_init(init_menu); module_exit(exit_menu);
wanam/Adam-Kernel-Note4-N910C
drivers/cpuidle/governors/menu.c
C
gpl-2.0
17,411
/* * scsi_netlink.c - SCSI Transport Netlink Interface * * Copyright (C) 2006 James Smart, Emulex Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/time.h> #include <linux/jiffies.h> #include <linux/security.h> #include <linux/delay.h> #include <net/sock.h> #include <net/netlink.h> #include <scsi/scsi_netlink.h> #include "scsi_priv.h" struct sock *scsi_nl_sock = NULL; EXPORT_SYMBOL_GPL(scsi_nl_sock); static DEFINE_SPINLOCK(scsi_nl_lock); static struct list_head scsi_nl_drivers; static u32 scsi_nl_state; #define STATE_EHANDLER_BSY 0x00000001 struct scsi_nl_transport { int (*msg_handler)(struct sk_buff *); void (*event_handler)(struct notifier_block *, unsigned long, void *); unsigned int refcnt; int flags; }; /* flags values (bit flags) */ #define HANDLER_DELETING 0x1 static struct scsi_nl_transport transports[SCSI_NL_MAX_TRANSPORTS] = { {NULL, }, }; struct scsi_nl_drvr { struct list_head next; int (*dmsg_handler)(struct Scsi_Host *shost, void *payload, u32 len, u32 pid); void (*devt_handler)(struct notifier_block *nb, unsigned long event, void *notify_ptr); struct scsi_host_template *hostt; u64 vendor_id; unsigned int refcnt; int flags; }; /** * scsi_nl_rcv_msg - * Receive message handler. Extracts message from a receive buffer. * Validates message header and calls appropriate transport message handler * * @skb: socket receive buffer * **/ static void scsi_nl_rcv_msg(struct sk_buff *skb) { struct nlmsghdr *nlh; struct scsi_nl_hdr *hdr; unsigned long flags; u32 rlen; int err, tport; while (skb->len >= NLMSG_SPACE(0)) { err = 0; nlh = (struct nlmsghdr *) skb->data; if ((nlh->nlmsg_len < (sizeof(*nlh) + sizeof(*hdr))) || (skb->len < nlh->nlmsg_len)) { printk(KERN_WARNING "%s: discarding partial skb\n", __FUNCTION__); return; } rlen = NLMSG_ALIGN(nlh->nlmsg_len); if (rlen > skb->len) rlen = skb->len; if (nlh->nlmsg_type != SCSI_TRANSPORT_MSG) { err = -EBADMSG; goto next_msg; } hdr = NLMSG_DATA(nlh); if ((hdr->version != SCSI_NL_VERSION) || (hdr->magic != SCSI_NL_MAGIC)) { err = -EPROTOTYPE; goto next_msg; } if (security_netlink_recv(skb, CAP_SYS_ADMIN)) { err = -EPERM; goto next_msg; } if (nlh->nlmsg_len < (sizeof(*nlh) + hdr->msglen)) { printk(KERN_WARNING "%s: discarding partial message\n", __FUNCTION__); goto next_msg; } /* * Deliver message to the appropriate transport */ spin_lock_irqsave(&scsi_nl_lock, flags); tport = hdr->transport; if ((tport < SCSI_NL_MAX_TRANSPORTS) && !(transports[tport].flags & HANDLER_DELETING) && (transports[tport].msg_handler)) { transports[tport].refcnt++; spin_unlock_irqrestore(&scsi_nl_lock, flags); err = transports[tport].msg_handler(skb); spin_lock_irqsave(&scsi_nl_lock, flags); transports[tport].refcnt--; } else err = -ENOENT; spin_unlock_irqrestore(&scsi_nl_lock, flags); next_msg: if ((err) || (nlh->nlmsg_flags & NLM_F_ACK)) netlink_ack(skb, nlh, err); skb_pull(skb, rlen); } } /** * scsi_nl_rcv_msg - * Receive handler for a socket. Extracts a received message buffer from * the socket, and starts message processing. * * @sk: socket * @len: * **/ static void scsi_nl_rcv(struct sock *sk, int len) { struct sk_buff *skb; while ((skb = skb_dequeue(&sk->sk_receive_queue))) { scsi_nl_rcv_msg(skb); kfree_skb(skb); } } /** * scsi_nl_rcv_event - * Event handler for a netlink socket. * * @this: event notifier block * @event: event type * @ptr: event payload * **/ static int scsi_nl_rcv_event(struct notifier_block *this, unsigned long event, void *ptr) { struct netlink_notify *n = ptr; struct scsi_nl_drvr *driver; unsigned long flags; int tport; if (n->protocol != NETLINK_SCSITRANSPORT) return NOTIFY_DONE; spin_lock_irqsave(&scsi_nl_lock, flags); scsi_nl_state |= STATE_EHANDLER_BSY; /* * Pass event on to any transports that may be listening */ for (tport = 0; tport < SCSI_NL_MAX_TRANSPORTS; tport++) { if (!(transports[tport].flags & HANDLER_DELETING) && (transports[tport].event_handler)) { spin_unlock_irqrestore(&scsi_nl_lock, flags); transports[tport].event_handler(this, event, ptr); spin_lock_irqsave(&scsi_nl_lock, flags); } } /* * Pass event on to any drivers that may be listening */ list_for_each_entry(driver, &scsi_nl_drivers, next) { if (!(driver->flags & HANDLER_DELETING) && (driver->devt_handler)) { spin_unlock_irqrestore(&scsi_nl_lock, flags); driver->devt_handler(this, event, ptr); spin_lock_irqsave(&scsi_nl_lock, flags); } } scsi_nl_state &= ~STATE_EHANDLER_BSY; spin_unlock_irqrestore(&scsi_nl_lock, flags); return NOTIFY_DONE; } static struct notifier_block scsi_netlink_notifier = { .notifier_call = scsi_nl_rcv_event, }; /** * GENERIC SCSI transport receive and event handlers **/ /** * scsi_generic_msg_handler - receive message handler for GENERIC transport * messages * * @skb: socket receive buffer * **/ static int scsi_generic_msg_handler(struct sk_buff *skb) { struct nlmsghdr *nlh = (struct nlmsghdr *)skb->data; struct scsi_nl_hdr *snlh = NLMSG_DATA(nlh); struct scsi_nl_drvr *driver; struct Scsi_Host *shost; unsigned long flags; int err = 0, match, pid; pid = NETLINK_CREDS(skb)->pid; switch (snlh->msgtype) { case SCSI_NL_SHOST_VENDOR: { struct scsi_nl_host_vendor_msg *msg = NLMSG_DATA(nlh); /* Locate the driver that corresponds to the message */ spin_lock_irqsave(&scsi_nl_lock, flags); match = 0; list_for_each_entry(driver, &scsi_nl_drivers, next) { if (driver->vendor_id == msg->vendor_id) { match = 1; break; } } if ((!match) || (!driver->dmsg_handler)) { spin_unlock_irqrestore(&scsi_nl_lock, flags); err = -ESRCH; goto rcv_exit; } if (driver->flags & HANDLER_DELETING) { spin_unlock_irqrestore(&scsi_nl_lock, flags); err = -ESHUTDOWN; goto rcv_exit; } driver->refcnt++; spin_unlock_irqrestore(&scsi_nl_lock, flags); /* if successful, scsi_host_lookup takes a shost reference */ shost = scsi_host_lookup(msg->host_no); if (!shost) { err = -ENODEV; goto driver_exit; } /* is this host owned by the vendor ? */ if (shost->hostt != driver->hostt) { err = -EINVAL; goto vendormsg_put; } /* pass message on to the driver */ err = driver->dmsg_handler(shost, (void *)&msg[1], msg->vmsg_datalen, pid); vendormsg_put: /* release reference by scsi_host_lookup */ scsi_host_put(shost); driver_exit: /* release our own reference on the registration object */ spin_lock_irqsave(&scsi_nl_lock, flags); driver->refcnt--; spin_unlock_irqrestore(&scsi_nl_lock, flags); break; } default: err = -EBADR; break; } rcv_exit: if (err) printk(KERN_WARNING "%s: Msgtype %d failed - err %d\n", __func__, snlh->msgtype, err); return err; } /** * scsi_nl_add_transport - * Registers message and event handlers for a transport. Enables * receipt of netlink messages and events to a transport. * * @tport: transport registering handlers * @msg_handler: receive message handler callback * @event_handler: receive event handler callback **/ int scsi_nl_add_transport(u8 tport, int (*msg_handler)(struct sk_buff *), void (*event_handler)(struct notifier_block *, unsigned long, void *)) { unsigned long flags; int err = 0; if (tport >= SCSI_NL_MAX_TRANSPORTS) return -EINVAL; spin_lock_irqsave(&scsi_nl_lock, flags); if (scsi_nl_state & STATE_EHANDLER_BSY) { spin_unlock_irqrestore(&scsi_nl_lock, flags); msleep(1); spin_lock_irqsave(&scsi_nl_lock, flags); } if (transports[tport].msg_handler || transports[tport].event_handler) { err = -EALREADY; goto register_out; } transports[tport].msg_handler = msg_handler; transports[tport].event_handler = event_handler; transports[tport].flags = 0; transports[tport].refcnt = 0; register_out: spin_unlock_irqrestore(&scsi_nl_lock, flags); return err; } EXPORT_SYMBOL_GPL(scsi_nl_add_transport); /** * scsi_nl_remove_transport - * Disable transport receiption of messages and events * * @tport: transport deregistering handlers * **/ void scsi_nl_remove_transport(u8 tport) { unsigned long flags; spin_lock_irqsave(&scsi_nl_lock, flags); if (scsi_nl_state & STATE_EHANDLER_BSY) { spin_unlock_irqrestore(&scsi_nl_lock, flags); msleep(1); spin_lock_irqsave(&scsi_nl_lock, flags); } if (tport < SCSI_NL_MAX_TRANSPORTS) { transports[tport].flags |= HANDLER_DELETING; while (transports[tport].refcnt != 0) { spin_unlock_irqrestore(&scsi_nl_lock, flags); schedule_timeout_uninterruptible(HZ/4); spin_lock_irqsave(&scsi_nl_lock, flags); } transports[tport].msg_handler = NULL; transports[tport].event_handler = NULL; transports[tport].flags = 0; } spin_unlock_irqrestore(&scsi_nl_lock, flags); return; } EXPORT_SYMBOL_GPL(scsi_nl_remove_transport); /** * scsi_nl_add_driver - * A driver is registering its interfaces for SCSI netlink messages * * @vendor_id: A unique identification value for the driver. * @hostt: address of the driver's host template. Used * to verify an shost is bound to the driver * @nlmsg_handler: receive message handler callback * @nlevt_handler: receive event handler callback * * Returns: * 0 on Success * error result otherwise **/ int scsi_nl_add_driver(u64 vendor_id, struct scsi_host_template *hostt, int (*nlmsg_handler)(struct Scsi_Host *shost, void *payload, u32 len, u32 pid), void (*nlevt_handler)(struct notifier_block *nb, unsigned long event, void *notify_ptr)) { struct scsi_nl_drvr *driver; unsigned long flags; driver = kzalloc(sizeof(*driver), GFP_KERNEL); if (unlikely(!driver)) { printk(KERN_ERR "%s: allocation failure\n", __func__); return -ENOMEM; } driver->dmsg_handler = nlmsg_handler; driver->devt_handler = nlevt_handler; driver->hostt = hostt; driver->vendor_id = vendor_id; spin_lock_irqsave(&scsi_nl_lock, flags); if (scsi_nl_state & STATE_EHANDLER_BSY) { spin_unlock_irqrestore(&scsi_nl_lock, flags); msleep(1); spin_lock_irqsave(&scsi_nl_lock, flags); } list_add_tail(&driver->next, &scsi_nl_drivers); spin_unlock_irqrestore(&scsi_nl_lock, flags); return 0; } EXPORT_SYMBOL_GPL(scsi_nl_add_driver); /** * scsi_nl_remove_driver - * An driver is unregistering with the SCSI netlink messages * * @vendor_id: The unique identification value for the driver. **/ void scsi_nl_remove_driver(u64 vendor_id) { struct scsi_nl_drvr *driver; unsigned long flags; spin_lock_irqsave(&scsi_nl_lock, flags); if (scsi_nl_state & STATE_EHANDLER_BSY) { spin_unlock_irqrestore(&scsi_nl_lock, flags); msleep(1); spin_lock_irqsave(&scsi_nl_lock, flags); } list_for_each_entry(driver, &scsi_nl_drivers, next) { if (driver->vendor_id == vendor_id) { driver->flags |= HANDLER_DELETING; while (driver->refcnt != 0) { spin_unlock_irqrestore(&scsi_nl_lock, flags); schedule_timeout_uninterruptible(HZ/4); spin_lock_irqsave(&scsi_nl_lock, flags); } list_del(&driver->next); kfree(driver); spin_unlock_irqrestore(&scsi_nl_lock, flags); return; } } spin_unlock_irqrestore(&scsi_nl_lock, flags); printk(KERN_ERR "%s: removal of driver failed - vendor_id 0x%llx\n", __func__, vendor_id); return; } EXPORT_SYMBOL_GPL(scsi_nl_remove_driver); /** * scsi_netlink_init - * Called by SCSI subsystem to intialize the SCSI transport netlink * interface * **/ void scsi_netlink_init(void) { int error; INIT_LIST_HEAD(&scsi_nl_drivers); error = netlink_register_notifier(&scsi_netlink_notifier); if (error) { printk(KERN_ERR "%s: register of event handler failed - %d\n", __FUNCTION__, error); return; } scsi_nl_sock = netlink_kernel_create(NETLINK_SCSITRANSPORT, SCSI_NL_GRP_CNT, scsi_nl_rcv, THIS_MODULE); if (!scsi_nl_sock) { printk(KERN_ERR "%s: register of recieve handler failed\n", __FUNCTION__); netlink_unregister_notifier(&scsi_netlink_notifier); return; } /* Register the entry points for the generic SCSI transport */ error = scsi_nl_add_transport(SCSI_NL_TRANSPORT, scsi_generic_msg_handler, NULL); if (error) printk(KERN_ERR "%s: register of GENERIC transport handler" " failed - %d\n", __func__, error); return; } /** * scsi_netlink_exit - * Called by SCSI subsystem to disable the SCSI transport netlink * interface * **/ void scsi_netlink_exit(void) { scsi_nl_remove_transport(SCSI_NL_TRANSPORT); if (scsi_nl_sock) { sock_release(scsi_nl_sock->sk_socket); netlink_unregister_notifier(&scsi_netlink_notifier); } return; } /* * Exported Interfaces */ /** * scsi_nl_send_transport_msg - * Generic function to send a single message from a SCSI transport to * a single process * * @pid: receiving pid * @hdr: message payload * **/ void scsi_nl_send_transport_msg(u32 pid, struct scsi_nl_hdr *hdr) { struct sk_buff *skb; struct nlmsghdr *nlh; const char *fn; char *datab; u32 len, skblen; int err; if (!scsi_nl_sock) { err = -ENOENT; fn = "netlink socket"; goto msg_fail; } len = NLMSG_SPACE(hdr->msglen); skblen = NLMSG_SPACE(len); skb = alloc_skb(skblen, GFP_KERNEL); if (!skb) { err = -ENOBUFS; fn = "alloc_skb"; goto msg_fail; } nlh = nlmsg_put(skb, pid, 0, SCSI_TRANSPORT_MSG, len - sizeof(*nlh), 0); if (!nlh) { err = -ENOBUFS; fn = "nlmsg_put"; goto msg_fail_skb; } datab = NLMSG_DATA(nlh); memcpy(datab, hdr, hdr->msglen); err = nlmsg_unicast(scsi_nl_sock, skb, pid); if (err < 0) { fn = "nlmsg_unicast"; /* nlmsg_unicast already kfree_skb'd */ goto msg_fail; } return; msg_fail_skb: kfree_skb(skb); msg_fail: printk(KERN_WARNING "%s: Dropped Message : pid %d Transport %d, msgtype x%x, " "msglen %d: %s : err %d\n", __func__, pid, hdr->transport, hdr->msgtype, hdr->msglen, fn, err); return; } EXPORT_SYMBOL_GPL(scsi_nl_send_transport_msg); /** * scsi_nl_send_vendor_msg - called to send a shost vendor unique message * to a specific process id. * * @pid: process id of the receiver * @host_no: host # sending the message * @vendor_id: unique identifier for the driver's vendor * @data_len: amount, in bytes, of vendor unique payload data * @data_buf: pointer to vendor unique data buffer * * Returns: * 0 on succesful return * otherwise, failing error code * * Notes: * This routine assumes no locks are held on entry. */ int scsi_nl_send_vendor_msg(u32 pid, unsigned short host_no, u64 vendor_id, char *data_buf, u32 data_len) { struct sk_buff *skb; struct nlmsghdr *nlh; struct scsi_nl_host_vendor_msg *msg; u32 len, skblen; int err; if (!scsi_nl_sock) { err = -ENOENT; goto send_vendor_fail; } len = SCSI_NL_MSGALIGN(sizeof(*msg) + data_len); skblen = NLMSG_SPACE(len); skb = alloc_skb(skblen, GFP_KERNEL); if (!skb) { err = -ENOBUFS; goto send_vendor_fail; } nlh = nlmsg_put(skb, 0, 0, SCSI_TRANSPORT_MSG, skblen - sizeof(*nlh), 0); if (!nlh) { err = -ENOBUFS; goto send_vendor_fail_skb; } msg = NLMSG_DATA(nlh); INIT_SCSI_NL_HDR(&msg->snlh, SCSI_NL_TRANSPORT, SCSI_NL_SHOST_VENDOR, len); msg->vendor_id = vendor_id; msg->host_no = host_no; msg->vmsg_datalen = data_len; /* bytes */ memcpy(&msg[1], data_buf, data_len); err = nlmsg_unicast(scsi_nl_sock, skb, pid); if (err) /* nlmsg_multicast already kfree_skb'd */ goto send_vendor_fail; return 0; send_vendor_fail_skb: kfree_skb(skb); send_vendor_fail: printk(KERN_WARNING "%s: Dropped SCSI Msg : host %d vendor_unique - err %d\n", __func__, host_no, err); return err; } EXPORT_SYMBOL(scsi_nl_send_vendor_msg);
dduval/kernel-rhel5
drivers/scsi/scsi_netlink.c
C
gpl-2.0
16,503
/* vim: set ts=8 sw=8 sts=8 noet tw=78: * * tup - A file-based build system * * Copyright (C) 2011-2017 Mike Shal <marfey@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef tup_fuse_fs_h #define tup_fuse_fs_h #define FUSE_USE_VERSION 26 #include <fuse.h> #include "tup/tupid.h" #define TUP_TMP ".tup/tmp" #define TUP_JOB "@tupjob-" struct file_info; int tup_fuse_add_group(int id, struct file_info *finfo); int tup_fuse_rm_group(struct file_info *finfo); void tup_fuse_set_parser_mode(int mode); int tup_fuse_server_get_dir_entries(const char *path, void *buf, fuse_fill_dir_t filler); void tup_fuse_fs_init(void); int tup_fs_inited(void); extern struct fuse_operations tup_fs_oper; #endif
fasterthanlime/tup-fuseless
src/tup/server/tup_fuse_fs.h
C
gpl-2.0
1,337
/* This file is part of the KDE project * Copyright (C) 2010 Matus Talcik <matus.talcik@gmail.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ /**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef KIS_UNDO_MODEL_H #define KIS_UNDO_MODEL_H #include <QAbstractItemModel> #include <kundo2qstack.h> #include <QItemSelectionModel> #include <QIcon> #include <kundo2command.h> #include "kis_types.h" #include "kis_canvas2.h" #include "kis_view2.h" #include "kis_image.h" #include "kis_paint_device.h" class KisUndoModel : public QAbstractItemModel { Q_OBJECT public: KisUndoModel(QObject *parent = 0); KUndo2QStack *stack() const; virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; virtual QModelIndex parent(const QModelIndex &child) const; virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QModelIndex selectedIndex() const; QItemSelectionModel *selectionModel() const; QString emptyLabel() const; void setEmptyLabel(const QString &label); void setCleanIcon(const QIcon &icon); QIcon cleanIcon() const; void setCanvas(KisCanvas2* canvas); public slots: void setStack(KUndo2QStack *stack); void addImage(int idx); private slots: void stackChanged(); void stackDestroyed(QObject *obj); void setStackCurrentIndex(const QModelIndex &index); private: bool m_blockOutgoingHistoryChange; KUndo2QStack *m_stack; QItemSelectionModel *m_sel_model; QString m_empty_label; QIcon m_clean_icon; KisCanvas2* m_canvas; QMap<const KUndo2Command*, QImage> imageMap; }; #endif
harshitamistry/calligraRepository
krita/plugins/extensions/dockers/historydocker/KisUndoModel.h
C
gpl-2.0
3,982
// papi.h // // Copyright 1997-2006 by David K. McAllister // http://www.cs.unc.edu/~davemc/Particle // // Include this file in all applications that use the Particle System API. #ifndef _particle_api_h #define _particle_api_h #include "./pDomain.h" // Defines NULL. #include <stdlib.h> // This is the major and minor version number of this release of the API. #define P_VERSION 200 #ifdef WIN32 // Define PARTICLE_MAKE_DLL in the project file to make the DLL. #ifdef PARTICLE_MAKE_DLL #include <windows.h> #ifdef PARTICLEDLL_EXPORTS #define PARTICLEDLL_API __declspec(dllexport) #else #define PARTICLEDLL_API __declspec(dllimport) #endif #else #define PARTICLEDLL_API #endif #else #define PARTICLEDLL_API #endif // Actually this must be < sqrt(MAXFLOAT) since we store this value squared. #define P_MAXFLOAT 1.0e16f #ifdef MAXINT #define P_MAXINT MAXINT #else #define P_MAXINT 0x7fffffff #endif #define P_EPS 1e-3f // State setting calls PARTICLEDLL_API void pColor(float red, float green, float blue, float alpha = 1.0f); PARTICLEDLL_API void pColorD(const pDomain &cdom); PARTICLEDLL_API void pColorD(const pDomain &cdom, const pDomain &adom); PARTICLEDLL_API void pSize(const pVec &size); PARTICLEDLL_API void pSizeD(const pDomain &dom); PARTICLEDLL_API void pMass(float mass); PARTICLEDLL_API void pStartingAge(float age, float sigma = 1.0f); PARTICLEDLL_API void pTimeStep(float new_dt); PARTICLEDLL_API void pUpVec(const pVec &v); PARTICLEDLL_API void pUpVecD(const pDomain &dom); PARTICLEDLL_API void pVelocity(const pVec &vel); PARTICLEDLL_API void pVelocityD(const pDomain &dom); PARTICLEDLL_API void pRotVelocity(const pVec &v); PARTICLEDLL_API void pRotVelocityD(const pDomain &dom); PARTICLEDLL_API void pVertexB(const pVec &v); PARTICLEDLL_API void pVertexBD(const pDomain &dom); PARTICLEDLL_API void pVertexBTracks(bool track_vertex = true); // Action List Calls PARTICLEDLL_API void pCallActionList(int action_list_num); PARTICLEDLL_API void pDeleteActionLists(int action_list_num, int action_list_count = 1); PARTICLEDLL_API void pEndActionList(); PARTICLEDLL_API int pGenActionLists(int action_list_count = 1); PARTICLEDLL_API void pNewActionList(int action_list_num); // Particle Group Calls PARTICLEDLL_API void pCopyGroup(int p_src_group_num, size_t index = 0, size_t copy_count = P_MAXINT); PARTICLEDLL_API void pCurrentGroup(int p_group_num); PARTICLEDLL_API void pDeleteParticleGroups(int p_group_num, int p_group_count = 1); PARTICLEDLL_API int pGenParticleGroups(int p_group_count = 1, size_t max_particles = 0); PARTICLEDLL_API size_t pGetGroupCount(); PARTICLEDLL_API size_t pGetParticles(size_t index, size_t count, float *position = NULL, float *color = NULL, float *vel = NULL, float *size = NULL, float *age = NULL); PARTICLEDLL_API size_t pGetParticlePointer(float *&ptr, size_t &stride, size_t &pos3Ofs, size_t &posB3Ofs, size_t &size3Ofs, size_t &vel3Ofs, size_t &velB3Ofs, size_t &color3Ofs, size_t &alpha1Ofs, size_t &age1Ofs); PARTICLEDLL_API size_t pSetMaxParticles(size_t max_count); PARTICLEDLL_API size_t pGetMaxParticles(); // Actions PARTICLEDLL_API void pAvoid(float magnitude, float epsilon, float look_ahead, const pDomain &dom); PARTICLEDLL_API void pBounce(float friction, float resilience, float cutoff, const pDomain &dom); PARTICLEDLL_API void pCopyVertexB(bool copy_pos = true, bool copy_vel = false); PARTICLEDLL_API void pDamping(const pVec &damping, float vlow = 0.0f, float vhigh = P_MAXFLOAT); PARTICLEDLL_API void pRotDamping(const pVec &damping, float vlow = 0.0f, float vhigh = P_MAXFLOAT); PARTICLEDLL_API void pExplosion(const pVec &center, float velocity, float magnitude, float stdev, float epsilon = P_EPS, float age = 0.0f); PARTICLEDLL_API void pFollow(float magnitude = 1.0f, float epsilon = P_EPS, float max_radius = P_MAXFLOAT); PARTICLEDLL_API void pFountain(); // EXPERIMENTAL. DO NOT USE! PARTICLEDLL_API void pGravitate(float magnitude = 1.0f, float epsilon = P_EPS, float max_radius = P_MAXFLOAT); PARTICLEDLL_API void pGravity(const pVec &dir); PARTICLEDLL_API void pJet(const pDomain &dom, const pDomain &acc); PARTICLEDLL_API void pKillOld(float age_limit, bool kill_less_than = false); PARTICLEDLL_API void pMatchVelocity(float magnitude = 1.0f, float epsilon = P_EPS, float max_radius = P_MAXFLOAT); PARTICLEDLL_API void pMatchRotVelocity(float magnitude = 1.0f, float epsilon = P_EPS, float max_radius = P_MAXFLOAT); PARTICLEDLL_API void pMove(); PARTICLEDLL_API void pOrbitLine(const pVec &p, const pVec &axis, float magnitude = 1.0f, float epsilon = P_EPS, float max_radius = P_MAXFLOAT); PARTICLEDLL_API void pOrbitPoint(const pVec &center, float magnitude = 1.0f, float epsilon = P_EPS, float max_radius = P_MAXFLOAT); PARTICLEDLL_API void pRandomAccel(const pDomain &dom); PARTICLEDLL_API void pRandomDisplace(const pDomain &dom); PARTICLEDLL_API void pRandomVelocity(const pDomain &dom); PARTICLEDLL_API void pRandomRotVelocity(const pDomain &dom); PARTICLEDLL_API void pRestore(float time, bool vel = true, bool rvel = true); PARTICLEDLL_API void pSink(bool kill_inside, const pDomain &dom); PARTICLEDLL_API void pSinkVelocity(bool kill_inside, const pDomain &dom); PARTICLEDLL_API void pSort(const pVec &eye, const pVec &look); PARTICLEDLL_API void pSource(float particle_rate, const pDomain &dom); PARTICLEDLL_API void pSpeedLimit(float min_speed, float max_speed = P_MAXFLOAT); PARTICLEDLL_API void pTargetColor(const pVec &color, float alpha, float scale); PARTICLEDLL_API void pTargetSize(const pVec &size, const pVec &scale); PARTICLEDLL_API void pTargetVelocity(const pVec &vel, float scale); PARTICLEDLL_API void pTargetRotVelocity(const pVec &vel, float scale); PARTICLEDLL_API void pVertex(const pVec &v, long data = 0); PARTICLEDLL_API void pVortex(const pVec &center, const pVec &axis, float magnitude = 1.0f, float tightnessExponent = 1.0f, float rotSpeed = 1.0f, float epsilon = P_EPS, float max_radius = P_MAXFLOAT); ///////////////////////////////////////////////////// // Other stuff typedef void (*P_PARTICLE_CALLBACK)(struct Particle &particle, void *data); PARTICLEDLL_API void pBirthCallback(P_PARTICLE_CALLBACK callback, void *data = NULL); PARTICLEDLL_API void pDeathCallback(P_PARTICLE_CALLBACK callback, void *data = NULL); PARTICLEDLL_API void pReset(); PARTICLEDLL_API void pSeed(unsigned int seed); enum ErrorCodes { PERR_NO_ERROR = 0, PERR_NOT_IMPLEMENTED = 1, PERR_INTERNAL_ERROR = 2 }; // Returns the first error hit in this thread PARTICLEDLL_API int pGetError(); #endif
armagetronad-xtw/0.4-armagetronad-xtw
src/thirdparty/particles/papi.h
C
gpl-2.0
6,874
package com.willblaschko.android.alexa.system; import android.app.Instrumentation; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.os.Handler; import android.os.Looper; import android.provider.AlarmClock; import android.support.annotation.NonNull; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; import com.willblaschko.android.alexa.AlexaManager; import com.willblaschko.android.alexa.callbacks.ImplAsyncCallback; import com.willblaschko.android.alexa.data.Directive; import com.willblaschko.android.alexa.data.Event; import com.willblaschko.android.alexa.interfaces.AvsItem; import com.willblaschko.android.alexa.interfaces.AvsResponse; import com.willblaschko.android.alexa.interfaces.alerts.AvsDeleteAlertItem; import com.willblaschko.android.alexa.interfaces.alerts.AvsSetAlertItem; import com.willblaschko.android.alexa.interfaces.playbackcontrol.AvsMediaNextCommandItem; import com.willblaschko.android.alexa.interfaces.playbackcontrol.AvsMediaPauseCommandItem; import com.willblaschko.android.alexa.interfaces.playbackcontrol.AvsMediaPlayCommandItem; import com.willblaschko.android.alexa.interfaces.playbackcontrol.AvsMediaPreviousCommandItem; import com.willblaschko.android.alexa.interfaces.response.ResponseParser; import com.willblaschko.android.alexa.interfaces.speaker.AvsAdjustVolumeItem; import com.willblaschko.android.alexa.interfaces.speaker.AvsSetMuteItem; import com.willblaschko.android.alexa.interfaces.speaker.AvsSetVolumeItem; import com.willblaschko.android.alexa.interfaces.system.AvsSetEndpointItem; import com.willblaschko.android.alexa.service.DownChannelService; import java.io.IOException; import java.text.ParseException; import static android.content.Context.AUDIO_SERVICE; /** * Created by will on 4/8/2017. */ public class AndroidSystemHandler { private static final String TAG = "AndroidSystemHandler"; private static AndroidSystemHandler instance; private Context context; private AndroidSystemHandler(Context context){ this.context = context.getApplicationContext(); } public static AndroidSystemHandler getInstance(Context context){ if(instance == null){ instance = new AndroidSystemHandler(context); } return instance; } public void handleItems(@NonNull AvsResponse response){ for(AvsItem current: response){ Log.i(TAG, "Handling AvsItem: " + current.getClass()); if(current instanceof AvsSetEndpointItem){ Log.i(TAG, "Setting URL endpoint: " + ((AvsSetEndpointItem) current).getEndpoint()); AlexaManager.getInstance(context) .setUrlEndpoint(((AvsSetEndpointItem) current).getEndpoint()); context.stopService(new Intent(context, DownChannelService.class)); context.startService(new Intent(context, DownChannelService.class)); }else if (current instanceof AvsSetVolumeItem) { //set our volume setVolume(((AvsSetVolumeItem) current).getVolume()); } else if(current instanceof AvsAdjustVolumeItem){ //adjust the volume adjustVolume(((AvsAdjustVolumeItem) current).getAdjustment()); } else if(current instanceof AvsSetMuteItem){ //mute/unmute the device setMute(((AvsSetMuteItem) current).isMute()); }else if(current instanceof AvsMediaPlayCommandItem){ //fake a hardware "play" press sendMediaButton(KeyEvent.KEYCODE_MEDIA_PLAY); Log.i(TAG, "Media play command issued"); }else if(current instanceof AvsMediaPauseCommandItem){ //fake a hardware "pause" press sendMediaButton(KeyEvent.KEYCODE_MEDIA_PAUSE); Log.i(TAG, "Media pause command issued"); }else if(current instanceof AvsMediaNextCommandItem){ //fake a hardware "next" press sendMediaButton(KeyEvent.KEYCODE_MEDIA_NEXT); Log.i(TAG, "Media next command issued"); }else if(current instanceof AvsMediaPreviousCommandItem){ //fake a hardware "previous" press sendMediaButton(KeyEvent.KEYCODE_MEDIA_PREVIOUS); Log.i(TAG, "Media previous command issued"); }else if (current instanceof AvsSetAlertItem){ if(((AvsSetAlertItem) current).isAlarm()){ setAlarm((AvsSetAlertItem) current); }else if(((AvsSetAlertItem) current).isTimer()){ setTimer((AvsSetAlertItem) current); } }else if (current instanceof AvsDeleteAlertItem){ } } } public void handleDirective(Directive directive){ try { AvsItem item = ResponseParser.parseDirective(directive); handleItem(item); } catch (IOException e) { e.printStackTrace(); } } public void handleItem(AvsItem item){ if(item == null){ return; } AvsResponse response = new AvsResponse(); response.add(item); handleItems(response); } private void setTimer(final AvsSetAlertItem item){ Intent i = new Intent(AlarmClock.ACTION_SET_TIMER); try { int time = (int) ((item.getScheduledTimeMillis() - System.currentTimeMillis()) / 1000); i.putExtra(AlarmClock.EXTRA_LENGTH, time); i.putExtra(AlarmClock.EXTRA_SKIP_UI, true); context.startActivity(i); AlexaManager.getInstance(context) .sendEvent(Event.getSetAlertSucceededEvent(item.getToken()), null); //cheating way to tell Alexa that the timer happened successfully--this SHOULD be improved //todo make this better new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { AlexaManager.getInstance(context) .sendEvent(Event.getAlertStartedEvent(item.getToken()), new ImplAsyncCallback<AvsResponse, Exception>() { @Override public void complete() { AlexaManager.getInstance(context) .sendEvent(Event.getAlertStoppedEvent(item.getToken()), null); } }); } }, time * 1000); } catch (ParseException e) { e.printStackTrace(); } } private void setAlarm(AvsSetAlertItem item){ Intent i = new Intent(AlarmClock.ACTION_SET_ALARM); try { i.putExtra(AlarmClock.EXTRA_HOUR, item.getHour()); i.putExtra(AlarmClock.EXTRA_MINUTES, item.getMinutes()); i.putExtra(AlarmClock.EXTRA_SKIP_UI, true); context.startActivity(i); AlexaManager.getInstance(context) .sendEvent(Event.getSetAlertSucceededEvent(item.getToken()), null); } catch (ParseException e) { e.printStackTrace(); } } /** * Force the device to think that a hardware button has been pressed, this is used for Play/Pause/Previous/Next Media commands * @param keyCode keycode for the hardware button we're emulating */ private static void sendMediaButton(int keyCode) { Instrumentation inst = new Instrumentation(); inst.sendKeyDownUpSync(keyCode); } private void adjustVolume(long adjust){ setVolume(adjust, true); } private void setVolume(long volume){ setVolume(volume, false); } private void setVolume(final long volume, final boolean adjust){ AudioManager am = (AudioManager) context.getSystemService(AUDIO_SERVICE); final int max = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); long vol = am.getStreamVolume(AudioManager.STREAM_MUSIC); if (adjust) { vol += volume * max / 100; } else { vol = volume * max / 100; } am.setStreamVolume(AudioManager.STREAM_MUSIC, (int) vol, AudioManager.FLAG_VIBRATE); AlexaManager.getInstance(context).sendVolumeChangedEvent(volume, vol == 0, null); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if(adjust) { Toast.makeText(context, "Volume adjusted.", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context, "Volume set to: " + (volume / 10), Toast.LENGTH_SHORT).show(); } } }); } private void setMute(final boolean isMute){ AudioManager am = (AudioManager) context.getSystemService(AUDIO_SERVICE); am.setStreamMute(AudioManager.STREAM_MUSIC, isMute); AlexaManager.getInstance(context).sendMutedEvent(isMute, null); Log.i(TAG, "Mute set to : "+isMute); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, "Volume " + (isMute ? "muted" : "unmuted"), Toast.LENGTH_SHORT).show(); } }); } }
willblaschko/AlexaAndroid
libs/AlexaAndroid/src/main/java/com/willblaschko/android/alexa/system/AndroidSystemHandler.java
Java
gpl-2.0
9,467
/* GStreamer Stream Splitter * Copyright (C) 2010 Edward Hervey <edward.hervey@collabora.co.uk> * (C) 2009 Nokia Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gststreamsplitter.h" static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src_%u", GST_PAD_SRC, GST_PAD_REQUEST, GST_STATIC_CAPS_ANY); static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY); GST_DEBUG_CATEGORY_STATIC (gst_stream_splitter_debug); #define GST_CAT_DEFAULT gst_stream_splitter_debug G_DEFINE_TYPE (GstStreamSplitter, gst_stream_splitter, GST_TYPE_ELEMENT); #define STREAMS_LOCK(obj) (g_mutex_lock(&obj->lock)) #define STREAMS_UNLOCK(obj) (g_mutex_unlock(&obj->lock)) static void gst_stream_splitter_dispose (GObject * object); static void gst_stream_splitter_finalize (GObject * object); static gboolean gst_stream_splitter_sink_setcaps (GstPad * pad, GstCaps * caps); static GstPad *gst_stream_splitter_request_new_pad (GstElement * element, GstPadTemplate * templ, const gchar * name, const GstCaps * caps); static void gst_stream_splitter_release_pad (GstElement * element, GstPad * pad); static void gst_stream_splitter_class_init (GstStreamSplitterClass * klass) { GObjectClass *gobject_klass; GstElementClass *gstelement_klass; gobject_klass = (GObjectClass *) klass; gstelement_klass = (GstElementClass *) klass; gobject_klass->dispose = gst_stream_splitter_dispose; gobject_klass->finalize = gst_stream_splitter_finalize; GST_DEBUG_CATEGORY_INIT (gst_stream_splitter_debug, "streamsplitter", 0, "Stream Splitter"); gst_element_class_add_pad_template (gstelement_klass, gst_static_pad_template_get (&src_template)); gst_element_class_add_pad_template (gstelement_klass, gst_static_pad_template_get (&sink_template)); gstelement_klass->request_new_pad = GST_DEBUG_FUNCPTR (gst_stream_splitter_request_new_pad); gstelement_klass->release_pad = GST_DEBUG_FUNCPTR (gst_stream_splitter_release_pad); gst_element_class_set_static_metadata (gstelement_klass, "streamsplitter", "Generic", "Splits streams based on their media type", "Edward Hervey <edward.hervey@collabora.co.uk>"); } static void gst_stream_splitter_dispose (GObject * object) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) object; g_list_foreach (stream_splitter->pending_events, (GFunc) gst_event_unref, NULL); g_list_free (stream_splitter->pending_events); stream_splitter->pending_events = NULL; G_OBJECT_CLASS (gst_stream_splitter_parent_class)->dispose (object); } static void gst_stream_splitter_finalize (GObject * object) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) object; g_mutex_clear (&stream_splitter->lock); G_OBJECT_CLASS (gst_stream_splitter_parent_class)->finalize (object); } static GstFlowReturn gst_stream_splitter_chain (GstPad * pad, GstObject * parent, GstBuffer * buf) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) parent; GstFlowReturn res; GstPad *srcpad = NULL; STREAMS_LOCK (stream_splitter); if (stream_splitter->current) srcpad = gst_object_ref (stream_splitter->current); STREAMS_UNLOCK (stream_splitter); if (G_UNLIKELY (srcpad == NULL)) goto nopad; if (G_UNLIKELY (stream_splitter->pending_events)) { GList *tmp; GST_DEBUG_OBJECT (srcpad, "Pushing out pending events"); for (tmp = stream_splitter->pending_events; tmp; tmp = tmp->next) { GstEvent *event = (GstEvent *) tmp->data; gst_pad_push_event (srcpad, event); } g_list_free (stream_splitter->pending_events); stream_splitter->pending_events = NULL; } /* Forward to currently activated stream */ res = gst_pad_push (srcpad, buf); gst_object_unref (srcpad); return res; nopad: GST_WARNING_OBJECT (stream_splitter, "No output pad was configured"); return GST_FLOW_ERROR; } static gboolean gst_stream_splitter_sink_event (GstPad * pad, GstObject * parent, GstEvent * event) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) parent; gboolean res = TRUE; gboolean toall = FALSE; gboolean store = FALSE; gboolean eos = FALSE; gboolean flushpending = FALSE; /* FLUSH_START/STOP : forward to all * EOS : transform to CUSTOM_REAL_EOS and forward to all * INBAND events : store to send in chain function to selected chain * OUT_OF_BAND events : send to all */ GST_DEBUG_OBJECT (stream_splitter, "Got event %s", GST_EVENT_TYPE_NAME (event)); switch (GST_EVENT_TYPE (event)) { case GST_EVENT_CAPS: { GstCaps *caps; gst_event_parse_caps (event, &caps); res = gst_stream_splitter_sink_setcaps (pad, caps); store = TRUE; break; } case GST_EVENT_FLUSH_STOP: flushpending = TRUE; toall = TRUE; break; case GST_EVENT_FLUSH_START: toall = TRUE; break; case GST_EVENT_EOS: /* Replace with our custom eos event */ gst_event_unref (event); event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM, gst_structure_new_empty ("stream-switching-eos")); toall = TRUE; eos = TRUE; break; default: if (GST_EVENT_TYPE (event) & GST_EVENT_TYPE_SERIALIZED) store = TRUE; } if (flushpending) { g_list_foreach (stream_splitter->pending_events, (GFunc) gst_event_unref, NULL); g_list_free (stream_splitter->pending_events); stream_splitter->pending_events = NULL; } if (store) { stream_splitter->pending_events = g_list_append (stream_splitter->pending_events, event); } else if (toall || eos) { GList *tmp; guint32 cookie; /* Send to all pads */ STREAMS_LOCK (stream_splitter); resync: if (G_UNLIKELY (stream_splitter->srcpads == NULL)) { STREAMS_UNLOCK (stream_splitter); /* No source pads */ gst_event_unref (event); res = FALSE; goto beach; } tmp = stream_splitter->srcpads; cookie = stream_splitter->cookie; while (tmp) { GstPad *srcpad = (GstPad *) tmp->data; STREAMS_UNLOCK (stream_splitter); /* In case of EOS, we first push out the real one to flush out * each streams (but which will be discarded in the streamcombiner) * before our custom one (which will be converted back to and EOS * in the streamcombiner) */ if (eos) gst_pad_push_event (srcpad, gst_event_new_eos ()); gst_event_ref (event); res = gst_pad_push_event (srcpad, event); STREAMS_LOCK (stream_splitter); if (G_UNLIKELY (cookie != stream_splitter->cookie)) goto resync; tmp = tmp->next; } STREAMS_UNLOCK (stream_splitter); gst_event_unref (event); } else { GstPad *pad; /* Only send to current pad */ STREAMS_LOCK (stream_splitter); pad = stream_splitter->current; STREAMS_UNLOCK (stream_splitter); if (pad) res = gst_pad_push_event (pad, event); else { gst_event_unref (event); res = FALSE; } } beach: return res; } static GstCaps * gst_stream_splitter_sink_getcaps (GstPad * pad, GstCaps * filter) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) GST_PAD_PARENT (pad); guint32 cookie; GList *tmp; GstCaps *res = NULL; /* Return the combination of all downstream caps */ STREAMS_LOCK (stream_splitter); resync: if (G_UNLIKELY (stream_splitter->srcpads == NULL)) { res = (filter ? gst_caps_ref (filter) : gst_caps_new_any ()); goto beach; } res = NULL; cookie = stream_splitter->cookie; tmp = stream_splitter->srcpads; while (tmp) { GstPad *srcpad = (GstPad *) tmp->data; STREAMS_UNLOCK (stream_splitter); if (res) { GstCaps *peercaps = gst_pad_peer_query_caps (srcpad, filter); if (peercaps) res = gst_caps_merge (res, peercaps); } else { res = gst_pad_peer_query_caps (srcpad, filter); } STREAMS_LOCK (stream_splitter); if (G_UNLIKELY (cookie != stream_splitter->cookie)) { if (res) gst_caps_unref (res); goto resync; } tmp = tmp->next; } beach: STREAMS_UNLOCK (stream_splitter); return res; } static gboolean gst_stream_splitter_sink_query (GstPad * pad, GstObject * parent, GstQuery * query) { gboolean res; switch (GST_QUERY_TYPE (query)) { case GST_QUERY_CAPS: { GstCaps *filter, *caps; gst_query_parse_caps (query, &filter); caps = gst_stream_splitter_sink_getcaps (pad, filter); gst_query_set_caps_result (query, caps); gst_caps_unref (caps); res = TRUE; break; } default: res = gst_pad_query_default (pad, parent, query); break; } return res; } static gboolean gst_stream_splitter_sink_setcaps (GstPad * pad, GstCaps * caps) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) GST_PAD_PARENT (pad); guint32 cookie; GList *tmp; gboolean res; GST_DEBUG_OBJECT (stream_splitter, "caps %" GST_PTR_FORMAT, caps); /* Try on all pads, choose the one that succeeds as the current stream */ STREAMS_LOCK (stream_splitter); resync: if (G_UNLIKELY (stream_splitter->srcpads == NULL)) { res = FALSE; goto beach; } res = FALSE; tmp = stream_splitter->srcpads; cookie = stream_splitter->cookie; while (tmp) { GstPad *srcpad = (GstPad *) tmp->data; GstCaps *peercaps; STREAMS_UNLOCK (stream_splitter); peercaps = gst_pad_peer_query_caps (srcpad, NULL); if (peercaps) { res = gst_caps_can_intersect (caps, peercaps); gst_caps_unref (peercaps); } STREAMS_LOCK (stream_splitter); if (G_UNLIKELY (cookie != stream_splitter->cookie)) goto resync; if (res) { /* FIXME : we need to switch properly */ GST_DEBUG_OBJECT (srcpad, "Setting caps on this pad was successful"); stream_splitter->current = srcpad; goto beach; } tmp = tmp->next; } beach: STREAMS_UNLOCK (stream_splitter); return res; } static gboolean gst_stream_splitter_src_event (GstPad * pad, GstObject * parent, GstEvent * event) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) parent; GST_DEBUG_OBJECT (pad, "%s", GST_EVENT_TYPE_NAME (event)); /* Forward upstream as is */ return gst_pad_push_event (stream_splitter->sinkpad, event); } static gboolean gst_stream_splitter_src_query (GstPad * pad, GstObject * parent, GstQuery * query) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) parent; GST_DEBUG_OBJECT (pad, "%s", GST_QUERY_TYPE_NAME (query)); /* Forward upstream as is */ return gst_pad_peer_query (stream_splitter->sinkpad, query); } static void gst_stream_splitter_init (GstStreamSplitter * stream_splitter) { stream_splitter->sinkpad = gst_pad_new_from_static_template (&sink_template, "sink"); gst_pad_set_chain_function (stream_splitter->sinkpad, gst_stream_splitter_chain); gst_pad_set_event_function (stream_splitter->sinkpad, gst_stream_splitter_sink_event); gst_pad_set_query_function (stream_splitter->sinkpad, gst_stream_splitter_sink_query); gst_element_add_pad (GST_ELEMENT (stream_splitter), stream_splitter->sinkpad); g_mutex_init (&stream_splitter->lock); } static GstPad * gst_stream_splitter_request_new_pad (GstElement * element, GstPadTemplate * templ, const gchar * name, const GstCaps * caps) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) element; GstPad *srcpad; srcpad = gst_pad_new_from_static_template (&src_template, name); gst_pad_set_event_function (srcpad, gst_stream_splitter_src_event); gst_pad_set_query_function (srcpad, gst_stream_splitter_src_query); STREAMS_LOCK (stream_splitter); stream_splitter->srcpads = g_list_append (stream_splitter->srcpads, srcpad); gst_pad_set_active (srcpad, TRUE); gst_element_add_pad (element, srcpad); stream_splitter->cookie++; STREAMS_UNLOCK (stream_splitter); return srcpad; } static void gst_stream_splitter_release_pad (GstElement * element, GstPad * pad) { GstStreamSplitter *stream_splitter = (GstStreamSplitter *) element; GList *tmp; STREAMS_LOCK (stream_splitter); tmp = g_list_find (stream_splitter->srcpads, pad); if (tmp) { GstPad *pad = (GstPad *) tmp->data; stream_splitter->srcpads = g_list_delete_link (stream_splitter->srcpads, tmp); stream_splitter->cookie++; if (pad == stream_splitter->current) { /* Deactivate current flow */ GST_DEBUG_OBJECT (element, "Removed pad was the current one"); stream_splitter->current = NULL; } gst_element_remove_pad (element, pad); } STREAMS_UNLOCK (stream_splitter); return; }
rawoul/gst-plugins-base
gst/encoding/gststreamsplitter.c
C
gpl-2.0
13,553
<?php require_once(dirname(__FILE__) . "/wpws-access.php"); define("WPWS_RESIZE_IMAGE_TEMPFILE", WPWS_CACHE_DIR . "/" . wpws_genUniqueCode() . ".img"); define("WPWS_RESIZE_IMAGE_ESCAPESIGN", "---"); class wpws_ImageUtils { /** * Returns true if the given file resides in the given directory. * @param string dir * @param string file * @return string cache entry file name */ function file_resides_in_directory($dir, $file) { $dir = realpath($dir); $file = realpath($file); if(!$dir || !$file) return false; if(strlen($file) < strlen($dir)) return false; if(substr($file, 0, strlen($dir)) != $dir) return false; return true; } /** * Return the file name to be used as a cache entry * @param string file (path) * @param int image width * @param int image height * @param int value between 0 and 100 for jpeg; null for any other format * @return string cache entry file name */ function generate_cache_filename($src, $width, $height, $quality) { $normalized = (strpos($src, "/") == 0) ? substr($src, 1) : $src; $escaped = str_replace(WPWS_RESIZE_IMAGE_ESCAPESIGN, WPWS_RESIZE_IMAGE_ESCAPESIGN . WPWS_RESIZE_IMAGE_ESCAPESIGN, $normalized); $masked = str_replace("/", WPWS_RESIZE_IMAGE_ESCAPESIGN, $escaped); $widthed = $masked . WPWS_RESIZE_IMAGE_ESCAPESIGN . $width; $heighted = $widthed . WPWS_RESIZE_IMAGE_ESCAPESIGN . $height; $qualitied = $heighted . WPWS_RESIZE_IMAGE_ESCAPESIGN . $quality; return $qualitied; } /** * Return the file name to be used as a timestamped cache entry * @param string file (path) * @param int image width * @param int image height * @param int value between 0 and 100 for jpeg; null for any other format * @param int last modified timestamp * @return string timestamped cache entry file name */ function generate_timestamped_cache_filename($src, $width, $height, $quality, $timestamp) { $timestamped = wpws_ImageUtils::generate_cache_filename($src, $width, $height, $quality) . WPWS_RESIZE_IMAGE_ESCAPESIGN . $timestamp; return $timestamped; } /** * Returns the mime type of a file (e.g. text, gif, png, jpg, ...) * @param string file * @return string file type */ function get_mime_type($file) { $image_info = getimagesize($file); return $image_info["mime"]; } /** * Returns the type of a file (e.g. text, gif, png, jpg, ...) * @param string file * @return string file type */ function get_type($file) { list(, $type) = split("/", wpws_ImageUtils::get_mime_type($file)); return $type; } /** * Returns the PHP function name for graphics creation * @param string file format to use (gif|png|...|jpg) * @return string function name; preceeded with a dollar sign the corresponding function gets called */ function get_create_function_name($file) { return "imagecreatefrom" . wpws_ImageUtils::get_type($file); } /** * Returns the PHP function name for graphics output * @param string file format to use (gif|png|...|jpg) * @return string function name; preceeded with a dollar sign the corresponding function gets called */ function get_send_function_name($file) { return "image" . wpws_ImageUtils::get_type($file); } /** * Resized a given image * @param string file (path) pointing to the image * @param int width to resize to * @param int height to resize to * @return Image resized image */ function generate_resized_image($file, $width, $height) { $image_info = getimagesize($file); // Make sure, the image does not become bigger than the original if($width > $image_info[0]) $width = $image_info[0]; if($height > $image_info[1]) $height = $image_info[1]; if($width && $height) { // Final dimensions are already set } else if($width) { // Width set $height = round($width/($image_info[0]/$image_info[1])); } else if($height) { // Height set $width = round($height*($image_info[0]/$image_info[1])); } else { // Nothing set $width = $image_info[0]; $height = $image_info[1]; } $create_function_name = wpws_ImageUtils::get_create_function_name($file); $original_image = $create_function_name($file); $resized_image = imagecreatetruecolor($width, $height); $white = imagecolorallocate($resized_image, 255, 255, 255); imagefill($resized_image, 0, 0, $white); imagesavealpha($resized_image, true); imagealphablending($resized_image, true); imageantialias($resized_image, true); imagecopyresampled( $resized_image, $original_image, 0, 0, 0, 0, $width, $height, $image_info[0], $image_info[1] ); imagedestroy($original_image); return $resized_image; } /** * Returns the absolute path to a given cache entry * @param string file (path) * @param int width to resize to * @param int height to resize to * @param int value between 0 and 100 for jpeg; null for any other format */ function get_cached_file($src, $width, $height, $quality) { $testfile = wpws_ImageUtils::generate_cache_filename($src, $width, $height, $quality); $cached_file = null; $dh = opendir(WPWS_CACHE_DIR); while(($file = readdir($dh)) !== false) { if(substr($file, 0, strlen($testfile)) == $testfile) { $cached_file = $file; break; } } closedir($dh); return ($cached_file == null) ? null : WPWS_CACHE_DIR . "/" . $cached_file; } /** * Removes a cache entry for a given file. * @param string file (path) * @param int width to resize to * @param int height to resize to * @param int value between 0 and 100 for jpeg; null for any other format */ function remove_cached_file($src, $width, $height, $quality) { $cached_file = wpws_ImageUtils::get_cached_file($src, $width, $height, $quality); if($cached_file) unlink($cached_file); } /** * Determines the last modified timestamp of a file. * @param string file (path) * @return int last modified timestamp */ function get_mtime_from_cached_file($file) { $parts = explode(WPWS_RESIZE_IMAGE_ESCAPESIGN, $file); if(count($parts) > 1) return $parts[count($parts)-1]; else return null; } /** * Determines whether the cache entry needs to be updated * for a specified file. * @param string file (path) * @param int width to resize to * @param int height to resize to * @param int value between 0 and 100 for jpeg; null for any other format * @param int last modified timestamp of the file in question * @param boolean true if cache needs to be created / updated */ function cached_file_is_needed($src, $width, $height, $quality, $timestamp) { $cached_file = wpws_ImageUtils::get_cached_file($src, $width, $height, $quality); if(!$cached_file) return true; $cached_file_timestamp = wpws_ImageUtils::get_mtime_from_cached_file($cached_file); if($cached_file_timestamp != $timestamp) return true; return false; } } ?>
eestec/eestec.portal-2
wp-content/plugins/wordpress-web-service/includes/wpws-imageutils.php
PHP
gpl-2.0
6,869
#include "request_listener/ipc_request_listener.h" #include <glog/logging.h> #include <chrono> #include <thread> #include <vector> #include <arpa/inet.h> #include <poll.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include "request_listener/request_listener_exception.h" #include "request_listener/socket_reply_channel.h" #include "request.pb.h" namespace { using datto_linux_client::RequestListenerException; using datto_linux_client::Request; const int SOCKET_BACKLOG = 5; int OpenSocket(std::string ipc_socket_path) { LOG(INFO) << "Opening socket " << ipc_socket_path; const char *ipc_path_cstr = ipc_socket_path.c_str(); int sock_fd = socket(AF_UNIX, SOCK_STREAM, 0); if (sock_fd < 0) { PLOG(ERROR) << "Unable to open socket"; throw RequestListenerException("Unable to open socket"); } if (unlink(ipc_path_cstr)) { if (errno != ENOENT) { PLOG(ERROR) << "Error removing " << ipc_path_cstr; throw RequestListenerException("Unable to remove socket path"); } } struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, ipc_path_cstr, ipc_socket_path.length()); if (bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr))) { PLOG(ERROR) << "Error during bind"; throw RequestListenerException("Unable to bind socket"); } if (listen(sock_fd, SOCKET_BACKLOG)) { PLOG(ERROR) << "Unable to listen on socket"; throw RequestListenerException("Unable to listen on socket"); } LOG(INFO) << "Listening on socket " << ipc_socket_path; return sock_fd; } bool ConnectionIsReady(int socket_fd, int timeout_millis) { struct pollfd pfd; pfd.fd = socket_fd; pfd.events = POLLIN; switch (poll(&pfd, 1, timeout_millis)) { case -1: PLOG(ERROR) << "Unable to poll file descriptor"; throw RequestListenerException("Poll failure"); case 0: return false; case 1: return true; default: throw RequestListenerException("Unexpected branch"); } } int GetNewConnection(int socket_fd) { int connection_fd = accept(socket_fd, NULL, NULL); if (connection_fd < 0) { PLOG(ERROR) << "Error accepting connection"; throw RequestListenerException("Unable to accept connection"); } return connection_fd; } Request ReadProtobufRequest(int connection_fd) { uint32_t message_length; ssize_t bytes_read; bytes_read = read(connection_fd, &message_length, sizeof(uint32_t)); if (bytes_read != sizeof(uint32_t)) { PLOG(ERROR) << "Unable to read message length from socket"; throw RequestListenerException("Error during read from socket"); } message_length = ntohl(message_length); LOG(INFO) << "Getting request of size: " << message_length; // Sanity check, shouldn't be larger than 1MB if (message_length > 1 * 1024 * 1024) { LOG(ERROR) << "Message length: " << message_length; throw RequestListenerException("Message was too big"); } std::string message_buf; message_buf.resize(message_length); bytes_read = recv(connection_fd, &message_buf[0], message_length, MSG_WAITALL); if (bytes_read != (int32_t)message_length) { PLOG(ERROR) << "Bytes read: " << bytes_read; throw RequestListenerException("Error reading request"); } Request request; request.ParseFromString(message_buf); return request; } } // namespace namespace datto_linux_client { IpcRequestListener::IpcRequestListener( std::string ipc_socket_path, std::unique_ptr<RequestHandler> request_handler) : request_handler_(std::move(request_handler)), do_stop_(false) { socket_fd_ = OpenSocket(ipc_socket_path); std::atomic<bool> started(false); LOG(INFO) << "Starting IPC listener thread"; listen_thread_ = std::thread([&]() { while (!do_stop_) { try { if (ConnectionIsReady(socket_fd_, 500)) { if (do_stop_) { break; } int connection_fd = GetNewConnection(socket_fd_); // The reply_channel is responsible for cleaning up the // connection_fd, so we construct it as soon as possible // in case there is an exception. std::shared_ptr<ReplyChannel> reply_channel( new SocketReplyChannel(connection_fd)); auto request = ReadProtobufRequest(connection_fd); request_handler_->Handle(request, reply_channel); } } catch (const std::exception &e) { LOG(ERROR) << "Exception during connection loop: " << e.what(); } started = true; } LOG(INFO) << "IPC listener thread stopped"; }); while (!started) { std::this_thread::yield(); } } void IpcRequestListener::Stop() { do_stop_ = true; shutdown(socket_fd_, SHUT_RDWR); close(socket_fd_); } IpcRequestListener::~IpcRequestListener() { LOG(INFO) << "Tearing down IpcRequestListener"; Stop(); listen_thread_.join(); } }
fuhry/linux-agent
request_listener/ipc_request_listener.cc
C++
gpl-2.0
4,935
/** * * Copyright (c) 2009-2013 Freedomotic team * http://freedomotic.com * * This file is part of Freedomotic * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Freedomotic; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. */ package it.freedomotic.plugins; /** * * @author Enrico */ public class Coordinate { private int id; private int x; private int y; private int time; public int getX() { return x; } public int getY() { return y; } public int getTime() { return time; } public int getId() { return id; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setTime(int time) { this.time = time; } public void setId(int id) { this.id = id; } }
sanyaade-iot/freedomotic
plugins/devices/test/src/main/java/it/freedomotic/plugins/Coordinate.java
Java
gpl-2.0
1,464
# shibeta.org a website designed for 助け屋SHIBETA. ## Installation ``` npm install npm install pm2 -g ``` ## Running ``` pm2 start shibeta.js ``` ## Preview [shibeta.org](https://shibeta.org) ## License GPL
stitchcula/shibeta.org
README.md
Markdown
gpl-2.0
212
<!-- Have you read AutolabJS' Code of Conduct? By filing an Issue, you are expected to comply with it, including treating everyone with respect: https://github.com/AutolabJS/AutolabJS/blob/master/.github/CODE_OF_CONDUCT.md --> ### Description [Description of the issue] ### Steps to Reproduce 1. [First Step] 2. [Second Step] 3. [and so on...] **Expected behavior:** [What you expect to happen] **Actual behavior:** [What actually happens] **Reproduces how often:** [What percentage of the time does it reproduce?] ### Additional Information Any additional information, configuration or data that might be necessary to reproduce the issue.
prasadtalasila/JavaAutolab
.github/ISSUE_TEMPLATE.md
Markdown
gpl-2.0
650
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2009-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 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.web.controller.inventory; /** * <p>RancidReportExecCommClass class.</p> * * @author ranger * @version $Id: $ * @since 1.8.1 */ public class RancidReportExecCommClass { private String date; private String fieldhas; private String reporttype; private String reportfiletype; private String reportemail; /** * <p>Getter for the field <code>date</code>.</p> * * @return a {@link java.lang.String} object. */ public String getDate() { return date; } /** * <p>Setter for the field <code>date</code>.</p> * * @param date a {@link java.lang.String} object. */ public void setDate(String date) { this.date = date; } /** * <p>Getter for the field <code>fieldhas</code>.</p> * * @return a {@link java.lang.String} object. */ public String getFieldhas() { return fieldhas; } /** * <p>Setter for the field <code>fieldhas</code>.</p> * * @param fieldhas a {@link java.lang.String} object. */ public void setFieldhas(String fieldhas) { this.fieldhas = fieldhas; } /** * <p>Getter for the field <code>reporttype</code>.</p> * * @return a {@link java.lang.String} object. */ public String getReporttype() { return reporttype; } /** * <p>Setter for the field <code>reporttype</code>.</p> * * @param reporttype a {@link java.lang.String} object. */ public void setReporttype(String reporttype) { this.reporttype = reporttype; } /** * <p>Getter for the field <code>reportfiletype</code>.</p> * * @return a {@link java.lang.String} object. */ public String getReportfiletype() { return reportfiletype; } /** * <p>Setter for the field <code>reportfiletype</code>.</p> * * @param reportfiletype a {@link java.lang.String} object. */ public void setReportfiletype(String reportfiletype) { this.reportfiletype = reportfiletype; } /** * <p>Getter for the field <code>reportemail</code>.</p> * * @return a {@link java.lang.String} object. */ public String getReportemail() { return reportemail; } /** * <p>Setter for the field <code>reportemail</code>.</p> * * @param reportemail a {@link java.lang.String} object. */ public void setReportemail(String reportemail) { this.reportemail = reportemail; } }
bugcy013/opennms-tmp-tools
opennms-webapp/src/main/java/org/opennms/web/controller/inventory/RancidReportExecCommClass.java
Java
gpl-2.0
3,738
/*************************************************************************** * Copyright (C) 2013 by Andes Technology * * Hsiangkai Wang <hkwang@andestech.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, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <jtag/drivers/libusb_helper.h> #include <helper/log.h> #include <helper/time_support.h> #include <target/target.h> #include <jtag/jtag.h> #include <target/nds32_insn.h> #include <target/nds32_reg.h> #include "aice_usb.h" /* Global USB buffers */ static uint8_t usb_in_buffer[AICE_IN_BUFFER_SIZE]; static uint8_t usb_out_buffer[AICE_OUT_BUFFER_SIZE]; static uint32_t jtag_clock; static struct aice_usb_handler_s aice_handler; /* AICE max retry times. If AICE command timeout, retry it. */ static int aice_max_retry_times = 50; /* Default endian is little endian. */ static enum aice_target_endian data_endian; /* Constants for AICE command format length */ #define AICE_FORMAT_HTDA (3) #define AICE_FORMAT_HTDC (7) #define AICE_FORMAT_HTDMA (4) #define AICE_FORMAT_HTDMB (8) #define AICE_FORMAT_HTDMC (8) #define AICE_FORMAT_HTDMD (12) #define AICE_FORMAT_DTHA (6) #define AICE_FORMAT_DTHB (2) #define AICE_FORMAT_DTHMA (8) #define AICE_FORMAT_DTHMB (4) /* Constants for AICE command */ static const uint8_t AICE_CMD_SCAN_CHAIN = 0x00; static const uint8_t AICE_CMD_T_READ_MISC = 0x20; static const uint8_t AICE_CMD_T_READ_EDMSR = 0x21; static const uint8_t AICE_CMD_T_READ_DTR = 0x22; static const uint8_t AICE_CMD_T_READ_MEM_B = 0x24; static const uint8_t AICE_CMD_T_READ_MEM_H = 0x25; static const uint8_t AICE_CMD_T_READ_MEM = 0x26; static const uint8_t AICE_CMD_T_FASTREAD_MEM = 0x27; static const uint8_t AICE_CMD_T_WRITE_MISC = 0x28; static const uint8_t AICE_CMD_T_WRITE_EDMSR = 0x29; static const uint8_t AICE_CMD_T_WRITE_DTR = 0x2A; static const uint8_t AICE_CMD_T_WRITE_DIM = 0x2B; static const uint8_t AICE_CMD_T_WRITE_MEM_B = 0x2C; static const uint8_t AICE_CMD_T_WRITE_MEM_H = 0x2D; static const uint8_t AICE_CMD_T_WRITE_MEM = 0x2E; static const uint8_t AICE_CMD_T_FASTWRITE_MEM = 0x2F; static const uint8_t AICE_CMD_T_EXECUTE = 0x3E; static const uint8_t AICE_CMD_READ_CTRL = 0x50; static const uint8_t AICE_CMD_WRITE_CTRL = 0x51; static const uint8_t AICE_CMD_BATCH_BUFFER_READ = 0x60; static const uint8_t AICE_CMD_READ_DTR_TO_BUFFER = 0x61; static const uint8_t AICE_CMD_BATCH_BUFFER_WRITE = 0x68; static const uint8_t AICE_CMD_WRITE_DTR_FROM_BUFFER = 0x69; /***************************************************************************/ /* AICE commands' pack/unpack functions */ static void aice_pack_htda(uint8_t cmd_code, uint8_t extra_word_length, uint32_t address) { usb_out_buffer[0] = cmd_code; usb_out_buffer[1] = extra_word_length; usb_out_buffer[2] = (uint8_t)(address & 0xFF); } static void aice_pack_htdc(uint8_t cmd_code, uint8_t extra_word_length, uint32_t address, uint32_t word, enum aice_target_endian access_endian) { usb_out_buffer[0] = cmd_code; usb_out_buffer[1] = extra_word_length; usb_out_buffer[2] = (uint8_t)(address & 0xFF); if (access_endian == AICE_BIG_ENDIAN) { usb_out_buffer[6] = (uint8_t)((word >> 24) & 0xFF); usb_out_buffer[5] = (uint8_t)((word >> 16) & 0xFF); usb_out_buffer[4] = (uint8_t)((word >> 8) & 0xFF); usb_out_buffer[3] = (uint8_t)(word & 0xFF); } else { usb_out_buffer[3] = (uint8_t)((word >> 24) & 0xFF); usb_out_buffer[4] = (uint8_t)((word >> 16) & 0xFF); usb_out_buffer[5] = (uint8_t)((word >> 8) & 0xFF); usb_out_buffer[6] = (uint8_t)(word & 0xFF); } } static void aice_pack_htdma(uint8_t cmd_code, uint8_t target_id, uint8_t extra_word_length, uint32_t address) { usb_out_buffer[0] = cmd_code; usb_out_buffer[1] = target_id; usb_out_buffer[2] = extra_word_length; usb_out_buffer[3] = (uint8_t)(address & 0xFF); } static void aice_pack_htdmb(uint8_t cmd_code, uint8_t target_id, uint8_t extra_word_length, uint32_t address) { usb_out_buffer[0] = cmd_code; usb_out_buffer[1] = target_id; usb_out_buffer[2] = extra_word_length; usb_out_buffer[3] = 0; usb_out_buffer[4] = (uint8_t)((address >> 24) & 0xFF); usb_out_buffer[5] = (uint8_t)((address >> 16) & 0xFF); usb_out_buffer[6] = (uint8_t)((address >> 8) & 0xFF); usb_out_buffer[7] = (uint8_t)(address & 0xFF); } static void aice_pack_htdmc(uint8_t cmd_code, uint8_t target_id, uint8_t extra_word_length, uint32_t address, uint32_t word, enum aice_target_endian access_endian) { usb_out_buffer[0] = cmd_code; usb_out_buffer[1] = target_id; usb_out_buffer[2] = extra_word_length; usb_out_buffer[3] = (uint8_t)(address & 0xFF); if (access_endian == AICE_BIG_ENDIAN) { usb_out_buffer[7] = (uint8_t)((word >> 24) & 0xFF); usb_out_buffer[6] = (uint8_t)((word >> 16) & 0xFF); usb_out_buffer[5] = (uint8_t)((word >> 8) & 0xFF); usb_out_buffer[4] = (uint8_t)(word & 0xFF); } else { usb_out_buffer[4] = (uint8_t)((word >> 24) & 0xFF); usb_out_buffer[5] = (uint8_t)((word >> 16) & 0xFF); usb_out_buffer[6] = (uint8_t)((word >> 8) & 0xFF); usb_out_buffer[7] = (uint8_t)(word & 0xFF); } } static void aice_pack_htdmc_multiple_data(uint8_t cmd_code, uint8_t target_id, uint8_t extra_word_length, uint32_t address, uint32_t *word, uint8_t num_of_words, enum aice_target_endian access_endian) { usb_out_buffer[0] = cmd_code; usb_out_buffer[1] = target_id; usb_out_buffer[2] = extra_word_length; usb_out_buffer[3] = (uint8_t)(address & 0xFF); uint8_t i; for (i = 0 ; i < num_of_words ; i++, word++) { if (access_endian == AICE_BIG_ENDIAN) { usb_out_buffer[7 + i * 4] = (uint8_t)((*word >> 24) & 0xFF); usb_out_buffer[6 + i * 4] = (uint8_t)((*word >> 16) & 0xFF); usb_out_buffer[5 + i * 4] = (uint8_t)((*word >> 8) & 0xFF); usb_out_buffer[4 + i * 4] = (uint8_t)(*word & 0xFF); } else { usb_out_buffer[4 + i * 4] = (uint8_t)((*word >> 24) & 0xFF); usb_out_buffer[5 + i * 4] = (uint8_t)((*word >> 16) & 0xFF); usb_out_buffer[6 + i * 4] = (uint8_t)((*word >> 8) & 0xFF); usb_out_buffer[7 + i * 4] = (uint8_t)(*word & 0xFF); } } } static void aice_pack_htdmd(uint8_t cmd_code, uint8_t target_id, uint8_t extra_word_length, uint32_t address, uint32_t word, enum aice_target_endian access_endian) { usb_out_buffer[0] = cmd_code; usb_out_buffer[1] = target_id; usb_out_buffer[2] = extra_word_length; usb_out_buffer[3] = 0; usb_out_buffer[4] = (uint8_t)((address >> 24) & 0xFF); usb_out_buffer[5] = (uint8_t)((address >> 16) & 0xFF); usb_out_buffer[6] = (uint8_t)((address >> 8) & 0xFF); usb_out_buffer[7] = (uint8_t)(address & 0xFF); if (access_endian == AICE_BIG_ENDIAN) { usb_out_buffer[11] = (uint8_t)((word >> 24) & 0xFF); usb_out_buffer[10] = (uint8_t)((word >> 16) & 0xFF); usb_out_buffer[9] = (uint8_t)((word >> 8) & 0xFF); usb_out_buffer[8] = (uint8_t)(word & 0xFF); } else { usb_out_buffer[8] = (uint8_t)((word >> 24) & 0xFF); usb_out_buffer[9] = (uint8_t)((word >> 16) & 0xFF); usb_out_buffer[10] = (uint8_t)((word >> 8) & 0xFF); usb_out_buffer[11] = (uint8_t)(word & 0xFF); } } static void aice_pack_htdmd_multiple_data(uint8_t cmd_code, uint8_t target_id, uint8_t extra_word_length, uint32_t address, const uint8_t *word, enum aice_target_endian access_endian) { usb_out_buffer[0] = cmd_code; usb_out_buffer[1] = target_id; usb_out_buffer[2] = extra_word_length; usb_out_buffer[3] = 0; usb_out_buffer[4] = (uint8_t)((address >> 24) & 0xFF); usb_out_buffer[5] = (uint8_t)((address >> 16) & 0xFF); usb_out_buffer[6] = (uint8_t)((address >> 8) & 0xFF); usb_out_buffer[7] = (uint8_t)(address & 0xFF); uint32_t i; /* num_of_words may be over 0xFF, so use uint32_t */ uint32_t num_of_words = extra_word_length + 1; for (i = 0 ; i < num_of_words ; i++, word += 4) { if (access_endian == AICE_BIG_ENDIAN) { usb_out_buffer[11 + i * 4] = word[3]; usb_out_buffer[10 + i * 4] = word[2]; usb_out_buffer[9 + i * 4] = word[1]; usb_out_buffer[8 + i * 4] = word[0]; } else { usb_out_buffer[8 + i * 4] = word[3]; usb_out_buffer[9 + i * 4] = word[2]; usb_out_buffer[10 + i * 4] = word[1]; usb_out_buffer[11 + i * 4] = word[0]; } } } static void aice_unpack_dtha(uint8_t *cmd_ack_code, uint8_t *extra_word_length, uint32_t *word, enum aice_target_endian access_endian) { *cmd_ack_code = usb_in_buffer[0]; *extra_word_length = usb_in_buffer[1]; if (access_endian == AICE_BIG_ENDIAN) { *word = (usb_in_buffer[5] << 24) | (usb_in_buffer[4] << 16) | (usb_in_buffer[3] << 8) | (usb_in_buffer[2]); } else { *word = (usb_in_buffer[2] << 24) | (usb_in_buffer[3] << 16) | (usb_in_buffer[4] << 8) | (usb_in_buffer[5]); } } static void aice_unpack_dtha_multiple_data(uint8_t *cmd_ack_code, uint8_t *extra_word_length, uint32_t *word, uint8_t num_of_words, enum aice_target_endian access_endian) { *cmd_ack_code = usb_in_buffer[0]; *extra_word_length = usb_in_buffer[1]; uint8_t i; for (i = 0 ; i < num_of_words ; i++, word++) { if (access_endian == AICE_BIG_ENDIAN) { *word = (usb_in_buffer[5 + i * 4] << 24) | (usb_in_buffer[4 + i * 4] << 16) | (usb_in_buffer[3 + i * 4] << 8) | (usb_in_buffer[2 + i * 4]); } else { *word = (usb_in_buffer[2 + i * 4] << 24) | (usb_in_buffer[3 + i * 4] << 16) | (usb_in_buffer[4 + i * 4] << 8) | (usb_in_buffer[5 + i * 4]); } } } static void aice_unpack_dthb(uint8_t *cmd_ack_code, uint8_t *extra_word_length) { *cmd_ack_code = usb_in_buffer[0]; *extra_word_length = usb_in_buffer[1]; } static void aice_unpack_dthma(uint8_t *cmd_ack_code, uint8_t *target_id, uint8_t *extra_word_length, uint32_t *word, enum aice_target_endian access_endian) { *cmd_ack_code = usb_in_buffer[0]; *target_id = usb_in_buffer[1]; *extra_word_length = usb_in_buffer[2]; if (access_endian == AICE_BIG_ENDIAN) { *word = (usb_in_buffer[7] << 24) | (usb_in_buffer[6] << 16) | (usb_in_buffer[5] << 8) | (usb_in_buffer[4]); } else { *word = (usb_in_buffer[4] << 24) | (usb_in_buffer[5] << 16) | (usb_in_buffer[6] << 8) | (usb_in_buffer[7]); } } static void aice_unpack_dthma_multiple_data(uint8_t *cmd_ack_code, uint8_t *target_id, uint8_t *extra_word_length, uint8_t *word, enum aice_target_endian access_endian) { *cmd_ack_code = usb_in_buffer[0]; *target_id = usb_in_buffer[1]; *extra_word_length = usb_in_buffer[2]; if (access_endian == AICE_BIG_ENDIAN) { word[0] = usb_in_buffer[4]; word[1] = usb_in_buffer[5]; word[2] = usb_in_buffer[6]; word[3] = usb_in_buffer[7]; } else { word[0] = usb_in_buffer[7]; word[1] = usb_in_buffer[6]; word[2] = usb_in_buffer[5]; word[3] = usb_in_buffer[4]; } word += 4; uint8_t i; for (i = 0; i < *extra_word_length; i++) { if (access_endian == AICE_BIG_ENDIAN) { word[0] = usb_in_buffer[8 + i * 4]; word[1] = usb_in_buffer[9 + i * 4]; word[2] = usb_in_buffer[10 + i * 4]; word[3] = usb_in_buffer[11 + i * 4]; } else { word[0] = usb_in_buffer[11 + i * 4]; word[1] = usb_in_buffer[10 + i * 4]; word[2] = usb_in_buffer[9 + i * 4]; word[3] = usb_in_buffer[8 + i * 4]; } word += 4; } } static void aice_unpack_dthmb(uint8_t *cmd_ack_code, uint8_t *target_id, uint8_t *extra_word_length) { *cmd_ack_code = usb_in_buffer[0]; *target_id = usb_in_buffer[1]; *extra_word_length = usb_in_buffer[2]; } /***************************************************************************/ /* End of AICE commands' pack/unpack functions */ /* calls the given usb_bulk_* function, allowing for the data to * trickle in with some timeouts */ static int usb_bulk_with_retries( int (*f)(libusb_device_handle *, int, char *, int, int, int *), libusb_device_handle *dev, int ep, char *bytes, int size, int timeout, int *transferred) { int tries = 3, count = 0; while (tries && (count < size)) { int result, ret; ret = f(dev, ep, bytes + count, size - count, timeout, &result); if (ERROR_OK == ret) count += result; else if ((ERROR_TIMEOUT_REACHED != ret) || !--tries) return ret; } *transferred = count; return ERROR_OK; } static int wrap_usb_bulk_write(libusb_device_handle *dev, int ep, char *buff, int size, int timeout, int *transferred) { /* usb_bulk_write() takes const char *buff */ jtag_libusb_bulk_write(dev, ep, buff, size, timeout, transferred); return 0; } static inline int usb_bulk_write_ex(libusb_device_handle *dev, int ep, char *bytes, int size, int timeout) { int tr = 0; usb_bulk_with_retries(&wrap_usb_bulk_write, dev, ep, bytes, size, timeout, &tr); return tr; } static inline int usb_bulk_read_ex(struct libusb_device_handle *dev, int ep, char *bytes, int size, int timeout) { int tr = 0; usb_bulk_with_retries(&jtag_libusb_bulk_read, dev, ep, bytes, size, timeout, &tr); return tr; } /* Write data from out_buffer to USB. */ static int aice_usb_write(uint8_t *out_buffer, int out_length) { int result; if (out_length > AICE_OUT_BUFFER_SIZE) { LOG_ERROR("aice_write illegal out_length=%i (max=%i)", out_length, AICE_OUT_BUFFER_SIZE); return -1; } result = usb_bulk_write_ex(aice_handler.usb_handle, aice_handler.usb_write_ep, (char *)out_buffer, out_length, AICE_USB_TIMEOUT); LOG_DEBUG_IO("aice_usb_write, out_length = %i, result = %i", out_length, result); return result; } /* Read data from USB into in_buffer. */ static int aice_usb_read(uint8_t *in_buffer, int expected_size) { int result = usb_bulk_read_ex(aice_handler.usb_handle, aice_handler.usb_read_ep, (char *)in_buffer, expected_size, AICE_USB_TIMEOUT); LOG_DEBUG_IO("aice_usb_read, result = %d", result); return result; } static uint8_t usb_out_packets_buffer[AICE_OUT_PACKETS_BUFFER_SIZE]; static uint8_t usb_in_packets_buffer[AICE_IN_PACKETS_BUFFER_SIZE]; static uint32_t usb_out_packets_buffer_length; static uint32_t usb_in_packets_buffer_length; static enum aice_command_mode aice_command_mode; static int aice_batch_buffer_write(uint8_t buf_index, const uint8_t *word, uint32_t num_of_words); static int aice_usb_packet_flush(void) { if (usb_out_packets_buffer_length == 0) return 0; if (AICE_COMMAND_MODE_PACK == aice_command_mode) { LOG_DEBUG("Flush usb packets (AICE_COMMAND_MODE_PACK)"); if (aice_usb_write(usb_out_packets_buffer, usb_out_packets_buffer_length) < 0) return ERROR_FAIL; if (aice_usb_read(usb_in_packets_buffer, usb_in_packets_buffer_length) < 0) return ERROR_FAIL; usb_out_packets_buffer_length = 0; usb_in_packets_buffer_length = 0; } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { LOG_DEBUG("Flush usb packets (AICE_COMMAND_MODE_BATCH)"); /* use BATCH_BUFFER_WRITE to fill command-batch-buffer */ if (aice_batch_buffer_write(AICE_BATCH_COMMAND_BUFFER_0, usb_out_packets_buffer, (usb_out_packets_buffer_length + 3) / 4) != ERROR_OK) return ERROR_FAIL; usb_out_packets_buffer_length = 0; usb_in_packets_buffer_length = 0; /* enable BATCH command */ aice_command_mode = AICE_COMMAND_MODE_NORMAL; if (aice_write_ctrl(AICE_WRITE_CTRL_BATCH_CTRL, 0x80000000) != ERROR_OK) return ERROR_FAIL; aice_command_mode = AICE_COMMAND_MODE_BATCH; /* wait 1 second (AICE bug, workaround) */ alive_sleep(1000); /* check status */ uint32_t i; uint32_t batch_status; i = 0; while (1) { int retval = aice_read_ctrl(AICE_READ_CTRL_BATCH_STATUS, &batch_status); if (retval != ERROR_OK) return retval; if (batch_status & 0x1) return ERROR_OK; else if (batch_status & 0xE) return ERROR_FAIL; if ((i % 30) == 0) keep_alive(); i++; } } return ERROR_OK; } static int aice_usb_packet_append(uint8_t *out_buffer, int out_length, int in_length) { uint32_t max_packet_size = AICE_OUT_PACKETS_BUFFER_SIZE; if (AICE_COMMAND_MODE_PACK == aice_command_mode) { max_packet_size = AICE_OUT_PACK_COMMAND_SIZE; } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { max_packet_size = AICE_OUT_BATCH_COMMAND_SIZE; } else { /* AICE_COMMAND_MODE_NORMAL */ if (aice_usb_packet_flush() != ERROR_OK) return ERROR_FAIL; } if (usb_out_packets_buffer_length + out_length > max_packet_size) if (aice_usb_packet_flush() != ERROR_OK) { LOG_DEBUG("Flush usb packets failed"); return ERROR_FAIL; } LOG_DEBUG("Append usb packets 0x%02x", out_buffer[0]); memcpy(usb_out_packets_buffer + usb_out_packets_buffer_length, out_buffer, out_length); usb_out_packets_buffer_length += out_length; usb_in_packets_buffer_length += in_length; return ERROR_OK; } /***************************************************************************/ /* AICE commands */ static int aice_reset_box(void) { if (aice_write_ctrl(AICE_WRITE_CTRL_CLEAR_TIMEOUT_STATUS, 0x1) != ERROR_OK) return ERROR_FAIL; /* turn off FASTMODE */ uint32_t pin_status; if (aice_read_ctrl(AICE_READ_CTRL_GET_JTAG_PIN_STATUS, &pin_status) != ERROR_OK) return ERROR_FAIL; if (aice_write_ctrl(AICE_WRITE_CTRL_JTAG_PIN_STATUS, pin_status & (~0x2)) != ERROR_OK) return ERROR_FAIL; return ERROR_OK; } static int aice_scan_chain(uint32_t *id_codes, uint8_t *num_of_ids) { int retry_times = 0; if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) aice_usb_packet_flush(); do { aice_pack_htda(AICE_CMD_SCAN_CHAIN, 0x0F, 0x0); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDA); LOG_DEBUG("SCAN_CHAIN, length: 0x0F"); /** TODO: modify receive length */ int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHA); if (AICE_FORMAT_DTHA != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHA, result); return ERROR_FAIL; } uint8_t cmd_ack_code; aice_unpack_dtha_multiple_data(&cmd_ack_code, num_of_ids, id_codes, 0x10, AICE_LITTLE_ENDIAN); if (cmd_ack_code != AICE_CMD_SCAN_CHAIN) { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_SCAN_CHAIN, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; continue; } LOG_DEBUG("SCAN_CHAIN response, # of IDs: %" PRIu8, *num_of_ids); if (*num_of_ids == 0xFF) { LOG_ERROR("No target connected"); return ERROR_FAIL; } else if (*num_of_ids == AICE_MAX_NUM_CORE) { LOG_INFO("The ice chain over 16 targets"); } else { (*num_of_ids)++; } break; } while (1); return ERROR_OK; } int aice_read_ctrl(uint32_t address, uint32_t *data) { if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) aice_usb_packet_flush(); aice_pack_htda(AICE_CMD_READ_CTRL, 0, address); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDA); LOG_DEBUG("READ_CTRL, address: 0x%" PRIx32, address); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHA); if (AICE_FORMAT_DTHA != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHA, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; aice_unpack_dtha(&cmd_ack_code, &extra_length, data, AICE_LITTLE_ENDIAN); LOG_DEBUG("READ_CTRL response, data: 0x%" PRIx32, *data); if (cmd_ack_code != AICE_CMD_READ_CTRL) { LOG_ERROR("aice command error (command=0x%" PRIx32 ", response=0x%" PRIx8 ")", (uint32_t)AICE_CMD_READ_CTRL, cmd_ack_code); return ERROR_FAIL; } return ERROR_OK; } int aice_write_ctrl(uint32_t address, uint32_t data) { if (AICE_COMMAND_MODE_PACK == aice_command_mode) { aice_usb_packet_flush(); } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { aice_pack_htdc(AICE_CMD_WRITE_CTRL, 0, address, data, AICE_LITTLE_ENDIAN); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDC, AICE_FORMAT_DTHB); } aice_pack_htdc(AICE_CMD_WRITE_CTRL, 0, address, data, AICE_LITTLE_ENDIAN); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDC); LOG_DEBUG("WRITE_CTRL, address: 0x%" PRIx32 ", data: 0x%" PRIx32, address, data); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHB); if (AICE_FORMAT_DTHB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; aice_unpack_dthb(&cmd_ack_code, &extra_length); LOG_DEBUG("WRITE_CTRL response"); if (cmd_ack_code != AICE_CMD_WRITE_CTRL) { LOG_ERROR("aice command error (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_WRITE_CTRL, cmd_ack_code); return ERROR_FAIL; } return ERROR_OK; } static int aice_read_dtr(uint8_t target_id, uint32_t *data) { int retry_times = 0; if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) aice_usb_packet_flush(); do { aice_pack_htdma(AICE_CMD_T_READ_DTR, target_id, 0, 0); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMA); LOG_DEBUG("READ_DTR, COREID: %" PRIu8, target_id); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMA); if (AICE_FORMAT_DTHMA != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMA, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthma(&cmd_ack_code, &res_target_id, &extra_length, data, AICE_LITTLE_ENDIAN); if (cmd_ack_code == AICE_CMD_T_READ_DTR) { LOG_DEBUG("READ_DTR response, data: 0x%" PRIx32, *data); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_READ_DTR, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_read_dtr_to_buffer(uint8_t target_id, uint32_t buffer_idx) { int retry_times = 0; if (AICE_COMMAND_MODE_PACK == aice_command_mode) { aice_usb_packet_flush(); } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { aice_pack_htdma(AICE_CMD_READ_DTR_TO_BUFFER, target_id, 0, buffer_idx); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMA, AICE_FORMAT_DTHMB); } do { aice_pack_htdma(AICE_CMD_READ_DTR_TO_BUFFER, target_id, 0, buffer_idx); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMA); LOG_DEBUG("READ_DTR_TO_BUFFER, COREID: %" PRIu8, target_id); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_READ_DTR_TO_BUFFER) { break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_READ_DTR_TO_BUFFER, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_write_dtr(uint8_t target_id, uint32_t data) { int retry_times = 0; if (AICE_COMMAND_MODE_PACK == aice_command_mode) { aice_usb_packet_flush(); } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { aice_pack_htdmc(AICE_CMD_T_WRITE_DTR, target_id, 0, 0, data, AICE_LITTLE_ENDIAN); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMC, AICE_FORMAT_DTHMB); } do { aice_pack_htdmc(AICE_CMD_T_WRITE_DTR, target_id, 0, 0, data, AICE_LITTLE_ENDIAN); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMC); LOG_DEBUG("WRITE_DTR, COREID: %" PRIu8 ", data: 0x%" PRIx32, target_id, data); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_T_WRITE_DTR) { LOG_DEBUG("WRITE_DTR response"); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_WRITE_DTR, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_write_dtr_from_buffer(uint8_t target_id, uint32_t buffer_idx) { int retry_times = 0; if (AICE_COMMAND_MODE_PACK == aice_command_mode) { aice_usb_packet_flush(); } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { aice_pack_htdma(AICE_CMD_WRITE_DTR_FROM_BUFFER, target_id, 0, buffer_idx); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMA, AICE_FORMAT_DTHMB); } do { aice_pack_htdma(AICE_CMD_WRITE_DTR_FROM_BUFFER, target_id, 0, buffer_idx); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMA); LOG_DEBUG("WRITE_DTR_FROM_BUFFER, COREID: %" PRIu8 "", target_id); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_WRITE_DTR_FROM_BUFFER) { break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_WRITE_DTR_FROM_BUFFER, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_read_misc(uint8_t target_id, uint32_t address, uint32_t *data) { int retry_times = 0; if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) aice_usb_packet_flush(); do { aice_pack_htdma(AICE_CMD_T_READ_MISC, target_id, 0, address); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMA); LOG_DEBUG("READ_MISC, COREID: %" PRIu8 ", address: 0x%" PRIx32, target_id, address); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMA); if (AICE_FORMAT_DTHMA != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMA, result); return ERROR_AICE_DISCONNECT; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthma(&cmd_ack_code, &res_target_id, &extra_length, data, AICE_LITTLE_ENDIAN); if (cmd_ack_code == AICE_CMD_T_READ_MISC) { LOG_DEBUG("READ_MISC response, data: 0x%" PRIx32, *data); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_READ_MISC, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_write_misc(uint8_t target_id, uint32_t address, uint32_t data) { int retry_times = 0; if (AICE_COMMAND_MODE_PACK == aice_command_mode) { aice_usb_packet_flush(); } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { aice_pack_htdmc(AICE_CMD_T_WRITE_MISC, target_id, 0, address, data, AICE_LITTLE_ENDIAN); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMC, AICE_FORMAT_DTHMB); } do { aice_pack_htdmc(AICE_CMD_T_WRITE_MISC, target_id, 0, address, data, AICE_LITTLE_ENDIAN); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMC); LOG_DEBUG("WRITE_MISC, COREID: %" PRIu8 ", address: 0x%" PRIx32 ", data: 0x%" PRIx32, target_id, address, data); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_T_WRITE_MISC) { LOG_DEBUG("WRITE_MISC response"); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_WRITE_MISC, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_read_edmsr(uint8_t target_id, uint32_t address, uint32_t *data) { int retry_times = 0; if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) aice_usb_packet_flush(); do { aice_pack_htdma(AICE_CMD_T_READ_EDMSR, target_id, 0, address); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMA); LOG_DEBUG("READ_EDMSR, COREID: %" PRIu8 ", address: 0x%" PRIx32, target_id, address); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMA); if (AICE_FORMAT_DTHMA != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMA, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthma(&cmd_ack_code, &res_target_id, &extra_length, data, AICE_LITTLE_ENDIAN); if (cmd_ack_code == AICE_CMD_T_READ_EDMSR) { LOG_DEBUG("READ_EDMSR response, data: 0x%" PRIx32, *data); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_READ_EDMSR, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_write_edmsr(uint8_t target_id, uint32_t address, uint32_t data) { int retry_times = 0; if (AICE_COMMAND_MODE_PACK == aice_command_mode) { aice_usb_packet_flush(); } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { aice_pack_htdmc(AICE_CMD_T_WRITE_EDMSR, target_id, 0, address, data, AICE_LITTLE_ENDIAN); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMC, AICE_FORMAT_DTHMB); } do { aice_pack_htdmc(AICE_CMD_T_WRITE_EDMSR, target_id, 0, address, data, AICE_LITTLE_ENDIAN); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMC); LOG_DEBUG("WRITE_EDMSR, COREID: %" PRIu8 ", address: 0x%" PRIx32 ", data: 0x%" PRIx32, target_id, address, data); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_T_WRITE_EDMSR) { LOG_DEBUG("WRITE_EDMSR response"); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_WRITE_EDMSR, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_switch_to_big_endian(uint32_t *word, uint8_t num_of_words) { uint32_t tmp; for (uint8_t i = 0 ; i < num_of_words ; i++) { tmp = ((word[i] >> 24) & 0x000000FF) | ((word[i] >> 8) & 0x0000FF00) | ((word[i] << 8) & 0x00FF0000) | ((word[i] << 24) & 0xFF000000); word[i] = tmp; } return ERROR_OK; } static int aice_write_dim(uint8_t target_id, uint32_t *word, uint8_t num_of_words) { uint32_t big_endian_word[4]; int retry_times = 0; /** instruction is big-endian */ memcpy(big_endian_word, word, sizeof(big_endian_word)); aice_switch_to_big_endian(big_endian_word, num_of_words); if (AICE_COMMAND_MODE_PACK == aice_command_mode) { aice_usb_packet_flush(); } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { aice_pack_htdmc_multiple_data(AICE_CMD_T_WRITE_DIM, target_id, num_of_words - 1, 0, big_endian_word, num_of_words, AICE_LITTLE_ENDIAN); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMC + (num_of_words - 1) * 4, AICE_FORMAT_DTHMB); } do { aice_pack_htdmc_multiple_data(AICE_CMD_T_WRITE_DIM, target_id, num_of_words - 1, 0, big_endian_word, num_of_words, AICE_LITTLE_ENDIAN); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMC + (num_of_words - 1) * 4); LOG_DEBUG("WRITE_DIM, COREID: %" PRIu8 ", data: 0x%08" PRIx32 ", 0x%08" PRIx32 ", 0x%08" PRIx32 ", 0x%08" PRIx32, target_id, big_endian_word[0], big_endian_word[1], big_endian_word[2], big_endian_word[3]); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_T_WRITE_DIM) { LOG_DEBUG("WRITE_DIM response"); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_WRITE_DIM, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_do_execute(uint8_t target_id) { int retry_times = 0; if (AICE_COMMAND_MODE_PACK == aice_command_mode) { aice_usb_packet_flush(); } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { aice_pack_htdmc(AICE_CMD_T_EXECUTE, target_id, 0, 0, 0, AICE_LITTLE_ENDIAN); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMC, AICE_FORMAT_DTHMB); } do { aice_pack_htdmc(AICE_CMD_T_EXECUTE, target_id, 0, 0, 0, AICE_LITTLE_ENDIAN); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMC); LOG_DEBUG("EXECUTE, COREID: %" PRIu8 "", target_id); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_T_EXECUTE) { LOG_DEBUG("EXECUTE response"); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_EXECUTE, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_write_mem_b(uint8_t target_id, uint32_t address, uint32_t data) { int retry_times = 0; LOG_DEBUG("WRITE_MEM_B, COREID: %" PRIu8 ", ADDRESS %08" PRIx32 " VALUE %08" PRIx32, target_id, address, data); if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) { aice_pack_htdmd(AICE_CMD_T_WRITE_MEM_B, target_id, 0, address, data & 0x000000FF, data_endian); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMD, AICE_FORMAT_DTHMB); } else { do { aice_pack_htdmd(AICE_CMD_T_WRITE_MEM_B, target_id, 0, address, data & 0x000000FF, data_endian); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMD); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_T_WRITE_MEM_B) { break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_WRITE_MEM_B, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); } return ERROR_OK; } static int aice_write_mem_h(uint8_t target_id, uint32_t address, uint32_t data) { int retry_times = 0; LOG_DEBUG("WRITE_MEM_H, COREID: %" PRIu8 ", ADDRESS %08" PRIx32 " VALUE %08" PRIx32, target_id, address, data); if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) { aice_pack_htdmd(AICE_CMD_T_WRITE_MEM_H, target_id, 0, (address >> 1) & 0x7FFFFFFF, data & 0x0000FFFF, data_endian); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMD, AICE_FORMAT_DTHMB); } else { do { aice_pack_htdmd(AICE_CMD_T_WRITE_MEM_H, target_id, 0, (address >> 1) & 0x7FFFFFFF, data & 0x0000FFFF, data_endian); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMD); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_T_WRITE_MEM_H) { break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_WRITE_MEM_H, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); } return ERROR_OK; } static int aice_write_mem(uint8_t target_id, uint32_t address, uint32_t data) { int retry_times = 0; LOG_DEBUG("WRITE_MEM, COREID: %" PRIu8 ", ADDRESS %08" PRIx32 " VALUE %08" PRIx32, target_id, address, data); if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) { aice_pack_htdmd(AICE_CMD_T_WRITE_MEM, target_id, 0, (address >> 2) & 0x3FFFFFFF, data, data_endian); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMD, AICE_FORMAT_DTHMB); } else { do { aice_pack_htdmd(AICE_CMD_T_WRITE_MEM, target_id, 0, (address >> 2) & 0x3FFFFFFF, data, data_endian); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMD); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_T_WRITE_MEM) { break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_WRITE_MEM, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); } return ERROR_OK; } static int aice_fastread_mem(uint8_t target_id, uint8_t *word, uint32_t num_of_words) { int retry_times = 0; if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) aice_usb_packet_flush(); do { aice_pack_htdmb(AICE_CMD_T_FASTREAD_MEM, target_id, num_of_words - 1, 0); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMB); LOG_DEBUG("FASTREAD_MEM, COREID: %" PRIu8 ", # of DATA %08" PRIx32, target_id, num_of_words); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMA + (num_of_words - 1) * 4); if (result < 0) { LOG_ERROR("aice_usb_read failed (requested=%" PRIu32 ", result=%d)", AICE_FORMAT_DTHMA + (num_of_words - 1) * 4, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthma_multiple_data(&cmd_ack_code, &res_target_id, &extra_length, word, data_endian); if (cmd_ack_code == AICE_CMD_T_FASTREAD_MEM) { break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_FASTREAD_MEM, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_fastwrite_mem(uint8_t target_id, const uint8_t *word, uint32_t num_of_words) { int retry_times = 0; if (AICE_COMMAND_MODE_PACK == aice_command_mode) { aice_usb_packet_flush(); } else if (AICE_COMMAND_MODE_BATCH == aice_command_mode) { aice_pack_htdmd_multiple_data(AICE_CMD_T_FASTWRITE_MEM, target_id, num_of_words - 1, 0, word, data_endian); return aice_usb_packet_append(usb_out_buffer, AICE_FORMAT_HTDMD + (num_of_words - 1) * 4, AICE_FORMAT_DTHMB); } do { aice_pack_htdmd_multiple_data(AICE_CMD_T_FASTWRITE_MEM, target_id, num_of_words - 1, 0, word, data_endian); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMD + (num_of_words - 1) * 4); LOG_DEBUG("FASTWRITE_MEM, COREID: %" PRIu8 ", # of DATA %08" PRIx32, target_id, num_of_words); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_T_FASTWRITE_MEM) { break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_FASTWRITE_MEM, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_read_mem_b(uint8_t target_id, uint32_t address, uint32_t *data) { int retry_times = 0; if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) aice_usb_packet_flush(); do { aice_pack_htdmb(AICE_CMD_T_READ_MEM_B, target_id, 0, address); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMB); LOG_DEBUG("READ_MEM_B, COREID: %" PRIu8 "", target_id); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMA); if (AICE_FORMAT_DTHMA != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMA, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthma(&cmd_ack_code, &res_target_id, &extra_length, data, data_endian); if (cmd_ack_code == AICE_CMD_T_READ_MEM_B) { LOG_DEBUG("READ_MEM_B response, data: 0x%02" PRIx32, *data); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_READ_MEM_B, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_read_mem_h(uint8_t target_id, uint32_t address, uint32_t *data) { int retry_times = 0; if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) aice_usb_packet_flush(); do { aice_pack_htdmb(AICE_CMD_T_READ_MEM_H, target_id, 0, (address >> 1) & 0x7FFFFFFF); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMB); LOG_DEBUG("READ_MEM_H, CORE_ID: %" PRIu8 "", target_id); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMA); if (AICE_FORMAT_DTHMA != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMA, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthma(&cmd_ack_code, &res_target_id, &extra_length, data, data_endian); if (cmd_ack_code == AICE_CMD_T_READ_MEM_H) { LOG_DEBUG("READ_MEM_H response, data: 0x%" PRIx32, *data); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_READ_MEM_H, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_read_mem(uint8_t target_id, uint32_t address, uint32_t *data) { int retry_times = 0; if ((AICE_COMMAND_MODE_PACK == aice_command_mode) || (AICE_COMMAND_MODE_BATCH == aice_command_mode)) aice_usb_packet_flush(); do { aice_pack_htdmb(AICE_CMD_T_READ_MEM, target_id, 0, (address >> 2) & 0x3FFFFFFF); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMB); LOG_DEBUG("READ_MEM, COREID: %" PRIu8 "", target_id); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMA); if (AICE_FORMAT_DTHMA != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMA, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthma(&cmd_ack_code, &res_target_id, &extra_length, data, data_endian); if (cmd_ack_code == AICE_CMD_T_READ_MEM) { LOG_DEBUG("READ_MEM response, data: 0x%" PRIx32, *data); break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_T_READ_MEM, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } static int aice_batch_buffer_read(uint8_t buf_index, uint32_t *word, uint32_t num_of_words) { int retry_times = 0; do { aice_pack_htdma(AICE_CMD_BATCH_BUFFER_READ, 0, num_of_words - 1, buf_index); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMA); LOG_DEBUG("BATCH_BUFFER_READ, # of DATA %08" PRIx32, num_of_words); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMA + (num_of_words - 1) * 4); if (result < 0) { LOG_ERROR("aice_usb_read failed (requested=%" PRIu32 ", result=%d)", AICE_FORMAT_DTHMA + (num_of_words - 1) * 4, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthma_multiple_data(&cmd_ack_code, &res_target_id, &extra_length, (uint8_t *)word, data_endian); if (cmd_ack_code == AICE_CMD_BATCH_BUFFER_READ) { break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_BATCH_BUFFER_READ, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } int aice_batch_buffer_write(uint8_t buf_index, const uint8_t *word, uint32_t num_of_words) { int retry_times = 0; if (num_of_words == 0) return ERROR_OK; do { /* only pack AICE_CMD_BATCH_BUFFER_WRITE command header */ aice_pack_htdmc(AICE_CMD_BATCH_BUFFER_WRITE, 0, num_of_words - 1, buf_index, 0, data_endian); /* use append instead of pack */ memcpy(usb_out_buffer + 4, word, num_of_words * 4); aice_usb_write(usb_out_buffer, AICE_FORMAT_HTDMC + (num_of_words - 1) * 4); LOG_DEBUG("BATCH_BUFFER_WRITE, # of DATA %08" PRIx32, num_of_words); int result = aice_usb_read(usb_in_buffer, AICE_FORMAT_DTHMB); if (AICE_FORMAT_DTHMB != result) { LOG_ERROR("aice_usb_read failed (requested=%d, result=%d)", AICE_FORMAT_DTHMB, result); return ERROR_FAIL; } uint8_t cmd_ack_code; uint8_t extra_length; uint8_t res_target_id; aice_unpack_dthmb(&cmd_ack_code, &res_target_id, &extra_length); if (cmd_ack_code == AICE_CMD_BATCH_BUFFER_WRITE) { break; } else { if (retry_times > aice_max_retry_times) { LOG_ERROR("aice command timeout (command=0x%" PRIx8 ", response=0x%" PRIx8 ")", AICE_CMD_BATCH_BUFFER_WRITE, cmd_ack_code); return ERROR_FAIL; } /* clear timeout and retry */ if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; retry_times++; } } while (1); return ERROR_OK; } /***************************************************************************/ /* End of AICE commands */ typedef int (*read_mem_func_t)(uint32_t coreid, uint32_t address, uint32_t *data); typedef int (*write_mem_func_t)(uint32_t coreid, uint32_t address, uint32_t data); static struct aice_nds32_info core_info[AICE_MAX_NUM_CORE]; static uint8_t total_num_of_core; static char *custom_srst_script; static char *custom_trst_script; static char *custom_restart_script; static uint32_t aice_count_to_check_dbger = 30; static int aice_read_reg(uint32_t coreid, uint32_t num, uint32_t *val); static int aice_write_reg(uint32_t coreid, uint32_t num, uint32_t val); static int check_suppressed_exception(uint32_t coreid, uint32_t dbger_value) { uint32_t ir4_value = 0; uint32_t ir6_value = 0; /* the default value of handling_suppressed_exception is false */ static bool handling_suppressed_exception; if (handling_suppressed_exception) return ERROR_OK; if ((dbger_value & NDS_DBGER_ALL_SUPRS_EX) == NDS_DBGER_ALL_SUPRS_EX) { LOG_ERROR("<-- TARGET WARNING! Exception is detected and suppressed. -->"); handling_suppressed_exception = true; aice_read_reg(coreid, IR4, &ir4_value); /* Clear IR6.SUPRS_EXC, IR6.IMP_EXC */ aice_read_reg(coreid, IR6, &ir6_value); /* * For MCU version(MSC_CFG.MCU == 1) like V3m * | SWID[30:16] | Reserved[15:10] | SUPRS_EXC[9] | IMP_EXC[8] * |VECTOR[7:5] | INST[4] | Exc Type[3:0] | * * For non-MCU version(MSC_CFG.MCU == 0) like V3 * | SWID[30:16] | Reserved[15:14] | SUPRS_EXC[13] | IMP_EXC[12] * | VECTOR[11:5] | INST[4] | Exc Type[3:0] | */ LOG_INFO("EVA: 0x%08" PRIx32, ir4_value); LOG_INFO("ITYPE: 0x%08" PRIx32, ir6_value); ir6_value = ir6_value & (~0x300); /* for MCU */ ir6_value = ir6_value & (~0x3000); /* for non-MCU */ aice_write_reg(coreid, IR6, ir6_value); handling_suppressed_exception = false; } return ERROR_OK; } static int check_privilege(uint32_t coreid, uint32_t dbger_value) { if ((dbger_value & NDS_DBGER_ILL_SEC_ACC) == NDS_DBGER_ILL_SEC_ACC) { LOG_ERROR("<-- TARGET ERROR! Insufficient security privilege " "to execute the debug operations. -->"); /* Clear DBGER.ILL_SEC_ACC */ if (aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_ILL_SEC_ACC) != ERROR_OK) return ERROR_FAIL; } return ERROR_OK; } static int aice_check_dbger(uint32_t coreid, uint32_t expect_status) { uint32_t i = 0; uint32_t value_dbger = 0; while (1) { aice_read_misc(coreid, NDS_EDM_MISC_DBGER, &value_dbger); if ((value_dbger & expect_status) == expect_status) { if (ERROR_OK != check_suppressed_exception(coreid, value_dbger)) return ERROR_FAIL; if (ERROR_OK != check_privilege(coreid, value_dbger)) return ERROR_FAIL; return ERROR_OK; } if ((i % 30) == 0) keep_alive(); int64_t then = 0; if (i == aice_count_to_check_dbger) then = timeval_ms(); if (i >= aice_count_to_check_dbger) { if ((timeval_ms() - then) > 1000) { LOG_ERROR("Timeout (1000ms) waiting for $DBGER status " "being 0x%08" PRIx32, expect_status); return ERROR_FAIL; } } i++; } return ERROR_FAIL; } static int aice_execute_dim(uint32_t coreid, uint32_t *insts, uint8_t n_inst) { /** fill DIM */ if (aice_write_dim(coreid, insts, n_inst) != ERROR_OK) return ERROR_FAIL; /** clear DBGER.DPED */ if (aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_DPED) != ERROR_OK) return ERROR_FAIL; /** execute DIM */ if (aice_do_execute(coreid) != ERROR_OK) return ERROR_FAIL; /** read DBGER.DPED */ if (aice_check_dbger(coreid, NDS_DBGER_DPED) != ERROR_OK) { LOG_ERROR("<-- TARGET ERROR! Debug operations do not finish properly: " "0x%08" PRIx32 "0x%08" PRIx32 "0x%08" PRIx32 "0x%08" PRIx32 ". -->", insts[0], insts[1], insts[2], insts[3]); return ERROR_FAIL; } return ERROR_OK; } static int aice_read_reg(uint32_t coreid, uint32_t num, uint32_t *val) { LOG_DEBUG("aice_read_reg, reg_no: 0x%08" PRIx32, num); uint32_t instructions[4]; /** execute instructions in DIM */ if (NDS32_REG_TYPE_GPR == nds32_reg_type(num)) { /* general registers */ instructions[0] = MTSR_DTR(num); instructions[1] = DSB; instructions[2] = NOP; instructions[3] = BEQ_MINUS_12; } else if (NDS32_REG_TYPE_SPR == nds32_reg_type(num)) { /* user special registers */ instructions[0] = MFUSR_G0(0, nds32_reg_sr_index(num)); instructions[1] = MTSR_DTR(0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } else if (NDS32_REG_TYPE_AUMR == nds32_reg_type(num)) { /* audio registers */ if ((CB_CTL <= num) && (num <= CBE3)) { instructions[0] = AMFAR2(0, nds32_reg_sr_index(num)); instructions[1] = MTSR_DTR(0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } else { instructions[0] = AMFAR(0, nds32_reg_sr_index(num)); instructions[1] = MTSR_DTR(0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } } else if (NDS32_REG_TYPE_FPU == nds32_reg_type(num)) { /* fpu registers */ if (FPCSR == num) { instructions[0] = FMFCSR; instructions[1] = MTSR_DTR(0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } else if (FPCFG == num) { instructions[0] = FMFCFG; instructions[1] = MTSR_DTR(0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } else { if (FS0 <= num && num <= FS31) { /* single precision */ instructions[0] = FMFSR(0, nds32_reg_sr_index(num)); instructions[1] = MTSR_DTR(0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } else if (FD0 <= num && num <= FD31) { /* double precision */ instructions[0] = FMFDR(0, nds32_reg_sr_index(num)); instructions[1] = MTSR_DTR(0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } } } else { /* system registers */ instructions[0] = MFSR(0, nds32_reg_sr_index(num)); instructions[1] = MTSR_DTR(0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } aice_execute_dim(coreid, instructions, 4); uint32_t value_edmsw = 0; aice_read_edmsr(coreid, NDS_EDM_SR_EDMSW, &value_edmsw); if (value_edmsw & NDS_EDMSW_WDV) aice_read_dtr(coreid, val); else { LOG_ERROR("<-- TARGET ERROR! The debug target failed to update " "the DTR register. -->"); return ERROR_FAIL; } return ERROR_OK; } static int aice_usb_read_reg(uint32_t coreid, uint32_t num, uint32_t *val) { LOG_DEBUG("aice_usb_read_reg"); if (num == R0) { *val = core_info[coreid].r0_backup; } else if (num == R1) { *val = core_info[coreid].r1_backup; } else if (num == DR41) { /* As target is halted, OpenOCD will backup DR41/DR42/DR43. * As user wants to read these registers, OpenOCD should return * the backup values, instead of reading the real values. * As user wants to write these registers, OpenOCD should write * to the backup values, instead of writing to real registers. */ *val = core_info[coreid].edmsw_backup; } else if (num == DR42) { *val = core_info[coreid].edm_ctl_backup; } else if ((core_info[coreid].target_dtr_valid == true) && (num == DR43)) { *val = core_info[coreid].target_dtr_backup; } else { if (ERROR_OK != aice_read_reg(coreid, num, val)) *val = 0xBBADBEEF; } return ERROR_OK; } static int aice_write_reg(uint32_t coreid, uint32_t num, uint32_t val) { LOG_DEBUG("aice_write_reg, reg_no: 0x%08" PRIx32 ", value: 0x%08" PRIx32, num, val); uint32_t instructions[4]; /** execute instructions in DIM */ uint32_t value_edmsw = 0; aice_write_dtr(coreid, val); aice_read_edmsr(coreid, NDS_EDM_SR_EDMSW, &value_edmsw); if (0 == (value_edmsw & NDS_EDMSW_RDV)) { LOG_ERROR("<-- TARGET ERROR! AICE failed to write to the DTR register. -->"); return ERROR_FAIL; } if (NDS32_REG_TYPE_GPR == nds32_reg_type(num)) { /* general registers */ instructions[0] = MFSR_DTR(num); instructions[1] = DSB; instructions[2] = NOP; instructions[3] = BEQ_MINUS_12; } else if (NDS32_REG_TYPE_SPR == nds32_reg_type(num)) { /* user special registers */ instructions[0] = MFSR_DTR(0); instructions[1] = MTUSR_G0(0, nds32_reg_sr_index(num)); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } else if (NDS32_REG_TYPE_AUMR == nds32_reg_type(num)) { /* audio registers */ if ((CB_CTL <= num) && (num <= CBE3)) { instructions[0] = MFSR_DTR(0); instructions[1] = AMTAR2(0, nds32_reg_sr_index(num)); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } else { instructions[0] = MFSR_DTR(0); instructions[1] = AMTAR(0, nds32_reg_sr_index(num)); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } } else if (NDS32_REG_TYPE_FPU == nds32_reg_type(num)) { /* fpu registers */ if (FPCSR == num) { instructions[0] = MFSR_DTR(0); instructions[1] = FMTCSR; instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } else if (FPCFG == num) { /* FPCFG is readonly */ } else { if (FS0 <= num && num <= FS31) { /* single precision */ instructions[0] = MFSR_DTR(0); instructions[1] = FMTSR(0, nds32_reg_sr_index(num)); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } else if (FD0 <= num && num <= FD31) { /* double precision */ instructions[0] = MFSR_DTR(0); instructions[1] = FMTDR(0, nds32_reg_sr_index(num)); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } } } else { instructions[0] = MFSR_DTR(0); instructions[1] = MTSR(0, nds32_reg_sr_index(num)); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; } return aice_execute_dim(coreid, instructions, 4); } static int aice_usb_write_reg(uint32_t coreid, uint32_t num, uint32_t val) { LOG_DEBUG("aice_usb_write_reg"); if (num == R0) core_info[coreid].r0_backup = val; else if (num == R1) core_info[coreid].r1_backup = val; else if (num == DR42) /* As target is halted, OpenOCD will backup DR41/DR42/DR43. * As user wants to read these registers, OpenOCD should return * the backup values, instead of reading the real values. * As user wants to write these registers, OpenOCD should write * to the backup values, instead of writing to real registers. */ core_info[coreid].edm_ctl_backup = val; else if ((core_info[coreid].target_dtr_valid == true) && (num == DR43)) core_info[coreid].target_dtr_backup = val; else return aice_write_reg(coreid, num, val); return ERROR_OK; } static int aice_usb_open(struct aice_port_param_s *param) { const uint16_t vids[] = { param->vid, 0 }; const uint16_t pids[] = { param->pid, 0 }; struct libusb_device_handle *devh; if (jtag_libusb_open(vids, pids, NULL, &devh, NULL) != ERROR_OK) return ERROR_FAIL; /* BE ***VERY CAREFUL*** ABOUT MAKING CHANGES IN THIS * AREA!!!!!!!!!!! The behavior of libusb is not completely * consistent across Windows, Linux, and Mac OS X platforms. * The actions taken in the following compiler conditionals may * not agree with published documentation for libusb, but were * found to be necessary through trials and tribulations. Even * little tweaks can break one or more platforms, so if you do * make changes test them carefully on all platforms before * committing them! */ #if IS_WIN32 == 0 libusb_reset_device(devh); #if IS_DARWIN == 0 int timeout = 5; /* reopen jlink after usb_reset * on win32 this may take a second or two to re-enumerate */ int retval; while ((retval = jtag_libusb_open(vids, pids, NULL, &devh, NULL)) != ERROR_OK) { usleep(1000); timeout--; if (!timeout) break; } if (ERROR_OK != retval) return ERROR_FAIL; #endif #endif /* usb_set_configuration required under win32 */ libusb_set_configuration(devh, 0); libusb_claim_interface(devh, 0); unsigned int aice_read_ep; unsigned int aice_write_ep; jtag_libusb_choose_interface(devh, &aice_read_ep, &aice_write_ep, -1, -1, -1, LIBUSB_TRANSFER_TYPE_BULK); LOG_DEBUG("aice_read_ep=0x%x, aice_write_ep=0x%x", aice_read_ep, aice_write_ep); aice_handler.usb_read_ep = aice_read_ep; aice_handler.usb_write_ep = aice_write_ep; aice_handler.usb_handle = devh; return ERROR_OK; } static int aice_usb_read_reg_64(uint32_t coreid, uint32_t num, uint64_t *val) { LOG_DEBUG("aice_usb_read_reg_64, %s", nds32_reg_simple_name(num)); uint32_t value; uint32_t high_value; if (ERROR_OK != aice_read_reg(coreid, num, &value)) value = 0xBBADBEEF; aice_read_reg(coreid, R1, &high_value); LOG_DEBUG("low: 0x%08" PRIx32 ", high: 0x%08" PRIx32 "\n", value, high_value); if (data_endian == AICE_BIG_ENDIAN) *val = (((uint64_t)high_value) << 32) | value; else *val = (((uint64_t)value) << 32) | high_value; return ERROR_OK; } static int aice_usb_write_reg_64(uint32_t coreid, uint32_t num, uint64_t val) { uint32_t value; uint32_t high_value; if (data_endian == AICE_BIG_ENDIAN) { value = val & 0xFFFFFFFF; high_value = (val >> 32) & 0xFFFFFFFF; } else { high_value = val & 0xFFFFFFFF; value = (val >> 32) & 0xFFFFFFFF; } LOG_DEBUG("aice_usb_write_reg_64, %s, low: 0x%08" PRIx32 ", high: 0x%08" PRIx32 "\n", nds32_reg_simple_name(num), value, high_value); aice_write_reg(coreid, R1, high_value); return aice_write_reg(coreid, num, value); } static int aice_get_version_info(void) { uint32_t hardware_version; uint32_t firmware_version; uint32_t fpga_version; if (aice_read_ctrl(AICE_READ_CTRL_GET_HARDWARE_VERSION, &hardware_version) != ERROR_OK) return ERROR_FAIL; if (aice_read_ctrl(AICE_READ_CTRL_GET_FIRMWARE_VERSION, &firmware_version) != ERROR_OK) return ERROR_FAIL; if (aice_read_ctrl(AICE_READ_CTRL_GET_FPGA_VERSION, &fpga_version) != ERROR_OK) return ERROR_FAIL; LOG_INFO("AICE version: hw_ver = 0x%" PRIx32 ", fw_ver = 0x%" PRIx32 ", fpga_ver = 0x%" PRIx32, hardware_version, firmware_version, fpga_version); return ERROR_OK; } #define LINE_BUFFER_SIZE 1024 static int aice_execute_custom_script(const char *script) { FILE *script_fd; char line_buffer[LINE_BUFFER_SIZE]; char *op_str; char *reset_str; uint32_t delay; uint32_t write_ctrl_value; bool set_op; script_fd = fopen(script, "r"); if (script_fd == NULL) { return ERROR_FAIL; } else { while (fgets(line_buffer, LINE_BUFFER_SIZE, script_fd) != NULL) { /* execute operations */ set_op = false; op_str = strstr(line_buffer, "set"); if (op_str != NULL) { set_op = true; goto get_reset_type; } op_str = strstr(line_buffer, "clear"); if (op_str == NULL) continue; get_reset_type: reset_str = strstr(op_str, "srst"); if (reset_str != NULL) { if (set_op) write_ctrl_value = AICE_CUSTOM_DELAY_SET_SRST; else write_ctrl_value = AICE_CUSTOM_DELAY_CLEAN_SRST; goto get_delay; } reset_str = strstr(op_str, "dbgi"); if (reset_str != NULL) { if (set_op) write_ctrl_value = AICE_CUSTOM_DELAY_SET_DBGI; else write_ctrl_value = AICE_CUSTOM_DELAY_CLEAN_DBGI; goto get_delay; } reset_str = strstr(op_str, "trst"); if (reset_str != NULL) { if (set_op) write_ctrl_value = AICE_CUSTOM_DELAY_SET_TRST; else write_ctrl_value = AICE_CUSTOM_DELAY_CLEAN_TRST; goto get_delay; } continue; get_delay: /* get delay */ delay = strtoul(reset_str + 4, NULL, 0); write_ctrl_value |= (delay << 16); if (aice_write_ctrl(AICE_WRITE_CTRL_CUSTOM_DELAY, write_ctrl_value) != ERROR_OK) { fclose(script_fd); return ERROR_FAIL; } } fclose(script_fd); } return ERROR_OK; } static int aice_usb_set_clock(int set_clock) { if (set_clock & AICE_TCK_CONTROL_TCK_SCAN) { if (aice_write_ctrl(AICE_WRITE_CTRL_TCK_CONTROL, AICE_TCK_CONTROL_TCK_SCAN) != ERROR_OK) return ERROR_FAIL; /* Read out TCK_SCAN clock value */ uint32_t scan_clock; if (aice_read_ctrl(AICE_READ_CTRL_GET_ICE_STATE, &scan_clock) != ERROR_OK) return ERROR_FAIL; scan_clock &= 0x0F; uint32_t scan_base_freq; if (scan_clock & 0x8) scan_base_freq = 48000; /* 48 MHz */ else scan_base_freq = 30000; /* 30 MHz */ uint32_t set_base_freq; if (set_clock & 0x8) set_base_freq = 48000; else set_base_freq = 30000; uint32_t set_freq; uint32_t scan_freq; set_freq = set_base_freq >> (set_clock & 0x7); scan_freq = scan_base_freq >> (scan_clock & 0x7); if (scan_freq < set_freq) { LOG_ERROR("User specifies higher jtag clock than TCK_SCAN clock"); return ERROR_FAIL; } } if (aice_write_ctrl(AICE_WRITE_CTRL_TCK_CONTROL, set_clock) != ERROR_OK) return ERROR_FAIL; uint32_t check_speed; if (aice_read_ctrl(AICE_READ_CTRL_GET_ICE_STATE, &check_speed) != ERROR_OK) return ERROR_FAIL; if (((int)check_speed & 0x0F) != set_clock) { LOG_ERROR("Set jtag clock failed"); return ERROR_FAIL; } return ERROR_OK; } static int aice_edm_init(uint32_t coreid) { aice_write_edmsr(coreid, NDS_EDM_SR_DIMBR, 0xFFFF0000); aice_write_misc(coreid, NDS_EDM_MISC_DIMIR, 0); /* unconditionally try to turn on V3_EDM_MODE */ uint32_t edm_ctl_value; aice_read_edmsr(coreid, NDS_EDM_SR_EDM_CTL, &edm_ctl_value); aice_write_edmsr(coreid, NDS_EDM_SR_EDM_CTL, edm_ctl_value | 0x00000040); /* clear DBGER */ aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_DPED | NDS_DBGER_CRST | NDS_DBGER_AT_MAX); /* get EDM version */ uint32_t value_edmcfg; aice_read_edmsr(coreid, NDS_EDM_SR_EDM_CFG, &value_edmcfg); core_info[coreid].edm_version = (value_edmcfg >> 16) & 0xFFFF; return ERROR_OK; } static bool is_v2_edm(uint32_t coreid) { if ((core_info[coreid].edm_version & 0x1000) == 0) return true; else return false; } static int aice_init_edm_registers(uint32_t coreid, bool clear_dex_use_psw) { /* enable DEH_SEL & MAX_STOP & V3_EDM_MODE & DBGI_MASK */ uint32_t host_edm_ctl = core_info[coreid].edm_ctl_backup | 0xA000004F; if (clear_dex_use_psw) /* After entering debug mode, OpenOCD may set * DEX_USE_PSW accidentally through backup value * of target EDM_CTL. * So, clear DEX_USE_PSW by force. */ host_edm_ctl &= ~(0x40000000); LOG_DEBUG("aice_init_edm_registers - EDM_CTL: 0x%08" PRIx32, host_edm_ctl); int result = aice_write_edmsr(coreid, NDS_EDM_SR_EDM_CTL, host_edm_ctl); return result; } /** * EDM_CTL will be modified by OpenOCD as debugging. OpenOCD has the * responsibility to keep EDM_CTL untouched after debugging. * * There are two scenarios to consider: * 1. single step/running as debugging (running under debug session) * 2. detached from gdb (exit debug session) * * So, we need to bakcup EDM_CTL before halted and restore it after * running. The difference of these two scenarios is EDM_CTL.DEH_SEL * is on for scenario 1, and off for scenario 2. */ static int aice_backup_edm_registers(uint32_t coreid) { int result = aice_read_edmsr(coreid, NDS_EDM_SR_EDM_CTL, &core_info[coreid].edm_ctl_backup); /* To call aice_backup_edm_registers() after DEX on, DEX_USE_PSW * may be not correct. (For example, hit breakpoint, then backup * EDM_CTL. EDM_CTL.DEX_USE_PSW will be cleared.) Because debug * interrupt will clear DEX_USE_PSW, DEX_USE_PSW is always off after * DEX is on. It only backups correct value before OpenOCD issues DBGI. * (Backup EDM_CTL, then issue DBGI actively (refer aice_usb_halt())) */ if (core_info[coreid].edm_ctl_backup & 0x40000000) core_info[coreid].dex_use_psw_on = true; else core_info[coreid].dex_use_psw_on = false; LOG_DEBUG("aice_backup_edm_registers - EDM_CTL: 0x%08" PRIx32 ", DEX_USE_PSW: %s", core_info[coreid].edm_ctl_backup, core_info[coreid].dex_use_psw_on ? "on" : "off"); return result; } static int aice_restore_edm_registers(uint32_t coreid) { LOG_DEBUG("aice_restore_edm_registers -"); /* set DEH_SEL, because target still under EDM control */ int result = aice_write_edmsr(coreid, NDS_EDM_SR_EDM_CTL, core_info[coreid].edm_ctl_backup | 0x80000000); return result; } static int aice_backup_tmp_registers(uint32_t coreid) { LOG_DEBUG("backup_tmp_registers -"); /* backup target DTR first(if the target DTR is valid) */ uint32_t value_edmsw = 0; aice_read_edmsr(coreid, NDS_EDM_SR_EDMSW, &value_edmsw); core_info[coreid].edmsw_backup = value_edmsw; if (value_edmsw & 0x1) { /* EDMSW.WDV == 1 */ aice_read_dtr(coreid, &core_info[coreid].target_dtr_backup); core_info[coreid].target_dtr_valid = true; LOG_DEBUG("Backup target DTR: 0x%08" PRIx32, core_info[coreid].target_dtr_backup); } else { core_info[coreid].target_dtr_valid = false; } /* Target DTR has been backup, then backup $R0 and $R1 */ aice_read_reg(coreid, R0, &core_info[coreid].r0_backup); aice_read_reg(coreid, R1, &core_info[coreid].r1_backup); /* backup host DTR(if the host DTR is valid) */ if (value_edmsw & 0x2) { /* EDMSW.RDV == 1*/ /* read out host DTR and write into target DTR, then use aice_read_edmsr to * read out */ uint32_t instructions[4] = { MFSR_DTR(R0), /* R0 has already been backup */ DSB, MTSR_DTR(R0), BEQ_MINUS_12 }; aice_execute_dim(coreid, instructions, 4); aice_read_dtr(coreid, &core_info[coreid].host_dtr_backup); core_info[coreid].host_dtr_valid = true; LOG_DEBUG("Backup host DTR: 0x%08" PRIx32, core_info[coreid].host_dtr_backup); } else { core_info[coreid].host_dtr_valid = false; } LOG_DEBUG("r0: 0x%08" PRIx32 ", r1: 0x%08" PRIx32, core_info[coreid].r0_backup, core_info[coreid].r1_backup); return ERROR_OK; } static int aice_restore_tmp_registers(uint32_t coreid) { LOG_DEBUG("restore_tmp_registers - r0: 0x%08" PRIx32 ", r1: 0x%08" PRIx32, core_info[coreid].r0_backup, core_info[coreid].r1_backup); if (core_info[coreid].target_dtr_valid) { uint32_t instructions[4] = { SETHI(R0, core_info[coreid].target_dtr_backup >> 12), ORI(R0, R0, core_info[coreid].target_dtr_backup & 0x00000FFF), NOP, BEQ_MINUS_12 }; aice_execute_dim(coreid, instructions, 4); instructions[0] = MTSR_DTR(R0); instructions[1] = DSB; instructions[2] = NOP; instructions[3] = BEQ_MINUS_12; aice_execute_dim(coreid, instructions, 4); LOG_DEBUG("Restore target DTR: 0x%08" PRIx32, core_info[coreid].target_dtr_backup); } aice_write_reg(coreid, R0, core_info[coreid].r0_backup); aice_write_reg(coreid, R1, core_info[coreid].r1_backup); if (core_info[coreid].host_dtr_valid) { aice_write_dtr(coreid, core_info[coreid].host_dtr_backup); LOG_DEBUG("Restore host DTR: 0x%08" PRIx32, core_info[coreid].host_dtr_backup); } return ERROR_OK; } static int aice_open_device(struct aice_port_param_s *param) { if (ERROR_OK != aice_usb_open(param)) return ERROR_FAIL; if (ERROR_FAIL == aice_get_version_info()) { LOG_ERROR("Cannot get AICE version!"); return ERROR_FAIL; } LOG_INFO("AICE initialization started"); /* attempt to reset Andes EDM */ if (ERROR_FAIL == aice_reset_box()) { LOG_ERROR("Cannot initial AICE box!"); return ERROR_FAIL; } return ERROR_OK; } static int aice_usb_set_jtag_clock(uint32_t a_clock) { jtag_clock = a_clock; if (ERROR_OK != aice_usb_set_clock(a_clock)) { LOG_ERROR("Cannot set AICE JTAG clock!"); return ERROR_FAIL; } return ERROR_OK; } static int aice_usb_close(void) { jtag_libusb_close(aice_handler.usb_handle); free(custom_srst_script); free(custom_trst_script); free(custom_restart_script); return ERROR_OK; } static int aice_core_init(uint32_t coreid) { core_info[coreid].access_channel = NDS_MEMORY_ACC_CPU; core_info[coreid].memory_select = NDS_MEMORY_SELECT_AUTO; core_info[coreid].core_state = AICE_TARGET_UNKNOWN; return ERROR_OK; } static int aice_usb_idcode(uint32_t *idcode, uint8_t *num_of_idcode) { int retval; retval = aice_scan_chain(idcode, num_of_idcode); if (ERROR_OK == retval) { for (int i = 0; i < *num_of_idcode; i++) { aice_core_init(i); aice_edm_init(i); } total_num_of_core = *num_of_idcode; } return retval; } static int aice_usb_halt(uint32_t coreid) { if (core_info[coreid].core_state == AICE_TARGET_HALTED) { LOG_DEBUG("aice_usb_halt check halted"); return ERROR_OK; } LOG_DEBUG("aice_usb_halt"); /** backup EDM registers */ aice_backup_edm_registers(coreid); /** init EDM for host debugging */ /** no need to clear dex_use_psw, because dbgi will clear it */ aice_init_edm_registers(coreid, false); /** Clear EDM_CTL.DBGIM & EDM_CTL.DBGACKM */ uint32_t edm_ctl_value = 0; aice_read_edmsr(coreid, NDS_EDM_SR_EDM_CTL, &edm_ctl_value); if (edm_ctl_value & 0x3) aice_write_edmsr(coreid, NDS_EDM_SR_EDM_CTL, edm_ctl_value & ~(0x3)); uint32_t dbger = 0; uint32_t acc_ctl_value = 0; core_info[coreid].debug_under_dex_on = false; aice_read_misc(coreid, NDS_EDM_MISC_DBGER, &dbger); if (dbger & NDS_DBGER_AT_MAX) LOG_ERROR("<-- TARGET ERROR! Reaching the max interrupt stack level. -->"); if (dbger & NDS_DBGER_DEX) { if (is_v2_edm(coreid) == false) { /** debug 'debug mode'. use force_debug to issue dbgi */ aice_read_misc(coreid, NDS_EDM_MISC_ACC_CTL, &acc_ctl_value); acc_ctl_value |= 0x8; aice_write_misc(coreid, NDS_EDM_MISC_ACC_CTL, acc_ctl_value); core_info[coreid].debug_under_dex_on = true; aice_write_misc(coreid, NDS_EDM_MISC_EDM_CMDR, 0); /* If CPU stalled due to AT_MAX, clear AT_MAX status. */ if (dbger & NDS_DBGER_AT_MAX) aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_AT_MAX); } } else { /** Issue DBGI normally */ aice_write_misc(coreid, NDS_EDM_MISC_EDM_CMDR, 0); /* If CPU stalled due to AT_MAX, clear AT_MAX status. */ if (dbger & NDS_DBGER_AT_MAX) aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_AT_MAX); } if (aice_check_dbger(coreid, NDS_DBGER_DEX) != ERROR_OK) { LOG_ERROR("<-- TARGET ERROR! Unable to stop the debug target through DBGI. -->"); return ERROR_FAIL; } if (core_info[coreid].debug_under_dex_on) { if (core_info[coreid].dex_use_psw_on == false) { /* under debug 'debug mode', force $psw to 'debug mode' bahavior */ /* !!!NOTICE!!! this is workaround for debug 'debug mode'. * it is only for debugging 'debug exception handler' purpose. * after openocd detaches from target, target behavior is * undefined. */ uint32_t ir0_value = 0; uint32_t debug_mode_ir0_value; aice_read_reg(coreid, IR0, &ir0_value); debug_mode_ir0_value = ir0_value | 0x408; /* turn on DEX, set POM = 1 */ debug_mode_ir0_value &= ~(0x000000C1); /* turn off DT/IT/GIE */ aice_write_reg(coreid, IR0, debug_mode_ir0_value); } } /** set EDM_CTL.DBGIM & EDM_CTL.DBGACKM after halt */ if (edm_ctl_value & 0x3) aice_write_edmsr(coreid, NDS_EDM_SR_EDM_CTL, edm_ctl_value); /* backup r0 & r1 */ aice_backup_tmp_registers(coreid); core_info[coreid].core_state = AICE_TARGET_HALTED; return ERROR_OK; } static int aice_usb_state(uint32_t coreid, enum aice_target_state_s *state) { uint32_t dbger_value; uint32_t ice_state; int result = aice_read_misc(coreid, NDS_EDM_MISC_DBGER, &dbger_value); if (ERROR_AICE_TIMEOUT == result) { if (aice_read_ctrl(AICE_READ_CTRL_GET_ICE_STATE, &ice_state) != ERROR_OK) { LOG_ERROR("<-- AICE ERROR! AICE is unplugged. -->"); return ERROR_FAIL; } if ((ice_state & 0x20) == 0) { LOG_ERROR("<-- TARGET ERROR! Target is disconnected with AICE. -->"); return ERROR_FAIL; } else { return ERROR_FAIL; } } else if (ERROR_AICE_DISCONNECT == result) { LOG_ERROR("<-- AICE ERROR! AICE is unplugged. -->"); return ERROR_FAIL; } if ((dbger_value & NDS_DBGER_ILL_SEC_ACC) == NDS_DBGER_ILL_SEC_ACC) { LOG_ERROR("<-- TARGET ERROR! Insufficient security privilege. -->"); /* Clear ILL_SEC_ACC */ aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_ILL_SEC_ACC); *state = AICE_TARGET_RUNNING; core_info[coreid].core_state = AICE_TARGET_RUNNING; } else if ((dbger_value & NDS_DBGER_AT_MAX) == NDS_DBGER_AT_MAX) { /* Issue DBGI to exit cpu stall */ aice_usb_halt(coreid); /* Read OIPC to find out the trigger point */ uint32_t ir11_value; aice_read_reg(coreid, IR11, &ir11_value); LOG_ERROR("<-- TARGET ERROR! Reaching the max interrupt stack level; " "CPU is stalled at 0x%08" PRIx32 " for debugging. -->", ir11_value); *state = AICE_TARGET_HALTED; } else if ((dbger_value & NDS_DBGER_CRST) == NDS_DBGER_CRST) { LOG_DEBUG("DBGER.CRST is on."); *state = AICE_TARGET_RESET; core_info[coreid].core_state = AICE_TARGET_RUNNING; /* Clear CRST */ aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_CRST); } else if ((dbger_value & NDS_DBGER_DEX) == NDS_DBGER_DEX) { if (AICE_TARGET_RUNNING == core_info[coreid].core_state) { /* enter debug mode, init EDM registers */ /* backup EDM registers */ aice_backup_edm_registers(coreid); /* init EDM for host debugging */ aice_init_edm_registers(coreid, true); aice_backup_tmp_registers(coreid); core_info[coreid].core_state = AICE_TARGET_HALTED; } else if (AICE_TARGET_UNKNOWN == core_info[coreid].core_state) { /* debug 'debug mode', use force debug to halt core */ aice_usb_halt(coreid); } *state = AICE_TARGET_HALTED; } else { *state = AICE_TARGET_RUNNING; core_info[coreid].core_state = AICE_TARGET_RUNNING; } return ERROR_OK; } static int aice_usb_reset(void) { if (aice_reset_box() != ERROR_OK) return ERROR_FAIL; /* issue TRST */ if (custom_trst_script == NULL) { if (aice_write_ctrl(AICE_WRITE_CTRL_JTAG_PIN_CONTROL, AICE_JTAG_PIN_CONTROL_TRST) != ERROR_OK) return ERROR_FAIL; } else { /* custom trst operations */ if (aice_execute_custom_script(custom_trst_script) != ERROR_OK) return ERROR_FAIL; } if (aice_usb_set_clock(jtag_clock) != ERROR_OK) return ERROR_FAIL; return ERROR_OK; } static int aice_issue_srst(uint32_t coreid) { LOG_DEBUG("aice_issue_srst"); /* After issuing srst, target will be running. So we need to restore EDM_CTL. */ aice_restore_edm_registers(coreid); if (custom_srst_script == NULL) { if (aice_write_ctrl(AICE_WRITE_CTRL_JTAG_PIN_CONTROL, AICE_JTAG_PIN_CONTROL_SRST) != ERROR_OK) return ERROR_FAIL; } else { /* custom srst operations */ if (aice_execute_custom_script(custom_srst_script) != ERROR_OK) return ERROR_FAIL; } /* wait CRST infinitely */ uint32_t dbger_value; int i = 0; while (1) { if (aice_read_misc(coreid, NDS_EDM_MISC_DBGER, &dbger_value) != ERROR_OK) return ERROR_FAIL; if (dbger_value & NDS_DBGER_CRST) break; if ((i % 30) == 0) keep_alive(); i++; } core_info[coreid].host_dtr_valid = false; core_info[coreid].target_dtr_valid = false; core_info[coreid].core_state = AICE_TARGET_RUNNING; return ERROR_OK; } static int aice_issue_reset_hold(uint32_t coreid) { LOG_DEBUG("aice_issue_reset_hold"); /* set no_dbgi_pin to 0 */ uint32_t pin_status; aice_read_ctrl(AICE_READ_CTRL_GET_JTAG_PIN_STATUS, &pin_status); if (pin_status & 0x4) aice_write_ctrl(AICE_WRITE_CTRL_JTAG_PIN_STATUS, pin_status & (~0x4)); /* issue restart */ if (custom_restart_script == NULL) { if (aice_write_ctrl(AICE_WRITE_CTRL_JTAG_PIN_CONTROL, AICE_JTAG_PIN_CONTROL_RESTART) != ERROR_OK) return ERROR_FAIL; } else { /* custom restart operations */ if (aice_execute_custom_script(custom_restart_script) != ERROR_OK) return ERROR_FAIL; } if (aice_check_dbger(coreid, NDS_DBGER_CRST | NDS_DBGER_DEX) == ERROR_OK) { aice_backup_tmp_registers(coreid); core_info[coreid].core_state = AICE_TARGET_HALTED; return ERROR_OK; } else { /* set no_dbgi_pin to 1 */ aice_write_ctrl(AICE_WRITE_CTRL_JTAG_PIN_STATUS, pin_status | 0x4); /* issue restart again */ if (custom_restart_script == NULL) { if (aice_write_ctrl(AICE_WRITE_CTRL_JTAG_PIN_CONTROL, AICE_JTAG_PIN_CONTROL_RESTART) != ERROR_OK) return ERROR_FAIL; } else { /* custom restart operations */ if (aice_execute_custom_script(custom_restart_script) != ERROR_OK) return ERROR_FAIL; } if (aice_check_dbger(coreid, NDS_DBGER_CRST | NDS_DBGER_DEX) == ERROR_OK) { aice_backup_tmp_registers(coreid); core_info[coreid].core_state = AICE_TARGET_HALTED; return ERROR_OK; } /* do software reset-and-hold */ aice_issue_srst(coreid); aice_usb_halt(coreid); uint32_t value_ir3; aice_read_reg(coreid, IR3, &value_ir3); aice_write_reg(coreid, PC, value_ir3 & 0xFFFF0000); } return ERROR_FAIL; } static int aice_issue_reset_hold_multi(void) { uint32_t write_ctrl_value = 0; /* set SRST */ write_ctrl_value = AICE_CUSTOM_DELAY_SET_SRST; write_ctrl_value |= (0x200 << 16); if (aice_write_ctrl(AICE_WRITE_CTRL_CUSTOM_DELAY, write_ctrl_value) != ERROR_OK) return ERROR_FAIL; for (uint8_t i = 0 ; i < total_num_of_core ; i++) aice_write_misc(i, NDS_EDM_MISC_EDM_CMDR, 0); /* clear SRST */ write_ctrl_value = AICE_CUSTOM_DELAY_CLEAN_SRST; write_ctrl_value |= (0x200 << 16); if (aice_write_ctrl(AICE_WRITE_CTRL_CUSTOM_DELAY, write_ctrl_value) != ERROR_OK) return ERROR_FAIL; for (uint8_t i = 0; i < total_num_of_core; i++) aice_edm_init(i); return ERROR_FAIL; } static int aice_usb_assert_srst(uint32_t coreid, enum aice_srst_type_s srst) { if ((AICE_SRST != srst) && (AICE_RESET_HOLD != srst)) return ERROR_FAIL; /* clear DBGER */ if (aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_CLEAR_ALL) != ERROR_OK) return ERROR_FAIL; int result = ERROR_OK; if (AICE_SRST == srst) result = aice_issue_srst(coreid); else { if (1 == total_num_of_core) result = aice_issue_reset_hold(coreid); else result = aice_issue_reset_hold_multi(); } /* Clear DBGER.CRST after reset to avoid 'core-reset checking' errors. * assert_srst is user-intentional reset behavior, so we could * clear DBGER.CRST safely. */ if (aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_CRST) != ERROR_OK) return ERROR_FAIL; return result; } static int aice_usb_run(uint32_t coreid) { LOG_DEBUG("aice_usb_run"); uint32_t dbger_value; if (aice_read_misc(coreid, NDS_EDM_MISC_DBGER, &dbger_value) != ERROR_OK) return ERROR_FAIL; if ((dbger_value & NDS_DBGER_DEX) != NDS_DBGER_DEX) { LOG_WARNING("<-- TARGET WARNING! The debug target exited " "the debug mode unexpectedly. -->"); return ERROR_FAIL; } /* restore r0 & r1 before free run */ aice_restore_tmp_registers(coreid); core_info[coreid].core_state = AICE_TARGET_RUNNING; /* clear DBGER */ aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_CLEAR_ALL); /** restore EDM registers */ /** OpenOCD should restore EDM_CTL **before** to exit debug state. * Otherwise, following instruction will read wrong EDM_CTL value. * * pc -> mfsr $p0, EDM_CTL (single step) * slli $p0, $p0, 1 * slri $p0, $p0, 31 */ aice_restore_edm_registers(coreid); /** execute instructions in DIM */ uint32_t instructions[4] = { NOP, NOP, NOP, IRET }; int result = aice_execute_dim(coreid, instructions, 4); return result; } static int aice_usb_step(uint32_t coreid) { LOG_DEBUG("aice_usb_step"); uint32_t ir0_value; uint32_t ir0_reg_num; if (is_v2_edm(coreid) == true) /* V2 EDM will push interrupt stack as debug exception */ ir0_reg_num = IR1; else ir0_reg_num = IR0; /** enable HSS */ aice_read_reg(coreid, ir0_reg_num, &ir0_value); if ((ir0_value & 0x800) == 0) { /** set PSW.HSS */ ir0_value |= (0x01 << 11); aice_write_reg(coreid, ir0_reg_num, ir0_value); } if (ERROR_FAIL == aice_usb_run(coreid)) return ERROR_FAIL; int i = 0; enum aice_target_state_s state; while (1) { /* read DBGER */ if (aice_usb_state(coreid, &state) != ERROR_OK) return ERROR_FAIL; if (AICE_TARGET_HALTED == state) break; int64_t then = 0; if (i == 30) then = timeval_ms(); if (i >= 30) { if ((timeval_ms() - then) > 1000) LOG_WARNING("Timeout (1000ms) waiting for halt to complete"); return ERROR_FAIL; } i++; } /** disable HSS */ aice_read_reg(coreid, ir0_reg_num, &ir0_value); ir0_value &= ~(0x01 << 11); aice_write_reg(coreid, ir0_reg_num, ir0_value); return ERROR_OK; } static int aice_usb_read_mem_b_bus(uint32_t coreid, uint32_t address, uint32_t *data) { return aice_read_mem_b(coreid, address, data); } static int aice_usb_read_mem_h_bus(uint32_t coreid, uint32_t address, uint32_t *data) { return aice_read_mem_h(coreid, address, data); } static int aice_usb_read_mem_w_bus(uint32_t coreid, uint32_t address, uint32_t *data) { return aice_read_mem(coreid, address, data); } static int aice_usb_read_mem_b_dim(uint32_t coreid, uint32_t address, uint32_t *data) { uint32_t value; uint32_t instructions[4] = { LBI_BI(R1, R0), MTSR_DTR(R1), DSB, BEQ_MINUS_12 }; aice_execute_dim(coreid, instructions, 4); aice_read_dtr(coreid, &value); *data = value & 0xFF; return ERROR_OK; } static int aice_usb_read_mem_h_dim(uint32_t coreid, uint32_t address, uint32_t *data) { uint32_t value; uint32_t instructions[4] = { LHI_BI(R1, R0), MTSR_DTR(R1), DSB, BEQ_MINUS_12 }; aice_execute_dim(coreid, instructions, 4); aice_read_dtr(coreid, &value); *data = value & 0xFFFF; return ERROR_OK; } static int aice_usb_read_mem_w_dim(uint32_t coreid, uint32_t address, uint32_t *data) { uint32_t instructions[4] = { LWI_BI(R1, R0), MTSR_DTR(R1), DSB, BEQ_MINUS_12 }; aice_execute_dim(coreid, instructions, 4); aice_read_dtr(coreid, data); return ERROR_OK; } static int aice_usb_set_address_dim(uint32_t coreid, uint32_t address) { uint32_t instructions[4] = { SETHI(R0, address >> 12), ORI(R0, R0, address & 0x00000FFF), NOP, BEQ_MINUS_12 }; return aice_execute_dim(coreid, instructions, 4); } static int aice_usb_read_memory_unit(uint32_t coreid, uint32_t addr, uint32_t size, uint32_t count, uint8_t *buffer) { LOG_DEBUG("aice_usb_read_memory_unit, addr: 0x%08" PRIx32 ", size: %" PRIu32 ", count: %" PRIu32 "", addr, size, count); if (NDS_MEMORY_ACC_CPU == core_info[coreid].access_channel) aice_usb_set_address_dim(coreid, addr); uint32_t value; size_t i; read_mem_func_t read_mem_func; switch (size) { case 1: if (NDS_MEMORY_ACC_BUS == core_info[coreid].access_channel) read_mem_func = aice_usb_read_mem_b_bus; else read_mem_func = aice_usb_read_mem_b_dim; for (i = 0; i < count; i++) { read_mem_func(coreid, addr, &value); *buffer++ = (uint8_t)value; addr++; } break; case 2: if (NDS_MEMORY_ACC_BUS == core_info[coreid].access_channel) read_mem_func = aice_usb_read_mem_h_bus; else read_mem_func = aice_usb_read_mem_h_dim; for (i = 0; i < count; i++) { read_mem_func(coreid, addr, &value); uint16_t svalue = value; memcpy(buffer, &svalue, sizeof(uint16_t)); buffer += 2; addr += 2; } break; case 4: if (NDS_MEMORY_ACC_BUS == core_info[coreid].access_channel) read_mem_func = aice_usb_read_mem_w_bus; else read_mem_func = aice_usb_read_mem_w_dim; for (i = 0; i < count; i++) { read_mem_func(coreid, addr, &value); memcpy(buffer, &value, sizeof(uint32_t)); buffer += 4; addr += 4; } break; } return ERROR_OK; } static int aice_usb_write_mem_b_bus(uint32_t coreid, uint32_t address, uint32_t data) { return aice_write_mem_b(coreid, address, data); } static int aice_usb_write_mem_h_bus(uint32_t coreid, uint32_t address, uint32_t data) { return aice_write_mem_h(coreid, address, data); } static int aice_usb_write_mem_w_bus(uint32_t coreid, uint32_t address, uint32_t data) { return aice_write_mem(coreid, address, data); } static int aice_usb_write_mem_b_dim(uint32_t coreid, uint32_t address, uint32_t data) { uint32_t instructions[4] = { MFSR_DTR(R1), SBI_BI(R1, R0), DSB, BEQ_MINUS_12 }; aice_write_dtr(coreid, data & 0xFF); aice_execute_dim(coreid, instructions, 4); return ERROR_OK; } static int aice_usb_write_mem_h_dim(uint32_t coreid, uint32_t address, uint32_t data) { uint32_t instructions[4] = { MFSR_DTR(R1), SHI_BI(R1, R0), DSB, BEQ_MINUS_12 }; aice_write_dtr(coreid, data & 0xFFFF); aice_execute_dim(coreid, instructions, 4); return ERROR_OK; } static int aice_usb_write_mem_w_dim(uint32_t coreid, uint32_t address, uint32_t data) { uint32_t instructions[4] = { MFSR_DTR(R1), SWI_BI(R1, R0), DSB, BEQ_MINUS_12 }; aice_write_dtr(coreid, data); aice_execute_dim(coreid, instructions, 4); return ERROR_OK; } static int aice_usb_write_memory_unit(uint32_t coreid, uint32_t addr, uint32_t size, uint32_t count, const uint8_t *buffer) { LOG_DEBUG("aice_usb_write_memory_unit, addr: 0x%08" PRIx32 ", size: %" PRIu32 ", count: %" PRIu32 "", addr, size, count); if (NDS_MEMORY_ACC_CPU == core_info[coreid].access_channel) aice_usb_set_address_dim(coreid, addr); size_t i; write_mem_func_t write_mem_func; switch (size) { case 1: if (NDS_MEMORY_ACC_BUS == core_info[coreid].access_channel) write_mem_func = aice_usb_write_mem_b_bus; else write_mem_func = aice_usb_write_mem_b_dim; for (i = 0; i < count; i++) { write_mem_func(coreid, addr, *buffer); buffer++; addr++; } break; case 2: if (NDS_MEMORY_ACC_BUS == core_info[coreid].access_channel) write_mem_func = aice_usb_write_mem_h_bus; else write_mem_func = aice_usb_write_mem_h_dim; for (i = 0; i < count; i++) { uint16_t value; memcpy(&value, buffer, sizeof(uint16_t)); write_mem_func(coreid, addr, value); buffer += 2; addr += 2; } break; case 4: if (NDS_MEMORY_ACC_BUS == core_info[coreid].access_channel) write_mem_func = aice_usb_write_mem_w_bus; else write_mem_func = aice_usb_write_mem_w_dim; for (i = 0; i < count; i++) { uint32_t value; memcpy(&value, buffer, sizeof(uint32_t)); write_mem_func(coreid, addr, value); buffer += 4; addr += 4; } break; } return ERROR_OK; } static int aice_bulk_read_mem(uint32_t coreid, uint32_t addr, uint32_t count, uint8_t *buffer) { uint32_t packet_size; while (count > 0) { packet_size = (count >= 0x100) ? 0x100 : count; /** set address */ addr &= 0xFFFFFFFC; if (aice_write_misc(coreid, NDS_EDM_MISC_SBAR, addr) != ERROR_OK) return ERROR_FAIL; if (aice_fastread_mem(coreid, buffer, packet_size) != ERROR_OK) return ERROR_FAIL; buffer += (packet_size * 4); addr += (packet_size * 4); count -= packet_size; } return ERROR_OK; } static int aice_bulk_write_mem(uint32_t coreid, uint32_t addr, uint32_t count, const uint8_t *buffer) { uint32_t packet_size; while (count > 0) { packet_size = (count >= 0x100) ? 0x100 : count; /** set address */ addr &= 0xFFFFFFFC; if (aice_write_misc(coreid, NDS_EDM_MISC_SBAR, addr | 1) != ERROR_OK) return ERROR_FAIL; if (aice_fastwrite_mem(coreid, buffer, packet_size) != ERROR_OK) return ERROR_FAIL; buffer += (packet_size * 4); addr += (packet_size * 4); count -= packet_size; } return ERROR_OK; } static int aice_usb_bulk_read_mem(uint32_t coreid, uint32_t addr, uint32_t length, uint8_t *buffer) { LOG_DEBUG("aice_usb_bulk_read_mem, addr: 0x%08" PRIx32 ", length: 0x%08" PRIx32, addr, length); int retval; if (NDS_MEMORY_ACC_CPU == core_info[coreid].access_channel) aice_usb_set_address_dim(coreid, addr); if (NDS_MEMORY_ACC_CPU == core_info[coreid].access_channel) retval = aice_usb_read_memory_unit(coreid, addr, 4, length / 4, buffer); else retval = aice_bulk_read_mem(coreid, addr, length / 4, buffer); return retval; } static int aice_usb_bulk_write_mem(uint32_t coreid, uint32_t addr, uint32_t length, const uint8_t *buffer) { LOG_DEBUG("aice_usb_bulk_write_mem, addr: 0x%08" PRIx32 ", length: 0x%08" PRIx32, addr, length); int retval; if (NDS_MEMORY_ACC_CPU == core_info[coreid].access_channel) aice_usb_set_address_dim(coreid, addr); if (NDS_MEMORY_ACC_CPU == core_info[coreid].access_channel) retval = aice_usb_write_memory_unit(coreid, addr, 4, length / 4, buffer); else retval = aice_bulk_write_mem(coreid, addr, length / 4, buffer); return retval; } static int aice_usb_read_debug_reg(uint32_t coreid, uint32_t addr, uint32_t *val) { if (AICE_TARGET_HALTED == core_info[coreid].core_state) { if (NDS_EDM_SR_EDMSW == addr) { *val = core_info[coreid].edmsw_backup; } else if (NDS_EDM_SR_EDM_DTR == addr) { if (core_info[coreid].target_dtr_valid) { /* if EDM_DTR has read out, clear it. */ *val = core_info[coreid].target_dtr_backup; core_info[coreid].edmsw_backup &= (~0x1); core_info[coreid].target_dtr_valid = false; } else { *val = 0; } } } return aice_read_edmsr(coreid, addr, val); } static int aice_usb_write_debug_reg(uint32_t coreid, uint32_t addr, const uint32_t val) { if (AICE_TARGET_HALTED == core_info[coreid].core_state) { if (NDS_EDM_SR_EDM_DTR == addr) { core_info[coreid].host_dtr_backup = val; core_info[coreid].edmsw_backup |= 0x2; core_info[coreid].host_dtr_valid = true; } } return aice_write_edmsr(coreid, addr, val); } static int aice_usb_memory_access(uint32_t coreid, enum nds_memory_access channel) { LOG_DEBUG("aice_usb_memory_access, access channel: %u", channel); core_info[coreid].access_channel = channel; return ERROR_OK; } static int aice_usb_memory_mode(uint32_t coreid, enum nds_memory_select mem_select) { if (core_info[coreid].memory_select == mem_select) return ERROR_OK; LOG_DEBUG("aice_usb_memory_mode, memory select: %u", mem_select); core_info[coreid].memory_select = mem_select; if (NDS_MEMORY_SELECT_AUTO != core_info[coreid].memory_select) aice_write_misc(coreid, NDS_EDM_MISC_ACC_CTL, core_info[coreid].memory_select - 1); else aice_write_misc(coreid, NDS_EDM_MISC_ACC_CTL, NDS_MEMORY_SELECT_MEM - 1); return ERROR_OK; } static int aice_usb_read_tlb(uint32_t coreid, target_addr_t virtual_address, target_addr_t *physical_address) { LOG_DEBUG("aice_usb_read_tlb, virtual address: 0x%08" TARGET_PRIxADDR, virtual_address); uint32_t instructions[4]; uint32_t probe_result; uint32_t value_mr3; uint32_t value_mr4; uint32_t access_page_size; uint32_t virtual_offset; uint32_t physical_page_number; aice_write_dtr(coreid, virtual_address); /* probe TLB first */ instructions[0] = MFSR_DTR(R0); instructions[1] = TLBOP_TARGET_PROBE(R1, R0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; aice_execute_dim(coreid, instructions, 4); aice_read_reg(coreid, R1, &probe_result); if (probe_result & 0x80000000) return ERROR_FAIL; /* read TLB entry */ aice_write_dtr(coreid, probe_result & 0x7FF); /* probe TLB first */ instructions[0] = MFSR_DTR(R0); instructions[1] = TLBOP_TARGET_READ(R0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; aice_execute_dim(coreid, instructions, 4); /* TODO: it should backup mr3, mr4 */ aice_read_reg(coreid, MR3, &value_mr3); aice_read_reg(coreid, MR4, &value_mr4); access_page_size = value_mr4 & 0xF; if (0 == access_page_size) { /* 4K page */ virtual_offset = virtual_address & 0x00000FFF; physical_page_number = value_mr3 & 0xFFFFF000; } else if (1 == access_page_size) { /* 8K page */ virtual_offset = virtual_address & 0x00001FFF; physical_page_number = value_mr3 & 0xFFFFE000; } else if (5 == access_page_size) { /* 1M page */ virtual_offset = virtual_address & 0x000FFFFF; physical_page_number = value_mr3 & 0xFFF00000; } else { return ERROR_FAIL; } *physical_address = physical_page_number | virtual_offset; return ERROR_OK; } static int aice_usb_init_cache(uint32_t coreid) { LOG_DEBUG("aice_usb_init_cache"); uint32_t value_cr1; uint32_t value_cr2; aice_read_reg(coreid, CR1, &value_cr1); aice_read_reg(coreid, CR2, &value_cr2); struct cache_info *icache = &core_info[coreid].icache; icache->set = value_cr1 & 0x7; icache->log2_set = icache->set + 6; icache->set = 64 << icache->set; icache->way = ((value_cr1 >> 3) & 0x7) + 1; icache->line_size = (value_cr1 >> 6) & 0x7; if (icache->line_size != 0) { icache->log2_line_size = icache->line_size + 2; icache->line_size = 8 << (icache->line_size - 1); } else { icache->log2_line_size = 0; } LOG_DEBUG("\ticache set: %" PRIu32 ", way: %" PRIu32 ", line size: %" PRIu32 ", " "log2(set): %" PRIu32 ", log2(line_size): %" PRIu32 "", icache->set, icache->way, icache->line_size, icache->log2_set, icache->log2_line_size); struct cache_info *dcache = &core_info[coreid].dcache; dcache->set = value_cr2 & 0x7; dcache->log2_set = dcache->set + 6; dcache->set = 64 << dcache->set; dcache->way = ((value_cr2 >> 3) & 0x7) + 1; dcache->line_size = (value_cr2 >> 6) & 0x7; if (dcache->line_size != 0) { dcache->log2_line_size = dcache->line_size + 2; dcache->line_size = 8 << (dcache->line_size - 1); } else { dcache->log2_line_size = 0; } LOG_DEBUG("\tdcache set: %" PRIu32 ", way: %" PRIu32 ", line size: %" PRIu32 ", " "log2(set): %" PRIu32 ", log2(line_size): %" PRIu32 "", dcache->set, dcache->way, dcache->line_size, dcache->log2_set, dcache->log2_line_size); core_info[coreid].cache_init = true; return ERROR_OK; } static int aice_usb_dcache_inval_all(uint32_t coreid) { LOG_DEBUG("aice_usb_dcache_inval_all"); uint32_t set_index; uint32_t way_index; uint32_t cache_index; uint32_t instructions[4]; instructions[0] = MFSR_DTR(R0); instructions[1] = L1D_IX_INVAL(R0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; struct cache_info *dcache = &core_info[coreid].dcache; for (set_index = 0; set_index < dcache->set; set_index++) { for (way_index = 0; way_index < dcache->way; way_index++) { cache_index = (way_index << (dcache->log2_set + dcache->log2_line_size)) | (set_index << dcache->log2_line_size); if (ERROR_OK != aice_write_dtr(coreid, cache_index)) return ERROR_FAIL; if (ERROR_OK != aice_execute_dim(coreid, instructions, 4)) return ERROR_FAIL; } } return ERROR_OK; } static int aice_usb_dcache_va_inval(uint32_t coreid, uint32_t address) { LOG_DEBUG("aice_usb_dcache_va_inval"); uint32_t instructions[4]; aice_write_dtr(coreid, address); instructions[0] = MFSR_DTR(R0); instructions[1] = L1D_VA_INVAL(R0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; return aice_execute_dim(coreid, instructions, 4); } static int aice_usb_dcache_wb_all(uint32_t coreid) { LOG_DEBUG("aice_usb_dcache_wb_all"); uint32_t set_index; uint32_t way_index; uint32_t cache_index; uint32_t instructions[4]; instructions[0] = MFSR_DTR(R0); instructions[1] = L1D_IX_WB(R0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; struct cache_info *dcache = &core_info[coreid].dcache; for (set_index = 0; set_index < dcache->set; set_index++) { for (way_index = 0; way_index < dcache->way; way_index++) { cache_index = (way_index << (dcache->log2_set + dcache->log2_line_size)) | (set_index << dcache->log2_line_size); if (ERROR_OK != aice_write_dtr(coreid, cache_index)) return ERROR_FAIL; if (ERROR_OK != aice_execute_dim(coreid, instructions, 4)) return ERROR_FAIL; } } return ERROR_OK; } static int aice_usb_dcache_va_wb(uint32_t coreid, uint32_t address) { LOG_DEBUG("aice_usb_dcache_va_wb"); uint32_t instructions[4]; aice_write_dtr(coreid, address); instructions[0] = MFSR_DTR(R0); instructions[1] = L1D_VA_WB(R0); instructions[2] = DSB; instructions[3] = BEQ_MINUS_12; return aice_execute_dim(coreid, instructions, 4); } static int aice_usb_icache_inval_all(uint32_t coreid) { LOG_DEBUG("aice_usb_icache_inval_all"); uint32_t set_index; uint32_t way_index; uint32_t cache_index; uint32_t instructions[4]; instructions[0] = MFSR_DTR(R0); instructions[1] = L1I_IX_INVAL(R0); instructions[2] = ISB; instructions[3] = BEQ_MINUS_12; struct cache_info *icache = &core_info[coreid].icache; for (set_index = 0; set_index < icache->set; set_index++) { for (way_index = 0; way_index < icache->way; way_index++) { cache_index = (way_index << (icache->log2_set + icache->log2_line_size)) | (set_index << icache->log2_line_size); if (ERROR_OK != aice_write_dtr(coreid, cache_index)) return ERROR_FAIL; if (ERROR_OK != aice_execute_dim(coreid, instructions, 4)) return ERROR_FAIL; } } return ERROR_OK; } static int aice_usb_icache_va_inval(uint32_t coreid, uint32_t address) { LOG_DEBUG("aice_usb_icache_va_inval"); uint32_t instructions[4]; aice_write_dtr(coreid, address); instructions[0] = MFSR_DTR(R0); instructions[1] = L1I_VA_INVAL(R0); instructions[2] = ISB; instructions[3] = BEQ_MINUS_12; return aice_execute_dim(coreid, instructions, 4); } static int aice_usb_cache_ctl(uint32_t coreid, uint32_t subtype, uint32_t address) { LOG_DEBUG("aice_usb_cache_ctl"); int result; if (core_info[coreid].cache_init == false) aice_usb_init_cache(coreid); switch (subtype) { case AICE_CACHE_CTL_L1D_INVALALL: result = aice_usb_dcache_inval_all(coreid); break; case AICE_CACHE_CTL_L1D_VA_INVAL: result = aice_usb_dcache_va_inval(coreid, address); break; case AICE_CACHE_CTL_L1D_WBALL: result = aice_usb_dcache_wb_all(coreid); break; case AICE_CACHE_CTL_L1D_VA_WB: result = aice_usb_dcache_va_wb(coreid, address); break; case AICE_CACHE_CTL_L1I_INVALALL: result = aice_usb_icache_inval_all(coreid); break; case AICE_CACHE_CTL_L1I_VA_INVAL: result = aice_usb_icache_va_inval(coreid, address); break; default: result = ERROR_FAIL; break; } return result; } static int aice_usb_set_retry_times(uint32_t a_retry_times) { aice_max_retry_times = a_retry_times; return ERROR_OK; } static int aice_usb_program_edm(uint32_t coreid, char *command_sequence) { char *command_str; char *reg_name_0; char *reg_name_1; uint32_t data_value; int i; /* init strtok() */ command_str = strtok(command_sequence, ";"); if (command_str == NULL) return ERROR_OK; do { i = 0; /* process one command */ while (command_str[i] == ' ' || command_str[i] == '\n' || command_str[i] == '\r' || command_str[i] == '\t') i++; /* skip ' ', '\r', '\n', '\t' */ command_str = command_str + i; if (strncmp(command_str, "write_misc", 10) == 0) { reg_name_0 = strstr(command_str, "gen_port0"); reg_name_1 = strstr(command_str, "gen_port1"); if (reg_name_0 != NULL) { data_value = strtoul(reg_name_0 + 9, NULL, 0); if (aice_write_misc(coreid, NDS_EDM_MISC_GEN_PORT0, data_value) != ERROR_OK) return ERROR_FAIL; } else if (reg_name_1 != NULL) { data_value = strtoul(reg_name_1 + 9, NULL, 0); if (aice_write_misc(coreid, NDS_EDM_MISC_GEN_PORT1, data_value) != ERROR_OK) return ERROR_FAIL; } else { LOG_ERROR("program EDM, unsupported misc register: %s", command_str); } } else { LOG_ERROR("program EDM, unsupported command: %s", command_str); } /* update command_str */ command_str = strtok(NULL, ";"); } while (command_str != NULL); return ERROR_OK; } static int aice_usb_set_command_mode(enum aice_command_mode command_mode) { int retval = ERROR_OK; /* flush usb_packets_buffer as users change mode */ retval = aice_usb_packet_flush(); if (AICE_COMMAND_MODE_BATCH == command_mode) { /* reset batch buffer */ aice_command_mode = AICE_COMMAND_MODE_NORMAL; retval = aice_write_ctrl(AICE_WRITE_CTRL_BATCH_CMD_BUF0_CTRL, 0x40000); } aice_command_mode = command_mode; return retval; } static int aice_usb_execute(uint32_t coreid, uint32_t *instructions, uint32_t instruction_num) { uint32_t i, j; uint8_t current_instruction_num; uint32_t dim_instructions[4] = {NOP, NOP, NOP, BEQ_MINUS_12}; /* To execute 4 instructions as a special case */ if (instruction_num == 4) return aice_execute_dim(coreid, instructions, 4); for (i = 0 ; i < instruction_num ; i += 3) { if (instruction_num - i < 3) { current_instruction_num = instruction_num - i; for (j = current_instruction_num ; j < 3 ; j++) dim_instructions[j] = NOP; } else { current_instruction_num = 3; } memcpy(dim_instructions, instructions + i, current_instruction_num * sizeof(uint32_t)); /** fill DIM */ if (aice_write_dim(coreid, dim_instructions, 4) != ERROR_OK) return ERROR_FAIL; /** clear DBGER.DPED */ if (aice_write_misc(coreid, NDS_EDM_MISC_DBGER, NDS_DBGER_DPED) != ERROR_OK) return ERROR_FAIL; /** execute DIM */ if (aice_do_execute(coreid) != ERROR_OK) return ERROR_FAIL; /** check DBGER.DPED */ if (aice_check_dbger(coreid, NDS_DBGER_DPED) != ERROR_OK) { LOG_ERROR("<-- TARGET ERROR! Debug operations do not finish properly:" "0x%08" PRIx32 " 0x%08" PRIx32 " 0x%08" PRIx32 " 0x%08" PRIx32 ". -->", dim_instructions[0], dim_instructions[1], dim_instructions[2], dim_instructions[3]); return ERROR_FAIL; } } return ERROR_OK; } static int aice_usb_set_custom_srst_script(const char *script) { custom_srst_script = strdup(script); return ERROR_OK; } static int aice_usb_set_custom_trst_script(const char *script) { custom_trst_script = strdup(script); return ERROR_OK; } static int aice_usb_set_custom_restart_script(const char *script) { custom_restart_script = strdup(script); return ERROR_OK; } static int aice_usb_set_count_to_check_dbger(uint32_t count_to_check) { aice_count_to_check_dbger = count_to_check; return ERROR_OK; } static int aice_usb_set_data_endian(uint32_t coreid, enum aice_target_endian target_data_endian) { data_endian = target_data_endian; return ERROR_OK; } static int fill_profiling_batch_commands(uint32_t coreid, uint32_t reg_no) { uint32_t dim_instructions[4]; aice_usb_set_command_mode(AICE_COMMAND_MODE_BATCH); /* halt */ if (aice_write_misc(coreid, NDS_EDM_MISC_EDM_CMDR, 0) != ERROR_OK) return ERROR_FAIL; /* backup $r0 */ dim_instructions[0] = MTSR_DTR(0); dim_instructions[1] = DSB; dim_instructions[2] = NOP; dim_instructions[3] = BEQ_MINUS_12; if (aice_write_dim(coreid, dim_instructions, 4) != ERROR_OK) return ERROR_FAIL; aice_read_dtr_to_buffer(coreid, AICE_BATCH_DATA_BUFFER_0); /* get samples */ if (NDS32_REG_TYPE_GPR == nds32_reg_type(reg_no)) { /* general registers */ dim_instructions[0] = MTSR_DTR(reg_no); dim_instructions[1] = DSB; dim_instructions[2] = NOP; dim_instructions[3] = BEQ_MINUS_12; } else if (NDS32_REG_TYPE_SPR == nds32_reg_type(reg_no)) { /* user special registers */ dim_instructions[0] = MFUSR_G0(0, nds32_reg_sr_index(reg_no)); dim_instructions[1] = MTSR_DTR(0); dim_instructions[2] = DSB; dim_instructions[3] = BEQ_MINUS_12; } else { /* system registers */ dim_instructions[0] = MFSR(0, nds32_reg_sr_index(reg_no)); dim_instructions[1] = MTSR_DTR(0); dim_instructions[2] = DSB; dim_instructions[3] = BEQ_MINUS_12; } if (aice_write_dim(coreid, dim_instructions, 4) != ERROR_OK) return ERROR_FAIL; aice_read_dtr_to_buffer(coreid, AICE_BATCH_DATA_BUFFER_1); /* restore $r0 */ aice_write_dtr_from_buffer(coreid, AICE_BATCH_DATA_BUFFER_0); dim_instructions[0] = MFSR_DTR(0); dim_instructions[1] = DSB; dim_instructions[2] = NOP; dim_instructions[3] = IRET; /* free run */ if (aice_write_dim(coreid, dim_instructions, 4) != ERROR_OK) return ERROR_FAIL; aice_command_mode = AICE_COMMAND_MODE_NORMAL; /* use BATCH_BUFFER_WRITE to fill command-batch-buffer */ if (aice_batch_buffer_write(AICE_BATCH_COMMAND_BUFFER_0, usb_out_packets_buffer, (usb_out_packets_buffer_length + 3) / 4) != ERROR_OK) return ERROR_FAIL; usb_out_packets_buffer_length = 0; usb_in_packets_buffer_length = 0; return ERROR_OK; } static int aice_usb_profiling(uint32_t coreid, uint32_t interval, uint32_t iteration, uint32_t reg_no, uint32_t *samples, uint32_t *num_samples) { uint32_t iteration_count; uint32_t this_iteration; int retval = ERROR_OK; const uint32_t MAX_ITERATION = 250; *num_samples = 0; /* init DIM size */ if (aice_write_ctrl(AICE_WRITE_CTRL_BATCH_DIM_SIZE, 4) != ERROR_OK) return ERROR_FAIL; /* Use AICE_BATCH_DATA_BUFFER_0 to read/write $DTR. * Set it to circular buffer */ if (aice_write_ctrl(AICE_WRITE_CTRL_BATCH_DATA_BUF0_CTRL, 0xC0000) != ERROR_OK) return ERROR_FAIL; fill_profiling_batch_commands(coreid, reg_no); iteration_count = 0; while (iteration_count < iteration) { if (iteration - iteration_count < MAX_ITERATION) this_iteration = iteration - iteration_count; else this_iteration = MAX_ITERATION; /* set number of iterations */ uint32_t val_iteration; val_iteration = interval << 16 | this_iteration; if (aice_write_ctrl(AICE_WRITE_CTRL_BATCH_ITERATION, val_iteration) != ERROR_OK) { retval = ERROR_FAIL; goto end_profiling; } /* init AICE_WRITE_CTRL_BATCH_DATA_BUF1_CTRL to store $PC */ if (aice_write_ctrl(AICE_WRITE_CTRL_BATCH_DATA_BUF1_CTRL, 0x40000) != ERROR_OK) { retval = ERROR_FAIL; goto end_profiling; } aice_usb_run(coreid); /* enable BATCH command */ if (aice_write_ctrl(AICE_WRITE_CTRL_BATCH_CTRL, 0x80000000) != ERROR_OK) { aice_usb_halt(coreid); retval = ERROR_FAIL; goto end_profiling; } /* wait a while (AICE bug, workaround) */ alive_sleep(this_iteration); /* check status */ uint32_t i; uint32_t batch_status = 0; i = 0; while (1) { aice_read_ctrl(AICE_READ_CTRL_BATCH_STATUS, &batch_status); if (batch_status & 0x1) { break; } else if (batch_status & 0xE) { aice_usb_halt(coreid); retval = ERROR_FAIL; goto end_profiling; } if ((i % 30) == 0) keep_alive(); i++; } aice_usb_halt(coreid); /* get samples from batch data buffer */ if (aice_batch_buffer_read(AICE_BATCH_DATA_BUFFER_1, samples + iteration_count, this_iteration) != ERROR_OK) { retval = ERROR_FAIL; goto end_profiling; } iteration_count += this_iteration; } end_profiling: *num_samples = iteration_count; return retval; } /** */ struct aice_port_api_s aice_usb_api = { /** */ .open = aice_open_device, /** */ .close = aice_usb_close, /** */ .idcode = aice_usb_idcode, /** */ .state = aice_usb_state, /** */ .reset = aice_usb_reset, /** */ .assert_srst = aice_usb_assert_srst, /** */ .run = aice_usb_run, /** */ .halt = aice_usb_halt, /** */ .step = aice_usb_step, /** */ .read_reg = aice_usb_read_reg, /** */ .write_reg = aice_usb_write_reg, /** */ .read_reg_64 = aice_usb_read_reg_64, /** */ .write_reg_64 = aice_usb_write_reg_64, /** */ .read_mem_unit = aice_usb_read_memory_unit, /** */ .write_mem_unit = aice_usb_write_memory_unit, /** */ .read_mem_bulk = aice_usb_bulk_read_mem, /** */ .write_mem_bulk = aice_usb_bulk_write_mem, /** */ .read_debug_reg = aice_usb_read_debug_reg, /** */ .write_debug_reg = aice_usb_write_debug_reg, /** */ .set_jtag_clock = aice_usb_set_jtag_clock, /** */ .memory_access = aice_usb_memory_access, /** */ .memory_mode = aice_usb_memory_mode, /** */ .read_tlb = aice_usb_read_tlb, /** */ .cache_ctl = aice_usb_cache_ctl, /** */ .set_retry_times = aice_usb_set_retry_times, /** */ .program_edm = aice_usb_program_edm, /** */ .set_command_mode = aice_usb_set_command_mode, /** */ .execute = aice_usb_execute, /** */ .set_custom_srst_script = aice_usb_set_custom_srst_script, /** */ .set_custom_trst_script = aice_usb_set_custom_trst_script, /** */ .set_custom_restart_script = aice_usb_set_custom_restart_script, /** */ .set_count_to_check_dbger = aice_usb_set_count_to_check_dbger, /** */ .set_data_endian = aice_usb_set_data_endian, /** */ .profiling = aice_usb_profiling, };
olerem/openocd
src/jtag/aice/aice_usb.c
C
gpl-2.0
113,883
/* * drivers/power/huawei_charger.c * *huawei charger driver * * Copyright (C) 2012-2015 HUAWEI, Inc. * Author: HUAWEI, Inc. * * This package is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/jiffies.h> #include <linux/wakelock.h> #include <linux/usb/otg.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/power_supply.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/notifier.h> #include <linux/mutex.h> #include <linux/huawei/usb/hisi_usb.h> #include <huawei_platform/log/hw_log.h> #ifdef CONFIG_HUAWEI_HW_DEV_DCT #include <linux/hw_dev_dec.h> #endif #include <linux/raid/pq.h> #include <dsm/dsm_pub.h> #include <huawei_platform_legacy/Seattle/power/bq_bci_battery.h> #include <huawei_platform/power/huawei_charger.h> #include <huawei_platform_legacy/Seattle/power/hisi_coul_drv.h> #include <charging_core.h> #ifdef CONFIG_SWITCH_FSA9685 #include <huawei_platform/usb/switch/switch_fsa9685.h> #endif #define HWLOG_TAG huawei_charger HWLOG_REGIST(); static struct wake_lock charge_lock; static struct wake_lock stop_charge_lock; struct charge_device_ops *g_ops = NULL; struct fcp_adapter_device_ops *g_fcp_ops = NULL; static enum fcp_check_stage_type fcp_stage = FCP_STAGE_DEFAUTL; struct device *charge_dev = NULL; #define REG_NUM 21 struct hisi_charger_bootloader_info{ bool info_vaild; int ibus; char reg[REG_NUM]; }; extern char* get_charger_info_p(); static struct hisi_charger_bootloader_info hisi_charger_info = {0}; #define CHARGER_BASE_ADDR 512 struct charger_dsm { int error_no; bool notify_enable; char buf[ERR_NO_STRING_SIZE]; }; static struct charger_dsm err_count[]= { {ERROR_FCP_VOL_OVER_HIGH, true, "fcp vbus is high"}, {ERROR_FCP_DETECT, true, "fcp detect fail"}, {ERROR_FCP_OUTPUT, true, "fcp voltage output fail"}, {ERROR_SWITCH_ATTACH, true, "fcp adapter connecte fail"}, {ERROR_ADAPTER_OVLT, true, "fcp adapter voltage over high"}, {ERROR_ADAPTER_OCCURRENT, true, "fcp adapter current over high"}, {ERROR_ADAPTER_OTEMP, true, "fcp adapter temp over high"}, }; /********************************************************** * Function: dsm_report * Discription: dsm report interface * Parameters: err_no buf * return value: 0 :succ -1:fail **********************************************************/ int dsm_report(int err_no,void* buf) { if(NULL == buf || NULL == get_battery_dclient()) { hwlog_info("buf is NULL or battery_dclient is NULL!\n"); return -1; } if(!dsm_client_ocuppy(get_battery_dclient())) { dsm_client_record(get_battery_dclient(), "%s", buf); dsm_client_notify(get_battery_dclient(),err_no); hwlog_info("charger dsm report err_no:%d\n",err_no); return 0; } hwlog_info("charger dsm is busy!\n"); return -1; } /********************************************************** * Function: charger_dsm_report * Discription: charger dsm report * Parameters: err_no val * return value: 0:succ ;-1 :fail **********************************************************/ int charger_dsm_report (int err_no,int *val) { char temp[1024] = {0}; char buf[ERR_NO_STRING_SIZE] = {0}; switch_dump_register();/*dump switch register*/ strncpy(temp,err_count[get_index(err_no)].buf,ERR_NO_STRING_SIZE-1); if(val)/*need report reg*/ { snprintf(buf,sizeof(buf),"val= %d\n",*val); strncat(temp,buf,strlen(buf)); } if(true == err_count[get_index(err_no)].notify_enable)/*every err_no report one times*/ { if (!dsm_report(err_no,temp)) { err_count[get_index(err_no)].notify_enable = false;/*when it be set 1,it will not report */ return 0; } } return -1; } static int dump_bootloader_info(char *reg_value) { u8 reg[REG_NUM] = {0}; char buff[26] = {0}; int i = 0; memset(reg_value, 0, CHARGELOG_SIZE); snprintf(buff, 26, "%-8.2d", hisi_charger_info.ibus); strncat(reg_value, buff, strlen(buff)); for(i = 0;i<REG_NUM;i++) { snprintf(buff, 26, "0x%-8.2x",hisi_charger_info.reg[i]); strncat(reg_value, buff, strlen(buff)); } return 0; } static int copy_bootloader_charger_info(void) { char* p = NULL; int i =0 ; p = get_charger_info_p(); if( NULL == p ) { hwlog_err("bootloader pointer NULL!\n"); return -1; } memcpy(&hisi_charger_info, p+CHARGER_BASE_ADDR, sizeof(hisi_charger_info)); hwlog_info("bootloader ibus %d\n",hisi_charger_info.ibus); return 0; } /********************************************************** * Function: fcp_check_switch_status * Discription: check switch chip status * Parameters: void * return value: void **********************************************************/ void fcp_check_switch_status(struct charge_device_info *di) { int val = -1; int reg = 0; int ret = -1; if(di->ops->get_charge_state)/*check usb is on or not ,if not ,can not detect the switch status*/ { ret = di->ops->get_charge_state(&reg); if(ret) { hwlog_info("%s:read PG STAT fail.\n",__func__); return ; } if(reg & CHAGRE_STATE_NOT_PG) { hwlog_info("%s:PG NOT GOOD can not check switch status.\n",__func__); return ; } } val = fcp_read_switch_status(); if(val) { charger_dsm_report(ERROR_SWITCH_ATTACH,NULL); } } /********************************************************** * Function: fcp_check_switch_status * Discription: check adapter status * Parameters: void * return value: void **********************************************************/ void fcp_check_adapter_status(struct charge_device_info *di) { int val = -1; int reg = 0; int ret = -1; if(di->ops->get_charge_state)/*check usb is on or not ,if not ,can not detect the switch status*/ { ret = di->ops->get_charge_state(&reg); if(ret) { hwlog_info("%s:read PG STAT fail.\n",__func__); return ; } if(reg & CHAGRE_STATE_NOT_PG) { hwlog_info("%s:PG NOT GOOD can not check adapter status.\n",__func__); return ; } } val = fcp_read_adapter_status(); if( FCP_ADAPTER_OVLT == val) { charger_dsm_report(ERROR_ADAPTER_OVLT,NULL); } if( FCP_ADAPTER_OCURRENT == val) { charger_dsm_report(ERROR_ADAPTER_OCCURRENT,NULL); } if( FCP_ADAPTER_OTEMP == val) { charger_dsm_report(ERROR_ADAPTER_OTEMP,NULL); } } ATOMIC_NOTIFIER_HEAD(fault_notifier_list); /********************************************************** * Function: charge_rename_charger_type * Discription: rename the charger_type from USB PHY to charger * Parameters: type:charger type from USB PHY * di:charge_device_info * return value: NULL **********************************************************/ static void charge_rename_charger_type(enum hisi_charger_type type, struct charge_device_info *di) { switch(type) { case CHARGER_TYPE_SDP: di->charger_type = CHARGER_TYPE_USB; di->charger_source = POWER_SUPPLY_TYPE_USB; break; case CHARGER_TYPE_CDP: di->charger_type = CHARGER_TYPE_BC_USB; di->charger_source = POWER_SUPPLY_TYPE_USB; break; case CHARGER_TYPE_DCP: di->charger_type = CHARGER_TYPE_STANDARD; di->charger_source = POWER_SUPPLY_TYPE_MAINS; break; case CHARGER_TYPE_UNKNOWN: di->charger_type = CHARGER_TYPE_NON_STANDARD; di->charger_source = POWER_SUPPLY_TYPE_MAINS; break; case CHARGER_TYPE_NONE: di->charger_type = CHARGER_REMOVED; di->charger_source = POWER_SUPPLY_TYPE_BATTERY; break; case PLEASE_PROVIDE_POWER: di->charger_type = USB_EVENT_OTG_ID; di->charger_source = POWER_SUPPLY_TYPE_BATTERY; break; default: di->charger_type = CHARGER_REMOVED; di->charger_source = POWER_SUPPLY_TYPE_BATTERY; break; } } /********************************************************** * Function: charge_update_charger_type * Discription: update charger_type from fsa9685 when the charger_type is CHARGER_TYPE_NON_STANDARD * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_update_charger_type(struct charge_device_info *di) { enum hisi_charger_type type = CHARGER_TYPE_NONE; if(di->charger_type != CHARGER_TYPE_NON_STANDARD) return; #ifdef CONFIG_SWITCH_FSA9685 type = fsa9685_get_charger_type(); if(type != CHARGER_TYPE_NONE) { charge_rename_charger_type(type, di); } hwlog_info("[%s]charger type is update to[%d] from nonstd charger!\n",__func__,di->charger_type); #endif } /********************************************************** * Function: charge_send_uevent * Discription: send charge uevent immediately after charger type is recognized * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_send_uevent(struct charge_device_info *di) { /*send events*/ enum charge_status_event events; if(di == NULL) { hwlog_err("[%s]di is NULL!\n",__func__); return; } if(di->charger_source == POWER_SUPPLY_TYPE_MAINS) { events = VCHRG_START_AC_CHARGING_EVENT; hisi_coul_charger_event_rcv(events); } else if(di->charger_source == POWER_SUPPLY_TYPE_USB) { events = VCHRG_START_USB_CHARGING_EVENT; hisi_coul_charger_event_rcv(events); } else { //do nothing } } EXPORT_SYMBOL(fcp_get_stage_status); /********************************************************** * Function: fcp_get_stage_status * Discription: get the stage of fcp charge * Parameters: di:charge_device_info * return value: NULL **********************************************************/ enum fcp_check_stage_type fcp_get_stage_status(void) { return fcp_stage; } /********************************************************** * Function: fcp_set_stage_status * Discription: set the stage of fcp charge * Parameters: di:charge_device_info * return value: NULL **********************************************************/ void fcp_set_stage_status(enum fcp_check_stage_type stage_type) { fcp_stage = stage_type; } /********************************************************** * Function: fcp_retry_pre_operate * Discription: pre operate before retry fcp enable * Parameters: di:charge_device_info,type : enum fcp_retry_operate_type * return value: 0: fcp pre operate success -1:fcp pre operate fail **********************************************************/ static int fcp_retry_pre_operate(enum fcp_retry_operate_type type,struct charge_device_info *di) { int pg_state =0,ret =-1; ret = di->ops->get_charge_state(&pg_state); if(ret < 0) { hwlog_err("get_charge_state fail!!ret = 0x%x\n",ret); return ret; } /*check status charger not power good state*/ if(pg_state & CHAGRE_STATE_NOT_PG) { hwlog_err("state is not power good \n"); return -1; } switch(type) { case FCP_RETRY_OPERATE_RESET_ADAPTER: if(NULL != di->fcp_ops->fcp_adapter_reset) { hwlog_info("send fcp adapter reset cmd \n"); ret = di->fcp_ops->fcp_adapter_reset(); } else { ret = -1; } break; case FCP_RETRY_OPERATE_RESET_FSA9688: if(NULL != di->fcp_ops->switch_chip_reset) { hwlog_info(" switch_chip_reset \n"); ret = di->fcp_ops->switch_chip_reset(); msleep(2000); } else { ret = -1; } break; default: break; } return ret; } /********************************************************** * Function: fcp_start_charging * Discription: enter fcp charging mode * Parameters: di:charge_device_info * return value: 0: fcp start success -1:fcp start fail 1:fcp start failed need to retry **********************************************************/ static int fcp_start_charging(struct charge_device_info *di) { int ret = -1; fcp_set_stage_status(FCP_STAGE_SUPPORT_DETECT); if(( NULL == di->fcp_ops->is_support_fcp )||( NULL ==di->fcp_ops->detect_adapter) ||( NULL ==di->fcp_ops->set_adapter_output_vol)||( NULL ==di->fcp_ops->get_adapter_output_current)) { hwlog_err("fcp ops is NULL!\n"); return -1; } /*check whether support fcp*/ if (di->fcp_ops->is_support_fcp()) { hwlog_err("not support fcp!\n"); return -1; } /*To avoid to effect accp detect , input current need to be lower than 1A,we set 0.5A */ di->input_current = CHARGE_CURRENT_0500_MA; di->ops->set_input_current(di->input_current); /*detect fcp adapter*/ fcp_set_stage_status(FCP_STAGE_ADAPTER_DETECT); ret = di->fcp_ops->detect_adapter(); if (FCP_ADAPTER_DETECT_SUCC != ret) { hwlog_err("fcp detect fail!\n"); if(FCP_ADAPTER_DETECT_FAIL == ret) { return 1; } return -1; } fcp_set_stage_status(FCP_STAGE_ADAPTER_ENABLE); di->ops->fcp_chip_init(); /*disable charger when vol is changed */ di->ops->set_charge_enable(FALSE); /*set fcp adapter output vol*/ if (di->fcp_ops->set_adapter_output_vol()) { di->ops->chip_init(); hwlog_err("fcp set vol fail!\n"); return 1; } /*enable charger when vol is changed */ di->ops->set_charge_enable(TRUE); di->charger_type= CHARGER_TYPE_FCP; fcp_set_stage_status(FCP_STAGE_SUCESS); hwlog_info("fcp charging start success!\n"); return 0; } /********************************************************** * Function: charge_vbus_voltage_check * Discription: check whether the voltage of vbus is normal * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_vbus_voltage_check(struct charge_device_info *di) { int ret=0; unsigned int vbus_vol =0; static int fcp_vbus_lower_count = 0; static int nonfcp_vbus_higher_count=0; if (NULL == di->ops->get_vbus || NULL == di->ops->set_covn_start){ return; } ret = di->ops->set_covn_start(true);/*enable the covn ,after 1s the it will be set 0 auto*/ if(ret){ hwlog_err("[%s]set covn start fail.\n",__func__); return; } ret = di->ops->get_vbus(&vbus_vol); hwlog_info("vbus vbus_vol:%d.\n",vbus_vol); if(ret){ hwlog_err("[%s]vbus read failed \n",__func__); } if(FCP_STAGE_SUCESS == fcp_get_stage_status()) { /* fcp stage : vbus must be higher than 7000 mV */ if(vbus_vol < VBUS_VOLTAGE_FCP_MIN_MV) { fcp_vbus_lower_count+=1; hwlog_err("[%s]fcp output vol =%d mV, lower 7000 mV , fcp_vbus_lower_count =%d!!\n",__func__,vbus_vol,fcp_vbus_lower_count); } else { fcp_vbus_lower_count = 0; } /* check continuous abnormal vbus cout */ if(fcp_vbus_lower_count >= VBUS_VOLTAGE_ABNORMAL_MAX_COUNT) { fcp_check_adapter_status(di); fcp_set_stage_status(FCP_STAGE_DEFAUTL); di->charger_type= CHARGER_TYPE_STANDARD; fcp_vbus_lower_count = VBUS_VOLTAGE_ABNORMAL_MAX_COUNT; charger_dsm_report(ERROR_FCP_VOL_OVER_HIGH,&vbus_vol); } nonfcp_vbus_higher_count= 0; } else { /*non fcp stage : vbus must be lower than 6500 mV */ if(vbus_vol > VBUS_VOLTAGE_NON_FCP_MAX_MV) { nonfcp_vbus_higher_count+=1; hwlog_info("[%s]non standard fcp and vbus voltage is %d mv,over 6500mv ,nonfcp_vbus_higher_count =%d!!\n",__func__,vbus_vol,nonfcp_vbus_higher_count); } else { nonfcp_vbus_higher_count = 0; } /* check continuous abnormal vbus cout */ if(nonfcp_vbus_higher_count >= VBUS_VOLTAGE_ABNORMAL_MAX_COUNT) { di->charge_enable = FALSE; nonfcp_vbus_higher_count = VBUS_VOLTAGE_ABNORMAL_MAX_COUNT; charger_dsm_report(ERROR_FCP_VOL_OVER_HIGH,&vbus_vol); } fcp_vbus_lower_count =0; } } /********************************************************** * Function: fcp_charge_check * Discription: check whether start fcp charging,if support try to start fcp charging * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void fcp_charge_check(struct charge_device_info *di) { int ret =0,i= 0; /* if chip not support fcp, return */ if(!di->ops->fcp_chip_init) { return; } if(FCP_STAGE_SUCESS == fcp_get_stage_status()) { fcp_check_switch_status(di); } if(di->charger_type != CHARGER_TYPE_STANDARD || !(is_hisi_battery_exist())) { return; } if(FCP_STAGE_DEFAUTL == fcp_get_stage_status() ) { ret = fcp_start_charging(di); for(i=0;i<3 && ret == 1;i++) { /* reset adapter and try again */ if((fcp_retry_pre_operate(FCP_RETRY_OPERATE_RESET_ADAPTER , di)) < 0) { hwlog_err("reset adapter failed \n"); ret = -1;/*PG NOT GOOD*/ break; } ret = fcp_start_charging(di); } if(ret == 1) { /* reset fsa9688 chip and try again */ if((fcp_retry_pre_operate(FCP_RETRY_OPERATE_RESET_FSA9688 , di)) == 0) { ret = fcp_start_charging(di); } else { hwlog_err("%s : fcp_retry_pre_operate failed \n",__func__); ret = -1;/*PG NOT GOOD*/ } } if(ret == 1) { if(FCP_STAGE_ADAPTER_ENABLE == fcp_get_stage_status()) { charger_dsm_report(ERROR_FCP_OUTPUT,NULL); } if(FCP_STAGE_ADAPTER_DETECT == fcp_get_stage_status()) { charger_dsm_report(ERROR_FCP_DETECT,NULL); } } hwlog_info("[%s]fcp stage %s !!! \n",__func__,fcp_check_stage[fcp_get_stage_status()]); } } /********************************************************** * Function: charge_select_charging_current * Discription: get the input current and charge current from different charger_type and charging linited value * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_select_charging_current(struct charge_device_info *di) { static unsigned int first_in = 1; switch(di->charger_type) { case CHARGER_TYPE_USB: di->input_current = di->core_data->iin_usb; di->charge_current = di->core_data->ichg_usb; break; case CHARGER_TYPE_NON_STANDARD: di->input_current = di->core_data->iin_nonstd; di->charge_current = di->core_data->ichg_nonstd; break; case CHARGER_TYPE_BC_USB: di->input_current = di->core_data->iin_bc_usb; di->charge_current = di->core_data->ichg_bc_usb; break; case CHARGER_TYPE_STANDARD: di->input_current = di->core_data->iin_ac; di->charge_current = di->core_data->ichg_ac; break; case CHARGER_TYPE_FCP: di->input_current = di->core_data->iin_fcp; di->charge_current = di->core_data->ichg_fcp; break; default: di->input_current = CHARGE_CURRENT_0500_MA; di->charge_current = CHARGE_CURRENT_0500_MA; break; } if (strstr(saved_command_line, "androidboot.swtype=factory") && (!is_hisi_battery_exist())) { if (first_in) { hwlog_info("facory_version and battery not exist, enable charge\n"); first_in = 0; } } else { if (di->sysfs_data.charge_limit == TRUE) { di->input_current = ((di->input_current < di->core_data->iin) ? di->input_current : di->core_data->iin); di->input_current = ((di->input_current < di->sysfs_data.iin_thl) ? di->input_current : di->sysfs_data.iin_thl); di->input_current = ((di->input_current < di->sysfs_data.iin_rt) ? di->input_current : di->sysfs_data.iin_rt); di->charge_current = ((di->charge_current < di->core_data->ichg) ? di->charge_current : di->core_data->ichg); di->charge_current = ((di->charge_current < di->sysfs_data.ichg_thl) ? di->charge_current : di->sysfs_data.ichg_thl); di->charge_current = ((di->charge_current < di->sysfs_data.ichg_rt) ? di->charge_current : di->sysfs_data.ichg_rt); } } if (1 == di->sysfs_data.batfet_disable) di->input_current = CHARGE_CURRENT_2000_MA; } /********************************************************** * Function: charge_update_vindpm * Discription: update the input dpm voltage setting by battery capacity * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_update_vindpm(struct charge_device_info *di) { int ret = 0; int vindpm = CHARGE_VOLTAGE_4520_MV; if(FCP_STAGE_SUCESS == fcp_get_stage_status()) { return; } if(POWER_SUPPLY_TYPE_MAINS == di->charger_source) { vindpm = di->core_data->vdpm; } if(di->ops->set_dpm_voltage) { ret = di->ops->set_dpm_voltage(vindpm); if(ret > 0) { hwlog_info("dpm voltage is out of range:%dmV!!\n",ret); ret = di->ops->set_dpm_voltage(ret); if(ret < 0) hwlog_err("set dpm voltage fail!!\n"); } else if(ret < 0) hwlog_err("set dpm voltage fail!!\n"); } } /********************************************************** * Function: charge_update_external_setting * Discription: update the others chargerIC setting * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_update_external_setting(struct charge_device_info *di) { int ret = 0; unsigned int batfet_disable = FALSE; unsigned int watchdog_timer = WATCHDOG_TIMER_80_S; /*update batfet setting*/ if(di->sysfs_data.batfet_disable == TRUE) { batfet_disable = TRUE; } if(di->ops->set_batfet_disable) { ret = di->ops->set_batfet_disable(batfet_disable); if(ret) hwlog_err("set batfet disable fail!!\n"); } /*update watch dog timer setting*/ if(di->sysfs_data.wdt_disable == TRUE) { watchdog_timer = WATCHDOG_TIMER_DISABLE; } if(di->ops->set_watchdog_timer) { ret = di->ops->set_watchdog_timer(watchdog_timer); if(ret) hwlog_err("set watchdog timer fail!!\n"); } } /********************************************************** * Function: charge_is_charging_full * Discription: check the battery is charging full or not * Parameters: di:charge_device_info * return value: TURE-is full or FALSE-no full **********************************************************/ static int charge_is_charging_full(struct charge_device_info *di) { int ichg = -hisi_battery_current(); int ichg_avg = hisi_battery_current_avg(); int val = FALSE; if(!(di->charge_enable) || !(is_hisi_battery_exist())) return val; if((ichg > MIN_CHARGING_CURRENT_OFFSET) && (ichg < di->core_data->iterm) &&(ichg_avg > MIN_CHARGING_CURRENT_OFFSET) && (ichg_avg < di->core_data->iterm)) { di->check_full_count++; if(di->check_full_count >= BATTERY_FULL_CHECK_TIMIES) { di->check_full_count = BATTERY_FULL_CHECK_TIMIES; val = TRUE; hwlog_info("battery is full!capacity = %d,ichg = %d,ichg_avg = %d\n",hisi_battery_capacity(),ichg,ichg_avg); } } else { di->check_full_count = 0; } return val; } /********************************************************** * Function: charge_full_handle * Discription: set term enable flag by charge current is lower than iterm * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_full_handle(struct charge_device_info *di) { int ret = 0; int is_battery_full = charge_is_charging_full(di); if(di->ops->set_term_enable) { ret = di->ops->set_term_enable(is_battery_full); if(ret) hwlog_err("set term enable fail!!\n"); } /*set terminal current*/ ret = di->ops->set_terminal_current(di->core_data->iterm); if (ret > 0) { di->ops->set_terminal_current(ret); } else if (ret < 0) { hwlog_err("set terminal current fail!\n"); } /* reset adapter to 5v after fcp charge done,avoid long-term at high voltage */ if(is_battery_full && FCP_STAGE_SUCESS == fcp_get_stage_status() && hisi_battery_capacity() == 100 && NULL != di->fcp_ops->fcp_adapter_reset) { if(di->fcp_ops->fcp_adapter_reset()) { hwlog_err("adapter reset failed \n"); } fcp_set_stage_status(FCP_STAGE_CHARGE_DONE); hwlog_info("fcp charge done, reset adapter to 5v !\n"); } } /********************************************************** * Function: charge_kick_watchdog * Discription: kick watchdog timer * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_kick_watchdog(struct charge_device_info *di) { int ret = 0; ret = di->ops->reset_watchdog_timer(); if(ret) hwlog_err("reset watchdog timer fail!!\n"); } /********************************************************** * Function: charge_start_charging * Discription: enter into charging mode * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_start_charging(struct charge_device_info *di) { int ret = 0; hwlog_info("---->START CHARGING\n"); wake_lock(&charge_lock); di->sysfs_data.charge_enable = TRUE; di->check_full_count = 0; /*chip init*/ ret = di->ops->chip_init(); if(ret) hwlog_err("chip init fail!!\n"); schedule_delayed_work(&di->charge_work,msecs_to_jiffies(0)); } /********************************************************** * Function: charge_stop_charging * Discription: exit charging mode * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_stop_charging(struct charge_device_info *di) { int ret =0; enum charge_status_event events = VCHRG_STOP_CHARGING_EVENT; hwlog_info("---->STOP CHARGING\n"); if (!wake_lock_active(&charge_lock)) { wake_lock(&charge_lock); } di->sysfs_data.charge_enable = FALSE; di->check_full_count = 0; di->charger_source = POWER_SUPPLY_TYPE_BATTERY; hisi_coul_charger_event_rcv(events); ret = di->ops->set_charge_enable(FALSE); if(ret) hwlog_err("[%s]set charge enable fail!\n",__func__); ret = di->ops->set_otg_enable(FALSE); if(ret) hwlog_err("[%s]set otg enable fail!\n",__func__); cancel_delayed_work_sync(&di->charge_work); cancel_delayed_work_sync(&di->otg_work); if((di->sysfs_data.wdt_disable == TRUE) && (di->ops->set_watchdog_timer))/*when charger stop ,disable watch dog ,only for hiz*/ { if(di->ops->set_watchdog_timer(WATCHDOG_TIMER_DISABLE)) hwlog_err("set watchdog timer fail for hiz!!\n"); } if(di->ops->stop_charge_config) { if(di->ops->stop_charge_config()) { hwlog_err(" stop charge config failed \n"); } } /*flag must be clear after charge_work has been canceled*/ fcp_set_stage_status(FCP_STAGE_DEFAUTL); msleep(1000); wake_lock_timeout(&stop_charge_lock, HZ); wake_unlock(&charge_lock); } /********************************************************** * Function: charge_start_usb_otg * Discription: enter into otg mode * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_start_usb_otg(struct charge_device_info *di) { int ret = 0; hwlog_info("---->START OTG MODE\n"); wake_lock(&charge_lock); ret = di->ops->set_charge_enable(FALSE); if(ret) hwlog_err("[%s]set charge enable fail!\n",__func__); ret = di->ops->set_otg_enable(TRUE); if(ret) hwlog_err("[%s]set otg enable fail!\n",__func__); if(di->ops->set_otg_current) { ret = di->ops->set_otg_current(di->core_data->otg_curr);/*otg current set 500mA form dtsi*/ if(ret) hwlog_err("[%s]set otg current fail!\n",__func__); } schedule_delayed_work(&di->otg_work, msecs_to_jiffies(0)); } /********************************************************** * Function: charge_otg_work * Discription: monitor the otg mode status * Parameters: work:otg workqueue * return value: NULL **********************************************************/ static void charge_otg_work(struct work_struct *work) { struct charge_device_info *di = container_of(work,struct charge_device_info, otg_work.work); charge_kick_watchdog(di); schedule_delayed_work(&di->otg_work,msecs_to_jiffies(CHARGING_WORK_TIMEOUT)); } /********************************************************** * Function: charge_fault_work * Discription: handler the fault events from chargerIC * Parameters: work:fault workqueue * return value: NULL **********************************************************/ static void charge_fault_work(struct work_struct *work) { struct charge_device_info *di = container_of(work, struct charge_device_info, fault_work); switch(di->charge_fault) { case CHARGE_FAULT_BOOST_OCP: hwlog_err("vbus overloaded in boost mode,close otg mode!!\n"); di->ops->set_otg_enable(FALSE); di->charge_fault = CHARGE_FAULT_NON; break; default: break; } } /********************************************************** * Function: charge_update_status * Discription: update the states of charging * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_update_status(struct charge_device_info *di) { enum charge_status_event events = VCHRG_POWER_NONE_EVENT; unsigned int state = CHAGRE_STATE_NORMAL; int ret =0; ret = di->ops->get_charge_state(&state); if(ret < 0) { hwlog_err("get_charge_state fail!!ret = 0x%x\n",ret); return; } /*check status charger not power good state*/ if(state & CHAGRE_STATE_NOT_PG) { hwlog_err("VCHRG_POWER_SUPPLY_WEAKSOURCE\n"); events = VCHRG_POWER_SUPPLY_WEAKSOURCE; hisi_coul_charger_event_rcv(events); } /*check status charger ovp err*/ if(state & CHAGRE_STATE_VBUS_OVP) { hwlog_err("VCHRG_POWER_SUPPLY_OVERVOLTAGE\n"); events = VCHRG_POWER_SUPPLY_OVERVOLTAGE; hisi_coul_charger_event_rcv(events); } /*check status watchdog timer expiration*/ if(state & CHAGRE_STATE_WDT_FAULT) { hwlog_err("CHAGRE_STATE_WDT_TIMEOUT\n"); /*init chip register when watchdog timeout*/ di->ops->chip_init(); events = VCHRG_STATE_WDT_TIMEOUT; hisi_coul_charger_event_rcv(events); } /*check status battery ovp*/ if(state & CHAGRE_STATE_BATT_OVP) { hwlog_err("CHAGRE_STATE_BATT_OVP\n"); } /*check status charge done, ac charge and usb charge*/ if((di->charge_enable) && (is_hisi_battery_exist())) { if(state & CHAGRE_STATE_CHRG_DONE) { events = VCHRG_CHARGE_DONE_EVENT; hwlog_info("VCHRG_CHARGE_DONE_EVENT\n"); } else if(di->charger_source == POWER_SUPPLY_TYPE_MAINS) events = VCHRG_START_AC_CHARGING_EVENT; else events = VCHRG_START_USB_CHARGING_EVENT; } else { events = VCHRG_NOT_CHARGING_EVENT; hwlog_info("VCHRG_NOT_CHARGING_EVENT\n"); } hisi_coul_charger_event_rcv(events); } /********************************************************** * Function: charge_turn_on_charging * Discription: turn on charging, set input and charge currrent /CV termminal voltage / charge enable * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static void charge_turn_on_charging(struct charge_device_info *di) { int ret = 0; unsigned int vterm = 0; di->charge_enable = TRUE; /* check vbus voltage ,if vbus is abnormal disable charge or abort from fcp*/ charge_vbus_voltage_check(di); /*set input current*/ ret = di->ops->set_input_current(di->input_current); if(ret > 0) { hwlog_info("input current is out of range:%dmA!!\n",ret); di->ops->set_input_current(ret); } else if(ret < 0) hwlog_err("set input current fail!\n"); /*check if allow charging or not*/ if(di->charge_current == CHARGE_CURRENT_0000_MA) { di->charge_enable = FALSE; hwlog_info("charge current is set 0mA, turn off charging!\n"); } else { /*set CC charge current*/ ret = di->ops->set_charge_current(di->charge_current); if(ret > 0) { hwlog_info("charge current is out of range:%dmA!!\n",ret); di->ops->set_charge_current(ret); } else if(ret < 0) hwlog_err("set charge current fail!\n"); /*set CV terminal voltage*/ vterm = ((di->core_data->vterm < di->sysfs_data.vterm_rt) ? di->core_data->vterm : di->sysfs_data.vterm_rt); ret = di->ops->set_terminal_voltage(vterm); if(ret > 0) { hwlog_info("terminal voltage is out of range:%dmV!!\n",ret); di->ops->set_terminal_voltage(ret); } else if(ret < 0) hwlog_err("set terminal voltage fail!\n"); } /*enable/disable charge*/ di->charge_enable &= di->sysfs_data.charge_enable; ret = di->ops->set_charge_enable(di->charge_enable); if(ret) hwlog_err("set charge enable fail!!\n"); hwlog_debug("input_current is [%d],charge_current is [%d],terminal_voltage is [%d],charge_enable is [%d]\n", di->input_current,di->charge_current,vterm,di->charge_enable); } /********************************************************** * Function: charge_monitor_work * Discription: monitor the charging process * Parameters: work:charge workqueue * return value: NULL **********************************************************/ static void charge_monitor_work(struct work_struct *work) { struct charge_device_info *di = container_of(work,struct charge_device_info, charge_work.work); /* update type before get params*/ charge_update_charger_type(di); fcp_charge_check(di); di->core_data = charge_core_get_params(); charge_select_charging_current(di); charge_turn_on_charging(di); charge_full_handle(di); charge_update_vindpm(di); charge_update_external_setting(di); charge_update_status(di); charge_kick_watchdog(di); schedule_delayed_work(&di->charge_work,msecs_to_jiffies(CHARGING_WORK_TIMEOUT)); } /********************************************************** * Function: charge_usb_work * Discription: handler interface by different charger_type * Parameters: work:usb workqueue * return value: NULL **********************************************************/ static void charge_usb_work(struct work_struct *work) { struct charge_device_info *di = container_of(work, struct charge_device_info, usb_work); /* move uevent into usb_work in case usb_notifier run in irq context*/ charge_send_uevent(di); switch (di->charger_type) { case CHARGER_TYPE_USB: hwlog_info("case = CHARGER_TYPE_USB-> \n"); charge_start_charging(di); break; case CHARGER_TYPE_NON_STANDARD: hwlog_info("case = CHARGER_TYPE_NON_STANDARD -> \n"); charge_start_charging(di); break; case CHARGER_TYPE_BC_USB: hwlog_info("case = CHARGER_TYPE_BC_USB -> \n"); charge_start_charging(di); break; case CHARGER_TYPE_STANDARD: hwlog_info("case = CHARGER_TYPE_STANDARD-> \n"); charge_start_charging(di); break; case CHARGER_REMOVED: hwlog_info("case = USB_EVENT_NONE-> \n"); charge_stop_charging(di); break; case USB_EVENT_OTG_ID: hwlog_info("case = USB_EVENT_OTG_ID-> \n"); charge_start_usb_otg(di); break; default: break; } } /********************************************************** * Function: charge_usb_notifier_call * Discription: respond the charger_type events from USB PHY * Parameters: usb_nb:usb notifier_block * event:charger type event name * data:unused * return value: NOTIFY_OK-success or others **********************************************************/ static int charge_usb_notifier_call(struct notifier_block *usb_nb, unsigned long event, void *data) { struct charge_device_info *di = container_of(usb_nb, struct charge_device_info, usb_nb); charge_rename_charger_type((enum hisi_charger_type)event, di); schedule_work(&di->usb_work); return NOTIFY_OK; } /********************************************************** * Function: charge_fault_notifier_call * Discription: respond the fault events from chargerIC * Parameters: fault_nb:fault notifier_block * event:fault event name * data:unused * return value: NOTIFY_OK-success or others **********************************************************/ static int charge_fault_notifier_call(struct notifier_block *fault_nb,unsigned long event, void *data) { struct charge_device_info *di = container_of(fault_nb, struct charge_device_info, fault_nb); di->charge_fault = (enum charge_fault_type)event; schedule_work(&di->fault_work); return NOTIFY_OK; } /********************************************************** * Function: charge_check_input_dpm_state * Discription: check charger whether VINDPM or IINDPM * Parameters: NULL * return value: 1 means charger VINDPM or IINDPM * 0 means charger NoT DPM * -1 means chargeIC not support this function **********************************************************/ int charge_check_input_dpm_state(void) { if (NULL == g_ops || NULL == g_ops->check_input_dpm_state) { return -1; } return g_ops->check_input_dpm_state(); } #if CONFIG_SYSFS #define CHARGE_SYSFS_FIELD(_name, n, m, store) \ { \ .attr = __ATTR(_name, m, charge_sysfs_show, store), \ .name = CHARGE_SYSFS_##n, \ } #define CHARGE_SYSFS_FIELD_RW(_name, n) \ CHARGE_SYSFS_FIELD(_name, n, S_IWUSR | S_IRUGO, \ charge_sysfs_store) #define CHARGE_SYSFS_FIELD_RO(_name, n) \ CHARGE_SYSFS_FIELD(_name, n, S_IRUGO, NULL) static ssize_t charge_sysfs_show(struct device *dev, struct device_attribute *attr, char *buf); static ssize_t charge_sysfs_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count); struct charge_sysfs_field_info { struct device_attribute attr; u8 name; }; static struct charge_sysfs_field_info charge_sysfs_field_tbl[] = { CHARGE_SYSFS_FIELD_RW(iin_thermal, IIN_THERMAL), CHARGE_SYSFS_FIELD_RW(ichg_thermal, ICHG_THERMAL), /*iin_runningtest will be used for running test and audio test*/ CHARGE_SYSFS_FIELD_RW(iin_runningtest, IIN_RUNNINGTEST), CHARGE_SYSFS_FIELD_RW(ichg_runningtest, ICHG_RUNNINGTEST), CHARGE_SYSFS_FIELD_RW(enable_charger, ENABLE_CHARGER), CHARGE_SYSFS_FIELD_RW(limit_charging, LIMIT_CHARGING), CHARGE_SYSFS_FIELD_RW(regulation_voltage, REGULATION_VOLTAGE), CHARGE_SYSFS_FIELD_RW(shutdown_q4, BATFET_DISABLE), CHARGE_SYSFS_FIELD_RW(shutdown_watchdog, WATCHDOG_DISABLE), CHARGE_SYSFS_FIELD_RO(chargelog, CHARGELOG), CHARGE_SYSFS_FIELD_RO(chargelog_head, CHARGELOG_HEAD), CHARGE_SYSFS_FIELD_RO(Ibus, IBUS), CHARGE_SYSFS_FIELD_RW(enable_hiz, HIZ), CHARGE_SYSFS_FIELD_RO(chargerType, CHARGE_TYPE), CHARGE_SYSFS_FIELD_RO(bootloader_charger_info, BOOTLOADER_CHARGER_INFO), }; static struct attribute *charge_sysfs_attrs[ARRAY_SIZE(charge_sysfs_field_tbl) + 1]; static const struct attribute_group charge_sysfs_attr_group = { .attrs = charge_sysfs_attrs, }; /********************************************************** * Function: charge_sysfs_init_attrs * Discription: initialize charge_sysfs_attrs[] for charge attribute * Parameters: NULL * return value: NULL **********************************************************/ static void charge_sysfs_init_attrs(void) { int i, limit = ARRAY_SIZE(charge_sysfs_field_tbl); for (i = 0; i < limit; i++) { charge_sysfs_attrs[i] = &charge_sysfs_field_tbl[i].attr.attr; } charge_sysfs_attrs[limit] = NULL; /* Has additional entry for this */ } /********************************************************** * Function: charge_sysfs_field_lookup * Discription: get the current device_attribute from charge_sysfs_field_tbl by attr's name * Parameters: name:device attribute name * return value: charge_sysfs_field_tbl[] **********************************************************/ static struct charge_sysfs_field_info *charge_sysfs_field_lookup(const char *name) { int i, limit = ARRAY_SIZE(charge_sysfs_field_tbl); for (i = 0; i < limit; i++) { if (!strncmp(name, charge_sysfs_field_tbl[i].attr.attr.name,strlen(name))) break; } if (i >= limit) return NULL; return &charge_sysfs_field_tbl[i]; } /********************************************************** * Function: charge_sysfs_show * Discription: show the value for all charge device's node * Parameters: dev:device * attr:device_attribute * buf:string of node value * return value: 0-sucess or others-fail **********************************************************/ static ssize_t charge_sysfs_show(struct device *dev, struct device_attribute *attr, char *buf) { struct charge_sysfs_field_info *info = NULL; struct charge_device_info *di = dev_get_drvdata(dev); int ret; info = charge_sysfs_field_lookup(attr->attr.name); if (!info) return -EINVAL; switch(info->name){ case CHARGE_SYSFS_IIN_THERMAL: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.iin_thl); case CHARGE_SYSFS_ICHG_THERMAL: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.ichg_thl); case CHARGE_SYSFS_IIN_RUNNINGTEST: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.iin_rt); case CHARGE_SYSFS_ICHG_RUNNINGTEST: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.ichg_rt); case CHARGE_SYSFS_ENABLE_CHARGER: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.charge_enable); case CHARGE_SYSFS_LIMIT_CHARGING: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.charge_limit); case CHARGE_SYSFS_REGULATION_VOLTAGE: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.vterm_rt); case CHARGE_SYSFS_BATFET_DISABLE: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.batfet_disable); case CHARGE_SYSFS_WATCHDOG_DISABLE: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.wdt_disable); case CHARGE_SYSFS_CHARGELOG: mutex_lock(&di->sysfs_data.dump_reg_lock); di->ops->dump_register(di->sysfs_data.reg_value); ret = snprintf(buf,PAGE_SIZE, "%s\n", di->sysfs_data.reg_value); mutex_unlock(&di->sysfs_data.dump_reg_lock); return ret; case CHARGE_SYSFS_CHARGELOG_HEAD: mutex_lock(&di->sysfs_data.dump_reg_head_lock); di->ops->get_register_head(di->sysfs_data.reg_head); ret = snprintf(buf,PAGE_SIZE, "%s\n", di->sysfs_data.reg_head); mutex_unlock(&di->sysfs_data.dump_reg_head_lock); return ret; case CHARGE_SYSFS_IBUS: di->sysfs_data.ibus = 0; if (di->ops->get_ibus) //this is an optional interface for charger { di->sysfs_data.ibus = di->ops->get_ibus(); } return snprintf(buf,PAGE_SIZE, "%d\n", di->sysfs_data.ibus); case CHARGE_SYSFS_HIZ: return snprintf(buf,PAGE_SIZE, "%u\n", di->sysfs_data.hiz_enable); case CHARGE_SYSFS_CHARGE_TYPE: return snprintf(buf,PAGE_SIZE, "%d\n", di->charger_type); case CHARGE_SYSFS_BOOTLOADER_CHARGER_INFO: mutex_lock(&di->sysfs_data.bootloader_info_lock); if(hisi_charger_info.info_vaild) { dump_bootloader_info(di->sysfs_data.bootloader_info); ret = snprintf(buf,PAGE_SIZE, "%s\n", di->sysfs_data.bootloader_info); } else { ret = snprintf(buf,PAGE_SIZE, "\n"); } mutex_unlock(&di->sysfs_data.bootloader_info_lock); return ret; default: hwlog_err("(%s)NODE ERR!!HAVE NO THIS NODE:(%d)\n",__func__,info->name); break; } return 0; } /********************************************************** * Function: charge_sysfs_store * Discription: set the value for charge_data's node which is can be written * Parameters: dev:device * attr:device_attribute * buf:string of node value * count:unused * return value: 0-sucess or others-fail **********************************************************/ static ssize_t charge_sysfs_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct charge_sysfs_field_info *info = NULL; struct charge_device_info *di = dev_get_drvdata(dev); long val = 0; enum charge_status_event events = VCHRG_POWER_NONE_EVENT; info = charge_sysfs_field_lookup(attr->attr.name); if (!info) return -EINVAL; switch(info->name){ /*NOTICE: it will be charging with default current when the current node has been set to 0/1, include iin_thermal/ichg_thermal/iin_runningtest/ichg_runningtest node */ case CHARGE_SYSFS_IIN_THERMAL: /*CONFIG_OVERHEATVER is only for high temperature runningtest. we do not want charge current limited by non-battery temperature. */ #ifndef CONFIG_HLTHERM_RUNTEST if((strict_strtol(buf, 10, &val) < 0)||(val < 0)||(val > 3000)) return -EINVAL; if((val == 0)||(val == 1)) di->sysfs_data.iin_thl = di->core_data->iin_max; else if((val > 1)&&(val <= 100)) di->sysfs_data.iin_thl = 100; else di->sysfs_data.iin_thl = val; if(di->input_current > di->sysfs_data.iin_thl) di->ops->set_input_current(di->sysfs_data.iin_thl); hwlog_info("THERMAL set input current = %d\n", di->sysfs_data.iin_thl); #endif break; case CHARGE_SYSFS_ICHG_THERMAL: #ifndef CONFIG_HLTHERM_RUNTEST if((strict_strtol(buf, 10, &val) < 0)||(val < 0)||(val > 3000)) return -EINVAL; if((val == 0)||(val == 1)) di->sysfs_data.ichg_thl = di->core_data->ichg_max; else if((val > 1)&&(val <= 205)) di->sysfs_data.ichg_thl = 205; else di->sysfs_data.ichg_thl = val; if(di->charge_current > di->sysfs_data.ichg_thl) di->ops->set_charge_current(di->sysfs_data.ichg_thl); hwlog_info("THERMAL set charge current = %d\n", di->sysfs_data.ichg_thl); #endif break; case CHARGE_SYSFS_IIN_RUNNINGTEST: if((strict_strtol(buf, 10, &val) < 0)||(val < 0)||(val > 3000)) return -EINVAL; if((val == 0)||(val == 1)) di->sysfs_data.iin_rt = di->core_data->iin_max; else if((val > 1)&&(val <= 100)) di->sysfs_data.iin_rt = 100; else di->sysfs_data.iin_rt = val; if(di->input_current > di->sysfs_data.iin_rt) di->ops->set_input_current(di->sysfs_data.iin_rt); hwlog_info("RUNNINGTEST set input current = %d\n", di->sysfs_data.iin_rt); break; case CHARGE_SYSFS_ICHG_RUNNINGTEST: if((strict_strtol(buf, 10, &val) < 0)||(val < 0)||(val > 3000)) return -EINVAL; if((val == 0)||(val == 1)) di->sysfs_data.ichg_rt = di->core_data->ichg_max; else if((val > 1)&&(val <= 205)) di->sysfs_data.ichg_rt = 205; else di->sysfs_data.ichg_rt = val; if(di->charge_current > di->sysfs_data.ichg_rt) di->ops->set_charge_current(di->sysfs_data.ichg_rt); hwlog_info("RUNNINGTEST set input current = %d\n", di->sysfs_data.ichg_rt); break; case CHARGE_SYSFS_ENABLE_CHARGER: if ((strict_strtol(buf, 10, &val) < 0) || (val < 0) || (val > 1)) return -EINVAL; di->sysfs_data.charge_enable = val; di->sysfs_data.charge_limit = TRUE; /*why should send events in this command? because it will get the /sys/class/power_supply/Battery/status immediately to check if the enable/disable command set successfully or not in some product line station */ if(di->sysfs_data.charge_enable) { events = VCHRG_START_CHARGING_EVENT; } else { events = VCHRG_NOT_CHARGING_EVENT; } di->ops->set_charge_enable(di->sysfs_data.charge_enable); hisi_coul_charger_event_rcv(events); hwlog_info("RUNNINGTEST set charge enable = %d\n", di->sysfs_data.charge_enable); break; case CHARGE_SYSFS_LIMIT_CHARGING: if ((strict_strtol(buf, 10, &val) < 0) || (val < 0) || (val > 1)) return -EINVAL; di->sysfs_data.charge_limit = val; hwlog_info("PROJECTMUNE set limit charge enable = %d\n", di->sysfs_data.charge_limit); break; case CHARGE_SYSFS_REGULATION_VOLTAGE: if((strict_strtol(buf, 10, &val) < 0)||(val < 3200)||(val > 4400)) return -EINVAL; di->sysfs_data.vterm_rt = val; di->ops->set_terminal_voltage(di->sysfs_data.vterm_rt); hwlog_info("RUNNINGTEST set terminal voltage = %d\n", di->sysfs_data.vterm_rt); break; case CHARGE_SYSFS_BATFET_DISABLE: if ((strict_strtol(buf, 10, &val) < 0) || (val < 0) || (val > 1)) return -EINVAL; di->sysfs_data.batfet_disable = val; if (1 == val) di->ops->set_input_current(CHARGE_CURRENT_2000_MA); di->ops->set_batfet_disable(di->sysfs_data.batfet_disable); hwlog_info("RUNNINGTEST set batfet disable = %d\n", di->sysfs_data.batfet_disable); break; case CHARGE_SYSFS_WATCHDOG_DISABLE: if ((strict_strtol(buf, 10, &val) < 0) || (val < 0) || (val > 1)) return -EINVAL; di->sysfs_data.wdt_disable = val; if(val == 1) di->ops->set_watchdog_timer(WATCHDOG_TIMER_DISABLE); hwlog_info("RUNNINGTEST set wdt disable = %d\n", di->sysfs_data.wdt_disable); break; case CHARGE_SYSFS_HIZ: if ((strict_strtol(buf, 10, &val) < 0) || (val < 0) || (val > 1)) return -EINVAL; di->sysfs_data.hiz_enable= val; if (di->ops->set_charger_hiz) di->ops->set_charger_hiz(di->sysfs_data.hiz_enable); hwlog_info("RUNNINGTEST set hiz enable = %d\n", di->sysfs_data.hiz_enable); break; default: hwlog_err("(%s)NODE ERR!!HAVE NO THIS NODE:(%d)\n",__func__,info->name); break; } return count; } /********************************************************** * Function: charge_check_charger_plugged * Discription: detect whether USB or adaptor is plugged * Parameters: NULL * return value: 1 means USB or adpator plugged * 0 means USB or adaptor not plugged * -1 means chargeIC not support this function **********************************************************/ int charge_check_charger_plugged(void) { if (NULL == g_ops || NULL == g_ops->check_charger_plugged) { return -1; } return g_ops->check_charger_plugged(); } /********************************************************** * Function: charge_sysfs_create_group * Discription: create the charge device sysfs group * Parameters: di:charge_device_info * return value: 0-sucess or others-fail **********************************************************/ static int charge_sysfs_create_group(struct charge_device_info *di) { charge_sysfs_init_attrs(); return sysfs_create_group(&di->dev->kobj, &charge_sysfs_attr_group); } /********************************************************** * Function: charge_sysfs_remove_group * Discription: remove the charge device sysfs group * Parameters: di:charge_device_info * return value: NULL **********************************************************/ static inline void charge_sysfs_remove_group(struct charge_device_info *di) { sysfs_remove_group(&di->dev->kobj, &charge_sysfs_attr_group); } #else static int charge_sysfs_create_group(struct charge_device_info *di) { return 0; } static inline void charge_sysfs_remove_group(struct charge_device_info *di) {} #endif /********************************************************** * Function: charge_ops_register * Discription: register the handler ops for chargerIC * Parameters: ops:operations interface of charge device * return value: 0-sucess or others-fail **********************************************************/ int charge_ops_register(struct charge_device_ops *ops) { int ret = 0; if(ops != NULL) { g_ops = ops; } else { hwlog_err("charge ops register fail!\n"); ret = -EPERM; } return ret; } /********************************************************** * Function: fcp_adpter_ops_register * Discription: register the handler ops for fcp adpter * Parameters: ops:operations interface of fcp adpter * return value: 0-sucess or others-fail **********************************************************/ int fcp_adapter_ops_register(struct fcp_adapter_device_ops *ops) { int ret = 0; if(ops != NULL) { g_fcp_ops = ops; } else { hwlog_err("fcp ops register fail!\n"); ret = -EPERM; } return ret; } /********************************************************** * Function: charge_probe * Discription: chargre module probe * Parameters: pdev:platform_device * return value: 0-sucess or others-fail **********************************************************/ static int charge_probe(struct platform_device *pdev) { int ret = 0; struct charge_device_info *di; enum hisi_charger_type type = hisi_get_charger_type(); struct class *power_class = NULL; di = kzalloc(sizeof(*di), GFP_KERNEL); if (!di) { hwlog_err("alloc di failed\n"); return -ENOMEM; } di->core_data = (struct charge_core_data*)kzalloc(sizeof(struct charge_core_data), GFP_KERNEL); if (NULL == di->core_data) { hwlog_err("alloc di->core_data failed\n"); ret = -ENOMEM; goto charge_fail_0; } di->dev = &pdev->dev; di->ops = g_ops; di->fcp_ops = g_fcp_ops; if((di->ops->chip_init == NULL)||(di->ops->set_input_current == NULL) ||(di->ops->set_charge_current == NULL)||(di->ops->set_charge_enable == NULL) ||(di->ops->set_otg_enable == NULL)||(di->ops->set_terminal_current == NULL) ||(di->ops->set_terminal_voltage == NULL)||(di->ops->dump_register == NULL) ||(di->ops->get_charge_state == NULL)||(di->ops->reset_watchdog_timer == NULL) ||(di->ops->get_register_head == NULL)) { hwlog_err("charge ops is NULL!\n"); ret = -EINVAL; goto charge_fail_1; } ret = di->ops->chip_init(); if(ret) hwlog_err("[%s]chip init fail!!\n",__func__); di->core_data = charge_core_get_params(); platform_set_drvdata(pdev, di); wake_lock_init(&charge_lock, WAKE_LOCK_SUSPEND, "charge_wakelock"); wake_lock_init(&stop_charge_lock, WAKE_LOCK_SUSPEND, "stop_charge_wakelock"); INIT_DELAYED_WORK(&di->charge_work,charge_monitor_work); INIT_DELAYED_WORK(&di->otg_work,charge_otg_work); INIT_WORK(&di->usb_work, charge_usb_work); INIT_WORK(&di->fault_work, charge_fault_work); di->usb_nb.notifier_call = charge_usb_notifier_call; ret = hisi_charger_type_notifier_register(&di->usb_nb); if (ret < 0) { hwlog_err("hisi_charger_type_notifier_register failed\n"); goto charge_fail_2; } di->fault_nb.notifier_call = charge_fault_notifier_call; ret = atomic_notifier_chain_register(&fault_notifier_list, &di->fault_nb); if (ret < 0) { hwlog_err("charge_fault_register_notifier failed\n"); goto charge_fail_2; } di->sysfs_data.iin_thl = di->core_data->iin_max; di->sysfs_data.ichg_thl = di->core_data->ichg_max; di->sysfs_data.iin_rt = di->core_data->iin_max; di->sysfs_data.ichg_rt = di->core_data->ichg_max; di->sysfs_data.vterm_rt = hisi_battery_vbat_max(); di->sysfs_data.charge_enable = TRUE; di->sysfs_data.batfet_disable = FALSE; di->sysfs_data.wdt_disable= FALSE; di->sysfs_data.charge_limit = TRUE; di->sysfs_data.hiz_enable= FALSE; mutex_init(&di->sysfs_data.dump_reg_lock); mutex_init(&di->sysfs_data.dump_reg_head_lock); mutex_init(&di->sysfs_data.bootloader_info_lock); di->charge_fault = CHARGE_FAULT_NON; di->check_full_count = 0; charge_rename_charger_type(type,di); charge_send_uevent(di); schedule_work(&di->usb_work); #ifdef CONFIG_HUAWEI_HW_DEV_DCT /* detect current device successful, set the flag as present */ set_hw_dev_flag(DEV_I2C_CHARGER); #endif ret = charge_sysfs_create_group(di); if (ret) hwlog_err("can't create charge sysfs entries\n"); power_class = hw_power_get_class(); if(power_class) { if(charge_dev == NULL) charge_dev = device_create(power_class, NULL, 0, NULL,"charger"); ret = sysfs_create_link(&charge_dev->kobj, &di->dev->kobj, "charge_data"); if(ret) { hwlog_err("create link to charge_data fail.\n"); goto charge_fail_3; } } copy_bootloader_charger_info(); hwlog_info("huawei charger probe ok!\n"); return 0; charge_fail_3: charge_sysfs_remove_group(di); charge_fail_2: wake_lock_destroy(&charge_lock); wake_lock_destroy(&stop_charge_lock); charge_fail_1: di->ops = NULL; charge_fail_0: platform_set_drvdata(pdev, NULL); kfree(di); di = NULL; return ret; } /********************************************************** * Function: charge_remove * Discription: charge module remove * Parameters: pdev:platform_device * return value: 0-sucess or others-fail **********************************************************/ static int charge_remove(struct platform_device *pdev) { struct charge_device_info *di = platform_get_drvdata(pdev); if (di == NULL) { hwlog_err("[%s]di is NULL!\n",__func__); return -ENODEV; } hisi_charger_type_notifier_unregister(&di->usb_nb); atomic_notifier_chain_unregister(&fault_notifier_list, &di->fault_nb); charge_sysfs_remove_group(di); wake_lock_destroy(&charge_lock); wake_lock_destroy(&stop_charge_lock); cancel_delayed_work(&di->charge_work); cancel_delayed_work(&di->otg_work); if (NULL != di->ops) { di->ops = NULL; g_ops = NULL; } if (NULL != di->fcp_ops) { di->fcp_ops = NULL; g_fcp_ops = NULL; } kfree(di); di = NULL; return 0; } /********************************************************** * Function: charge_shutdown * Discription: charge module shutdown * Parameters: pdev:platform_device * return value: NULL **********************************************************/ static void charge_shutdown(struct platform_device *pdev) { struct charge_device_info *di = platform_get_drvdata(pdev); int ret =0; hwlog_info("%s ++\n",__func__); if (NULL == di) { hwlog_err("[%s]di is NULL!\n",__func__); return; } ret = di->ops->set_otg_enable(FALSE); if(ret) { hwlog_err("[%s]set otg default fail!\n",__func__); } if (di->ops->set_charger_hiz) { ret = di->ops->set_charger_hiz(FALSE); if(ret) { hwlog_err("[%s]set charger hiz default fail!\n",__func__); } } hisi_charger_type_notifier_unregister(&di->usb_nb); atomic_notifier_chain_unregister(&fault_notifier_list, &di->fault_nb); cancel_delayed_work(&di->charge_work); cancel_delayed_work(&di->otg_work); hwlog_info("%s --\n",__func__); return; } #ifdef CONFIG_PM /********************************************************** * Function: charge_suspend * Discription: charge module suspend * Parameters: pdev:platform_device * state:unused * return value: 0-sucess or others-fail **********************************************************/ static int charge_suspend(struct platform_device *pdev, pm_message_t state) { struct charge_device_info *di = platform_get_drvdata(pdev); if(di->charger_source == POWER_SUPPLY_TYPE_MAINS) { if(charge_is_charging_full(di)) { if (!wake_lock_active(&charge_lock)) { cancel_delayed_work(&di->charge_work); } } } charge_kick_watchdog(di); return 0; } /********************************************************** * Function: charge_resume * Discription: charge module resume * Parameters: pdev:platform_device * return value: 0-sucess or others-fail **********************************************************/ static int charge_resume(struct platform_device *pdev) { struct charge_device_info *di = platform_get_drvdata(pdev); if(di->charger_source == POWER_SUPPLY_TYPE_MAINS) { schedule_delayed_work(&di->charge_work, msecs_to_jiffies(0)); } charge_kick_watchdog(di); return 0; } #endif /* CONFIG_PM */ static struct of_device_id charge_match_table[] = { { .compatible = "huawei,charger", .data = NULL, }, { }, }; static struct platform_driver charge_driver = { .probe = charge_probe, .remove = charge_remove, #ifdef CONFIG_PM .suspend = charge_suspend, .resume = charge_resume, #endif .shutdown = charge_shutdown, .driver = { .name = "huawei,charger", .owner = THIS_MODULE, .of_match_table = of_match_ptr(charge_match_table), }, }; /********************************************************** * Function: charge_init * Discription: charge module initialization * Parameters: NULL * return value: 0-sucess or others-fail **********************************************************/ static int __init charge_init(void) { return platform_driver_register(&charge_driver); } /********************************************************** * Function: charge_exit * Discription: charge module exit * Parameters: NULL * return value: NULL **********************************************************/ static void __exit charge_exit(void) { platform_driver_unregister(&charge_driver); } device_initcall_sync(charge_init); module_exit(charge_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("huawei charger module driver"); MODULE_AUTHOR("HUAWEI Inc");
XePeleato/ALE-L21_ESAL
drivers/huawei_platform/power/charger/huawei_charger.c
C
gpl-2.0
65,759
/* * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2015 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ ace.define('ace/snippets/objectivec', ['require', 'exports', 'module' ], function(require, exports, module) { exports.snippetText = ""; exports.scope = "objectivec"; });
hoangyen201201/TrienLamOnline
plugins/editors/rokpad/ace/snippets/objectivec.js
JavaScript
gpl-2.0
360
/******************************************************************************/ /* */ /* Copyright (c) International Business Machines Corp., 2001 */ /* */ /* 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 */ /* */ /******************************************************************************/ /******************************************************************************/ /* */ /* History: July - 02 - 2001 Created by Manoj Iyer, IBM Austin TX. */ /* email:manjo@austin.ibm.com */ /* */ /* July - 07 - 2001 Modified - changed MAP_PRIVATE to MAP_SHARED */ /* read defect 187 for details. */ /* */ /* July - 09 - 2001 Modified - added option to MAP_PRIVATE or */ /* MAP_SHARED, -p, default is to MAP_SHARED. */ /* */ /* July - 09 - 2001 Modified - added option '-a' MAP_ANONYMOUS. */ /* Default is to map a file. */ /* */ /* Aug - 01 - 2001 Modified - added option 'a' to getop list. */ /* */ /* Oct - 25 - 2001 Modified - changed scheme. Test will be run */ /* once unless -x option is used. */ /* */ /* Apr - 16 - 2003 Modified - replaced tempnam() use with */ /* mkstemp(). -Robbie Williamson */ /* email:robbiew@us.ibm.com */ /* */ /* May - 12 - 2003 Modified - remove the huge files when */ /* we are done with the test - Paul Larson */ /* email:plars@linuxtestproject.org */ /* File: mmap2.c */ /* */ /* Description: Test the LINUX memory manager. The program is aimed at */ /* stressing the memory manager by repeaded map/write/unmap of a */ /* of a large gb size file. */ /* */ /* Create a file of the specified size in gb, map the file, */ /* change the contents of the file and unmap it. This is repeated*/ /* several times for the specified number of hours. */ /* */ /******************************************************************************/ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <sys/mman.h> #include <sched.h> #include <stdlib.h> #include <signal.h> #include <sys/time.h> #include <sys/wait.h> #include <signal.h> #include <string.h> #include <getopt.h> #include "test.h" #include "usctest.h" #define GB 1000000000 #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif static int mkfile(int size) { int fd; int index = 0; char buff[4096]; char template[PATH_MAX]; memset(buff, 'a', 4096); snprintf(template, PATH_MAX, "ashfileXXXXXX"); fd = mkstemp(template); if (fd == -1) { perror("mkfile(): mkstemp()"); return -1; } else { unlink(template); fprintf(stdout, "creating tmp file and writing 'a' to it "); } while (index < (size * GB)) { index += 4096; if (write(fd, buff, 4096) == -1) { perror("mkfile(): write()"); return -1; } } fprintf(stdout, "created file of size %d\n" "content of the file is 'a'\n", index); if (fsync(fd) == -1) { perror("mkfile(): fsync()"); return -1; } return fd; } static void sig_handler(int signal) { if (signal != SIGALRM) { fprintf(stderr, "sig_handlder(): unexpected signal caught" "[%d]\n", signal); exit(-1); } else fprintf(stdout, "Test ended, success\n"); exit(0); } static void usage(char *progname) { fprintf(stderr, "Usage: %s -h -s -x\n" "\t -a set map_flags to MAP_ANONYMOUS\n" "\t -h help, usage message.\n" "\t -p set map_flag to MAP_PRIVATE.\tdefault:" "MAP_SHARED\n" "\t -s size of the file/memory to be mmaped.\tdefault:" "1GB\n" "\t -x time for which test is to be run.\tdefault:" "24 Hrs\n", progname); exit(-1); } int main(int argc, char **argv) { int fd; int fsize = 1; float exec_time = 24; int c; int sig_ndx; int map_flags = MAP_SHARED; int map_anon = FALSE; int run_once = TRUE; char *memptr; struct sigaction sigptr; static struct signal_info { int signum; char *signame; } sig_info[] = { { SIGHUP, "SIGHUP"}, { SIGINT, "SIGINT"}, { SIGQUIT, "SIGQUIT"}, { SIGABRT, "SIGABRT"}, { SIGBUS, "SIGBUS"}, { SIGSEGV, "SIGSEGV"}, { SIGALRM, "SIGALRM"}, { SIGUSR1, "SIGUSR1"}, { SIGUSR2, "SIGUSR2"}, { -1, "ENDSIG"} }; while ((c = getopt(argc, argv, "ahps:x:")) != -1) { switch (c) { case 'a': map_anon = TRUE; break; case 'h': usage(argv[0]); exit(-1); break; case 'p': map_flags = MAP_PRIVATE; break; case 's': fsize = atoi(optarg); if (fsize == 0) fprintf(stderr, "Using default " "fsize %d GB\n", fsize = 1); break; case 'x': exec_time = atof(optarg); if (exec_time == 0) fprintf(stderr, "Using default exec " "time %f hrs", exec_time = (float)24); run_once = FALSE; break; default: usage(argv[0]); break; } } fprintf(stdout, "MM Stress test, map/write/unmap large file\n" "\tTest scheduled to run for: %f\n" "\tSize of temp file in GB: %d\n", exec_time, fsize); alarm(exec_time * 3600.00); sigptr.sa_handler = sig_handler; sigfillset(&sigptr.sa_mask); sigptr.sa_flags = 0; for (sig_ndx = 0; sig_info[sig_ndx].signum != -1; sig_ndx++) { sigaddset(&sigptr.sa_mask, sig_info[sig_ndx].signum); if (sigaction(sig_info[sig_ndx].signum, &sigptr, NULL) == -1) { perror("man(): sigaction()"); fprintf(stderr, "could not set handler for SIGALRM," "errno = %d\n", errno); exit(-1); } } do { if (!map_anon) { fd = mkfile(fsize); if (fd == -1) { fprintf(stderr, "main(): mkfile(): Failed " "to create temp file.\n"); exit(-1); } } else { fd = -1; map_flags = map_flags | MAP_ANONYMOUS; } memptr = mmap(0, (fsize * GB), PROT_READ | PROT_WRITE, map_flags, fd, 0); if (memptr == MAP_FAILED) { perror("main(): mmap()"); exit(-1); } else fprintf(stdout, "file mapped at %p\n" "changing file content to 'A'\n", memptr); memset(memptr, 'A', ((fsize * GB) / sizeof(char))); if (msync(memptr, ((fsize * GB) / sizeof(char)), MS_SYNC | MS_INVALIDATE) == -1) { perror("main(): msync()"); exit(-1); } if (munmap(memptr, (fsize * GB) / sizeof(char)) == -1) { perror("main(): munmap()"); exit(-1); } else fprintf(stdout, "unmapped file at %p\n", memptr); close(fd); sync(); } while (TRUE && !run_once); exit(0); }
heluxie/LTP
testcases/kernel/mem/mtest06/mmap2.c
C
gpl-2.0
7,424
/**************************************************************************/ /*! @File @Title Server side Display Class functions @Copyright Copyright (c) Imagination Technologies Ltd. All Rights Reserved @Description Implements the server side functions of the Display Class interface. @License Dual MIT/GPLv2 The contents of this file are subject to the MIT license as set out below. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 ("GPL") in which case the provisions of GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of GPL, and not to allow others to use your version of this file under the terms of the MIT license, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by GPL as set out in the file called "GPL-COPYING" included in this distribution. If you do not delete the provisions above, a recipient may use your version of this file under the terms of either the MIT license or GPL. This License is also included in this distribution in the file called "MIT-COPYING". EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /***************************************************************************/ #include "allocmem.h" #include "lock.h" #include "osfunc.h" #include "img_types.h" #include "scp.h" #include "dc_server.h" #include "kerneldisplay.h" #include "pvr_debug.h" #include "pmr.h" #include "pdump_physmem.h" #include "sync_server.h" #include "pvrsrv.h" #include "debug_request_ids.h" #if defined(PVR_RI_DEBUG) #include "ri_server.h" #endif struct _DC_DISPLAY_CONTEXT_ { DC_DEVICE *psDevice; SCP_CONTEXT *psSCPContext; IMG_HANDLE hDisplayContext; IMG_UINT32 ui32ConfigsInFlight; IMG_UINT32 ui32RefCount; POS_LOCK hLock; IMG_UINT32 ui32TokenOut; IMG_UINT32 ui32TokenIn; IMG_HANDLE hCmdCompNotify; IMG_BOOL bIssuedNullFlip; IMG_HANDLE hMISR; IMG_HANDLE hDebugNotify; IMG_PVOID hTimer; }; struct _DC_DEVICE_ { const DC_DEVICE_FUNCTIONS *psFuncTable; IMG_UINT32 ui32MaxConfigsInFlight; IMG_HANDLE hDeviceData; IMG_UINT32 ui32RefCount; POS_LOCK hLock; IMG_UINT32 ui32Index; IMG_HANDLE psEventList; IMG_HANDLE hSystemBuffer; PMR *psSystemBufferPMR; DC_DISPLAY_CONTEXT sSystemContext; DC_DEVICE *psNext; }; typedef enum _DC_BUFFER_TYPE_ { DC_BUFFER_TYPE_UNKNOWN = 0, DC_BUFFER_TYPE_ALLOC, DC_BUFFER_TYPE_IMPORT, DC_BUFFER_TYPE_SYSTEM, } DC_BUFFER_TYPE; typedef struct _DC_BUFFER_ALLOC_DATA_ { PMR *psPMR; } DC_BUFFER_ALLOC_DATA; typedef struct _DC_BUFFER_IMPORT_DATA_ { /* Required as the DC doesn't need to map the PMR during the import call we need to make sure that the PMR doesn't get freed before the DC maps it by taking an ref on the PMR during the import and drop it on the unimport. */ IMG_UINT32 ui32NumPlanes; PMR *apsImport[3]; } DC_BUFFER_IMPORT_DATA; struct _DC_BUFFER_ { DC_DISPLAY_CONTEXT *psDisplayContext; DC_BUFFER_TYPE eType; union { DC_BUFFER_ALLOC_DATA sAllocData; DC_BUFFER_IMPORT_DATA sImportData; } uBufferData; IMG_HANDLE hBuffer; IMG_UINT32 ui32MapCount; IMG_UINT32 ui32RefCount; POS_LOCK hLock; POS_LOCK hMapLock; }; typedef struct _DC_CMD_RDY_DATA_ { DC_DISPLAY_CONTEXT *psDisplayContext; IMG_UINT32 ui32BufferCount; PVRSRV_SURFACE_CONFIG_INFO *pasSurfAttrib; IMG_HANDLE *pahBuffer; IMG_UINT32 ui32DisplayPeriod; } DC_CMD_RDY_DATA; typedef struct _DC_CMD_COMP_DATA_ { DC_DISPLAY_CONTEXT *psDisplayContext; IMG_UINT32 ui32BufferCount; DC_BUFFER **apsBuffer; IMG_UINT32 ui32Token; } DC_CMD_COMP_DATA; typedef struct _DC_BUFFER_PMR_DATA_ { DC_BUFFER *psBuffer; /*!< The buffer this PMR private data refers to */ IMG_DEVMEM_LOG2ALIGN_T uiLog2PageSize; /*!< Log 2 of the buffers pagesize */ IMG_UINT32 ui32PageCount; /*!< Number of pages in this buffer */ PHYS_HEAP *psPhysHeap; /*!< The physical heap the memory resides on */ IMG_DEV_PHYADDR *pasDevPAddr; /*!< Pointer to an array of device physcial addresses */ IMG_PVOID pvLinAddr; /*!< CPU virtual pointer or NULL if the DC driver didn't have one */ IMG_HANDLE hPDumpAllocInfo; /*!< Handle to PDump alloc data */ IMG_BOOL bPDumpMalloced; /*!< Did we get as far as PDump alloc? */ } DC_BUFFER_PMR_DATA; POS_LOCK g_hDCListLock; DC_DEVICE *g_psDCDeviceList; IMG_UINT32 g_ui32DCDeviceCount; IMG_UINT32 g_ui32DCNextIndex; #if defined(DC_DEBUG) && defined(REFCOUNT_DEBUG) #define DC_REFCOUNT_PRINT(fmt, ...) \ PVRSRVDebugPrintf(PVR_DBG_WARNING, \ __FILE__, \ __LINE__, \ fmt, \ __VA_ARGS__) #else #define DC_REFCOUNT_PRINT(fmt, ...) #endif #if defined(DC_DEBUG) #define DC_DEBUG_PRINT(fmt, ...) \ PVRSRVDebugPrintf(PVR_DBG_WARNING, \ __FILE__, \ __LINE__, \ fmt, \ __VA_ARGS__) #else #define DC_DEBUG_PRINT(fmt, ...) #endif /***************************************************************************** * Private functions * *****************************************************************************/ static IMG_VOID _DCDeviceAcquireRef(DC_DEVICE *psDevice) { OSLockAcquire(psDevice->hLock); psDevice->ui32RefCount++; DC_REFCOUNT_PRINT("%s: DC device %p, refcount = %d", __FUNCTION__, psDevice, psDevice->ui32RefCount); OSLockRelease(psDevice->hLock); } static IMG_VOID _DCDeviceReleaseRef(DC_DEVICE *psDevice) { IMG_UINT32 ui32RefCount; OSLockAcquire(psDevice->hLock); ui32RefCount = --psDevice->ui32RefCount; OSLockRelease(psDevice->hLock); if (ui32RefCount == 0) { OSLockAcquire(g_hDCListLock); if (psDevice == g_psDCDeviceList) { g_psDCDeviceList = psDevice->psNext; } else { DC_DEVICE *psTmp = g_psDCDeviceList; while (psTmp->psNext != psDevice) { psTmp = psTmp->psNext; } psTmp->psNext = g_psDCDeviceList->psNext; } g_ui32DCDeviceCount--; OSLockRelease(g_hDCListLock); } else { /* Signal this devices event list as the unload might be blocked on it */ OSEventObjectSignal(psDevice->psEventList); } DC_REFCOUNT_PRINT("%s: DC device %p, refcount = %d", __FUNCTION__, psDevice, ui32RefCount); } static IMG_VOID _DCDisplayContextAcquireRef(DC_DISPLAY_CONTEXT *psDisplayContext) { OSLockAcquire(psDisplayContext->hLock); psDisplayContext->ui32RefCount++; DC_REFCOUNT_PRINT("%s: DC display context %p, refcount = %d", __FUNCTION__, psDisplayContext, psDisplayContext->ui32RefCount); OSLockRelease(psDisplayContext->hLock); } static IMG_VOID _DCDisplayContextReleaseRef(DC_DISPLAY_CONTEXT *psDisplayContext) { IMG_UINT32 ui32RefCount; OSLockAcquire(psDisplayContext->hLock); ui32RefCount = --psDisplayContext->ui32RefCount; OSLockRelease(psDisplayContext->hLock); if (ui32RefCount == 0) { DC_DEVICE *psDevice = psDisplayContext->psDevice; PVRSRVUnregisterDbgRequestNotify(psDisplayContext->hDebugNotify); /* unregister the device from cmd complete notifications */ PVRSRVUnregisterCmdCompleteNotify(psDisplayContext->hCmdCompNotify); psDisplayContext->hCmdCompNotify = IMG_NULL; OSUninstallMISR(psDisplayContext->hMISR); SCPDestroy(psDisplayContext->psSCPContext); psDevice->psFuncTable->pfnContextDestroy(psDisplayContext->hDisplayContext); _DCDeviceReleaseRef(psDevice); OSLockDestroy(psDisplayContext->hLock); OSFreeMem(psDisplayContext); } DC_REFCOUNT_PRINT("%s: DC display context %p, refcount = %d", __FUNCTION__, psDisplayContext, ui32RefCount); } static IMG_VOID _DCBufferAcquireRef(DC_BUFFER *psBuffer) { OSLockAcquire(psBuffer->hLock); psBuffer->ui32RefCount++; DC_REFCOUNT_PRINT("%s: DC buffer %p, refcount = %d", __FUNCTION__, psBuffer, psBuffer->ui32RefCount); OSLockRelease(psBuffer->hLock); } static IMG_VOID _DCFreeAllocedBuffer(DC_BUFFER *psBuffer) { DC_DISPLAY_CONTEXT *psDisplayContext = psBuffer->psDisplayContext; DC_DEVICE *psDevice = psDisplayContext->psDevice; psDevice->psFuncTable->pfnBufferFree(psBuffer->hBuffer); _DCDisplayContextReleaseRef(psDisplayContext); } static IMG_VOID _DCFreeImportedBuffer(DC_BUFFER *psBuffer) { DC_DISPLAY_CONTEXT *psDisplayContext = psBuffer->psDisplayContext; DC_DEVICE *psDevice = psDisplayContext->psDevice; IMG_UINT32 i; for (i=0;i<psBuffer->uBufferData.sImportData.ui32NumPlanes;i++) { PMRUnrefPMR(psBuffer->uBufferData.sImportData.apsImport[i]); } psDevice->psFuncTable->pfnBufferFree(psBuffer->hBuffer); _DCDisplayContextReleaseRef(psDisplayContext); } static IMG_VOID _DCFreeSystemBuffer(DC_BUFFER *psBuffer) { DC_DISPLAY_CONTEXT *psDisplayContext = psBuffer->psDisplayContext; DC_DEVICE *psDevice = psDisplayContext->psDevice; psDevice->psFuncTable->pfnBufferSystemRelease(psBuffer->hBuffer); _DCDeviceReleaseRef(psDevice); } /* Drop a reference on the buffer. Last person gets to free it */ static IMG_VOID _DCBufferReleaseRef(DC_BUFFER *psBuffer) { IMG_UINT32 ui32RefCount; OSLockAcquire(psBuffer->hLock); ui32RefCount = --psBuffer->ui32RefCount; OSLockRelease(psBuffer->hLock); if (ui32RefCount == 0) { switch (psBuffer->eType) { case DC_BUFFER_TYPE_ALLOC: _DCFreeAllocedBuffer(psBuffer); break; case DC_BUFFER_TYPE_IMPORT: _DCFreeImportedBuffer(psBuffer); break; case DC_BUFFER_TYPE_SYSTEM: _DCFreeSystemBuffer(psBuffer); break; default: PVR_ASSERT(IMG_FALSE); } OSLockDestroy(psBuffer->hMapLock); OSLockDestroy(psBuffer->hLock); OSFreeMem(psBuffer); } DC_REFCOUNT_PRINT("%s: DC buffer %p, refcount = %d", __FUNCTION__, psBuffer, ui32RefCount); } static PVRSRV_ERROR _DCBufferMap(DC_BUFFER *psBuffer) { PVRSRV_ERROR eError = PVRSRV_OK; OSLockAcquire(psBuffer->hMapLock); if (psBuffer->ui32MapCount++ == 0) { DC_DEVICE *psDevice = psBuffer->psDisplayContext->psDevice; if(psDevice->psFuncTable->pfnBufferMap) { eError = psDevice->psFuncTable->pfnBufferMap(psBuffer->hBuffer); if (eError != PVRSRV_OK) { goto out_unlock; } } _DCBufferAcquireRef(psBuffer); } DC_REFCOUNT_PRINT("%s: DC buffer %p, MapCount = %d", __FUNCTION__, psBuffer, psBuffer->ui32MapCount); out_unlock: OSLockRelease(psBuffer->hMapLock); return eError; } static IMG_VOID _DCBufferUnmap(DC_BUFFER *psBuffer) { DC_DEVICE *psDevice = psBuffer->psDisplayContext->psDevice; IMG_UINT32 ui32MapCount; OSLockAcquire(psBuffer->hMapLock); ui32MapCount = --psBuffer->ui32MapCount; OSLockRelease(psBuffer->hMapLock); if (ui32MapCount == 0) { if(psDevice->psFuncTable->pfnBufferUnmap) { psDevice->psFuncTable->pfnBufferUnmap(psBuffer->hBuffer); } _DCBufferReleaseRef(psBuffer); } DC_REFCOUNT_PRINT("%s: DC Buffer %p, MapCount = %d", __FUNCTION__, psBuffer, ui32MapCount); } static PVRSRV_ERROR _DCDeviceBufferArrayCreate(IMG_UINT32 ui32BufferCount, DC_BUFFER **papsBuffers, IMG_HANDLE **pahDeviceBuffers) { IMG_HANDLE *ahDeviceBuffers; IMG_UINT32 i; /* Create an array of the DC's private Buffer handles */ ahDeviceBuffers = OSAllocMem(sizeof(IMG_HANDLE) * ui32BufferCount); if (ahDeviceBuffers == IMG_NULL) { return PVRSRV_ERROR_OUT_OF_MEMORY; } OSMemSet(ahDeviceBuffers, 0, sizeof(IMG_HANDLE) * ui32BufferCount); for (i=0;i<ui32BufferCount;i++) { ahDeviceBuffers[i] = papsBuffers[i]->hBuffer; } *pahDeviceBuffers = ahDeviceBuffers; return PVRSRV_OK; } static IMG_VOID _DCDeviceBufferArrayDestroy(IMG_HANDLE ahDeviceBuffers) { OSFreeMem(ahDeviceBuffers); } static IMG_BOOL _DCDisplayContextReady(IMG_PVOID hReadyData) { DC_CMD_RDY_DATA *psReadyData = (DC_CMD_RDY_DATA *) hReadyData; DC_DISPLAY_CONTEXT *psDisplayContext = psReadyData->psDisplayContext; DC_DEVICE *psDevice = psDisplayContext->psDevice; if (psDisplayContext->ui32ConfigsInFlight >= psDevice->ui32MaxConfigsInFlight) { /* We're at the DC's max commands in-flight so don't take this command off the queue */ return IMG_FALSE; } return IMG_TRUE; } #if defined SUPPORT_DC_COMPLETE_TIMEOUT_DEBUG static IMG_VOID _RetireTimeout(IMG_PVOID pvData) { DC_CMD_COMP_DATA *psCompleteData = pvData; DC_DISPLAY_CONTEXT *psDisplayContext = psCompleteData->psDisplayContext; PVR_DPF((PVR_DBG_ERROR, "Timeout fired for operation %d", psCompleteData->ui32Token)); SCPDumpStatus(psDisplayContext->psSCPContext); OSDisableTimer(psDisplayContext->hTimer); OSRemoveTimer(psDisplayContext->hTimer); psDisplayContext->hTimer = IMG_NULL; } #endif /* SUPPORT_DC_COMPLETE_TIMEOUT_DEBUG */ static IMG_VOID _DCDisplayContextConfigure(IMG_PVOID hReadyData, IMG_PVOID hCompleteData) { DC_CMD_RDY_DATA *psReadyData = (DC_CMD_RDY_DATA *) hReadyData; DC_DISPLAY_CONTEXT *psDisplayContext = psReadyData->psDisplayContext; DC_DEVICE *psDevice = psDisplayContext->psDevice; OSLockAcquire(psDisplayContext->hLock); psDisplayContext->ui32ConfigsInFlight++; #if defined SUPPORT_DC_COMPLETE_TIMEOUT_DEBUG if (psDisplayContext->ui32ConfigsInFlight == psDevice->ui32MaxConfigsInFlight) { /* We've just sent out a new config which has filled the DC's pipeline. This means that we expect a retire within a VSync period, start a timer that will print out a message if we haven't got a complete within a reasonable period (200ms) */ PVR_ASSERT(psDisplayContext->hTimer == IMG_NULL); psDisplayContext->hTimer = OSAddTimer(_RetireTimeout, hCompleteData, 200); OSEnableTimer(psDisplayContext->hTimer); } #endif OSLockRelease(psDisplayContext->hLock); #if defined(DC_DEBUG) { DC_DEBUG_PRINT("_DCDisplayContextConfigure: Send command (%d) out", ((DC_CMD_COMP_DATA*) hCompleteData)->ui32Token); } #endif /* DC_DEBUG */ /* Note: We've already done all the acquire refs at DCDisplayContextConfigure time. */ psDevice->psFuncTable->pfnContextConfigure(psDisplayContext->hDisplayContext, psReadyData->ui32BufferCount, psReadyData->pasSurfAttrib, psReadyData->pahBuffer, psReadyData->ui32DisplayPeriod, hCompleteData); } /* _DCDisplayContextRun Kick the MISR which will check for any commands which can be processed */ static INLINE IMG_VOID _DCDisplayContextRun(DC_DISPLAY_CONTEXT *psDisplayContext) { OSScheduleMISR(psDisplayContext->hMISR); } /* _DCDisplayContextMISR This gets called when this MISR is fired */ static IMG_VOID _DCDisplayContextMISR(IMG_VOID *pvData) { DC_DISPLAY_CONTEXT *psDisplayContext = pvData; SCPRun(psDisplayContext->psSCPContext); } /* * PMR related functions and structures */ /* Callback function for locking the system physical page addresses. As we acquire the display memory at PMR create time there is nothing to do here. */ static PVRSRV_ERROR _DCPMRLockPhysAddresses(PMR_IMPL_PRIVDATA pvPriv, IMG_UINT32 uiLog2DevPageSize) { DC_BUFFER_PMR_DATA *psPMRPriv = pvPriv; DC_BUFFER *psBuffer = psPMRPriv->psBuffer; DC_DEVICE *psDevice = psBuffer->psDisplayContext->psDevice; PVRSRV_ERROR eError; if (uiLog2DevPageSize < psPMRPriv->uiLog2PageSize) { eError = PVRSRV_ERROR_PMR_INCOMPATIBLE_CONTIGUITY; goto fail_contigcheck; } psPMRPriv->pasDevPAddr = OSAllocMem(sizeof(IMG_DEV_PHYADDR) * psPMRPriv->ui32PageCount); if (psPMRPriv->pasDevPAddr == IMG_NULL) { eError = PVRSRV_ERROR_OUT_OF_MEMORY; goto fail_alloc; } OSMemSet(psPMRPriv->pasDevPAddr, 0, sizeof(IMG_DEV_PHYADDR) * psPMRPriv->ui32PageCount); eError = psDevice->psFuncTable->pfnBufferAcquire(psBuffer->hBuffer, psPMRPriv->pasDevPAddr, &psPMRPriv->pvLinAddr); if (eError != PVRSRV_OK) { goto fail_query; } return PVRSRV_OK; fail_query: OSFreeMem(psPMRPriv->pasDevPAddr); fail_alloc: fail_contigcheck: return eError; } static PVRSRV_ERROR _DCPMRUnlockPhysAddresses(PMR_IMPL_PRIVDATA pvPriv) { DC_BUFFER_PMR_DATA *psPMRPriv = pvPriv; DC_BUFFER *psBuffer = psPMRPriv->psBuffer; DC_DEVICE *psDevice = psBuffer->psDisplayContext->psDevice; psDevice->psFuncTable->pfnBufferRelease(psBuffer->hBuffer); OSFreeMem(psPMRPriv->pasDevPAddr); return PVRSRV_OK; } static PVRSRV_ERROR _DCPMRDevPhysAddr(PMR_IMPL_PRIVDATA pvPriv, IMG_DEVMEM_OFFSET_T uiOffset, IMG_DEV_PHYADDR *psDevAddrPtr) { DC_BUFFER_PMR_DATA *psPMRPriv = pvPriv; IMG_UINT32 uiNumPages; IMG_UINT32 uiLog2PageSize; IMG_UINT32 uiPageSize; IMG_UINT32 uiPageIndex; IMG_UINT32 uiInPageOffset; IMG_DEV_PHYADDR sDevAddr; uiLog2PageSize = psPMRPriv->uiLog2PageSize; uiNumPages = psPMRPriv->ui32PageCount; uiPageSize = 1ULL << uiLog2PageSize; uiPageIndex = (IMG_UINT32)(uiOffset >> uiLog2PageSize); /* verify the cast */ /* N.B. Strictly... this could be triggered by an illegal uiOffset arg too. */ PVR_ASSERT((IMG_DEVMEM_OFFSET_T)uiPageIndex << uiLog2PageSize == uiOffset); uiInPageOffset = (IMG_UINT32)(uiOffset - ((IMG_DEVMEM_OFFSET_T)uiPageIndex << uiLog2PageSize)); PVR_ASSERT(uiOffset == ((IMG_DEVMEM_OFFSET_T)uiPageIndex << uiLog2PageSize) + uiInPageOffset); PVR_ASSERT(uiPageIndex < uiNumPages); PVR_ASSERT(uiInPageOffset < uiPageSize); sDevAddr.uiAddr = psPMRPriv->pasDevPAddr[uiPageIndex].uiAddr; PVR_ASSERT((sDevAddr.uiAddr & (uiPageSize - 1)) == 0); *psDevAddrPtr = sDevAddr; psDevAddrPtr->uiAddr += uiInPageOffset; return PVRSRV_OK; } static PVRSRV_ERROR _DCPMRFinalize(PMR_IMPL_PRIVDATA pvPriv) { DC_BUFFER_PMR_DATA *psPMRPriv = pvPriv; /* Conditionally do the PDump free, because if CreatePMR failed we won't have done the PDump MALLOC. */ if (psPMRPriv->bPDumpMalloced) { PDumpPMRFree(psPMRPriv->hPDumpAllocInfo); } PhysHeapRelease(psPMRPriv->psPhysHeap); _DCBufferReleaseRef(psPMRPriv->psBuffer); OSFreeMem(psPMRPriv); return PVRSRV_OK; } static PVRSRV_ERROR _DCPMRReadBytes(PMR_IMPL_PRIVDATA pvPriv, IMG_DEVMEM_OFFSET_T uiOffset, IMG_UINT8 *pcBuffer, IMG_SIZE_T uiBufSz, IMG_SIZE_T *puiNumBytes) { DC_BUFFER_PMR_DATA *psPMRPriv = pvPriv; IMG_CPU_PHYADDR sCpuPAddr; IMG_SIZE_T uiBytesCopied = 0; IMG_SIZE_T uiBytesToCopy = uiBufSz; IMG_SIZE_T uiBytesCopyableFromPage; IMG_VOID *pvMapping; IMG_UINT8 *pcKernelPointer; IMG_SIZE_T uiBufferOffset = 0; IMG_SIZE_T uiPageIndex; IMG_SIZE_T uiInPageOffset; /* If we already have a CPU mapping just us it */ if (psPMRPriv->pvLinAddr) { pcKernelPointer = psPMRPriv->pvLinAddr; OSMemCopy(pcBuffer, &pcKernelPointer[uiOffset], uiBufSz); *puiNumBytes = uiBufSz; return PVRSRV_OK; } /* Copy the data page by page */ while (uiBytesToCopy > 0) { /* we have to kmap one page in at a time */ uiPageIndex = TRUNCATE_64BITS_TO_SIZE_T(uiOffset >> psPMRPriv->uiLog2PageSize); uiInPageOffset = TRUNCATE_64BITS_TO_SIZE_T(uiOffset - ((IMG_DEVMEM_OFFSET_T)uiPageIndex << psPMRPriv->uiLog2PageSize)); uiBytesCopyableFromPage = uiBytesToCopy; if (uiBytesCopyableFromPage + uiInPageOffset > (1U<<psPMRPriv->uiLog2PageSize)) { uiBytesCopyableFromPage = (1 << psPMRPriv->uiLog2PageSize)-uiInPageOffset; } PhysHeapDevPAddrToCpuPAddr(psPMRPriv->psPhysHeap, &sCpuPAddr, &psPMRPriv->pasDevPAddr[uiPageIndex]); pvMapping = OSMapPhysToLin(sCpuPAddr, 1 << psPMRPriv->uiLog2PageSize, 0); PVR_ASSERT(pvMapping != IMG_NULL); pcKernelPointer = pvMapping; OSMemCopy(&pcBuffer[uiBufferOffset], &pcKernelPointer[uiInPageOffset], uiBytesCopyableFromPage); OSUnMapPhysToLin(pvMapping, 1 << psPMRPriv->uiLog2PageSize, 0); uiBufferOffset += uiBytesCopyableFromPage; uiBytesToCopy -= uiBytesCopyableFromPage; uiOffset += uiBytesCopyableFromPage; uiBytesCopied += uiBytesCopyableFromPage; } *puiNumBytes = uiBytesCopied; return PVRSRV_OK; } static PMR_IMPL_FUNCTAB sDCPMRFuncTab = { _DCPMRLockPhysAddresses, /* .pfnLockPhysAddresses */ _DCPMRUnlockPhysAddresses, /* .pfnUnlockPhysAddresses */ _DCPMRDevPhysAddr, /* .pfnDevPhysAddr */ IMG_NULL, /* .pfnPDumpSymbolicAddr */ IMG_NULL, /* .pfnAcquireKernelMappingData */ IMG_NULL, /* .pfnReleaseKernelMappingData */ _DCPMRReadBytes, /* .pfnReadBytes */ IMG_NULL, /* .pfnWriteBytes */ _DCPMRFinalize /* .pfnFinalize */ }; static PVRSRV_ERROR _DCCreatePMR(IMG_DEVMEM_LOG2ALIGN_T uiLog2PageSize, IMG_UINT32 ui32PageCount, IMG_UINT32 ui32PhysHeapID, DC_BUFFER *psBuffer, PMR **ppsPMR) { DC_BUFFER_PMR_DATA *psPMRPriv; PHYS_HEAP *psPhysHeap; IMG_DEVMEM_SIZE_T uiBufferSize; IMG_HANDLE hPDumpAllocInfo; PVRSRV_ERROR eError; IMG_BOOL bMappingTable = IMG_TRUE; /* Create the PMR for this buffer. Note: At this stage we don't need to know the physcial pages just the page size and the size of the PMR. The 1st call that needs the physcial pages will cause a request into the DC driver (pfnBufferQuery) */ psPMRPriv = OSAllocMem(sizeof(DC_BUFFER_PMR_DATA)); if (psPMRPriv == IMG_NULL) { eError = PVRSRV_ERROR_OUT_OF_MEMORY; goto fail_privalloc; } OSMemSet(psPMRPriv, 0, sizeof(DC_BUFFER_PMR_DATA)); /* Acquire the physical heap the memory is on */ eError = PhysHeapAcquire(ui32PhysHeapID, &psPhysHeap); if (eError != PVRSRV_OK) { goto fail_physheap; } /* Take a reference on the buffer (for the copy in the PMR) */ _DCBufferAcquireRef(psBuffer); /* Fill in the private data for the PMR */ psPMRPriv->uiLog2PageSize = uiLog2PageSize; psPMRPriv->ui32PageCount = ui32PageCount; psPMRPriv->psPhysHeap = psPhysHeap; psPMRPriv->pasDevPAddr = IMG_NULL; psPMRPriv->psBuffer = psBuffer; uiBufferSize = (1 << uiLog2PageSize) * ui32PageCount; /* Create the PMR for the MM layer */ eError = PMRCreatePMR(psPhysHeap, uiBufferSize, uiBufferSize, 1, 1, &bMappingTable, uiLog2PageSize, PVRSRV_MEMALLOCFLAG_WRITE_COMBINE, "DISPLAY", &sDCPMRFuncTab, psPMRPriv, ppsPMR, &hPDumpAllocInfo, IMG_TRUE); if (eError != PVRSRV_OK) { goto fail_pmrcreate; } #if defined(PDUMP) psPMRPriv->hPDumpAllocInfo = hPDumpAllocInfo; psPMRPriv->bPDumpMalloced = IMG_TRUE; #endif return PVRSRV_OK; fail_pmrcreate: PhysHeapRelease(psPhysHeap); fail_physheap: OSFreeMem(psPMRPriv); fail_privalloc: return eError; } static IMG_VOID _DCDisplayContextNotify(PVRSRV_CMDCOMP_HANDLE hCmdCompHandle) { DC_DISPLAY_CONTEXT *psDisplayContext = (DC_DISPLAY_CONTEXT*) hCmdCompHandle; _DCDisplayContextRun(psDisplayContext); } static IMG_VOID _DCDebugRequest(PVRSRV_DBGREQ_HANDLE hDebugRequestHandle, IMG_UINT32 ui32VerbLevel) { DC_DISPLAY_CONTEXT *psDisplayContext = (DC_DISPLAY_CONTEXT*) hDebugRequestHandle; switch(ui32VerbLevel) { case DEBUG_REQUEST_VERBOSITY_LOW: PVR_LOG(("Configs in-flight = %d", psDisplayContext->ui32ConfigsInFlight)); break; case DEBUG_REQUEST_VERBOSITY_MEDIUM: PVR_LOG(("Display context SCP status")); SCPDumpStatus(psDisplayContext->psSCPContext); break; default: break; } } /***************************************************************************** * Public interface functions exposed through the bridge to services client * *****************************************************************************/ PVRSRV_ERROR DCDevicesQueryCount(IMG_UINT32 *pui32DeviceCount) { *pui32DeviceCount = g_ui32DCDeviceCount; return PVRSRV_OK; } PVRSRV_ERROR DCDevicesEnumerate(IMG_UINT32 ui32DeviceArraySize, IMG_UINT32 *pui32DeviceCount, IMG_UINT32 *paui32DeviceIndex) { IMG_UINT32 i; IMG_UINT32 ui32LoopCount; DC_DEVICE *psTmp = g_psDCDeviceList; OSLockAcquire(g_hDCListLock); if (g_ui32DCDeviceCount > ui32DeviceArraySize) { ui32LoopCount = ui32DeviceArraySize; } else { ui32LoopCount = g_ui32DCDeviceCount; } for (i=0;i<ui32LoopCount;i++) { PVR_ASSERT(psTmp != IMG_NULL); paui32DeviceIndex[i] = psTmp->ui32Index; psTmp = psTmp->psNext; } *pui32DeviceCount = ui32LoopCount; OSLockRelease(g_hDCListLock); return PVRSRV_OK; } PVRSRV_ERROR DCDeviceAcquire(IMG_UINT32 ui32DeviceIndex, DC_DEVICE **ppsDevice) { DC_DEVICE *psDevice = g_psDCDeviceList; if (psDevice == IMG_NULL) { return PVRSRV_ERROR_NO_DC_DEVICES_FOUND; } while(psDevice->ui32Index != ui32DeviceIndex) { psDevice = psDevice->psNext; if (psDevice == IMG_NULL) { return PVRSRV_ERROR_NO_DC_DEVICES_FOUND; } } _DCDeviceAcquireRef(psDevice); *ppsDevice = psDevice; return PVRSRV_OK; } PVRSRV_ERROR DCDeviceRelease(DC_DEVICE *psDevice) { _DCDeviceReleaseRef(psDevice); return PVRSRV_OK; } PVRSRV_ERROR DCGetInfo(DC_DEVICE *psDevice, DC_DISPLAY_INFO *psDisplayInfo) { psDevice->psFuncTable->pfnGetInfo(psDevice->hDeviceData, psDisplayInfo); return PVRSRV_OK; } PVRSRV_ERROR DCPanelQueryCount(DC_DEVICE *psDevice, IMG_UINT32 *pui32NumPanels) { psDevice->psFuncTable->pfnPanelQueryCount(psDevice->hDeviceData, pui32NumPanels); return PVRSRV_OK; } PVRSRV_ERROR DCPanelQuery(DC_DEVICE *psDevice, IMG_UINT32 ui32PanelsArraySize, IMG_UINT32 *pui32NumPanels, PVRSRV_PANEL_INFO *pasPanelInfo) { psDevice->psFuncTable->pfnPanelQuery(psDevice->hDeviceData, ui32PanelsArraySize, pui32NumPanels, pasPanelInfo); return PVRSRV_OK; } PVRSRV_ERROR DCFormatQuery(DC_DEVICE *psDevice, IMG_UINT32 ui32FormatArraySize, PVRSRV_SURFACE_FORMAT *pasFormat, IMG_UINT32 *pui32Supported) { psDevice->psFuncTable->pfnFormatQuery(psDevice->hDeviceData, ui32FormatArraySize, pasFormat, pui32Supported); return PVRSRV_OK; } PVRSRV_ERROR DCDimQuery(DC_DEVICE *psDevice, IMG_UINT32 ui32DimSize, PVRSRV_SURFACE_DIMS *pasDim, IMG_UINT32 *pui32Supported) { psDevice->psFuncTable->pfnDimQuery(psDevice->hDeviceData, ui32DimSize, pasDim, pui32Supported); return PVRSRV_OK; } PVRSRV_ERROR DCSetBlank(DC_DEVICE *psDevice, IMG_BOOL bEnabled) { PVRSRV_ERROR eError = PVRSRV_ERROR_NOT_IMPLEMENTED; if (psDevice->psFuncTable->pfnSetBlank) { eError = psDevice->psFuncTable->pfnSetBlank(psDevice->hDeviceData, bEnabled); } return eError; } PVRSRV_ERROR DCSetVSyncReporting(DC_DEVICE *psDevice, IMG_BOOL bEnabled) { PVRSRV_ERROR eError = PVRSRV_ERROR_NOT_IMPLEMENTED; if (psDevice->psFuncTable->pfnSetVSyncReporting) { eError = psDevice->psFuncTable->pfnSetVSyncReporting(psDevice->hDeviceData, bEnabled); } return eError; } PVRSRV_ERROR DCLastVSyncQuery(DC_DEVICE *psDevice, IMG_INT64 *pi64Timestamp) { PVRSRV_ERROR eError = PVRSRV_ERROR_NOT_IMPLEMENTED; if (psDevice->psFuncTable->pfnLastVSyncQuery) { eError = psDevice->psFuncTable->pfnLastVSyncQuery(psDevice->hDeviceData, pi64Timestamp); } return eError; } /* The system buffer breaks the rule of only calling DC callbacks on first ref and last deref. For the pfnBufferSystemAcquire this is expected as each call could get back a different buffer, but calls to pfnBufferAcquire and pfnBufferRelease could happen multiple times for the same buffer */ PVRSRV_ERROR DCSystemBufferAcquire(DC_DEVICE *psDevice, IMG_UINT32 *pui32ByteStride, DC_BUFFER **ppsBuffer) { DC_BUFFER *psNew; PMR *psPMR; PVRSRV_ERROR eError; IMG_DEVMEM_LOG2ALIGN_T uiLog2PageSize; IMG_UINT32 ui32PageCount; IMG_UINT32 ui32PhysHeapID; if (psDevice->psFuncTable->pfnBufferSystemAcquire == IMG_NULL) { eError = PVRSRV_ERROR_NO_SYSTEM_BUFFER; goto fail_nopfn; } psNew = OSAllocMem(sizeof(DC_BUFFER)); if (psNew == IMG_NULL) { eError = PVRSRV_ERROR_OUT_OF_MEMORY; goto fail_alloc; } OSMemSet(psNew, 0, sizeof(DC_BUFFER)); eError = OSLockCreate(&psNew->hLock, LOCK_TYPE_NONE); if (eError != PVRSRV_OK) { goto fail_lock; } eError = OSLockCreate(&psNew->hMapLock, LOCK_TYPE_NONE); if (eError != PVRSRV_OK) { goto fail_maplock; } eError = psDevice->psFuncTable->pfnBufferSystemAcquire(psDevice->hDeviceData, &uiLog2PageSize, &ui32PageCount, &ui32PhysHeapID, pui32ByteStride, &psNew->hBuffer); if (eError != PVRSRV_OK) { goto fail_bufferacquire; } psNew->psDisplayContext = &psDevice->sSystemContext; psNew->eType = DC_BUFFER_TYPE_SYSTEM; psNew->ui32MapCount = 0; psNew->ui32RefCount = 1; /* Creating the PMR for the system buffer is a bit tricky as there is no "create" call for it. We should only ever have one PMR for the same buffer and so we can't just create one every call to this function. We also have to deal with the system buffer changing (mode change) so we can't just create the PMR once at DC driver register time. So what we do is cache the DC's handle to the system buffer and check if this call the handle has changed (indicating a mode change) and create a new PMR in this case. */ if (psNew->hBuffer != psDevice->hSystemBuffer) { if (psDevice->psSystemBufferPMR) { /* Mode change: We've already got a system buffer but the DC has given us a new one so we need to drop the 2nd reference we took on it as a different system buffer will be freed as DC unregister time */ PMRUnrefPMR(psDevice->psSystemBufferPMR); } eError = _DCCreatePMR(uiLog2PageSize, ui32PageCount, ui32PhysHeapID, psNew, &psPMR); if (eError != PVRSRV_OK) { goto fail_createpmr; } #if defined(PVR_RI_DEBUG) { /* Dummy handle - we don't need to store the reference to the PMR RI entry. Its deletion is handled internally. */ DC_DISPLAY_INFO sDisplayInfo; IMG_CHAR pszRIText[RI_MAX_TEXT_LEN]; DCGetInfo(psDevice, &sDisplayInfo); OSSNPrintf((IMG_CHAR *)pszRIText, RI_MAX_TEXT_LEN, "%s: DisplayContext 0x%p SystemBuffer", (IMG_CHAR *)sDisplayInfo.szDisplayName, &psDevice->sSystemContext); pszRIText[RI_MAX_TEXT_LEN-1] = '\0'; eError = RIWritePMREntryKM (psPMR, (IMG_CHAR *)pszRIText, (uiLog2PageSize*ui32PageCount)); } #endif psNew->uBufferData.sAllocData.psPMR = psPMR; psDevice->hSystemBuffer = psNew->hBuffer; psDevice->psSystemBufferPMR = psPMR; /* Take a 2nd reference on the PMR as we always drop a reference in the release call but we don't want the PMR to be freed until either a new system buffer as been acquired or the DC device gets unregistered */ PMRRefPMR(psDevice->psSystemBufferPMR); } else { /* A PMR for the system buffer as already been created so just take a reference to the PMR to make sure it doesn't go away */ PMRRefPMR(psDevice->psSystemBufferPMR); psNew->uBufferData.sAllocData.psPMR = psDevice->psSystemBufferPMR; } /* The system buffer is tied to the device unlike all other buffers which are tied to a display context. */ _DCDeviceAcquireRef(psDevice); *ppsBuffer = psNew; return PVRSRV_OK; fail_createpmr: fail_bufferacquire: OSLockDestroy(psNew->hMapLock); fail_maplock: OSLockDestroy(psNew->hLock); fail_lock: OSFreeMem(psNew); fail_alloc: fail_nopfn: return eError; } PVRSRV_ERROR DCSystemBufferRelease(DC_BUFFER *psBuffer) { PMRUnrefPMR(psBuffer->uBufferData.sAllocData.psPMR); _DCBufferReleaseRef(psBuffer); return PVRSRV_OK; } PVRSRV_ERROR DCDisplayContextCreate(DC_DEVICE *psDevice, DC_DISPLAY_CONTEXT **ppsDisplayContext) { DC_DISPLAY_CONTEXT *psDisplayContext; PVRSRV_ERROR eError; psDisplayContext = OSAllocMem(sizeof(DC_DISPLAY_CONTEXT)); if (psDisplayContext == IMG_NULL) { return PVRSRV_ERROR_OUT_OF_MEMORY; } psDisplayContext->psDevice = psDevice; psDisplayContext->hDisplayContext = IMG_NULL; psDisplayContext->ui32TokenOut = 0; psDisplayContext->ui32TokenIn = 0; psDisplayContext->ui32RefCount = 1; psDisplayContext->ui32ConfigsInFlight = 0; psDisplayContext->bIssuedNullFlip = IMG_FALSE; psDisplayContext->hTimer = IMG_NULL; eError = OSLockCreate(&psDisplayContext->hLock, LOCK_TYPE_NONE); if (eError != PVRSRV_OK) { goto FailLock; } /* Create a Software Command Processor with 4K CCB size. * With the HWC it might be possible to reach the limit off the buffer. * This could be bad when the buffers currently on the screen can't be * flipped to the new one, cause the command for them doesn't fit into the * queue (Deadlock). This situation should properly detected to make at * least the debugging easier. */ eError = SCPCreate(12, &psDisplayContext->psSCPContext); if (eError != PVRSRV_OK) { goto FailSCP; } eError = psDevice->psFuncTable->pfnContextCreate(psDevice->hDeviceData, &psDisplayContext->hDisplayContext); if (eError != PVRSRV_OK) { goto FailDCDeviceContext; } _DCDeviceAcquireRef(psDevice); /* Create an MISR for our display context */ eError = OSInstallMISR(&psDisplayContext->hMISR, _DCDisplayContextMISR, psDisplayContext); if (eError != PVRSRV_OK) { goto FailMISR; } /* Register for the command complete callback. Note: After calling this function our MISR can be called at any point. */ eError = PVRSRVRegisterCmdCompleteNotify(&psDisplayContext->hCmdCompNotify, _DCDisplayContextNotify, psDisplayContext); if (eError != PVRSRV_OK) { goto FailRegisterCmdComplete; } /* Register our debug request notify callback */ eError = PVRSRVRegisterDbgRequestNotify(&psDisplayContext->hDebugNotify, _DCDebugRequest, DEBUG_REQUEST_DC, psDisplayContext); if (eError != PVRSRV_OK) { goto FailRegisterDbgRequest; } *ppsDisplayContext = psDisplayContext; return PVRSRV_OK; FailRegisterDbgRequest: PVRSRVUnregisterCmdCompleteNotify(psDisplayContext->hCmdCompNotify); FailRegisterCmdComplete: OSUninstallMISR(psDisplayContext->hMISR); FailMISR: _DCDeviceReleaseRef(psDevice); FailDCDeviceContext: SCPDestroy(psDisplayContext->psSCPContext); FailSCP: OSLockDestroy(psDisplayContext->hLock); FailLock: OSFreeMem(psDisplayContext); return eError; } PVRSRV_ERROR DCDisplayContextConfigureCheck(DC_DISPLAY_CONTEXT *psDisplayContext, IMG_UINT32 ui32PipeCount, PVRSRV_SURFACE_CONFIG_INFO *pasSurfAttrib, DC_BUFFER **papsBuffers) { DC_DEVICE *psDevice = psDisplayContext->psDevice; PVRSRV_ERROR eError; IMG_HANDLE *ahBuffers; _DCDisplayContextAcquireRef(psDisplayContext); /* Create an array of private device specific buffer handles */ eError = _DCDeviceBufferArrayCreate(ui32PipeCount, papsBuffers, &ahBuffers); if (eError != PVRSRV_OK) { goto FailBufferArrayCreate; } /* Do we need to check if this is valid config? */ if (psDevice->psFuncTable->pfnContextConfigureCheck) { eError = psDevice->psFuncTable->pfnContextConfigureCheck(psDisplayContext->hDisplayContext, ui32PipeCount, pasSurfAttrib, ahBuffers); if (eError != PVRSRV_OK) { goto FailConfigCheck; } } _DCDeviceBufferArrayDestroy(ahBuffers); _DCDisplayContextReleaseRef(psDisplayContext); return PVRSRV_OK; FailConfigCheck: _DCDeviceBufferArrayDestroy(ahBuffers); FailBufferArrayCreate: _DCDisplayContextReleaseRef(psDisplayContext); PVR_ASSERT(eError != PVRSRV_OK); return eError; } PVRSRV_ERROR DCDisplayContextConfigure(DC_DISPLAY_CONTEXT *psDisplayContext, IMG_UINT32 ui32PipeCount, PVRSRV_SURFACE_CONFIG_INFO *pasSurfAttrib, DC_BUFFER **papsBuffers, IMG_UINT32 ui32SyncOpCount, SERVER_SYNC_PRIMITIVE **papsSync, IMG_BOOL *pabUpdate, IMG_UINT32 ui32DisplayPeriod, IMG_UINT32 ui32MaxDepth, IMG_INT32 i32AcquireFenceFd, IMG_INT32 *pi32ReleaseFenceFd) { DC_DEVICE *psDevice = psDisplayContext->psDevice; PVRSRV_ERROR eError; IMG_HANDLE *ahBuffers; IMG_UINT32 ui32BuffersMapped = 0; IMG_UINT32 i; IMG_UINT32 ui32CmdRdySize; IMG_UINT32 ui32CmdCompSize; IMG_UINT32 ui32CopySize; IMG_PUINT8 pui8ReadyData; IMG_PVOID pvCompleteData; DC_CMD_RDY_DATA *psReadyData; DC_CMD_COMP_DATA *psCompleteData; PVRSRV_DATA *psData = PVRSRVGetPVRSRVData(); _DCDisplayContextAcquireRef(psDisplayContext); if (ui32MaxDepth == 1) { eError = PVRSRV_ERROR_DC_INVALID_MAXDEPTH; goto FailMaxDepth; } else if (ui32MaxDepth > 0) { /* ui32TokenOut/In wrap-around case takes care of itself. */ if (psDisplayContext->ui32TokenOut - psDisplayContext->ui32TokenIn >= ui32MaxDepth) { eError = PVRSRV_ERROR_RETRY; goto FailMaxDepth; } } /* Reset the release fd */ if (pi32ReleaseFenceFd) *pi32ReleaseFenceFd = -1; /* If we get sent a NULL flip then we don't need to do the check or map */ if (ui32PipeCount != 0) { /* Create an array of private device specific buffer handles */ eError = _DCDeviceBufferArrayCreate(ui32PipeCount, papsBuffers, &ahBuffers); if (eError != PVRSRV_OK) { goto FailBufferArrayCreate; } /* Do we need to check if this is valid config? */ if (psDevice->psFuncTable->pfnContextConfigureCheck) { eError = psDevice->psFuncTable->pfnContextConfigureCheck(psDisplayContext->hDisplayContext, ui32PipeCount, pasSurfAttrib, ahBuffers); if (eError != PVRSRV_OK) { goto FailConfigCheck; } } /* Map all the buffers that are going to be used */ for (i=0;i<ui32PipeCount;i++) { eError = _DCBufferMap(papsBuffers[i]); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR, "DCDisplayContextConfigure: Failed to map buffer")); goto FailMapBuffer; } ui32BuffersMapped++; } } ui32CmdRdySize = sizeof(DC_CMD_RDY_DATA) + ((sizeof(IMG_HANDLE) + sizeof(PVRSRV_SURFACE_CONFIG_INFO)) * ui32PipeCount); ui32CmdCompSize = sizeof(DC_CMD_COMP_DATA) + (sizeof(DC_BUFFER *) * ui32PipeCount); /* Allocate a command */ eError = SCPAllocCommand(psDisplayContext->psSCPContext, ui32SyncOpCount, papsSync, pabUpdate, i32AcquireFenceFd, _DCDisplayContextReady, _DCDisplayContextConfigure, ui32CmdRdySize, ui32CmdCompSize, (IMG_PVOID *)&pui8ReadyData, &pvCompleteData, pi32ReleaseFenceFd); if (eError != PVRSRV_OK) { goto FailCommandAlloc; } /* Set up command ready data */ psReadyData = (DC_CMD_RDY_DATA *)pui8ReadyData; pui8ReadyData += sizeof(DC_CMD_RDY_DATA); psReadyData->ui32DisplayPeriod = ui32DisplayPeriod; psReadyData->psDisplayContext = psDisplayContext; psReadyData->ui32BufferCount = ui32PipeCount; /* Copy over surface atrribute array */ if (ui32PipeCount != 0) { psReadyData->pasSurfAttrib = (PVRSRV_SURFACE_CONFIG_INFO *)pui8ReadyData; ui32CopySize = sizeof(PVRSRV_SURFACE_CONFIG_INFO) * ui32PipeCount; OSMemCopy(psReadyData->pasSurfAttrib, pasSurfAttrib, ui32CopySize); pui8ReadyData = pui8ReadyData + ui32CopySize; } else { psReadyData->pasSurfAttrib = IMG_NULL; } /* Copy over device buffer handle buffer array */ if (ui32PipeCount != 0) { psReadyData->pahBuffer = (IMG_HANDLE)pui8ReadyData; ui32CopySize = sizeof(IMG_HANDLE) * ui32PipeCount; OSMemCopy(psReadyData->pahBuffer, ahBuffers, ui32CopySize); } else { psReadyData->pahBuffer = IMG_NULL; } /* Set up command complete data */ psCompleteData = pvCompleteData; pvCompleteData = (IMG_PUINT8)pvCompleteData + sizeof(DC_CMD_COMP_DATA); psCompleteData->psDisplayContext = psDisplayContext; psCompleteData->ui32Token = psDisplayContext->ui32TokenOut++; psCompleteData->ui32BufferCount = ui32PipeCount; if (ui32PipeCount != 0) { /* Copy the buffer pointers */ psCompleteData->apsBuffer = pvCompleteData; for (i=0;i<ui32PipeCount;i++) { psCompleteData->apsBuffer[i] = papsBuffers[i]; } } /* Check if we need to do any CPU cache operations before sending the config */ OSCPUOperation(psData->uiCacheOp); psData->uiCacheOp = PVRSRV_CACHE_OP_NONE; /* Submit the command */ eError = SCPSubmitCommand(psDisplayContext->psSCPContext); /* Check for new work on this display context */ _DCDisplayContextRun(psDisplayContext); /* The only way this submit can fail is if there is a bug in this module */ PVR_ASSERT(eError == PVRSRV_OK); if (ui32PipeCount != 0) { _DCDeviceBufferArrayDestroy(ahBuffers); } return PVRSRV_OK; FailCommandAlloc: FailMapBuffer: if (ui32PipeCount != 0) { for (i=0;i<ui32BuffersMapped;i++) { _DCBufferUnmap(papsBuffers[i]); } } FailConfigCheck: if (ui32PipeCount != 0) { _DCDeviceBufferArrayDestroy(ahBuffers); } FailBufferArrayCreate: FailMaxDepth: _DCDisplayContextReleaseRef(psDisplayContext); return eError; } PVRSRV_ERROR DCDisplayContextDestroy(DC_DISPLAY_CONTEXT *psDisplayContext) { PVRSRV_ERROR eError; /* On the first cleanup request try to issue the NULL flip. If we fail then we should get retry which we pass back to the caller who will try again later. */ if (!psDisplayContext->bIssuedNullFlip) { eError = DCDisplayContextConfigure(psDisplayContext, 0, IMG_NULL, IMG_NULL, 0, IMG_NULL, IMG_NULL, 0, 0, -1, IMG_NULL); if (eError != PVRSRV_OK) { return eError; } psDisplayContext->bIssuedNullFlip = IMG_TRUE; } /* Flush out everything from SCP This will ensure that the MISR isn't dropping the last reference which would cause a deadlock during cleanup */ eError = SCPFlush(psDisplayContext->psSCPContext); if (eError != PVRSRV_OK) { return eError; } _DCDisplayContextReleaseRef(psDisplayContext); return PVRSRV_OK; } PVRSRV_ERROR DCBufferAlloc(DC_DISPLAY_CONTEXT *psDisplayContext, DC_BUFFER_CREATE_INFO *psSurfInfo, IMG_UINT32 *pui32ByteStride, DC_BUFFER **ppsBuffer) { DC_DEVICE *psDevice = psDisplayContext->psDevice; DC_BUFFER *psNew; PMR *psPMR; PVRSRV_ERROR eError; IMG_DEVMEM_LOG2ALIGN_T uiLog2PageSize; IMG_UINT32 ui32PageCount; IMG_UINT32 ui32PhysHeapID; psNew = OSAllocMem(sizeof(DC_BUFFER)); if (psNew == IMG_NULL) { return PVRSRV_ERROR_OUT_OF_MEMORY; } OSMemSet(psNew, 0, sizeof(DC_BUFFER)); eError = OSLockCreate(&psNew->hLock, LOCK_TYPE_NONE); if (eError != PVRSRV_OK) { goto fail_lock; } eError = OSLockCreate(&psNew->hMapLock, LOCK_TYPE_NONE); if (eError != PVRSRV_OK) { goto fail_maplock; } eError = psDevice->psFuncTable->pfnBufferAlloc(psDisplayContext->hDisplayContext, psSurfInfo, &uiLog2PageSize, &ui32PageCount, &ui32PhysHeapID, pui32ByteStride, &psNew->hBuffer); if (eError != PVRSRV_OK) { goto fail_bufferalloc; } /* Fill in the basic info for our buffer (must be before _DCCreatePMR) */ psNew->psDisplayContext = psDisplayContext; psNew->eType = DC_BUFFER_TYPE_ALLOC; psNew->ui32MapCount = 0; psNew->ui32RefCount = 1; eError = _DCCreatePMR(uiLog2PageSize, ui32PageCount, ui32PhysHeapID, psNew, &psPMR); if (eError != PVRSRV_OK) { goto fail_createpmr; } #if defined(PVR_RI_DEBUG) { /* Dummy handle - we don't need to store the reference to the PMR RI entry. Its deletion is handled internally. */ DC_DISPLAY_INFO sDisplayInfo; IMG_CHAR pszRIText[RI_MAX_TEXT_LEN]; DCGetInfo(psDevice, &sDisplayInfo); OSSNPrintf((IMG_CHAR *)pszRIText, RI_MAX_TEXT_LEN, "%s: DisplayContext 0x%p BufferAlloc", (IMG_CHAR *)sDisplayInfo.szDisplayName, &psDevice->sSystemContext); pszRIText[RI_MAX_TEXT_LEN-1] = '\0'; eError = RIWritePMREntryKM (psPMR, (IMG_CHAR *)pszRIText, (uiLog2PageSize*ui32PageCount)); } #endif psNew->uBufferData.sAllocData.psPMR = psPMR; _DCDisplayContextAcquireRef(psDisplayContext); *ppsBuffer = psNew; return PVRSRV_OK; fail_createpmr: psDevice->psFuncTable->pfnBufferFree(psNew->hBuffer); fail_bufferalloc: OSLockDestroy(psNew->hMapLock); fail_maplock: OSLockDestroy(psNew->hLock); fail_lock: OSFreeMem(psNew); return eError; } PVRSRV_ERROR DCBufferFree(DC_BUFFER *psBuffer) { /* Only drop the reference on the PMR if this is a DC allocated buffer. In the case of imported buffers the 3rd party DC driver manages the PMR's "directly" */ if (psBuffer->eType == DC_BUFFER_TYPE_ALLOC) { PMRUnrefPMR(psBuffer->uBufferData.sAllocData.psPMR); } _DCBufferReleaseRef(psBuffer); return PVRSRV_OK; } PVRSRV_ERROR DCBufferImport(DC_DISPLAY_CONTEXT *psDisplayContext, IMG_UINT32 ui32NumPlanes, PMR **papsImport, DC_BUFFER_IMPORT_INFO *psSurfAttrib, DC_BUFFER **ppsBuffer) { DC_DEVICE *psDevice = psDisplayContext->psDevice; DC_BUFFER *psNew; PVRSRV_ERROR eError; IMG_UINT32 i; if(psDevice->psFuncTable->pfnBufferImport == IMG_NULL) { eError = PVRSRV_ERROR_NOT_SUPPORTED; goto FailEarlyError; } psNew = OSAllocMem(sizeof(DC_BUFFER)); if (psNew == IMG_NULL) { eError = PVRSRV_ERROR_OUT_OF_MEMORY; goto FailEarlyError; } OSMemSet(psNew, 0, sizeof(DC_BUFFER)); eError = OSLockCreate(&psNew->hLock, LOCK_TYPE_NONE); if (eError != PVRSRV_OK) { goto FailLock; } eError = OSLockCreate(&psNew->hMapLock, LOCK_TYPE_NONE); if (eError != PVRSRV_OK) { goto FailMapLock; } eError = psDevice->psFuncTable->pfnBufferImport(psDisplayContext->hDisplayContext, ui32NumPlanes, (IMG_HANDLE **)papsImport, psSurfAttrib, &psNew->hBuffer); if (eError != PVRSRV_OK) { goto FailBufferImport; } /* Take a reference on the PMR to make sure it can't be released before we've finished with it */ for (i=0;i<ui32NumPlanes;i++) { PMRRefPMR(papsImport[i]); psNew->uBufferData.sImportData.apsImport[i] = papsImport[i]; } _DCDisplayContextAcquireRef(psDisplayContext); psNew->psDisplayContext = psDisplayContext; psNew->eType = DC_BUFFER_TYPE_IMPORT; psNew->uBufferData.sImportData.ui32NumPlanes = ui32NumPlanes; psNew->ui32MapCount = 0; psNew->ui32RefCount = 1; *ppsBuffer = psNew; return PVRSRV_OK; FailBufferImport: OSLockDestroy(psNew->hMapLock); FailMapLock: OSLockDestroy(psNew->hLock); FailLock: OSFreeMem(psNew); FailEarlyError: return eError; } PVRSRV_ERROR DCBufferUnimport(DC_BUFFER *psBuffer) { _DCBufferReleaseRef(psBuffer); return PVRSRV_OK; } PVRSRV_ERROR DCBufferAcquire(DC_BUFFER *psBuffer, PMR **ppsPMR) { PMR *psPMR = psBuffer->uBufferData.sAllocData.psPMR; PVRSRV_ERROR eError; if (psBuffer->eType == DC_BUFFER_TYPE_IMPORT) { PVR_DPF((PVR_DBG_ERROR, "DCBufferAcquire: Invalid request, DC buffer is an import")); eError = PVRSRV_ERROR_INVALID_PARAMS; goto fail_typecheck; } PMRRefPMR(psPMR); *ppsPMR = psPMR; return PVRSRV_OK; fail_typecheck: return eError; } PVRSRV_ERROR DCBufferRelease(PMR *psPMR) { /* Drop our reference on the PMR. If we're the last one then the PMR will be freed and are _DCPMRFinalize function will be called where we drop our reference on the buffer */ PMRUnrefPMR(psPMR); return PVRSRV_OK; } PVRSRV_ERROR DCBufferPin(DC_BUFFER *psBuffer, DC_PIN_HANDLE *phPin) { *phPin = psBuffer; return _DCBufferMap(psBuffer); } PVRSRV_ERROR DCBufferUnpin(DC_PIN_HANDLE hPin) { DC_BUFFER *psBuffer = hPin; _DCBufferUnmap(psBuffer); return PVRSRV_OK; } /***************************************************************************** * Public interface functions for 3rd party display class devices * *****************************************************************************/ PVRSRV_ERROR DCRegisterDevice(DC_DEVICE_FUNCTIONS *psFuncTable, IMG_UINT32 ui32MaxConfigsInFlight, IMG_HANDLE hDeviceData, IMG_HANDLE *phSrvHandle) { DC_DEVICE *psNew; PVRSRV_ERROR eError; psNew = OSAllocMem(sizeof(DC_DEVICE)); if (psNew == IMG_NULL) { return PVRSRV_ERROR_OUT_OF_MEMORY; } eError = OSLockCreate(&psNew->hLock, LOCK_TYPE_NONE); if (eError != PVRSRV_OK) { return eError; } psNew->psFuncTable = psFuncTable; psNew->ui32MaxConfigsInFlight = ui32MaxConfigsInFlight; psNew->hDeviceData = hDeviceData; psNew->ui32RefCount = 1; psNew->hSystemBuffer = IMG_NULL; psNew->ui32Index = g_ui32DCNextIndex++; eError = OSEventObjectCreate("DC_EVENT_OBJ", &psNew->psEventList); if (eError != PVRSRV_OK) { return eError; } /* Init state required for system surface */ psNew->hSystemBuffer = IMG_NULL; psNew->psSystemBufferPMR = IMG_NULL; psNew->sSystemContext.psDevice = psNew; psNew->sSystemContext.hDisplayContext = hDeviceData; /* FIXME: Is this the correct thing to do? */ OSLockAcquire(g_hDCListLock); psNew->psNext = g_psDCDeviceList; g_psDCDeviceList = psNew; g_ui32DCDeviceCount++; OSLockRelease(g_hDCListLock); *phSrvHandle = (IMG_HANDLE) psNew; return PVRSRV_OK; } IMG_VOID DCUnregisterDevice(IMG_HANDLE hSrvHandle) { DC_DEVICE *psDevice = (DC_DEVICE *) hSrvHandle; PVRSRV_DATA *psPVRSRVData = PVRSRVGetPVRSRVData(); PVRSRV_ERROR eError; /* If the system buffer was acquired and a PMR created for it, release it before releasing the device as the PMR will have a reference to the device */ if (psDevice->psSystemBufferPMR) { PMRUnrefPMR(psDevice->psSystemBufferPMR); } /* * At this stage the DC driver wants to unload, if other things have * reference to the DC device we need to block here until they have * been release as when this function returns the DC driver code could * be unloaded. */ /* If the driver is in a bad state we just free resources regardless */ if (psPVRSRVData->eServicesState == PVRSRV_SERVICES_STATE_OK) { volatile IMG_UINT32 * ref_count_ptr = &(psDevice->ui32RefCount); /* Skip the wait if we're the last reference holder */ if (*ref_count_ptr != 1) { IMG_HANDLE hEvent; eError = OSEventObjectOpen(psDevice->psEventList, &hEvent); if (eError != PVRSRV_OK) { PVR_DPF((PVR_DBG_ERROR, "%s: Failed to open event object (%d), will busy wait", __FUNCTION__, eError)); hEvent = IMG_NULL; } while(*ref_count_ptr != 1) { if (hEvent != IMG_NULL) { OSEventObjectWait(hEvent); } } if (hEvent != IMG_NULL) { OSEventObjectClose(hEvent); } } } else { /* We're in a bad state, force the refcount */ psDevice->ui32RefCount = 1; } _DCDeviceReleaseRef(psDevice); PVR_ASSERT(psDevice->ui32RefCount == 0); OSEventObjectDestroy(psDevice->psEventList); OSLockDestroy(psDevice->hLock); OSFreeMem(psDevice); } IMG_VOID DCDisplayConfigurationRetired(IMG_HANDLE hConfigData) { DC_CMD_COMP_DATA *psData = hConfigData; DC_DISPLAY_CONTEXT *psDisplayContext = psData->psDisplayContext; IMG_UINT32 i; DC_DEBUG_PRINT("DCDisplayConfigurationRetired: Command (%d) received", psData->ui32Token); /* Sanity check */ if (psData->ui32Token != psDisplayContext->ui32TokenIn) { PVR_DPF((PVR_DBG_ERROR, "Display config retired in unexpected order (was %d, expecting %d)", psData->ui32Token, psDisplayContext->ui32TokenIn)); PVR_ASSERT(IMG_FALSE); } OSLockAcquire(psDisplayContext->hLock); psDisplayContext->ui32TokenIn++; #if defined SUPPORT_DC_COMPLETE_TIMEOUT_DEBUG if (psDisplayContext->hTimer) { OSDisableTimer(psDisplayContext->hTimer); OSRemoveTimer(psDisplayContext->hTimer); psDisplayContext->hTimer = IMG_NULL; } #endif /* SUPPORT_DC_COMPLETE_TIMEOUT_DEBUG */ psDisplayContext->ui32ConfigsInFlight--; OSLockRelease(psDisplayContext->hLock); for (i = 0; i < psData->ui32BufferCount; i++) { _DCBufferUnmap(psData->apsBuffer[i]); } _DCDisplayContextReleaseRef(psDisplayContext); /* Note: We must call SCPCommandComplete here and not before as we need to ensure that we're not the last to hold the reference as we can't destroy the display context from the MISR which we can be called from. */ SCPCommandComplete(psDisplayContext->psSCPContext); /* Notify devices (including ourself) in case some item has been unblocked */ PVRSRVCheckStatus(IMG_NULL); } PVRSRV_ERROR DCImportBufferAcquire(IMG_HANDLE hImport, IMG_DEVMEM_LOG2ALIGN_T uiLog2PageSize, IMG_UINT32 *pui32PageCount, IMG_DEV_PHYADDR **ppasDevPAddr) { PMR *psPMR = hImport; IMG_DEV_PHYADDR *pasDevPAddr; IMG_DEVMEM_SIZE_T uiLogicalSize; IMG_SIZE_T uiPageCount; IMG_DEVMEM_OFFSET_T uiOffset = 0; IMG_UINT32 i; PVRSRV_ERROR eError; eError = PMR_LogicalSize(psPMR, &uiLogicalSize); if (eError != PVRSRV_OK) { goto fail_getsize; } uiPageCount = TRUNCATE_64BITS_TO_SIZE_T(uiLogicalSize >> uiLog2PageSize); pasDevPAddr = OSAllocMem(sizeof(IMG_DEV_PHYADDR) * uiPageCount); if (pasDevPAddr == IMG_NULL) { eError = PVRSRV_ERROR_OUT_OF_MEMORY; goto fail_alloc; } OSMemSet(pasDevPAddr, 0, sizeof(IMG_DEV_PHYADDR) * uiPageCount); /* Lock the pages */ eError = PMRLockSysPhysAddresses(psPMR, uiLog2PageSize); if (eError != PVRSRV_OK) { goto fail_lock; } /* Get each page one by one */ for (i=0;i<uiPageCount;i++) { IMG_BOOL bValid; eError = PMR_DevPhysAddr(psPMR, uiOffset, &pasDevPAddr[i], &bValid); if (eError != PVRSRV_OK) { goto fail_getphysaddr; } /* The DC import function doesn't support sparse allocations */ PVR_ASSERT(bValid); uiOffset += 1ULL << uiLog2PageSize; } *pui32PageCount = TRUNCATE_SIZE_T_TO_32BITS(uiPageCount); *ppasDevPAddr = pasDevPAddr; return PVRSRV_OK; fail_getphysaddr: PMRUnlockSysPhysAddresses(psPMR); fail_lock: OSFreeMem(pasDevPAddr); fail_alloc: fail_getsize: return eError; } IMG_VOID DCImportBufferRelease(IMG_HANDLE hImport, IMG_DEV_PHYADDR *pasDevPAddr) { PMR *psPMR = hImport; /* Unlock the pages */ PMRUnlockSysPhysAddresses(psPMR); OSFreeMem(pasDevPAddr); } /***************************************************************************** * Public interface functions for services * *****************************************************************************/ PVRSRV_ERROR DCInit() { g_psDCDeviceList = IMG_NULL; g_ui32DCNextIndex = 0; return OSLockCreate(&g_hDCListLock, LOCK_TYPE_NONE); } PVRSRV_ERROR DCDeInit() { PVRSRV_DATA *psPVRSRVData = PVRSRVGetPVRSRVData(); if (psPVRSRVData->eServicesState == PVRSRV_SERVICES_STATE_OK) { PVR_ASSERT(g_psDCDeviceList == IMG_NULL); } OSLockDestroy(g_hDCListLock); return PVRSRV_OK; }
jmztaylor/android_kernel_amazon_ariel
drivers/gpu/mt8135/rgx_1.3_2876724/services/server/common/dc_server.c
C
gpl-2.0
55,224
/*FreeMind - A Program for creating and viewing Mindmaps *Copyright (C) 2000-2006 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitri Polivaev and others. * *See COPYING for Details * *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. */ /* * Created on 06.05.2005 * */ package freemind.controller.filter.condition; import freemind.main.Resources; import freemind.modes.MindIcon; import javax.swing.*; import java.awt.*; ; /** * @author dimitri 06.05.2005 */ public class ConditionRenderer implements ListCellRenderer { final public static Color SELECTED_BACKGROUND = new Color(207, 247, 202); /* * (non-Javadoc) * * @see * javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing * .JList, java.lang.Object, int, boolean, boolean) */ public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value == null) return new JLabel(Resources.getInstance().getResourceString( "filter_no_filtering")); JComponent component; if (value instanceof MindIcon) { component = new JLabel(((MindIcon) value).getIcon()); } else if (value instanceof Condition) { Condition cond = (Condition) value; component = cond.getListCellRendererComponent(); } else { component = new JLabel(value.toString()); } component.setOpaque(true); if (isSelected) { component.setBackground(SELECTED_BACKGROUND); } else { component.setBackground(Color.WHITE); } component.setAlignmentX(Component.LEFT_ALIGNMENT); return component; } }
d4span/freemindfx
src/main/java/freemind/controller/filter/condition/ConditionRenderer.java
Java
gpl-2.0
2,453
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct template as_min&lt;T, std_vector_tag&gt;</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../../accumulators/reference.html#header.boost.accumulators.numeric.functional.vector_hpp" title="Header &lt;boost/accumulators/numeric/functional/vector.hpp&gt;"> <link rel="prev" href="promote_ToFrom__ToFrom__id581365.html" title="Struct template promote&lt;ToFrom, ToFrom, std_vector_tag, std_vector_tag&gt;"> <link rel="next" href="as_max_T__std_vector_ta_id581446.html" title="Struct template as_max&lt;T, std_vector_tag&gt;"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="promote_ToFrom__ToFrom__id581365.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.numeric.functional.vector_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="as_max_T__std_vector_ta_id581446.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.numeric.functional.as_min_T,_std_vector_ta_id581408"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template as_min&lt;T, std_vector_tag&gt;</span></h2> <p>boost::numeric::functional::as_min&lt;T, std_vector_tag&gt;</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../../accumulators/reference.html#header.boost.accumulators.numeric.functional.vector_hpp" title="Header &lt;boost/accumulators/numeric/functional/vector.hpp&gt;">boost/accumulators/numeric/functional/vector.hpp</a>&gt; </span><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> T<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="as_min_T__std_vector_ta_id581408.html" title="Struct template as_min&lt;T, std_vector_tag&gt;">as_min</a><span class="special">&lt;</span><span class="identifier">T</span><span class="special">,</span> <span class="identifier">std_vector_tag</span><span class="special">&gt;</span> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">unary_function</span><span class="special">&lt;</span> <span class="identifier">T</span><span class="special">,</span> <span class="identifier">remove_const</span><span class="special">&lt;</span> <span class="identifier">T</span> <span class="special">&gt;</span><span class="special">::</span><span class="identifier">type</span> <span class="special">&gt;</span> <span class="special">{</span> <span class="comment">// <a class="link" href="as_min_T__std_vector_ta_id581408.html#id581429-bb">public member functions</a></span> <span class="identifier">remove_const</span><span class="special">&lt;</span> <span class="identifier">T</span> <span class="special">&gt;</span><span class="special">::</span><span class="identifier">type</span> <a class="link" href="as_min_T__std_vector_ta_id581408.html#id581432-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">T</span> <span class="special">&amp;</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="id1026914"></a><h2>Description</h2> <div class="refsect2"> <a name="id1026918"></a><h3> <a name="id581429-bb"></a><code class="computeroutput">as_min</code> public member functions</h3> <div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"><span class="identifier">remove_const</span><span class="special">&lt;</span> <span class="identifier">T</span> <span class="special">&gt;</span><span class="special">::</span><span class="identifier">type</span> <a name="id581432-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">T</span> <span class="special">&amp;</span> arr<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li></ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2005, 2006 Eric Niebler<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="promote_ToFrom__ToFrom__id581365.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.numeric.functional.vector_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="as_max_T__std_vector_ta_id581446.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
phra/802_21
boost_1_49_0/doc/html/boost/numeric/functional/as_min_T__std_vector_ta_id581408.html
HTML
gpl-2.0
6,721
/* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/ * Copyright : Copyright © Nequeo Pty Ltd 2014 http://www.nequeo.com.au/ * * File : TextIterator.h * Purpose : TextIterator header. * */ /* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #ifndef _TEXTITERATOR_H #define _TEXTITERATOR_H #include "GlobalText.h" namespace Nequeo{ namespace IO{ namespace Text { class TextEncoding; class TextIterator /// An unidirectional iterator for iterating over characters in a string. /// The TextIterator uses a TextEncoding object to /// work with multi-byte character encodings like UTF-8. /// Characters are reported in Unicode. /// /// Example: Count the number of UTF-8 characters in a string. /// /// UTF8Encoding utf8Encoding; /// std::string utf8String("...."); /// TextIterator it(utf8String, utf8Encoding); /// TextIterator end(utf8String); /// int n = 0; /// while (it != end) { ++n; ++it; } /// /// NOTE: When an UTF-16 encoding is used, surrogate pairs will be /// reported as two separate characters, due to restrictions of /// the TextEncoding class. /// /// For iterating over char buffers, see the TextBufferIterator class. { public: TextIterator(); /// Creates an uninitialized TextIterator. TextIterator(const std::string& str, const TextEncoding& encoding); /// Creates a TextIterator for the given string. /// The encoding object must not be deleted as long as the iterator /// is in use. TextIterator(const std::string::const_iterator& begin, const std::string::const_iterator& end, const TextEncoding& encoding); /// Creates a TextIterator for the given range. /// The encoding object must not be deleted as long as the iterator /// is in use. TextIterator(const std::string& str); /// Creates an end TextIterator for the given string. TextIterator(const std::string::const_iterator& end); /// Creates an end TextIterator. ~TextIterator(); /// Destroys the TextIterator. TextIterator(const TextIterator& it); /// Copy constructor. TextIterator& operator = (const TextIterator& it); /// Assignment operator. void swap(TextIterator& it); /// Swaps the iterator with another one. int operator * () const; /// Returns the Unicode value of the current character. /// If there is no valid character at the current position, /// -1 is returned. TextIterator& operator ++ (); /// Prefix increment operator. TextIterator operator ++ (int); /// Postfix increment operator. bool operator == (const TextIterator& it) const; /// Compares two iterators for equality. bool operator != (const TextIterator& it) const; /// Compares two iterators for inequality. TextIterator end() const; /// Returns the end iterator for the range handled /// by the iterator. private: const TextEncoding* _pEncoding; std::string::const_iterator _it; std::string::const_iterator _end; }; // // inlines // inline bool TextIterator::operator == (const TextIterator& it) const { return _it == it._it; } inline bool TextIterator::operator != (const TextIterator& it) const { return _it != it._it; } inline void swap(TextIterator& it1, TextIterator& it2) { it1.swap(it2); } inline TextIterator TextIterator::end() const { return TextIterator(_end); } } } } #endif
drazenzadravec/nequeo
Source/References/Release/Include/Components/IO/Text/TextIterator.h
C
gpl-2.0
4,697
/* ScummVM - Graphic Adventure Engine * * ScummVM 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. * */ #ifndef TITANIC_FPOINT_H #define TITANIC_FPOINT_H namespace Titanic { /** * Floating point Point class */ class FPoint { public: double _x, _y; public: FPoint() : _x(0), _y(0) {} FPoint(double x, double y) : _x(x), _y(y) {} bool operator==(const FPoint &p) const { return _x == p._x && _y == p._y; } bool operator!=(const FPoint &p) const { return _x != p._x || _y != p._y; } void operator+=(const FPoint &delta) { _x += delta._x; _y += delta._y; } void operator-=(const FPoint &delta) { _x -= delta._x; _y -= delta._y; } /** * Normalises the X and Y coordinates as fractions relative to the * value of the hypotenuse formed by a triangle from the origin (0,0) */ void normalize(); }; } // End of namespace Titanic #endif /* TITANIC_FPOINT_H */
jammm/scummvm
engines/titanic/star_control/fpoint.h
C
gpl-2.0
1,729
/* * @file include/linux/dmt10.h * @brief DMT g-sensor Linux device driver * @author Domintech Technology Co., Ltd (http://www.domintech.com.tw) * @version 1.02 * @date 2012/12/10 * * @section LICENSE * * Copyright 2012 Domintech Technology Co., Ltd * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @DMT Package version D10_General_driver v1.4 * * */ #ifndef DMT10_H #define DMT10_H #include <linux/types.h> #include <linux/ioctl.h> #include <linux/cdev.h> #include <linux/mutex.h> #include <linux/syscalls.h> #include <linux/wait.h> #include <linux/workqueue.h> #include <linux/delay.h> #define AUTO_CALIBRATION 0 #define DMT_DEBUG_DATA 0 #define GSE_TAG "[DMT_Gsensor]" #if DMT_DEBUG_DATA #define GSE_ERR(fmt, args...) printk(KERN_ERR GSE_TAG"%s %d : "fmt, __FUNCTION__, __LINE__, ##args) #define GSE_LOG(fmt, args...) printk(KERN_INFO GSE_TAG fmt, ##args) #define GSE_FUN(f) printk(KERN_INFO GSE_TAG" %s: %s: %i\n", __FILE__, __func__, __LINE__) #define DMT_DATA(dev, ...) dev_dbg((dev), ##__VA_ARGS__) #else #define GSE_ERR(fmt, args...) #define GSE_LOG(fmt, args...) #define GSE_FUN(f) #define DMT_DATA(dev, format, ...) #endif #define DMT10_I2C_ADDR 0x18 #define INPUT_NAME_ACC "g-sensor" /* Input Device Name */ #define DEVICE_I2C_NAME "g-sensor" /* Device name for DMARD10 misc. device */ #define REG_ACTR 0x00 #define REG_WDAL 0x01 #define REG_TAPNS 0x0f #define REG_MISC2 0x1f #define REG_AFEM 0x0c #define REG_CKSEL 0x0d #define REG_INTC 0x0e #define REG_STADR 0x12 #define REG_STAINT 0x1C #define REG_PD 0x21 #define REG_TCGYZ 0x26 #define REG_X_OUT 0x41 #define MODE_Off 0x00 #define MODE_ResetAtOff 0x01 #define MODE_Standby 0x02 #define MODE_ResetAtStandby 0x03 #define MODE_Active 0x06 #define MODE_Trigger 0x0a #define MODE_ReadOTP 0x12 #define MODE_WriteOTP 0x22 #define MODE_WriteOTPBuf 0x42 #define MODE_ResetDataPath 0x82 #define VALUE_STADR 0x55 #define VALUE_STAINT 0xAA #define VALUE_AFEM_AFEN_Normal 0x8f// AFEN set 1 , ATM[2:0]=b'000(normal),EN_Z/Y/X/T=1 #define VALUE_AFEM_Normal 0x0f// AFEN set 0 , ATM[2:0]=b'000(normal),EN_Z/Y/X/T=1 #define VALUE_INTC 0x00// INTC[6:5]=b'00 #define VALUE_INTC_Interrupt_En 0x20// INTC[6:5]=b'01 (Data ready interrupt enable, active high at INT0) #define VALUE_CKSEL_ODR_0_204 0x04// ODR[3:0]=b'0000 (0.78125Hz), CCK[3:0]=b'0100 (204.8kHZ) #define VALUE_CKSEL_ODR_1_204 0x14// ODR[3:0]=b'0001 (1.5625Hz), CCK[3:0]=b'0100 (204.8kHZ) #define VALUE_CKSEL_ODR_3_204 0x24// ODR[3:0]=b'0010 (3.125Hz), CCK[3:0]=b'0100 (204.8kHZ) #define VALUE_CKSEL_ODR_6_204 0x34// ODR[3:0]=b'0011 (6.25Hz), CCK[3:0]=b'0100 (204.8kHZ) #define VALUE_CKSEL_ODR_12_204 0x44// ODR[3:0]=b'0100 (12.5Hz), CCK[3:0]=b'0100 (204.8kHZ) #define VALUE_CKSEL_ODR_25_204 0x54// ODR[3:0]=b'0101 (25Hz), CCK[3:0]=b'0100 (204.8kHZ) #define VALUE_CKSEL_ODR_50_204 0x64// ODR[3:0]=b'0110 (50Hz), CCK[3:0]=b'0100 (204.8kHZ) #define VALUE_CKSEL_ODR_100_204 0x74// ODR[3:0]=b'0111 (100Hz), CCK[3:0]=b'0100 (204.8kHZ) #define VALUE_TAPNS_NoFilter 0x00 // TAP1/TAP2 NO FILTER #define VALUE_TAPNS_Ave_2 0x11 // TAP1/TAP2 Average 2 #define VALUE_TAPNS_Ave_4 0x22 // TAP1/TAP2 Average 4 #define VALUE_TAPNS_Ave_8 0x33 // TAP1/TAP2 Average 8 #define VALUE_TAPNS_Ave_16 0x44 // TAP1/TAP2 Average 16 #define VALUE_TAPNS_Ave_32 0x55 // TAP1/TAP2 Average 32 #define VALUE_MISC2_OSCA_EN 0x08 #define VALUE_PD_RST 0x52 #define CONFIG_GSEN_CALIBRATION_GRAVITY_ON_Z_NEGATIVE 1 #define CONFIG_GSEN_CALIBRATION_GRAVITY_ON_Z_POSITIVE 2 #define CONFIG_GSEN_CALIBRATION_GRAVITY_ON_Y_NEGATIVE 3 #define CONFIG_GSEN_CALIBRATION_GRAVITY_ON_Y_POSITIVE 4 #define CONFIG_GSEN_CALIBRATION_GRAVITY_ON_X_NEGATIVE 5 #define CONFIG_GSEN_CALIBRATION_GRAVITY_ON_X_POSITIVE 6 #define AVG_NUM 16 #define SENSOR_DATA_SIZE 3 #define DEFAULT_SENSITIVITY 1024 #define IOCTL_MAGIC 0x09 #define SENSOR_RESET _IO(IOCTL_MAGIC, 0) #define SENSOR_CALIBRATION _IOWR(IOCTL_MAGIC, 1, int[SENSOR_DATA_SIZE]) #define SENSOR_GET_OFFSET _IOR(IOCTL_MAGIC, 2, int[SENSOR_DATA_SIZE]) #define SENSOR_SET_OFFSET _IOWR(IOCTL_MAGIC, 3, int[SENSOR_DATA_SIZE]) #define SENSOR_READ_ACCEL_XYZ _IOR(IOCTL_MAGIC, 4, int[SENSOR_DATA_SIZE]) #define SENSOR_SETYPR _IOW(IOCTL_MAGIC, 5, int[SENSOR_DATA_SIZE]) #define SENSOR_GET_OPEN_STATUS _IO(IOCTL_MAGIC, 6) #define SENSOR_GET_CLOSE_STATUS _IO(IOCTL_MAGIC, 7) #define SENSOR_GET_DELAY _IOR(IOCTL_MAGIC, 8, unsigned int*) #define SENSOR_MAXNR 8 /* g-senor layout configuration, choose one of the following configuration */ #define CONFIG_GSEN_LAYOUT_PAT_1 1 #define CONFIG_GSEN_LAYOUT_PAT_2 0 #define CONFIG_GSEN_LAYOUT_PAT_3 0 #define CONFIG_GSEN_LAYOUT_PAT_4 0 #define CONFIG_GSEN_LAYOUT_PAT_5 0 #define CONFIG_GSEN_LAYOUT_PAT_6 0 #define CONFIG_GSEN_LAYOUT_PAT_7 0 #define CONFIG_GSEN_LAYOUT_PAT_8 0 s16 sensorlayout[3][3] = { #if CONFIG_GSEN_LAYOUT_PAT_1 { 1, 0, 0}, { 0, 1, 0}, { 0, 0, 1}, #elif CONFIG_GSEN_LAYOUT_PAT_2 { 0, 1, 0}, {-1, 0, 0}, { 0, 0, 1}, #elif CONFIG_GSEN_LAYOUT_PAT_3 {-1, 0, 0}, { 0,-1, 0}, { 0, 0, 1}, #elif CONFIG_GSEN_LAYOUT_PAT_4 { 0,-1, 0}, { 1, 0, 0}, { 0, 0, 1}, #elif CONFIG_GSEN_LAYOUT_PAT_5 {-1, 0, 0}, { 0, 1, 0}, { 0, 0,-1}, #elif CONFIG_GSEN_LAYOUT_PAT_6 { 0,-1, 0}, {-1, 0, 0}, { 0, 0,-1}, #elif CONFIG_GSEN_LAYOUT_PAT_7 { 1, 0, 0}, { 0,-1, 0}, { 0, 0,-1}, #elif CONFIG_GSEN_LAYOUT_PAT_8 { 0, 1, 0}, { 1, 0, 0}, { 0, 0,-1}, #endif }; typedef union { struct { s16 x; s16 y; s16 z; } u; s16 v[SENSOR_DATA_SIZE]; } raw_data; struct dmt_data { dev_t devno; struct cdev cdev; struct device *class_dev; struct class *class; struct input_dev *input; struct i2c_client *client; struct delayed_work delaywork; struct work_struct work; struct mutex sensor_mutex; wait_queue_head_t open_wq; atomic_t active; atomic_t delay; atomic_t enable; }; #define ACC_DATA_FLAG 0 #define MAG_DATA_FLAG 1 #define ORI_DATA_FLAG 2 #define DMT_NUM_SENSORS 3 #endif
FOSSEE/FOSSEE-netbook-kernel-source
drivers/input/sensor/TP_DRIVER_NOT_USE/dmt10_gsensor/dmt10.h
C
gpl-2.0
6,525
<?php define('CUSTOM_POST_TYPE2','slider'); define('CUSTOM_CATEGORY_TYPE2','scategory'); define('CUSTOM_TAG_TYPE2','stags'); define('CUSTOM_MENU_TITLE2',__('Slider','templatic')); define('CUSTOM_MENU_NAME2',__('Slider','templatic')); define('CUSTOM_MENU_SIGULAR_NAME2',__('Slider','templatic')); define('CUSTOM_MENU_ADD_NEW2',__('Add Post','templatic')); define('CUSTOM_MENU_ADD_NEW_ITEM2',__('Add New Post','templatic')); define('CUSTOM_MENU_EDIT2',__('Edit','templatic')); define('CUSTOM_MENU_EDIT_ITEM2',__('Edit Post','templatic')); define('CUSTOM_MENU_NEW2',__('New Post','templatic')); define('CUSTOM_MENU_VIEW2',__('View Post','templatic')); define('CUSTOM_MENU_SEARCH2',__('Search Post','templatic')); define('CUSTOM_MENU_NOT_FOUND2',__('No Post found','templatic')); define('CUSTOM_MENU_NOT_FOUND_TRASH2',__('No Post found in trash','templatic')); define('CUSTOM_MENU_CAT_LABEL2',__('Slider Categories','templatic')); define('CUSTOM_MENU_CAT_TITLE2',__('Slider Categories','templatic')); define('CUSTOM_MENU_SIGULAR_CAT2',__('Category','templatic')); define('CUSTOM_MENU_CAT_SEARCH2',__('Search Category','templatic')); define('CUSTOM_MENU_CAT_POPULAR2',__('Popular Categories','templatic')); define('CUSTOM_MENU_CAT_ALL2',__('All Categories','templatic')); define('CUSTOM_MENU_CAT_PARENT2',__('Parent Category','templatic')); define('CUSTOM_MENU_CAT_PARENT_COL2',__('Parent Category:','templatic')); define('CUSTOM_MENU_CAT_EDIT2',__('Edit Category','templatic')); define('CUSTOM_MENU_CAT_UPDATE2',__('Update Category','templatic')); define('CUSTOM_MENU_CAT_ADDNEW2',__('Add New Category','templatic')); define('CUSTOM_MENU_CAT_NEW_NAME2',__('New Category Name','templatic')); define('CUSTOM_MENU_TAG_LABEL2',__('Slider Tags','templatic')); define('CUSTOM_MENU_TAG_TITLE2',__('Slider Tags','templatic')); define('CUSTOM_MENU_TAG_NAME2',__('Slider Tags','templatic')); define('CUSTOM_MENU_TAG_SEARCH2',__('Slider Tags','templatic')); define('CUSTOM_MENU_TAG_POPULAR2',__('Popular Slider Tags','templatic')); define('CUSTOM_MENU_TAG_ALL2',__('All Slider Tags','templatic')); define('CUSTOM_MENU_TAG_PARENT2',__('Parent Slider Tags','templatic')); define('CUSTOM_MENU_TAG_PARENT_COL2',__('Parent Slider Tags:','templatic')); define('CUSTOM_MENU_TAG_EDIT2',__('Edit Slider Tags','templatic')); define('CUSTOM_MENU_TAG_UPDATE2',__('Update Slider Tags','templatic')); define('CUSTOM_MENU_TAG_ADD_NEW2',__('Add New Slider Tags','templatic')); define('CUSTOM_MENU_TAG_NEW_ADD2',__('New Slider Tags Name','templatic')); ?>
annguyenit/getdeal
wp-content/themes/DailyDeal_bak/admin/widgets/anything_slider/custom_post_type_slider/custom_post_type_slider_lang.php
PHP
gpl-2.0
2,526
<?php /** * Result Count * * Shows text: Showing x - x of x results * * @author WooThemes * @package WooCommerce/Templates * @version 2.0.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $woocommerce, $wp_query; if ( ! woocommerce_products_will_display() ) return; ?> <p class="woocommerce-result-count"> <?php $paged = max( 1, $wp_query->get( 'paged' ) ); $per_page = $wp_query->get( 'posts_per_page' ); $total = $wp_query->found_posts; $first = ( $per_page * $paged ) - $per_page + 1; $last = min( $total, $wp_query->get( 'posts_per_page' ) * $paged ); if ( 1 == $total ) { _e( 'Showing the single result', 'woocommerce' ); } elseif ( $total <= $per_page || -1 == $per_page ) { printf( __( 'Showing all %d results', 'woocommerce' ), $total ); } else { printf( _x( 'Showing %1$d&ndash;%2$d of %3$d results', '%1$d = first, %2$d = last, %3$d = total', 'woocommerce' ), $first, $last, $total ); } ?> </p>
epiii/aros
wp-content/themes/flatmarket/woocommerce/loop/result-count.php
PHP
gpl-2.0
981